2009-09-10 Sebastien Pouliot <sebastien@ximian.com>
[mono.git] / mono / metadata / object.c
index 52220ca4c5d6d6c4f92c0dfaf2353788c012776b..e0b30b70ed1d84e4bd24401ba2a4d4d233b03dc6 100644 (file)
@@ -40,6 +40,7 @@
 #include <mono/metadata/gc-internal.h>
 #include <mono/utils/strenc.h>
 #include <mono/utils/mono-counters.h>
+#include "cominterop.h"
 
 #ifdef HAVE_BOEHM_GC
 #define NEED_TO_ZERO_PTRFREE 1
@@ -141,6 +142,9 @@ static GHashTable *blocked_thread_hash;
 /* Main thread */
 static MonoThread *main_thread;
 
+/* Functions supplied by the runtime */
+static MonoRuntimeCallbacks callbacks;
+
 /**
  * mono_thread_set_main:
  * @thread: thread to set as the main thread
@@ -473,6 +477,18 @@ static MonoImtThunkBuilder imt_thunk_builder = NULL;
 #error "MONO_IMT_SIZE cannot be larger than 32"
 #endif
 
+void
+mono_install_callbacks (MonoRuntimeCallbacks *cbs)
+{
+       memcpy (&callbacks, cbs, sizeof (*cbs));
+}
+
+MonoRuntimeCallbacks*
+mono_get_runtime_callbacks (void)
+{
+       return &callbacks;
+}
+
 void
 mono_install_trampoline (MonoTrampoline func) 
 {
@@ -579,6 +595,8 @@ mono_runtime_free_method (MonoDomain *domain, MonoMethod *method)
        if (default_mono_free_method != NULL)
                default_mono_free_method (domain, method);
 
+       mono_method_clear_object (domain, method);
+
        mono_free_method (method);
 }
 
@@ -626,6 +644,10 @@ compute_class_bitmap (MonoClass *class, gsize *bitmap, int size, int offset, int
                        if (field->type->byref)
                                break;
 
+                       if (static_fields && field->offset == -1)
+                               /* special static */
+                               continue;
+
                        pos = field->offset / sizeof (gpointer);
                        pos += offset;
 
@@ -843,7 +865,7 @@ mono_string_alloc (int length)
        return mono_string_new_size (mono_domain_get (), length);
 }
 
-static void
+void
 mono_class_compute_gc_descriptor (MonoClass *class)
 {
        int max_set = 0;
@@ -955,6 +977,22 @@ field_is_special_static (MonoClass *fklass, MonoClassField *field)
        return SPECIAL_STATIC_NONE;
 }
 
+static gpointer imt_trampoline = NULL;
+
+void
+mono_install_imt_trampoline (gpointer tramp_code)
+{
+       imt_trampoline = tramp_code;
+}
+
+static gpointer vtable_trampoline = NULL;
+
+void
+mono_install_vtable_trampoline (gpointer tramp_code)
+{
+       vtable_trampoline = tramp_code;
+}
+
 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
 #define mix(a,b,c) { \
        a -= c;  a ^= rot(c, 4);  c += b; \
@@ -975,17 +1013,22 @@ field_is_special_static (MonoClass *fklass, MonoClassField *field)
 }
 
 guint32
