2009-12-10 Mark Probst <mark.probst@gmail.com>
[mono.git] / mono / metadata / domain.c
index c2ab6697fb6ec6c7c7fc0f1e9709cf4f0bf3114c..77985657b6efd296d271ac01e27b8a9f61d21940 100644 (file)
@@ -5,7 +5,8 @@
  *     Dietmar Maurer (dietmar@ximian.com)
  *     Patrik Torstensson
  *
- * (C) 2001 Ximian, Inc.
+ * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
+ * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
  */
 
 #include <config.h>
@@ -25,7 +26,6 @@
 #include <mono/metadata/class-internals.h>
 #include <mono/metadata/assembly.h>
 #include <mono/metadata/exception.h>
-#include <mono/metadata/rawbuffer.h>
 #include <mono/metadata/metadata-internals.h>
 #include <mono/metadata/gc-internal.h>
 #include <mono/metadata/appdomain.h>
@@ -34,6 +34,7 @@
 #include <mono/metadata/threads-types.h>
 #include <metadata/threads.h>
 #include <metadata/profiler-private.h>
+#include <mono/metadata/coree.h>
 
 /* #define DEBUG_DOMAIN_UNLOAD */
 
  * but we can't depend on this).
  */
 static guint32 appdomain_thread_id = -1;
+
+/* 
+ * Avoid calling TlsSetValue () if possible, since in the io-layer, it acquires
+ * a global lock (!) so it is a contention point.
+ */
+#if (defined(__i386__) || defined(__x86_64__)) && !defined(HOST_WIN32)
+#define NO_TLS_SET_VALUE
+#endif
  
 #ifdef HAVE_KW_THREAD
+
 static __thread MonoDomain * tls_appdomain MONO_TLS_FAST;
+
 #define GET_APPDOMAIN() tls_appdomain
+
+#ifdef NO_TLS_SET_VALUE
+#define SET_APPDOMAIN(x) do { \
+       tls_appdomain = x; \
+} while (FALSE)
+#else
 #define SET_APPDOMAIN(x) do { \
        tls_appdomain = x; \
        TlsSetValue (appdomain_thread_id, x); \
 } while (FALSE)
+#endif
 
-#else
+#else /* !HAVE_KW_THREAD */
 
 #define GET_APPDOMAIN() ((MonoDomain *)TlsGetValue (appdomain_thread_id))
 #define SET_APPDOMAIN(x) TlsSetValue (appdomain_thread_id, x);
 
 #endif
 
-#define GET_APPCONTEXT() (mono_thread_current ()->current_appcontext)
-#define SET_APPCONTEXT(x) MONO_OBJECT_SETREF (mono_thread_current (), current_appcontext, (x))
+#define GET_APPCONTEXT() (mono_thread_internal_current ()->current_appcontext)
+#define SET_APPCONTEXT(x) MONO_OBJECT_SETREF (mono_thread_internal_current (), current_appcontext, (x))
 
 static guint16 appdomain_list_size = 0;
 static guint16 appdomain_next = 0;
 static MonoDomain **appdomains_list = NULL;
 static MonoImage *exe_image;
 
+gboolean mono_dont_free_domains;
+
 #define mono_appdomains_lock() EnterCriticalSection (&appdomains_mutex)
 #define mono_appdomains_unlock() LeaveCriticalSection (&appdomains_mutex)
 static CRITICAL_SECTION appdomains_mutex;
@@ -112,12 +132,17 @@ static const MonoRuntimeInfo supported_runtimes[] = {
        {"v1.1.4322", "1.0", { {1,0,5000,0}, {7,0,5000,0} }     },
        {"v2.0.50215","2.0", { {2,0,0,0},    {8,0,0,0} }        },
        {"v2.0.50727","2.0", { {2,0,0,0},    {8,0,0,0} }        },
+       {"v4.0.21006","4.0", { {4,0,0,0},    {10,0,0,0} }   },
        {"moonlight", "2.1", { {2,0,5,0},    {9,0,0,0} }    },
 };
 
 
 /* The stable runtime version */
-#define DEFAULT_RUNTIME_VERSION "v1.1.4322"
+#define DEFAULT_RUNTIME_VERSION "v2.0.50727"
+
+/* Callbacks installed by the JIT */
+static MonoCreateDomainFunc create_domain_hook;
+static MonoFreeDomainFunc free_domain_hook;
 
 /* This is intentionally not in the header file, so people don't misuse it. */
 extern void _mono_debug_init_corlib (MonoDomain *domain);
