2010-05-07 Rodrigo Kumpera <rkumpera@novell.com>
[mono.git] / mono / metadata / appdomain.c
index 89096c5ff0dcca4747ae1f2c87f619e3b7567d4a..79cfcaa634a4724887fd418e7645e777027773fe 100644 (file)
 #include <mono/metadata/threads-types.h>
 #include <mono/metadata/tokentype.h>
 #include <mono/utils/mono-uri.h>
-#include <mono/utils/mono-logger.h>
+#include <mono/utils/mono-logger-internal.h>
 #include <mono/utils/mono-path.h>
 #include <mono/utils/mono-stdlib.h>
 #include <mono/utils/mono-io-portability.h>
 #include <mono/utils/mono-error-internals.h>
-
-#ifdef PLATFORM_WIN32
+#ifdef HOST_WIN32
 #include <direct.h>
 #endif
 
  * Changes which are already detected at runtime, like the addition
  * of icalls, do not require an increment.
  */
-#define MONO_CORLIB_VERSION 86
+#define MONO_CORLIB_VERSION 90
 
 typedef struct
 {
        int runtime_count;
        int assemblybinding_count;
        MonoDomain *domain;
+       gchar *filename;
 } RuntimeConfig;
 
 CRITICAL_SECTION mono_delegate_section;
@@ -139,13 +139,13 @@ mono_runtime_load (const char *filename, const char *runtime_version)
        return load_function (filename, runtime_version);
 }
 
-/*
+/**
  * mono_runtime_set_no_exec:
  *
- *   Instructs the runtime to operate in static mode, i.e. avoid/do not allow managed
- * code execution. This is useful for running the AOT compiler on platforms which
- * allow full-aot execution only.
- * This should be called before mono_runtime_init ().
+ * Instructs the runtime to operate in static mode, i.e. avoid/do not
+ * allow managed code execution. This is useful for running the AOT
+ * compiler on platforms which allow full-aot execution only.  This
+ * should be called before mono_runtime_init ().
  */
 void
 mono_runtime_set_no_exec (gboolean val)
@@ -153,12 +153,55 @@ mono_runtime_set_no_exec (gboolean val)
        no_exec = val;
 }
 
+/**
+ * mono_runtime_get_no_exec:
+ *
+ * If true, then the runtime will not allow managed code execution.
+ */
 gboolean
 mono_runtime_get_no_exec (void)
 {
        return no_exec;
 }
 
+static void
+create_exceptions (MonoDomain *domain)
+{
+       MonoDomain *old_domain = mono_domain_get ();
+       MonoString *arg;
+
+       if (domain != old_domain) {
+               mono_thread_push_appdomain_ref (domain);
+               mono_domain_set_internal_with_options (domain, FALSE);
+       }
+
+       /*
+        * Create an instance early since we can't do it when there is no memory.
+        */
+       arg = mono_string_new (domain, "Out of memory");
+       domain->out_of_memory_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "OutOfMemoryException", arg, NULL);
+
+       /* 
+        * These two are needed because the signal handlers might be executing on
+        * an alternate stack, and Boehm GC can't handle that.
+        */
+       arg = mono_string_new (domain, "A null value was found where an object instance was required");
+       domain->null_reference_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "NullReferenceException", arg, NULL);
+       arg = mono_string_new (domain, "The requested operation caused a stack overflow.");
+       domain->stack_overflow_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "StackOverflowException", arg, NULL);
+
+       if (domain != old_domain) {
+               mono_thread_pop_appdomain_ref ();
+               mono_domain_set_internal_with_options (old_domain, FALSE);
+       }
+
+       /* 
+        * This class is used during exception handling, so initialize it here, to prevent
+        * stack overflows while handling stack overflows.
+        */
+       mono_class_init (mono_array_class_get (mono_defaults.int_class, 1));
+}
+
 /**
  * mono_runtime_init:
  * @domain: domain returned by mono_init ()
@@ -178,7 +221,6 @@ mono_runtime_init (MonoDomain *domain, MonoThreadStartCB start_cb,
        MonoAppDomainSetup *setup;
        MonoAppDomain *ad;
        MonoClass *class;
-       MonoString *arg;
 
        mono_portability_helpers_init ();
        
@@ -220,22 +262,8 @@ mono_runtime_init (MonoDomain *domain, MonoThreadStartCB start_cb,
 
        mono_type_initialization_init ();
 
-       if (!mono_runtime_get_no_exec ()) {
-               /*
-                * Create an instance early since we can't do it when there is no memory.
-                */
-               arg = mono_string_new (domain, "Out of memory");
-               domain->out_of_memory_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "OutOfMemoryException", arg, NULL);
-       
-               /* 
-                * These two are needed because the signal handlers might be executing on
-                * an alternate stack, and Boehm GC can't handle that.
-                */
-               arg = mono_string_new (domain, "A null value was found where an object instance was required");
-               domain->null_reference_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "NullReferenceException", arg, NULL);
-               arg = mono_string_new (domain, "The requested operation caused a stack overflow.");
-               domain->stack_overflow_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "StackOverflowException", arg, NULL);
-       }
+       if (!mono_runtime_get_no_exec ())
+               create_exceptions (domain);
 
        /* GC init has to happen after thread init */
        mono_gc_init ();
