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