@@ -134,7 +159,12 @@ mono_jit_info_find_aot_module (guint8* addr);
 guint32
 mono_domain_get_tls_key (void)
 {
+#ifdef NO_TLS_SET_VALUE
+       g_assert_not_reached ();
+       return 0;
+#else
        return appdomain_thread_id;
+#endif
 }
 
 gint32
@@ -154,7 +184,8 @@ mono_domain_get_tls_offset (void)
 #define JIT_INFO_TABLE_LOW_WATERMARK(n)                ((n) / 2)
 #define JIT_INFO_TABLE_HIGH_WATERMARK(n)       ((n) * 5 / 6)
 
-#define IS_JIT_INFO_TOMBSTONE(ji)      ((ji)->method == NULL)
+#define JIT_INFO_TOMBSTONE_MARKER      ((MonoMethod*)NULL)
+#define IS_JIT_INFO_TOMBSTONE(ji)      ((ji)->method == JIT_INFO_TOMBSTONE_MARKER)
 
 #define JIT_INFO_TABLE_HAZARD_INDEX            0
 #define JIT_INFO_HAZARD_INDEX                  1
@@ -189,10 +220,11 @@ jit_info_table_new_chunk (void)
 }
 
 static MonoJitInfoTable *
-jit_info_table_new (void)
+jit_info_table_new (MonoDomain *domain)
 {
-       MonoJitInfoTable *table = g_malloc0 (sizeof (MonoJitInfoTable) + sizeof (MonoJitInfoTableChunk*));
+       MonoJitInfoTable *table = g_malloc0 (MONO_SIZEOF_JIT_INFO_TABLE + sizeof (MonoJitInfoTableChunk*));
 
+       table->domain = domain;
        table->num_chunks = 1;
        table->chunks [0] = jit_info_table_new_chunk ();
 
@@ -204,6 +236,20 @@ jit_info_table_free (MonoJitInfoTable *table)
 {
        int i;
        int num_chunks = table->num_chunks;
+       MonoDomain *domain = table->domain;
+
+       mono_domain_lock (domain);
+
+       table->domain->num_jit_info_tables--;
+       if (table->domain->num_jit_info_tables <= 1) {
+               GSList *list;
+
+               for (list = table->domain->jit_info_free_queue; list; list = list->next)
+                       g_free (list->data);
+
+               g_slist_free (table->domain->jit_info_free_queue);
+               table->domain->jit_info_free_queue = NULL;
+       }
 
        /* At this point we assume that there are no other threads
           still accessing the table, so we don't have to worry about
@@ -228,6 +274,8 @@ jit_info_table_free (MonoJitInfoTable *table)
                g_free (chunk);
        }
 
+       mono_domain_unlock (domain);
+
        g_free (table);
 }
 
@@ -377,13 +425,14 @@ mono_jit_info_table_find (MonoDomain *domain, char *addr)
                           beyond what we're looking for, we have to end the
                           search. */
                        if ((gint8*)addr < (gint8*)ji->code_start)
-                               break;
+                               goto not_found;
                }
 
                ++chunk_pos;
                pos = 0;
-        } while (chunk_pos < table->num_chunks);
+       } while (chunk_pos < table->num_chunks);
 
+ not_found:
        mono_hazard_pointer_clear (hp, JIT_INFO_TABLE_HAZARD_INDEX);
        mono_hazard_pointer_clear (hp, JIT_INFO_HAZARD_INDEX);
 
@@ -458,7 +507,8 @@ jit_info_table_realloc (MonoJitInfoTable *old)
        required_size = (int)((long)num_elements * JIT_INFO_TABLE_FILL_RATIO_DENOM / JIT_INFO_TABLE_FILL_RATIO_NOM);
        num_chunks = (required_size + MONO_JIT_INFO_TABLE_CHUNK_SIZE - 1) / MONO_JIT_INFO_TABLE_CHUNK_SIZE;
 
-       new = g_malloc (sizeof (MonoJitInfoTable) + sizeof (MonoJitInfoTableChunk*) * num_chunks);
+       new = g_malloc (MONO_SIZEOF_JIT_INFO_TABLE + sizeof (MonoJitInfoTableChunk*) * num_chunks);
+       new->domain = old->domain;
        new->num_chunks = num_chunks;
 
        for (i = 0; i < num_chunks; ++i)
