2004-07-05 Zoltan Varga <vargaz@freemail.hu>
[mono.git] / mono / metadata / object.c
index 5689fa35cb8d8b729afe8d41a4fd92d5a5bc235b..bdf832baa6dcb0a122d98130410123ff6c39076e 100644 (file)
@@ -3,8 +3,9 @@
  *
  * Author:
  *   Miguel de Icaza (miguel@ximian.com)
+ *   Paolo Molaro (lupus@ximian.com)
  *
- * (C) 2001 Ximian, Inc.
+ * (C) 2001-2004 Ximian, Inc.
  */
 #include <config.h>
 #include <stdlib.h>
 #include <mono/metadata/object.h>
 #include <mono/metadata/gc-internal.h>
 #include <mono/metadata/exception.h>
-#include <mono/metadata/appdomain.h>
+#include <mono/metadata/domain-internals.h>
+#include "mono/metadata/metadata-internals.h"
+#include "mono/metadata/class-internals.h"
 #include <mono/metadata/assembly.h>
 #include <mono/metadata/threadpool.h>
 #include <mono/metadata/marshal.h>
 #include "mono/metadata/debug-helpers.h"
 #include "mono/metadata/marshal.h"
 #include <mono/metadata/threads.h>
+#include <mono/metadata/threads-types.h>
 #include <mono/metadata/environment.h>
 #include "mono/metadata/profiler-private.h"
 #include <mono/os/gc_wrapper.h>
+#include <mono/utils/strenc.h>
 
 /*
  * Enable experimental typed allocation using the GC_gcj_malloc function.
@@ -53,9 +58,61 @@ mono_runtime_object_init (MonoObject *this)
 
        g_assert (method);
 
+       if (method->klass->valuetype)
+               this = mono_object_unbox (this);
        mono_runtime_invoke (method, this, NULL, NULL);
 }
 
+/* The pseudo algorithm for type initialization from the spec
+Note it doesn't say anything about domains - only threads.
+
+2. If the type is initialized you are done.
+2.1. If the type is not yet initialized, try to take an 
+     initialization lock.  
+2.2. If successful, record this thread as responsible for 
+     initializing the type and proceed to step 2.3.
+2.2.1. If not, see whether this thread or any thread 
+     waiting for this thread to complete already holds the lock.
+2.2.2. If so, return since blocking would create a deadlock.  This thread 
+     will now see an incompletely initialized state for the type, 
+     but no deadlock will arise.
+2.2.3  If not, block until the type is initialized then return.
+2.3 Initialize the parent type and then all interfaces implemented 
+    by this type.
+2.4 Execute the type initialization code for this type.
+2.5 Mark the type as initialized, release the initialization lock, 
+    awaken any threads waiting for this type to be initialized, 
+    and return.
+
+*/
+
+typedef struct
+{
+       guint32 initializing_tid;
+       guint32 waiting_count;
+       CRITICAL_SECTION initialization_section;
+} TypeInitializationLock;
+
+/* for locking access to type_initialization_hash and blocked_thread_hash */
+static CRITICAL_SECTION type_initialization_section;
+
+/* from vtable to lock */
+static GHashTable *type_initialization_hash;
+
+/* from thread id to thread id being waited on */
+static GHashTable *blocked_thread_hash;
+
+/* Main thread */
+static MonoThread *main_thread;
+
+void
+mono_type_initialization_init (void)
+{
+       InitializeCriticalSection (&type_initialization_section);
+       type_initialization_hash = g_hash_table_new (NULL, NULL);
+       blocked_thread_hash = g_hash_table_new (NULL, NULL);
+}
+
 /*
  * mono_runtime_class_init:
  * @vtable: vtable that needs to be initialized
@@ -68,20 +125,20 @@ mono_runtime_class_init (MonoVTable *vtable)
        int i;
        MonoException *exc;
        MonoException *exc_to_throw;
-       MonoMethod *method;
+       MonoMethod *method = NULL;
        MonoClass *klass;
        gchar *full_name;
        gboolean found;
 
        MONO_ARCH_SAVE_REGS;
 
-       if (vtable->initialized || vtable->initializing)
+       if (vtable->initialized)
                return;
 
        exc = NULL;
        found = FALSE;
        klass = vtable->klass;
-       
+
        for (i = 0; i < klass->method.count; ++i) {
                method = klass->methods [i];
                if ((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) && 
@@ -92,16 +149,82 @@ mono_runtime_class_init (MonoVTable *vtable)
        }
 
        if (found) {
-               mono_domain_lock (vtable->domain);
+               MonoDomain *domain = vtable->domain;
+               TypeInitializationLock *lock;
+               guint32 tid = GetCurrentThreadId();
+               int do_initialization = 0;
+               MonoDomain *last_domain = NULL;
+
+               EnterCriticalSection (&type_initialization_section);
                /* double check... */
-               if (vtable->initialized || vtable->initializing)
+               if (vtable->initialized) {
+                       LeaveCriticalSection (&type_initialization_section);
                        return;
-               vtable->initializing = 1;
-               mono_runtime_invoke (method, NULL, NULL, (MonoObject **) &exc);
+               }
+               lock = g_hash_table_lookup (type_initialization_hash, vtable);
+               if (lock == NULL) {
+                       /* This thread will get to do the initialization */
+                       if (mono_domain_get () != domain) {
+                               /* Transfer into the target domain */
+                               last_domain = mono_domain_get ();
+                               if (!mono_domain_set (domain, FALSE)) {
+                                       vtable->initialized = 1;
+                                       LeaveCriticalSection (&type_initialization_section);
+                                       mono_raise_exception (mono_get_exception_appdomain_unloaded ());
+                               }
+                       }
+                       lock = g_malloc (sizeof(TypeInitializationLock));
+                       InitializeCriticalSection (&lock->initialization_section);
+                       lock->initializing_tid = tid;
+                       lock->waiting_count = 1;
+                       /* grab the vtable lock while this thread still owns type_initialization_section */
+                       EnterCriticalSection (&lock->initialization_section);
+                       g_hash_table_insert (type_initialization_hash, vtable, lock);
+                       do_initialization = 1;
+               } else {
+                       gpointer blocked;
+
+                       if (lock->initializing_tid == tid) {
+                               LeaveCriticalSection (&type_initialization_section);
+                               return;
+                       }
+                       /* see if the thread doing the initialization is already blocked on this thread */
+                       blocked = GUINT_TO_POINTER (lock->initializing_tid);
+                       while ((blocked = g_hash_table_lookup (blocked_thread_hash, blocked))) {
+                               if (blocked == GUINT_TO_POINTER (tid)) {
+                                       LeaveCriticalSection (&type_initialization_section);
+                                       return;
+                               }
+                       }
+                       ++lock->waiting_count;
+                       /* record the fact that we are waiting on the initializing thread */
+                       g_hash_table_insert (blocked_thread_hash, GUINT_TO_POINTER (tid), GUINT_TO_POINTER (lock->initializing_tid));
+               }
+               LeaveCriticalSection (&type_initialization_section);
+
+               if (do_initialization) {
+                       mono_runtime_invoke (method, NULL, NULL, (MonoObject **) &exc);
+                       if (last_domain)
+                               mono_domain_set (last_domain, TRUE);
+                       LeaveCriticalSection (&lock->initialization_section);
+               } else {
+                       /* this just blocks until the initializing thread is done */
+                       EnterCriticalSection (&lock->initialization_section);
+                       LeaveCriticalSection (&lock->initialization_section);
+               }
+
+               EnterCriticalSection (&type_initialization_section);
+               if (lock->initializing_tid != tid)
+                       g_hash_table_remove (blocked_thread_hash, GUINT_TO_POINTER (tid));
+               --lock->waiting_count;
+               if (lock->waiting_count == 0) {
+                       DeleteCriticalSection (&lock->initialization_section);
+                       g_hash_table_remove (type_initialization_hash, vtable);
+                       g_free (lock);
+               }
                vtable->initialized = 1;
-               vtable->initializing = 0;
                /* FIXME: if the cctor fails, the type must be marked as unusable */
