[netcore] Implement Thread.GetCurrentProcessorId (#18450)
[mono-project.git] / mono / metadata / domain.c
blob061ba2239e06d7586564926e4231eb9193ffb241
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 static void
135 mono_domain_alcs_lock (MonoDomain *domain);
137 static void
138 mono_domain_alcs_unlock (MonoDomain *domain);
140 static void
141 mono_domain_create_default_alc (MonoDomain *domain);
143 static LockFreeMempool*
144 lock_free_mempool_new (void)
146 return g_new0 (LockFreeMempool, 1);
149 static void
150 lock_free_mempool_free (LockFreeMempool *mp)
152 LockFreeMempoolChunk *chunk, *next;
154 chunk = mp->chunks;
155 while (chunk) {
156 next = (LockFreeMempoolChunk *)chunk->prev;
157 mono_vfree (chunk, mono_pagesize (), MONO_MEM_ACCOUNT_DOMAIN);
158 chunk = next;
160 g_free (mp);
164 * This is async safe
166 static LockFreeMempoolChunk*
167 lock_free_mempool_chunk_new (LockFreeMempool *mp, int len)
169 LockFreeMempoolChunk *chunk, *prev;
170 int size;
172 size = mono_pagesize ();
173 while (size - sizeof (LockFreeMempoolChunk) < len)
174 size += mono_pagesize ();
175 chunk = (LockFreeMempoolChunk *)mono_valloc (0, size, MONO_MMAP_READ|MONO_MMAP_WRITE, MONO_MEM_ACCOUNT_DOMAIN);
176 g_assert (chunk);
177 chunk->mem = (guint8 *)ALIGN_PTR_TO ((char*)chunk + sizeof (LockFreeMempoolChunk), 16);
178 chunk->size = ((char*)chunk + size) - (char*)chunk->mem;
179 chunk->pos = 0;
181 /* Add to list of chunks lock-free */
182 while (TRUE) {
183 prev = mp->chunks;
184 if (mono_atomic_cas_ptr ((volatile gpointer*)&mp->chunks, chunk, prev) == prev)
185 break;
187 chunk->prev = prev;
189 return chunk;
193 * This is async safe
195 static gpointer
196 lock_free_mempool_alloc0 (LockFreeMempool *mp, guint size)
198 LockFreeMempoolChunk *chunk;
199 gpointer res;
200 int oldpos;
202 // FIXME: Free the allocator
204 size = ALIGN_TO (size, 8);
205 chunk = mp->current;
206 if (!chunk) {
207 chunk = lock_free_mempool_chunk_new (mp, size);
208 mono_memory_barrier ();
209 /* Publish */
210 mp->current = chunk;
213 /* The code below is lock-free, 'chunk' is shared state */
214 oldpos = mono_atomic_fetch_add_i32 (&chunk->pos, size);
215 if (oldpos + size > chunk->size) {
216 chunk = lock_free_mempool_chunk_new (mp, size);
217 g_assert (chunk->pos + size <= chunk->size);
218 res = chunk->mem;
219 chunk->pos += size;
220 mono_memory_barrier ();
221 mp->current = chunk;
222 } else {
223 res = (char*)chunk->mem + oldpos;
226 return res;
229 void
230 mono_install_create_domain_hook (MonoCreateDomainFunc func)
232 create_domain_hook = func;
235 void
236 mono_install_free_domain_hook (MonoFreeDomainFunc func)
238 free_domain_hook = func;
241 gboolean
242 mono_string_equal_internal (MonoString *s1, MonoString *s2)
244 int l1 = mono_string_length_internal (s1);
245 int l2 = mono_string_length_internal (s2);
247 if (s1 == s2)
248 return TRUE;
249 if (l1 != l2)
250 return FALSE;
252 return memcmp (mono_string_chars_internal (s1), mono_string_chars_internal (s2), l1 * 2) == 0;
256 * mono_string_equal:
257 * \param s1 First string to compare
258 * \param s2 Second string to compare
260 * Compares two \c MonoString* instances ordinally for equality.
262 * \returns FALSE if the strings differ.
264 gboolean
265 mono_string_equal (MonoString *s1, MonoString *s2)
267 MONO_EXTERNAL_ONLY (gboolean, mono_string_equal_internal (s1, s2));
270 guint
271 mono_string_hash_internal (MonoString *s)
273 const gunichar2 *p = mono_string_chars_internal (s);
274 int i, len = mono_string_length_internal (s);
275 guint h = 0;
277 for (i = 0; i < len; i++) {
278 h = (h << 5) - h + *p;
279 p++;
282 return h;
286 * mono_string_hash:
287 * \param s the string to hash
289 * Compute the hash for a \c MonoString*
290 * \returns the hash for the string.
292 guint
293 mono_string_hash (MonoString *s)
295 MONO_EXTERNAL_ONLY (guint, mono_string_hash_internal (s));
298 static gboolean
299 mono_ptrarray_equal (gpointer *s1, gpointer *s2)
301 int len = GPOINTER_TO_INT (s1 [0]);
302 if (len != GPOINTER_TO_INT (s2 [0]))
303 return FALSE;
305 return memcmp (s1 + 1, s2 + 1, len * sizeof(gpointer)) == 0;
308 static guint
309 mono_ptrarray_hash (gpointer *s)
311 int i;
312 int len = GPOINTER_TO_INT (s [0]);
313 guint hash = 0;
315 for (i = 1; i < len; i++)
316 hash += GPOINTER_TO_UINT (s [i]);
318 return hash;
321 //g_malloc on sgen and mono_gc_alloc_fixed on boehm
322 static void*
323 gc_alloc_fixed_non_heap_list (size_t size)
325 if (mono_gc_is_moving ())
326 return g_malloc0 (size);
327 else
328 return mono_gc_alloc_fixed (size, MONO_GC_DESCRIPTOR_NULL, MONO_ROOT_SOURCE_DOMAIN, NULL, "Domain List");
331 static void
332 gc_free_fixed_non_heap_list (void *ptr)
334 if (mono_gc_is_moving ())
335 g_free (ptr);
336 else
337 mono_gc_free_fixed (ptr);
340 * Allocate an id for domain and set domain->domain_id.
341 * LOCKING: must be called while holding appdomains_mutex.
342 * We try to assign low numbers to the domain, so it can be used
343 * as an index in data tables to lookup domain-specific info
344 * with minimal memory overhead. We also try not to reuse the
345 * same id too quickly (to help debugging).
347 static int
348 domain_id_alloc (MonoDomain *domain)
350 int id = -1, i;
351 if (!appdomains_list) {
352 appdomain_list_size = 2;
353 appdomains_list = (MonoDomain **)gc_alloc_fixed_non_heap_list (appdomain_list_size * sizeof (void*));
356 for (i = appdomain_next; i < appdomain_list_size; ++i) {
357 if (!appdomains_list [i]) {
358 id = i;
359 break;
362 if (id == -1) {
363 for (i = 0; i < appdomain_next; ++i) {
364 if (!appdomains_list [i]) {
365 id = i;
366 break;
370 if (id == -1) {
371 MonoDomain **new_list;
372 int new_size = appdomain_list_size * 2;
373 if (new_size >= (1 << 16))
374 g_assert_not_reached ();
375 id = appdomain_list_size;
376 new_list = (MonoDomain **)gc_alloc_fixed_non_heap_list (new_size * sizeof (void*));
377 memcpy (new_list, appdomains_list, appdomain_list_size * sizeof (void*));
378 gc_free_fixed_non_heap_list (appdomains_list);
379 appdomains_list = new_list;
380 appdomain_list_size = new_size;
382 domain->domain_id = id;
383 appdomains_list [id] = domain;
384 appdomain_next++;
385 if (appdomain_next > appdomain_list_size)
386 appdomain_next = 0;
387 return id;
390 static gsize domain_gc_bitmap [sizeof(MonoDomain)/4/32 + 1];
391 static MonoGCDescriptor domain_gc_desc = MONO_GC_DESCRIPTOR_NULL;
392 static guint32 domain_shadow_serial = 0L;
395 * mono_domain_create:
397 * Creates a new application domain, the unmanaged representation
398 * of the actual domain.
400 * Application domains provide an isolation facilty for assemblies. You
401 * can load assemblies and execute code in them that will not be visible
402 * to other application domains. This is a runtime-based virtualization
403 * technology.
405 * It is possible to unload domains, which unloads the assemblies and
406 * data that was allocated in that domain.
408 * When a domain is created a mempool is allocated for domain-specific
409 * structures, along a dedicated code manager to hold code that is
410 * associated with the domain.
412 * \returns New initialized \c MonoDomain, with no configuration or assemblies
413 * loaded into it.
415 MonoDomain *
416 mono_domain_create (void)
418 MonoDomain *domain;
419 guint32 shadow_serial;
421 mono_appdomains_lock ();
422 shadow_serial = domain_shadow_serial++;
424 if (!domain_gc_desc) {
425 unsigned int i, bit = 0;
426 for (i = G_STRUCT_OFFSET (MonoDomain, MONO_DOMAIN_FIRST_OBJECT); i < G_STRUCT_OFFSET (MonoDomain, MONO_DOMAIN_FIRST_GC_TRACKED); i += sizeof (gpointer)) {
427 bit = i / sizeof (gpointer);
428 domain_gc_bitmap [bit / 32] |= (gsize) 1 << (bit % 32);
430 domain_gc_desc = mono_gc_make_descr_from_bitmap ((gsize*)domain_gc_bitmap, bit + 1);
432 mono_appdomains_unlock ();
434 if (!mono_gc_is_moving ())
435 domain = (MonoDomain *)mono_gc_alloc_fixed (sizeof (MonoDomain), MONO_GC_DESCRIPTOR_NULL, MONO_ROOT_SOURCE_DOMAIN, NULL, "Domain Structure");
436 else
437 domain = (MonoDomain *)mono_gc_alloc_fixed (sizeof (MonoDomain), domain_gc_desc, MONO_ROOT_SOURCE_DOMAIN, NULL, "Domain Structure");
439 domain->shadow_serial = shadow_serial;
440 domain->domain = NULL;
441 domain->setup = NULL;
442 domain->friendly_name = NULL;
443 domain->search_path = NULL;
445 MONO_PROFILER_RAISE (domain_loading, (domain));
447 domain->mp = mono_mempool_new ();
448 domain->code_mp = mono_code_manager_new ();
449 domain->lock_free_mp = lock_free_mempool_new ();
450 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");
451 domain->domain_assemblies = NULL;
452 domain->assembly_bindings = NULL;
453 domain->assembly_bindings_parsed = FALSE;
454 domain->class_vtable_array = g_ptr_array_new ();
455 domain->proxy_vtable_hash = g_hash_table_new ((GHashFunc)mono_ptrarray_hash, (GCompareFunc)mono_ptrarray_equal);
456 mono_jit_code_hash_init (&domain->jit_code_hash);
457 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");
458 domain->num_jit_info_table_duplicates = 0;
459 domain->jit_info_table = mono_jit_info_table_new (domain);
460 domain->jit_info_free_queue = NULL;
461 domain->finalizable_objects_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
462 domain->ftnptrs_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
464 mono_coop_mutex_init_recursive (&domain->lock);
466 mono_os_mutex_init_recursive (&domain->assemblies_lock);
467 mono_os_mutex_init_recursive (&domain->jit_code_hash_lock);
468 mono_os_mutex_init_recursive (&domain->finalizable_objects_hash_lock);
470 #ifdef ENABLE_NETCORE
471 mono_coop_mutex_init (&domain->alcs_lock);
472 #endif
474 mono_appdomains_lock ();
475 domain_id_alloc (domain);
476 mono_appdomains_unlock ();
478 #ifndef DISABLE_PERFCOUNTERS
479 mono_atomic_inc_i32 (&mono_perfcounters->loader_appdomains);
480 mono_atomic_inc_i32 (&mono_perfcounters->loader_total_appdomains);
481 #endif
483 mono_debug_domain_create (domain);
485 #ifdef ENABLE_NETCORE
486 mono_domain_create_default_alc (domain);
487 #endif
489 if (create_domain_hook)
490 create_domain_hook (domain);
492 MONO_PROFILER_RAISE (domain_loaded, (domain));
494 return domain;
498 * mono_init_internal:
500 * Creates the initial application domain and initializes the mono_defaults
501 * structure.
502 * This function is guaranteed to not run any IL code.
503 * If exe_filename is not NULL, the method will determine the required runtime
504 * from the exe configuration file or the version PE field.
505 * If runtime_version is not NULL, that runtime version will be used.
506 * Either exe_filename or runtime_version must be provided.
508 * Returns: the initial domain.
510 static MonoDomain *
511 mono_init_internal (const char *filename, const char *exe_filename, const char *runtime_version)
513 static MonoDomain *domain = NULL;
514 MonoAssembly *ass = NULL;
515 MonoImageOpenStatus status = MONO_IMAGE_OK;
516 GSList *runtimes = NULL;
518 #ifdef DEBUG_DOMAIN_UNLOAD
519 debug_domain_unload = TRUE;
520 #endif
522 if (domain)
523 g_assert_not_reached ();
525 #if defined(HOST_WIN32) && G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
526 /* Avoid system error message boxes. */
527 SetErrorMode (SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
528 #endif
530 #ifndef HOST_WIN32
531 mono_w32handle_init ();
532 mono_w32handle_namespace_init ();
533 #endif
535 mono_w32mutex_init ();
536 mono_w32semaphore_init ();
537 mono_w32event_init ();
538 mono_w32process_init ();
539 mono_w32file_init ();
541 #ifndef DISABLE_PERFCOUNTERS
542 mono_perfcounters_init ();
543 #endif
544 mono_counters_init ();
546 mono_counters_register ("Max native code in a domain", MONO_COUNTER_INT|MONO_COUNTER_JIT, &max_domain_code_size);
547 mono_counters_register ("Max code space allocated in a domain", MONO_COUNTER_INT|MONO_COUNTER_JIT, &max_domain_code_alloc);
548 mono_counters_register ("Total code space allocated", MONO_COUNTER_INT|MONO_COUNTER_JIT, &total_domain_code_alloc);
550 mono_counters_register ("Max HashTable Chain Length", MONO_COUNTER_INT|MONO_COUNTER_METADATA, &mono_g_hash_table_max_chain_length);
552 mono_gc_base_init ();
553 mono_thread_info_attach ();
555 mono_coop_mutex_init_recursive (&appdomains_mutex);
557 mono_metadata_init ();
558 mono_images_init ();
559 mono_assemblies_init ();
560 mono_classes_init ();
561 mono_loader_init ();
562 mono_reflection_init ();
563 mono_runtime_init_tls ();
564 mono_icall_init ();
566 domain = mono_domain_create ();
567 mono_root_domain = domain;
569 SET_APPDOMAIN (domain);
571 #if defined(ENABLE_EXPERIMENT_null)
572 if (mono_experiment_enabled (MONO_EXPERIMENT_null))
573 g_warning ("null experiment enabled");
574 #endif
576 /* Get a list of runtimes supported by the exe */
577 if (exe_filename != NULL) {
579 * This function will load the exe file as a MonoImage. We need to close it, but
580 * that would mean it would be reloaded later. So instead, we save it to
581 * exe_image, and close it during shutdown.
583 runtimes = get_runtimes_from_exe (exe_filename, &exe_image);
584 #ifdef HOST_WIN32
585 if (!exe_image) {
586 exe_image = mono_assembly_open_from_bundle (mono_domain_default_alc (domain), exe_filename, NULL, FALSE);
587 if (!exe_image)
588 exe_image = mono_image_open (exe_filename, NULL);
590 mono_fixup_exe_image (exe_image);
591 #endif
592 } else if (runtime_version != NULL) {
593 const MonoRuntimeInfo* rt = get_runtime_by_version (runtime_version);
594 if (rt != NULL)
595 runtimes = g_slist_prepend (runtimes, (gpointer)rt);
598 if (runtimes == NULL) {
599 const MonoRuntimeInfo *default_runtime = get_runtime_by_version (DEFAULT_RUNTIME_VERSION);
600 g_assert (default_runtime);
601 runtimes = g_slist_prepend (runtimes, (gpointer)default_runtime);
602 if (runtime_version != NULL)
603 g_print ("WARNING: The requested runtime version \"%s\" is unavailable.\n", runtime_version);
604 else
605 g_print ("WARNING: The runtime version supported by this application is unavailable.\n");
606 g_print ("Using default runtime: %s\n", default_runtime->runtime_version);
609 /* The selected runtime will be the first one for which there is a mscrolib.dll */
610 GSList *tmp = runtimes;
611 while (tmp != NULL) {
612 current_runtime = (MonoRuntimeInfo*)tmp->data;
613 g_assert (current_runtime);
614 ass = mono_assembly_load_corlib (current_runtime, &status);
615 if (status != MONO_IMAGE_OK && status != MONO_IMAGE_ERROR_ERRNO)
616 break;
617 tmp = tmp->next;
620 g_slist_free (runtimes);
622 if ((status != MONO_IMAGE_OK) || (ass == NULL)) {
623 switch (status){
624 case MONO_IMAGE_ERROR_ERRNO: {
625 char *corlib_file = g_build_filename (mono_assembly_getrootdir (), "mono", current_runtime->framework_version, "mscorlib.dll", (const char*)NULL);
626 g_print ("The assembly mscorlib.dll was not found or could not be loaded.\n");
627 g_print ("It should have been installed in the `%s' directory.\n", corlib_file);
628 g_free (corlib_file);
629 break;
631 case MONO_IMAGE_IMAGE_INVALID:
632 g_print ("The file %s/mscorlib.dll is an invalid CIL image\n",
633 mono_assembly_getrootdir ());
634 break;
635 case MONO_IMAGE_MISSING_ASSEMBLYREF:
636 g_print ("Missing assembly reference in %s/mscorlib.dll\n",
637 mono_assembly_getrootdir ());
638 break;
639 case MONO_IMAGE_OK:
640 /* to suppress compiler warning */
641 break;
644 exit (1);
646 mono_defaults.corlib = mono_assembly_get_image_internal (ass);
648 mono_defaults.object_class = mono_class_load_from_name (
649 mono_defaults.corlib, "System", "Object");
651 mono_defaults.void_class = mono_class_load_from_name (
652 mono_defaults.corlib, "System", "Void");
654 mono_defaults.boolean_class = mono_class_load_from_name (
655 mono_defaults.corlib, "System", "Boolean");
657 mono_defaults.byte_class = mono_class_load_from_name (
658 mono_defaults.corlib, "System", "Byte");
660 mono_defaults.sbyte_class = mono_class_load_from_name (
661 mono_defaults.corlib, "System", "SByte");
663 mono_defaults.int16_class = mono_class_load_from_name (
664 mono_defaults.corlib, "System", "Int16");
666 mono_defaults.uint16_class = mono_class_load_from_name (
667 mono_defaults.corlib, "System", "UInt16");
669 mono_defaults.int32_class = mono_class_load_from_name (
670 mono_defaults.corlib, "System", "Int32");
672 mono_defaults.uint32_class = mono_class_load_from_name (
673 mono_defaults.corlib, "System", "UInt32");
675 mono_defaults.uint_class = mono_class_load_from_name (
676 mono_defaults.corlib, "System", "UIntPtr");
678 mono_defaults.int_class = mono_class_load_from_name (
679 mono_defaults.corlib, "System", "IntPtr");
681 mono_defaults.int64_class = mono_class_load_from_name (
682 mono_defaults.corlib, "System", "Int64");
684 mono_defaults.uint64_class = mono_class_load_from_name (
685 mono_defaults.corlib, "System", "UInt64");
687 mono_defaults.single_class = mono_class_load_from_name (
688 mono_defaults.corlib, "System", "Single");
690 mono_defaults.double_class = mono_class_load_from_name (
691 mono_defaults.corlib, "System", "Double");
693 mono_defaults.char_class = mono_class_load_from_name (
694 mono_defaults.corlib, "System", "Char");
696 mono_defaults.string_class = mono_class_load_from_name (
697 mono_defaults.corlib, "System", "String");
699 mono_defaults.enum_class = mono_class_load_from_name (
700 mono_defaults.corlib, "System", "Enum");
702 mono_defaults.array_class = mono_class_load_from_name (
703 mono_defaults.corlib, "System", "Array");
705 mono_defaults.delegate_class = mono_class_load_from_name (
706 mono_defaults.corlib, "System", "Delegate");
708 mono_defaults.multicastdelegate_class = mono_class_load_from_name (
709 mono_defaults.corlib, "System", "MulticastDelegate");
711 #ifndef ENABLE_NETCORE
712 mono_defaults.manualresetevent_class = mono_class_load_from_name (
713 mono_defaults.corlib, "System.Threading", "ManualResetEvent");
714 #endif
716 mono_defaults.typehandle_class = mono_class_load_from_name (
717 mono_defaults.corlib, "System", "RuntimeTypeHandle");
719 mono_defaults.methodhandle_class = mono_class_load_from_name (
720 mono_defaults.corlib, "System", "RuntimeMethodHandle");
722 mono_defaults.fieldhandle_class = mono_class_load_from_name (
723 mono_defaults.corlib, "System", "RuntimeFieldHandle");
725 mono_defaults.systemtype_class = mono_class_load_from_name (
726 mono_defaults.corlib, "System", "Type");
728 mono_defaults.runtimetype_class = mono_class_load_from_name (
729 mono_defaults.corlib, "System", "RuntimeType");
731 mono_defaults.exception_class = mono_class_load_from_name (
732 mono_defaults.corlib, "System", "Exception");
734 mono_defaults.threadabortexception_class = mono_class_load_from_name (
735 mono_defaults.corlib, "System.Threading", "ThreadAbortException");
737 mono_defaults.thread_class = mono_class_load_from_name (
738 mono_defaults.corlib, "System.Threading", "Thread");
740 #ifdef ENABLE_NETCORE
741 /* There is only one thread class */
742 mono_defaults.internal_thread_class = mono_defaults.thread_class;
743 #else
744 mono_defaults.internal_thread_class = mono_class_load_from_name (
745 mono_defaults.corlib, "System.Threading", "InternalThread");
746 #endif
748 mono_defaults.appdomain_class = mono_class_get_appdomain_class ();
750 #ifndef DISABLE_REMOTING
751 mono_defaults.transparent_proxy_class = mono_class_load_from_name (
752 mono_defaults.corlib, "System.Runtime.Remoting.Proxies", "TransparentProxy");
754 mono_defaults.real_proxy_class = mono_class_load_from_name (
755 mono_defaults.corlib, "System.Runtime.Remoting.Proxies", "RealProxy");
757 mono_defaults.marshalbyrefobject_class = mono_class_load_from_name (
758 mono_defaults.corlib, "System", "MarshalByRefObject");
760 mono_defaults.iremotingtypeinfo_class = mono_class_load_from_name (
761 mono_defaults.corlib, "System.Runtime.Remoting", "IRemotingTypeInfo");
763 #endif
765 /* FIXME pretty sure this is wrong and netcore has messages... */
766 #ifndef ENABLE_NETCORE
767 mono_defaults.mono_method_message_class = mono_class_load_from_name (
768 mono_defaults.corlib, "System.Runtime.Remoting.Messaging", "MonoMethodMessage");
769 #endif
771 mono_defaults.field_info_class = mono_class_load_from_name (
772 mono_defaults.corlib, "System.Reflection", "FieldInfo");
774 mono_defaults.method_info_class = mono_class_load_from_name (
775 mono_defaults.corlib, "System.Reflection", "MethodInfo");
777 #ifdef ENABLE_NETCORE
778 mono_defaults.stack_frame_class = mono_class_load_from_name (
779 mono_defaults.corlib, "System.Diagnostics", "MonoStackFrame");
780 #else
781 mono_defaults.stack_frame_class = mono_class_load_from_name (
782 mono_defaults.corlib, "System.Diagnostics", "StackFrame");
783 #endif
785 mono_defaults.marshal_class = mono_class_load_from_name (
786 mono_defaults.corlib, "System.Runtime.InteropServices", "Marshal");
788 mono_defaults.typed_reference_class = mono_class_load_from_name (
789 mono_defaults.corlib, "System", "TypedReference");
791 mono_defaults.argumenthandle_class = mono_class_load_from_name (
792 mono_defaults.corlib, "System", "RuntimeArgumentHandle");
794 mono_defaults.monitor_class = mono_class_load_from_name (
795 mono_defaults.corlib, "System.Threading", "Monitor");
797 Not using GENERATE_TRY_GET_CLASS_WITH_CACHE_DECL as this type is heavily checked by sgen when computing finalization.
799 mono_defaults.critical_finalizer_object = mono_class_try_load_from_name (mono_defaults.corlib,
800 "System.Runtime.ConstrainedExecution", "CriticalFinalizerObject");
802 mono_assembly_load_friends (ass);
804 mono_defaults.attribute_class = mono_class_load_from_name (
805 mono_defaults.corlib, "System", "Attribute");
807 mono_class_init_internal (mono_defaults.array_class);
808 mono_defaults.generic_nullable_class = mono_class_load_from_name (
809 mono_defaults.corlib, "System", "Nullable`1");
810 mono_defaults.generic_ilist_class = mono_class_load_from_name (
811 mono_defaults.corlib, "System.Collections.Generic", "IList`1");
812 mono_defaults.generic_ireadonlylist_class = mono_class_load_from_name (
813 mono_defaults.corlib, "System.Collections.Generic", "IReadOnlyList`1");
814 mono_defaults.generic_ienumerator_class = mono_class_load_from_name (
815 mono_defaults.corlib, "System.Collections.Generic", "IEnumerator`1");
817 #ifndef ENABLE_NETCORE
818 MonoClass *threadpool_wait_callback_class = mono_class_load_from_name (
819 mono_defaults.corlib, "System.Threading", "_ThreadPoolWaitCallback");
821 ERROR_DECL (error);
822 mono_defaults.threadpool_perform_wait_callback_method = mono_class_get_method_from_name_checked (
823 threadpool_wait_callback_class, "PerformWaitCallback", 0, 0, error);
824 mono_error_assert_ok (error);
825 #endif
827 domain->friendly_name = g_path_get_basename (filename);
829 MONO_PROFILER_RAISE (domain_name, (domain, domain->friendly_name));
831 return domain;
835 * mono_init:
837 * Creates the initial application domain and initializes the mono_defaults
838 * structure.
840 * This function is guaranteed to not run any IL code.
841 * The runtime is initialized using the default runtime version.
843 * Returns: the initial domain.
845 MonoDomain *
846 mono_init (const char *domain_name)
848 return mono_init_internal (domain_name, NULL, DEFAULT_RUNTIME_VERSION);
852 * mono_init_from_assembly:
853 * \param domain_name name to give to the initial domain
854 * \param filename filename to load on startup
856 * Used by the runtime, users should use mono_jit_init instead.
858 * Creates the initial application domain and initializes the mono_defaults
859 * structure.
860 * This function is guaranteed to not run any IL code.
861 * The runtime is initialized using the runtime version required by the
862 * provided executable. The version is determined by looking at the exe
863 * configuration file and the version PE field)
865 * \returns the initial domain.
867 MonoDomain *
868 mono_init_from_assembly (const char *domain_name, const char *filename)
870 return mono_init_internal (domain_name, filename, NULL);
874 * mono_init_version:
876 * Used by the runtime, users should use \c mono_jit_init instead.
878 * Creates the initial application domain and initializes the \c mono_defaults
879 * structure.
881 * This function is guaranteed to not run any IL code.
882 * The runtime is initialized using the provided rutime version.
884 * \returns the initial domain.
886 MonoDomain *
887 mono_init_version (const char *domain_name, const char *version)
889 return mono_init_internal (domain_name, NULL, version);
893 * mono_cleanup:
895 * Cleans up all metadata modules.
897 void
898 mono_cleanup (void)
900 mono_close_exe_image ();
902 mono_thread_info_cleanup ();
904 mono_defaults.corlib = NULL;
906 mono_config_cleanup ();
907 mono_loader_cleanup ();
908 mono_classes_cleanup ();
909 mono_assemblies_cleanup ();
910 mono_debug_cleanup ();
911 mono_images_cleanup ();
912 mono_metadata_cleanup ();
914 mono_coop_mutex_destroy (&appdomains_mutex);
916 mono_w32process_cleanup ();
917 mono_w32file_cleanup ();
920 void
921 mono_close_exe_image (void)
923 if (exe_image)
924 mono_image_close (exe_image);
928 * mono_get_root_domain:
930 * The root AppDomain is the initial domain created by the runtime when it is
931 * initialized. Programs execute on this AppDomain, but can create new ones
932 * later. Currently there is no unmanaged API to create new AppDomains, this
933 * must be done from managed code.
935 * Returns: the root appdomain, to obtain the current domain, use mono_domain_get ()
937 MonoDomain*
938 mono_get_root_domain (void)
940 return mono_root_domain;
944 * mono_domain_get:
946 * This method returns the value of the current \c MonoDomain that this thread
947 * and code are running under. To obtain the root domain use
948 * \c mono_get_root_domain API.
950 * \returns the current domain
952 MonoDomain *
953 mono_domain_get ()
955 return GET_APPDOMAIN ();
958 void
959 mono_domain_unset (void)
961 SET_APPDOMAIN (NULL);
964 void
965 mono_domain_set_internal_with_options (MonoDomain *domain, gboolean migrate_exception)
967 MONO_REQ_GC_UNSAFE_MODE;
968 MonoInternalThread *thread;
970 if (mono_domain_get () == domain)
971 return;
973 SET_APPDOMAIN (domain);
974 SET_APPCONTEXT (domain->default_context);
976 if (migrate_exception) {
977 thread = mono_thread_internal_current ();
978 if (!thread->abort_exc)
979 return;
981 g_assert (thread->abort_exc->object.vtable->domain != domain);
982 MONO_OBJECT_SETREF_INTERNAL (thread, abort_exc, mono_get_exception_thread_abort ());
983 g_assert (thread->abort_exc->object.vtable->domain == domain);
988 * mono_domain_foreach:
989 * \param func function to invoke with the domain data
990 * \param user_data user-defined pointer that is passed to the supplied \p func fo reach domain
992 * Use this method to safely iterate over all the loaded application
993 * domains in the current runtime. The provided \p func is invoked with a
994 * pointer to the \c MonoDomain and is given the value of the \p user_data
995 * parameter which can be used to pass state to your called routine.
997 void
998 mono_domain_foreach (MonoDomainFunc func, gpointer user_data)
1000 MONO_ENTER_GC_UNSAFE;
1001 int i, size;
1002 MonoDomain **copy;
1005 * Create a copy of the data to avoid calling the user callback
1006 * inside the lock because that could lead to deadlocks.
1007 * We can do this because this function is not perf. critical.
1009 mono_appdomains_lock ();
1010 size = appdomain_list_size;
1011 copy = (MonoDomain **)gc_alloc_fixed_non_heap_list (appdomain_list_size * sizeof (void*));
1012 memcpy (copy, appdomains_list, appdomain_list_size * sizeof (void*));
1013 mono_appdomains_unlock ();
1015 for (i = 0; i < size; ++i) {
1016 if (copy [i])
1017 func (copy [i], user_data);
1020 gc_free_fixed_non_heap_list (copy);
1021 MONO_EXIT_GC_UNSAFE;
1024 /* FIXME: maybe we should integrate this with mono_assembly_open? */
1026 * mono_domain_assembly_open:
1027 * \param domain the application domain
1028 * \param name file name of the assembly
1030 MonoAssembly *
1031 mono_domain_assembly_open (MonoDomain *domain, const char *name)
1033 MonoAssembly *result;
1034 MONO_ENTER_GC_UNSAFE;
1035 result = mono_domain_assembly_open_internal (domain, mono_domain_default_alc (domain), name);
1036 MONO_EXIT_GC_UNSAFE;
1037 return result;
1040 // Uses the domain on legacy mono and the ALC on current
1041 MonoAssembly *
1042 mono_domain_assembly_open_internal (MonoDomain *domain, MonoAssemblyLoadContext *alc, const char *name)
1044 MonoDomain *current;
1045 MonoAssembly *ass;
1046 GSList *tmp;
1048 MONO_REQ_GC_UNSAFE_MODE;
1050 #ifdef ENABLE_NETCORE
1051 mono_alc_assemblies_lock (alc);
1052 for (tmp = alc->loaded_assemblies; tmp; tmp = tmp->next) {
1053 ass = (MonoAssembly *)tmp->data;
1054 if (strcmp (name, ass->aname.name) == 0) {
1055 mono_alc_assemblies_unlock (alc);
1056 return ass;
1059 mono_alc_assemblies_unlock (alc);
1060 #else
1061 mono_domain_assemblies_lock (domain);
1062 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
1063 ass = (MonoAssembly *)tmp->data;
1064 if (strcmp (name, ass->aname.name) == 0) {
1065 mono_domain_assemblies_unlock (domain);
1066 return ass;
1069 mono_domain_assemblies_unlock (domain);
1070 #endif
1072 MonoAssemblyOpenRequest req;
1073 mono_assembly_request_prepare_open (&req, MONO_ASMCTX_DEFAULT, alc);
1074 if (domain != mono_domain_get ()) {
1075 current = mono_domain_get ();
1077 mono_domain_set_fast (domain, FALSE);
1078 ass = mono_assembly_request_open (name, &req, NULL);
1079 mono_domain_set_fast (current, FALSE);
1080 } else {
1081 ass = mono_assembly_request_open (name, &req, NULL);
1084 return ass;
1087 static void
1088 unregister_vtable_reflection_type (MonoVTable *vtable)
1090 MonoObject *type = (MonoObject *)vtable->type;
1092 if (type->vtable->klass != mono_defaults.runtimetype_class)
1093 MONO_GC_UNREGISTER_ROOT_IF_MOVING (vtable->type);
1097 * mono_domain_free:
1098 * \param domain the domain to release
1099 * \param force if TRUE, it allows the root domain to be released (used at shutdown only).
1101 * This releases the resources associated with the specific domain.
1102 * This is a low-level function that is invoked by the AppDomain infrastructure
1103 * when necessary.
1105 * In theory, this is dead code on netcore and thus does not need to be ALC-aware.
1107 void
1108 mono_domain_free (MonoDomain *domain, gboolean force)
1110 int code_size, code_alloc;
1111 GSList *tmp;
1112 gpointer *p;
1114 if ((domain == mono_root_domain) && !force) {
1115 g_warning ("cant unload root domain");
1116 return;
1119 if (mono_dont_free_domains)
1120 return;
1122 MONO_PROFILER_RAISE (domain_unloading, (domain));
1124 mono_debug_domain_unload (domain);
1126 /* must do this early as it accesses fields and types */
1127 if (domain->special_static_fields) {
1128 mono_alloc_special_static_data_free (domain->special_static_fields);
1129 g_hash_table_destroy (domain->special_static_fields);
1130 domain->special_static_fields = NULL;
1134 * We must destroy all these hash tables here because they
1135 * contain references to managed objects belonging to the
1136 * domain. Once we let the GC clear the domain there must be
1137 * no more such references, or we'll crash if a collection
1138 * occurs.
1140 mono_g_hash_table_destroy (domain->ldstr_table);
1141 domain->ldstr_table = NULL;
1143 mono_g_hash_table_destroy (domain->env);
1144 domain->env = NULL;
1146 mono_reflection_cleanup_domain (domain);
1148 /* This must be done before type_hash is freed */
1149 if (domain->class_vtable_array) {
1150 int i;
1151 for (i = 0; i < domain->class_vtable_array->len; ++i)
1152 unregister_vtable_reflection_type ((MonoVTable *)g_ptr_array_index (domain->class_vtable_array, i));
1155 if (domain->type_hash) {
1156 mono_g_hash_table_destroy (domain->type_hash);
1157 domain->type_hash = NULL;
1159 if (domain->type_init_exception_hash) {
1160 mono_g_hash_table_destroy (domain->type_init_exception_hash);
1161 domain->type_init_exception_hash = NULL;
1164 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
1165 MonoAssembly *ass = (MonoAssembly *)tmp->data;
1166 mono_assembly_release_gc_roots (ass);
1169 /* Have to zero out reference fields since they will be invalidated by the clear_domain () call below */
1170 for (p = (gpointer*)&domain->MONO_DOMAIN_FIRST_OBJECT; p < (gpointer*)&domain->MONO_DOMAIN_FIRST_GC_TRACKED; ++p)
1171 *p = NULL;
1173 /* This needs to be done before closing assemblies */
1174 mono_gc_clear_domain (domain);
1176 /* Close dynamic assemblies first, since they have no ref count */
1177 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
1178 MonoAssembly *ass = (MonoAssembly *)tmp->data;
1179 if (!ass->image || !image_is_dynamic (ass->image))
1180 continue;
1181 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);
1182 if (!mono_assembly_close_except_image_pools (ass))
1183 tmp->data = NULL;
1186 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
1187 MonoAssembly *ass = (MonoAssembly *)tmp->data;
1188 if (!ass)
1189 continue;
1190 if (!ass->image || image_is_dynamic (ass->image))
1191 continue;
1192 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);
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 mono_assembly_close_finish (ass);
1202 g_slist_free (domain->domain_assemblies);
1203 domain->domain_assemblies = NULL;
1206 * Send this after the assemblies have been unloaded and the domain is still in a
1207 * usable state.
1209 MONO_PROFILER_RAISE (domain_unloaded, (domain));
1211 if (free_domain_hook)
1212 free_domain_hook (domain);
1214 /* FIXME: free delegate_hash_table when it's used */
1215 if (domain->search_path) {
1216 g_strfreev (domain->search_path);
1217 domain->search_path = NULL;
1219 domain->create_proxy_for_type_method = NULL;
1220 domain->private_invoke_method = NULL;
1221 domain->default_context = NULL;
1222 domain->out_of_memory_ex = NULL;
1223 domain->null_reference_ex = NULL;
1224 domain->stack_overflow_ex = NULL;
1225 domain->ephemeron_tombstone = NULL;
1226 domain->entry_assembly = NULL;
1228 g_free (domain->friendly_name);
1229 domain->friendly_name = NULL;
1230 g_ptr_array_free (domain->class_vtable_array, TRUE);
1231 domain->class_vtable_array = NULL;
1232 g_hash_table_destroy (domain->proxy_vtable_hash);
1233 domain->proxy_vtable_hash = NULL;
1234 mono_internal_hash_table_destroy (&domain->jit_code_hash);
1237 * There might still be jit info tables of this domain which
1238 * are not freed. Since the domain cannot be in use anymore,
1239 * this will free them.
1241 mono_thread_hazardous_try_free_all ();
1242 if (domain->aot_modules)
1243 mono_jit_info_table_free (domain->aot_modules);
1244 g_assert (domain->num_jit_info_table_duplicates == 0);
1245 mono_jit_info_table_free (domain->jit_info_table);
1246 domain->jit_info_table = NULL;
1247 g_assert (!domain->jit_info_free_queue);
1249 /* collect statistics */
1250 code_alloc = mono_code_manager_size (domain->code_mp, &code_size);
1251 total_domain_code_alloc += code_alloc;
1252 max_domain_code_alloc = MAX (max_domain_code_alloc, code_alloc);
1253 max_domain_code_size = MAX (max_domain_code_size, code_size);
1255 if (debug_domain_unload) {
1256 mono_mempool_invalidate (domain->mp);
1257 mono_code_manager_invalidate (domain->code_mp);
1258 } else {
1259 #ifndef DISABLE_PERFCOUNTERS
1260 /* FIXME: use an explicit subtraction method as soon as it's available */
1261 mono_atomic_fetch_add_i32 (&mono_perfcounters->loader_bytes, -1 * mono_mempool_get_allocated (domain->mp));
1262 #endif
1263 mono_mempool_destroy (domain->mp);
1264 domain->mp = NULL;
1265 mono_code_manager_destroy (domain->code_mp);
1266 domain->code_mp = NULL;
1268 lock_free_mempool_free (domain->lock_free_mp);
1269 domain->lock_free_mp = NULL;
1271 g_hash_table_destroy (domain->finalizable_objects_hash);
1272 domain->finalizable_objects_hash = NULL;
1273 if (domain->generic_virtual_cases) {
1274 g_hash_table_destroy (domain->generic_virtual_cases);
1275 domain->generic_virtual_cases = NULL;
1277 if (domain->ftnptrs_hash) {
1278 g_hash_table_destroy (domain->ftnptrs_hash);
1279 domain->ftnptrs_hash = NULL;
1281 if (domain->method_to_dyn_method) {
1282 g_hash_table_destroy (domain->method_to_dyn_method);
1283 domain->method_to_dyn_method = NULL;
1286 mono_domain_alcs_destroy (domain);
1288 #ifdef ENABLE_NETCORE
1289 mono_coop_mutex_destroy (&domain->alcs_lock);
1290 #endif
1292 mono_os_mutex_destroy (&domain->finalizable_objects_hash_lock);
1293 mono_os_mutex_destroy (&domain->assemblies_lock);
1294 mono_os_mutex_destroy (&domain->jit_code_hash_lock);
1296 mono_coop_mutex_destroy (&domain->lock);
1298 domain->setup = NULL;
1300 if (mono_gc_is_moving ())
1301 mono_gc_deregister_root ((char*)&(domain->MONO_DOMAIN_FIRST_GC_TRACKED));
1303 mono_appdomains_lock ();
1304 appdomains_list [domain->domain_id] = NULL;
1305 mono_appdomains_unlock ();
1307 mono_gc_free_fixed (domain);
1309 #ifndef DISABLE_PERFCOUNTERS
1310 mono_atomic_dec_i32 (&mono_perfcounters->loader_appdomains);
1311 #endif
1313 if (domain == mono_root_domain)
1314 mono_root_domain = NULL;
1318 * mono_domain_get_by_id:
1319 * \param domainid the ID
1320 * \returns the domain for a specific domain id.
1322 MonoDomain *
1323 mono_domain_get_by_id (gint32 domainid)
1325 MonoDomain * domain;
1327 MONO_ENTER_GC_UNSAFE;
1328 mono_appdomains_lock ();
1329 if (domainid < appdomain_list_size)
1330 domain = appdomains_list [domainid];
1331 else
1332 domain = NULL;
1333 mono_appdomains_unlock ();
1334 MONO_EXIT_GC_UNSAFE;
1335 return domain;
1339 * mono_domain_get_id:
1341 * A domain ID is guaranteed to be unique for as long as the domain
1342 * using it is alive. It may be reused later once the domain has been
1343 * unloaded.
1345 * \returns The unique ID for \p domain.
1347 gint32
1348 mono_domain_get_id (MonoDomain *domain)
1350 return domain->domain_id;
1354 * mono_domain_get_friendly_name:
1356 * The returned string's lifetime is the same as \p domain's. Consider
1357 * copying it if you need to store it somewhere.
1359 * \returns The friendly name of \p domain. Can be NULL if not yet set.
1361 const char *
1362 mono_domain_get_friendly_name (MonoDomain *domain)
1364 return domain->friendly_name;
1368 * mono_domain_alloc:
1370 * LOCKING: Acquires the domain lock.
1372 gpointer
1373 (mono_domain_alloc) (MonoDomain *domain, guint size)
1375 gpointer res;
1377 mono_domain_lock (domain);
1378 #ifndef DISABLE_PERFCOUNTERS
1379 mono_atomic_fetch_add_i32 (&mono_perfcounters->loader_bytes, size);
1380 #endif
1381 res = mono_mempool_alloc (domain->mp, size);
1382 mono_domain_unlock (domain);
1384 return res;
1388 * mono_domain_alloc0:
1390 * LOCKING: Acquires the domain lock.
1392 gpointer
1393 (mono_domain_alloc0) (MonoDomain *domain, guint size)
1395 gpointer res;
1397 mono_domain_lock (domain);
1398 #ifndef DISABLE_PERFCOUNTERS
1399 mono_atomic_fetch_add_i32 (&mono_perfcounters->loader_bytes, size);
1400 #endif
1401 res = mono_mempool_alloc0 (domain->mp, size);
1402 mono_domain_unlock (domain);
1404 return res;
1407 gpointer
1408 (mono_domain_alloc0_lock_free) (MonoDomain *domain, guint size)
1410 return lock_free_mempool_alloc0 (domain->lock_free_mp, size);
1414 * mono_domain_code_reserve:
1416 * LOCKING: Acquires the domain lock.
1418 void*
1419 (mono_domain_code_reserve) (MonoDomain *domain, int size)
1421 gpointer res;
1423 mono_domain_lock (domain);
1424 res = mono_code_manager_reserve (domain->code_mp, size);
1425 mono_domain_unlock (domain);
1427 return res;
1431 * mono_domain_code_reserve_align:
1433 * LOCKING: Acquires the domain lock.
1435 void*
1436 (mono_domain_code_reserve_align) (MonoDomain *domain, int size, int alignment)
1438 gpointer res;
1440 mono_domain_lock (domain);
1441 res = mono_code_manager_reserve_align (domain->code_mp, size, alignment);
1442 mono_domain_unlock (domain);
1444 return res;
1448 * mono_domain_code_commit:
1450 * LOCKING: Acquires the domain lock.
1452 void
1453 mono_domain_code_commit (MonoDomain *domain, void *data, int size, int newsize)
1455 mono_domain_lock (domain);
1456 mono_code_manager_commit (domain->code_mp, data, size, newsize);
1457 mono_domain_unlock (domain);
1461 * mono_domain_code_foreach:
1462 * Iterate over the code thunks of the code manager of @domain.
1464 * The @func callback MUST not take any locks. If it really needs to, it must respect
1465 * the locking rules of the runtime: http://www.mono-project.com/Mono:Runtime:Documentation:ThreadSafety
1466 * LOCKING: Acquires the domain lock.
1469 void
1470 mono_domain_code_foreach (MonoDomain *domain, MonoCodeManagerFunc func, void *user_data)
1472 mono_domain_lock (domain);
1473 mono_code_manager_foreach (domain->code_mp, func, user_data);
1474 mono_domain_unlock (domain);
1478 * mono_context_set:
1480 void
1481 mono_context_set (MonoAppContext * new_context)
1483 SET_APPCONTEXT (new_context);
1486 void
1487 mono_context_set_handle (MonoAppContextHandle new_context)
1489 SET_APPCONTEXT (MONO_HANDLE_RAW (new_context));
1493 * mono_context_get:
1495 * Returns: the current Mono Application Context.
1497 MonoAppContext *
1498 mono_context_get (void)
1500 return GET_APPCONTEXT ();
1504 * mono_context_get_handle:
1506 * Returns: the current Mono Application Context.
1508 MonoAppContextHandle
1509 mono_context_get_handle (void)
1511 return MONO_HANDLE_NEW (MonoAppContext, GET_APPCONTEXT ());
1515 * mono_context_get_id:
1516 * \param context the context to operate on.
1518 * Context IDs are guaranteed to be unique for the duration of a Mono
1519 * process; they are never reused.
1521 * \returns The unique ID for \p context.
1523 gint32
1524 mono_context_get_id (MonoAppContext *context)
1526 return context->context_id;
1530 * mono_context_get_domain_id:
1531 * \param context the context to operate on.
1532 * \returns The ID of the domain that \p context was created in.
1534 gint32
1535 mono_context_get_domain_id (MonoAppContext *context)
1537 return context->domain_id;
1541 * mono_get_corlib:
1542 * Use this function to get the \c MonoImage* for the \c mscorlib.dll assembly
1543 * \returns The \c MonoImage for mscorlib.dll
1545 MonoImage*
1546 mono_get_corlib (void)
1548 return mono_defaults.corlib;
1552 * mono_get_object_class:
1553 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Object .
1554 * \returns The \c MonoClass* for the \c System.Object type.
1556 MonoClass*
1557 mono_get_object_class (void)
1559 return mono_defaults.object_class;
1563 * mono_get_byte_class:
1564 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Byte .
1565 * \returns The \c MonoClass* for the \c System.Byte type.
1567 MonoClass*
1568 mono_get_byte_class (void)
1570 return mono_defaults.byte_class;
1574 * mono_get_void_class:
1575 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Void .
1576 * \returns The \c MonoClass* for the \c System.Void type.
1578 MonoClass*
1579 mono_get_void_class (void)
1581 return mono_defaults.void_class;
1585 * mono_get_boolean_class:
1586 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Boolean .
1587 * \returns The \c MonoClass* for the \c System.Boolean type.
1589 MonoClass*
1590 mono_get_boolean_class (void)
1592 return mono_defaults.boolean_class;
1596 * mono_get_sbyte_class:
1597 * Use this function to get the \c MonoClass* that the runtime is using for \c System.SByte.
1598 * \returns The \c MonoClass* for the \c System.SByte type.
1600 MonoClass*
1601 mono_get_sbyte_class (void)
1603 return mono_defaults.sbyte_class;
1607 * mono_get_int16_class:
1608 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Int16 .
1609 * \returns The \c MonoClass* for the \c System.Int16 type.
1611 MonoClass*
1612 mono_get_int16_class (void)
1614 return mono_defaults.int16_class;
1618 * mono_get_uint16_class:
1619 * Use this function to get the \c MonoClass* that the runtime is using for \c System.UInt16 .
1620 * \returns The \c MonoClass* for the \c System.UInt16 type.
1622 MonoClass*
1623 mono_get_uint16_class (void)
1625 return mono_defaults.uint16_class;
1629 * mono_get_int32_class:
1630 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Int32 .
1631 * \returns The \c MonoClass* for the \c System.Int32 type.
1633 MonoClass*
1634 mono_get_int32_class (void)
1636 return mono_defaults.int32_class;
1640 * mono_get_uint32_class:
1641 * Use this function to get the \c MonoClass* that the runtime is using for \c System.UInt32 .
1642 * \returns The \c MonoClass* for the \c System.UInt32 type.
1644 MonoClass*
1645 mono_get_uint32_class (void)
1647 return mono_defaults.uint32_class;
1651 * mono_get_intptr_class:
1652 * Use this function to get the \c MonoClass* that the runtime is using for \c System.IntPtr .
1653 * \returns The \c MonoClass* for the \c System.IntPtr type.
1655 MonoClass*
1656 mono_get_intptr_class (void)
1658 return mono_defaults.int_class;
1662 * mono_get_uintptr_class:
1663 * Use this function to get the \c MonoClass* that the runtime is using for \c System.UIntPtr .
1664 * \returns The \c MonoClass* for the \c System.UIntPtr type.
1666 MonoClass*
1667 mono_get_uintptr_class (void)
1669 return mono_defaults.uint_class;
1673 * mono_get_int64_class:
1674 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Int64 .
1675 * \returns The \c MonoClass* for the \c System.Int64 type.
1677 MonoClass*
1678 mono_get_int64_class (void)
1680 return mono_defaults.int64_class;
1684 * mono_get_uint64_class:
1685 * Use this function to get the \c MonoClass* that the runtime is using for \c System.UInt64 .
1686 * \returns The \c MonoClass* for the \c System.UInt64 type.
1688 MonoClass*
1689 mono_get_uint64_class (void)
1691 return mono_defaults.uint64_class;
1695 * mono_get_single_class:
1696 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Single (32-bit floating points).
1697 * \returns The \c MonoClass* for the \c System.Single type.
1699 MonoClass*
1700 mono_get_single_class (void)
1702 return mono_defaults.single_class;
1706 * mono_get_double_class:
1707 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Double (64-bit floating points).
1708 * \returns The \c MonoClass* for the \c System.Double type.
1710 MonoClass*
1711 mono_get_double_class (void)
1713 return mono_defaults.double_class;
1717 * mono_get_char_class:
1718 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Char .
1719 * \returns The \c MonoClass* for the \c System.Char type.
1721 MonoClass*
1722 mono_get_char_class (void)
1724 return mono_defaults.char_class;
1728 * mono_get_string_class:
1729 * Use this function to get the \c MonoClass* that the runtime is using for \c System.String .
1730 * \returns The \c MonoClass* for the \c System.String type.
1732 MonoClass*
1733 mono_get_string_class (void)
1735 return mono_defaults.string_class;
1739 * mono_get_enum_class:
1740 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Enum .
1741 * \returns The \c MonoClass* for the \c System.Enum type.
1743 MonoClass*
1744 mono_get_enum_class (void)
1746 return mono_defaults.enum_class;
1750 * mono_get_array_class:
1751 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Array .
1752 * \returns The \c MonoClass* for the \c System.Array type.
1754 MonoClass*
1755 mono_get_array_class (void)
1757 return mono_defaults.array_class;
1761 * mono_get_thread_class:
1762 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Threading.Thread .
1763 * \returns The \c MonoClass* for the \c System.Threading.Thread type.
1765 MonoClass*
1766 mono_get_thread_class (void)
1768 return mono_defaults.thread_class;
1772 * mono_get_exception_class:
1773 * Use this function to get the \c MonoClass* that the runtime is using for \c System.Exception .
1774 * \returns The \c MonoClass* for the \c type.
1776 MonoClass*
1777 mono_get_exception_class (void)
1779 return mono_defaults.exception_class;
1783 static char* get_attribute_value (const gchar **attribute_names,
1784 const gchar **attribute_values,
1785 const char *att_name)
1787 int n;
1788 for (n=0; attribute_names[n] != NULL; n++) {
1789 if (strcmp (attribute_names[n], att_name) == 0)
1790 return g_strdup (attribute_values[n]);
1792 return NULL;
1795 static void start_element (GMarkupParseContext *context,
1796 const gchar *element_name,
1797 const gchar **attribute_names,
1798 const gchar **attribute_values,
1799 gpointer user_data,
1800 GError **gerror)
1802 AppConfigInfo* app_config = (AppConfigInfo*) user_data;
1804 if (strcmp (element_name, "configuration") == 0) {
1805 app_config->configuration_count++;
1806 return;
1808 if (strcmp (element_name, "startup") == 0) {
1809 app_config->startup_count++;
1810 return;
1813 if (app_config->configuration_count != 1 || app_config->startup_count != 1)
1814 return;
1816 if (strcmp (element_name, "requiredRuntime") == 0) {
1817 app_config->required_runtime = get_attribute_value (attribute_names, attribute_values, "version");
1818 } else if (strcmp (element_name, "supportedRuntime") == 0) {
1819 char *version = get_attribute_value (attribute_names, attribute_values, "version");
1820 app_config->supported_runtimes = g_slist_append (app_config->supported_runtimes, version);
1824 static void end_element (GMarkupParseContext *context,
1825 const gchar *element_name,
1826 gpointer user_data,
1827 GError **gerror)
1829 AppConfigInfo* app_config = (AppConfigInfo*) user_data;
1831 if (strcmp (element_name, "configuration") == 0) {
1832 app_config->configuration_count--;
1833 } else if (strcmp (element_name, "startup") == 0) {
1834 app_config->startup_count--;
1838 static const GMarkupParser
1839 mono_parser = {
1840 start_element,
1841 end_element,
1842 NULL,
1843 NULL,
1844 NULL
1847 static AppConfigInfo *
1848 app_config_parse (const char *exe_filename)
1850 AppConfigInfo *app_config;
1851 GMarkupParseContext *context;
1852 char *text;
1853 gsize len;
1854 const char *bundled_config;
1855 char *config_filename;
1857 bundled_config = mono_config_string_for_assembly_file (exe_filename);
1859 if (bundled_config) {
1860 text = g_strdup (bundled_config);
1861 len = strlen (text);
1862 } else {
1863 config_filename = g_strconcat (exe_filename, ".config", (const char*)NULL);
1865 if (!g_file_get_contents (config_filename, &text, &len, NULL)) {
1866 g_free (config_filename);
1867 return NULL;
1869 g_free (config_filename);
1872 app_config = g_new0 (AppConfigInfo, 1);
1874 context = g_markup_parse_context_new (&mono_parser, (GMarkupParseFlags)0, app_config, NULL);
1875 if (g_markup_parse_context_parse (context, text, len, NULL)) {
1876 g_markup_parse_context_end_parse (context, NULL);
1878 g_markup_parse_context_free (context);
1879 g_free (text);
1880 return app_config;
1883 static void
1884 app_config_free (AppConfigInfo* app_config)
1886 char *rt;
1887 GSList *list = app_config->supported_runtimes;
1888 while (list != NULL) {
1889 rt = (char*)list->data;
1890 g_free (rt);
1891 list = g_slist_next (list);
1893 g_slist_free (app_config->supported_runtimes);
1894 g_free (app_config->required_runtime);
1895 g_free (app_config);
1899 static const MonoRuntimeInfo*
1900 get_runtime_by_version (const char *version)
1902 int n;
1903 int max = G_N_ELEMENTS (supported_runtimes);
1904 int vlen;
1906 if (!version)
1907 return NULL;
1909 for (n=0; n<max; n++) {
1910 if (strcmp (version, supported_runtimes[n].runtime_version) == 0)
1911 return &supported_runtimes[n];
1914 vlen = strlen (version);
1915 if (vlen >= 4 && version [1] - '0' >= 4) {
1916 for (n=0; n<max; n++) {
1917 if (strncmp (version, supported_runtimes[n].runtime_version, 4) == 0)
1918 return &supported_runtimes[n];
1922 return NULL;
1925 static GSList*
1926 get_runtimes_from_exe (const char *file, MonoImage **out_image)
1928 AppConfigInfo* app_config;
1929 char *version;
1930 const MonoRuntimeInfo* runtime = NULL;
1931 MonoImage *image = NULL;
1932 GSList *runtimes = NULL;
1934 app_config = app_config_parse (file);
1936 if (app_config != NULL) {
1937 /* Check supportedRuntime elements, if none is supported, fail.
1938 * If there are no such elements, look for a requiredRuntime element.
1940 if (app_config->supported_runtimes != NULL) {
1941 GSList *list = app_config->supported_runtimes;
1942 while (list != NULL) {
1943 version = (char*) list->data;
1944 runtime = get_runtime_by_version (version);
1945 if (runtime != NULL)
1946 runtimes = g_slist_prepend (runtimes, (gpointer)runtime);
1947 list = g_slist_next (list);
1949 runtimes = g_slist_reverse (runtimes);
1950 app_config_free (app_config);
1951 return runtimes;
1954 /* Check the requiredRuntime element. This is for 1.0 apps only. */
1955 if (app_config->required_runtime != NULL) {
1956 const MonoRuntimeInfo* runtime = get_runtime_by_version (app_config->required_runtime);
1957 if (runtime != NULL)
1958 runtimes = g_slist_prepend (runtimes, (gpointer)runtime);
1959 app_config_free (app_config);
1960 return runtimes;
1962 app_config_free (app_config);
1965 /* Look for a runtime with the exact version */
1966 image = mono_assembly_open_from_bundle (mono_domain_default_alc (mono_domain_get ()), file, NULL, FALSE);
1968 if (image == NULL)
1969 image = mono_image_open (file, NULL);
1971 if (image == NULL) {
1972 /* The image is wrong or the file was not found. In this case return
1973 * a default runtime and leave to the initialization method the work of
1974 * reporting the error.
1976 runtime = get_runtime_by_version (DEFAULT_RUNTIME_VERSION);
1977 runtimes = g_slist_prepend (runtimes, (gpointer)runtime);
1978 return runtimes;
1981 *out_image = image;
1983 runtime = get_runtime_by_version (image->version);
1984 if (runtime != NULL)
1985 runtimes = g_slist_prepend (runtimes, (gpointer)runtime);
1986 return runtimes;
1991 * mono_get_runtime_info:
1993 * Returns: the version of the current runtime instance.
1995 const MonoRuntimeInfo*
1996 mono_get_runtime_info (void)
1998 return current_runtime;
2002 * mono_framework_version:
2004 * Return the major version of the framework curently executing.
2007 mono_framework_version (void)
2009 return current_runtime->framework_version [0] - '0';
2012 void
2013 mono_enable_debug_domain_unload (gboolean enable)
2015 debug_domain_unload = enable;
2018 MonoAotCacheConfig *
2019 mono_get_aot_cache_config (void)
2021 return &aot_cache_config;
2024 void
2025 mono_domain_lock (MonoDomain *domain)
2027 mono_locks_coop_acquire (&domain->lock, DomainLock);
2030 void
2031 mono_domain_unlock (MonoDomain *domain)
2033 mono_locks_coop_release (&domain->lock, DomainLock);
2036 GPtrArray*
2037 mono_domain_get_assemblies (MonoDomain *domain, gboolean refonly)
2039 GSList *tmp;
2040 GPtrArray *assemblies;
2041 MonoAssembly *ass;
2043 assemblies = g_ptr_array_new ();
2044 mono_domain_assemblies_lock (domain);
2045 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
2046 ass = (MonoAssembly *)tmp->data;
2047 gboolean ass_ref_only = mono_asmctx_get_kind (&ass->context) == MONO_ASMCTX_REFONLY;
2048 if (refonly != ass_ref_only)
2049 continue;
2050 if (ass->corlib_internal)
2051 continue;
2052 g_ptr_array_add (assemblies, ass);
2054 mono_domain_assemblies_unlock (domain);
2055 return assemblies;
2058 MonoAssemblyLoadContext *
2059 mono_domain_default_alc (MonoDomain *domain)
2061 #ifndef ENABLE_NETCORE
2062 return NULL;
2063 #else
2064 return domain->default_alc;
2065 #endif
2068 #ifdef ENABLE_NETCORE
2069 static inline void
2070 mono_domain_alcs_lock (MonoDomain *domain)
2072 mono_coop_mutex_lock (&domain->alcs_lock);
2075 static inline void
2076 mono_domain_alcs_unlock (MonoDomain *domain)
2078 mono_coop_mutex_unlock (&domain->alcs_lock);
2080 #endif
2083 static MonoAssemblyLoadContext *
2084 create_alc (MonoDomain *domain, gboolean is_default)
2086 #ifdef ENABLE_NETCORE
2087 MonoAssemblyLoadContext *alc = NULL;
2089 mono_domain_alcs_lock (domain);
2090 if (is_default && domain->default_alc)
2091 goto leave;
2093 alc = g_new0 (MonoAssemblyLoadContext, 1);
2094 mono_alc_init (alc, domain);
2096 domain->alcs = g_slist_prepend (domain->alcs, alc);
2097 if (is_default)
2098 domain->default_alc = alc;
2099 leave:
2100 mono_domain_alcs_unlock (domain);
2101 return alc;
2102 #else
2103 return NULL;
2104 #endif
2107 void
2108 mono_domain_create_default_alc (MonoDomain *domain)
2110 #ifdef ENABLE_NETCORE
2111 if (domain->default_alc)
2112 return;
2113 create_alc (domain, TRUE);
2114 #endif
2117 #ifdef ENABLE_NETCORE
2118 MonoAssemblyLoadContext *
2119 mono_domain_create_individual_alc (MonoDomain *domain, uint32_t this_gchandle, gboolean collectible, MonoError *error)
2121 g_assert (!collectible); /* TODO: implement collectible ALCs */
2122 MonoAssemblyLoadContext *alc = create_alc (domain, FALSE);
2123 alc->gchandle = this_gchandle;
2124 return alc;
2126 #endif
2128 static void
2129 mono_alc_free (MonoAssemblyLoadContext *alc)
2131 #ifdef ENABLE_NETCORE
2132 mono_alc_cleanup (alc);
2133 g_free (alc);
2134 #endif
2137 void
2138 mono_domain_alcs_destroy (MonoDomain *domain)
2140 #ifdef ENABLE_NETCORE
2141 mono_domain_alcs_lock (domain);
2142 GSList *alcs = domain->alcs;
2143 domain->alcs = NULL;
2144 domain->default_alc = NULL;
2145 mono_domain_alcs_unlock (domain);
2147 for (GSList *iter = alcs; iter; iter = g_slist_next (iter)) {
2148 mono_alc_free ((MonoAssemblyLoadContext*)iter->data);
2150 #endif