@@ -526,10 +576,11 @@ jit_info_table_split_chunk (MonoJitInfoTableChunk *chunk, MonoJitInfoTableChunk
 static MonoJitInfoTable*
 jit_info_table_copy_and_split_chunk (MonoJitInfoTable *table, MonoJitInfoTableChunk *chunk)
 {
-       MonoJitInfoTable *new_table = g_malloc (sizeof (MonoJitInfoTable)
+       MonoJitInfoTable *new_table = g_malloc (MONO_SIZEOF_JIT_INFO_TABLE
                + sizeof (MonoJitInfoTableChunk*) * (table->num_chunks + 1));
        int i, j;
 
+       new_table->domain = table->domain;
        new_table->num_chunks = table->num_chunks + 1;
 
        j = 0;
@@ -573,10 +624,11 @@ jit_info_table_purify_chunk (MonoJitInfoTableChunk *old)
 static MonoJitInfoTable*
 jit_info_table_copy_and_purify_chunk (MonoJitInfoTable *table, MonoJitInfoTableChunk *chunk)
 {
-       MonoJitInfoTable *new_table = g_malloc (sizeof (MonoJitInfoTable)
+       MonoJitInfoTable *new_table = g_malloc (MONO_SIZEOF_JIT_INFO_TABLE
                + sizeof (MonoJitInfoTableChunk*) * table->num_chunks);
        int i, j;
 
+       new_table->domain = table->domain;
        new_table->num_chunks = table->num_chunks;
 
        j = 0;
@@ -680,6 +732,7 @@ mono_jit_info_table_add (MonoDomain *domain, MonoJitInfo *ji)
 
                domain->jit_info_table = new_table;
                mono_memory_barrier ();
+               domain->num_jit_info_tables++;
                mono_thread_hazardous_free_or_queue (table, (MonoHazardousFreeFunc)jit_info_table_free);
                table = new_table;
 
@@ -730,11 +783,26 @@ mono_jit_info_make_tombstone (MonoJitInfo *ji)
 
        tombstone->code_start = ji->code_start;
        tombstone->code_size = ji->code_size;
-       tombstone->method = NULL;
+       tombstone->method = JIT_INFO_TOMBSTONE_MARKER;
 
        return tombstone;
 }
 
+/*
+ * LOCKING: domain lock
+ */
+static void
+mono_jit_info_free_or_queue (MonoDomain *domain, MonoJitInfo *ji)
+{
+       if (domain->num_jit_info_tables <= 1) {
+               /* Can it actually happen that we only have one table
+                  but ji is still hazardous? */
+               mono_thread_hazardous_free_or_queue (ji, g_free);
+       } else {
+               domain->jit_info_free_queue = g_slist_prepend (domain->jit_info_free_queue, ji);
+       }
+}
+
 void
 mono_jit_info_table_remove (MonoDomain *domain, MonoJitInfo *ji)
 {
@@ -779,6 +847,8 @@ mono_jit_info_table_remove (MonoDomain *domain, MonoJitInfo *ji)
        /* Debugging code, should be removed. */
        //jit_info_table_check (table);
 
+       mono_jit_info_free_or_queue (domain, ji);
+
        mono_domain_unlock (domain);
 }
 
@@ -955,6 +1025,18 @@ mono_jit_info_set_generic_sharing_context (MonoJitInfo *ji, MonoGenericSharingCo
 
        gi->generic_sharing_context = gsctx;
 }
+void
+mono_install_create_domain_hook (MonoCreateDomainFunc func)
+{
+       create_domain_hook = func;
+}
+
+void
+mono_install_free_domain_hook (MonoFreeDomainFunc func)
+{
+       free_domain_hook = func;
+}
 
 /**
  * mono_string_equal:
@@ -1101,6 +1183,8 @@ mono_domain_create (void)
        domain->friendly_name = NULL;
        domain->search_path = NULL;
 
+       mono_gc_register_root ((char*)&(domain->MONO_DOMAIN_FIRST_GC_TRACKED), G_STRUCT_OFFSET (MonoDomain, MONO_DOMAIN_LAST_GC_TRACKED) - G_STRUCT_OFFSET (MonoDomain, MONO_DOMAIN_FIRST_GC_TRACKED), NULL);
+
        mono_profiler_appdomain_event (domain, MONO_PROFILE_START_LOAD);
 
        domain->mp = mono_mempool_new ();
@@ -1111,25 +1195,34 @@ mono_domain_create (void)
        domain->proxy_vtable_hash = g_hash_table_new ((GHashFunc)mono_ptrarray_hash, (GCompareFunc)mono_ptrarray_equal);
        domain->static_data_array = NULL;
        mono_jit_code_hash_init (&domain->jit_code_hash);
-       domain->ldstr_table = mono_g_hash_table_new ((GHashFunc)mono_string_hash, (GCompareFunc)mono_string_equal);
-       domain->jit_info_table = jit_info_table_new ();
-       domain->class_init_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
-       domain->jump_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
+       domain->ldstr_table = mono_g_hash_table_new_type ((GHashFunc)mono_string_hash, (GCompareFunc)mono_string_equal, MONO_HASH_KEY_VALUE_GC);
+       domain->num_jit_info_tables = 1;
+       domain->jit_info_table = jit_info_table_new (domain);
+       domain->jit_info_free_queue = NULL;
        domain->finalizable_objects_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
-       domain->jit_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
-       domain->delegate_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
+#ifndef HAVE_SGEN_GC
+       domain->track_resurrection_handles_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
+#endif
 
        InitializeCriticalSection (&domain->lock);
        InitializeCriticalSection (&domain->assemblies_lock);
+       InitializeCriticalSection (&domain->jit_code_hash_lock);
+       InitializeCriticalSection (&domain->finalizable_objects_hash_lock);
 
-       domain->shared_generics_hash = NULL;
-
-       mono_debug_domain_create (domain);
+       domain->method_rgctx_hash = NULL;
 
        mono_appdomains_lock ();
        domain_id_alloc (domain);
        mono_appdomains_unlock ();
 
+       mono_perfcounters->loader_appdomains++;
+       mono_perfcounters->loader_total_appdomains++;
+
+       mono_debug_domain_create (domain);
+
+       if (create_domain_hook)
+               create_domain_hook (domain);
+
        mono_profiler_appdomain_loaded (domain, MONO_PROFILE_OK);
        
        return domain;
@@ -1160,6 +1253,13 @@ mono_init_internal (const char *filename, const char *exe_filename, const char *
        if (domain)
                g_assert_not_reached ();
 
+#ifdef HOST_WIN32
+       /* Avoid system error message boxes. */
+       SetErrorMode (SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
+
+       mono_load_coree (exe_filename);
+#endif
+
        mono_perfcounters_init ();
 
        mono_counters_register ("Max native code in a domain", MONO_COUNTER_INT|MONO_COUNTER_JIT, &max_domain_code_size);
@@ -1173,7 +1273,6 @@ mono_init_internal (const char *filename, const char *exe_filename, const char *
        InitializeCriticalSection (&appdomains_mutex);
 
        mono_metadata_init ();
-       mono_raw_buffer_init ();
        mono_images_init ();
        mono_assemblies_init ();
        mono_classes_init ();
@@ -1196,6 +1295,14 @@ mono_init_internal (const char *filename, const char *exe_filename, const char *
                 * exe_image, and close it during shutdown.
                 */
                get_runtimes_from_exe (exe_filename, &exe_image, runtimes);
+#ifdef HOST_WIN32
+               if (!exe_image) {
+                       exe_image = mono_assembly_open_from_bundle (exe_filename, NULL, FALSE);
+                       if (!exe_image)
+                               exe_image = mono_image_open (exe_filename, NULL);
+               }
+               mono_fixup_exe_image (exe_image);
+#endif
        } else if (runtime_version != NULL) {
                runtimes [0] = get_runtime_by_version (runtime_version);
                runtimes [1] = NULL;
@@ -1206,7 +1313,7 @@ mono_init_internal (const char *filename, const char *exe_filename, const char *
                runtimes [0] = default_runtime;
                runtimes [1] = NULL;
                g_print ("WARNING: The runtime version supported by this application is unavailable.\n");
-               g_print ("Using default runtime: %s\n", default_runtime->runtime_version);
+               g_print ("Using default runtime: %s\n", default_runtime->runtime_version); 
        }
 
        /* The selected runtime will be the first one for which there is a mscrolib.dll */
@@ -1219,8 +1326,8 @@ mono_init_internal (const char *filename, const char *exe_filename, const char *
        }
        
        /* Now that we have a runtime, set the policy for unhandled exceptions */
-       if (mono_get_runtime_info ()->framework_version [0] < '2') {
-               mono_runtime_unhandled_exception_policy_set (MONO_UNHANLED_POLICY_LEGACY);
+       if (mono_framework_version () < 2) {
+               mono_runtime_unhandled_exception_policy_set (MONO_UNHANDLED_POLICY_LEGACY);
        }
 
        if ((status != MONO_IMAGE_OK) || (ass == NULL)) {
@@ -1338,9 +1445,9 @@ mono_init_internal (const char *filename, const char *exe_filename, const char *
                "AsyncResult");
        g_assert (mono_defaults.asyncresult_class != 0 );
 
-       mono_defaults.waithandle_class = mono_class_from_name (
-               mono_defaults.corlib, "System.Threading", "WaitHandle");
-       g_assert (mono_defaults.waithandle_class != 0 );
+       mono_defaults.manualresetevent_class = mono_class_from_name (
+               mono_defaults.corlib, "System.Threading", "ManualResetEvent");
+       g_assert (mono_defaults.manualresetevent_class != 0 );
 
        mono_defaults.typehandle_class = mono_class_from_name (
                 mono_defaults.corlib, "System", "RuntimeTypeHandle");
@@ -1374,6 +1481,16 @@ mono_init_internal (const char *filename, const char *exe_filename, const char *
                 mono_defaults.corlib, "System.Threading", "Thread");
        g_assert (mono_defaults.thread_class != 0);
 
+       mono_defaults.internal_thread_class = mono_class_from_name (
+                mono_defaults.corlib, "System.Threading", "InternalThread");
+       if (!mono_defaults.internal_thread_class) {
+               /* This can happen with an old mscorlib */
+               fprintf (stderr, "Corlib too old for this runtime.\n");
+               fprintf (stderr, "Loaded from: %s\n",
+                                mono_defaults.corlib? mono_image_get_filename (mono_defaults.corlib): "unknown");
+               exit (1);
+       }
+
        mono_defaults.appdomain_class = mono_class_from_name (
                 mono_defaults.corlib, "System", "AppDomain");
        g_assert (mono_defaults.appdomain_class != 0);
@@ -1459,6 +1576,9 @@ mono_init_internal (const char *filename, const char *exe_filename, const char *
        mono_defaults.internals_visible_class = mono_class_from_name (
                mono_defaults.corlib, "System.Runtime.CompilerServices", "InternalsVisibleToAttribute");
 
+       mono_defaults.critical_finalizer_object = mono_class_from_name (
+               mono_defaults.corlib, "System.Runtime.ConstrainedExecution", "CriticalFinalizerObject");
+
        /*
         * mscorlib needs a little help, only now it can load its friends list (after we have
         * loaded the InternalsVisibleToAttribute), load it now
@@ -1599,21 +1719,26 @@ mono_init_com_types (void)
 void
 mono_cleanup (void)
 {
-       if (exe_image)
-               mono_image_close (exe_image);
+       mono_close_exe_image ();
 
        mono_loader_cleanup ();
        mono_classes_cleanup ();
        mono_assemblies_cleanup ();
        mono_images_cleanup ();
        mono_debug_cleanup ();
-       mono_raw_buffer_cleanup ();
        mono_metadata_cleanup ();
 
        TlsFree (appdomain_thread_id);
        DeleteCriticalSection (&appdomains_mutex);
 }
 
+void
+mono_close_exe_image (void)
+{
+       if (exe_image)
+               mono_image_close (exe_image);
+}
+
 /**
  * mono_get_root_domain:
  *
@@ -1642,6 +1767,34 @@ mono_domain_get ()
        return GET_APPDOMAIN ();
 }
 
+void
+mono_domain_unset (void)
+{
+       SET_APPDOMAIN (NULL);
+}
+
+void
+mono_domain_set_internal_with_options (MonoDomain *domain, gboolean migrate_exception)
+{
+       MonoInternalThread *thread;
+
+       if (mono_domain_get () == domain)
+               return;
+
+       SET_APPDOMAIN (domain);
+       SET_APPCONTEXT (domain->default_context);
+
+       if (migrate_exception) {
+               thread = mono_thread_internal_current ();
+               if (!thread->abort_exc)
+                       return;
+
+               g_assert (thread->abort_exc->object.vtable->domain != domain);
+               MONO_OBJECT_SETREF (thread, abort_exc, mono_get_exception_thread_abort ());
+               g_assert (thread->abort_exc->object.vtable->domain == domain);
+       }
+}
+
 /**
  * mono_domain_set_internal:
  * @domain: the new domain
@@ -1651,8 +1804,7 @@ mono_domain_get ()
 void
 mono_domain_set_internal (MonoDomain *domain)
 {
-       SET_APPDOMAIN (domain);
-       SET_APPCONTEXT (domain->default_context);
+       mono_domain_set_internal_with_options (domain, TRUE);
 }
 
 void
@@ -1690,6 +1842,7 @@ mono_domain_foreach (MonoDomainFunc func, gpointer user_data)
 MonoAssembly *
 mono_domain_assembly_open (MonoDomain *domain, const char *name)
 {
+       MonoDomain *current;
        MonoAssembly *ass;
        GSList *tmp;
 
@@ -1703,42 +1856,21 @@ mono_domain_assembly_open (MonoDomain *domain, const char *name)
        }
        mono_domain_assemblies_unlock (domain);
 
-       if (!(ass = mono_assembly_open (name, NULL)))
-               return NULL;
-
-       return ass;
-}
-
-MonoJitInfo*
-mono_domain_lookup_shared_generic (MonoDomain *domain, MonoMethod *method)
-{
-       if (!domain->shared_generics_hash)
-               return NULL;
-
-       return g_hash_table_lookup (domain->shared_generics_hash, method);
-}
-
-void
-mono_domain_register_shared_generic (MonoDomain *domain, MonoMethod *method, MonoJitInfo *jit_info)
-{
-       if (!domain->shared_generics_hash)
-               domain->shared_generics_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
-
-       g_assert (domain->shared_generics_hash);
+       if (domain != mono_domain_get ()) {
+               current = mono_domain_get ();
 
-       g_hash_table_insert (domain->shared_generics_hash, method, jit_info);
-}
+               mono_domain_set (domain, FALSE);
+               ass = mono_assembly_open (name, NULL);
+               mono_domain_set (current, FALSE);
+       } else {
+               ass = mono_assembly_open (name, NULL);
+       }
 
-static void
-dynamic_method_info_free (gpointer key, gpointer value, gpointer user_data)
-{
-       MonoJitDynamicMethodInfo *di = value;
-       mono_code_manager_destroy (di->code_mp);
-       g_free (di);
+       return ass;
 }
 
 static void
-delete_jump_list (gpointer key, gpointer value, gpointer user_data)
+free_slist (gpointer key, gpointer value, gpointer user_data)
 {
        g_slist_free (value);
 }
@@ -1753,44 +1885,83 @@ mono_domain_free (MonoDomain *domain, gboolean force)
                return;
        }
 
+       if (mono_dont_free_domains)
+               return;
+
        mono_profiler_appdomain_event (domain, MONO_PROFILE_START_UNLOAD);
 
+       if (free_domain_hook)
+               free_domain_hook (domain);
+
        mono_debug_domain_unload (domain);
 
        mono_appdomains_lock ();
        appdomains_list [domain->domain_id] = NULL;
        mono_appdomains_unlock ();
 
-       /* FIXME: free delegate_hash_table when it's used */
-       if (domain->search_path) {
-               g_strfreev (domain->search_path);
-               domain->search_path = NULL;
-       }
-       domain->create_proxy_for_type_method = NULL;
-       domain->private_invoke_method = NULL;
-       domain->default_context = NULL;
-       domain->out_of_memory_ex = NULL;
-       domain->null_reference_ex = NULL;
-       domain->stack_overflow_ex = NULL;
-       domain->entry_assembly = NULL;
        /* must do this early as it accesses fields and types */
        if (domain->special_static_fields) {
                mono_alloc_special_static_data_free (domain->special_static_fields);
                g_hash_table_destroy (domain->special_static_fields);
                domain->special_static_fields = NULL;
        }
+
+       /*
+        * We must destroy all these hash tables here because they
+        * contain references to managed objects belonging to the
+        * domain.  Once we let the GC clear the domain there must be
+        * no more such references, or we'll crash if a collection
+        * occurs.
+        */
+       mono_g_hash_table_destroy (domain->ldstr_table);
+       domain->ldstr_table = NULL;
+
+       mono_g_hash_table_destroy (domain->env);
+       domain->env = NULL;
+
+       mono_reflection_cleanup_domain (domain);
+
+       if (domain->type_hash) {
+               mono_g_hash_table_destroy (domain->type_hash);
+               domain->type_hash = NULL;
+       }
+       if (domain->type_init_exception_hash) {
+               mono_g_hash_table_destroy (domain->type_init_exception_hash);
+               domain->type_init_exception_hash = NULL;
+       }
+
        for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
                MonoAssembly *ass = tmp->data;
                mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading domain %s %p, assembly %s %p, refcount=%d\n", domain->friendly_name, domain, ass->aname.name, ass, ass->ref_count);
-               mono_assembly_close (ass);
+               if (!mono_assembly_close_except_image_pools (ass))
+                       tmp->data = NULL;
+       }
+
+       mono_gc_clear_domain (domain);
+
+       for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
+               MonoAssembly *ass = tmp->data;
+               if (ass)
+                       mono_assembly_close_finish (ass);
        }
        g_slist_free (domain->domain_assemblies);
        domain->domain_assemblies = NULL;
 
+       /* FIXME: free delegate_hash_table when it's used */
+       if (domain->search_path) {
+               g_strfreev (domain->search_path);
+               domain->search_path = NULL;
+       }
+       domain->create_proxy_for_type_method = NULL;
+       domain->private_invoke_method = NULL;
+       domain->default_context = NULL;
+       domain->out_of_memory_ex = NULL;
+       domain->null_reference_ex = NULL;
+       domain->stack_overflow_ex = NULL;
+       domain->entry_assembly = NULL;
+
        g_free (domain->friendly_name);
        domain->friendly_name = NULL;
-       mono_g_hash_table_destroy (domain->env);
-       domain->env = NULL;
        g_hash_table_destroy (domain->class_vtable_hash);
        domain->class_vtable_hash = NULL;
        g_hash_table_destroy (domain->proxy_vtable_hash);
@@ -1800,15 +1971,17 @@ mono_domain_free (MonoDomain *domain, gboolean force)
                domain->static_data_array = NULL;
        }
        mono_internal_hash_table_destroy (&domain->jit_code_hash);
-       if (domain->dynamic_code_hash) {
-               g_hash_table_foreach (domain->dynamic_code_hash, dynamic_method_info_free, NULL);
-               g_hash_table_destroy (domain->dynamic_code_hash);
-               domain->dynamic_code_hash = NULL;
-       }
-       mono_g_hash_table_destroy (domain->ldstr_table);
-       domain->ldstr_table = NULL;
+
+       /*
+        * There might still be jit info tables of this domain which
+        * are not freed.  Since the domain cannot be in use anymore,
+        * this will free them.
+        */
+       mono_thread_hazardous_try_free_all ();
+       g_assert (domain->num_jit_info_tables == 1);
        jit_info_table_free (domain->jit_info_table);
        domain->jit_info_table = NULL;
+       g_assert (!domain->jit_info_free_queue);
 
        /* collect statistics */
        code_alloc = mono_code_manager_size (domain->code_mp, &code_size);
@@ -1816,59 +1989,52 @@ mono_domain_free (MonoDomain *domain, gboolean force)
        max_domain_code_alloc = MAX (max_domain_code_alloc, code_alloc);
        max_domain_code_size = MAX (max_domain_code_size, code_size);
 
-       mono_class_unregister_domain_generic_vtables (domain);
-
 #ifdef DEBUG_DOMAIN_UNLOAD
        mono_mempool_invalidate (domain->mp);
        mono_code_manager_invalidate (domain->code_mp);
 #else
+       mono_perfcounters->loader_bytes -= mono_mempool_get_allocated (domain->mp);
        mono_mempool_destroy (domain->mp);
        domain->mp = NULL;
        mono_code_manager_destroy (domain->code_mp);
        domain->code_mp = NULL;
 #endif 
-       if (domain->jump_target_hash) {
-               g_hash_table_foreach (domain->jump_target_hash, delete_jump_list, NULL);
-               g_hash_table_destroy (domain->jump_target_hash);
-               domain->jump_target_hash = NULL;
-       }
-       if (domain->type_hash) {
-               mono_g_hash_table_destroy (domain->type_hash);
-               domain->type_hash = NULL;
-       }
-       if (domain->refobject_hash) {
-               mono_g_hash_table_destroy (domain->refobject_hash);
-               domain->refobject_hash = NULL;
-       }
-       if (domain->type_init_exception_hash) {
-               mono_g_hash_table_destroy (domain->type_init_exception_hash);
-               domain->type_init_exception_hash = NULL;
-       }
-       g_hash_table_destroy (domain->class_init_trampoline_hash);
-       domain->class_init_trampoline_hash = NULL;
-       g_hash_table_destroy (domain->jump_trampoline_hash);
-       domain->jump_trampoline_hash = NULL;
+
        g_hash_table_destroy (domain->finalizable_objects_hash);
        domain->finalizable_objects_hash = NULL;
-       g_hash_table_destroy (domain->jit_trampoline_hash);
-       domain->jit_trampoline_hash = NULL;
-       g_hash_table_destroy (domain->delegate_trampoline_hash);
-       domain->delegate_trampoline_hash = NULL;
-       if (domain->shared_generics_hash) {
-               g_hash_table_destroy (domain->shared_generics_hash);
-               domain->shared_generics_hash = NULL;
+#ifndef HAVE_SGEN_GC
+       if (domain->track_resurrection_objects_hash) {
+               g_hash_table_foreach (domain->track_resurrection_objects_hash, free_slist, NULL);
+               g_hash_table_destroy (domain->track_resurrection_objects_hash);
+       }
+       if (domain->track_resurrection_handles_hash)
+               g_hash_table_destroy (domain->track_resurrection_handles_hash);
+#endif
+       if (domain->method_rgctx_hash) {
+               g_hash_table_destroy (domain->method_rgctx_hash);
+               domain->method_rgctx_hash = NULL;
+       }
+       if (domain->generic_virtual_cases) {
+               g_hash_table_destroy (domain->generic_virtual_cases);
+               domain->generic_virtual_cases = NULL;
        }
 
+       DeleteCriticalSection (&domain->finalizable_objects_hash_lock);
        DeleteCriticalSection (&domain->assemblies_lock);
+       DeleteCriticalSection (&domain->jit_code_hash_lock);
        DeleteCriticalSection (&domain->lock);
        domain->setup = NULL;
 
+       mono_gc_deregister_root ((char*)&(domain->MONO_DOMAIN_FIRST_GC_TRACKED));
+
        /* FIXME: anything else required ? */
 
        mono_profiler_appdomain_event (domain, MONO_PROFILE_END_UNLOAD);
 
        mono_gc_free_fixed (domain);
 
+       mono_perfcounters->loader_appdomains--;
+
        if ((domain == mono_root_domain))
                mono_root_domain = NULL;
 }
@@ -1900,6 +2066,107 @@ mono_domain_get_id (MonoDomain *domain)
        return domain->domain_id;
 }
 
+/*
+ * mono_domain_alloc:
+ *
+ * LOCKING: Acquires the domain lock.
+ */
+gpointer
+mono_domain_alloc (MonoDomain *domain, guint size)
+{
+       gpointer res;
+
+       mono_domain_lock (domain);
+       mono_perfcounters->loader_bytes += size;
+       res = mono_mempool_alloc (domain->mp, size);
+       mono_domain_unlock (domain);
+
+       return res;
+}
+
+/*
+ * mono_domain_alloc0:
+ *
+ * LOCKING: Acquires the domain lock.
+ */
+gpointer
+mono_domain_alloc0 (MonoDomain *domain, guint size)
+{
+       gpointer res;
+
+       mono_domain_lock (domain);
+       mono_perfcounters->loader_bytes += size;
+       res = mono_mempool_alloc0 (domain->mp, size);
+       mono_domain_unlock (domain);
+
+       return res;
+}
+
+/*
+ * mono_domain_code_reserve:
+ *
+ * LOCKING: Acquires the domain lock.
+ */
+void*
+mono_domain_code_reserve (MonoDomain *domain, int size)
+{
+       gpointer res;
+
+       mono_domain_lock (domain);
+       res = mono_code_manager_reserve (domain->code_mp, size);
+       mono_domain_unlock (domain);
+
+       return res;
+}
+
+/*
+ * mono_domain_code_reserve_align:
+ *
+ * LOCKING: Acquires the domain lock.
+ */
+void*
+mono_domain_code_reserve_align (MonoDomain *domain, int size, int alignment)
+{
+       gpointer res;
+
+       mono_domain_lock (domain);
+       res = mono_code_manager_reserve_align (domain->code_mp, size, alignment);
+       mono_domain_unlock (domain);
+
+       return res;
+}
+
+/*
+ * mono_domain_code_commit:
+ *
+ * LOCKING: Acquires the domain lock.
+ */
+void
+mono_domain_code_commit (MonoDomain *domain, void *data, int size, int newsize)
+{
+       mono_domain_lock (domain);
+       mono_code_manager_commit (domain->code_mp, data, size, newsize);
+       mono_domain_unlock (domain);
+}
+
+/*
+ * mono_domain_code_foreach:
+ * Iterate over the code thunks of the code manager of @domain.
+ * 
+ * The @func callback MUST not take any locks. If it really needs to, it must respect
+ * the locking rules of the runtime: http://www.mono-project.com/Mono:Runtime:Documentation:ThreadSafety 
+ * LOCKING: Acquires the domain lock.
+ */
+
+void
+mono_domain_code_foreach (MonoDomain *domain, MonoCodeManagerFunc func, void *user_data)
+{
+       mono_domain_lock (domain);
+       mono_code_manager_foreach (domain->code_mp, func, user_data);
+       mono_domain_unlock (domain);
+}
+
+
 void 
 mono_context_set (MonoAppContext * new_context)
 {
@@ -2147,7 +2414,6 @@ app_config_parse (const char *exe_filename)
        GMarkupParseContext *context;
        char *text;
        gsize len;
-       struct stat buf;
        const char *bundled_config;
        char *config_filename;
 
@@ -2159,11 +2425,6 @@ app_config_parse (const char *exe_filename)
        } else {
                config_filename = g_strconcat (exe_filename, ".config", NULL);
 
-               if (stat (config_filename, &buf) != 0) {
-                       g_free (config_filename);
-                       return NULL;
-               }
-       
                if (!g_file_get_contents (config_filename, &text, &len, NULL)) {
                        g_free (config_filename);
                        return NULL;
@@ -2304,3 +2565,15 @@ mono_debugger_check_runtime_version (const char *filename)
 
        return NULL;
 }
+
+/**
+ * mono_framework_version:
+ *
+ * Return the major version of the framework curently executing.
+ */
+int
+mono_framework_version (void)
+{
+       return current_runtime->framework_version [0] - '0';
+}
+