[Loader] Change mono_trace level from info to debug (#19110)
[mono-project.git] / mono / metadata / domain.c
blob5940f6cb2d1dd2b012fc12fb9865c3ee20e1cd57
1 /**
2 * \file
3 * MonoDomain functions
5 * Author:
6 * Dietmar Maurer (dietmar@ximian.com)
7 * Patrik Torstensson
9 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
10 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
11 * Copyright 2011-2012 Xamarin, Inc (http://www.xamarin.com)
12 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
15 #include <config.h>
16 #include <glib.h>
17 #include <string.h>
18 #include <sys/stat.h>
20 #include <mono/metadata/gc-internals.h>
22 #include <mono/utils/atomic.h>
23 #include <mono/utils/mono-compiler.h>
24 #include <mono/utils/mono-logger-internals.h>
25 #include <mono/utils/mono-membar.h>
26 #include <mono/utils/mono-counters.h>
27 #include <mono/utils/hazard-pointer.h>
28 #include <mono/utils/mono-tls.h>
29 #include <mono/utils/mono-mmap.h>
30 #include <mono/utils/mono-threads.h>
31 #include <mono/metadata/object.h>
32 #include <mono/metadata/object-internals.h>
33 #include <mono/metadata/domain-internals.h>
34 #include <mono/metadata/class-internals.h>
35 #include <mono/metadata/class-init.h>
36 #include <mono/metadata/debug-internals.h>
37 #include <mono/metadata/assembly-internals.h>
38 #include <mono/metadata/exception.h>
39 #include <mono/metadata/metadata-internals.h>
40 #include <mono/metadata/appdomain.h>
41 #include <mono/metadata/mono-config.h>
42 #include <mono/metadata/mono-hash-internals.h>
43 #include <mono/metadata/threads-types.h>
44 #include <mono/metadata/runtime.h>
45 #include <mono/metadata/w32mutex.h>
46 #include <mono/metadata/w32semaphore.h>
47 #include <mono/metadata/w32event.h>
48 #include <mono/metadata/w32process.h>
49 #include <mono/metadata/w32file.h>
50 #include <mono/metadata/threads.h>
51 #include <mono/metadata/profiler-private.h>
52 #include <mono/metadata/coree.h>
53 #include <mono/utils/mono-experiments.h>
54 #include "external-only.h"
55 #include "mono/utils/mono-tls-inline.h"
57 //#define DEBUG_DOMAIN_UNLOAD 1
59 #define GET_APPDOMAIN mono_tls_get_domain
60 #define SET_APPDOMAIN(x) do { \
61 MonoThreadInfo *info; \
62 mono_tls_set_domain (x); \
63 info = mono_thread_info_current (); \
64 if (info) \
65 mono_thread_info_tls_set (info, TLS_KEY_DOMAIN, (x)); \
66 } while (FALSE)
68 #define GET_APPCONTEXT() (mono_thread_internal_current ()->current_appcontext)
69 #define SET_APPCONTEXT(x) MONO_OBJECT_SETREF_INTERNAL (mono_thread_internal_current (), current_appcontext, (x))
71 static guint16 appdomain_list_size = 0;
72 static guint16 appdomain_next = 0;
73 static MonoDomain **appdomains_list = NULL;
74 static MonoImage *exe_image;
75 static gboolean debug_domain_unload;
77 gboolean mono_dont_free_domains;
79 #define mono_appdomains_lock() mono_coop_mutex_lock (&appdomains_mutex)
80 #define mono_appdomains_unlock() mono_coop_mutex_unlock (&appdomains_mutex)
81 static MonoCoopMutex appdomains_mutex;
83 static MonoDomain *mono_root_domain = NULL;
85 /* some statistics */
86 static int max_domain_code_size = 0;
87 static int max_domain_code_alloc = 0;
88 static int total_domain_code_alloc = 0;
90 /* AppConfigInfo: Information about runtime versions supported by an
91 * aplication.
93 typedef struct {
94 GSList *supported_runtimes;
95 char *required_runtime;
96 int configuration_count;
97 int startup_count;
98 } AppConfigInfo;
100 static const MonoRuntimeInfo *current_runtime = NULL;
102 #define NOT_AVAIL {0xffffU,0xffffU,0xffffU,0xffffU}
104 /* This is the list of runtime versions supported by this JIT.
106 static const MonoRuntimeInfo supported_runtimes[] = {
107 {"v4.0.30319","4.5", { {4,0,0,0}, {10,0,0,0}, {4,0,0,0}, {4,0,0,0}, {4,0,0,0} } },
108 {"mobile", "2.1", { {2,0,5,0}, {10,0,0,0}, {2,0,5,0}, {2,0,5,0}, {4,0,0,0} } },
109 {"moonlight", "2.1", { {2,0,5,0}, { 9,0,0,0}, {3,5,0,0}, {3,0,0,0}, NOT_AVAIL } },
112 #undef NOT_AVAIL
115 /* The stable runtime version */
116 #define DEFAULT_RUNTIME_VERSION "v4.0.30319"
118 /* Callbacks installed by the JIT */
119 static MonoCreateDomainFunc create_domain_hook;
120 static MonoFreeDomainFunc free_domain_hook;
122 /* AOT cache configuration */
123 static MonoAotCacheConfig aot_cache_config;
125 static GSList*
126 get_runtimes_from_exe (const char *exe_file, MonoImage **exe_image);
128 static const MonoRuntimeInfo*
129 get_runtime_by_version (const char *version);
131 static void
132 mono_domain_alcs_destroy (MonoDomain *domain);
134 #ifdef ENABLE_NETCORE
135 static void
136 mono_domain_alcs_lock (MonoDomain *domain);
138 static void
139 mono_domain_alcs_unlock (MonoDomain *domain);
141 static void
142 mono_domain_create_default_alc (MonoDomain *domain);
143 #endif
145 static LockFreeMempool*
146 lock_free_mempool_new (void)
148 return g_new0 (LockFreeMempool, 1);
151 static void
152 lock_free_mempool_free (LockFreeMempool *mp)
154 LockFreeMempoolChunk *chunk, *next;
156 chunk = mp->chunks;
157 while (chunk) {
158 next = (LockFreeMempoolChunk *)chunk->prev;
159 mono_vfree (chunk, mono_pagesize (), MONO_MEM_ACCOUNT_DOMAIN);
160 chunk = next;
162 g_free (mp);
166 * This is async safe
168 static LockFreeMempoolChunk*
169 lock_free_mempool_chunk_new (LockFreeMempool *mp, int len)
171 LockFreeMempoolChunk *chunk, *prev;
172 int size;
174 size = mono_pagesize ();
175 while (size - sizeof (LockFreeMempoolChunk) < len)
176 size += mono_pagesize ();
177 chunk = (LockFreeMempoolChunk *)mono_valloc (0, size, MONO_MMAP_READ|MONO_MMAP_WRITE, MONO_MEM_ACCOUNT_DOMAIN);
178 g_assert (chunk);
179 chunk->mem = (guint8 *)ALIGN_PTR_TO ((char*)chunk + sizeof (LockFreeMempoolChunk), 16);
180 chunk->size = ((char*)chunk + size) - (char*)chunk->mem;
181 chunk->pos = 0;
183 /* Add to list of chunks lock-free */
184 while (TRUE) {
185 prev = mp->chunks;
186 if (mono_atomic_cas_ptr ((volatile gpointer*)&mp->chunks, chunk, prev) == prev)
187 break;
189 chunk->prev = prev;
191 return chunk;
195 * This is async safe
197 static gpointer
198 lock_free_mempool_alloc0 (LockFreeMempool *mp, guint size)
200 LockFreeMempoolChunk *chunk;
201 gpointer res;
202 int oldpos;
204 // FIXME: Free the allocator
206 size = ALIGN_TO (size, 8);
207 chunk = mp->current;
208 if (!chunk) {
209 chunk = lock_free_mempool_chunk_new (mp, size);
210 mono_memory_barrier ();
211 /* Publish */
212 mp->current = chunk;
215 /* The code below is lock-free, 'chunk' is shared state */
216 oldpos = mono_atomic_fetch_add_i32 (&chunk->pos, size);
217 if (oldpos + size > chunk->size) {
218 chunk = lock_free_mempool_chunk_new (mp, size);
219 g_assert (chunk->pos + size <= chunk->size);
220 res = chunk->mem;
221 chunk->pos += size;
222 mono_memory_barrier ();
223 mp->current = chunk;
224 } else {
225 res = (char*)chunk->mem + oldpos;
228 return res;
231 void
232 mono_install_create_domain_hook (MonoCreateDomainFunc func)
234 create_domain_hook = func;
237 void
238 mono_install_free_domain_hook (MonoFreeDomainFunc func)
240 free_domain_hook = func;
243 gboolean
244 mono_string_equal_internal (MonoString *s1, MonoString *s2)
246 int l1 = mono_string_length_internal (s1);
247 int l2 = mono_string_length_internal (s2);
249 if (s1 == s2)
250 return TRUE;
251 if (l1 != l2)
252 return FALSE;
254 return memcmp (mono_string_chars_internal (s1), mono_string_chars_internal (s2), l1 * 2) == 0;
258 * mono_string_equal:
259 * \param s1 First string to compare
260 * \param s2 Second string to compare
262 * Compares two \c MonoString* instances ordinally for equality.
264 * \returns FALSE if the strings differ.
266 gboolean
267 mono_string_equal (MonoString *s1, MonoString *s2)
269 MONO_EXTERNAL_ONLY (gboolean, mono_string_equal_internal (s1, s2));
272 guint
273 mono_string_hash_internal (MonoString *s)
275 const gunichar2 *p = mono_string_chars_internal (s);
276 int i, len = mono_string_length_internal (s);
277 guint h = 0;
279 for (i = 0; i < len; i++) {
280 h = (h << 5) - h + *p;
281 p++;
284 return h;
288 * mono_string_hash:
289 * \param s the string to hash
291 * Compute the hash for a \c MonoString*
292 * \returns the hash for the string.
294 guint
295 mono_string_hash (MonoString *s)
297 MONO_EXTERNAL_ONLY (guint, mono_string_hash_internal (s));
300 static gboolean
301 mono_ptrarray_equal (gpointer *s1, gpointer *s2)
303 int len = GPOINTER_TO_INT (s1 [0]);
304 if (len != GPOINTER_TO_INT (s2 [0]))
305 return FALSE;
307 return memcmp (s1 + 1, s2 + 1, len * sizeof(gpointer)) == 0;
310 static guint
311 mono_ptrarray_hash (gpointer *s)
313 int i;
314 int len = GPOINTER_TO_INT (s [0]);
315 guint hash = 0;
317 for (i = 1; i < len; i++)
318 hash += GPOINTER_TO_UINT (s [i]);
320 return hash;
323 //g_malloc on sgen and mono_gc_alloc_fixed on boehm
324 static void*
325 gc_alloc_fixed_non_heap_list (size_t size)
327 if (mono_gc_is_moving ())
328 return g_malloc0 (size);
329 else
330 return mono_gc_alloc_fixed (size, MONO_GC_DESCRIPTOR_NULL, MONO_ROOT_SOURCE_DOMAIN, NULL, "Domain List");
333 static void
334 gc_free_fixed_non_heap_list (void *ptr)
336 if (mono_gc_is_moving ())
337 g_free (ptr);
338 else
339 mono_gc_free_fixed (ptr);
342 * Allocate an id for domain and set domain->domain_id.
343 * LOCKING: must be called while holding appdomains_mutex.
344 * We try to assign low numbers to the domain, so it can be used
345 * as an index in data tables to lookup domain-specific info
346 * with minimal memory overhead. We also try not to reuse the
347 * same id too quickly (to help debugging).
349 static int
350 domain_id_alloc (MonoDomain *domain)
352 int id = -1, i;
353 if (!appdomains_list) {
354 appdomain_list_size = 2;
355 appdomains_list = (MonoDomain **)gc_alloc_fixed_non_heap_list (appdomain_list_size * sizeof (void*));
358 for (i = appdomain_next; i < appdomain_list_size; ++i) {
359 if (!appdomains_list [i]) {
360 id = i;
361 break;
364 if (id == -1) {
365 for (i = 0; i < appdomain_next; ++i) {
366 if (!appdomains_list [i]) {
367 id = i;
368 break;
372 if (id == -1) {
373 MonoDomain **new_list;
374 int new_size = appdomain_list_size * 2;
375 if (new_size >= (1 << 16))
376 g_assert_not_reached ();
377 id = appdomain_list_size;
378 new_list = (MonoDomain **)gc_alloc_fixed_non_heap_list (new_size * sizeof (void*));
379 memcpy (new_list, appdomains_list, appdomain_list_size * sizeof (void*));
380 gc_free_fixed_non_heap_list (appdomains_list);
381 appdomains_list = new_list;
382 appdomain_list_size = new_size;
384 domain->domain_id = id;
385 appdomains_list [id] = domain;
386 appdomain_next++;
387 if (appdomain_next > appdomain_list_size)
388 appdomain_next = 0;
389 return id;
392 static gsize domain_gc_bitmap [sizeof(MonoDomain)/4/32 + 1];
393 static MonoGCDescriptor domain_gc_desc = MONO_GC_DESCRIPTOR_NULL;
394 static guint32 domain_shadow_serial = 0L;
397 * mono_domain_create:
399 * Creates a new application domain, the unmanaged representation
400 * of the actual domain.
402 * Application domains provide an isolation facilty for assemblies. You
403 * can load assemblies and execute code in them that will not be visible
404 * to other application domains. This is a runtime-based virtualization
405 * technology.
407 * It is possible to unload domains, which unloads the assemblies and
408 * data that was allocated in that domain.
410 * When a domain is created a mempool is allocated for domain-specific
411 * structures, along a dedicated code manager to hold code that is
412 * associated with the domain.
414 * \returns New initialized \c MonoDomain, with no configuration or assemblies
415 * loaded into it.
417 MonoDomain *
418 mono_domain_create (void)
420 MonoDomain *domain;
421 guint32 shadow_serial;
423 mono_appdomains_lock ();
424 shadow_serial = domain_shadow_serial++;
426 if (!domain_gc_desc) {
427 unsigned int i, bit = 0;
428 for (i = G_STRUCT_OFFSET (MonoDomain, MONO_DOMAIN_FIRST_OBJECT); i < G_STRUCT_OFFSET (MonoDomain, MONO_DOMAIN_FIRST_GC_TRACKED); i += sizeof (gpointer)) {
429 bit = i / sizeof (gpointer);
430 domain_gc_bitmap [bit / 32] |= (gsize) 1 << (bit % 32);
432 domain_gc_desc = mono_gc_make_descr_from_bitmap ((gsize*)domain_gc_bitmap, bit + 1);
434 mono_appdomains_unlock ();
436 if (!mono_gc_is_moving ())
437 domain = (MonoDomain *)mono_gc_alloc_fixed (sizeof (MonoDomain), MONO_GC_DESCRIPTOR_NULL, MONO_ROOT_SOURCE_DOMAIN, NULL, "Domain Structure");
438 else
439 domain = (MonoDomain *)mono_gc_alloc_fixed (sizeof (MonoDomain), domain_gc_desc, MONO_ROOT_SOURCE_DOMAIN, NULL, "Domain Structure");
441 domain->shadow_serial = shadow_serial;
442 domain->domain = NULL;
443 domain->setup = NULL;
444 domain->friendly_name = NULL;
445 domain->search_path = NULL;
447 MONO_PROFILER_RAISE (domain_loading, (domain));
449 domain->mp = mono_mempool_new ();
450 domain->code_mp = mono_code_manager_new ();
451 domain->lock_free_mp = lock_free_mempool_new ();
452 domain->env = mono_g_hash_table_new_type_internal ((GHashFunc)mono_string_hash_internal, (GCompareFunc)mono_string_equal_internal, MONO_HASH_KEY_VALUE_GC, MONO_ROOT_SOURCE_DOMAIN, domain, "Domain Environment Variable Table");
453 domain->domain_assemblies = NULL;
454 domain->assembly_bindings = NULL;
455 domain->assembly_bindings_parsed = FALSE;
456 domain->class_vtable_array = g_ptr_array_new ();
457 domain->proxy_vtable_hash = g_hash_table_new ((GHashFunc)mono_ptrarray_hash, (GCompareFunc)mono_ptrarray_equal);
458 mono_jit_code_hash_init (&domain->jit_code_hash);
459 domain->ldstr_table = mono_g_hash_table_new_type_internal ((GHashFunc)mono_string_hash_internal, (GCompareFunc)mono_string_equal_internal, MONO_HASH_KEY_VALUE_GC, MONO_ROOT_SOURCE_DOMAIN, domain, "Domain String Pool Table");
460 domain->num_jit_info_table_duplicates = 0;
461 domain->jit_info_table = mono_jit_info_table_new (domain);
462 domain->jit_info_free_queue = NULL;
463 domain->finalizable_objects_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
464 domain->ftnptrs_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
466 mono_coop_mutex_init_recursive (&domain->lock);
468 mono_coop_mutex_init_recursive (&domain->assemblies_lock);
469 mono_os_mutex_init_recursive (&domain->jit_code_hash_lock);
470 mono_os_mutex_init_recursive (&domain->finalizable_objects_hash_lock);
472 #ifdef ENABLE_NETCORE
473 mono_coop_mutex_init (&domain->alcs_lock);
474 #endif
476 mono_appdomains_lock ();
477 domain_id_alloc (domain);
478 mono_appdomains_unlock ();
480 #ifndef DISABLE_PERFCOUNTERS
481 mono_atomic_inc_i32 (&mono_perfcounters->loader_appdomains);
482 mono_atomic_inc_i32 (&mono_perfcounters->loader_total_appdomains);
483 #endif
485 mono_debug_domain_create (domain);
487 #ifdef ENABLE_NETCORE
488 mono_domain_create_default_alc (domain);
489 #endif
491 if (create_domain_hook)
492 create_domain_hook (domain);
494 MONO_PROFILER_RAISE (domain_loaded, (domain));
496 return domain;
500 * mono_init_internal:
502 * Creates the initial application domain and initializes the mono_defaults
503 * structure.
504 * This function is guaranteed to not run any IL code.
505 * If exe_filename is not NULL, the method will determine the required runtime
506 * from the exe configuration file or the version PE field.
507 * If runtime_version is not NULL, that runtime version will be used.
508 * Either exe_filename or runtime_version must be provided.
510 * Returns: the initial domain.
512 static MonoDomain *
513 mono_init_internal (const char *filename, const char *exe_filename, const char *runtime_version)
515 static MonoDomain *domain = NULL;
516 MonoAssembly *ass = NULL;
517 MonoImageOpenStatus status = MONO_IMAGE_OK;
518 GSList *runtimes = NULL;
520 #ifdef DEBUG_DOMAIN_UNLOAD
521 debug_domain_unload = TRUE;
522 #endif
524 if (domain)
525 g_assert_not_reached ();
527 #if defined(HOST_WIN32) && G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
528 /* Avoid system error message boxes. */
529 SetErrorMode (SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
530 #endif
532 #ifndef HOST_WIN32
533 mono_w32handle_init ();
534 mono_w32handle_namespace_init ();
535 #endif
537 mono_w32mutex_init ();
538 mono_w32semaphore_init ();
539 mono_w32event_init ();
540 mono_w32process_init ();
541 mono_w32file_init ();
543 #ifndef DISABLE_PERFCOUNTERS
544 mono_perfcounters_init ();
545 #endif
546 mono_counters_init ();
548 mono_counters_register ("Max native code in a domain", MONO_COUNTER_INT|MONO_COUNTER_JIT, &max_domain_code_size);
549 mono_counters_register ("Max code space allocated in a domain", MONO_COUNTER_INT|MONO_COUNTER_JIT, &max_domain_code_alloc);
550 mono_counters_register ("Total code space allocated", MONO_COUNTER_INT|MONO_COUNTER_JIT, &total_domain_code_alloc);
552 mono_counters_register ("Max HashTable Chain Length", MONO_COUNTER_INT|MONO_COUNTER_METADATA, &mono_g_hash_table_max_chain_length);
554 mono_gc_base_init ();
555 mono_thread_info_attach ();
557 mono_coop_mutex_init_recursive (&appdomains_mutex);
559 mono_metadata_init ();
560 mono_images_init ();
561 mono_assemblies_init ();
562 mono_classes_init ();
563 mono_loader_init ();
564 mono_reflection_init ();
565 mono_runtime_init_tls ();
566 mono_icall_init ();
568 domain = mono_domain_create ();
569 mono_root_domain = domain;
571 SET_APPDOMAIN (domain);
573 #if defined(ENABLE_EXPERIMENT_null)
574 if (mono_experiment_enabled (MONO_EXPERIMENT_null))
575 g_warning ("null experiment enabled");
576 #endif
578 /* Get a list of runtimes supported by the exe */
579 if (exe_filename != NULL) {
581 * This function will load the exe file as a MonoImage. We need to close it, but
582 * that would mean it would be reloaded later. So instead, we save it to
583 * exe_image, and close it during shutdown.
585 runtimes = get_runtimes_from_exe (exe_filename, &exe_image);
586 #ifdef HOST_WIN32
587 if (!exe_image) {
588 exe_image = mono_assembly_open_from_bundle (mono_domain_default_alc (domain), exe_filename, NULL, FALSE);
589 if (!exe_image)
590 exe_image = mono_image_open (exe_filename, NULL);
592 mono_fixup_exe_image (exe_image);
593 #endif
594 } else if (runtime_version != NULL) {
595 const MonoRuntimeInfo* rt = get_runtime_by_version (runtime_version);
596 if (rt != NULL)
597 runtimes = g_slist_prepend (runtimes, (gpointer)rt);
600 if (runtimes == NULL) {
601 const MonoRuntimeInfo *default_runtime = get_runtime_by_version (DEFAULT_RUNTIME_VERSION);
602 g_assert (default_runtime);
603 runtimes = g_slist_prepend (runtimes, (gpointer)default_runtime);
604 if (runtime_version != NULL)
605 g_print ("WARNING: The requested runtime version \"%s\" is unavailable.\n", runtime_version);
606 else
607 g_print ("WARNING: The runtime version supported by this application is unavailable.\n");
608 g_print ("Using default runtime: %s\n", default_runtime->runtime_version);
611 /* The selected runtime will be the first one for which there is a mscrolib.dll */
612 GSList *tmp = runtimes;
613 while (tmp != NULL) {
614 current_runtime = (MonoRuntimeInfo*)tmp->data;
615 g_assert (current_runtime);
616 ass = mono_assembly_load_corlib (current_runtime, &status);
617 if (status != MONO_IMAGE_OK && status != MONO_IMAGE_ERROR_ERRNO)
618 break;
619 tmp = tmp->next;
622 g_slist_free (runtimes);
624 if ((status != MONO_IMAGE_OK) || (ass == NULL)) {
625 switch (status){
626 case MONO_IMAGE_ERROR_ERRNO: {
627 char *corlib_file = g_build_filename (mono_assembly_getrootdir (), "mono", current_runtime->framework_version, "mscorlib.dll", (const char*)NULL);
628 g_print ("The assembly mscorlib.dll was not found or could not be loaded.\n");
629 g_print ("It should have been installed in the `%s' directory.\n", corlib_file);
630 g_free (corlib_file);
631 break;
633 case MONO_IMAGE_IMAGE_INVALID:
634 g_print ("The file %s/mscorlib.dll is an invalid CIL image\n",
635 mono_assembly_getrootdir ());
636 break;
637 case MONO_IMAGE_MISSING_ASSEMBLYREF:
638 g_print ("Missing assembly reference in %s/mscorlib.dll\n",
639 mono_assembly_getrootdir ());
640 break;
641 case MONO_IMAGE_OK:
642 /* to suppress compiler warning */
643 break;
646 exit (1);
648 mono_defaults.corlib = mono_assembly_get_image_internal (ass);
650 mono_defaults.object_class = mono_class_load_from_name (
651 mono_defaults.corlib, "System", "Object");
653 mono_defaults.void_class = mono_class_load_from_name (
654 mono_defaults.corlib, "System", "Void");
656 mono_defaults.boolean_class = mono_class_load_from_name (
657 mono_defaults.corlib, "System", "Boolean");
659 mono_defaults.byte_class = mono_class_load_from_name (
660 mono_defaults.corlib, "System", "Byte");
662 mono_defaults.sbyte_class = mono_class_load_from_name (
663 mono_defaults.corlib, "System", "SByte");
665 mono_defaults.int16_class = mono_class_load_from_name (
666 mono_defaults.corlib, "System", "Int16");
668 mono_defaults.uint16_class = mono_class_load_from_name (
669 mono_defaults.corlib, "System", "UInt16");
671 mono_defaults.int32_class = mono_class_load_from_name (
672 mono_defaults.corlib, "System", "Int32");
674 mono_defaults.uint32_class = mono_class_load_from_name (
675 mono_defaults.corlib, "System", "UInt32");
677 mono_defaults.uint_class = mono_class_load_from_name (
678 mono_defaults.corlib, "System", "UIntPtr");
680 mono_defaults.int_class = mono_class_load_from_name (
681 mono_defaults.corlib, "System", "IntPtr");
683 mono_defaults.int64_class = mono_class_load_from_name (
684 mono_defaults.corlib, "System", "Int64");
686 mono_defaults.uint64_class = mono_class_load_from_name (
687 mono_defaults.corlib, "System", "UInt64");
689 mono_defaults.single_class = mono_class_load_from_name (
690 mono_defaults.corlib, "System", "Single");
692 mono_defaults.double_class = mono_class_load_from_name (
693 mono_defaults.corlib, "System", "Double");
695 mono_defaults.char_class = mono_class_load_from_name (
696 mono_defaults.corlib, "System", "Char");
698 mono_defaults.string_class = mono_class_load_from_name (
699 mono_defaults.corlib, "System", "String");
701 mono_defaults.enum_class = mono_class_load_from_name (
702 mono_defaults.corlib, "System", "Enum");
704 mono_defaults.array_class = mono_class_load_from_name (
705 mono_defaults.corlib, "System", "Array");
707 mono_defaults.delegate_class = mono_class_load_from_name (
708 mono_defaults.corlib, "System", "Delegate");
710 mono_defaults.multicastdelegate_class = mono_class_load_from_name (
711 mono_defaults.corlib, "System", "MulticastDelegate");
713 #ifndef ENABLE_NETCORE
714 mono_defaults.manualresetevent_class = mono_class_load_from_name (
715 mono_defaults.corlib, "System.Threading", "ManualResetEvent");
716 #endif
718 mono_defaults.typehandle_class = mono_class_load_from_name (
719 mono_defaults.corlib, "System", "RuntimeTypeHandle");
721 mono_defaults.methodhandle_class = mono_class_load_from_name (
722 mono_defaults.corlib, "System", "RuntimeMethodHandle");
724 mono_defaults.fieldhandle_class = mono_class_load_from_name (
725 mono_defaults.corlib, "System", "RuntimeFieldHandle");
727 mono_defaults.systemtype_class = mono_class_load_from_name (
728 mono_defaults.corlib, "System", "Type");
730 mono_defaults.runtimetype_class = mono_class_load_from_name (
731 mono_defaults.corlib, "System", "RuntimeType");
733 mono_defaults.exception_class = mono_class_load_from_name (
734 mono_defaults.corlib, "System", "Exception");
736 mono_defaults.thread_class = mono_class_load_from_name (
737 mono_defaults.corlib, "System.Threading", "Thread");
739 #ifdef ENABLE_NETCORE
740 /* There is only one thread class */
741 mono_defaults.internal_thread_class = mono_defaults.thread_class;
742 #else
743 mono_defaults.internal_thread_class = mono_class_load_from_name (
744 mono_defaults.corlib, "System.Threading", "InternalThread");
746 mono_defaults.threadabortexception_class = mono_class_load_from_name (
747 mono_defaults.corlib, "System.Threading", "ThreadAbortException");
748 #endif
750 mono_defaults.appdomain_class = mono_class_get_appdomain_class ();
752 #ifndef DISABLE_REMOTING
753 mono_defaults.transparent_proxy_class = mono_class_load_from_name (
754 mono_defaults.corlib, "System.Runtime.Remoting.Proxies", "TransparentProxy");
756 mono_defaults.real_proxy_class = mono_class_load_from_name (
757 mono_defaults.corlib, "System.Runtime.Remoting.Proxies", "RealProxy");
759 mono_defaults.marshalbyrefobject_class = mono_class_load_from_name (
760 mono_defaults.corlib, "System", "MarshalByRefObject");
762 mono_defaults.iremotingtypeinfo_class = mono_class_load_from_name (
763 mono_defaults.corlib, "System.Runtime.Remoting", "IRemotingTypeInfo");
765 #endif
767 /* FIXME pretty sure this is wrong and netcore has messages... */
768 #ifndef ENABLE_NETCORE
769 mono_defaults.mono_method_message_class = mono_class_load_from_name (
770 mono_defaults.corlib, "System.Runtime.Remoting.Messaging", "MonoMethodMessage");
771 #endif
773 mono_defaults.field_info_class = mono_class_load_from_name (
774 mono_defaults.corlib, "System.Reflection", "FieldInfo");
776 mono_defaults.method_info_class = mono_class_load_from_name (
777 mono_defaults.corlib, "System.Reflection", "MethodInfo");
779 #ifdef ENABLE_NETCORE
780 mono_defaults.stack_frame_class = mono_class_load_from_name (
781 mono_defaults.corlib, "System.Diagnostics", "MonoStackFrame");
782 #else
783 mono_defaults.stack_frame_class = mono_class_load_from_name (
784 mono_defaults.corlib, "System.Diagnostics", "StackFrame");
785 #endif
787 mono_defaults.marshal_class = mono_class_load_from_name (
788 mono_defaults.corlib, "System.Runtime.InteropServices", "Marshal");
790 mono_defaults.typed_reference_class = mono_class_load_from_name (
791 mono_defaults.corlib, "System", "TypedReference");
793 mono_defaults.argumenthandle_class = mono_class_load_from_name (
794 mono_defaults.corlib, "System", "RuntimeArgumentHandle");
796 mono_defaults.monitor_class = mono_class_load_from_name (
797 mono_defaults.corlib, "System.Threading", "Monitor");
799 Not using GENERATE_TRY_GET_CLASS_WITH_CACHE_DECL as this type is heavily checked by sgen when computing finalization.
801 mono_defaults.critical_finalizer_object = mono_class_try_load_from_name (mono_defaults.corlib,
802 "System.Runtime.ConstrainedExecution", "CriticalFinalizerObject");
804 mono_assembly_load_friends (ass);
806 mono_defaults.attribute_class = mono_class_load_from_name (
807 mono_defaults.corlib, "System", "Attribute");
809 mono_class_init_internal (mono_defaults.array_class);
810 mono_defaults.generic_nullable_class = mono_class_load_from_name (
811 mono_defaults.corlib, "System", "Nullable`1");
812 mono_defaults.generic_ilist_class = mono_class_load_from_name (
813 mono_defaults.corlib, "System.Collections.Generic", "IList`1");
814 mono_defaults.generic_ireadonlylist_class = mono_class_load_from_name (
815 mono_defaults.corlib, "System.Collections.Generic", "IReadOnlyList`1");
816 mono_defaults.generic_ienumerator_class = mono_class_load_from_name (
817 mono_defaults.corlib, "System.Collections.Generic", "IEnumerator`1");
819 #ifndef ENABLE_NETCORE
820 MonoClass *threadpool_wait_callback_class = mono_class_load_from_name (
821 mono_defaults.corlib, "System.Threading", "_ThreadPoolWaitCallback");
823 ERROR_DECL (error);
824 mono_defaults.threadpool_perform_wait_callback_method = mono_class_get_method_from_name_checked (
825 threadpool_wait_callback_class, "PerformWaitCallback", 0, 0, error);
826 mono_error_assert_ok (error);
827 #endif
829 domain->friendly_name = g_path_get_basename (filename);
831 MONO_PROFILER_RAISE (domain_name, (domain, domain->friendly_name));
833 return domain;
837 * mono_init:
839 * Creates the initial application domain and initializes the mono_defaults
840 * structure.
842 * This function is guaranteed to not run any IL code.
843 * The runtime is initialized using the default runtime version.
845 * Returns: the initial domain.
847 MonoDomain *
848 mono_init (const char *domain_name)
850 return mono_init_internal (domain_name, NULL, DEFAULT_RUNTIME_VERSION);
854 * mono_init_from_assembly:
855 * \param domain_name name to give to the initial domain
856 * \param filename filename to load on startup
858 * Used by the runtime, users should use mono_jit_init instead.
860 * Creates the initial application domain and initializes the mono_defaults
861 * structure.
862 * This function is guaranteed to not run any IL code.
863 * The runtime is initialized using the runtime version required by the
864 * provided executable. The version is determined by looking at the exe
865 * configuration file and the version PE field)
867 * \returns the initial domain.
869 MonoDomain *
870 mono_init_from_assembly (const char *domain_name, const char *filename)
872 return mono_init_internal (domain_name, filename, NULL);
876 * mono_init_version:
878 * Used by the runtime, users should use \c mono_jit_init instead.
880 * Creates the initial application domain and initializes the \c mono_defaults
881 * structure.
883 * This function is guaranteed to not run any IL code.
884 * The runtime is initialized using the provided rutime version.
886 * \returns the initial domain.
888 MonoDomain *
889 mono_init_version (const char *domain_name, const char *version)
891 return mono_init_internal (domain_name, NULL, version);
895 * mono_cleanup:
897 * Cleans up all metadata modules.
899 void
900 mono_cleanup (void)
902 mono_close_exe_image ();
904 mono_thread_info_cleanup ();
906 mono_defaults.corlib = NULL;
908 mono_config_cleanup ();
909 mono_loader_cleanup ();
910 mono_classes_cleanup ();
911 mono_assemblies_cleanup ();
912 mono_debug_cleanup ();
913 mono_images_cleanup ();
914 mono_metadata_cleanup ();
916 mono_coop_mutex_destroy (&appdomains_mutex);
918 mono_w32process_cleanup ();
919 mono_w32file_cleanup ();
922 void
923 mono_close_exe_image (void)
925 if (exe_image)
926 mono_image_close (exe_image);
930 * mono_get_root_domain:
932 * The root AppDomain is the initial domain created by the runtime when it is
933 * initialized. Programs execute on this AppDomain, but can create new ones
934 * later. Currently there is no unmanaged API to create new AppDomains, this
935 * must be done from managed code.
937 * Returns: the root appdomain, to obtain the current domain, use mono_domain_get ()
939 MonoDomain*
940 mono_get_root_domain (void)
942 return mono_root_domain;
946 * mono_domain_get:
948 * This method returns the value of the current \c MonoDomain that this thread
949 * and code are running under. To obtain the root domain use
950 * \c mono_get_root_domain API.
952 * \returns the current domain
954 MonoDomain *
955 mono_domain_get ()
957 return GET_APPDOMAIN ();
960 void
961 mono_domain_unset (void)
963 SET_APPDOMAIN (NULL);
966 void
967 mono_domain_set_internal_with_options (MonoDomain *domain, gboolean migrate_exception)
969 MONO_REQ_GC_UNSAFE_MODE;
970 MonoInternalThread *thread;
972 if (mono_domain_get () == domain)
973 return;
975 SET_APPDOMAIN (domain);
976 SET_APPCONTEXT (domain->default_context);
978 if (migrate_exception) {
979 thread = mono_thread_internal_current ();
980 if (!thread->abort_exc)
981 return;
983 g_assert (thread->abort_exc->object.vtable->domain != domain);
984 MONO_OBJECT_SETREF_INTERNAL (thread, abort_exc, mono_get_exception_thread_abort ());
985 g_assert (thread->abort_exc->object.vtable->domain == domain);
990 * mono_domain_foreach:
991 * \param func function to invoke with the domain data
992 * \param user_data user-defined pointer that is passed to the supplied \p func fo reach domain
994 * Use this method to safely iterate over all the loaded application
995 * domains in the current runtime. The provided \p func is invoked with a
996 * pointer to the \c MonoDomain and is given the value of the \p user_data
997 * parameter which can be used to pass state to your called routine.
999 void
1000 mono_domain_foreach (MonoDomainFunc func, gpointer user_data)
1002 MONO_ENTER_GC_UNSAFE;
1003 int i, size;
1004 MonoDomain **copy;
1007 * Create a copy of the data to avoid calling the user callback
1008 * inside the lock because that could lead to deadlocks.
1009 * We can do this because this function is not perf. critical.
1011 mono_appdomains_lock ();
1012 size = appdomain_list_size;
1013 copy = (MonoDomain **)gc_alloc_fixed_non_heap_list (appdomain_list_size * sizeof (void*));
1014 memcpy (copy, appdomains_list, appdomain_list_size * sizeof (void*));
1015 mono_appdomains_unlock ();
1017 for (i = 0; i < size; ++i) {
1018 if (copy [i])
1019 func (copy [i], user_data);
1022 gc_free_fixed_non_heap_list (copy);
1023 MONO_EXIT_GC_UNSAFE;
1026 void
1027 mono_domain_ensure_entry_assembly (MonoDomain *domain, MonoAssembly *assembly)
1029 if (!mono_runtime_get_no_exec () && !domain->entry_assembly && assembly) {
1030 gchar *str;
1031 ERROR_DECL (error);
1033 domain->entry_assembly = assembly;
1034 /* Domains created from another domain already have application_base and configuration_file set */
1035 if (domain->setup->application_base == NULL) {
1036 MonoString *basedir = mono_string_new_checked (domain, assembly->basedir, error);
1037 mono_error_assert_ok (error);
1038 MONO_OBJECT_SETREF_INTERNAL (domain->setup, application_base, basedir);
1041 if (domain->setup->configuration_file == NULL) {
1042 str = g_strconcat (assembly->image->name, ".config", (const char*)NULL);
1043 MonoString *config_file = mono_string_new_checked (domain, str, error);
1044 mono_error_assert_ok (error);
1045 MONO_OBJECT_SETREF_INTERNAL (domain->setup, configuration_file, config_file);
1046 g_free (str);
1047 mono_domain_set_options_from_config (domain);
1053 * mono_domain_assembly_open:
1054 * \param domain the application domain
1055 * \param name file name of the assembly
1057 MonoAssembly *
1058 mono_domain_assembly_open (MonoDomain *domain, const char *name)
1060 MonoAssembly *result;
1061 MONO_ENTER_GC_UNSAFE;
1062 result = mono_domain_assembly_open_internal (domain, mono_domain_default_alc (domain), name);
1063 MONO_EXIT_GC_UNSAFE;
1064 return result;
1067 // Uses the domain on legacy mono and the ALC on current
1068 // Intended only for loading the main assembly
1069 MonoAssembly *
1070 mono_domain_assembly_open_internal (MonoDomain *domain, MonoAssemblyLoadContext *alc, const char *name)
1072 MonoDomain *current;
1073 MonoAssembly *ass;
1075 MONO_REQ_GC_UNSAFE_MODE;
1077 MonoAssemblyOpenRequest req;
1078 mono_assembly_request_prepare_open (&req, MONO_ASMCTX_DEFAULT, alc);
1079 if (domain != mono_domain_get ()) {
1080 current = mono_domain_get ();
1082 mono_domain_set_fast (domain, FALSE);
1083 ass = mono_assembly_request_open (name, &req, NULL);
1084 mono_domain_set_fast (current, FALSE);
1085 } else {
1086 ass = mono_assembly_request_open (name, &req, NULL);
1089 // On netcore, this is necessary because we check the AppContext.BaseDirectory property as part of the assembly lookup algorithm
1090 // AppContext.BaseDirectory can sometimes fall back to checking the location of the entry_assembly, which should be non-null
1091 #ifdef ENABLE_NETCORE
1092 mono_domain_ensure_entry_assembly (domain, ass);
1093 #endif
1095 return ass;
1098 static void
1099 unregister_vtable_reflection_type (MonoVTable *vtable)
1101 MonoObject *type = (MonoObject *)vtable->type;
1103 if (type->vtable->klass != mono_defaults.runtimetype_class)
1104 MONO_GC_UNREGISTER_ROOT_IF_MOVING (vtable->type);
1108 * mono_domain_free:
1109 * \param domain the domain to release
1110 * \param force if TRUE, it allows the root domain to be released (used at shutdown only).
1112 * This releases the resources associated with the specific domain.
1113 * This is a low-level function that is invoked by the AppDomain infrastructure
1114 * when necessary.
1116 * In theory, this is dead code on netcore and thus does not need to be ALC-aware.
1118 void
1119 mono_domain_free (MonoDomain *domain, gboolean force)
1121 int code_size, code_alloc;
1122 GSList *tmp;
1123 gpointer *p;
1125 if ((domain == mono_root_domain) && !force) {
1126 g_warning ("cant unload root domain");
1127 return;
1130 if (mono_dont_free_domains)
1131 return;
1133 MONO_PROFILER_RAISE (domain_unloading, (domain));
1135 mono_debug_domain_unload (domain);
1137 /* must do this early as it accesses fields and types */
1138 if (domain->special_static_fields) {
1139 mono_alloc_special_static_data_free (domain->special_static_fields);
1140 g_hash_table_destroy (domain->special_static_fields);
1141 domain->special_static_fields = NULL;
1145 * We must destroy all these hash tables here because they
1146 * contain references to managed objects belonging to the
1147 * domain. Once we let the GC clear the domain there must be
1148 * no more such references, or we'll crash if a collection
1149 * occurs.
1151 mono_g_hash_table_destroy (domain->ldstr_table);
1152 domain->ldstr_table = NULL;
1154 mono_g_hash_table_destroy (domain->env);
1155 domain->env = NULL;
1157 mono_reflection_cleanup_domain (domain);
1159 /* This must be done before type_hash is freed */
1160 if (domain->class_vtable_array) {
1161 int i;
1162 for (i = 0; i < domain->class_vtable_array->len; ++i)
1163 unregister_vtable_reflection_type ((MonoVTable *)g_ptr_array_index (domain->class_vtable_array, i));
1166 if (domain->type_hash) {
1167 mono_g_hash_table_destroy (domain->type_hash);
1168 domain->type_hash = NULL;
1170 if (domain->type_init_exception_hash) {
1171 mono_g_hash_table_destroy (domain->type_init_exception_hash);
1172 domain->type_init_exception_hash = NULL;
1175 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
1176 MonoAssembly *ass = (MonoAssembly *)tmp->data;
1177 mono_assembly_release_gc_roots (ass);
1180 /* Have to zero out reference fields since they will be invalidated by the clear_domain () call below */
1181 for (p = (gpointer*)&domain->MONO_DOMAIN_FIRST_OBJECT; p < (gpointer*)&domain->MONO_DOMAIN_FIRST_GC_TRACKED; ++p)
1182 *p = NULL;
1184 /* This needs to be done before closing assemblies */
1185 mono_gc_clear_domain (domain);
1187 /* Close dynamic assemblies first, since they have no ref count */
1188 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
1189 MonoAssembly *ass = (MonoAssembly *)tmp->data;
1190 if (!ass->image || !image_is_dynamic (ass->image))
1191 continue;
1192 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_ASSEMBLY, "Unloading domain %s[%p], assembly %s[%p], ref_count=%d", domain->friendly_name, domain, ass->aname.name, ass, ass->ref_count);
1193 if (!mono_assembly_close_except_image_pools (ass))
1194 tmp->data = NULL;
1197 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
1198 MonoAssembly *ass = (MonoAssembly *)tmp->data;
1199 if (!ass)
1200 continue;
1201 if (!ass->image || image_is_dynamic (ass->image))
1202 continue;
1203 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_ASSEMBLY, "Unloading domain %s[%p], assembly %s[%p], ref_count=%d", domain->friendly_name, domain, ass->aname.name, ass, ass->ref_count);
1204 if (!mono_assembly_close_except_image_pools (ass))
1205 tmp->data = NULL;
1208 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
1209 MonoAssembly *ass = (MonoAssembly *)tmp->data;
1210 if (ass)
1211 mono_assembly_close_finish (ass);
1213 g_slist_free (domain->domain_assemblies);
1214 domain->domain_assemblies = NULL;
1217 * Send this after the assemblies have been unloaded and the domain is still in a
1218 * usable state.
1220 MONO_PROFILER_RAISE (domain_unloaded, (domain));
1222 if (free_domain_hook)
1223 free_domain_hook (domain);
1225 /* FIXME: free delegate_hash_table when it's used */
1226 if (domain->search_path) {
1227 g_strfreev (domain->search_path);
1228 domain->search_path = NULL;
1230 domain->create_proxy_for_type_method = NULL;
1231 domain->private_invoke_method = NULL;
1232 domain->default_context = NULL;
1233 domain->out_of_memory_ex = NULL;
1234 domain->null_reference_ex = NULL;
1235 domain->stack_overflow_ex = NULL;
1236 domain->ephemeron_tombstone = NULL;
1237 domain->entry_assembly = NULL;
1239 g_free (domain->friendly_name);
1240 domain->friendly_name = NULL;
1241 g_ptr_array_free (domain->class_vtable_array, TRUE);
1242 domain->class_vtable_array = NULL;
1243 g_hash_table_destroy (domain->proxy_vtable_hash);
1244 domain->proxy_vtable_hash = NULL;
1245 mono_internal_hash_table_destroy (&domain->jit_code_hash);
1248 * There might still be jit info tables of this domain which
1249 * are not freed. Since the domain cannot be in use anymore,
1250 * this will free them.
1252 mono_thread_hazardous_try_free_all ();
1253 if (domain->aot_modules)
1254 mono_jit_info_table_free (domain->aot_modules);
1255 g_assert (domain->num_jit_info_table_duplicates == 0);
1256 mono_jit_info_table_free (domain->jit_info_table);
1257 domain->jit_info_table = NULL;
1258 g_assert (!domain->jit_info_free_queue);
1260 /* collect statistics */
1261 code_alloc = mono_code_manager_size (domain->code_mp, &code_size);
1262 total_domain_code_alloc += code_alloc;
1263 max_domain_code_alloc = MAX (max_domain_code_alloc, code_alloc);
1264 max_domain_code_size = MAX (max_domain_code_size, code_size);
1266 if (debug_domain_unload) {
1267 mono_mempool_invalidate (domain->mp);
1268 mono_code_manager_invalidate (domain->code_mp);
1269 } else {
1270 #ifndef DISABLE_PERFCOUNTERS
1271 /* FIXME: use an explicit subtraction method as soon as it's available */
1272 mono_atomic_fetch_add_i32 (&mono_perfcounters->loader_bytes, -1 * mono_mempool_get_allocated (domain->mp));
1273 #endif
1274 mono_mempool_destroy (domain->mp);
1275 domain->mp = NULL;
1276 mono_code_manager_destroy (domain->code_mp);
1277 domain->code_mp = NULL;
1279 lock_free_mempool_free (domain->lock_free_mp);
1280 domain->lock_free_mp = NULL;
1282 g_hash_table_destroy (domain->finalizable_objects_hash);
1283 domain->finalizable_objects_hash = NULL;
1284 if (domain->generic_virtual_cases) {
1285 g_hash_table_destroy (domain->generic_virtual_cases);
1286 domain->generic_virtual_cases = NULL;
1288 if (domain->ftnptrs_hash) {
1289 g_hash_table_destroy (domain->ftnptrs_hash);
1290 domain->ftnptrs_hash = NULL;
1292 if (domain->method_to_dyn_method) {
1293 g_hash_table_destroy (domain->method_to_dyn_method);
1294 domain->method_to_dyn_method = NULL;
1297 mono_domain_alcs_destroy (domain);
1299 #ifdef ENABLE_NETCORE
1300 mono_coop_mutex_destroy (&domain->alcs_lock);
1301 #endif
1303 mono_os_mutex_destroy (&domain->finalizable_objects_hash_lock);
1304 mono_coop_mutex_destroy (&domain->assemblies_lock);
1305 mono_os_mutex_destroy (&domain->jit_code_hash_lock);
1307 mono_coop_mutex_destroy (&domain->lock);
1309 domain->setup = NULL;
1311 if (mono_gc_is_moving ())
1312 mono_gc_deregister_root ((char*)&(domain->MONO_DOMAIN_FIRST_GC_TRACKED));
1314 mono_appdomains_lock ();
1315 appdomains_list [domain->domain_id] = NULL;
1316 mono_appdomains_unlock ();
1318 mono_gc_free_fixed (domain);
1320 #ifndef DISABLE_PERFCOUNTERS
1321 mono_atomic_dec_i32 (&mono_perfcounters->loader_appdomains);
1322 #endif
1324 if (domain == mono_root_domain)
1325 mono_root_domain = NULL;
1329 * mono_domain_get_by_id:
1330 * \param domainid the ID
1331 * \returns the domain for a specific domain id.
1333 MonoDomain *
1334 mono_domain_get_by_id (gint32 domainid)
1336 MonoDomain * domain;
1338 MONO_ENTER_GC_UNSAFE;
1339 mono_appdomains_lock ();
1340 if (domainid < appdomain_list_size)
1341 domain = appdomains_list [domainid];
1342 else
1343 domain = NULL;
1344 mono_appdomains_unlock ();
1345 MONO_EXIT_GC_UNSAFE;
1346 return domain;
1350 * mono_domain_get_id:
1352 * A domain ID is guaranteed to be unique for as long as the domain
1353 * using it is alive. It may be reused later once the domain has been
1354 * unloaded.
1356 * \returns The unique ID for \p domain.
1358 gint32
1359 mono_domain_get_id (MonoDomain *domain)
1361 return domain->domain_id;
1365 * mono_domain_get_friendly_name:
1367 * The returned string's lifetime is the same as \p domain's. Consider
1368 * copying it if you need to store it somewhere.
1370 * \returns The friendly name of \p domain. Can be NULL if not yet set.
1372 const char *
1373 mono_domain_get_friendly_name (MonoDomain *domain)
1375 return domain->friendly_name;
1379 * mono_domain_alloc:
1381 * LOCKING: Acquires the domain lock.
1383 gpointer
1384 (mono_domain_alloc) (MonoDomain *domain, guint size)
1386 gpointer res;
1388 mono_domain_lock (domain);
1389 #ifndef DISABLE_PERFCOUNTERS
1390 mono_atomic_fetch_add_i32 (&mono_perfcounters->loader_bytes, size);
1391 #endif
1392 res = mono_mempool_alloc (domain->mp, size);
1393 mono_domain_unlock (domain);
1395 return res;
1399 * mono_domain_alloc0:
1401 * LOCKING: Acquires the domain lock.
1403 gpointer
1404 (mono_domain_alloc0) (MonoDomain *domain, guint size)
1406 gpointer res;
1408 mono_domain_lock (domain);
1409 #ifndef DISABLE_PERFCOUNTERS
1410 mono_atomic_fetch_add_i32 (&mono_perfcounters->loader_bytes, size);
1411 #endif
1412 res = mono_mempool_alloc0 (domain->mp, size);
1413 mono_domain_unlock (domain);
1415 return res;
1418 gpointer
1419 (mono_domain_alloc0_lock_free) (MonoDomain *domain, guint size)
1421 return lock_free_mempool_alloc0 (domain->lock_free_mp, size);
1425 * mono_domain_code_reserve:
1427 * LOCKING: Acquires the domain lock.
1429 void*
1430 (mono_domain_code_reserve) (MonoDomain *domain, int size)
1432 gpointer res;
1434 mono_domain_lock (domain);
1435 res = mono_code_manager_reserve (domain->code_mp, size);
1436 mono_domain_unlock (domain);
1438 return res;
1442 * mono_domain_code_reserve_align:
1444 * LOCKING: Acquires the domain lock.
1446 void*
1447 (mono_domain_code_reserve_align) (MonoDomain *domain, int size, int alignment)
1449 gpointer res;
1451 mono_domain_lock (domain);
1452 res = mono_code_manager_reserve_align (domain->code_mp, size, alignment);
1453 mono_domain_unlock (domain);
1455 return res;
1459 * mono_domain_code_commit:
1461 * LOCKING: Acquires the domain lock.
1463 void
1464 mono_domain_code_commit (MonoDomain *domain, void *data, int size, int newsize)
1466 mono_domain_lock (domain);
1467 mono_code_manager_commit (domain->code_mp, data, size, newsize);
1468 mono_domain_unlock (domain);
1472 * mono_domain_code_foreach:
1473 * Iterate over the code thunks of the code manager of @domain.
1475 * The @func callback MUST not take any locks. If it really needs to, it must respect
1476 * the locking rules of the runtime: http://www.mono-project.com/Mono:Runtime:Documentation:ThreadSafety
1477 * LOCKING: Acquires the domain lock.
1480 void
1481 mono_domain_code_foreach (MonoDomain *domain, MonoCodeManagerFunc func, void *user_data)
1483 mono_domain_lock (domain);
1484 mono_code_manager_foreach (domain->code_mp, func, user_data);
1485 mono_domain_unlock (domain);
1489 * mono_context_set:
1491 void
1492 mono_context_set (MonoAppContext * new_context)
1494 SET_APPCONTEXT (new_context);
1497 void
1498 mono_context_set_handle (MonoAppContextHandle new_context)
1500 SET_APPCONTEXT (MONO_HANDLE_RAW (new_context));
1504 * mono_context_get:
1506 * Returns: the current Mono Application Context.
1508 MonoAppContext *
1509 mono_context_get (void)
1511 return GET_APPCONTEXT ();
1515 * mono_context_get_handle:
1517 * Returns: the current Mono Application Context.
1519 MonoAppContextHandle
1520 mono_context_get_handle (void)
1522 return MONO_HANDLE_NEW (MonoAppContext, GET_APPCONTEXT ());
1526 * mono_context_get_id:
1527 * \param context the context to operate on.
1529 * Context IDs are guaranteed to be unique for the duration of a Mono
1530 * process; they are never reused.
1532 * \returns The unique ID for \p context.
1534 gint32
1535 mono_context_get_id (MonoAppContext *context)
1537 return context->context_id;
1541 * mono_context_get_domain_id:
1542 * \param context the context to operate on.
1543 * \returns The ID of the domain that \p context was created in.
1545 gint32
1546 mono_context_get_domain_id (MonoAppContext *context)
1548 return context->domain_id;
1552 * mono_get_corlib:
1553 * Use this function to get the \c MonoImage* for the \c mscorlib.dll assembly
1554 * \returns The \c MonoImage for mscorlib.dll
1556 MonoImage*
1557 mono_get_corlib (void)
1559 return mono_defaults.corlib;
1563 * mono_get_object_class:
1564 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Object .
1565 * \returns The \c MonoClass* for the \c System.Object type.
1567 MonoClass*
1568 mono_get_object_class (void)
1570 return mono_defaults.object_class;
1574 * mono_get_byte_class:
1575 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Byte .
1576 * \returns The \c MonoClass* for the \c System.Byte type.
1578 MonoClass*
1579 mono_get_byte_class (void)
1581 return mono_defaults.byte_class;
1585 * mono_get_void_class:
1586 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Void .
1587 * \returns The \c MonoClass* for the \c System.Void type.
1589 MonoClass*
1590 mono_get_void_class (void)
1592 return mono_defaults.void_class;
1596 * mono_get_boolean_class:
1597 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Boolean .
1598 * \returns The \c MonoClass* for the \c System.Boolean type.
1600 MonoClass*
1601 mono_get_boolean_class (void)
1603 return mono_defaults.boolean_class;
1607 * mono_get_sbyte_class:
1608 * Use this function to get the \c MonoClass* that the runtime is using for \c System.SByte.
1609 * \returns The \c MonoClass* for the \c System.SByte type.
1611 MonoClass*
1612 mono_get_sbyte_class (void)
1614 return mono_defaults.sbyte_class;
1618 * mono_get_int16_class:
1619 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Int16 .
1620 * \returns The \c MonoClass* for the \c System.Int16 type.
1622 MonoClass*
1623 mono_get_int16_class (void)
1625 return mono_defaults.int16_class;
1629 * mono_get_uint16_class:
1630 * Use this function to get the \c MonoClass* that the runtime is using for \c System.UInt16 .
1631 * \returns The \c MonoClass* for the \c System.UInt16 type.
1633 MonoClass*
1634 mono_get_uint16_class (void)
1636 return mono_defaults.uint16_class;
1640 * mono_get_int32_class:
1641 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Int32 .
1642 * \returns The \c MonoClass* for the \c System.Int32 type.
1644 MonoClass*
1645 mono_get_int32_class (void)
1647 return mono_defaults.int32_class;
1651 * mono_get_uint32_class:
1652 * Use this function to get the \c MonoClass* that the runtime is using for \c System.UInt32 .
1653 * \returns The \c MonoClass* for the \c System.UInt32 type.
1655 MonoClass*
1656 mono_get_uint32_class (void)
1658 return mono_defaults.uint32_class;
1662 * mono_get_intptr_class:
1663 * Use this function to get the \c MonoClass* that the runtime is using for \c System.IntPtr .
1664 * \returns The \c MonoClass* for the \c System.IntPtr type.
1666 MonoClass*
1667 mono_get_intptr_class (void)
1669 return mono_defaults.int_class;
1673 * mono_get_uintptr_class:
1674 * Use this function to get the \c MonoClass* that the runtime is using for \c System.UIntPtr .
1675 * \returns The \c MonoClass* for the \c System.UIntPtr type.
1677 MonoClass*
1678 mono_get_uintptr_class (void)
1680 return mono_defaults.uint_class;
1684 * mono_get_int64_class:
1685 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Int64 .
1686 * \returns The \c MonoClass* for the \c System.Int64 type.
1688 MonoClass*
1689 mono_get_int64_class (void)
1691 return mono_defaults.int64_class;
1695 * mono_get_uint64_class:
1696 * Use this function to get the \c MonoClass* that the runtime is using for \c System.UInt64 .
1697 * \returns The \c MonoClass* for the \c System.UInt64 type.
1699 MonoClass*
1700 mono_get_uint64_class (void)
1702 return mono_defaults.uint64_class;
1706 * mono_get_single_class:
1707 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Single (32-bit floating points).
1708 * \returns The \c MonoClass* for the \c System.Single type.
1710 MonoClass*
1711 mono_get_single_class (void)
1713 return mono_defaults.single_class;
1717 * mono_get_double_class:
1718 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Double (64-bit floating points).
1719 * \returns The \c MonoClass* for the \c System.Double type.
1721 MonoClass*
1722 mono_get_double_class (void)
1724 return mono_defaults.double_class;
1728 * mono_get_char_class:
1729 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Char .
1730 * \returns The \c MonoClass* for the \c System.Char type.
1732 MonoClass*
1733 mono_get_char_class (void)
1735 return mono_defaults.char_class;
1739 * mono_get_string_class:
1740 * Use this function to get the \c MonoClass* that the runtime is using for \c System.String .
1741 * \returns The \c MonoClass* for the \c System.String type.
1743 MonoClass*
1744 mono_get_string_class (void)
1746 return mono_defaults.string_class;
1750 * mono_get_enum_class:
1751 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Enum .
1752 * \returns The \c MonoClass* for the \c System.Enum type.
1754 MonoClass*
1755 mono_get_enum_class (void)
1757 return mono_defaults.enum_class;
1761 * mono_get_array_class:
1762 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Array .
1763 * \returns The \c MonoClass* for the \c System.Array type.
1765 MonoClass*
1766 mono_get_array_class (void)
1768 return mono_defaults.array_class;
1772 * mono_get_thread_class:
1773 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Threading.Thread .
1774 * \returns The \c MonoClass* for the \c System.Threading.Thread type.
1776 MonoClass*
1777 mono_get_thread_class (void)
1779 return mono_defaults.thread_class;
1783 * mono_get_exception_class:
1784 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Exception .
1785 * \returns The \c MonoClass* for the \c type.
1787 MonoClass*
1788 mono_get_exception_class (void)
1790 return mono_defaults.exception_class;
1794 static char* get_attribute_value (const gchar **attribute_names,
1795 const gchar **attribute_values,
1796 const char *att_name)
1798 int n;
1799 for (n=0; attribute_names[n] != NULL; n++) {
1800 if (strcmp (attribute_names[n], att_name) == 0)
1801 return g_strdup (attribute_values[n]);
1803 return NULL;
1806 static void start_element (GMarkupParseContext *context,
1807 const gchar *element_name,
1808 const gchar **attribute_names,
1809 const gchar **attribute_values,
1810 gpointer user_data,
1811 GError **gerror)
1813 AppConfigInfo* app_config = (AppConfigInfo*) user_data;
1815 if (strcmp (element_name, "configuration") == 0) {
1816 app_config->configuration_count++;
1817 return;
1819 if (strcmp (element_name, "startup") == 0) {
1820 app_config->startup_count++;
1821 return;
1824 if (app_config->configuration_count != 1 || app_config->startup_count != 1)
1825 return;
1827 if (strcmp (element_name, "requiredRuntime") == 0) {
1828 app_config->required_runtime = get_attribute_value (attribute_names, attribute_values, "version");
1829 } else if (strcmp (element_name, "supportedRuntime") == 0) {
1830 char *version = get_attribute_value (attribute_names, attribute_values, "version");
1831 app_config->supported_runtimes = g_slist_append (app_config->supported_runtimes, version);
1835 static void end_element (GMarkupParseContext *context,
1836 const gchar *element_name,
1837 gpointer user_data,
1838 GError **gerror)
1840 AppConfigInfo* app_config = (AppConfigInfo*) user_data;
1842 if (strcmp (element_name, "configuration") == 0) {
1843 app_config->configuration_count--;
1844 } else if (strcmp (element_name, "startup") == 0) {
1845 app_config->startup_count--;
1849 static const GMarkupParser
1850 mono_parser = {
1851 start_element,
1852 end_element,
1853 NULL,
1854 NULL,
1855 NULL
1858 static AppConfigInfo *
1859 app_config_parse (const char *exe_filename)
1861 AppConfigInfo *app_config;
1862 GMarkupParseContext *context;
1863 char *text;
1864 gsize len;
1865 const char *bundled_config;
1866 char *config_filename;
1868 bundled_config = mono_config_string_for_assembly_file (exe_filename);
1870 if (bundled_config) {
1871 text = g_strdup (bundled_config);
1872 len = strlen (text);
1873 } else {
1874 config_filename = g_strconcat (exe_filename, ".config", (const char*)NULL);
1876 if (!g_file_get_contents (config_filename, &text, &len, NULL)) {
1877 g_free (config_filename);
1878 return NULL;
1880 g_free (config_filename);
1883 app_config = g_new0 (AppConfigInfo, 1);
1885 context = g_markup_parse_context_new (&mono_parser, (GMarkupParseFlags)0, app_config, NULL);
1886 if (g_markup_parse_context_parse (context, text, len, NULL)) {
1887 g_markup_parse_context_end_parse (context, NULL);
1889 g_markup_parse_context_free (context);
1890 g_free (text);
1891 return app_config;
1894 static void
1895 app_config_free (AppConfigInfo* app_config)
1897 char *rt;
1898 GSList *list = app_config->supported_runtimes;
1899 while (list != NULL) {
1900 rt = (char*)list->data;
1901 g_free (rt);
1902 list = g_slist_next (list);
1904 g_slist_free (app_config->supported_runtimes);
1905 g_free (app_config->required_runtime);
1906 g_free (app_config);
1910 static const MonoRuntimeInfo*
1911 get_runtime_by_version (const char *version)
1913 int n;
1914 int max = G_N_ELEMENTS (supported_runtimes);
1915 int vlen;
1917 if (!version)
1918 return NULL;
1920 for (n=0; n<max; n++) {
1921 if (strcmp (version, supported_runtimes[n].runtime_version) == 0)
1922 return &supported_runtimes[n];
1925 vlen = strlen (version);
1926 if (vlen >= 4 && version [1] - '0' >= 4) {
1927 for (n=0; n<max; n++) {
1928 if (strncmp (version, supported_runtimes[n].runtime_version, 4) == 0)
1929 return &supported_runtimes[n];
1933 return NULL;
1936 static GSList*
1937 get_runtimes_from_exe (const char *file, MonoImage **out_image)
1939 AppConfigInfo* app_config;
1940 char *version;
1941 const MonoRuntimeInfo* runtime = NULL;
1942 MonoImage *image = NULL;
1943 GSList *runtimes = NULL;
1945 app_config = app_config_parse (file);
1947 if (app_config != NULL) {
1948 /* Check supportedRuntime elements, if none is supported, fail.
1949 * If there are no such elements, look for a requiredRuntime element.
1951 if (app_config->supported_runtimes != NULL) {
1952 GSList *list = app_config->supported_runtimes;
1953 while (list != NULL) {
1954 version = (char*) list->data;
1955 runtime = get_runtime_by_version (version);
1956 if (runtime != NULL)
1957 runtimes = g_slist_prepend (runtimes, (gpointer)runtime);
1958 list = g_slist_next (list);
1960 runtimes = g_slist_reverse (runtimes);
1961 app_config_free (app_config);
1962 return runtimes;
1965 /* Check the requiredRuntime element. This is for 1.0 apps only. */
1966 if (app_config->required_runtime != NULL) {
1967 const MonoRuntimeInfo* runtime = get_runtime_by_version (app_config->required_runtime);
1968 if (runtime != NULL)
1969 runtimes = g_slist_prepend (runtimes, (gpointer)runtime);
1970 app_config_free (app_config);
1971 return runtimes;
1973 app_config_free (app_config);
1976 /* Look for a runtime with the exact version */
1977 image = mono_assembly_open_from_bundle (mono_domain_default_alc (mono_domain_get ()), file, NULL, FALSE);
1979 if (image == NULL)
1980 image = mono_image_open (file, NULL);
1982 if (image == NULL) {
1983 /* The image is wrong or the file was not found. In this case return
1984 * a default runtime and leave to the initialization method the work of
1985 * reporting the error.
1987 runtime = get_runtime_by_version (DEFAULT_RUNTIME_VERSION);
1988 runtimes = g_slist_prepend (runtimes, (gpointer)runtime);
1989 return runtimes;
1992 *out_image = image;
1994 runtime = get_runtime_by_version (image->version);
1995 if (runtime != NULL)
1996 runtimes = g_slist_prepend (runtimes, (gpointer)runtime);
1997 return runtimes;
2002 * mono_get_runtime_info:
2004 * Returns: the version of the current runtime instance.
2006 const MonoRuntimeInfo*
2007 mono_get_runtime_info (void)
2009 return current_runtime;
2013 * mono_framework_version:
2015 * Return the major version of the framework curently executing.
2018 mono_framework_version (void)
2020 return current_runtime->framework_version [0] - '0';
2023 void
2024 mono_enable_debug_domain_unload (gboolean enable)
2026 debug_domain_unload = enable;
2029 MonoAotCacheConfig *
2030 mono_get_aot_cache_config (void)
2032 return &aot_cache_config;
2035 void
2036 mono_domain_lock (MonoDomain *domain)
2038 mono_locks_coop_acquire (&domain->lock, DomainLock);
2041 void
2042 mono_domain_unlock (MonoDomain *domain)
2044 mono_locks_coop_release (&domain->lock, DomainLock);
2047 GPtrArray*
2048 mono_domain_get_assemblies (MonoDomain *domain, gboolean refonly)
2050 GSList *tmp;
2051 GPtrArray *assemblies;
2052 MonoAssembly *ass;
2054 assemblies = g_ptr_array_new ();
2055 mono_domain_assemblies_lock (domain);
2056 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
2057 ass = (MonoAssembly *)tmp->data;
2058 gboolean ass_ref_only = mono_asmctx_get_kind (&ass->context) == MONO_ASMCTX_REFONLY;
2059 if (refonly != ass_ref_only)
2060 continue;
2061 if (ass->corlib_internal)
2062 continue;
2063 g_ptr_array_add (assemblies, ass);
2065 mono_domain_assemblies_unlock (domain);
2066 return assemblies;
2069 MonoAssemblyLoadContext *
2070 mono_domain_default_alc (MonoDomain *domain)
2072 #ifndef ENABLE_NETCORE
2073 return NULL;
2074 #else
2075 return domain->default_alc;
2076 #endif
2079 #ifdef ENABLE_NETCORE
2080 static inline void
2081 mono_domain_alcs_lock (MonoDomain *domain)
2083 mono_coop_mutex_lock (&domain->alcs_lock);
2086 static inline void
2087 mono_domain_alcs_unlock (MonoDomain *domain)
2089 mono_coop_mutex_unlock (&domain->alcs_lock);
2091 #endif
2094 #ifdef ENABLE_NETCORE
2095 static MonoAssemblyLoadContext *
2096 create_alc (MonoDomain *domain, gboolean is_default)
2098 MonoAssemblyLoadContext *alc = NULL;
2100 mono_domain_alcs_lock (domain);
2101 if (is_default && domain->default_alc)
2102 goto leave;
2104 alc = g_new0 (MonoAssemblyLoadContext, 1);
2105 mono_alc_init (alc, domain);
2107 domain->alcs = g_slist_prepend (domain->alcs, alc);
2108 if (is_default)
2109 domain->default_alc = alc;
2110 leave:
2111 mono_domain_alcs_unlock (domain);
2112 return alc;
2114 #endif
2116 #ifdef ENABLE_NETCORE
2117 void
2118 mono_domain_create_default_alc (MonoDomain *domain)
2120 if (domain->default_alc)
2121 return;
2122 create_alc (domain, TRUE);
2125 MonoAssemblyLoadContext *
2126 mono_domain_create_individual_alc (MonoDomain *domain, uint32_t this_gchandle, gboolean collectible, MonoError *error)
2128 g_assert (!collectible); /* TODO: implement collectible ALCs */
2129 MonoAssemblyLoadContext *alc = create_alc (domain, FALSE);
2130 alc->gchandle = this_gchandle;
2131 return alc;
2134 static void
2135 mono_alc_free (MonoAssemblyLoadContext *alc)
2137 mono_alc_cleanup (alc);
2138 g_free (alc);
2140 #endif
2142 void
2143 mono_domain_alcs_destroy (MonoDomain *domain)
2145 #ifdef ENABLE_NETCORE
2146 mono_domain_alcs_lock (domain);
2147 GSList *alcs = domain->alcs;
2148 domain->alcs = NULL;
2149 domain->default_alc = NULL;
2150 mono_domain_alcs_unlock (domain);
2152 for (GSList *iter = alcs; iter; iter = g_slist_next (iter)) {
2153 mono_alc_free ((MonoAssemblyLoadContext*)iter->data);
2155 #endif