-mono_method_get_imt_slot (MonoMethod *method) {
+mono_method_get_imt_slot (MonoMethod *method)
+{
        MonoMethodSignature *sig;
        int hashes_count;
        guint32 *hashes_start, *hashes;
        guint32 a, b, c;
        int i;
 
+       /* This can be used to stress tests the collision code */
+       //return 0;
+
        /*
         * We do this to simplify generic sharing.  It will hurt
         * performance in cases where a class implements two different
         * instantiations of the same generic interface.
+        * The code in build_imt_slots () depends on this.
         */
        if (method->is_inflated)
                method = ((MonoMethodInflated*)method)->declaring;
@@ -1053,7 +1096,7 @@ add_imt_builder_entry (MonoImtBuilderEntry **imt_builder, MonoMethod *method, gu
                return;
        }
 
-       entry = malloc (sizeof (MonoImtBuilderEntry));
+       entry = g_malloc0 (sizeof (MonoImtBuilderEntry));
        entry->key = method;
        entry->value.vtable_slot = vtable_slot;
        entry->next = imt_builder [imt_slot];
@@ -1111,6 +1154,7 @@ imt_emit_ir (MonoImtBuilderEntry **sorted_array, int start, int end, GPtrArray *
                        MonoIMTCheckItem *item = g_new0 (MonoIMTCheckItem, 1);
                        item->key = sorted_array [i]->key;
                        item->value = sorted_array [i]->value;
+                       item->has_target_code = sorted_array [i]->has_target_code;
                        item->is_equals = TRUE;
                        if (i < end - 1)
                                item->check_target_idx = out_array->len + 1;
@@ -1155,9 +1199,10 @@ imt_sort_slot_entries (MonoImtBuilderEntry *entries) {
 }
 
 static gpointer
-initialize_imt_slot (MonoVTable *vtable, MonoDomain *domain, MonoImtBuilderEntry *imt_builder_entry) {
+initialize_imt_slot (MonoVTable *vtable, MonoDomain *domain, MonoImtBuilderEntry *imt_builder_entry, gpointer fail_tramp)
+{
        if (imt_builder_entry != NULL) {
-               if (imt_builder_entry->children == 0) {
+               if (imt_builder_entry->children == 0 && !fail_tramp) {
                        /* No collision, return the vtable slot contents */
                        return vtable->vtable [imt_builder_entry->value.vtable_slot];
                } else {
@@ -1166,26 +1211,38 @@ initialize_imt_slot (MonoVTable *vtable, MonoDomain *domain, MonoImtBuilderEntry
                        gpointer result;
                        int i;
                        result = imt_thunk_builder (vtable, domain,
-                               (MonoIMTCheckItem**)imt_ir->pdata, imt_ir->len, NULL);
+                               (MonoIMTCheckItem**)imt_ir->pdata, imt_ir->len, fail_tramp);
                        for (i = 0; i < imt_ir->len; ++i)
                                g_free (g_ptr_array_index (imt_ir, i));
                        g_ptr_array_free (imt_ir, TRUE);
                        return result;
                }
        } else {
-               /* Empty slot */
-               return NULL;
+               if (fail_tramp)
+                       return fail_tramp;
+               else
+                       /* Empty slot */
+                       return NULL;
        }
 }
 
+static MonoImtBuilderEntry*
+get_generic_virtual_entries (MonoDomain *domain, gpointer *vtable_slot);
+
+/*
+ * LOCKING: requires the loader and domain locks.
+ *
+*/
 static void
-build_imt_slots (MonoClass *klass, MonoVTable *vt, MonoDomain *domain, gpointer* imt, GSList *extra_interfaces, int slot_num) {
+build_imt_slots (MonoClass *klass, MonoVTable *vt, MonoDomain *domain, gpointer* imt, GSList *extra_interfaces, int slot_num)
+{
        int i;
        GSList *list_item;
        guint32 imt_collisions_bitmap = 0;
        MonoImtBuilderEntry **imt_builder = calloc (MONO_IMT_SIZE, sizeof (MonoImtBuilderEntry*));
        int method_count = 0;
        gboolean record_method_count_for_max_collisions = FALSE;
+       gboolean has_generic_virtual = FALSE;
 
 #if DEBUG_IMT
        printf ("Building IMT for class %s.%s\n", klass->name_space, klass->name);
@@ -1195,7 +1252,24 @@ build_imt_slots (MonoClass *klass, MonoVTable *vt, MonoDomain *domain, gpointer*
                int interface_offset = klass->interface_offsets_packed [i];
                int method_slot_in_interface;
                for (method_slot_in_interface = 0; method_slot_in_interface < iface->method.count; method_slot_in_interface++) {
-                       MonoMethod *method = mono_class_get_method_by_index (iface, method_slot_in_interface);
+                       MonoMethod *method;
+
+                       if (slot_num >= 0 && iface->is_inflated) {
+                               /*
+                                * The imt slot of the method is the same as for its declaring method,
+                                * see the comment in mono_method_get_imt_slot (), so we can
+                                * avoid inflating methods which will be discarded by 
+                                * add_imt_builder_entry anyway.
+                                */
+                               method = mono_class_get_method_by_index (iface->generic_class->container_class, method_slot_in_interface);
+                               if (mono_method_get_imt_slot (method) != slot_num)
+                                       continue;
+                       }
+                       method = mono_class_get_method_by_index (iface, method_slot_in_interface);
+                       if (method->is_generic) {
+                               has_generic_virtual = TRUE;
+                               continue;
+                       }
                        add_imt_builder_entry (imt_builder, method, &imt_collisions_bitmap, interface_offset + method_slot_in_interface, slot_num);
                }
        }
@@ -1214,10 +1288,39 @@ build_imt_slots (MonoClass *klass, MonoVTable *vt, MonoDomain *domain, gpointer*
        }
        for (i = 0; i < MONO_IMT_SIZE; ++i) {
                /* overwrite the imt slot only if we're building all the entries or if 
-                * we're uilding this specific one
+                * we're building this specific one
                 */
-               if (slot_num < 0 || i == slot_num)
-                       imt [i] = initialize_imt_slot (vt, domain, imt_builder [i]);
+               if (slot_num < 0 || i == slot_num) {
+                       MonoImtBuilderEntry *entries = get_generic_virtual_entries (domain, &imt [i]);
+
+                       if (entries) {
+                               if (imt_builder [i]) {
+                                       MonoImtBuilderEntry *entry;
+
+                                       /* Link entries with imt_builder [i] */
+                                       for (entry = entries; entry->next; entry = entry->next)
+                                               ;                                               
+                                       entry->next = imt_builder [i];
+                                       entries->children += imt_builder [i]->children + 1;
+                               }
+                               imt_builder [i] = entries;
+                       }
+
+                       if (has_generic_virtual) {
+                               /*
+                                * There might be collisions later when the the thunk is expanded.
+                                */
+                               imt_collisions_bitmap |= (1 << i);
+
+                               /* 
+                                * The IMT thunk might be called with an instance of one of the 
+                                * generic virtual methods, so has to fallback to the IMT trampoline.
+                                */
+                               imt [i] = initialize_imt_slot (vt, domain, imt_builder [i], imt_trampoline);
+                       } else {
+                               imt [i] = initialize_imt_slot (vt, domain, imt_builder [i], NULL);
+                       }
+               }
 #if DEBUG_IMT
                printf ("initialize_imt_slot[%d]: %p\n", i, imt [i]);
 #endif
@@ -1240,7 +1343,7 @@ build_imt_slots (MonoClass *klass, MonoVTable *vt, MonoDomain *domain, gpointer*
                MonoImtBuilderEntry* entry = imt_builder [i];
                while (entry != NULL) {
                        MonoImtBuilderEntry* next = entry->next;
-                       free (entry);
+                       g_free (entry);
                        entry = next;
                }
        }
@@ -1254,22 +1357,6 @@ build_imt (MonoClass *klass, MonoVTable *vt, MonoDomain *domain, gpointer* imt,
        build_imt_slots (klass, vt, domain, imt, extra_interfaces, -1);
 }
 
-static gpointer imt_trampoline = NULL;
-
-void
-mono_install_imt_trampoline (gpointer tramp_code)
-{
-       imt_trampoline = tramp_code;
-}
-
-static gpointer vtable_trampoline = NULL;
-
-void
-mono_install_vtable_trampoline (gpointer tramp_code)
-{
-       vtable_trampoline = tramp_code;
-}
-
 /**
  * mono_vtable_build_imt_slot:
  * @vtable: virtual object table struct
@@ -1278,6 +1365,8 @@ mono_install_vtable_trampoline (gpointer tramp_code)
  * Fill the given @imt_slot in the IMT table of @vtable with
  * a trampoline or a thunk for the case of collisions.
  * This is part of the internal mono API.
+ *
+ * LOCKING: Take the domain lock.
  */
 void
 mono_vtable_build_imt_slot (MonoVTable* vtable, int imt_slot)
@@ -1291,11 +1380,13 @@ mono_vtable_build_imt_slot (MonoVTable* vtable, int imt_slot)
         * Update and heck needs to ahppen inside the proper domain lock, as all
         * the changes made to a MonoVTable.
         */
+       mono_loader_lock (); /*FIXME build_imt_slots requires the loader lock.*/
        mono_domain_lock (vtable->domain);
        /* we change the slot only if it wasn't changed from the generic imt trampoline already */
        if (imt [imt_slot] == imt_trampoline)
                build_imt_slots (vtable->klass, vtable, vtable->domain, imt, NULL, imt_slot);
        mono_domain_unlock (vtable->domain);
+       mono_loader_unlock ();
 }
 
 
@@ -1389,7 +1480,7 @@ mono_method_alloc_generic_virtual_thunk (MonoDomain *domain, int size)
        }
        generic_virtual_thunks_size += size;
 
-       p = mono_code_manager_reserve (domain->code_mp, size);
+       p = mono_domain_code_reserve (domain, size);
        *p = size;
 
        return p + 1;
@@ -1435,17 +1526,58 @@ invalidate_generic_virtual_thunk (MonoDomain *domain, gpointer code)
 }
 
 typedef struct _GenericVirtualCase {
-       MonoGenericInst *inst;
+       MonoMethod *method;
        gpointer code;
        int count;
        struct _GenericVirtualCase *next;
 } GenericVirtualCase;
 
+/*
+ * get_generic_virtual_entries:
+ *
+ *   Return IMT entries for the generic virtual method instances for vtable slot
+ * VTABLE_SLOT.
+ */ 
+static MonoImtBuilderEntry*
+get_generic_virtual_entries (MonoDomain *domain, gpointer *vtable_slot)
+{
+       GenericVirtualCase *list;
+       MonoImtBuilderEntry *entries;
+  
+       mono_domain_lock (domain);
+       if (!domain->generic_virtual_cases)
+               domain->generic_virtual_cases = g_hash_table_new (mono_aligned_addr_hash, NULL);
+       list = g_hash_table_lookup (domain->generic_virtual_cases, vtable_slot);
+       entries = NULL;
+       for (; list; list = list->next) {
+               MonoImtBuilderEntry *entry;
+               if (list->count < THUNK_THRESHOLD)
+                       continue;
+               entry = g_new0 (MonoImtBuilderEntry, 1);
+               entry->key = list->method;
+               entry->value.target_code = mono_get_addr_from_ftnptr (list->code);
+               entry->has_target_code = 1;
+               if (entries)
+                       entry->children = entries->children + 1;
+               entry->next = entries;
+               entries = entry;
+       }
+       mono_domain_unlock (domain);
+       /* FIXME: Leaking memory ? */
+       return entries;
+}
+
 /**
  * mono_method_add_generic_virtual_invocation:
  * @domain: a domain
  * @vtable_slot: pointer to the vtable slot
- * @method_inst: the method's method_inst
+ * @method: the inflated generic virtual method
  * @code: the method's code
  *
  * Registers a call via unmanaged code to a generic virtual method
@@ -1454,8 +1586,9 @@ typedef struct _GenericVirtualCase {
  * virtual method thunk.
  */
 void
-mono_method_add_generic_virtual_invocation (MonoDomain *domain, gpointer *vtable_slot,
-       MonoGenericInst *method_inst, gpointer code)
+mono_method_add_generic_virtual_invocation (MonoDomain *domain, MonoVTable *vtable,
+                                                                                       gpointer *vtable_slot,
+                                                                                       MonoMethod *method, gpointer code)
 {
        static gboolean inited = FALSE;
        static int num_added = 0;
@@ -1470,9 +1603,10 @@ mono_method_add_generic_virtual_invocation (MonoDomain *domain, gpointer *vtable
                domain->generic_virtual_cases = g_hash_table_new (mono_aligned_addr_hash, NULL);
 
        /* Check whether the case was already added */
-       gvc = g_hash_table_lookup (domain->generic_virtual_cases, vtable_slot);
+       list = g_hash_table_lookup (domain->generic_virtual_cases, vtable_slot);
+       gvc = list;
        while (gvc) {
-               if (gvc->inst == method_inst)
+               if (gvc->method == method)
                        break;
                gvc = gvc->next;
        }
@@ -1480,7 +1614,7 @@ mono_method_add_generic_virtual_invocation (MonoDomain *domain, gpointer *vtable
        /* If not found, make a new one */
        if (!gvc) {
                gvc = mono_domain_alloc (domain, sizeof (GenericVirtualCase));
-               gvc->inst = method_inst;
+               gvc->method = method;
                gvc->code = code;
                gvc->count = 0;
                gvc->next = g_hash_table_lookup (domain->generic_virtual_cases, vtable_slot);
@@ -1494,46 +1628,36 @@ mono_method_add_generic_virtual_invocation (MonoDomain *domain, gpointer *vtable
                num_added++;
        }
 
-       if (++gvc->count < THUNK_THRESHOLD) {
-               mono_domain_unlock (domain);
-               return;
-       }
-
-       entries = NULL;
-       for (list = gvc; list; list = list->next) {
-               MonoImtBuilderEntry *entry;
+       if (++gvc->count == THUNK_THRESHOLD) {
+               gpointer *old_thunk = *vtable_slot;
 
-               if (list->count < THUNK_THRESHOLD)
-                       continue;
-
-               entry = g_new0 (MonoImtBuilderEntry, 1);
-               entry->key = list->inst;
-               entry->value.target_code = mono_get_addr_from_ftnptr (list->code);
-               if (entries)
-                       entry->children = entries->children + 1;
-               entry->next = entries;
-               entries = entry;
-       }
+               if ((gpointer)vtable_slot < (gpointer)vtable)
+                       /* Force the rebuild of the thunk at the next call */
+                       *vtable_slot = imt_trampoline;
+               else {
+                       entries = get_generic_virtual_entries (domain, vtable_slot);
 
-       sorted = imt_sort_slot_entries (entries);
+                       sorted = imt_sort_slot_entries (entries);
 
-       if (*vtable_slot != vtable_trampoline)
-               invalidate_generic_virtual_thunk (domain, *vtable_slot);
+                       *vtable_slot = imt_thunk_builder (NULL, domain, (MonoIMTCheckItem**)sorted->pdata, sorted->len,
+                                                                                         vtable_trampoline);
 
-       *vtable_slot = imt_thunk_builder (NULL, domain, (MonoIMTCheckItem**)sorted->pdata, sorted->len,
-               vtable_trampoline);
+                       while (entries) {
+                               MonoImtBuilderEntry *next = entries->next;
+                               g_free (entries);
+                               entries = next;
+                       }
 
-       mono_domain_unlock (domain);
+                       for (i = 0; i < sorted->len; ++i)
+                               g_free (g_ptr_array_index (sorted, i));
+                       g_ptr_array_free (sorted, TRUE);
+               }
 
-       while (entries) {
-               MonoImtBuilderEntry *next = entries->next;
-               g_free (entries);
-               entries = next;
+               if (old_thunk != vtable_trampoline && old_thunk != imt_trampoline)
+                       invalidate_generic_virtual_thunk (domain, old_thunk);
        }
 
-       for (i = 0; i < sorted->len; ++i)
-               g_free (g_ptr_array_index (sorted, i));
-       g_ptr_array_free (sorted, TRUE);
+       mono_domain_unlock (domain);
 }
 
 static MonoVTable *mono_class_create_runtime_vtable (MonoDomain *domain, MonoClass *class);
@@ -1598,16 +1722,19 @@ mono_class_create_runtime_vtable (MonoDomain *domain, MonoClass *class)
        gpointer iter;
        gpointer *interface_offsets;
 
+       mono_loader_lock (); /*FIXME mono_class_init acquires it*/
        mono_domain_lock (domain);
        runtime_info = class->runtime_info;
        if (runtime_info && runtime_info->max_domain >= domain->domain_id && runtime_info->domain_vtables [domain->domain_id]) {
                mono_domain_unlock (domain);
+               mono_loader_unlock ();
                return runtime_info->domain_vtables [domain->domain_id];
        }
        if (!class->inited || class->exception_type) {
                if (!mono_class_init (class) || class->exception_type){
                        MonoException *exc;
                        mono_domain_unlock (domain);
+                       mono_loader_unlock ();
                        exc = mono_class_get_exception_for_failure (class);
                        g_assert (exc);
                        mono_raise_exception (exc);
@@ -1625,11 +1752,12 @@ mono_class_create_runtime_vtable (MonoDomain *domain, MonoClass *class)
 
        if (class->exception_type) {
                mono_domain_unlock (domain);
+               mono_loader_unlock ();
                return NULL;
        }
 
        if (ARCH_USE_IMT) {
-               vtable_size = sizeof (MonoVTable) + class->vtable_size * sizeof (gpointer);
+               vtable_size = MONO_SIZEOF_VTABLE + class->vtable_size * sizeof (gpointer);
                if (class->interface_offsets_count) {
                        imt_table_bytes = sizeof (gpointer) * (MONO_IMT_SIZE);
                        vtable_size += sizeof (gpointer) * (MONO_IMT_SIZE);
@@ -1638,7 +1766,7 @@ mono_class_create_runtime_vtable (MonoDomain *domain, MonoClass *class)
                }
        } else {
                vtable_size = sizeof (gpointer) * (class->max_interface_id + 1) +
-                       sizeof (MonoVTable) + class->vtable_size * sizeof (gpointer);
+                       MONO_SIZEOF_VTABLE + class->vtable_size * sizeof (gpointer);
        }
 
        mono_stats.used_class_count++;
@@ -1682,7 +1810,7 @@ mono_class_create_runtime_vtable (MonoDomain *domain, MonoClass *class)
 
                        bitmap = compute_class_bitmap (class, default_bitmap, sizeof (default_bitmap) * 8, 0, &max_set, TRUE);
                        /*g_print ("bitmap 0x%x for %s.%s (size: %d)\n", bitmap [0], class->name_space, class->name, class_size);*/
-                       statics_gc_descr = mono_gc_make_descr_from_bitmap (bitmap, max_set? max_set + 1: 0);
+                       statics_gc_descr = mono_gc_make_descr_from_bitmap (bitmap, max_set + 1);
                        vt->data = mono_gc_alloc_fixed (class_size, statics_gc_descr);
                        mono_domain_add_class_static_data (domain, class, vt->data, NULL);
                        if (bitmap != default_bitmap)
@@ -1710,6 +1838,11 @@ mono_class_create_runtime_vtable (MonoDomain *domain, MonoClass *class)
                                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));
+                               /* 
+                                * This marks the field as special static to speed up the
+                                * checks in mono_field_static_get/set_value ().
+                                */
+                               field->offset = -1;
                                continue;
                        }
                }
@@ -1756,7 +1889,7 @@ mono_class_create_runtime_vtable (MonoDomain *domain, MonoClass *class)
        /* class->runtime_info is protected by the loader lock, both when
         * it it enlarged and when it is stored info.
         */
-       mono_loader_lock ();
+
        old_info = class->runtime_info;
        if (old_info && old_info->max_domain >= domain->domain_id) {
                /* someone already created a large enough runtime info */
@@ -1775,7 +1908,7 @@ mono_class_create_runtime_vtable (MonoDomain *domain, MonoClass *class)
                /* this is a bounded memory retention issue: may want to 
                 * handle it differently when we'll have a rcu-like system.
                 */
-               runtime_info = mono_image_alloc0 (class->image, sizeof (MonoClassRuntimeInfo) + new_size * sizeof (gpointer));
+               runtime_info = mono_image_alloc0 (class->image, MONO_SIZEOF_CLASS_RUNTIME_INFO + new_size * sizeof (gpointer));
                runtime_info->max_domain = new_size - 1;
                /* copy the stuff from the older info */
                if (old_info) {
@@ -1786,7 +1919,6 @@ mono_class_create_runtime_vtable (MonoDomain *domain, MonoClass *class)
                mono_memory_barrier ();
                class->runtime_info = runtime_info;
        }
-       mono_loader_unlock ();
 
        /* Initialize vtable */
        if (vtable_trampoline) {
@@ -1800,13 +1932,8 @@ mono_class_create_runtime_vtable (MonoDomain *domain, MonoClass *class)
                for (i = 0; i < class->vtable_size; ++i) {
                        MonoMethod *cm;
 
-                       if ((cm = class->vtable [i])) {
-                               if (mono_method_signature (cm)->generic_param_count)
-                                       /* FIXME: Why is this needed ? */
-                                       vt->vtable [i] = cm;
-                               else
-                                       vt->vtable [i] = vtable_trampoline? vtable_trampoline: arch_create_jit_trampoline (cm);
-                       }
+                       if ((cm = class->vtable [i]))
+                               vt->vtable [i] = vtable_trampoline? vtable_trampoline: arch_create_jit_trampoline (cm);
                }
        }
 
@@ -1822,6 +1949,7 @@ mono_class_create_runtime_vtable (MonoDomain *domain, MonoClass *class)
        }
 
        mono_domain_unlock (domain);
+       mono_loader_unlock ();
 
        /* Initialization is now complete, we can throw if the InheritanceDemand aren't satisfied */
        if (mono_is_security_manager_active () && (class->exception_type == MONO_EXCEPTION_SECURITY_INHERITANCEDEMAND)) {
@@ -1903,10 +2031,10 @@ mono_class_proxy_vtable (MonoDomain *domain, MonoRemoteClass *remote_class, Mono
                mono_stats.imt_number_of_tables++;
                mono_stats.imt_tables_size += (sizeof (gpointer) * MONO_IMT_SIZE);
                vtsize = sizeof (gpointer) * (MONO_IMT_SIZE) +
-                       sizeof (MonoVTable) + class->vtable_size * sizeof (gpointer);
+                       MONO_SIZEOF_VTABLE + class->vtable_size * sizeof (gpointer);
        } else {
                vtsize = sizeof (gpointer) * (max_interface_id + 1) +
-                       sizeof (MonoVTable) + class->vtable_size * sizeof (gpointer);
+                       MONO_SIZEOF_VTABLE + class->vtable_size * sizeof (gpointer);
        }
 
        mono_stats.class_vtable_size += vtsize + extra_interface_vtsize;
@@ -1916,7 +2044,7 @@ mono_class_proxy_vtable (MonoDomain *domain, MonoRemoteClass *remote_class, Mono
                pvt = (MonoVTable*) (interface_offsets + MONO_IMT_SIZE);
        else
                pvt = (MonoVTable*) (interface_offsets + max_interface_id + 1);
-       memcpy (pvt, vt, sizeof (MonoVTable) + class->vtable_size * sizeof (gpointer));
+       memcpy (pvt, vt, MONO_SIZEOF_VTABLE + class->vtable_size * sizeof (gpointer));
 
        pvt->klass = mono_defaults.transparent_proxy_class;
        /* we need to keep the GC descriptor for a transparent proxy or we confuse the precise GC */
@@ -2136,12 +2264,12 @@ mono_remote_class (MonoDomain *domain, MonoString *class_name, MonoClass *proxy_
        key = mp_key;
 
        if (proxy_class->flags & TYPE_ATTRIBUTE_INTERFACE) {
-               rc = mono_domain_alloc (domain, sizeof(MonoRemoteClass) + sizeof(MonoClass*));
+               rc = mono_domain_alloc (domain, MONO_SIZEOF_REMOTE_CLASS + sizeof(MonoClass*));
                rc->interface_count = 1;
                rc->interfaces [0] = proxy_class;
                rc->proxy_class = mono_defaults.marshalbyrefobject_class;
        } else {
-               rc = mono_domain_alloc (domain, sizeof(MonoRemoteClass));
+               rc = mono_domain_alloc (domain, MONO_SIZEOF_REMOTE_CLASS);
                rc->interface_count = 0;
                rc->proxy_class = proxy_class;
        }
@@ -2180,7 +2308,7 @@ clone_remote_class (MonoDomain *domain, MonoRemoteClass* remote_class, MonoClass
 
        if (extra_class->flags & TYPE_ATTRIBUTE_INTERFACE) {
                int i,j;
-               rc = mono_domain_alloc (domain, sizeof(MonoRemoteClass) + sizeof(MonoClass*) * (remote_class->interface_count + 1));
+               rc = mono_domain_alloc (domain, MONO_SIZEOF_REMOTE_CLASS + sizeof(MonoClass*) * (remote_class->interface_count + 1));
                rc->proxy_class = remote_class->proxy_class;
                rc->interface_count = remote_class->interface_count + 1;
                
@@ -2195,7 +2323,7 @@ clone_remote_class (MonoDomain *domain, MonoRemoteClass* remote_class, MonoClass
                        rc->interfaces [j] = extra_class;
        } else {
                // Replace the old class. The interface array is the same
-               rc = mono_domain_alloc (domain, sizeof(MonoRemoteClass) + sizeof(MonoClass*) * remote_class->interface_count);
+               rc = mono_domain_alloc (domain, MONO_SIZEOF_REMOTE_CLASS + sizeof(MonoClass*) * remote_class->interface_count);
                rc->proxy_class = extra_class;
                rc->interface_count = remote_class->interface_count;
                if (rc->interface_count > 0)
@@ -2214,11 +2342,13 @@ clone_remote_class (MonoDomain *domain, MonoRemoteClass* remote_class, MonoClass
 gpointer
 mono_remote_class_vtable (MonoDomain *domain, MonoRemoteClass *remote_class, MonoRealProxy *rp)
 {
+       mono_loader_lock (); /*FIXME mono_class_from_mono_type and mono_class_proxy_vtable take it*/
        mono_domain_lock (domain);
        if (rp->target_domain_id != -1) {
                if (remote_class->xdomain_vtable == NULL)
                        remote_class->xdomain_vtable = mono_class_proxy_vtable (domain, remote_class, MONO_REMOTING_TARGET_APPDOMAIN);
                mono_domain_unlock (domain);
+               mono_loader_unlock ();
                return remote_class->xdomain_vtable;
        }
        if (remote_class->default_vtable == NULL) {
@@ -2233,6 +2363,7 @@ mono_remote_class_vtable (MonoDomain *domain, MonoRemoteClass *remote_class, Mon
        }
        
        mono_domain_unlock (domain);
+       mono_loader_unlock ();
        return remote_class->default_vtable;
 }
 
@@ -2253,6 +2384,7 @@ mono_upgrade_remote_class (MonoDomain *domain, MonoObject *proxy_object, MonoCla
        MonoRemoteClass *remote_class;
        gboolean redo_vtable;
 
+       mono_loader_lock (); /*FIXME mono_remote_class_vtable requires it.*/
        mono_domain_lock (domain);
 
        tproxy = (MonoTransparentProxy*) proxy_object;
@@ -2275,6 +2407,7 @@ mono_upgrade_remote_class (MonoDomain *domain, MonoObject *proxy_object, MonoCla
        }
        
        mono_domain_unlock (domain);
+       mono_loader_unlock ();
 }
 
 
@@ -2337,10 +2470,16 @@ mono_object_get_virtual_method (MonoObject *obj, MonoMethod *method)
                /* generic methods demand invoke_with_check */
                if (mono_method_signature (res)->generic_param_count)
                        res = mono_marshal_get_remoting_invoke_with_check (res);
-               else
-                       res = mono_marshal_get_remoting_invoke (res);
+               else {
+#ifndef DISABLE_COM
+                       if (klass == mono_defaults.com_object_class || klass->is_com_object)
+                               res = mono_cominterop_get_invoke (res);
+                       else
+#endif
+                               res = mono_marshal_get_remoting_invoke (res);
+               }
        } else {
-               if (method->is_inflated && !res->is_inflated) {
+               if (method->is_inflated) {
                        /* Have to inflate the result */
                        res = mono_class_inflate_generic_method (res, &((MonoMethodInflated*)method)->context);
                }
@@ -2465,6 +2604,8 @@ set_value (MonoType *type, void *dest, void *value, int deref_pointer)
 {
        int t;
        if (type->byref) {
+               /* object fields cannot be byref, so we don't need a
+                  wbarrier here */
                gpointer *p = (gpointer*)dest;
                *p = value;
                return;
@@ -2535,12 +2676,14 @@ handle_enum:
                        t = mono_class_enum_basetype (type->data.klass)->type;
                        goto handle_enum;
                } else {
-                       int size;
-                       size = mono_class_value_size (mono_class_from_mono_type (type), NULL);
-                       if (value == NULL)
+                       MonoClass *class = mono_class_from_mono_type (type);
+                       int size = mono_class_value_size (class, NULL);
+                       if (value == NULL) {
                                memset (dest, 0, size);
-                       else
+                       } else {
                                memcpy (dest, value, size);
+                               mono_gc_wbarrier_value_copy (dest, value, size, class);
+                       }
                }
                return;
        case MONO_TYPE_GENERICINST:
@@ -2593,8 +2736,14 @@ mono_field_static_set_value (MonoVTable *vt, MonoClassField *field, void *value)
        g_return_if_fail (field->type->attrs & FIELD_ATTRIBUTE_STATIC);
        /* you cant set a constant! */
        g_return_if_fail (!(field->type->attrs & FIELD_ATTRIBUTE_LITERAL));
-       
-       dest = (char*)vt->data + field->offset;
+
+       if (field->offset == -1) {
+               /* Special static */
+               gpointer addr = g_hash_table_lookup (vt->domain->special_static_fields, field);
+               dest = mono_get_special_static_data (GPOINTER_TO_UINT (addr));
+       } else {
+               dest = (char*)vt->data + field->offset;
+       }
        set_value (field->type, dest, value, FALSE);
 }
 
@@ -2799,7 +2948,13 @@ mono_field_static_get_value (MonoVTable *vt, MonoClassField *field, void *value)
                return;
        }
 
-       src = (char*)vt->data + field->offset;
+       if (field->offset == -1) {
+               /* Special static */
+               gpointer addr = g_hash_table_lookup (vt->domain->special_static_fields, field);
+               src = mono_get_special_static_data (GPOINTER_TO_UINT (addr));
+       } else {
+               src = (char*)vt->data + field->offset;
+       }
        set_value (field->type, value, src, TRUE);
 }
 
@@ -2912,6 +3067,9 @@ mono_get_delegate_invoke (MonoClass *klass)
 {
        MonoMethod *im;
 
+       /* This is called at runtime, so avoid the slower search in metadata */
+       mono_class_setup_methods (klass);
+
        im = mono_class_get_method_from_name (klass, "Invoke", -1);
        g_assert (im);
 
@@ -3449,8 +3607,21 @@ mono_runtime_invoke_array (MonoMethod *method, void *obj, MonoArray *params,
                                else
                                        t = &t->data.generic_class->container_class->byval_arg;
                                goto again;
+                       case MONO_TYPE_PTR: {
+                               MonoObject *arg;
+
+                               /* The argument should be an IntPtr */
+                               arg = mono_array_get (params, MonoObject*, i);
+                               if (arg == NULL) {
+                                       pa [i] = NULL;
+                               } else {
+                                       g_assert (arg->vtable->klass == mono_defaults.int_class);
+                                       pa [i] = ((MonoIntPtr*)arg)->m_value;
+                               }
+                               break;
+                       }
                        default:
-                               g_error ("type 0x%x not handled in ves_icall_InternalInvoke", sig->params [i]->type);
+                               g_error ("type 0x%x not handled in mono_runtime_invoke_array", sig->params [i]->type);
                        }
                }
        }
@@ -3497,6 +3668,27 @@ mono_runtime_invoke_array (MonoMethod *method, void *obj, MonoArray *params,
                /* obj must be already unboxed if needed */
                res = mono_runtime_invoke (method, obj, pa, exc);
 
+               if (sig->ret->type == MONO_TYPE_PTR) {
+                       MonoClass *pointer_class;
+                       static MonoMethod *box_method;
+                       void *box_args [2];
+                       MonoObject *box_exc;
+
+                       /* 
+                        * The runtime-invoke wrapper returns a boxed IntPtr, need to 
+                        * convert it to a Pointer object.
+                        */
+                       pointer_class = mono_class_from_name_cached (mono_defaults.corlib, "System.Reflection", "Pointer");
+                       if (!box_method)
+                               box_method = mono_class_get_method_from_name (pointer_class, "Box", -1);
+
+                       g_assert (res->vtable->klass == mono_defaults.int_class);
+                       box_args [0] = ((MonoIntPtr*)res)->m_value;
+                       box_args [1] = mono_type_get_object (mono_domain_get (), sig->ret);
+                       res = mono_runtime_invoke (box_method, NULL, box_args, &box_exc);
+                       g_assert (!box_exc);
+               }
+
                if (has_byref_nullables) {
                        /* 
                         * The runtime invoke wrapper already converted byref nullables back,
@@ -4719,24 +4911,27 @@ mono_string_from_utf16 (gunichar2 *data)
        return mono_string_new_utf16 (domain, data, len);
 }
 
-/**
- * mono_string_to_utf8_mp:
- * @s: a System.String
- *
- * Same as mono_string_to_utf8, but allocate the string from a mempool.
- */
-char *
-mono_string_to_utf8_mp (MonoMemPool *mp, MonoString *s)
+
+static char *
+mono_string_to_utf8_internal (MonoMemPool *mp, MonoImage *image, MonoString *s)
 {
-       char *r = mono_string_to_utf8 (s);
+       char *r;
        char *mp_s;
        int len;
 
+       if (!mp && !image)
+               return mono_string_to_utf8 (s);
+
+       r = mono_string_to_utf8 (s);
        if (!r)
                return NULL;
 
        len = strlen (r) + 1;
-       mp_s = mono_mempool_alloc (mp, len);
+       if (mp)
+               mp_s = mono_mempool_alloc (mp, len);
+       else
+               mp_s = mono_image_alloc (image, len);
+
        memcpy (mp_s, r, len);
 
        g_free (r);
@@ -4744,6 +4939,30 @@ mono_string_to_utf8_mp (MonoMemPool *mp, MonoString *s)
        return mp_s;
 }
 
+/**
+ * mono_string_to_utf8_image:
+ * @s: a System.String
+ *
+ * Same as mono_string_to_utf8, but allocate the string from the image mempool.
+ */
+char *
+mono_string_to_utf8_image (MonoImage *image, MonoString *s)
+{
+       return mono_string_to_utf8_internal (NULL, image, s);
+}
+
+/**
+ * mono_string_to_utf8_mp:
+ * @s: a System.String
+ *
+ * Same as mono_string_to_utf8, but allocate the string from a mempool.
+ */
+char *
+mono_string_to_utf8_mp (MonoMemPool *mp, MonoString *s)
+{
+       return mono_string_to_utf8_internal (mp, NULL, s);
+}
+
 static void
 default_ex_handler (MonoException *ex)
 {
@@ -4783,8 +5002,11 @@ mono_raise_exception (MonoException *ex)
         * will point into the next function in the executable, not this one.
         */
 
-       if (((MonoObject*)ex)->vtable->klass == mono_defaults.threadabortexception_class)
-               MONO_OBJECT_SETREF (mono_thread_current (), abort_exc, ex);
+       if (((MonoObject*)ex)->vtable->klass == mono_defaults.threadabortexception_class) {
+               MonoThread *thread = mono_thread_current ();
+               g_assert (ex->object.vtable->domain == mono_domain_get ());
+               MONO_OBJECT_SETREF (thread, abort_exc, ex);
+       }
        
        ex_handler (ex);
 }
@@ -4837,6 +5059,26 @@ mono_wait_handle_get_handle (MonoWaitHandle *handle)
        }
 }
 
+
+static MonoObject*
+mono_runtime_capture_context (MonoDomain *domain)
+{
+       RuntimeInvokeFunction runtime_invoke;
+
+       if (!domain->capture_context_runtime_invoke || !domain->capture_context_method) {
+               MonoMethod *method = mono_get_context_capture_method ();
+               MonoMethod *wrapper;
+               if (!method)
+                       return NULL;
+               wrapper = mono_marshal_get_runtime_invoke (method, FALSE);
+               domain->capture_context_runtime_invoke = mono_compile_method (wrapper);
+               domain->capture_context_method = mono_compile_method (method);
+       }
+
+       runtime_invoke = domain->capture_context_runtime_invoke;
+
+       return runtime_invoke (NULL, NULL, NULL, domain->capture_context_method);
+}
 /**
  * mono_async_result_new:
  * @domain:domain where the object will be created.
@@ -4852,11 +5094,10 @@ MonoAsyncResult *
 mono_async_result_new (MonoDomain *domain, HANDLE handle, MonoObject *state, gpointer data, MonoObject *object_data)
 {
        MonoAsyncResult *res = (MonoAsyncResult *)mono_object_new (domain, mono_defaults.asyncresult_class);
-       MonoMethod *method = mono_get_context_capture_method ();
-
+       MonoObject *context = mono_runtime_capture_context (domain);
        /* we must capture the execution context from the original thread */
-       if (method) {
-               MONO_OBJECT_SETREF (res, execution_context, mono_runtime_invoke (method, NULL, NULL, NULL));
+       if (context) {
+               MONO_OBJECT_SETREF (res, execution_context, context);
                /* note: result may be null if the flow is suppressed */
        }
 
@@ -5523,53 +5764,24 @@ mono_store_remote_field_new (MonoObject *this, MonoClass *klass, MonoClassField
  * mono_create_ftnptr:
  *
  *   Given a function address, create a function descriptor for it.
- * This is only needed on IA64 and PPC64.
+ * This is only needed on some platforms.
  */
 gpointer
 mono_create_ftnptr (MonoDomain *domain, gpointer addr)
 {
-#ifdef __ia64__
-       gpointer *desc;
-
-       mono_domain_lock (domain);
-       desc = mono_code_manager_reserve (domain->code_mp, 2 * sizeof (gpointer));
-       mono_domain_unlock (domain);
-
-       desc [0] = addr;
-       desc [1] = NULL;
-
-       return desc;
-#elif defined(__ppc64__) || defined(__powerpc64__)
-       gpointer *desc;
-
-       mono_domain_lock (domain);
-       desc = mono_code_manager_reserve (domain->code_mp, 3 * sizeof (gpointer));
-       mono_domain_unlock (domain);
-
-       desc [0] = addr;
-       desc [1] = NULL;
-       desc [2] = NULL;
-
-       return desc;
-#else
-       return addr;
-#endif
+       return callbacks.create_ftnptr (domain, addr);
 }
 
 /*
  * mono_get_addr_from_ftnptr:
  *
  *   Given a pointer to a function descriptor, return the function address.
- * This is only needed on IA64 and PPC64.
+ * This is only needed on some platforms.
  */
 gpointer
 mono_get_addr_from_ftnptr (gpointer descr)
 {
-#if defined(__ia64__) || defined(__ppc64__) || defined(__powerpc64__)
-       return *(gpointer*)descr;
-#else
-       return descr;
-#endif
+       return callbacks.get_addr_from_ftnptr (descr);
 }      
 
 #if 0