[2020-02] Fix leak in assembly-specific dllmap lookups (#21053)
[mono-project.git] / mono / metadata / domain.c
blob98214f13a6128951a5863b26a1ed83dd6a2e44dc
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_os_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 /* FIXME: maybe we should integrate this with mono_assembly_open? */
1028 * mono_domain_assembly_open:
1029 * \param domain the application domain
1030 * \param name file name of the assembly
1032 MonoAssembly *
1033 mono_domain_assembly_open (MonoDomain *domain, const char *name)
1035 MonoAssembly *result;
1036 MONO_ENTER_GC_UNSAFE;
1037 result = mono_domain_assembly_open_internal (domain, mono_domain_default_alc (domain), name);
1038 MONO_EXIT_GC_UNSAFE;
1039 return result;
1042 // Uses the domain on legacy mono and the ALC on current
1043 MonoAssembly *
1044 mono_domain_assembly_open_internal (MonoDomain *domain, MonoAssemblyLoadContext *alc, const char *name)
1046 MonoDomain *current;
1047 MonoAssembly *ass;
1048 GSList *tmp;
1050 MONO_REQ_GC_UNSAFE_MODE;
1052 #ifdef ENABLE_NETCORE
1053 mono_alc_assemblies_lock (alc);
1054 for (tmp = alc->loaded_assemblies; tmp; tmp = tmp->next) {
1055 ass = (MonoAssembly *)tmp->data;
1056 if (strcmp (name, ass->aname.name) == 0) {
1057 mono_alc_assemblies_unlock (alc);
1058 return ass;
1061 mono_alc_assemblies_unlock (alc);
1062 #else
1063 mono_domain_assemblies_lock (domain);
1064 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
1065 ass = (MonoAssembly *)tmp->data;
1066 if (strcmp (name, ass->aname.name) == 0) {
1067 mono_domain_assemblies_unlock (domain);
1068 return ass;
1071 mono_domain_assemblies_unlock (domain);
1072 #endif
1074 MonoAssemblyOpenRequest req;
1075 mono_assembly_request_prepare_open (&req, MONO_ASMCTX_DEFAULT, alc);
1076 if (domain != mono_domain_get ()) {
1077 current = mono_domain_get ();
1079 mono_domain_set_fast (domain, FALSE);
1080 ass = mono_assembly_request_open (name, &req, NULL);
1081 mono_domain_set_fast (current, FALSE);
1082 } else {
1083 ass = mono_assembly_request_open (name, &req, NULL);
1086 return ass;
1089 static void
1090 unregister_vtable_reflection_type (MonoVTable *vtable)
1092 MonoObject *type = (MonoObject *)vtable->type;
1094 if (type->vtable->klass != mono_defaults.runtimetype_class)
1095 MONO_GC_UNREGISTER_ROOT_IF_MOVING (vtable->type);
1099 * mono_domain_free:
1100 * \param domain the domain to release
1101 * \param force if TRUE, it allows the root domain to be released (used at shutdown only).
1103 * This releases the resources associated with the specific domain.
1104 * This is a low-level function that is invoked by the AppDomain infrastructure
1105 * when necessary.
1107 * In theory, this is dead code on netcore and thus does not need to be ALC-aware.
1109 void
1110 mono_domain_free (MonoDomain *domain, gboolean force)
1112 int code_size, code_alloc;
1113 GSList *tmp;
1114 gpointer *p;
1116 if ((domain == mono_root_domain) && !force) {
1117 g_warning ("cant unload root domain");
1118 return;
1121 if (mono_dont_free_domains)
1122 return;
1124 MONO_PROFILER_RAISE (domain_unloading, (domain));
1126 mono_debug_domain_unload (domain);
1128 /* must do this early as it accesses fields and types */
1129 if (domain->special_static_fields) {
1130 mono_alloc_special_static_data_free (domain->special_static_fields);
1131 g_hash_table_destroy (domain->special_static_fields);
1132 domain->special_static_fields = NULL;
1136 * We must destroy all these hash tables here because they
1137 * contain references to managed objects belonging to the
1138 * domain. Once we let the GC clear the domain there must be
1139 * no more such references, or we'll crash if a collection
1140 * occurs.
1142 mono_g_hash_table_destroy (domain->ldstr_table);
1143 domain->ldstr_table = NULL;
1145 mono_g_hash_table_destroy (domain->env);
1146 domain->env = NULL;
1148 mono_reflection_cleanup_domain (domain);
1150 /* This must be done before type_hash is freed */
1151 if (domain->class_vtable_array) {
1152 int i;
1153 for (i = 0; i < domain->class_vtable_array->len; ++i)
1154 unregister_vtable_reflection_type ((MonoVTable *)g_ptr_array_index (domain->class_vtable_array, i));
1157 if (domain->type_hash) {
1158 mono_g_hash_table_destroy (domain->type_hash);
1159 domain->type_hash = NULL;
1161 if (domain->type_init_exception_hash) {
1162 mono_g_hash_table_destroy (domain->type_init_exception_hash);
1163 domain->type_init_exception_hash = NULL;
1166 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
1167 MonoAssembly *ass = (MonoAssembly *)tmp->data;
1168 mono_assembly_release_gc_roots (ass);
1171 /* Have to zero out reference fields since they will be invalidated by the clear_domain () call below */
1172 for (p = (gpointer*)&domain->MONO_DOMAIN_FIRST_OBJECT; p < (gpointer*)&domain->MONO_DOMAIN_FIRST_GC_TRACKED; ++p)
1173 *p = NULL;
1175 /* This needs to be done before closing assemblies */
1176 mono_gc_clear_domain (domain);
1178 /* Close dynamic assemblies first, since they have no ref count */
1179 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
1180 MonoAssembly *ass = (MonoAssembly *)tmp->data;
1181 if (!ass->image || !image_is_dynamic (ass->image))
1182 continue;
1183 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);
1184 if (!mono_assembly_close_except_image_pools (ass))
1185 tmp->data = NULL;
1188 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
1189 MonoAssembly *ass = (MonoAssembly *)tmp->data;
1190 if (!ass)
1191 continue;
1192 if (!ass->image || image_is_dynamic (ass->image))
1193 continue;
1194 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);
1195 if (!mono_assembly_close_except_image_pools (ass))
1196 tmp->data = NULL;
1199 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
1200 MonoAssembly *ass = (MonoAssembly *)tmp->data;
1201 if (ass)
1202 mono_assembly_close_finish (ass);
1204 g_slist_free (domain->domain_assemblies);
1205 domain->domain_assemblies = NULL;
1208 * Send this after the assemblies have been unloaded and the domain is still in a
1209 * usable state.
1211 MONO_PROFILER_RAISE (domain_unloaded, (domain));
1213 if (free_domain_hook)
1214 free_domain_hook (domain);
1216 /* FIXME: free delegate_hash_table when it's used */
1217 if (domain->search_path) {
1218 g_strfreev (domain->search_path);
1219 domain->search_path = NULL;
1221 domain->create_proxy_for_type_method = NULL;
1222 domain->private_invoke_method = NULL;
1223 domain->default_context = NULL;
1224 domain->out_of_memory_ex = NULL;
1225 domain->null_reference_ex = NULL;
1226 domain->stack_overflow_ex = NULL;
1227 domain->ephemeron_tombstone = NULL;
1228 domain->entry_assembly = NULL;
1230 g_free (domain->friendly_name);
1231 domain->friendly_name = NULL;
1232 g_ptr_array_free (domain->class_vtable_array, TRUE);
1233 domain->class_vtable_array = NULL;
1234 g_hash_table_destroy (domain->proxy_vtable_hash);
1235 domain->proxy_vtable_hash = NULL;
1236 mono_internal_hash_table_destroy (&domain->jit_code_hash);
1239 * There might still be jit info tables of this domain which
1240 * are not freed. Since the domain cannot be in use anymore,
1241 * this will free them.
1243 mono_thread_hazardous_try_free_all ();
1244 if (domain->aot_modules)
1245 mono_jit_info_table_free (domain->aot_modules);
1246 g_assert (domain->num_jit_info_table_duplicates == 0);
1247 mono_jit_info_table_free (domain->jit_info_table);
1248 domain->jit_info_table = NULL;
1249 g_assert (!domain->jit_info_free_queue);
1251 /* collect statistics */
1252 code_alloc = mono_code_manager_size (domain->code_mp, &code_size);
1253 total_domain_code_alloc += code_alloc;
1254 max_domain_code_alloc = MAX (max_domain_code_alloc, code_alloc);
1255 max_domain_code_size = MAX (max_domain_code_size, code_size);
1257 if (debug_domain_unload) {
1258 mono_mempool_invalidate (domain->mp);
1259 mono_code_manager_invalidate (domain->code_mp);
1260 } else {
1261 #ifndef DISABLE_PERFCOUNTERS
1262 /* FIXME: use an explicit subtraction method as soon as it's available */
1263 mono_atomic_fetch_add_i32 (&mono_perfcounters->loader_bytes, -1 * mono_mempool_get_allocated (domain->mp));
1264 #endif
1265 mono_mempool_destroy (domain->mp);
1266 domain->mp = NULL;
1267 mono_code_manager_destroy (domain->code_mp);
1268 domain->code_mp = NULL;
1270 lock_free_mempool_free (domain->lock_free_mp);
1271 domain->lock_free_mp = NULL;
1273 g_hash_table_destroy (domain->finalizable_objects_hash);
1274 domain->finalizable_objects_hash = NULL;
1275 if (domain->generic_virtual_cases) {
1276 g_hash_table_destroy (domain->generic_virtual_cases);
1277 domain->generic_virtual_cases = NULL;
1279 if (domain->ftnptrs_hash) {
1280 g_hash_table_destroy (domain->ftnptrs_hash);
1281 domain->ftnptrs_hash = NULL;
1283 if (domain->method_to_dyn_method) {
1284 g_hash_table_destroy (domain->method_to_dyn_method);
1285 domain->method_to_dyn_method = NULL;
1288 mono_domain_alcs_destroy (domain);
1290 #ifdef ENABLE_NETCORE
1291 mono_coop_mutex_destroy (&domain->alcs_lock);
1292 #endif
1294 mono_os_mutex_destroy (&domain->finalizable_objects_hash_lock);
1295 mono_os_mutex_destroy (&domain->assemblies_lock);
1296 mono_os_mutex_destroy (&domain->jit_code_hash_lock);
1298 mono_coop_mutex_destroy (&domain->lock);
1300 domain->setup = NULL;
1302 if (mono_gc_is_moving ())
1303 mono_gc_deregister_root ((char*)&(domain->MONO_DOMAIN_FIRST_GC_TRACKED));
1305 mono_appdomains_lock ();
1306 appdomains_list [domain->domain_id] = NULL;
1307 mono_appdomains_unlock ();
1309 mono_gc_free_fixed (domain);
1311 #ifndef DISABLE_PERFCOUNTERS
1312 mono_atomic_dec_i32 (&mono_perfcounters->loader_appdomains);
1313 #endif
1315 if (domain == mono_root_domain)
1316 mono_root_domain = NULL;
1320 * mono_domain_get_by_id:
1321 * \param domainid the ID
1322 * \returns the domain for a specific domain id.
1324 MonoDomain *
1325 mono_domain_get_by_id (gint32 domainid)
1327 MonoDomain * domain;
1329 MONO_ENTER_GC_UNSAFE;
1330 mono_appdomains_lock ();
1331 if (domainid < appdomain_list_size)
1332 domain = appdomains_list [domainid];
1333 else
1334 domain = NULL;
1335 mono_appdomains_unlock ();
1336 MONO_EXIT_GC_UNSAFE;
1337 return domain;
1341 * mono_domain_get_id:
1343 * A domain ID is guaranteed to be unique for as long as the domain
1344 * using it is alive. It may be reused later once the domain has been
1345 * unloaded.
1347 * \returns The unique ID for \p domain.
1349 gint32
1350 mono_domain_get_id (MonoDomain *domain)
1352 return domain->domain_id;
1356 * mono_domain_get_friendly_name:
1358 * The returned string's lifetime is the same as \p domain's. Consider
1359 * copying it if you need to store it somewhere.
1361 * \returns The friendly name of \p domain. Can be NULL if not yet set.
1363 const char *
1364 mono_domain_get_friendly_name (MonoDomain *domain)
1366 return domain->friendly_name;
1370 * mono_domain_alloc:
1372 * LOCKING: Acquires the domain lock.
1374 gpointer
1375 (mono_domain_alloc) (MonoDomain *domain, guint size)
1377 gpointer res;
1379 mono_domain_lock (domain);
1380 #ifndef DISABLE_PERFCOUNTERS
1381 mono_atomic_fetch_add_i32 (&mono_perfcounters->loader_bytes, size);
1382 #endif
1383 res = mono_mempool_alloc (domain->mp, size);
1384 mono_domain_unlock (domain);
1386 return res;
1390 * mono_domain_alloc0:
1392 * LOCKING: Acquires the domain lock.
1394 gpointer
1395 (mono_domain_alloc0) (MonoDomain *domain, guint size)
1397 gpointer res;
1399 mono_domain_lock (domain);
1400 #ifndef DISABLE_PERFCOUNTERS
1401 mono_atomic_fetch_add_i32 (&mono_perfcounters->loader_bytes, size);
1402 #endif
1403 res = mono_mempool_alloc0 (domain->mp, size);
1404 mono_domain_unlock (domain);
1406 return res;
1409 gpointer
1410 (mono_domain_alloc0_lock_free) (MonoDomain *domain, guint size)
1412 return lock_free_mempool_alloc0 (domain->lock_free_mp, size);
1416 * mono_domain_code_reserve:
1418 * LOCKING: Acquires the domain lock.
1420 void*
1421 (mono_domain_code_reserve) (MonoDomain *domain, int size)
1423 gpointer res;
1425 mono_domain_lock (domain);
1426 res = mono_code_manager_reserve (domain->code_mp, size);
1427 mono_domain_unlock (domain);
1429 return res;
1433 * mono_domain_code_reserve_align:
1435 * LOCKING: Acquires the domain lock.
1437 void*
1438 (mono_domain_code_reserve_align) (MonoDomain *domain, int size, int alignment)
1440 gpointer res;
1442 mono_domain_lock (domain);
1443 res = mono_code_manager_reserve_align (domain->code_mp, size, alignment);
1444 mono_domain_unlock (domain);
1446 return res;
1450 * mono_domain_code_commit:
1452 * LOCKING: Acquires the domain lock.
1454 void
1455 mono_domain_code_commit (MonoDomain *domain, void *data, int size, int newsize)
1457 mono_domain_lock (domain);
1458 mono_code_manager_commit (domain->code_mp, data, size, newsize);
1459 mono_domain_unlock (domain);
1463 * mono_domain_code_foreach:
1464 * Iterate over the code thunks of the code manager of @domain.
1466 * The @func callback MUST not take any locks. If it really needs to, it must respect
1467 * the locking rules of the runtime: http://www.mono-project.com/Mono:Runtime:Documentation:ThreadSafety
1468 * LOCKING: Acquires the domain lock.
1471 void
1472 mono_domain_code_foreach (MonoDomain *domain, MonoCodeManagerFunc func, void *user_data)
1474 mono_domain_lock (domain);
1475 mono_code_manager_foreach (domain->code_mp, func, user_data);
1476 mono_domain_unlock (domain);
1480 * mono_context_set:
1482 void
1483 mono_context_set (MonoAppContext * new_context)
1485 SET_APPCONTEXT (new_context);
1488 void
1489 mono_context_set_handle (MonoAppContextHandle new_context)
1491 SET_APPCONTEXT (MONO_HANDLE_RAW (new_context));
1495 * mono_context_get:
1497 * Returns: the current Mono Application Context.
1499 MonoAppContext *
1500 mono_context_get (void)
1502 return GET_APPCONTEXT ();
1506 * mono_context_get_handle:
1508 * Returns: the current Mono Application Context.
1510 MonoAppContextHandle
1511 mono_context_get_handle (void)
1513 return MONO_HANDLE_NEW (MonoAppContext, GET_APPCONTEXT ());
1517 * mono_context_get_id:
1518 * \param context the context to operate on.
1520 * Context IDs are guaranteed to be unique for the duration of a Mono
1521 * process; they are never reused.
1523 * \returns The unique ID for \p context.
1525 gint32
1526 mono_context_get_id (MonoAppContext *context)
1528 return context->context_id;
1532 * mono_context_get_domain_id:
1533 * \param context the context to operate on.
1534 * \returns The ID of the domain that \p context was created in.
1536 gint32
1537 mono_context_get_domain_id (MonoAppContext *context)
1539 return context->domain_id;
1543 * mono_get_corlib:
1544 * Use this function to get the \c MonoImage* for the \c mscorlib.dll assembly
1545 * \returns The \c MonoImage for mscorlib.dll
1547 MonoImage*
1548 mono_get_corlib (void)
1550 return mono_defaults.corlib;
1554 * mono_get_object_class:
1555 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Object .
1556 * \returns The \c MonoClass* for the \c System.Object type.
1558 MonoClass*
1559 mono_get_object_class (void)
1561 return mono_defaults.object_class;
1565 * mono_get_byte_class:
1566 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Byte .
1567 * \returns The \c MonoClass* for the \c System.Byte type.
1569 MonoClass*
1570 mono_get_byte_class (void)
1572 return mono_defaults.byte_class;
1576 * mono_get_void_class:
1577 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Void .
1578 * \returns The \c MonoClass* for the \c System.Void type.
1580 MonoClass*
1581 mono_get_void_class (void)
1583 return mono_defaults.void_class;
1587 * mono_get_boolean_class:
1588 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Boolean .
1589 * \returns The \c MonoClass* for the \c System.Boolean type.
1591 MonoClass*
1592 mono_get_boolean_class (void)
1594 return mono_defaults.boolean_class;
1598 * mono_get_sbyte_class:
1599 * Use this function to get the \c MonoClass* that the runtime is using for \c System.SByte.
1600 * \returns The \c MonoClass* for the \c System.SByte type.
1602 MonoClass*
1603 mono_get_sbyte_class (void)
1605 return mono_defaults.sbyte_class;
1609 * mono_get_int16_class:
1610 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Int16 .
1611 * \returns The \c MonoClass* for the \c System.Int16 type.
1613 MonoClass*
1614 mono_get_int16_class (void)
1616 return mono_defaults.int16_class;
1620 * mono_get_uint16_class:
1621 * Use this function to get the \c MonoClass* that the runtime is using for \c System.UInt16 .
1622 * \returns The \c MonoClass* for the \c System.UInt16 type.
1624 MonoClass*
1625 mono_get_uint16_class (void)
1627 return mono_defaults.uint16_class;
1631 * mono_get_int32_class:
1632 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Int32 .
1633 * \returns The \c MonoClass* for the \c System.Int32 type.
1635 MonoClass*
1636 mono_get_int32_class (void)
1638 return mono_defaults.int32_class;
1642 * mono_get_uint32_class:
1643 * Use this function to get the \c MonoClass* that the runtime is using for \c System.UInt32 .
1644 * \returns The \c MonoClass* for the \c System.UInt32 type.
1646 MonoClass*
1647 mono_get_uint32_class (void)
1649 return mono_defaults.uint32_class;
1653 * mono_get_intptr_class:
1654 * Use this function to get the \c MonoClass* that the runtime is using for \c System.IntPtr .
1655 * \returns The \c MonoClass* for the \c System.IntPtr type.
1657 MonoClass*
1658 mono_get_intptr_class (void)
1660 return mono_defaults.int_class;
1664 * mono_get_uintptr_class:
1665 * Use this function to get the \c MonoClass* that the runtime is using for \c System.UIntPtr .
1666 * \returns The \c MonoClass* for the \c System.UIntPtr type.
1668 MonoClass*
1669 mono_get_uintptr_class (void)
1671 return mono_defaults.uint_class;
1675 * mono_get_int64_class:
1676 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Int64 .
1677 * \returns The \c MonoClass* for the \c System.Int64 type.
1679 MonoClass*
1680 mono_get_int64_class (void)
1682 return mono_defaults.int64_class;
1686 * mono_get_uint64_class:
1687 * Use this function to get the \c MonoClass* that the runtime is using for \c System.UInt64 .
1688 * \returns The \c MonoClass* for the \c System.UInt64 type.
1690 MonoClass*
1691 mono_get_uint64_class (void)
1693 return mono_defaults.uint64_class;
1697 * mono_get_single_class:
1698 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Single (32-bit floating points).
1699 * \returns The \c MonoClass* for the \c System.Single type.
1701 MonoClass*
1702 mono_get_single_class (void)
1704 return mono_defaults.single_class;
1708 * mono_get_double_class:
1709 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Double (64-bit floating points).
1710 * \returns The \c MonoClass* for the \c System.Double type.
1712 MonoClass*
1713 mono_get_double_class (void)
1715 return mono_defaults.double_class;
1719 * mono_get_char_class:
1720 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Char .
1721 * \returns The \c MonoClass* for the \c System.Char type.
1723 MonoClass*
1724 mono_get_char_class (void)
1726 return mono_defaults.char_class;
1730 * mono_get_string_class:
1731 * Use this function to get the \c MonoClass* that the runtime is using for \c System.String .
1732 * \returns The \c MonoClass* for the \c System.String type.
1734 MonoClass*
1735 mono_get_string_class (void)
1737 return mono_defaults.string_class;
1741 * mono_get_enum_class:
1742 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Enum .
1743 * \returns The \c MonoClass* for the \c System.Enum type.
1745 MonoClass*
1746 mono_get_enum_class (void)
1748 return mono_defaults.enum_class;
1752 * mono_get_array_class:
1753 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Array .
1754 * \returns The \c MonoClass* for the \c System.Array type.
1756 MonoClass*
1757 mono_get_array_class (void)
1759 return mono_defaults.array_class;
1763 * mono_get_thread_class:
1764 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Threading.Thread .
1765 * \returns The \c MonoClass* for the \c System.Threading.Thread type.
1767 MonoClass*
1768 mono_get_thread_class (void)
1770 return mono_defaults.thread_class;
1774 * mono_get_exception_class:
1775 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Exception .
1776 * \returns The \c MonoClass* for the \c type.
1778 MonoClass*
1779 mono_get_exception_class (void)
1781 return mono_defaults.exception_class;
1785 static char* get_attribute_value (const gchar **attribute_names,
1786 const gchar **attribute_values,
1787 const char *att_name)
1789 int n;
1790 for (n=0; attribute_names[n] != NULL; n++) {
1791 if (strcmp (attribute_names[n], att_name) == 0)
1792 return g_strdup (attribute_values[n]);
1794 return NULL;
1797 static void start_element (GMarkupParseContext *context,
1798 const gchar *element_name,
1799 const gchar **attribute_names,
1800 const gchar **attribute_values,
1801 gpointer user_data,
1802 GError **gerror)
1804 AppConfigInfo* app_config = (AppConfigInfo*) user_data;
1806 if (strcmp (element_name, "configuration") == 0) {
1807 app_config->configuration_count++;
1808 return;
1810 if (strcmp (element_name, "startup") == 0) {
1811 app_config->startup_count++;
1812 return;
1815 if (app_config->configuration_count != 1 || app_config->startup_count != 1)
1816 return;
1818 if (strcmp (element_name, "requiredRuntime") == 0) {
1819 app_config->required_runtime = get_attribute_value (attribute_names, attribute_values, "version");
1820 } else if (strcmp (element_name, "supportedRuntime") == 0) {
1821 char *version = get_attribute_value (attribute_names, attribute_values, "version");
1822 app_config->supported_runtimes = g_slist_append (app_config->supported_runtimes, version);
1826 static void end_element (GMarkupParseContext *context,
1827 const gchar *element_name,
1828 gpointer user_data,
1829 GError **gerror)
1831 AppConfigInfo* app_config = (AppConfigInfo*) user_data;
1833 if (strcmp (element_name, "configuration") == 0) {
1834 app_config->configuration_count--;
1835 } else if (strcmp (element_name, "startup") == 0) {
1836 app_config->startup_count--;
1840 static const GMarkupParser
1841 mono_parser = {
1842 start_element,
1843 end_element,
1844 NULL,
1845 NULL,
1846 NULL
1849 static AppConfigInfo *
1850 app_config_parse (const char *exe_filename)
1852 AppConfigInfo *app_config;
1853 GMarkupParseContext *context;
1854 char *text;
1855 gsize len;
1856 const char *bundled_config;
1857 char *config_filename;
1859 bundled_config = mono_config_string_for_assembly_file (exe_filename);
1861 if (bundled_config) {
1862 text = g_strdup (bundled_config);
1863 len = strlen (text);
1864 } else {
1865 config_filename = g_strconcat (exe_filename, ".config", (const char*)NULL);
1867 if (!g_file_get_contents (config_filename, &text, &len, NULL)) {
1868 g_free (config_filename);
1869 return NULL;
1871 g_free (config_filename);
1874 app_config = g_new0 (AppConfigInfo, 1);
1876 context = g_markup_parse_context_new (&mono_parser, (GMarkupParseFlags)0, app_config, NULL);
1877 if (g_markup_parse_context_parse (context, text, len, NULL)) {
1878 g_markup_parse_context_end_parse (context, NULL);
1880 g_markup_parse_context_free (context);
1881 g_free (text);
1882 return app_config;
1885 static void
1886 app_config_free (AppConfigInfo* app_config)
1888 char *rt;
1889 GSList *list = app_config->supported_runtimes;
1890 while (list != NULL) {
1891 rt = (char*)list->data;
1892 g_free (rt);
1893 list = g_slist_next (list);
1895 g_slist_free (app_config->supported_runtimes);
1896 g_free (app_config->required_runtime);
1897 g_free (app_config);
1901 static const MonoRuntimeInfo*
1902 get_runtime_by_version (const char *version)
1904 int n;
1905 int max = G_N_ELEMENTS (supported_runtimes);
1906 int vlen;
1908 if (!version)
1909 return NULL;
1911 for (n=0; n<max; n++) {
1912 if (strcmp (version, supported_runtimes[n].runtime_version) == 0)
1913 return &supported_runtimes[n];
1916 vlen = strlen (version);
1917 if (vlen >= 4 && version [1] - '0' >= 4) {
1918 for (n=0; n<max; n++) {
1919 if (strncmp (version, supported_runtimes[n].runtime_version, 4) == 0)
1920 return &supported_runtimes[n];
1924 return NULL;
1927 static GSList*
1928 get_runtimes_from_exe (const char *file, MonoImage **out_image)
1930 AppConfigInfo* app_config;
1931 char *version;
1932 const MonoRuntimeInfo* runtime = NULL;
1933 MonoImage *image = NULL;
1934 GSList *runtimes = NULL;
1936 app_config = app_config_parse (file);
1938 if (app_config != NULL) {
1939 /* Check supportedRuntime elements, if none is supported, fail.
1940 * If there are no such elements, look for a requiredRuntime element.
1942 if (app_config->supported_runtimes != NULL) {
1943 GSList *list = app_config->supported_runtimes;
1944 while (list != NULL) {
1945 version = (char*) list->data;
1946 runtime = get_runtime_by_version (version);
1947 if (runtime != NULL)
1948 runtimes = g_slist_prepend (runtimes, (gpointer)runtime);
1949 list = g_slist_next (list);
1951 runtimes = g_slist_reverse (runtimes);
1952 app_config_free (app_config);
1953 return runtimes;
1956 /* Check the requiredRuntime element. This is for 1.0 apps only. */
1957 if (app_config->required_runtime != NULL) {
1958 const MonoRuntimeInfo* runtime = get_runtime_by_version (app_config->required_runtime);
1959 if (runtime != NULL)
1960 runtimes = g_slist_prepend (runtimes, (gpointer)runtime);
1961 app_config_free (app_config);
1962 return runtimes;
1964 app_config_free (app_config);
1967 /* Look for a runtime with the exact version */
1968 image = mono_assembly_open_from_bundle (mono_domain_default_alc (mono_domain_get ()), file, NULL, FALSE);
1970 if (image == NULL)
1971 image = mono_image_open (file, NULL);
1973 if (image == NULL) {
1974 /* The image is wrong or the file was not found. In this case return
1975 * a default runtime and leave to the initialization method the work of
1976 * reporting the error.
1978 runtime = get_runtime_by_version (DEFAULT_RUNTIME_VERSION);
1979 runtimes = g_slist_prepend (runtimes, (gpointer)runtime);
1980 return runtimes;
1983 *out_image = image;
1985 runtime = get_runtime_by_version (image->version);
1986 if (runtime != NULL)
1987 runtimes = g_slist_prepend (runtimes, (gpointer)runtime);
1988 return runtimes;
1993 * mono_get_runtime_info:
1995 * Returns: the version of the current runtime instance.
1997 const MonoRuntimeInfo*
1998 mono_get_runtime_info (void)
2000 return current_runtime;
2004 * mono_framework_version:
2006 * Return the major version of the framework curently executing.
2009 mono_framework_version (void)
2011 return current_runtime->framework_version [0] - '0';
2014 void
2015 mono_enable_debug_domain_unload (gboolean enable)
2017 debug_domain_unload = enable;
2020 MonoAotCacheConfig *
2021 mono_get_aot_cache_config (void)
2023 return &aot_cache_config;
2026 void
2027 mono_domain_lock (MonoDomain *domain)
2029 mono_locks_coop_acquire (&domain->lock, DomainLock);
2032 void
2033 mono_domain_unlock (MonoDomain *domain)
2035 mono_locks_coop_release (&domain->lock, DomainLock);
2038 GPtrArray*
2039 mono_domain_get_assemblies (MonoDomain *domain, gboolean refonly)
2041 GSList *tmp;
2042 GPtrArray *assemblies;
2043 MonoAssembly *ass;
2045 assemblies = g_ptr_array_new ();
2046 mono_domain_assemblies_lock (domain);
2047 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
2048 ass = (MonoAssembly *)tmp->data;
2049 gboolean ass_ref_only = mono_asmctx_get_kind (&ass->context) == MONO_ASMCTX_REFONLY;
2050 if (refonly != ass_ref_only)
2051 continue;
2052 if (ass->corlib_internal)
2053 continue;
2054 g_ptr_array_add (assemblies, ass);
2056 mono_domain_assemblies_unlock (domain);
2057 return assemblies;
2060 MonoAssemblyLoadContext *
2061 mono_domain_default_alc (MonoDomain *domain)
2063 #ifndef ENABLE_NETCORE
2064 return NULL;
2065 #else
2066 return domain->default_alc;
2067 #endif
2070 #ifdef ENABLE_NETCORE
2071 static inline void
2072 mono_domain_alcs_lock (MonoDomain *domain)
2074 mono_coop_mutex_lock (&domain->alcs_lock);
2077 static inline void
2078 mono_domain_alcs_unlock (MonoDomain *domain)
2080 mono_coop_mutex_unlock (&domain->alcs_lock);
2082 #endif
2085 #ifdef ENABLE_NETCORE
2086 static MonoAssemblyLoadContext *
2087 create_alc (MonoDomain *domain, gboolean is_default)
2089 MonoAssemblyLoadContext *alc = NULL;
2091 mono_domain_alcs_lock (domain);
2092 if (is_default && domain->default_alc)
2093 goto leave;
2095 alc = g_new0 (MonoAssemblyLoadContext, 1);
2096 mono_alc_init (alc, domain);
2098 domain->alcs = g_slist_prepend (domain->alcs, alc);
2099 if (is_default)
2100 domain->default_alc = alc;
2101 leave:
2102 mono_domain_alcs_unlock (domain);
2103 return alc;
2105 #endif
2107 #ifdef ENABLE_NETCORE
2108 void
2109 mono_domain_create_default_alc (MonoDomain *domain)
2111 if (domain->default_alc)
2112 return;
2113 create_alc (domain, TRUE);
2116 MonoAssemblyLoadContext *
2117 mono_domain_create_individual_alc (MonoDomain *domain, uint32_t this_gchandle, gboolean collectible, MonoError *error)
2119 g_assert (!collectible); /* TODO: implement collectible ALCs */
2120 MonoAssemblyLoadContext *alc = create_alc (domain, FALSE);
2121 alc->gchandle = this_gchandle;
2122 return alc;
2125 static void
2126 mono_alc_free (MonoAssemblyLoadContext *alc)
2128 mono_alc_cleanup (alc);
2129 g_free (alc);
2131 #endif
2133 void
2134 mono_domain_alcs_destroy (MonoDomain *domain)
2136 #ifdef ENABLE_NETCORE
2137 mono_domain_alcs_lock (domain);
2138 GSList *alcs = domain->alcs;
2139 domain->alcs = NULL;
2140 domain->default_alc = NULL;
2141 mono_domain_alcs_unlock (domain);
2143 for (GSList *iter = alcs; iter; iter = g_slist_next (iter)) {
2144 mono_alc_free ((MonoAssemblyLoadContext*)iter->data);
2146 #endif