-               mono_domain_unlock (vtable->domain);
+               LeaveCriticalSection (&type_initialization_section);
        } else {
                vtable->initialized = 1;
                return;
@@ -183,9 +306,8 @@ vtable_finalizer (void *obj, void *data) {
 #define GC_NO_DESCRIPTOR ((gpointer)(0 | GC_DS_LENGTH))
 
 /*
- * The vtable is assumed to be reachable by other roots, since vtables
- * are currently never freed. That might change in the future, but
- * for now, this is a correct (and worthwhile) optimization.
+ * The vtables in the root appdomain are assumed to be reachable by other 
+ * roots, and we don't use typed allocation in the other domains.
  */
 
 #define GC_HEADER_BITMAP (1 << (G_STRUCT_OFFSET (MonoObject,synchronisation) / sizeof(gpointer)))
@@ -195,6 +317,7 @@ mono_class_compute_gc_descriptor (MonoClass *class)
 {
        MonoClassField *field;
        guint64 bitmap;
+       guint32 bm [2];
        int i;
        static gboolean gcj_inited = FALSE;
 
@@ -234,7 +357,7 @@ mono_class_compute_gc_descriptor (MonoClass *class)
 
                /* GC 6.1 has trouble handling 64 bit descriptors... */
                if ((class->instance_size / sizeof (gpointer)) > 30) {
-//                     printf ("TOO LARGE: %s %d.\n", class->name, class->instance_size / sizeof (gpointer));
+/*                     printf ("TOO LARGE: %s %d.\n", class->name, class->instance_size / sizeof (gpointer)); */
                        return;
                }
 
@@ -242,10 +365,10 @@ mono_class_compute_gc_descriptor (MonoClass *class)
 
                count ++;
 
-//             if (count > 442)
-//                     return;
+/*             if (count > 442) */
+/*                     return;  */
 
-//             printf("KLASS: %s.\n", class->name);
+/*             printf("KLASS: %s.\n", class->name); */
 
                for (p = class; p != NULL; p = p->parent) {
                for (i = 0; i < p->field.count; ++i) {
@@ -273,7 +396,7 @@ mono_class_compute_gc_descriptor (MonoClass *class)
                        case MONO_TYPE_U8:
                        case MONO_TYPE_R4:
                        case MONO_TYPE_R8:
-//                             printf ("F: %s %s %d %lld %llx.\n", class->name, field->name, field->offset, ((guint64)1) << pos, bitmap);
+/*                             printf ("F: %s %s %d %lld %llx.\n", class->name, field->name, field->offset, ((guint64)1) << pos, bitmap); */
                                break;
                        case MONO_TYPE_I:
                        case MONO_TYPE_STRING:
@@ -285,13 +408,13 @@ mono_class_compute_gc_descriptor (MonoClass *class)
                                g_assert ((field->offset % sizeof(gpointer)) == 0);
 
                                bitmap |= ((guint64)1) << pos;
-//                             printf ("F: %s %s %d %d %lld %llx.\n", class->name, field->name, field->offset, pos, ((guint64)(1)) << pos, bitmap);
+/*                             printf ("F: %s %s %d %d %lld %llx.\n", class->name, field->name, field->offset, pos, ((guint64)(1)) << pos, bitmap); */
                                break;
                        case MONO_TYPE_VALUETYPE: {
                                MonoClass *fclass = field->type->data.klass;
                                if (!fclass->enumtype) {
                                        mono_class_compute_gc_descriptor (fclass);
-                                       bitmap |= (fclass->gc_bitmap & ~2) << pos;
+                                       bitmap |= (fclass->gc_bitmap >> (sizeof (MonoObject) / sizeof (gpointer))) << pos;
                                }
                                break;
                        }
@@ -301,15 +424,24 @@ mono_class_compute_gc_descriptor (MonoClass *class)
                }
                }
 
-//             printf("CLASS: %s.%s -> %d %llx.\n", class->name_space, class->name, class->instance_size / sizeof (gpointer), bitmap);
+/*             printf("CLASS: %s.%s -> %d %llx.\n", class->name_space, class->name, class->instance_size / sizeof (gpointer), bitmap); */
                class->gc_bitmap = bitmap;
-               class->gc_descr = (gpointer)GC_make_descriptor ((GC_bitmap)&bitmap, class->instance_size / sizeof (gpointer));
+               /* Convert to the format expected by GC_make_descriptor */
+               bm [0] = (guint32)bitmap;
+               bm [1] = (guint32)(bitmap >> 32);
+               class->gc_descr = (gpointer)GC_make_descriptor ((GC_bitmap)&bm, class->instance_size / sizeof (gpointer));
        }
 }
 #endif /* CREATION_SPEEDUP */
 
-static gboolean
-field_is_thread_static (MonoClass *fklass, MonoClassField *field)
+/**
+ * field_is_special_static:
+ *
+ * Returns SPECIAL_STATIC_THREAD if the field is thread static, SPECIAL_STATIC_CONTEXT if it is context static,
+ * SPECIAL_STATIC_NONE otherwise.
+ */
+static gint32
+field_is_special_static (MonoClass *fklass, MonoClassField *field)
 {
        MonoCustomAttrInfo *ainfo;
        int i;
@@ -318,13 +450,19 @@ field_is_thread_static (MonoClass *fklass, MonoClassField *field)
                return FALSE;
        for (i = 0; i < ainfo->num_attrs; ++i) {
                MonoClass *klass = ainfo->attrs [i].ctor->klass;
-               if (strcmp (klass->name, "ThreadStaticAttribute") == 0 && klass->image == mono_defaults.corlib) {
-                       mono_custom_attrs_free (ainfo);
-                       return TRUE;
+               if (klass->image == mono_defaults.corlib) {
+                       if (strcmp (klass->name, "ThreadStaticAttribute") == 0) {
+                               mono_custom_attrs_free (ainfo);
+                               return SPECIAL_STATIC_THREAD;
+                       }
+                       else if (strcmp (klass->name, "ContextStaticAttribute") == 0) {
+                               mono_custom_attrs_free (ainfo);
+                               return SPECIAL_STATIC_CONTEXT;
+                       }
                }
        }
        mono_custom_attrs_free (ainfo);
-       return FALSE;
+       return SPECIAL_STATIC_NONE;
 }
 
 /**
@@ -338,11 +476,14 @@ field_is_thread_static (MonoClass *fklass, MonoClassField *field)
 MonoVTable *
 mono_class_vtable (MonoDomain *domain, MonoClass *class)
 {
-       MonoVTable *vt;
+       MonoVTable *vt = NULL;
        MonoClassField *field;
        const char *p;
        char *t;
        int i, len;
+       guint32 vtable_size;
+       guint32 cindex;
+       guint32 constant_cols [MONO_CONSTANT_SIZE];
 
        g_assert (class);
 
@@ -362,14 +503,31 @@ mono_class_vtable (MonoDomain *domain, MonoClass *class)
        mono_stats.used_class_count++;
        mono_stats.class_vtable_size += sizeof (MonoVTable) + class->vtable_size * sizeof (gpointer);
 
-       vt = mono_mempool_alloc0 (domain->mp,  sizeof (MonoVTable) + 
-                                 class->vtable_size * sizeof (gpointer));
+       vtable_size = sizeof (MonoVTable) + class->vtable_size * sizeof (gpointer);
+
+       vt = mono_mempool_alloc0 (domain->mp,  vtable_size);
+
        vt->klass = class;
        vt->domain = domain;
 
 #if CREATION_SPEEDUP
        mono_class_compute_gc_descriptor (class);
-       vt->gc_descr = class->gc_descr;
+       if (domain != mono_get_root_domain ())
+               /*
+                * We can't use typed allocation in the non-root domains, since the
+                * collector needs the GC descriptor stored in the vtable even after
+                * the mempool containing the vtable is destroyed when the domain is
+                * unloaded. An alternative might be to allocate vtables in the GC
+                * heap, but this does not seem to work (it leads to crashes inside
+                * libgc). If that approach is tried, two gc descriptors need to be
+                * allocated for each class: one for the root domain, and one for all
+                * other domains. The second descriptor should contain a bit for the
+                * vtable field in MonoObject, since we can no longer assume the 
+                * vtable is reachable by other roots after the appdomain is unloaded.
+                */
+               vt->gc_descr = GC_NO_DESCRIPTOR;
+       else
+               vt->gc_descr = class->gc_descr;
 #endif
 
        if (class->class_size) {
@@ -385,18 +543,22 @@ mono_class_vtable (MonoDomain *domain, MonoClass *class)
                mono_stats.class_static_data_size += class->class_size + 8;
        }
 
+       cindex = -1;
        for (i = class->field.first; i < class->field.last; ++i) {
                field = &class->fields [i - class->field.first];
                if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
                        continue;
+               if (mono_field_is_deleted (field))
+                       continue;
                if (!(field->type->attrs & FIELD_ATTRIBUTE_LITERAL)) {
-                       if (field_is_thread_static (class, field)) {
+                       gint32 special_static = field_is_special_static (class, field);
+                       if (special_static != SPECIAL_STATIC_NONE) {
                                guint32 size, align, offset;
                                size = mono_type_size (field->type, &align);
-                               offset = mono_threads_alloc_static_data (size, align);
-                               if (!domain->thread_static_fields)
-                                       domain->thread_static_fields = g_hash_table_new (NULL, NULL);
-                               g_hash_table_insert (domain->thread_static_fields, field, GUINT_TO_POINTER (offset));
+                               offset = mono_alloc_special_static_data (special_static, size, align);
+                               if (!domain->special_static_fields)
+                                       domain->special_static_fields = g_hash_table_new (NULL, NULL);
+                               g_hash_table_insert (domain->special_static_fields, field, GUINT_TO_POINTER (offset));
                                continue;
                        }
                }
@@ -414,6 +576,17 @@ mono_class_vtable (MonoDomain *domain, MonoClass *class)
                }
                if (!(field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT))
                        continue;
+
+               if (!field->def_value) {
+                       cindex = mono_metadata_get_constant_index (class->image, MONO_TOKEN_FIELD_DEF | (i + 1), cindex + 1);
+                       g_assert (cindex);
+
+                       mono_metadata_decode_row (&class->image->tables [MONO_TABLE_CONSTANT], cindex - 1, constant_cols, MONO_CONSTANT_SIZE);
+                       field->def_value = g_new0 (MonoConstant, 1);
+                       field->def_value->type = constant_cols [MONO_CONSTANT_TYPE];
+                       field->def_value->value = (gpointer)mono_metadata_blob_heap (class->image, constant_cols [MONO_CONSTANT_VALUE]);
+               }
+
                p = field->def_value->value;
                len = mono_metadata_decode_blob_size (p, &p);
                t = (char*)vt->data + field->offset;
@@ -511,6 +684,7 @@ mono_class_vtable (MonoDomain *domain, MonoClass *class)
        if (class->parent)
                mono_class_vtable (domain, class->parent);
 
+       vt->type = mono_type_get_object (domain, &class->byval_arg);
        if (class->contextbound)
                vt->remote = 1;
        else
@@ -522,42 +696,44 @@ mono_class_vtable (MonoDomain *domain, MonoClass *class)
 /**
  * mono_class_proxy_vtable:
  * @domain: the application domain
- * @class: the class to proxy
+ * @remove_class: the remote class
  *
  * Creates a vtable for transparent proxies. It is basically
- * a copy of the real vtable of @class, but all function pointers invoke
- * the remoting functions, and vtable->klass points to the 
- * transparent proxy class, and not to @class.
+ * a copy of the real vtable of the class wrapped in @remote_class,
+ * but all function pointers invoke the remoting functions, and
+ * vtable->klass points to the transparent proxy class, and not to @class.
  */
-MonoVTable *
-mono_class_proxy_vtable (MonoDomain *domain, MonoClass *class)
+static MonoVTable *
+mono_class_proxy_vtable (MonoDomain *domain, MonoRemoteClass *remote_class)
 {
        MonoVTable *vt, *pvt;
-       int i, j, vtsize, interface_vtsize = 0;
-       MonoClass* iclass = NULL;
-       MonoClass* k;
+       int i, j, vtsize, max_interface_id, extra_interface_vtsize = 0;
+       MonoClass *k;
+       MonoClass *class = remote_class->proxy_class;
 
-       if ((pvt = mono_g_hash_table_lookup (domain->proxy_vtable_hash, class)))
-               return pvt;
+       vt = mono_class_vtable (domain, class);
+       max_interface_id = vt->max_interface_id;
 
-       if (class->flags & TYPE_ATTRIBUTE_INTERFACE) {
-               int method_count;
-               iclass = class;
-               class = mono_defaults.marshalbyrefobject_class;
+       /* Calculate vtable space for extra interfaces */
+       for (j = 0; j < remote_class->interface_count; j++) {
+               MonoClass* iclass = remote_class->interfaces[j];
+               int method_count = iclass->method.count;
+       
+               if (iclass->interface_id <= class->max_interface_id && class->interface_offsets[iclass->interface_id] != 0) 
+                       continue;       /* interface implemented by the class */
 
-               method_count = iclass->method.count;
                for (i = 0; i < iclass->interface_count; i++)
                        method_count += iclass->interfaces[i]->method.count;
 
-               interface_vtsize = method_count * sizeof (gpointer);
+               extra_interface_vtsize += method_count * sizeof (gpointer);
+               if (iclass->max_interface_id > max_interface_id) max_interface_id = iclass->max_interface_id;
        }
 
-       vt = mono_class_vtable (domain, class);
        vtsize = sizeof (MonoVTable) + class->vtable_size * sizeof (gpointer);
 
-       mono_stats.class_vtable_size += vtsize + interface_vtsize;
+       mono_stats.class_vtable_size += vtsize + extra_interface_vtsize;
 
-       pvt = mono_mempool_alloc (domain->mp, vtsize + interface_vtsize);
+       pvt = mono_mempool_alloc (domain->mp, vtsize + extra_interface_vtsize);
        memcpy (pvt, vt, vtsize);
 
        pvt->klass = mono_defaults.transparent_proxy_class;
@@ -582,55 +758,160 @@ mono_class_proxy_vtable (MonoDomain *domain, MonoClass *class)
                }
        }
 
-       if (iclass)
+       pvt->max_interface_id = max_interface_id;
+       pvt->interface_offsets = mono_mempool_alloc0 (domain->mp, 
+                       sizeof (gpointer) * (max_interface_id + 1));
+
+       /* initialize interface offsets */
+       for (i = 0; i <= class->max_interface_id; ++i) {
+               int slot = class->interface_offsets [i];
+               if (slot >= 0)
+                       pvt->interface_offsets [i] = &(pvt->vtable [slot]);
+       }
+
+       if (remote_class->interface_count > 0)
        {
-               int slot;
+               int slot = class->vtable_size;
                MonoClass* interf;
+               MonoClass* iclass;
+               int n;
 
-               pvt->max_interface_id = iclass->max_interface_id;
+               /* Create trampolines for the methods of the interfaces */
+               for (n = 0; n < remote_class->interface_count; n++) 
+               {
+                       iclass = remote_class->interfaces[n];
+                       if (iclass->interface_id <= class->max_interface_id && class->interface_offsets[iclass->interface_id] != 0) 
+                               continue;       /* interface implemented by the class */
                
-               pvt->interface_offsets = mono_mempool_alloc0 (domain->mp, 
-                               sizeof (gpointer) * (pvt->max_interface_id + 1));
+                       i = -1;
+                       interf = iclass;
+                       do {
+                               pvt->interface_offsets [interf->interface_id] = &pvt->vtable [slot];
+       
+                               for (j = 0; j < interf->method.count; ++j) {
+                                       MonoMethod *cm = interf->methods [j];
+                                       pvt->vtable [slot + j] = arch_create_remoting_trampoline (cm);
+                               }
+                               slot += interf->method.count;
+                               if (++i < iclass->interface_count) interf = iclass->interfaces[i];
+                               else interf = NULL;
+                               
+                       } while (interf);
+               }
+       }
 
-               /* Create trampolines for the methods of the interfaces */
-               slot = class->vtable_size;
-               interf = iclass;
-               i = -1;
-               do {
-                       pvt->interface_offsets [interf->interface_id] = &pvt->vtable [slot];
-
-                       for (j = 0; j < interf->method.count; ++j) {
-                               MonoMethod *cm = interf->methods [j];
-                               pvt->vtable [slot + j] = arch_create_remoting_trampoline (cm);
-                       }
-                       slot += interf->method.count;
-                       if (++i < iclass->interface_count) interf = iclass->interfaces[i];
-                       else interf = NULL;
-                       
-               } while (interf);
+       return pvt;
+}
+
+/**
+ * mono_remote_class:
+ * @domain: the application domain
+ * @class_name: name of the remote class
+ *
+ * Creates and initializes a MonoRemoteClass object for a remote type. 
+ * 
+ */
+MonoRemoteClass*
+mono_remote_class (MonoDomain *domain, MonoString *class_name, MonoClass *proxy_class)
+{
+       MonoRemoteClass *rc;
 
-               class = iclass;
+       mono_domain_lock (domain);
+       rc = mono_g_hash_table_lookup (domain->proxy_vtable_hash, class_name);
+
+       if (rc) {
+               mono_domain_unlock (domain);
+               return rc;
        }
-       else
+
+       rc = mono_mempool_alloc (domain->mp, sizeof(MonoRemoteClass));
+       rc->vtable = NULL;
+       rc->interface_count = 0;
+       rc->interfaces = NULL;
+       rc->proxy_class = mono_defaults.marshalbyrefobject_class;
+       rc->proxy_class_name = mono_string_to_utf8 (class_name);
+
+       mono_g_hash_table_insert (domain->proxy_vtable_hash, class_name, rc);
+       mono_upgrade_remote_class (domain, rc, proxy_class);
+
+       if (rc->vtable == NULL)
+               rc->vtable = mono_class_proxy_vtable (domain, rc);
+
+       mono_domain_unlock (domain);
+
+       return rc;
+}
+
+static void
+extend_interface_array (MonoDomain *domain, MonoRemoteClass *remote_class, int amount)
+{
+       /* Extends the array of interfaces. Memory is extended using blocks of 5 pointers */
+
+       int current_size = ((remote_class->interface_count / 5) + 1) * 5;
+       remote_class->interface_count += amount;
+
+       if (remote_class->interface_count > current_size || remote_class->interfaces == NULL) 
        {
-               pvt->interface_offsets = mono_mempool_alloc0 (domain->mp, 
-                               sizeof (gpointer) * (pvt->max_interface_id + 1));
-
-               /* initialize interface offsets */
-               for (i = 0; i <= class->max_interface_id; ++i) {
-                       int slot = class->interface_offsets [i];
-                       if (slot >= 0)
-                               pvt->interface_offsets [i] = &(pvt->vtable [slot]);
+               int new_size = ((remote_class->interface_count / 5) + 1) * 5;
+               MonoClass **new_array = mono_mempool_alloc (domain->mp, new_size * sizeof (MonoClass*));
+       
+               if (remote_class->interfaces != NULL)
+                       memcpy (new_array, remote_class->interfaces, current_size * sizeof (MonoClass*));
+               
+               remote_class->interfaces = new_array;
+       }
+}
+
+
+/**
+ * mono_upgrade_remote_class:
+ * @domain: the application domain
+ * @remote_class: the remote class
+ * @klass: class to which the remote class can be casted.
+ *
+ * Updates the vtable of the remote class by adding the necessary method slots
+ * and interface offsets so it can be safely casted to klass. klass can be a
+ * class or an interface.
+ */
+void mono_upgrade_remote_class (MonoDomain *domain, MonoRemoteClass *remote_class, MonoClass *klass)
+{
+       gboolean redo_vtable;
+
+       mono_domain_lock (domain);
+
+       if (klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
+               int i;
+               redo_vtable = TRUE;
+               for (i = 0; i < remote_class->interface_count; i++)
+                       if (remote_class->interfaces[i] == klass) redo_vtable = FALSE;
+                               
+               if (redo_vtable) {
+                       extend_interface_array (domain, remote_class, 1);
+                       remote_class->interfaces [remote_class->interface_count-1] = klass;
                }
        }
+       else {
+               redo_vtable = (remote_class->proxy_class != klass);
+               remote_class->proxy_class = klass;
+       }
 
-       mono_g_hash_table_insert (domain->proxy_vtable_hash, class, pvt);
+       if (redo_vtable)
+               remote_class->vtable = mono_class_proxy_vtable (domain, remote_class);
+/*
+       int n;
+       printf ("remote class upgrade - class:%s num-interfaces:%d\n", remote_class->proxy_class_name, remote_class->interface_count);
+       
+       for (n=0; n<remote_class->interface_count; n++)
+               printf ("  I:%s\n", remote_class->interfaces[n]->name);
+*/
 
-       return pvt;
+       mono_domain_unlock (domain);
 }
 
-/*
- * Retrieve the MonoMethod that would to be called on obj if obj is passed as
+/**
+ * mono_object_get_virtual_method:
+ *
+ * Retrieve the MonoMethod that would be called on obj if obj is passed as
  * the instance of a callvirt of method.
  */
 MonoMethod*
@@ -638,11 +919,11 @@ mono_object_get_virtual_method (MonoObject *obj, MonoMethod *method) {
        MonoClass *klass;
        MonoMethod **vtable;
        gboolean is_proxy;
-       MonoMethod *res;
+       MonoMethod *res = NULL;
 
        klass = mono_object_class (obj);
        if (klass == mono_defaults.transparent_proxy_class) {
-               klass = ((MonoTransparentProxy *)obj)->klass;
+               klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
                is_proxy = TRUE;
        } else {
                is_proxy = FALSE;
@@ -655,14 +936,19 @@ mono_object_get_virtual_method (MonoObject *obj, MonoMethod *method) {
 
        /* check method->slot is a valid index: perform isinstance? */
        if (method->klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
-               res = vtable [klass->interface_offsets [method->klass->interface_id] + method->slot];
+               if (!is_proxy)
+                       res = vtable [klass->interface_offsets [method->klass->interface_id] + method->slot];
        } else {
-               res = vtable [method->slot];
+               if (method->slot != -1)
+                       res = vtable [method->slot];
+       }
+
+       if (is_proxy) {
+               if (!res) res = method;   /* It may be an interface or abstract class method */
+               res = mono_marshal_get_remoting_invoke (res);
        }
-       g_assert (res);
 
-       if (is_proxy)
-               return mono_marshal_get_remoting_invoke (res);
+       g_assert (res);
        
        return res;
 }
@@ -676,6 +962,36 @@ dummy_mono_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObj
 
 static MonoInvokeFunc default_mono_runtime_invoke = dummy_mono_runtime_invoke;
 
+/**
+ * mono_runtime_invoke:
+ *
+ * Invokes the method represented by `method' on the object `obj'.
+ *
+ * obj is the 'this' pointer, it should be NULL for static
+ * methods, a MonoObject* for object instances and a pointer to
+ * the value type for value types.
+ *
+ * The params array contains the arguments to the method with the
+ * same convention: MonoObject* pointers for object instances and
+ * pointers to the value type otherwise. 
+ * 
+ * From unmanaged code you'll usually use the
+ * mono_runtime_invoke() variant.
+ *
+ * Note that this function doesn't handle virtual methods for
+ * you, it will exec the exact method you pass: we still need to
+ * expose a function to lookup the derived class implementation
+ * of a virtual method (there are examples of this in the code,
+ * though).
+ * 
+ * You can pass NULL as the exc argument if you don't want to
+ * catch exceptions, otherwise, *exc will be set to the exception
+ * thrown, if any.  if an exception is thrown, you can't use the
+ * MonoObject* result from the function.
+ * 
+ * If the method returns a value type, it is boxed in an object
+ * reference.
+ */
 MonoObject*
 mono_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
 {
@@ -796,6 +1112,77 @@ mono_field_get_value (MonoObject *obj, MonoClassField *field, void *value)
        set_value (field->type, value, src, TRUE);
 }
 
+MonoObject *
+mono_field_get_value_object (MonoDomain *domain, MonoClassField *field, MonoObject *obj)
+{      
+       MonoObject *o;
+       MonoClass *klass;
+       MonoVTable *vtable = NULL;
+       gchar *v;
+       gboolean is_static = FALSE;
+       gboolean is_ref = FALSE;
+
+       switch (field->type->type) {
+       case MONO_TYPE_STRING:
+       case MONO_TYPE_OBJECT:
+       case MONO_TYPE_CLASS:
+       case MONO_TYPE_ARRAY:
+       case MONO_TYPE_SZARRAY:
+               is_ref = TRUE;
+               break;
+       case MONO_TYPE_U1:
+       case MONO_TYPE_I1:
+       case MONO_TYPE_BOOLEAN:
+       case MONO_TYPE_U2:
+       case MONO_TYPE_I2:
+       case MONO_TYPE_CHAR:
+       case MONO_TYPE_U:
+       case MONO_TYPE_I:
+       case MONO_TYPE_U4:
+       case MONO_TYPE_I4:
+       case MONO_TYPE_R4:
+       case MONO_TYPE_U8:
+       case MONO_TYPE_I8:
+       case MONO_TYPE_R8:
+       case MONO_TYPE_VALUETYPE:
+               is_ref = field->type->byref;
+               break;
+       default:
+               g_error ("type 0x%x not handled in "
+                        "mono_field_get_value_object", field->type->type);
+               return NULL;
+       }
+
+       if (field->type->attrs & FIELD_ATTRIBUTE_STATIC) {
+               is_static = TRUE;
+               vtable = mono_class_vtable (domain, field->parent);
+               if (!vtable->initialized)
+                       mono_runtime_class_init (vtable);
+       }
+       
+       if (is_ref) {
+               if (is_static) {
+                       mono_field_static_get_value (vtable, field, &o);
+               } else {
+                       mono_field_get_value (obj, field, &o);
+               }
+               return o;
+       }
+
+       /* boxed value type */
+       klass = mono_class_from_mono_type (field->type);
+       o = mono_object_new (domain, klass);
+       v = ((gchar *) o) + sizeof (MonoObject);
+       if (is_static) {
+               mono_field_static_get_value (vtable, field, v);
+       } else {
+               mono_field_get_value (obj, field, v);
+       }
+
+       return o;
+}
+
+
 void
 mono_field_static_get_value (MonoVTable *vt, MonoClassField *field, void *value)
 {
@@ -859,6 +1246,29 @@ mono_runtime_get_main_args (void)
        return main_args;
 }
 
+static void
+fire_process_exit_event (void)
+{
+       MonoClassField *field;
+       MonoDomain *domain = mono_domain_get ();
+       gpointer pa [2];
+       MonoObject *delegate, *exc;
+       
+       field = mono_class_get_field_from_name (mono_defaults.appdomain_class, "ProcessExit");
+       g_assert (field);
+
+       if (domain != mono_get_root_domain ())
+               return;
+
+       delegate = *(MonoObject **)(((char *)domain->domain) + field->offset); 
+       if (delegate == NULL)
+               return;
+
+       pa [0] = domain;
+       pa [1] = NULL;
+       mono_runtime_delegate_invoke (delegate, pa, &exc);
+}
+
 /*
  * Execute a standard Main() method (argc/argv contains the
  * executable name). This method also sets the command line argument value
@@ -871,6 +1281,10 @@ mono_runtime_run_main (MonoMethod *method, int argc, char* argv[],
        int i;
        MonoArray *args = NULL;
        MonoDomain *domain = mono_domain_get ();
+       gchar *utf8_fullpath;
+       int result;
+
+       main_thread = mono_thread_current ();
 
        main_args = (MonoArray*)mono_array_new (domain, mono_defaults.string_class, argc);
 
@@ -879,16 +1293,46 @@ mono_runtime_run_main (MonoMethod *method, int argc, char* argv[],
                gchar *fullpath = g_build_filename (method->klass->image->assembly->basedir,
                                                    basename,
                                                    NULL);
-               
-               mono_array_set (main_args, gpointer, 0, mono_string_new (domain, fullpath));
+
+               utf8_fullpath = mono_utf8_from_external (fullpath);
+               if(utf8_fullpath == NULL) {
+                       /* Printing the arg text will cause glib to
+                        * whinge about "Invalid UTF-8", but at least
+                        * its relevant, and shows the problem text
+                        * string.
+                        */
+                       g_print ("\nCannot determine the text encoding for the assembly location: %s\n", fullpath);
+                       g_print ("Please add the correct encoding to MONO_EXTERNAL_ENCODINGS and try again.\n");
+                       exit (-1);
+               }
+
                g_free (fullpath);
                g_free (basename);
        } else {
-               mono_array_set (main_args, gpointer, 0, mono_string_new (domain, argv [0]));
+               utf8_fullpath = mono_utf8_from_external (argv[0]);
+               if(utf8_fullpath == NULL) {
+                       g_print ("\nCannot determine the text encoding for the assembly location: %s\n", argv[0]);
+                       g_print ("Please add the correct encoding to MONO_EXTERNAL_ENCODINGS and try again.\n");
+                       exit (-1);
+               }
        }
+               
+       mono_array_set (main_args, gpointer, 0, mono_string_new (domain, utf8_fullpath));
+       g_free (utf8_fullpath);
 
        for (i = 1; i < argc; ++i) {
-               MonoString *arg = mono_string_new (domain, argv [i]);
+               gchar *utf8_arg;
+               MonoString *arg;
+
+               utf8_arg=mono_utf8_from_external (argv[i]);
+               if(utf8_arg==NULL) {
+                       /* Ditto the comment about Invalid UTF-8 here */
+                       g_print ("\nCannot determine the text encoding for argument %d (%s).\n", i, argv[i]);
+                       g_print ("Please add the correct encoding to MONO_EXTERNAL_ENCODINGS and try again.\n");
+                       exit (-1);
+               }
+               
+               arg = mono_string_new (domain, utf8_arg);
                mono_array_set (main_args, gpointer, i, arg);
        }
        argc--;
@@ -896,7 +1340,11 @@ mono_runtime_run_main (MonoMethod *method, int argc, char* argv[],
        if (method->signature->param_count) {
                args = (MonoArray*)mono_array_new (domain, mono_defaults.string_class, argc);
                for (i = 0; i < argc; ++i) {
-                       MonoString *arg = mono_string_new (domain, argv [i]);
+                       /* The encodings should all work, given that
+                        * we've checked all these args for the
+                        * main_args array.
+                        */
+                       MonoString *arg = mono_string_new (domain, mono_utf8_from_external (argv [i]));
                        mono_array_set (args, gpointer, i, arg);
                }
        } else {
@@ -905,7 +1353,9 @@ mono_runtime_run_main (MonoMethod *method, int argc, char* argv[],
        
        mono_assembly_set_main (method->klass->image->assembly);
 
-       return mono_runtime_exec_main (method, args, exc);
+       result = mono_runtime_exec_main (method, args, exc);
+       fire_process_exit_event ();
+       return result;
 }
 
 /* Used in mono_unhandled_exception */
@@ -914,7 +1364,7 @@ create_unhandled_exception_eventargs (MonoObject *exc)
 {
        MonoClass *klass;
        gpointer args [2];
-       MonoMethod *method;
+       MonoMethod *method = NULL;
        MonoBoolean is_terminating = TRUE;
        MonoObject *obj;
        gint i;
@@ -965,9 +1415,10 @@ mono_unhandled_exception (MonoObject *exc)
        if (exc->vtable->klass != mono_defaults.threadabortexception_class) {
                delegate = *(MonoObject **)(((char *)domain->domain) + field->offset); 
 
-               /* set exitcode only in the main thread? */
-               mono_environment_exitcode_set (1);
-               if (domain != mono_root_domain || !delegate) {
+               /* set exitcode only in the main thread */
+               if (mono_thread_current () == main_thread)
+                       mono_environment_exitcode_set (1);
+               if (domain != mono_get_root_domain () || !delegate) {
                        mono_print_unhandled_exception (exc);
                } else {
                        MonoObject *e = NULL;
@@ -1022,8 +1473,19 @@ mono_runtime_exec_main (MonoMethod *method, MonoArray *args, MonoObject **exc)
 
        domain = mono_object_domain (args);
        if (!domain->entry_assembly) {
-               domain->entry_assembly = method->klass->image->assembly;
-               ves_icall_System_AppDomainSetup_InitAppDomainSetup (domain->setup);
+               gchar *str;
+               gchar *config_suffix;
+               MonoAssembly *assembly;
+
+               assembly = method->klass->image->assembly;
+               domain->entry_assembly = assembly;
+               domain->setup->application_base = mono_string_new (domain, assembly->basedir);
+
+               config_suffix = g_strconcat (assembly->aname.name, ".exe.config", NULL);
+               str = g_build_filename (assembly->basedir, config_suffix, NULL);
+               g_free (config_suffix);
+               domain->setup->configuration_file = mono_string_new (domain, str);
+               g_free (str);
        }
 
        /* FIXME: check signature of method */
@@ -1060,6 +1522,39 @@ mono_install_runtime_invoke (MonoInvokeFunc func)
        default_mono_runtime_invoke = func ? func: dummy_mono_runtime_invoke;
 }
 
+/**
+ * mono_runtime_invoke:
+ *
+ * Invokes the method represented by `method' on the object `obj'.
+ *
+ * obj is the 'this' pointer, it should be NULL for static
+ * methods, a MonoObject* for object instances and a pointer to
+ * the value type for value types.
+ *
+ * The params array contains the arguments to the method with the
+ * same convention: MonoObject* pointers for object instances and
+ * pointers to the value type otherwise. The _invoke_array
+ * variant takes a C# object[] as the params argument (MonoArray
+ * *params): in this case the value types are boxed inside the
+ * respective reference representation.
+ * 
+ * From unmanaged code you'll usually use the
+ * mono_runtime_invoke() variant.
+ *
+ * Note that this function doesn't handle virtual methods for
+ * you, it will exec the exact method you pass: we still need to
+ * expose a function to lookup the derived class implementation
+ * of a virtual method (there are examples of this in the code,
+ * though).
+ * 
+ * You can pass NULL as the exc argument if you don't want to
+ * catch exceptions, otherwise, *exc will be set to the exception
+ * thrown, if any.  if an exception is thrown, you can't use the
+ * MonoObject* result from the function.
+ * 
+ * If the method returns a value type, it is boxed in an object
+ * reference.
+ */
 MonoObject*
 mono_runtime_invoke_array (MonoMethod *method, void *obj, MonoArray *params,
                           MonoObject **exc)
@@ -1091,6 +1586,13 @@ mono_runtime_invoke_array (MonoMethod *method, void *obj, MonoArray *params,
                        case MONO_TYPE_R4:
                        case MONO_TYPE_R8:
                        case MONO_TYPE_VALUETYPE:
+                               if (sig->params [i]->byref) {
+                                       /* MS seems to create the objects if a null is passed in */
+                                       if (! ((gpointer *)params->vector)[i])
+                                               ((gpointer*)params->vector)[i] = mono_object_new (mono_domain_get (), mono_class_from_mono_type (sig->params [i]));
+                               }
+                               else
+                                       g_assert (((gpointer*)params->vector) [i]);
                                pa [i] = (char *)(((gpointer *)params->vector)[i]) + sizeof (MonoObject);
                                break;
                        case MONO_TYPE_STRING:
@@ -1110,19 +1612,26 @@ mono_runtime_invoke_array (MonoMethod *method, void *obj, MonoArray *params,
        }
 
        if (!strcmp (method->name, ".ctor") && method->klass != mono_defaults.string_class) {
+               void *o = obj;
                if (!obj) {
                        obj = mono_object_new (mono_domain_get (), method->klass);
                        if (mono_object_class(obj) == mono_defaults.transparent_proxy_class) {
-                               method = mono_marshal_get_remoting_invoke (method->klass->vtable [method->slot]);
+                               method = mono_marshal_get_remoting_invoke (method->slot == -1 ? method : method->klass->vtable [method->slot]);
                        }
+                       if (method->klass->valuetype)
+                               o = mono_object_unbox (obj);
+                       else
+                               o = obj;
                }
-               mono_runtime_invoke (method, obj, pa, exc);
+               mono_runtime_invoke (method, o, pa, exc);
                return obj;
-       } else
+       } else {
+               /* obj must be already unboxed if needed */
                return mono_runtime_invoke (method, obj, pa, exc);
+       }
 }
 
-G_GNUC_NORETURN static void
+static void
 out_of_memory (size_t size)
 {
        /* 
@@ -1130,8 +1639,7 @@ out_of_memory (size_t size)
         * back to the system at this point if we're really low on memory (ie, size is
         * lower than the memory we set apart)
         */
-       MonoException * ex = mono_exception_from_name (mono_defaults.corlib, "System", "OutOfMemoryException");
-       mono_raise_exception (ex);
+       mono_raise_exception (mono_domain_get ()->out_of_memory_ex);
 }
 
 /**
@@ -1143,7 +1651,7 @@ out_of_memory (size_t size)
  *
  * Returns: an allocated object of size @size, or NULL on failure.
  */
-static void *
+static inline void *
 mono_object_allocate (size_t size)
 {
 #if HAVE_BOEHM_GC
@@ -1160,7 +1668,7 @@ mono_object_allocate (size_t size)
 }
 
 #if CREATION_SPEEDUP
-static void *
+static inline void *
 mono_object_allocate_spec (size_t size, void *gcdescr)
 {
        /* if this is changed to GC_debug_malloc(), we need to change also metadata/gc.c */
@@ -1173,31 +1681,14 @@ mono_object_allocate_spec (size_t size, void *gcdescr)
 }
 #endif
 
-/**
- * mono_object_free:
- *
- * Frees the memory used by the object.  Debugging purposes
- * only, as we will have our GC system.
- */
-void
-mono_object_free (MonoObject *o)
-{
-#if HAVE_BOEHM_GC
-       g_error ("mono_object_free called with boehm gc.");
-#else
-       MonoClass *c = o->vtable->klass;
-       
-       memset (o, 0, c->instance_size);
-       free (o);
-#endif
-}
-
 /**
  * mono_object_new:
  * @klass: the class of the object that we want to create
  *
- * Returns: A newly created object whose definition is
- * looked up using @klass
+ * Returns a newly created object whose definition is
+ * looked up using @klass.   This will not invoke any constructors, 
+ * so the consumer of this routine has to invoke any constructors on
+ * its own to initialize the object.
  */
 MonoObject *
 mono_object_new (MonoDomain *domain, MonoClass *klass)
@@ -1262,7 +1753,7 @@ mono_object_new_fast (MonoVTable *vtable)
        if (vtable->gc_descr != GC_NO_DESCRIPTOR) {
                o = mono_object_allocate_spec (vtable->klass->instance_size, vtable);
        } else {
-//             printf("OBJECT: %s.%s.\n", vtable->klass->name_space, vtable->klass->name);
+/*             printf("OBJECT: %s.%s.\n", vtable->klass->name_space, vtable->klass->name); */
                o = mono_object_allocate (vtable->klass->instance_size);
                o->vtable = vtable;
        }
@@ -1282,7 +1773,7 @@ mono_object_new_alloc_specific (MonoVTable *vtable)
        if (vtable->gc_descr != GC_NO_DESCRIPTOR) {
                o = mono_object_allocate_spec (vtable->klass->instance_size, vtable);
        } else {
-//             printf("OBJECT: %s.%s.\n", vtable->klass->name_space, vtable->klass->name);
+/*             printf("OBJECT: %s.%s.\n", vtable->klass->name_space, vtable->klass->name); */
                o = mono_object_allocate (vtable->klass->instance_size);
                o->vtable = vtable;
        }
@@ -1485,7 +1976,7 @@ mono_array_new (MonoDomain *domain, MonoClass *eclass, guint32 n)
 
        MONO_ARCH_SAVE_REGS;
 
-       ac = mono_array_class_get (&eclass->byval_arg, 1);
+       ac = mono_array_class_get (eclass, 1);
        g_assert (ac != NULL);
 
        return mono_array_new_specific (mono_class_vtable (domain, ac), n);
@@ -1519,7 +2010,7 @@ mono_array_new_specific (MonoVTable *vtable, guint32 n)
        if (vtable->gc_descr != GC_NO_DESCRIPTOR) {
                o = mono_object_allocate_spec (byte_len, vtable);
        } else {
-//             printf("ARRAY: %s.%s.\n", vtable->klass->name_space, vtable->klass->name);
+/*             printf("ARRAY: %s.%s.\n", vtable->klass->name_space, vtable->klass->name); */
                o = mono_object_allocate (byte_len);
                o->vtable = vtable;
        }
@@ -1568,13 +2059,23 @@ mono_string_new_size (MonoDomain *domain, gint32 len)
 {
        MonoString *s;
        MonoVTable *vtable;
+       size_t size = (sizeof (MonoString) + ((len + 1) * 2));
+
+       /* overflow ? can't fit it, can't allocate it! */
+       if (len > size)
+               out_of_memory (-1);
 
        vtable = mono_class_vtable (domain, mono_defaults.string_class);
 
 #if CREATION_SPEEDUP
-       s = mono_object_allocate_spec (sizeof (MonoString) + ((len + 1) * 2), vtable);
+       if (vtable->gc_descr != GC_NO_DESCRIPTOR)
+               s = mono_object_allocate_spec (size, vtable);
+       else {
+               s = (MonoString*)mono_object_allocate (size);
+               s->object.vtable = vtable;
+       }
 #else
-       s = (MonoString*)mono_object_allocate (sizeof (MonoString) + ((len + 1) * 2));
+       s = (MonoString*)mono_object_allocate (size);
        s->object.vtable = vtable;
 #endif
 
@@ -1708,10 +2209,23 @@ mono_value_box (MonoDomain *domain, MonoClass *class, gpointer value)
        return res;
 }
 
+MonoDomain*
+mono_object_get_domain (MonoObject *obj)
+{
+       return mono_object_domain (obj);
+}
+
+MonoClass*
+mono_object_get_class (MonoObject *obj)
+{
+       return mono_object_class (obj);
+}
+
 gpointer
 mono_object_unbox (MonoObject *obj)
 {
        /* add assert for valuetypes? */
+       g_assert (obj->vtable->klass->valuetype);
        return ((char*)obj) + sizeof (MonoObject);
 }
 
@@ -1725,38 +2239,97 @@ mono_object_unbox (MonoObject *obj)
 MonoObject *
 mono_object_isinst (MonoObject *obj, MonoClass *klass)
 {
-       MonoVTable *vt;
-       MonoClass *oklass;
+       if (!klass->inited)
+               mono_class_init (klass);
+
+       if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) 
+               return mono_object_isinst_mbyref (obj, klass);
 
        if (!obj)
                return NULL;
 
-       vt = obj->vtable;
-       oklass = vt->klass;
+       return mono_class_is_assignable_from (klass, obj->vtable->klass) ? obj : NULL;
+}
 
-       if (!klass->inited)
-               mono_class_init (klass);
+MonoObject *
+mono_object_isinst_mbyref (MonoObject *obj, MonoClass *klass)
+{
+       MonoVTable *vt;
 
+       if (!obj)
+               return NULL;
+
+       vt = obj->vtable;
+       
        if (klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
                if ((klass->interface_id <= vt->max_interface_id) &&
-                   vt->interface_offsets [klass->interface_id])
+                   (vt->interface_offsets [klass->interface_id] != 0))
                        return obj;
-       } else {
-               if (oklass == mono_defaults.transparent_proxy_class) {
-                       /* fixme: add check for IRemotingTypeInfo */
-                       oklass = ((MonoTransparentProxy *)obj)->klass;
+       }
+       else {
+               MonoClass *oklass = vt->klass;
+               if ((oklass == mono_defaults.transparent_proxy_class))
+                       oklass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
+       
+               if ((oklass->idepth >= klass->idepth) && (oklass->supertypes [klass->idepth - 1] == klass))
+                       return obj;
+       }
+
+       if (vt->klass == mono_defaults.transparent_proxy_class && ((MonoTransparentProxy *)obj)->custom_type_info) 
+       {
+               MonoDomain *domain = mono_domain_get ();
+               MonoObject *res;
+               MonoObject *rp = (MonoObject *)((MonoTransparentProxy *)obj)->rp;
+               MonoClass *rpklass = mono_defaults.iremotingtypeinfo_class;
+               MonoMethod *im = NULL;
+               gpointer pa [2];
+               int i;
+       
+               for (i = 0; i < rpklass->method.count; ++i) {
+                       if (!strcmp ("CanCastTo", rpklass->methods [i]->name)) {
+                               im = rpklass->methods [i];
+                               break;
+                       }
                }
-               if (klass->rank) {
-                       if (oklass->rank == klass->rank && mono_class_has_parent (oklass->cast_class, klass->cast_class))
-                               return obj;
-                       
-               } else if (mono_class_has_parent (oklass, klass))
+       
+               im = mono_object_get_virtual_method (rp, im);
+               g_assert (im);
+       
+               pa [0] = mono_type_get_object (domain, &klass->byval_arg);
+               pa [1] = obj;
+
+               res = mono_runtime_invoke (im, rp, pa, NULL);
+       
+               if (*(MonoBoolean *) mono_object_unbox(res)) {
+                       /* Update the vtable of the remote type, so it can safely cast to this new type */
+                       mono_upgrade_remote_class (domain, ((MonoTransparentProxy *)obj)->remote_class, klass);
+                       obj->vtable = ((MonoTransparentProxy *)obj)->remote_class->vtable;
                        return obj;
+               }
        }
 
        return NULL;
 }
 
+/**
+ * mono_object_castclass_mbyref:
+ * @obj: an object
+ * @klass: a pointer to a class 
+ *
+ * Returns: @obj if @obj is derived from @klass, throws an exception otherwise
+ */
+MonoObject *
+mono_object_castclass_mbyref (MonoObject *obj, MonoClass *klass)
+{
+       if (!obj) return NULL;
+       if (mono_object_isinst_mbyref (obj, klass)) return obj;
+               
+       mono_raise_exception (mono_exception_from_name (mono_defaults.corlib,
+                                                       "System",
+                                                       "InvalidCastException"));
+       return NULL;
+}
+
 typedef struct {
        MonoDomain *orig_domain;
        char *ins;
@@ -1782,15 +2355,12 @@ mono_string_is_interned_lookup (MonoString *str, int insert)
        MonoDomain *domain;
        char *ins = g_malloc (4 + str->length * 2);
        char *p;
-       int bloblen;
        
        /* Encode the length */
+       /* Same code as in mono_image_insert_string () */
        p = ins;
-       mono_metadata_encode_value (2 * str->length, p, &p);
-       bloblen = p - ins;
-       p = ins;
-       mono_metadata_encode_value (bloblen + 2 * str->length, p, &p);
-       bloblen = (p - ins) + 2 * str->length;
+       mono_metadata_encode_value (1 | (2 * str->length), p, &p);
+
        /*
         * ins is stored in the hash table as a key and needs to have the same
         * representation as in the metadata: we swap the character bytes on big
@@ -1799,7 +2369,7 @@ mono_string_is_interned_lookup (MonoString *str, int insert)
 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
        {
                int i;
-               char *p2 = mono_string_chars (str);
+               char *p2 = (char *)mono_string_chars (str);
                for (i = 0; i < str->length; ++i) {
                        *p++ = p2 [1];
                        *p++ = p2 [0];
@@ -1872,7 +2442,7 @@ mono_ldstr (MonoDomain *domain, MonoImage *image, guint32 idx)
 
        MONO_ARCH_SAVE_REGS;
 
-       if (image->assembly->dynamic)
+       if (image->dynamic)
                return mono_lookup_dynamic_token (image, MONO_TOKEN_STRING | idx);
        else
                sig = str = mono_metadata_user_string (image, idx);
@@ -1977,7 +2547,7 @@ mono_string_from_utf16 (gunichar2 *data)
        return mono_string_new_utf16 (domain, data, len);
 }
 
-G_GNUC_NORETURN static void
+static void
 default_ex_handler (MonoException *ex)
 {
        MonoObject *o = (MonoObject*)ex;
@@ -1985,7 +2555,7 @@ default_ex_handler (MonoException *ex)
        exit (1);
 }
 
-static G_GNUC_NORETURN MonoExceptionFunc ex_handler = default_ex_handler;
+static MonoExceptionFunc ex_handler = default_ex_handler;
 
 void
 mono_install_handler        (MonoExceptionFunc func)
@@ -1999,9 +2569,16 @@ mono_install_handler        (MonoExceptionFunc func)
  *
  * Signal the runtime that the exception @ex has been raised in unmanaged code.
  */
-G_GNUC_NORETURN void
+void
 mono_raise_exception (MonoException *ex) 
 {
+       /*
+        * NOTE: Do NOT annotate this function with G_GNUC_NORETURN, since
+        * that will cause gcc to omit the function epilog, causing problems when
+        * the JIT tries to walk the stack, since the return address on the stack
+        * will point into the next function in the executable, not this one.
+        */
+
        ex_handler (ex);
 }
 
@@ -2026,7 +2603,9 @@ mono_async_result_new (MonoDomain *domain, HANDLE handle, MonoObject *state, gpo
 
        res->data = data;
        res->async_state = state;
-       res->handle = (MonoObject *)mono_wait_handle_new (domain, handle);
+       if (handle != NULL)
+               res->handle = (MonoObject *) mono_wait_handle_new (domain, handle);
+
        res->sync_completed = FALSE;
        res->completed = FALSE;
 
@@ -2049,6 +2628,8 @@ mono_message_init (MonoDomain *domain,
 
        this->args = mono_array_new (domain, mono_defaults.object_class, sig->param_count);
        this->arg_types = mono_array_new (domain, mono_defaults.byte_class, sig->param_count);
+       this->async_result = NULL;
+       this->call_type = CallType_Sync;
 
        names = g_new (char *, sig->param_count);
        mono_method_get_param_names (method->method, (const char **) names);
@@ -2060,7 +2641,6 @@ mono_message_init (MonoDomain *domain,
        }
 
        g_free (names);
-       
        for (i = 0, j = 0; i < sig->param_count; i++) {
 
                if (sig->params [i]->byref) {
@@ -2070,12 +2650,11 @@ mono_message_init (MonoDomain *domain,
                                j++;
                        }
                        arg_type = 2;
-                       if (sig->params [i]->attrs & PARAM_ATTRIBUTE_IN)
+                       if (!(sig->params [i]->attrs & PARAM_ATTRIBUTE_OUT))
                                arg_type |= 1;
                } else {
                        arg_type = 1;
                }
-
                mono_array_set (this->arg_types, guint8, i, arg_type);
        }
 }
@@ -2141,7 +2720,7 @@ mono_message_invoke (MonoObject *target, MonoMethodMessage *msg,
        if (target && target->vtable->klass == mono_defaults.transparent_proxy_class) {
 
                MonoTransparentProxy* tp = (MonoTransparentProxy *)target;
-               if (tp->klass->contextbound && tp->rp->context == (MonoObject *) mono_context_get ()) {
+               if (tp->remote_class->proxy_class->contextbound && tp->rp->context == (MonoObject *) mono_context_get ()) {
                        target = tp->rp->unwrapped_server;
                } else {
                        return mono_remoting_invoke ((MonoObject *)tp->rp, msg, exc, out_args);
@@ -2169,7 +2748,7 @@ mono_message_invoke (MonoObject *target, MonoMethodMessage *msg,
                }
        }
 
-       return mono_runtime_invoke_array (method, target, msg->args, exc);
+       return mono_runtime_invoke_array (method, method->klass->valuetype? mono_object_unbox (target): target, msg->args, exc);
 }
 
 void
@@ -2304,7 +2883,7 @@ mono_method_call_message_new (MonoMethod *method, gpointer *params, MonoMethod *
                mono_array_set (msg->args, gpointer, i, arg);
        }
 
-       if (invoke) {
+       if (cb != NULL && state != NULL) {
                *cb = *((MonoDelegate **)params [i]);
                i++;
                *state = *((MonoObject **)params [i]);
@@ -2323,16 +2902,13 @@ mono_method_return_message_restore (MonoMethod *method, gpointer *params, MonoAr
 {
        MonoMethodSignature *sig = method->signature;
        int i, j, type, size;
-       
        for (i = 0, j = 0; i < sig->param_count; i++) {
                MonoType *pt = sig->params [i];
 
-               size = mono_type_stack_size (pt, NULL);
-
                if (pt->byref) {
                        char *arg = mono_array_get (out_args, gpointer, j);
                        type = pt->type;
-                       
+
                        switch (type) {
                        case MONO_TYPE_VOID:
                                g_assert_not_reached ();
@@ -2350,6 +2926,7 @@ mono_method_return_message_restore (MonoMethod *method, gpointer *params, MonoAr
                        case MONO_TYPE_R4:
                        case MONO_TYPE_R8:
                        case MONO_TYPE_VALUETYPE: {
+                               size = mono_class_value_size (((MonoObject*)arg)->vtable->klass, NULL);
                                memcpy (*((gpointer *)params [i]), arg + sizeof (MonoObject), size); 
                                break;
                        }
@@ -2357,6 +2934,7 @@ mono_method_return_message_restore (MonoMethod *method, gpointer *params, MonoAr
                        case MONO_TYPE_CLASS: 
                        case MONO_TYPE_ARRAY:
                        case MONO_TYPE_SZARRAY:
+                       case MONO_TYPE_OBJECT:
                                **((MonoObject ***)params [i]) = (MonoObject *)arg;
                                break;
                        default:
@@ -2399,7 +2977,7 @@ mono_load_remote_field (MonoObject *this, MonoClass *klass, MonoClassField *fiel
        if (!res)
                res = &tmp;
 
-       if (tp->klass->contextbound && tp->rp->context == (MonoObject *) mono_context_get ()) {
+       if (tp->remote_class->proxy_class->contextbound && tp->rp->context == (MonoObject *) mono_context_get ()) {
                mono_field_get_value (tp->rp->unwrapped_server, field, res);
                return res;
        }
@@ -2429,6 +3007,8 @@ mono_load_remote_field (MonoObject *this, MonoClass *klass, MonoClassField *fiel
 
        mono_remoting_invoke ((MonoObject *)(tp->rp), msg, &exc, &out_args);
 
+       if (exc) mono_raise_exception ((MonoException *)exc);
+
        *res = mono_array_get (out_args, MonoObject *, 0);
 
        if (field_class->valuetype) {
@@ -2452,7 +3032,7 @@ mono_load_remote_field_new (MonoObject *this, MonoClass *klass, MonoClassField *
 
        field_class = mono_class_from_mono_type (field->type);
 
-       if (tp->klass->contextbound && tp->rp->context == (MonoObject *) mono_context_get ()) {
+       if (tp->remote_class->proxy_class->contextbound && tp->rp->context == (MonoObject *) mono_context_get ()) {
                gpointer val;
                if (field_class->valuetype) {
                        res = mono_object_new (domain, field_class);
@@ -2487,6 +3067,8 @@ mono_load_remote_field_new (MonoObject *this, MonoClass *klass, MonoClassField *
 
        mono_remoting_invoke ((MonoObject *)(tp->rp), msg, &exc, &out_args);
 
+       if (exc) mono_raise_exception ((MonoException *)exc);
+
        res = mono_array_get (out_args, MonoObject *, 0);
 
        return res;
@@ -2519,7 +3101,7 @@ mono_store_remote_field (MonoObject *this, MonoClass *klass, MonoClassField *fie
 
        field_class = mono_class_from_mono_type (field->type);
 
-       if (tp->klass->contextbound && tp->rp->context == (MonoObject *) mono_context_get ()) {
+       if (tp->remote_class->proxy_class->contextbound && tp->rp->context == (MonoObject *) mono_context_get ()) {
                if (field_class->valuetype) mono_field_set_value (tp->rp->unwrapped_server, field, val);
                else mono_field_set_value (tp->rp->unwrapped_server, field, *((MonoObject **)val));
                return;
@@ -2553,6 +3135,8 @@ mono_store_remote_field (MonoObject *this, MonoClass *klass, MonoClassField *fie
        mono_array_set (msg->args, gpointer, 2, arg);
 
        mono_remoting_invoke ((MonoObject *)(tp->rp), msg, &exc, &out_args);
+
+       if (exc) mono_raise_exception ((MonoException *)exc);
 }
 
 void
@@ -2570,7 +3154,7 @@ mono_store_remote_field_new (MonoObject *this, MonoClass *klass, MonoClassField
 
        field_class = mono_class_from_mono_type (field->type);
 
-       if (tp->klass->contextbound && tp->rp->context == (MonoObject *) mono_context_get ()) {
+       if (tp->remote_class->proxy_class->contextbound && tp->rp->context == (MonoObject *) mono_context_get ()) {
                if (field_class->valuetype) mono_field_set_value (tp->rp->unwrapped_server, field, ((gchar *) arg) + sizeof (MonoObject));
                else mono_field_set_value (tp->rp->unwrapped_server, field, arg);
                return;
@@ -2598,5 +3182,7 @@ mono_store_remote_field_new (MonoObject *this, MonoClass *klass, MonoClassField
        mono_array_set (msg->args, gpointer, 2, arg);
 
        mono_remoting_invoke ((MonoObject *)(tp->rp), msg, &exc, &out_args);
+
+       if (exc) mono_raise_exception ((MonoException *)exc);
 }