[coop] Attach mono-thread as early as possible.
[mono.git] / mono / metadata / domain.c
1 /*
2  * domain.c: MonoDomain functions
3  *
4  * Author:
5  *      Dietmar Maurer (dietmar@ximian.com)
6  *      Patrik Torstensson
7  *
8  * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
9  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
10  * Copyright 2011-2012 Xamarin, Inc (http://www.xamarin.com)
11  */
12
13 #include <config.h>
14 #include <glib.h>
15 #include <string.h>
16 #include <sys/stat.h>
17
18 #include <mono/metadata/gc-internal.h>
19
20 #include <mono/utils/atomic.h>
21 #include <mono/utils/mono-compiler.h>
22 #include <mono/utils/mono-logger-internal.h>
23 #include <mono/utils/mono-membar.h>
24 #include <mono/utils/mono-counters.h>
25 #include <mono/utils/hazard-pointer.h>
26 #include <mono/utils/mono-tls.h>
27 #include <mono/utils/mono-mmap.h>
28 #include <mono/utils/mono-threads.h>
29 #include <mono/metadata/object.h>
30 #include <mono/metadata/object-internals.h>
31 #include <mono/metadata/domain-internals.h>
32 #include <mono/metadata/class-internals.h>
33 #include <mono/metadata/assembly.h>
34 #include <mono/metadata/exception.h>
35 #include <mono/metadata/metadata-internals.h>
36 #include <mono/metadata/gc-internal.h>
37 #include <mono/metadata/appdomain.h>
38 #include <mono/metadata/mono-debug-debugger.h>
39 #include <mono/metadata/mono-config.h>
40 #include <mono/metadata/threads-types.h>
41 #include <mono/metadata/runtime.h>
42 #include <metadata/threads.h>
43 #include <metadata/profiler-private.h>
44 #include <mono/metadata/coree.h>
45
46 //#define DEBUG_DOMAIN_UNLOAD 1
47
48 /* we need to use both the Tls* functions and __thread because
49  * some archs may generate faster jit code with one meachanism
50  * or the other (we used to do it because tls slots were GC-tracked,
51  * but we can't depend on this).
52  */
53 static MonoNativeTlsKey appdomain_thread_id;
54
55 #ifdef MONO_HAVE_FAST_TLS
56
57 MONO_FAST_TLS_DECLARE(tls_appdomain);
58
59 #define GET_APPDOMAIN() ((MonoDomain*)MONO_FAST_TLS_GET(tls_appdomain))
60
61 #define SET_APPDOMAIN(x) do { \
62         MonoThreadInfo *info; \
63         MONO_FAST_TLS_SET (tls_appdomain,x); \
64         mono_native_tls_set_value (appdomain_thread_id, x); \
65         mono_gc_set_current_thread_appdomain (x); \
66         info = mono_thread_info_current (); \
67         if (info) \
68                 mono_thread_info_tls_set (info, TLS_KEY_DOMAIN, (x));   \
69 } while (FALSE)
70
71 #else /* !MONO_HAVE_FAST_TLS */
72
73 #define GET_APPDOMAIN() ((MonoDomain *)mono_native_tls_get_value (appdomain_thread_id))
74 #define SET_APPDOMAIN(x) do {                                           \
75                 MonoThreadInfo *info;                                                           \
76                 mono_native_tls_set_value (appdomain_thread_id, x);     \
77                 mono_gc_set_current_thread_appdomain (x);               \
78                 info = mono_thread_info_current ();                             \
79                 if (info)                                                                                                \
80                         mono_thread_info_tls_set (info, TLS_KEY_DOMAIN, (x));   \
81         } while (FALSE)
82
83 #endif
84
85 #define GET_APPCONTEXT() (mono_thread_internal_current ()->current_appcontext)
86 #define SET_APPCONTEXT(x) MONO_OBJECT_SETREF (mono_thread_internal_current (), current_appcontext, (x))
87
88 static guint16 appdomain_list_size = 0;
89 static guint16 appdomain_next = 0;
90 static MonoDomain **appdomains_list = NULL;
91 static MonoImage *exe_image;
92 static gboolean debug_domain_unload;
93
94 gboolean mono_dont_free_domains;
95
96 #define mono_appdomains_lock() mono_mutex_lock (&appdomains_mutex)
97 #define mono_appdomains_unlock() mono_mutex_unlock (&appdomains_mutex)
98 static mono_mutex_t appdomains_mutex;
99
100 static MonoDomain *mono_root_domain = NULL;
101
102 /* some statistics */
103 static int max_domain_code_size = 0;
104 static int max_domain_code_alloc = 0;
105 static int total_domain_code_alloc = 0;
106
107 /* AppConfigInfo: Information about runtime versions supported by an 
108  * aplication.
109  */
110 typedef struct {
111         GSList *supported_runtimes;
112         char *required_runtime;
113         int configuration_count;
114         int startup_count;
115 } AppConfigInfo;
116
117 static const MonoRuntimeInfo *current_runtime = NULL;
118
119 /* This is the list of runtime versions supported by this JIT.
120  */
121 static const MonoRuntimeInfo supported_runtimes[] = {
122         {"v4.0.30319","4.5", { {4,0,0,0}, {10,0,0,0}, {4,0,0,0}, {4,0,0,0} } },
123         {"v4.0.30128","4.0", { {4,0,0,0}, {10,0,0,0}, {4,0,0,0}, {4,0,0,0} } },
124         {"v4.0.20506","4.0", { {4,0,0,0}, {10,0,0,0}, {4,0,0,0}, {4,0,0,0} } },
125         {"mobile",    "2.1", { {2,0,5,0}, {10,0,0,0}, {2,0,5,0}, {2,0,5,0} } },
126         {"moonlight", "2.1", { {2,0,5,0}, { 9,0,0,0}, {3,5,0,0}, {3,0,0,0} } },
127 };
128
129
130 /* The stable runtime version */
131 #define DEFAULT_RUNTIME_VERSION "v4.0.30319"
132
133 /* Callbacks installed by the JIT */
134 static MonoCreateDomainFunc create_domain_hook;
135 static MonoFreeDomainFunc free_domain_hook;
136
137 /* AOT cache configuration */
138 static MonoAotCacheConfig aot_cache_config;
139
140 static void
141 get_runtimes_from_exe (const char *exe_file, MonoImage **exe_image, const MonoRuntimeInfo** runtimes);
142
143 static const MonoRuntimeInfo*
144 get_runtime_by_version (const char *version);
145
146 MonoNativeTlsKey
147 mono_domain_get_tls_key (void)
148 {
149         return appdomain_thread_id;
150 }
151
152 gint32
153 mono_domain_get_tls_offset (void)
154 {
155         int offset = -1;
156
157 #ifdef HOST_WIN32
158         if (appdomain_thread_id)
159                 offset = appdomain_thread_id;
160 #else
161         MONO_THREAD_VAR_OFFSET (tls_appdomain, offset);
162 #endif
163         return offset;
164 }
165
166 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
167 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
168
169 static LockFreeMempool*
170 lock_free_mempool_new (void)
171 {
172         return g_new0 (LockFreeMempool, 1);
173 }
174
175 static void
176 lock_free_mempool_free (LockFreeMempool *mp)
177 {
178         LockFreeMempoolChunk *chunk, *next;
179
180         chunk = mp->chunks;
181         while (chunk) {
182                 next = chunk->prev;
183                 mono_vfree (chunk, mono_pagesize ());
184                 chunk = next;
185         }
186         g_free (mp);
187 }
188
189 /*
190  * This is async safe
191  */
192 static LockFreeMempoolChunk*
193 lock_free_mempool_chunk_new (LockFreeMempool *mp, int len)
194 {
195         LockFreeMempoolChunk *chunk, *prev;
196         int size;
197
198         size = mono_pagesize ();
199         while (size - sizeof (LockFreeMempoolChunk) < len)
200                 size += mono_pagesize ();
201         chunk = mono_valloc (0, size, MONO_MMAP_READ|MONO_MMAP_WRITE);
202         g_assert (chunk);
203         chunk->mem = ALIGN_PTR_TO ((char*)chunk + sizeof (LockFreeMempoolChunk), 16);
204         chunk->size = ((char*)chunk + size) - (char*)chunk->mem;
205         chunk->pos = 0;
206
207         /* Add to list of chunks lock-free */
208         while (TRUE) {
209                 prev = mp->chunks;
210                 if (InterlockedCompareExchangePointer ((volatile gpointer*)&mp->chunks, chunk, prev) == prev)
211                         break;
212         }
213         chunk->prev = prev;
214
215         return chunk;
216 }
217
218 /*
219  * This is async safe
220  */
221 static gpointer
222 lock_free_mempool_alloc0 (LockFreeMempool *mp, guint size)
223 {
224         LockFreeMempoolChunk *chunk;
225         gpointer res;
226         int oldpos;
227
228         // FIXME: Free the allocator
229
230         size = ALIGN_TO (size, 8);
231         chunk = mp->current;
232         if (!chunk) {
233                 chunk = lock_free_mempool_chunk_new (mp, size);
234                 mono_memory_barrier ();
235                 /* Publish */
236                 mp->current = chunk;
237         }
238
239         /* The code below is lock-free, 'chunk' is shared state */
240         oldpos = InterlockedExchangeAdd (&chunk->pos, size);
241         if (oldpos + size > chunk->size) {
242                 chunk = lock_free_mempool_chunk_new (mp, size);
243                 g_assert (chunk->pos + size <= chunk->size);
244                 res = chunk->mem;
245                 chunk->pos += size;
246                 mono_memory_barrier ();
247                 mp->current = chunk;
248         } else {
249                 res = (char*)chunk->mem + oldpos;
250         }
251
252         return res;
253 }
254
255 void
256 mono_install_create_domain_hook (MonoCreateDomainFunc func)
257 {
258         create_domain_hook = func;
259 }
260
261 void
262 mono_install_free_domain_hook (MonoFreeDomainFunc func)
263 {
264         free_domain_hook = func;
265 }
266
267 /**
268  * mono_string_equal:
269  * @s1: First string to compare
270  * @s2: Second string to compare
271  *
272  * Returns FALSE if the strings differ.
273  */
274 gboolean
275 mono_string_equal (MonoString *s1, MonoString *s2)
276 {
277         int l1 = mono_string_length (s1);
278         int l2 = mono_string_length (s2);
279
280         if (s1 == s2)
281                 return TRUE;
282         if (l1 != l2)
283                 return FALSE;
284
285         return memcmp (mono_string_chars (s1), mono_string_chars (s2), l1 * 2) == 0; 
286 }
287
288 /**
289  * mono_string_hash:
290  * @s: the string to hash
291  *
292  * Returns the hash for the string.
293  */
294 guint
295 mono_string_hash (MonoString *s)
296 {
297         const guint16 *p = mono_string_chars (s);
298         int i, len = mono_string_length (s);
299         guint h = 0;
300
301         for (i = 0; i < len; i++) {
302                 h = (h << 5) - h + *p;
303                 p++;
304         }
305
306         return h;       
307 }
308
309 static gboolean
310 mono_ptrarray_equal (gpointer *s1, gpointer *s2)
311 {
312         int len = GPOINTER_TO_INT (s1 [0]);
313         if (len != GPOINTER_TO_INT (s2 [0]))
314                 return FALSE;
315
316         return memcmp (s1 + 1, s2 + 1, len * sizeof(gpointer)) == 0; 
317 }
318
319 static guint
320 mono_ptrarray_hash (gpointer *s)
321 {
322         int i;
323         int len = GPOINTER_TO_INT (s [0]);
324         guint hash = 0;
325         
326         for (i = 1; i < len; i++)
327                 hash += GPOINTER_TO_UINT (s [i]);
328
329         return hash;    
330 }
331
332 /*
333  * Allocate an id for domain and set domain->domain_id.
334  * LOCKING: must be called while holding appdomains_mutex.
335  * We try to assign low numbers to the domain, so it can be used
336  * as an index in data tables to lookup domain-specific info
337  * with minimal memory overhead. We also try not to reuse the
338  * same id too quickly (to help debugging).
339  */
340 static int
341 domain_id_alloc (MonoDomain *domain)
342 {
343         int id = -1, i;
344         if (!appdomains_list) {
345                 appdomain_list_size = 2;
346                 appdomains_list = mono_gc_alloc_fixed (appdomain_list_size * sizeof (void*), MONO_GC_DESCRIPTOR_NULL);
347         }
348         for (i = appdomain_next; i < appdomain_list_size; ++i) {
349                 if (!appdomains_list [i]) {
350                         id = i;
351                         break;
352                 }
353         }
354         if (id == -1) {
355                 for (i = 0; i < appdomain_next; ++i) {
356                         if (!appdomains_list [i]) {
357                                 id = i;
358                                 break;
359                         }
360                 }
361         }
362         if (id == -1) {
363                 MonoDomain **new_list;
364                 int new_size = appdomain_list_size * 2;
365                 if (new_size >= (1 << 16))
366                         g_assert_not_reached ();
367                 id = appdomain_list_size;
368                 new_list = mono_gc_alloc_fixed (new_size * sizeof (void*), MONO_GC_DESCRIPTOR_NULL);
369                 memcpy (new_list, appdomains_list, appdomain_list_size * sizeof (void*));
370                 mono_gc_free_fixed (appdomains_list);
371                 appdomains_list = new_list;
372                 appdomain_list_size = new_size;
373         }
374         domain->domain_id = id;
375         appdomains_list [id] = domain;
376         appdomain_next++;
377         if (appdomain_next > appdomain_list_size)
378                 appdomain_next = 0;
379         return id;
380 }
381
382 static gsize domain_gc_bitmap [sizeof(MonoDomain)/4/32 + 1];
383 static MonoGCDescriptor domain_gc_desc = MONO_GC_DESCRIPTOR_NULL;
384 static guint32 domain_shadow_serial = 0L;
385
386 MonoDomain *
387 mono_domain_create (void)
388 {
389         MonoDomain *domain;
390         guint32 shadow_serial;
391   
392         mono_appdomains_lock ();
393         shadow_serial = domain_shadow_serial++;
394   
395         if (!domain_gc_desc) {
396                 unsigned int i, bit = 0;
397                 for (i = G_STRUCT_OFFSET (MonoDomain, MONO_DOMAIN_FIRST_OBJECT); i < G_STRUCT_OFFSET (MonoDomain, MONO_DOMAIN_FIRST_GC_TRACKED); i += sizeof (gpointer)) {
398                         bit = i / sizeof (gpointer);
399                         domain_gc_bitmap [bit / 32] |= (gsize) 1 << (bit % 32);
400                 }
401                 domain_gc_desc = mono_gc_make_descr_from_bitmap ((gsize*)domain_gc_bitmap, bit + 1);
402         }
403         mono_appdomains_unlock ();
404
405 #ifdef HAVE_BOEHM_GC
406         /*
407          * Boehm doesn't like roots inside GC allocated objects, and alloc_fixed returns
408          * a GC_MALLOC-ed object, contrary to the api docs. This causes random crashes when
409          * running the corlib test suite.
410          * To solve this, we pass a NULL descriptor, and don't register roots.
411          */
412         domain = mono_gc_alloc_fixed (sizeof (MonoDomain), NULL);
413 #else
414         domain = mono_gc_alloc_fixed (sizeof (MonoDomain), domain_gc_desc);
415         mono_gc_register_root ((char*)&(domain->MONO_DOMAIN_FIRST_GC_TRACKED), G_STRUCT_OFFSET (MonoDomain, MONO_DOMAIN_LAST_GC_TRACKED) - G_STRUCT_OFFSET (MonoDomain, MONO_DOMAIN_FIRST_GC_TRACKED), MONO_GC_DESCRIPTOR_NULL);
416 #endif
417         domain->shadow_serial = shadow_serial;
418         domain->domain = NULL;
419         domain->setup = NULL;
420         domain->friendly_name = NULL;
421         domain->search_path = NULL;
422
423         mono_profiler_appdomain_event (domain, MONO_PROFILE_START_LOAD);
424
425         domain->mp = mono_mempool_new ();
426         domain->code_mp = mono_code_manager_new ();
427         domain->lock_free_mp = lock_free_mempool_new ();
428         domain->env = mono_g_hash_table_new_type ((GHashFunc)mono_string_hash, (GCompareFunc)mono_string_equal, MONO_HASH_KEY_VALUE_GC);
429         domain->domain_assemblies = NULL;
430         domain->assembly_bindings = NULL;
431         domain->assembly_bindings_parsed = FALSE;
432         domain->class_vtable_array = g_ptr_array_new ();
433         domain->proxy_vtable_hash = g_hash_table_new ((GHashFunc)mono_ptrarray_hash, (GCompareFunc)mono_ptrarray_equal);
434         domain->static_data_array = NULL;
435         mono_jit_code_hash_init (&domain->jit_code_hash);
436         domain->ldstr_table = mono_g_hash_table_new_type ((GHashFunc)mono_string_hash, (GCompareFunc)mono_string_equal, MONO_HASH_KEY_VALUE_GC);
437         domain->num_jit_info_tables = 1;
438         domain->jit_info_table = mono_jit_info_table_new (domain);
439         domain->jit_info_free_queue = NULL;
440         domain->finalizable_objects_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
441         domain->ftnptrs_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
442
443         mono_mutex_init_recursive (&domain->lock);
444         mono_mutex_init_recursive (&domain->assemblies_lock);
445         mono_mutex_init_recursive (&domain->jit_code_hash_lock);
446         mono_mutex_init_recursive (&domain->finalizable_objects_hash_lock);
447
448         domain->method_rgctx_hash = NULL;
449
450         mono_appdomains_lock ();
451         domain_id_alloc (domain);
452         mono_appdomains_unlock ();
453
454 #ifndef DISABLE_PERFCOUNTERS
455         mono_perfcounters->loader_appdomains++;
456         mono_perfcounters->loader_total_appdomains++;
457 #endif
458
459         mono_debug_domain_create (domain);
460
461         if (create_domain_hook)
462                 create_domain_hook (domain);
463
464         mono_profiler_appdomain_loaded (domain, MONO_PROFILE_OK);
465         
466         return domain;
467 }
468
469 /**
470  * mono_init_internal:
471  * 
472  * Creates the initial application domain and initializes the mono_defaults
473  * structure.
474  * This function is guaranteed to not run any IL code.
475  * If exe_filename is not NULL, the method will determine the required runtime
476  * from the exe configuration file or the version PE field.
477  * If runtime_version is not NULL, that runtime version will be used.
478  * Either exe_filename or runtime_version must be provided.
479  *
480  * Returns: the initial domain.
481  */
482 static MonoDomain *
483 mono_init_internal (const char *filename, const char *exe_filename, const char *runtime_version)
484 {
485         static MonoDomain *domain = NULL;
486         MonoAssembly *ass = NULL;
487         MonoImageOpenStatus status = MONO_IMAGE_OK;
488         const MonoRuntimeInfo* runtimes [G_N_ELEMENTS (supported_runtimes) + 1];
489         int n, dummy;
490
491 #ifdef DEBUG_DOMAIN_UNLOAD
492         debug_domain_unload = TRUE;
493 #endif
494
495         if (domain)
496                 g_assert_not_reached ();
497
498 #ifdef HOST_WIN32
499         /* Avoid system error message boxes. */
500         SetErrorMode (SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
501 #endif
502
503 #ifndef HOST_WIN32
504         wapi_init ();
505 #endif
506
507 #ifndef DISABLE_PERFCOUNTERS
508         mono_perfcounters_init ();
509 #endif
510         mono_counters_init ();
511
512         mono_counters_register ("Max native code in a domain", MONO_COUNTER_INT|MONO_COUNTER_JIT, &max_domain_code_size);
513         mono_counters_register ("Max code space allocated in a domain", MONO_COUNTER_INT|MONO_COUNTER_JIT, &max_domain_code_alloc);
514         mono_counters_register ("Total code space allocated", MONO_COUNTER_INT|MONO_COUNTER_JIT, &total_domain_code_alloc);
515
516         mono_gc_base_init ();
517         mono_thread_info_attach (&dummy);
518
519         MONO_FAST_TLS_INIT (tls_appdomain);
520         mono_native_tls_alloc (&appdomain_thread_id, NULL);
521
522         mono_mutex_init_recursive (&appdomains_mutex);
523
524         mono_metadata_init ();
525         mono_images_init ();
526         mono_assemblies_init ();
527         mono_classes_init ();
528         mono_loader_init ();
529         mono_reflection_init ();
530         mono_runtime_init_tls ();
531
532         /* FIXME: When should we release this memory? */
533         MONO_GC_REGISTER_ROOT_FIXED (appdomains_list);
534
535         domain = mono_domain_create ();
536         mono_root_domain = domain;
537
538         SET_APPDOMAIN (domain);
539         
540         /* Get a list of runtimes supported by the exe */
541         if (exe_filename != NULL) {
542                 /*
543                  * This function will load the exe file as a MonoImage. We need to close it, but
544                  * that would mean it would be reloaded later. So instead, we save it to
545                  * exe_image, and close it during shutdown.
546                  */
547                 get_runtimes_from_exe (exe_filename, &exe_image, runtimes);
548 #ifdef HOST_WIN32
549                 if (!exe_image) {
550                         exe_image = mono_assembly_open_from_bundle (exe_filename, NULL, FALSE);
551                         if (!exe_image)
552                                 exe_image = mono_image_open (exe_filename, NULL);
553                 }
554                 mono_fixup_exe_image (exe_image);
555 #endif
556         } else if (runtime_version != NULL) {
557                 runtimes [0] = get_runtime_by_version (runtime_version);
558                 runtimes [1] = NULL;
559         }
560
561         if (runtimes [0] == NULL) {
562                 const MonoRuntimeInfo *default_runtime = get_runtime_by_version (DEFAULT_RUNTIME_VERSION);
563                 runtimes [0] = default_runtime;
564                 runtimes [1] = NULL;
565                 g_print ("WARNING: The runtime version supported by this application is unavailable.\n");
566                 g_print ("Using default runtime: %s\n", default_runtime->runtime_version); 
567         }
568
569         /* The selected runtime will be the first one for which there is a mscrolib.dll */
570         for (n = 0; runtimes [n] != NULL && ass == NULL; n++) {
571                 current_runtime = runtimes [n];
572                 ass = mono_assembly_load_corlib (current_runtime, &status);
573                 if (status != MONO_IMAGE_OK && status != MONO_IMAGE_ERROR_ERRNO)
574                         break;
575
576         }
577         
578         if ((status != MONO_IMAGE_OK) || (ass == NULL)) {
579                 switch (status){
580                 case MONO_IMAGE_ERROR_ERRNO: {
581                         char *corlib_file = g_build_filename (mono_assembly_getrootdir (), "mono", current_runtime->framework_version, "mscorlib.dll", NULL);
582                         g_print ("The assembly mscorlib.dll was not found or could not be loaded.\n");
583                         g_print ("It should have been installed in the `%s' directory.\n", corlib_file);
584                         g_free (corlib_file);
585                         break;
586                 }
587                 case MONO_IMAGE_IMAGE_INVALID:
588                         g_print ("The file %s/mscorlib.dll is an invalid CIL image\n",
589                                  mono_assembly_getrootdir ());
590                         break;
591                 case MONO_IMAGE_MISSING_ASSEMBLYREF:
592                         g_print ("Missing assembly reference in %s/mscorlib.dll\n",
593                                  mono_assembly_getrootdir ());
594                         break;
595                 case MONO_IMAGE_OK:
596                         /* to suppress compiler warning */
597                         break;
598                 }
599                 
600                 exit (1);
601         }
602         mono_defaults.corlib = mono_assembly_get_image (ass);
603
604         mono_defaults.object_class = mono_class_from_name (
605                 mono_defaults.corlib, "System", "Object");
606         g_assert (mono_defaults.object_class != 0);
607
608         mono_defaults.void_class = mono_class_from_name (
609                 mono_defaults.corlib, "System", "Void");
610         g_assert (mono_defaults.void_class != 0);
611
612         mono_defaults.boolean_class = mono_class_from_name (
613                 mono_defaults.corlib, "System", "Boolean");
614         g_assert (mono_defaults.boolean_class != 0);
615
616         mono_defaults.byte_class = mono_class_from_name (
617                 mono_defaults.corlib, "System", "Byte");
618         g_assert (mono_defaults.byte_class != 0);
619
620         mono_defaults.sbyte_class = mono_class_from_name (
621                 mono_defaults.corlib, "System", "SByte");
622         g_assert (mono_defaults.sbyte_class != 0);
623
624         mono_defaults.int16_class = mono_class_from_name (
625                 mono_defaults.corlib, "System", "Int16");
626         g_assert (mono_defaults.int16_class != 0);
627
628         mono_defaults.uint16_class = mono_class_from_name (
629                 mono_defaults.corlib, "System", "UInt16");
630         g_assert (mono_defaults.uint16_class != 0);
631
632         mono_defaults.int32_class = mono_class_from_name (
633                 mono_defaults.corlib, "System", "Int32");
634         g_assert (mono_defaults.int32_class != 0);
635
636         mono_defaults.uint32_class = mono_class_from_name (
637                 mono_defaults.corlib, "System", "UInt32");
638         g_assert (mono_defaults.uint32_class != 0);
639
640         mono_defaults.uint_class = mono_class_from_name (
641                 mono_defaults.corlib, "System", "UIntPtr");
642         g_assert (mono_defaults.uint_class != 0);
643
644         mono_defaults.int_class = mono_class_from_name (
645                 mono_defaults.corlib, "System", "IntPtr");
646         g_assert (mono_defaults.int_class != 0);
647
648         mono_defaults.int64_class = mono_class_from_name (
649                 mono_defaults.corlib, "System", "Int64");
650         g_assert (mono_defaults.int64_class != 0);
651
652         mono_defaults.uint64_class = mono_class_from_name (
653                 mono_defaults.corlib, "System", "UInt64");
654         g_assert (mono_defaults.uint64_class != 0);
655
656         mono_defaults.single_class = mono_class_from_name (
657                 mono_defaults.corlib, "System", "Single");
658         g_assert (mono_defaults.single_class != 0);
659
660         mono_defaults.double_class = mono_class_from_name (
661                 mono_defaults.corlib, "System", "Double");
662         g_assert (mono_defaults.double_class != 0);
663
664         mono_defaults.char_class = mono_class_from_name (
665                 mono_defaults.corlib, "System", "Char");
666         g_assert (mono_defaults.char_class != 0);
667
668         mono_defaults.string_class = mono_class_from_name (
669                 mono_defaults.corlib, "System", "String");
670         g_assert (mono_defaults.string_class != 0);
671
672         mono_defaults.enum_class = mono_class_from_name (
673                 mono_defaults.corlib, "System", "Enum");
674         g_assert (mono_defaults.enum_class != 0);
675
676         mono_defaults.array_class = mono_class_from_name (
677                 mono_defaults.corlib, "System", "Array");
678         g_assert (mono_defaults.array_class != 0);
679
680         mono_defaults.delegate_class = mono_class_from_name (
681                 mono_defaults.corlib, "System", "Delegate");
682         g_assert (mono_defaults.delegate_class != 0 );
683
684         mono_defaults.multicastdelegate_class = mono_class_from_name (
685                 mono_defaults.corlib, "System", "MulticastDelegate");
686         g_assert (mono_defaults.multicastdelegate_class != 0 );
687
688         mono_defaults.asyncresult_class = mono_class_from_name (
689                 mono_defaults.corlib, "System.Runtime.Remoting.Messaging", 
690                 "AsyncResult");
691         g_assert (mono_defaults.asyncresult_class != 0 );
692
693         mono_defaults.manualresetevent_class = mono_class_from_name (
694                 mono_defaults.corlib, "System.Threading", "ManualResetEvent");
695         g_assert (mono_defaults.manualresetevent_class != 0 );
696
697         mono_defaults.typehandle_class = mono_class_from_name (
698                 mono_defaults.corlib, "System", "RuntimeTypeHandle");
699         g_assert (mono_defaults.typehandle_class != 0);
700
701         mono_defaults.methodhandle_class = mono_class_from_name (
702                 mono_defaults.corlib, "System", "RuntimeMethodHandle");
703         g_assert (mono_defaults.methodhandle_class != 0);
704
705         mono_defaults.fieldhandle_class = mono_class_from_name (
706                 mono_defaults.corlib, "System", "RuntimeFieldHandle");
707         g_assert (mono_defaults.fieldhandle_class != 0);
708
709         mono_defaults.systemtype_class = mono_class_from_name (
710                 mono_defaults.corlib, "System", "Type");
711         g_assert (mono_defaults.systemtype_class != 0);
712
713         mono_defaults.monotype_class = mono_class_from_name (
714                 mono_defaults.corlib, "System", "MonoType");
715         g_assert (mono_defaults.monotype_class != 0);
716
717         mono_defaults.runtimetype_class = mono_class_from_name (
718                 mono_defaults.corlib, "System", "RuntimeType");
719         g_assert (mono_defaults.runtimetype_class != 0);
720
721         mono_defaults.exception_class = mono_class_from_name (
722                 mono_defaults.corlib, "System", "Exception");
723         g_assert (mono_defaults.exception_class != 0);
724
725         mono_defaults.threadabortexception_class = mono_class_from_name (
726                 mono_defaults.corlib, "System.Threading", "ThreadAbortException");
727         g_assert (mono_defaults.threadabortexception_class != 0);
728
729         mono_defaults.thread_class = mono_class_from_name (
730                 mono_defaults.corlib, "System.Threading", "Thread");
731         g_assert (mono_defaults.thread_class != 0);
732
733         mono_defaults.internal_thread_class = mono_class_from_name (
734                 mono_defaults.corlib, "System.Threading", "InternalThread");
735         if (!mono_defaults.internal_thread_class) {
736                 /* This can happen with an old mscorlib */
737                 fprintf (stderr, "Corlib too old for this runtime.\n");
738                 fprintf (stderr, "Loaded from: %s\n",
739                                  mono_defaults.corlib? mono_image_get_filename (mono_defaults.corlib): "unknown");
740                 exit (1);
741         }
742
743         mono_defaults.appdomain_class = mono_class_from_name (
744                 mono_defaults.corlib, "System", "AppDomain");
745         g_assert (mono_defaults.appdomain_class != 0);
746
747 #ifndef DISABLE_REMOTING
748         mono_defaults.transparent_proxy_class = mono_class_from_name (
749                 mono_defaults.corlib, "System.Runtime.Remoting.Proxies", "TransparentProxy");
750         g_assert (mono_defaults.transparent_proxy_class != 0);
751
752         mono_defaults.real_proxy_class = mono_class_from_name (
753                 mono_defaults.corlib, "System.Runtime.Remoting.Proxies", "RealProxy");
754         g_assert (mono_defaults.real_proxy_class != 0);
755
756         mono_defaults.marshalbyrefobject_class =  mono_class_from_name (
757                 mono_defaults.corlib, "System", "MarshalByRefObject");
758         g_assert (mono_defaults.marshalbyrefobject_class != 0);
759
760         mono_defaults.iremotingtypeinfo_class = mono_class_from_name (
761                 mono_defaults.corlib, "System.Runtime.Remoting", "IRemotingTypeInfo");
762         g_assert (mono_defaults.iremotingtypeinfo_class != 0);
763 #endif
764
765         mono_defaults.mono_method_message_class = mono_class_from_name (
766                 mono_defaults.corlib, "System.Runtime.Remoting.Messaging", "MonoMethodMessage");
767         g_assert (mono_defaults.mono_method_message_class != 0);
768
769         mono_defaults.field_info_class = mono_class_from_name (
770                 mono_defaults.corlib, "System.Reflection", "FieldInfo");
771         g_assert (mono_defaults.field_info_class != 0);
772
773         mono_defaults.method_info_class = mono_class_from_name (
774                 mono_defaults.corlib, "System.Reflection", "MethodInfo");
775         g_assert (mono_defaults.method_info_class != 0);
776
777         mono_defaults.stringbuilder_class = mono_class_from_name (
778                 mono_defaults.corlib, "System.Text", "StringBuilder");
779         g_assert (mono_defaults.stringbuilder_class != 0);
780
781         mono_defaults.math_class = mono_class_from_name (
782                 mono_defaults.corlib, "System", "Math");
783         g_assert (mono_defaults.math_class != 0);
784
785         mono_defaults.stack_frame_class = mono_class_from_name (
786                 mono_defaults.corlib, "System.Diagnostics", "StackFrame");
787         g_assert (mono_defaults.stack_frame_class != 0);
788
789         mono_defaults.stack_trace_class = mono_class_from_name (
790                 mono_defaults.corlib, "System.Diagnostics", "StackTrace");
791         g_assert (mono_defaults.stack_trace_class != 0);
792
793         mono_defaults.marshal_class = mono_class_from_name (
794                 mono_defaults.corlib, "System.Runtime.InteropServices", "Marshal");
795         g_assert (mono_defaults.marshal_class != 0);
796
797         mono_defaults.typed_reference_class =  mono_class_from_name (
798                 mono_defaults.corlib, "System", "TypedReference");
799         g_assert (mono_defaults.typed_reference_class != 0);
800
801         mono_defaults.argumenthandle_class =  mono_class_from_name (
802                 mono_defaults.corlib, "System", "RuntimeArgumentHandle");
803         g_assert (mono_defaults.argumenthandle_class != 0);
804
805         mono_defaults.monitor_class =  mono_class_from_name (
806                 mono_defaults.corlib, "System.Threading", "Monitor");
807         g_assert (mono_defaults.monitor_class != 0);
808
809         mono_defaults.runtimesecurityframe_class = mono_class_from_name (
810                 mono_defaults.corlib, "System.Security", "RuntimeSecurityFrame");
811
812         mono_defaults.executioncontext_class = mono_class_from_name (
813                 mono_defaults.corlib, "System.Threading", "ExecutionContext");
814
815         mono_defaults.internals_visible_class = mono_class_from_name (
816                 mono_defaults.corlib, "System.Runtime.CompilerServices", "InternalsVisibleToAttribute");
817
818         mono_defaults.critical_finalizer_object = mono_class_from_name (
819                 mono_defaults.corlib, "System.Runtime.ConstrainedExecution", "CriticalFinalizerObject");
820
821         /*
822          * mscorlib needs a little help, only now it can load its friends list (after we have
823          * loaded the InternalsVisibleToAttribute), load it now
824          */
825         mono_assembly_load_friends (ass);
826         
827         mono_defaults.safehandle_class = mono_class_from_name (
828                 mono_defaults.corlib, "System.Runtime.InteropServices", "SafeHandle");
829
830         mono_defaults.handleref_class = mono_class_from_name (
831                 mono_defaults.corlib, "System.Runtime.InteropServices", "HandleRef");
832
833         mono_defaults.attribute_class = mono_class_from_name (
834                 mono_defaults.corlib, "System", "Attribute");
835
836         mono_defaults.customattribute_data_class = mono_class_from_name (
837                 mono_defaults.corlib, "System.Reflection", "CustomAttributeData");
838
839         mono_class_init (mono_defaults.array_class);
840         mono_defaults.generic_nullable_class = mono_class_from_name (
841                 mono_defaults.corlib, "System", "Nullable`1");
842         mono_defaults.generic_ilist_class = mono_class_from_name (
843                 mono_defaults.corlib, "System.Collections.Generic", "IList`1");
844         mono_defaults.generic_ireadonlylist_class = mono_class_from_name (
845                 mono_defaults.corlib, "System.Collections.Generic", "IReadOnlyList`1");
846
847         mono_defaults.threadpool_wait_callback_class = mono_class_from_name (
848                 mono_defaults.corlib, "System.Threading", "_ThreadPoolWaitCallback");
849         if (!mono_defaults.threadpool_wait_callback_class) {
850                 /* This can happen with an old mscorlib */
851                 fprintf (stderr, "Corlib too old for this runtime.\n");
852                 fprintf (stderr, "Loaded from: %s\n",
853                                  mono_defaults.corlib? mono_image_get_filename (mono_defaults.corlib): "unknown");
854                 exit (1);
855         }
856         mono_defaults.threadpool_perform_wait_callback_method = mono_class_get_method_from_name (
857                 mono_defaults.threadpool_wait_callback_class, "PerformWaitCallback", 0);
858
859         domain->friendly_name = g_path_get_basename (filename);
860
861         mono_profiler_appdomain_name (domain, domain->friendly_name);
862
863         return domain;
864 }
865
866 /**
867  * mono_init:
868  * 
869  * Creates the initial application domain and initializes the mono_defaults
870  * structure.
871  * This function is guaranteed to not run any IL code.
872  * The runtime is initialized using the default runtime version.
873  *
874  * Returns: the initial domain.
875  */
876 MonoDomain *
877 mono_init (const char *domain_name)
878 {
879         return mono_init_internal (domain_name, NULL, DEFAULT_RUNTIME_VERSION);
880 }
881
882 /**
883  * mono_init_from_assembly:
884  * @domain_name: name to give to the initial domain
885  * @filename: filename to load on startup
886  *
887  * Used by the runtime, users should use mono_jit_init instead.
888  *
889  * Creates the initial application domain and initializes the mono_defaults
890  * structure.
891  * This function is guaranteed to not run any IL code.
892  * The runtime is initialized using the runtime version required by the
893  * provided executable. The version is determined by looking at the exe 
894  * configuration file and the version PE field)
895  *
896  * Returns: the initial domain.
897  */
898 MonoDomain *
899 mono_init_from_assembly (const char *domain_name, const char *filename)
900 {
901         return mono_init_internal (domain_name, filename, NULL);
902 }
903
904 /**
905  * mono_init_version:
906  * 
907  * Used by the runtime, users should use mono_jit_init instead.
908  * 
909  * Creates the initial application domain and initializes the mono_defaults
910  * structure.
911  *
912  * This function is guaranteed to not run any IL code.
913  * The runtime is initialized using the provided rutime version.
914  *
915  * Returns: the initial domain.
916  */
917 MonoDomain *
918 mono_init_version (const char *domain_name, const char *version)
919 {
920         return mono_init_internal (domain_name, NULL, version);
921 }
922
923 /**
924  * mono_cleanup:
925  *
926  * Cleans up all metadata modules. 
927  */
928 void
929 mono_cleanup (void)
930 {
931         mono_close_exe_image ();
932
933         mono_defaults.corlib = NULL;
934
935         mono_config_cleanup ();
936         mono_loader_cleanup ();
937         mono_classes_cleanup ();
938         mono_assemblies_cleanup ();
939         mono_images_cleanup ();
940         mono_debug_cleanup ();
941         mono_metadata_cleanup ();
942
943         mono_native_tls_free (appdomain_thread_id);
944         mono_mutex_destroy (&appdomains_mutex);
945
946 #ifndef HOST_WIN32
947         wapi_cleanup ();
948 #endif
949 }
950
951 void
952 mono_close_exe_image (void)
953 {
954         if (exe_image)
955                 mono_image_close (exe_image);
956 }
957
958 /**
959  * mono_get_root_domain:
960  *
961  * The root AppDomain is the initial domain created by the runtime when it is
962  * initialized.  Programs execute on this AppDomain, but can create new ones
963  * later.   Currently there is no unmanaged API to create new AppDomains, this
964  * must be done from managed code.
965  *
966  * Returns: the root appdomain, to obtain the current domain, use mono_domain_get ()
967  */
968 MonoDomain*
969 mono_get_root_domain (void)
970 {
971         return mono_root_domain;
972 }
973
974 /**
975  * mono_domain_get:
976  *
977  * Returns: the current domain, to obtain the root domain use
978  * mono_get_root_domain().
979  */
980 MonoDomain *
981 mono_domain_get ()
982 {
983         return GET_APPDOMAIN ();
984 }
985
986 void
987 mono_domain_unset (void)
988 {
989         SET_APPDOMAIN (NULL);
990 }
991
992 void
993 mono_domain_set_internal_with_options (MonoDomain *domain, gboolean migrate_exception)
994 {
995         MonoInternalThread *thread;
996
997         if (mono_domain_get () == domain)
998                 return;
999
1000         SET_APPDOMAIN (domain);
1001         SET_APPCONTEXT (domain->default_context);
1002
1003         if (migrate_exception) {
1004                 thread = mono_thread_internal_current ();
1005                 if (!thread->abort_exc)
1006                         return;
1007
1008                 g_assert (thread->abort_exc->object.vtable->domain != domain);
1009                 MONO_OBJECT_SETREF (thread, abort_exc, mono_get_exception_thread_abort ());
1010                 g_assert (thread->abort_exc->object.vtable->domain == domain);
1011         }
1012 }
1013
1014 /**
1015  * mono_domain_set_internal:
1016  * @domain: the new domain
1017  *
1018  * Sets the current domain to @domain.
1019  */
1020 void
1021 mono_domain_set_internal (MonoDomain *domain)
1022 {
1023         mono_domain_set_internal_with_options (domain, TRUE);
1024 }
1025
1026 void
1027 mono_domain_foreach (MonoDomainFunc func, gpointer user_data)
1028 {
1029         int i, size;
1030         MonoDomain **copy;
1031
1032         /*
1033          * Create a copy of the data to avoid calling the user callback
1034          * inside the lock because that could lead to deadlocks.
1035          * We can do this because this function is not perf. critical.
1036          */
1037         mono_appdomains_lock ();
1038         size = appdomain_list_size;
1039         copy = mono_gc_alloc_fixed (appdomain_list_size * sizeof (void*), MONO_GC_DESCRIPTOR_NULL);
1040         memcpy (copy, appdomains_list, appdomain_list_size * sizeof (void*));
1041         mono_appdomains_unlock ();
1042
1043         for (i = 0; i < size; ++i) {
1044                 if (copy [i])
1045                         func (copy [i], user_data);
1046         }
1047
1048         mono_gc_free_fixed (copy);
1049 }
1050
1051 /**
1052  * mono_domain_assembly_open:
1053  * @domain: the application domain
1054  * @name: file name of the assembly
1055  *
1056  * fixme: maybe we should integrate this with mono_assembly_open ??
1057  */
1058 MonoAssembly *
1059 mono_domain_assembly_open (MonoDomain *domain, const char *name)
1060 {
1061         MonoDomain *current;
1062         MonoAssembly *ass;
1063         GSList *tmp;
1064
1065         mono_domain_assemblies_lock (domain);
1066         for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
1067                 ass = tmp->data;
1068                 if (strcmp (name, ass->aname.name) == 0) {
1069                         mono_domain_assemblies_unlock (domain);
1070                         return ass;
1071                 }
1072         }
1073         mono_domain_assemblies_unlock (domain);
1074
1075         if (domain != mono_domain_get ()) {
1076                 current = mono_domain_get ();
1077
1078                 mono_domain_set (domain, FALSE);
1079                 ass = mono_assembly_open (name, NULL);
1080                 mono_domain_set (current, FALSE);
1081         } else {
1082                 ass = mono_assembly_open (name, NULL);
1083         }
1084
1085         return ass;
1086 }
1087
1088 static void
1089 unregister_vtable_reflection_type (MonoVTable *vtable)
1090 {
1091         MonoObject *type = vtable->type;
1092
1093         if (type->vtable->klass != mono_defaults.monotype_class)
1094                 MONO_GC_UNREGISTER_ROOT_IF_MOVING (vtable->type);
1095 }
1096
1097 void
1098 mono_domain_free (MonoDomain *domain, gboolean force)
1099 {
1100         int code_size, code_alloc;
1101         GSList *tmp;
1102         gpointer *p;
1103
1104         if ((domain == mono_root_domain) && !force) {
1105                 g_warning ("cant unload root domain");
1106                 return;
1107         }
1108
1109         if (mono_dont_free_domains)
1110                 return;
1111
1112         mono_profiler_appdomain_event (domain, MONO_PROFILE_START_UNLOAD);
1113
1114         mono_debug_domain_unload (domain);
1115
1116         mono_appdomains_lock ();
1117         appdomains_list [domain->domain_id] = NULL;
1118         mono_appdomains_unlock ();
1119
1120         /* must do this early as it accesses fields and types */
1121         if (domain->special_static_fields) {
1122                 mono_alloc_special_static_data_free (domain->special_static_fields);
1123                 g_hash_table_destroy (domain->special_static_fields);
1124                 domain->special_static_fields = NULL;
1125         }
1126
1127         /*
1128          * We must destroy all these hash tables here because they
1129          * contain references to managed objects belonging to the
1130          * domain.  Once we let the GC clear the domain there must be
1131          * no more such references, or we'll crash if a collection
1132          * occurs.
1133          */
1134         mono_g_hash_table_destroy (domain->ldstr_table);
1135         domain->ldstr_table = NULL;
1136
1137         mono_g_hash_table_destroy (domain->env);
1138         domain->env = NULL;
1139
1140         mono_reflection_cleanup_domain (domain);
1141
1142         /* This must be done before type_hash is freed */
1143         if (domain->class_vtable_array) {
1144                 int i;
1145                 for (i = 0; i < domain->class_vtable_array->len; ++i)
1146                         unregister_vtable_reflection_type (g_ptr_array_index (domain->class_vtable_array, i));
1147         }
1148
1149         if (domain->type_hash) {
1150                 mono_g_hash_table_destroy (domain->type_hash);
1151                 domain->type_hash = NULL;
1152         }
1153         if (domain->type_init_exception_hash) {
1154                 mono_g_hash_table_destroy (domain->type_init_exception_hash);
1155                 domain->type_init_exception_hash = NULL;
1156         }
1157
1158         for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
1159                 MonoAssembly *ass = tmp->data;
1160                 mono_assembly_release_gc_roots (ass);
1161         }
1162
1163         /* Have to zero out reference fields since they will be invalidated by the clear_domain () call below */
1164         for (p = (gpointer*)&domain->MONO_DOMAIN_FIRST_OBJECT; p < (gpointer*)&domain->MONO_DOMAIN_FIRST_GC_TRACKED; ++p)
1165                 *p = NULL;
1166
1167         /* This needs to be done before closing assemblies */
1168         mono_gc_clear_domain (domain);
1169
1170         /* Close dynamic assemblies first, since they have no ref count */
1171         for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
1172                 MonoAssembly *ass = tmp->data;
1173                 if (!ass->image || !image_is_dynamic (ass->image))
1174                         continue;
1175                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading domain %s[%p], assembly %s[%p], ref_count=%d", domain->friendly_name, domain, ass->aname.name, ass, ass->ref_count);
1176                 if (!mono_assembly_close_except_image_pools (ass))
1177                         tmp->data = NULL;
1178         }
1179
1180         for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
1181                 MonoAssembly *ass = tmp->data;
1182                 if (!ass)
1183                         continue;
1184                 if (!ass->image || image_is_dynamic (ass->image))
1185                         continue;
1186                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading domain %s[%p], assembly %s[%p], ref_count=%d", domain->friendly_name, domain, ass->aname.name, ass, ass->ref_count);
1187                 if (!mono_assembly_close_except_image_pools (ass))
1188                         tmp->data = NULL;
1189         }
1190
1191         for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
1192                 MonoAssembly *ass = tmp->data;
1193                 if (ass)
1194                         mono_assembly_close_finish (ass);
1195         }
1196         g_slist_free (domain->domain_assemblies);
1197         domain->domain_assemblies = NULL;
1198
1199         /* 
1200          * Send this after the assemblies have been unloaded and the domain is still in a 
1201          * usable state.
1202          */
1203         mono_profiler_appdomain_event (domain, MONO_PROFILE_END_UNLOAD);
1204
1205         if (free_domain_hook)
1206                 free_domain_hook (domain);
1207
1208         /* FIXME: free delegate_hash_table when it's used */
1209         if (domain->search_path) {
1210                 g_strfreev (domain->search_path);
1211                 domain->search_path = NULL;
1212         }
1213         domain->create_proxy_for_type_method = NULL;
1214         domain->private_invoke_method = NULL;
1215         domain->default_context = NULL;
1216         domain->out_of_memory_ex = NULL;
1217         domain->null_reference_ex = NULL;
1218         domain->stack_overflow_ex = NULL;
1219         domain->ephemeron_tombstone = NULL;
1220         domain->entry_assembly = NULL;
1221
1222         g_free (domain->friendly_name);
1223         domain->friendly_name = NULL;
1224         g_ptr_array_free (domain->class_vtable_array, TRUE);
1225         domain->class_vtable_array = NULL;
1226         g_hash_table_destroy (domain->proxy_vtable_hash);
1227         domain->proxy_vtable_hash = NULL;
1228         if (domain->static_data_array) {
1229                 mono_gc_free_fixed (domain->static_data_array);
1230                 domain->static_data_array = NULL;
1231         }
1232         mono_internal_hash_table_destroy (&domain->jit_code_hash);
1233
1234         /*
1235          * There might still be jit info tables of this domain which
1236          * are not freed.  Since the domain cannot be in use anymore,
1237          * this will free them.
1238          */
1239         mono_thread_hazardous_try_free_all ();
1240         if (domain->aot_modules)
1241                 mono_jit_info_table_free (domain->aot_modules);
1242         g_assert (domain->num_jit_info_tables == 1);
1243         mono_jit_info_table_free (domain->jit_info_table);
1244         domain->jit_info_table = NULL;
1245         g_assert (!domain->jit_info_free_queue);
1246
1247         /* collect statistics */
1248         code_alloc = mono_code_manager_size (domain->code_mp, &code_size);
1249         total_domain_code_alloc += code_alloc;
1250         max_domain_code_alloc = MAX (max_domain_code_alloc, code_alloc);
1251         max_domain_code_size = MAX (max_domain_code_size, code_size);
1252
1253         if (debug_domain_unload) {
1254                 mono_mempool_invalidate (domain->mp);
1255                 mono_code_manager_invalidate (domain->code_mp);
1256         } else {
1257 #ifndef DISABLE_PERFCOUNTERS
1258                 mono_perfcounters->loader_bytes -= mono_mempool_get_allocated (domain->mp);
1259 #endif
1260                 mono_mempool_destroy (domain->mp);
1261                 domain->mp = NULL;
1262                 mono_code_manager_destroy (domain->code_mp);
1263                 domain->code_mp = NULL;
1264         }
1265         lock_free_mempool_free (domain->lock_free_mp);
1266         domain->lock_free_mp = NULL;
1267
1268         g_hash_table_destroy (domain->finalizable_objects_hash);
1269         domain->finalizable_objects_hash = NULL;
1270         if (domain->method_rgctx_hash) {
1271                 g_hash_table_destroy (domain->method_rgctx_hash);
1272                 domain->method_rgctx_hash = NULL;
1273         }
1274         if (domain->generic_virtual_cases) {
1275                 g_hash_table_destroy (domain->generic_virtual_cases);
1276                 domain->generic_virtual_cases = NULL;
1277         }
1278         if (domain->generic_virtual_thunks) {
1279                 g_hash_table_destroy (domain->generic_virtual_thunks);
1280                 domain->generic_virtual_thunks = NULL;
1281         }
1282         if (domain->ftnptrs_hash) {
1283                 g_hash_table_destroy (domain->ftnptrs_hash);
1284                 domain->ftnptrs_hash = NULL;
1285         }
1286
1287         mono_mutex_destroy (&domain->finalizable_objects_hash_lock);
1288         mono_mutex_destroy (&domain->assemblies_lock);
1289         mono_mutex_destroy (&domain->jit_code_hash_lock);
1290         mono_mutex_destroy (&domain->lock);
1291         domain->setup = NULL;
1292
1293         mono_gc_deregister_root ((char*)&(domain->MONO_DOMAIN_FIRST_GC_TRACKED));
1294
1295         /* FIXME: anything else required ? */
1296
1297         mono_gc_free_fixed (domain);
1298
1299 #ifndef DISABLE_PERFCOUNTERS
1300         mono_perfcounters->loader_appdomains--;
1301 #endif
1302
1303         if (domain == mono_root_domain)
1304                 mono_root_domain = NULL;
1305 }
1306
1307 /**
1308  * mono_domain_get_by_id:
1309  * @domainid: the ID
1310  *
1311  * Returns: the domain for a specific domain id.
1312  */
1313 MonoDomain * 
1314 mono_domain_get_by_id (gint32 domainid) 
1315 {
1316         MonoDomain * domain;
1317
1318         mono_appdomains_lock ();
1319         if (domainid < appdomain_list_size)
1320                 domain = appdomains_list [domainid];
1321         else
1322                 domain = NULL;
1323         mono_appdomains_unlock ();
1324
1325         return domain;
1326 }
1327
1328 /*
1329  * mono_domain_get_id:
1330  *
1331  * A domain ID is guaranteed to be unique for as long as the domain
1332  * using it is alive. It may be reused later once the domain has been
1333  * unloaded.
1334  *
1335  * Returns: The unique ID for @domain.
1336  */
1337 gint32
1338 mono_domain_get_id (MonoDomain *domain)
1339 {
1340         return domain->domain_id;
1341 }
1342
1343 /*
1344  * mono_domain_get_friendly_name:
1345  *
1346  * The returned string's lifetime is the same as @domain's. Consider
1347  * copying it if you need to store it somewhere.
1348  *
1349  * Returns: The friendly name of @domain. Can be NULL if not yet set.
1350  */
1351 const char *
1352 mono_domain_get_friendly_name (MonoDomain *domain)
1353 {
1354         return domain->friendly_name;
1355 }
1356
1357 /*
1358  * mono_domain_alloc:
1359  *
1360  * LOCKING: Acquires the domain lock.
1361  */
1362 gpointer
1363 mono_domain_alloc (MonoDomain *domain, guint size)
1364 {
1365         gpointer res;
1366
1367         mono_domain_lock (domain);
1368 #ifndef DISABLE_PERFCOUNTERS
1369         mono_perfcounters->loader_bytes += size;
1370 #endif
1371         res = mono_mempool_alloc (domain->mp, size);
1372         mono_domain_unlock (domain);
1373
1374         return res;
1375 }
1376
1377 /*
1378  * mono_domain_alloc0:
1379  *
1380  * LOCKING: Acquires the domain lock.
1381  */
1382 gpointer
1383 mono_domain_alloc0 (MonoDomain *domain, guint size)
1384 {
1385         gpointer res;
1386
1387         mono_domain_lock (domain);
1388 #ifndef DISABLE_PERFCOUNTERS
1389         mono_perfcounters->loader_bytes += size;
1390 #endif
1391         res = mono_mempool_alloc0 (domain->mp, size);
1392         mono_domain_unlock (domain);
1393
1394         return res;
1395 }
1396
1397 gpointer
1398 mono_domain_alloc0_lock_free (MonoDomain *domain, guint size)
1399 {
1400         return lock_free_mempool_alloc0 (domain->lock_free_mp, size);
1401 }
1402
1403 /*
1404  * mono_domain_code_reserve:
1405  *
1406  * LOCKING: Acquires the domain lock.
1407  */
1408 void*
1409 mono_domain_code_reserve (MonoDomain *domain, int size)
1410 {
1411         gpointer res;
1412
1413         mono_domain_lock (domain);
1414         res = mono_code_manager_reserve (domain->code_mp, size);
1415         mono_domain_unlock (domain);
1416
1417         return res;
1418 }
1419
1420 /*
1421  * mono_domain_code_reserve_align:
1422  *
1423  * LOCKING: Acquires the domain lock.
1424  */
1425 void*
1426 mono_domain_code_reserve_align (MonoDomain *domain, int size, int alignment)
1427 {
1428         gpointer res;
1429
1430         mono_domain_lock (domain);
1431         res = mono_code_manager_reserve_align (domain->code_mp, size, alignment);
1432         mono_domain_unlock (domain);
1433
1434         return res;
1435 }
1436
1437 /*
1438  * mono_domain_code_commit:
1439  *
1440  * LOCKING: Acquires the domain lock.
1441  */
1442 void
1443 mono_domain_code_commit (MonoDomain *domain, void *data, int size, int newsize)
1444 {
1445         mono_domain_lock (domain);
1446         mono_code_manager_commit (domain->code_mp, data, size, newsize);
1447         mono_domain_unlock (domain);
1448 }
1449
1450 #if defined(__native_client_codegen__) && defined(__native_client__)
1451 /*
1452  * Given the temporary buffer (allocated by mono_domain_code_reserve) into which
1453  * we are generating code, return a pointer to the destination in the dynamic 
1454  * code segment into which the code will be copied when mono_domain_code_commit
1455  * is called.
1456  * LOCKING: Acquires the domain lock.
1457  */
1458 void *
1459 nacl_domain_get_code_dest (MonoDomain *domain, void *data)
1460 {
1461         void *dest;
1462         mono_domain_lock (domain);
1463         dest = nacl_code_manager_get_code_dest (domain->code_mp, data);
1464         mono_domain_unlock (domain);
1465         return dest;
1466 }
1467
1468 /* 
1469  * Convenience function which calls mono_domain_code_commit to validate and copy
1470  * the code. The caller sets *buf_base and *buf_size to the start and size of
1471  * the buffer (allocated by mono_domain_code_reserve), and *code_end to the byte
1472  * after the last instruction byte. On return, *buf_base will point to the start
1473  * of the copied in the code segment, and *code_end will point after the end of 
1474  * the copied code.
1475  */
1476 void
1477 nacl_domain_code_validate (MonoDomain *domain, guint8 **buf_base, int buf_size, guint8 **code_end)
1478 {
1479         guint8 *tmp = nacl_domain_get_code_dest (domain, *buf_base);
1480         mono_domain_code_commit (domain, *buf_base, buf_size, *code_end - *buf_base);
1481         *code_end = tmp + (*code_end - *buf_base);
1482         *buf_base = tmp;
1483 }
1484
1485 #else
1486
1487 /* no-op versions of Native Client functions */
1488
1489 void *
1490 nacl_domain_get_code_dest (MonoDomain *domain, void *data)
1491 {
1492         return data;
1493 }
1494
1495 void
1496 nacl_domain_code_validate (MonoDomain *domain, guint8 **buf_base, int buf_size, guint8 **code_end)
1497 {
1498 }
1499
1500 #endif
1501
1502 /*
1503  * mono_domain_code_foreach:
1504  * Iterate over the code thunks of the code manager of @domain.
1505  * 
1506  * The @func callback MUST not take any locks. If it really needs to, it must respect
1507  * the locking rules of the runtime: http://www.mono-project.com/Mono:Runtime:Documentation:ThreadSafety 
1508  * LOCKING: Acquires the domain lock.
1509  */
1510
1511 void
1512 mono_domain_code_foreach (MonoDomain *domain, MonoCodeManagerFunc func, void *user_data)
1513 {
1514         mono_domain_lock (domain);
1515         mono_code_manager_foreach (domain->code_mp, func, user_data);
1516         mono_domain_unlock (domain);
1517 }
1518
1519
1520 void 
1521 mono_context_set (MonoAppContext * new_context)
1522 {
1523         SET_APPCONTEXT (new_context);
1524 }
1525
1526 MonoAppContext * 
1527 mono_context_get (void)
1528 {
1529         return GET_APPCONTEXT ();
1530 }
1531
1532 /*
1533  * mono_context_get_id:
1534  *
1535  * Context IDs are guaranteed to be unique for the duration of a Mono
1536  * process; they are never reused.
1537  *
1538  * Returns: The unique ID for @context.
1539  */
1540 gint32
1541 mono_context_get_id (MonoAppContext *context)
1542 {
1543         return context->context_id;
1544 }
1545
1546 /*
1547  * mono_context_get_domain_id:
1548  *
1549  * Returns: The ID of the domain that @context was created in.
1550  */
1551 gint32
1552 mono_context_get_domain_id (MonoAppContext *context)
1553 {
1554         return context->domain_id;
1555 }
1556
1557 /* LOCKING: the caller holds the lock for this domain */
1558 void
1559 mono_domain_add_class_static_data (MonoDomain *domain, MonoClass *klass, gpointer data, guint32 *bitmap)
1560 {
1561         /* The first entry in the array is the index of the next free slot
1562          * and the total size of the array
1563          */
1564         int next;
1565         if (domain->static_data_array) {
1566                 int size = GPOINTER_TO_INT (domain->static_data_array [1]);
1567                 next = GPOINTER_TO_INT (domain->static_data_array [0]);
1568                 if (next >= size) {
1569                         /* 'data' is allocated by alloc_fixed */
1570                         gpointer *new_array = mono_gc_alloc_fixed (sizeof (gpointer) * (size * 2), MONO_GC_ROOT_DESCR_FOR_FIXED (size * 2));
1571                         mono_gc_memmove_aligned (new_array, domain->static_data_array, sizeof (gpointer) * size);
1572                         size *= 2;
1573                         new_array [1] = GINT_TO_POINTER (size);
1574                         mono_gc_free_fixed (domain->static_data_array);
1575                         domain->static_data_array = new_array;
1576                 }
1577         } else {
1578                 int size = 32;
1579                 gpointer *new_array = mono_gc_alloc_fixed (sizeof (gpointer) * size, MONO_GC_ROOT_DESCR_FOR_FIXED (size));
1580                 next = 2;
1581                 new_array [0] = GINT_TO_POINTER (next);
1582                 new_array [1] = GINT_TO_POINTER (size);
1583                 domain->static_data_array = new_array;
1584         }
1585         domain->static_data_array [next++] = data;
1586         domain->static_data_array [0] = GINT_TO_POINTER (next);
1587 }
1588
1589 MonoImage*
1590 mono_get_corlib (void)
1591 {
1592         return mono_defaults.corlib;
1593 }
1594
1595 MonoClass*
1596 mono_get_object_class (void)
1597 {
1598         return mono_defaults.object_class;
1599 }
1600
1601 MonoClass*
1602 mono_get_byte_class (void)
1603 {
1604         return mono_defaults.byte_class;
1605 }
1606
1607 MonoClass*
1608 mono_get_void_class (void)
1609 {
1610         return mono_defaults.void_class;
1611 }
1612
1613 MonoClass*
1614 mono_get_boolean_class (void)
1615 {
1616         return mono_defaults.boolean_class;
1617 }
1618
1619 MonoClass*
1620 mono_get_sbyte_class (void)
1621 {
1622         return mono_defaults.sbyte_class;
1623 }
1624
1625 MonoClass*
1626 mono_get_int16_class (void)
1627 {
1628         return mono_defaults.int16_class;
1629 }
1630
1631 MonoClass*
1632 mono_get_uint16_class (void)
1633 {
1634         return mono_defaults.uint16_class;
1635 }
1636
1637 MonoClass*
1638 mono_get_int32_class (void)
1639 {
1640         return mono_defaults.int32_class;
1641 }
1642
1643 MonoClass*
1644 mono_get_uint32_class (void)
1645 {
1646         return mono_defaults.uint32_class;
1647 }
1648
1649 MonoClass*
1650 mono_get_intptr_class (void)
1651 {
1652         return mono_defaults.int_class;
1653 }
1654
1655 MonoClass*
1656 mono_get_uintptr_class (void)
1657 {
1658         return mono_defaults.uint_class;
1659 }
1660
1661 MonoClass*
1662 mono_get_int64_class (void)
1663 {
1664         return mono_defaults.int64_class;
1665 }
1666
1667 MonoClass*
1668 mono_get_uint64_class (void)
1669 {
1670         return mono_defaults.uint64_class;
1671 }
1672
1673 MonoClass*
1674 mono_get_single_class (void)
1675 {
1676         return mono_defaults.single_class;
1677 }
1678
1679 MonoClass*
1680 mono_get_double_class (void)
1681 {
1682         return mono_defaults.double_class;
1683 }
1684
1685 MonoClass*
1686 mono_get_char_class (void)
1687 {
1688         return mono_defaults.char_class;
1689 }
1690
1691 MonoClass*
1692 mono_get_string_class (void)
1693 {
1694         return mono_defaults.string_class;
1695 }
1696
1697 MonoClass*
1698 mono_get_enum_class (void)
1699 {
1700         return mono_defaults.enum_class;
1701 }
1702
1703 MonoClass*
1704 mono_get_array_class (void)
1705 {
1706         return mono_defaults.array_class;
1707 }
1708
1709 MonoClass*
1710 mono_get_thread_class (void)
1711 {
1712         return mono_defaults.thread_class;
1713 }
1714
1715 MonoClass*
1716 mono_get_exception_class (void)
1717 {
1718         return mono_defaults.exception_class;
1719 }
1720
1721
1722 static char* get_attribute_value (const gchar **attribute_names, 
1723                                         const gchar **attribute_values, 
1724                                         const char *att_name)
1725 {
1726         int n;
1727         for (n=0; attribute_names[n] != NULL; n++) {
1728                 if (strcmp (attribute_names[n], att_name) == 0)
1729                         return g_strdup (attribute_values[n]);
1730         }
1731         return NULL;
1732 }
1733
1734 static void start_element (GMarkupParseContext *context, 
1735                            const gchar         *element_name,
1736                            const gchar        **attribute_names,
1737                            const gchar        **attribute_values,
1738                            gpointer             user_data,
1739                            GError             **error)
1740 {
1741         AppConfigInfo* app_config = (AppConfigInfo*) user_data;
1742         
1743         if (strcmp (element_name, "configuration") == 0) {
1744                 app_config->configuration_count++;
1745                 return;
1746         }
1747         if (strcmp (element_name, "startup") == 0) {
1748                 app_config->startup_count++;
1749                 return;
1750         }
1751         
1752         if (app_config->configuration_count != 1 || app_config->startup_count != 1)
1753                 return;
1754         
1755         if (strcmp (element_name, "requiredRuntime") == 0) {
1756                 app_config->required_runtime = get_attribute_value (attribute_names, attribute_values, "version");
1757         } else if (strcmp (element_name, "supportedRuntime") == 0) {
1758                 char *version = get_attribute_value (attribute_names, attribute_values, "version");
1759                 app_config->supported_runtimes = g_slist_append (app_config->supported_runtimes, version);
1760         }
1761 }
1762
1763 static void end_element   (GMarkupParseContext *context,
1764                            const gchar         *element_name,
1765                            gpointer             user_data,
1766                            GError             **error)
1767 {
1768         AppConfigInfo* app_config = (AppConfigInfo*) user_data;
1769         
1770         if (strcmp (element_name, "configuration") == 0) {
1771                 app_config->configuration_count--;
1772         } else if (strcmp (element_name, "startup") == 0) {
1773                 app_config->startup_count--;
1774         }
1775 }
1776
1777 static const GMarkupParser 
1778 mono_parser = {
1779         start_element,
1780         end_element,
1781         NULL,
1782         NULL,
1783         NULL
1784 };
1785
1786 static AppConfigInfo *
1787 app_config_parse (const char *exe_filename)
1788 {
1789         AppConfigInfo *app_config;
1790         GMarkupParseContext *context;
1791         char *text;
1792         gsize len;
1793         const char *bundled_config;
1794         char *config_filename;
1795
1796         bundled_config = mono_config_string_for_assembly_file (exe_filename);
1797
1798         if (bundled_config) {
1799                 text = g_strdup (bundled_config);
1800                 len = strlen (text);
1801         } else {
1802                 config_filename = g_strconcat (exe_filename, ".config", NULL);
1803
1804                 if (!g_file_get_contents (config_filename, &text, &len, NULL)) {
1805                         g_free (config_filename);
1806                         return NULL;
1807                 }
1808                 g_free (config_filename);
1809         }
1810
1811         app_config = g_new0 (AppConfigInfo, 1);
1812
1813         context = g_markup_parse_context_new (&mono_parser, 0, app_config, NULL);
1814         if (g_markup_parse_context_parse (context, text, len, NULL)) {
1815                 g_markup_parse_context_end_parse (context, NULL);
1816         }
1817         g_markup_parse_context_free (context);
1818         g_free (text);
1819         return app_config;
1820 }
1821
1822 static void 
1823 app_config_free (AppConfigInfo* app_config)
1824 {
1825         char *rt;
1826         GSList *list = app_config->supported_runtimes;
1827         while (list != NULL) {
1828                 rt = (char*)list->data;
1829                 g_free (rt);
1830                 list = g_slist_next (list);
1831         }
1832         g_slist_free (app_config->supported_runtimes);
1833         g_free (app_config->required_runtime);
1834         g_free (app_config);
1835 }
1836
1837
1838 static const MonoRuntimeInfo*
1839 get_runtime_by_version (const char *version)
1840 {
1841         int n;
1842         int max = G_N_ELEMENTS (supported_runtimes);
1843         int vlen;
1844
1845         if (!version)
1846                 return NULL;
1847
1848         for (n=0; n<max; n++) {
1849                 if (strcmp (version, supported_runtimes[n].runtime_version) == 0)
1850                         return &supported_runtimes[n];
1851         }
1852         
1853         vlen = strlen (version);
1854         if (vlen >= 4 && version [1] - '0' >= 4) {
1855                 for (n=0; n<max; n++) {
1856                         if (strncmp (version, supported_runtimes[n].runtime_version, 4) == 0)
1857                                 return &supported_runtimes[n];
1858                 }
1859         }
1860         
1861         return NULL;
1862 }
1863
1864 static void
1865 get_runtimes_from_exe (const char *exe_file, MonoImage **exe_image, const MonoRuntimeInfo** runtimes)
1866 {
1867         AppConfigInfo* app_config;
1868         char *version;
1869         const MonoRuntimeInfo* runtime = NULL;
1870         MonoImage *image = NULL;
1871         
1872         app_config = app_config_parse (exe_file);
1873         
1874         if (app_config != NULL) {
1875                 /* Check supportedRuntime elements, if none is supported, fail.
1876                  * If there are no such elements, look for a requiredRuntime element.
1877                  */
1878                 if (app_config->supported_runtimes != NULL) {
1879                         int n = 0;
1880                         GSList *list = app_config->supported_runtimes;
1881                         while (list != NULL) {
1882                                 version = (char*) list->data;
1883                                 runtime = get_runtime_by_version (version);
1884                                 if (runtime != NULL)
1885                                         runtimes [n++] = runtime;
1886                                 list = g_slist_next (list);
1887                         }
1888                         runtimes [n] = NULL;
1889                         app_config_free (app_config);
1890                         return;
1891                 }
1892                 
1893                 /* Check the requiredRuntime element. This is for 1.0 apps only. */
1894                 if (app_config->required_runtime != NULL) {
1895                         runtimes [0] = get_runtime_by_version (app_config->required_runtime);
1896                         runtimes [1] = NULL;
1897                         app_config_free (app_config);
1898                         return;
1899                 }
1900                 app_config_free (app_config);
1901         }
1902         
1903         /* Look for a runtime with the exact version */
1904         image = mono_assembly_open_from_bundle (exe_file, NULL, FALSE);
1905
1906         if (image == NULL)
1907                 image = mono_image_open (exe_file, NULL);
1908
1909         if (image == NULL) {
1910                 /* The image is wrong or the file was not found. In this case return
1911                  * a default runtime and leave to the initialization method the work of
1912                  * reporting the error.
1913                  */
1914                 runtimes [0] = get_runtime_by_version (DEFAULT_RUNTIME_VERSION);
1915                 runtimes [1] = NULL;
1916                 return;
1917         }
1918
1919         *exe_image = image;
1920
1921         runtimes [0] = get_runtime_by_version (image->version);
1922         runtimes [1] = NULL;
1923 }
1924
1925
1926 /**
1927  * mono_get_runtime_info:
1928  *
1929  * Returns: the version of the current runtime instance.
1930  */
1931 const MonoRuntimeInfo*
1932 mono_get_runtime_info (void)
1933 {
1934         return current_runtime;
1935 }
1936
1937 /**
1938  * mono_framework_version:
1939  *
1940  * Return the major version of the framework curently executing.
1941  */
1942 int
1943 mono_framework_version (void)
1944 {
1945         return current_runtime->framework_version [0] - '0';
1946 }
1947
1948 void
1949 mono_enable_debug_domain_unload (gboolean enable)
1950 {
1951         debug_domain_unload = enable;
1952 }
1953
1954 MonoAotCacheConfig *
1955 mono_get_aot_cache_config (void)
1956 {
1957         return &aot_cache_config;
1958 }
1959
1960 void
1961 mono_domain_lock (MonoDomain *domain)
1962 {
1963         MONO_TRY_BLOCKING;
1964         mono_locks_acquire (&(domain)->lock, DomainLock);
1965         MONO_FINISH_TRY_BLOCKING;
1966 }
1967
1968 void
1969 mono_domain_unlock (MonoDomain *domain)
1970 {
1971         mono_locks_release (&(domain)->lock, DomainLock);
1972 }