@@ -273,6 +301,14 @@ mono_get_corlib_version (void)
        return *(gint32*)((gchar*)value + sizeof (MonoObject));
 }
 
+/**
+ * mono_check_corlib_version
+ *
+ * Checks that the corlib that is loaded matches the version of this runtime.
+ *
+ * Returns: NULL if the runtime will work with the corlib, or a g_malloc
+ * allocated string with the error otherwise.
+ */
 const char*
 mono_check_corlib_version (void)
 {
@@ -283,6 +319,12 @@ mono_check_corlib_version (void)
                return NULL;
 }
 
+/**
+ * mono_context_init:
+ * @domain: The domain where the System.Runtime.Remoting.Context.Context is initialized
+ *
+ * Initializes the @domain's default System.Runtime.Remoting's Context.
+ */
 void
 mono_context_init (MonoDomain *domain)
 {
@@ -326,7 +368,7 @@ mono_runtime_cleanup (MonoDomain *domain)
 
        mono_monitor_cleanup ();
 
-#ifndef PLATFORM_WIN32
+#ifndef HOST_WIN32
        _wapi_cleanup ();
 #endif
 }
@@ -461,12 +503,10 @@ mono_domain_create_appdomain_internal (char *friendly_name, MonoAppDomainSetup *
 
        mono_context_init (data);
 
+       data->setup = copy_app_domain_setup (data, setup);
        mono_set_private_bin_path_from_config (data);
-       
        add_assemblies_to_domain (data, mono_defaults.corlib->assembly, NULL);
 
-       data->setup = copy_app_domain_setup (data, setup);
-
 #ifndef DISABLE_SHADOW_COPY
        /*FIXME, guard this for when the debugger is not running */
        shadow_location = get_shadow_assembly_location_base (data, &error);
@@ -476,8 +516,7 @@ mono_domain_create_appdomain_internal (char *friendly_name, MonoAppDomainSetup *
        g_free (shadow_location);
 #endif
 
-       // FIXME: Initialize null_reference_ex and stack_overflow_ex
-       data->out_of_memory_ex = mono_exception_from_name_domain (data, mono_defaults.corlib, "System", "OutOfMemoryException");
+       create_exceptions (data);
 
        return ad;
 }
@@ -500,6 +539,10 @@ mono_domain_has_type_resolve (MonoDomain *domain)
                g_assert (field);
        }
 
+       /*pedump doesn't create an appdomin, so the domain object doesn't exist.*/
+       if (!domain->domain)
+               return FALSE;
+
        mono_field_get_value ((MonoObject*)(domain->domain), field, &o);
        return o != NULL;
 }
@@ -757,13 +800,25 @@ end_element (GMarkupParseContext *context,
                runtime_config->assemblybinding_count--;
 }
 
+static void
+parse_error   (GMarkupParseContext *context, GError *error, gpointer user_data)
+{
+       RuntimeConfig *state = user_data;
+       const gchar *msg;
+       const gchar *filename;
+
+       filename = state && state->filename ? (gchar *) state->filename : "<unknown>";
+       msg = error && error->message ? error->message : "";
+       g_warning ("Error parsing %s: %s", filename, msg);
+}
+
 static const GMarkupParser
 mono_parser = {
        start_element,
        end_element,
        NULL,
        NULL,
-       NULL
+       parse_error
 };
 
 void
@@ -774,6 +829,7 @@ mono_set_private_bin_path_from_config (MonoDomain *domain)
        gsize len;
        GMarkupParseContext *context;
        RuntimeConfig runtime_config;
+       gint offset;
        
        if (!domain || !domain->setup || !domain->setup->configuration_file)
                return;
@@ -788,17 +844,22 @@ mono_set_private_bin_path_from_config (MonoDomain *domain)
                g_free (config_file);
                return;
        }
-       g_free (config_file);
 
        runtime_config.runtime_count = 0;
        runtime_config.assemblybinding_count = 0;
        runtime_config.domain = domain;
+       runtime_config.filename = config_file;
        
+       offset = 0;
+       if (len > 3 && text [0] == '\xef' && text [1] == (gchar) '\xbb' && text [2] == '\xbf')
+               offset = 3; /* Skip UTF-8 BOM */
+
        context = g_markup_parse_context_new (&mono_parser, 0, &runtime_config, NULL);
-       if (g_markup_parse_context_parse (context, text, len, NULL))
+       if (g_markup_parse_context_parse (context, text + offset, len - offset, NULL))
                g_markup_parse_context_end_parse (context, NULL);
        g_markup_parse_context_free (context);
        g_free (text);
+       g_free (config_file);
 }
 
 MonoAppDomain *
@@ -893,12 +954,17 @@ mono_domain_assembly_postload_search (MonoAssemblyName *aname,
        MonoReflectionAssembly *assembly;
        MonoDomain *domain = mono_domain_get ();
        char *aname_str;
+       MonoString *str;
 
        aname_str = mono_stringify_assembly_name (aname);
 
        /* FIXME: We invoke managed code here, so there is a potential for deadlocks */
-       assembly = mono_try_assembly_resolve (domain, mono_string_new (domain, aname_str), refonly);
-
+       str = mono_string_new (domain, aname_str);
+       if (!str) {
+               g_free (aname_str);
+               return NULL;
+       }
+       assembly = mono_try_assembly_resolve (domain, str, refonly);
        g_free (aname_str);
 
        if (assembly)
@@ -1065,7 +1131,7 @@ set_domain_search_path (MonoDomain *domain)
                 * The issue was reported in bug #81446
                 */
 
-#ifndef PLATFORM_WIN32
+#ifndef TARGET_WIN32
                gint slen;
 
                slen = strlen (search_path);
@@ -1206,6 +1272,12 @@ shadow_copy_sibling (gchar *src, gint srclen, const char *extension, gchar *targ
        
        DeleteFile (dest);
        copy_result = CopyFile (orig, dest, FALSE);
+
+       /* Fix for bug #556884 - make sure the files have the correct mode so that they can be
+        * overwritten when updated in their original locations. */
+       if (copy_result)
+               copy_result = SetFileAttributes (dest, FILE_ATTRIBUTE_NORMAL);
+
        g_free (orig);
        g_free (dest);
        
@@ -1250,7 +1322,7 @@ get_shadow_assembly_location_base (MonoDomain *domain, MonoError *error)
                cache_path = mono_string_to_utf8_checked (setup->cache_path, error);
                if (!mono_error_ok (error))
                        return NULL;
-#ifndef PLATFORM_WIN32
+#ifndef TARGET_WIN32
                {
                        gint i;
                        for (i = strlen (cache_path) - 1; i >= 0; i--)
@@ -1310,7 +1382,7 @@ get_shadow_assembly_location (const char *filename, MonoError *error)
 static gboolean
 ensure_directory_exists (const char *filename)
 {
-#ifdef PLATFORM_WIN32
+#ifdef HOST_WIN32
        gchar *dir_utf8 = g_path_get_dirname (filename);
        gunichar2 *p;
        gunichar2 *dir_utf16 = NULL;
@@ -1455,7 +1527,6 @@ gboolean
 mono_is_shadow_copy_enabled (MonoDomain *domain, const gchar *dir_name)
 {
        MonoError error;
-       const char *version;
        MonoAppDomainSetup *setup;
        gchar *all_dirs;
        gchar **dir_ptr;
@@ -1472,21 +1543,14 @@ mono_is_shadow_copy_enabled (MonoDomain *domain, const gchar *dir_name)
        if (setup == NULL || setup->shadow_copy_files == NULL)
                return FALSE;
 
-       version = mono_get_runtime_info ()->framework_version;
-
-       /* For 1.x, not NULL is enough. In 2.0 it has to be "true" */
-       if (*version <= '1') {
-               shadow_enabled = TRUE;
-       } else {
-               shadow_status_string = mono_string_to_utf8_checked (setup->shadow_copy_files, &error);
-               if (!mono_error_ok (&error)) {
-                       mono_error_cleanup (&error);
-                       return FALSE;
-               }
-               shadow_enabled = !g_ascii_strncasecmp (shadow_status_string, "true", 4);
-               g_free (shadow_status_string);
+       shadow_status_string = mono_string_to_utf8_checked (setup->shadow_copy_files, &error);
+       if (!mono_error_ok (&error)) {
+               mono_error_cleanup (&error);
+               return FALSE;
        }
-               
+       shadow_enabled = !g_ascii_strncasecmp (shadow_status_string, "true", 4);
+       g_free (shadow_status_string);
+
        if (!shadow_enabled)
                return FALSE;
 
@@ -1591,6 +1655,12 @@ mono_make_shadow_copy (const char *filename)
        dest = g_utf8_to_utf16 (shadow, strlen (shadow), NULL, NULL, NULL);
        DeleteFile (dest);
        copy_result = CopyFile (orig, dest, FALSE);
+
+       /* Fix for bug #556884 - make sure the files have the correct mode so that they can be
+        * overwritten when updated in their original locations. */
+       if (copy_result)
+               copy_result = SetFileAttributes (dest, FILE_ATTRIBUTE_NORMAL);
+
        g_free (dest);
        g_free (orig);
 
@@ -2075,11 +2145,10 @@ mono_domain_is_unloading (MonoDomain *domain)
 }
 
 static void
-clear_cached_vtable (gpointer key, gpointer value, gpointer user_data)
+clear_cached_vtable (MonoVTable *vtable)
 {
-       MonoClass *klass = (MonoClass*)key;
-       MonoVTable *vtable = value;
-       MonoDomain *domain = (MonoDomain*)user_data;
+       MonoClass *klass = vtable->klass;
+       MonoDomain *domain = vtable->domain;
        MonoClassRuntimeInfo *runtime_info;
 
        runtime_info = klass->runtime_info;
@@ -2089,6 +2158,15 @@ clear_cached_vtable (gpointer key, gpointer value, gpointer user_data)
                mono_gc_free_fixed (vtable->data);
 }
 
+static G_GNUC_UNUSED void
+zero_static_data (MonoVTable *vtable)
+{
+       MonoClass *klass = vtable->klass;
+
+       if (vtable->data && klass->has_static_refs)
+               memset (vtable->data, 0, mono_class_data_size (klass));
+}
+
 typedef struct unload_data {
        MonoDomain *domain;
        char *failure_reason;
@@ -2103,8 +2181,7 @@ deregister_reflection_info_roots_nspace_table (gpointer key, gpointer value, gpo
 
        g_assert (class);
 
-       if (class->reflection_info)
-               mono_gc_deregister_root ((char*) &class->reflection_info);
+       mono_class_free_ref_info (class);
 }
 
 static void
@@ -2121,8 +2198,7 @@ deregister_reflection_info_roots_from_list (MonoImage *image)
        while (list) {
                MonoClass *class = list->data;
 
-               g_assert (class->reflection_info);
-               mono_gc_deregister_root ((char*) &class->reflection_info);
+               mono_class_free_ref_info (class);
 
                list = list->next;
        }
@@ -2167,9 +2243,11 @@ unload_thread_main (void *arg)
 {
        unload_data *data = (unload_data*)arg;
        MonoDomain *domain = data->domain;
+       MonoThread *thread;
+       int i;
 
        /* Have to attach to the runtime so shutdown can wait for this thread */
-       mono_thread_attach (mono_get_root_domain ());
+       thread = mono_thread_attach (mono_get_root_domain ());
 
        /* 
         * FIXME: Abort our parent thread last, so we can return a failure 
@@ -2198,7 +2276,22 @@ unload_thread_main (void *arg)
 
        mono_loader_lock ();
        mono_domain_lock (domain);
-       g_hash_table_foreach (domain->class_vtable_hash, clear_cached_vtable, domain);
+#ifdef HAVE_SGEN_GC
+       /*
+        * We need to make sure that we don't have any remsets
+        * pointing into static data of the to-be-freed domain because
+        * at the next collections they would be invalid.  So what we
+        * do is we first zero all static data and then do a minor
+        * collection.  Because all references in the static data will
+        * now be null we won't do any unnecessary copies and after
+        * the collection there won't be any more remsets.
+        */
+       for (i = 0; i < domain->class_vtable_array->len; ++i)
+               zero_static_data (g_ptr_array_index (domain->class_vtable_array, i));
+       mono_gc_collect (0);
+#endif
+       for (i = 0; i < domain->class_vtable_array->len; ++i)
+               clear_cached_vtable (g_ptr_array_index (domain->class_vtable_array, i));
 #ifdef HAVE_SGEN_GC
        deregister_reflection_info_roots (domain);
 #endif
@@ -2218,6 +2311,8 @@ unload_thread_main (void *arg)
 
        mono_gc_collect (mono_gc_max_generation ());
 
+       mono_thread_detach  (thread);
+
        return 0;
 }
 
@@ -2283,7 +2378,7 @@ mono_domain_try_unload (MonoDomain *domain, MonoObject **exc)
                        *exc = (MonoObject *) mono_get_exception_cannot_unload_appdomain ("Appdomain is already unloaded.");
                        return;
                default:
-                       g_warning ("Incalid appdomain state %d", prev_state);
+                       g_warning ("Invalid appdomain state %d", prev_state);
                        g_assert_not_reached ();
                }
        }