2009-01-13 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mono / metadata / marshal.c
index e66b5b1daf5a2aa3de38b83104aaba4b95964d98..6d321f9f6a4b48e498b439ab808c203111c97696 100644 (file)
@@ -11,7 +11,9 @@
 #include "config.h"
 #include "object.h"
 #include "loader.h"
+#include "cil-coff.h"
 #include "metadata/marshal.h"
+#include "metadata/method-builder.h"
 #include "metadata/tabledefs.h"
 #include "metadata/exception.h"
 #include "metadata/appdomain.h"
@@ -24,7 +26,9 @@
 #include "mono/metadata/gc-internal.h"
 #include "mono/metadata/threads-types.h"
 #include "mono/metadata/string-icalls.h"
-#include <mono/os/gc_wrapper.h>
+#include "mono/metadata/attrdefs.h"
+#include "mono/metadata/gc-internal.h"
+#include "mono/utils/mono-counters.h"
 #include <string.h>
 #include <errno.h>
 
@@ -40,22 +44,19 @@ typedef enum {
        MONO_MARSHAL_SERIALIZE          /* Value needs to be serialized into the new domain */
 } MonoXDomainMarshalType;
 
+typedef enum {
+       MONO_COM_DEFAULT,
+       MONO_COM_MS
+} MonoCOMProvider;
+
+static MonoCOMProvider com_provider = MONO_COM_DEFAULT;
+
 enum {
 #include "mono/cil/opcode.def"
        LAST = 0xff
 };
 #undef OPDEF
 
-struct _MonoMethodBuilder {
-       MonoMethod *method;
-       char *name;
-       GList *locals_list;
-       int locals;
-       gboolean dynamic;
-       guint32 code_size, pos;
-       unsigned char *code;
-};
-
 struct _MonoRemotingMethods {
        MonoMethod *invoke;
        MonoMethod *invoke_with_check;
@@ -65,23 +66,6 @@ struct _MonoRemotingMethods {
 
 typedef struct _MonoRemotingMethods MonoRemotingMethods;
 
-#ifdef DEBUG_RUNTIME_CODE
-static char*
-indenter (MonoDisHelper *dh, MonoMethod *method, guint32 ip_offset)
-{
-       return g_strdup (" ");
-}
-
-static MonoDisHelper marshal_dh = {
-       "\n",
-       "IL_%04x: ",
-       "IL_%04x",
-       indenter, 
-       NULL,
-       NULL
-};
-#endif 
-
 /* 
  * This mutex protects the various marshalling related caches in MonoImage
  * and a few other data structures static to this file.
@@ -97,9 +81,6 @@ static CRITICAL_SECTION marshal_mutex;
 #define mono_cominterop_unlock() LeaveCriticalSection (&cominterop_mutex)
 static CRITICAL_SECTION cominterop_mutex;
 
-/* Maps wrapper methods to the methods they wrap */
-static GHashTable *wrapper_hash;
-
 static guint32 last_error_tls_id;
 
 static guint32 load_type_info_tls_id;
@@ -116,6 +97,9 @@ mono_struct_delete_old (MonoClass *klass, char *ptr);
 void *
 mono_marshal_string_to_utf16 (MonoString *s);
 
+static void *
+mono_marshal_string_to_utf16_copy (MonoString *s);
+
 static gpointer
 mono_string_to_lpstr (MonoString *string_obj);
 
@@ -125,6 +109,9 @@ mono_string_from_bstr (gpointer bstr);
 static void 
 mono_free_bstr (gpointer bstr);
 
+static MonoStringBuilder *
+mono_string_utf8_to_builder2 (char *text);
+
 static void
 mono_byvalarray_to_array (MonoArray *arr, gpointer native_arr, MonoClass *eltype, guint32 elnum);
 
@@ -162,7 +149,7 @@ static void
 mono_marshal_set_last_error_windows (int error);
 
 static void
-mono_marshal_emit_native_wrapper (MonoImage *image, MonoMethodBuilder *mb, MonoMethodSignature *sig, MonoMethodPInvoke *piinfo, MonoMarshalSpec **mspecs, gpointer func);
+mono_marshal_emit_native_wrapper (MonoImage *image, MonoMethodBuilder *mb, MonoMethodSignature *sig, MonoMethodPInvoke *piinfo, MonoMarshalSpec **mspecs, gpointer func, gboolean aot, gboolean check_exceptions);
 
 static void init_safe_handle (void);
 
@@ -194,17 +181,15 @@ signature_dup (MonoImage *image, MonoMethodSignature *sig)
        MonoMethodSignature *res;
        int sigsize;
 
+       res = mono_metadata_signature_alloc (image, sig->param_count);
        sigsize = sizeof (MonoMethodSignature) + ((sig->param_count - MONO_ZERO_LEN_ARRAY) * sizeof (MonoType *));
-       mono_loader_lock ();
-       res = mono_mempool_alloc (image->mempool, sigsize);
-       mono_loader_unlock ();
        memcpy (res, sig, sigsize);
 
        return res;
 }
 
-static MonoMethodSignature*
-signature_no_pinvoke (MonoMethod *method)
+MonoMethodSignature*
+mono_signature_no_pinvoke (MonoMethod *method)
 {
        MonoMethodSignature *sig = mono_method_signature (method);
        if (sig->pinvoke) {
@@ -234,6 +219,9 @@ typedef struct {
        guint32 ref_count;
        guint32 gc_handle;
        GHashTable* vtable_hash;
+#ifdef  PLATFORM_WIN32
+       gpointer free_marshaler;
+#endif
 } MonoCCW;
 
 /* This type is the actual pointer passed to unmanaged code
@@ -244,6 +232,8 @@ typedef struct {
        MonoCCW* ccw;
 } MonoCCWInterface;
 
+#ifndef DISABLE_COM
+
 /* IUnknown */
 static int STDCALL cominterop_ccw_addref (MonoCCWInterface* ccwe);
 
@@ -276,28 +266,28 @@ static MonoObject*
 cominterop_get_ccw_object (MonoCCWInterface* ccw_entry, gboolean verify);
 
 /**
- * signature_cominterop:
- * @image: a image
- * @sig: managed method signature
+ * cominterop_method_signature:
+ * @method: a method
  *
  * Returns: the corresponding unmanaged method signature for a managed COM 
  * method.
  */
 static MonoMethodSignature*
-signature_cominterop (MonoImage *image, MonoMethodSignature *sig)
+cominterop_method_signature (MonoMethod* method)
 {
        MonoMethodSignature *res;
+       MonoImage *image = method->klass->image;
+       MonoMethodSignature *sig = mono_method_signature (method);
+       gboolean preserve_sig = method->iflags & METHOD_IMPL_ATTRIBUTE_PRESERVE_SIG;
        int sigsize;
        int i;
        int param_count = sig->param_count + 1; // convert this arg into IntPtr arg
 
-       if (!MONO_TYPE_IS_VOID (sig->ret))
+       if (!preserve_sig &&!MONO_TYPE_IS_VOID (sig->ret))
                param_count++;
 
-       sigsize = sizeof (MonoMethodSignature) + ((param_count - MONO_ZERO_LEN_ARRAY) * sizeof (MonoType *));
-       mono_loader_lock ();
-       res = mono_mempool_alloc (image->mempool, sigsize);
-       mono_loader_unlock ();
+       res = mono_metadata_signature_alloc (image, param_count);
+       sigsize = sizeof (MonoMethodSignature) + ((sig->param_count - MONO_ZERO_LEN_ARRAY) * sizeof (MonoType *));
        memcpy (res, sig, sigsize);
 
        // now move args forward one
@@ -307,11 +297,19 @@ signature_cominterop (MonoImage *image, MonoMethodSignature *sig)
        // first arg is interface pointer
        res->params[0] = &mono_defaults.int_class->byval_arg;
 
-       // last arg is return type
-       if (!MONO_TYPE_IS_VOID (sig->ret)) {
-               res->params[param_count-1] = mono_metadata_type_dup_mp (image, sig->ret);
-               res->params[param_count-1]->byref = 1;
-               res->params[param_count-1]->attrs = PARAM_ATTRIBUTE_OUT;
+       if (preserve_sig) {
+               res->ret = sig->ret;
+       }
+       else {
+               // last arg is return type
+               if (!MONO_TYPE_IS_VOID (sig->ret)) {
+                       res->params[param_count-1] = mono_metadata_type_dup (image->mempool, sig->ret);
+                       res->params[param_count-1]->byref = 1;
+                       res->params[param_count-1]->attrs = PARAM_ATTRIBUTE_OUT;
+               }
+
+               // return type is always int32 (HRESULT)
+               res->ret = &mono_defaults.int32_class->byval_arg;
        }
 
        // no pinvoke
@@ -323,9 +321,6 @@ signature_cominterop (MonoImage *image, MonoMethodSignature *sig)
        // set param_count
        res->param_count = param_count;
 
-       // return type is always int32 (HRESULT)
-       res->ret = &mono_defaults.int32_class->byval_arg;
-
        // STDCALL on windows, CDECL everywhere else to work with XPCOM and MainWin COM
 #ifdef PLATFORM_WIN32
        res->call_convention = MONO_CALL_STDCALL;
@@ -399,6 +394,41 @@ cominterop_get_com_slot_begin (MonoClass* klass)
                return 7; /* 7 methods in IDispatch*/
 }
 
+/**
+ * cominterop_get_method_interface:
+ * @method: method being called
+ *
+ * Returns: the MonoClass* representing the interface on which
+ * the method is defined.
+ */
+static MonoClass*
+cominterop_get_method_interface (MonoMethod* method)
+{
+       MonoClass *ic = method->klass;
+
+       /* if method is on a class, we need to look up interface method exists on */
+       if (!MONO_CLASS_IS_INTERFACE(method->klass)) {
+               GPtrArray *ifaces = mono_class_get_implemented_interfaces (method->klass);
+               if (ifaces) {
+                       int i;
+                       for (i = 0; i < ifaces->len; ++i) {
+                               int offset;
+                               ic = g_ptr_array_index (ifaces, i);
+                               offset = mono_class_interface_offset (method->klass, ic);
+                               if (method->slot >= offset && method->slot < offset + ic->method.count)
+                                       break;
+                               ic = NULL;
+                       }
+                       g_ptr_array_free (ifaces, TRUE);
+               }
+       }
+
+       g_assert (ic);
+       g_assert (MONO_CLASS_IS_INTERFACE (ic));
+
+       return ic;
+}
+
 /**
  * cominterop_get_com_slot_for_method:
  * @method: a method
@@ -409,71 +439,131 @@ static int
 cominterop_get_com_slot_for_method (MonoMethod* method)
 {
        guint32 slot = method->slot;
-       GPtrArray *ifaces;
-       MonoClass *ic = NULL;
-       int i;
+       MonoClass *ic = method->klass;
 
-       ifaces = mono_class_get_implemented_interfaces (method->klass);
-       if (ifaces) {
-               int offset;
-               for (i = 0; i < ifaces->len; ++i) {
-                       ic = g_ptr_array_index (ifaces, i);
-                       offset = method->klass->interface_offsets[ic->interface_id];
-                       if (method->slot >= offset && method->slot < offset + ic->method.count) {
-                               slot -= offset;
-                               break;
-                       }
-               }
-               g_ptr_array_free (ifaces, TRUE);
+       /* if method is on a class, we need to look up interface method exists on */
+       if (!MONO_CLASS_IS_INTERFACE(ic)) {
+               int offset = 0;
+               ic = cominterop_get_method_interface (method);
+               offset = mono_class_interface_offset (method->klass, ic);
+               g_assert(offset >= 0);
+               slot -= offset;
        }
 
-       if (!ic)
-               ic = method->klass;
-       
        g_assert (ic);
        g_assert (MONO_CLASS_IS_INTERFACE (ic));
 
        return slot + cominterop_get_com_slot_begin (ic);
 }
 
-/**
- * cominterop_get_method_interface:
- * @method: method being called
- *
- * Returns: the Type on which the method is defined on
- */
-static MonoReflectionType*
-cominterop_get_method_interface (MonoMethod* method)
+
+static void
+cominterop_mono_string_to_guid (const MonoString* string, guint8 *guid);
+
+static gboolean
+cominterop_class_guid (MonoClass* klass, guint8* guid)
 {
-       GPtrArray *ifaces;
-       MonoType* t = NULL;
-       MonoClass *ic = NULL;
-       int i;
-       MonoReflectionType* rt = NULL;
+       static MonoClass *GuidAttribute = NULL;
+       MonoCustomAttrInfo *cinfo;
 
-       ifaces = mono_class_get_implemented_interfaces (method->klass);
-       if (ifaces) {
-               int offset;
-               for (i = 0; i < ifaces->len; ++i) {
-                       ic = g_ptr_array_index (ifaces, i);
-                       offset = method->klass->interface_offsets[ic->interface_id];
-                       if (method->slot >= offset && method->slot < offset + ic->method.count)
-                               break;
-                       ic = NULL;
-               }
-               g_ptr_array_free (ifaces, TRUE);
+       /* Handle the GuidAttribute */
+       if (!GuidAttribute)
+               GuidAttribute = mono_class_from_name (mono_defaults.corlib, "System.Runtime.InteropServices", "GuidAttribute");
+
+       cinfo = mono_custom_attrs_from_class (klass);   
+       if (cinfo) {
+               MonoReflectionGuidAttribute *attr = (MonoReflectionGuidAttribute*)mono_custom_attrs_get_attr (cinfo, GuidAttribute);
+
+               if (!attr)
+                       return FALSE;
+               if (!cinfo->cached)
+                       mono_custom_attrs_free (cinfo);
+
+               cominterop_mono_string_to_guid (attr->guid, guid);
+               return TRUE;
+       }
+       return FALSE;
+}
+
+static gboolean
+cominterop_com_visible (MonoClass* klass)
+{
+       static MonoClass *ComVisibleAttribute = NULL;
+       MonoCustomAttrInfo *cinfo;
+
+       /* Handle the ComVisibleAttribute */
+       if (!ComVisibleAttribute)
+               ComVisibleAttribute = mono_class_from_name (mono_defaults.corlib, "System.Runtime.InteropServices", "ComVisibleAttribute");
+
+       cinfo = mono_custom_attrs_from_class (klass);   
+       if (cinfo) {
+               MonoReflectionComVisibleAttribute *attr = (MonoReflectionComVisibleAttribute*)mono_custom_attrs_get_attr (cinfo, ComVisibleAttribute);
+
+               if (!attr)
+                       return FALSE;
+               if (!cinfo->cached)
+                       mono_custom_attrs_free (cinfo);
+
+               if (attr->visible)
+                       return TRUE;
        }
+       return FALSE;
+}
+
+static void cominterop_raise_hr_exception (int hr)
+{
+       static MonoMethod* throw_exception_for_hr = NULL;
+       MonoException* ex;
+       void* params[1] = {&hr};
+       if (!throw_exception_for_hr)
+               throw_exception_for_hr = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetExceptionForHR", 1);
+       ex = (MonoException*)mono_runtime_invoke (throw_exception_for_hr, NULL, params, NULL);
+       mono_raise_exception (ex);
+}
 
-       if (!ic)
-               ic = method->klass;
+/**
+ * cominterop_get_interface:
+ * @obj: managed wrapper object containing COM object
+ * @ic: interface type to retrieve for COM object
+ *
+ * Returns: the COM interface requested
+ */
+static gpointer
+cominterop_get_interface (MonoComObject* obj, MonoClass* ic, gboolean throw_exception)
+{
+       gpointer itf = NULL;
 
        g_assert (ic);
        g_assert (MONO_CLASS_IS_INTERFACE (ic));
 
-       t = mono_class_get_type (ic);
-       rt = mono_type_get_object (mono_domain_get(), t);
+       mono_cominterop_lock ();
+       if (obj->itf_hash)
+               itf = g_hash_table_lookup (obj->itf_hash, GUINT_TO_POINTER ((guint)ic->interface_id));
+       mono_cominterop_unlock ();
+
+       if (!itf) {
+               guint8 iid [16];
+               int found = cominterop_class_guid (ic, iid);
+               int hr;
+               g_assert(found);
+               hr = ves_icall_System_Runtime_InteropServices_Marshal_QueryInterfaceInternal (obj->iunknown, iid, &itf);
+               if (hr < 0 && throw_exception) {
+                       cominterop_raise_hr_exception (hr);     
+               }
+
+               if (hr >= 0 && itf) {
+                       mono_cominterop_lock ();
+                       if (!obj->itf_hash)
+                               obj->itf_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
+                       g_hash_table_insert (obj->itf_hash, GUINT_TO_POINTER ((guint)ic->interface_id), itf);
+                       mono_cominterop_unlock ();
+               }
+
+       }
+       if (throw_exception)
+               g_assert (itf);
 
-       return rt;
+       return itf;
 }
 
 static int
@@ -483,20 +573,28 @@ cominterop_get_hresult_for_exception (MonoException* exc)
        return hr;
 }
 
+#endif /* DISABLE_COM */
+
 void
 mono_marshal_init (void)
 {
        static gboolean module_initialized = FALSE;
 
        if (!module_initialized) {
+               char* com_provider_env = NULL;
                module_initialized = TRUE;
                InitializeCriticalSection (&marshal_mutex);
                InitializeCriticalSection (&cominterop_mutex);
-               wrapper_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
                last_error_tls_id = TlsAlloc ();
                load_type_info_tls_id = TlsAlloc ();
 
+               com_provider_env = getenv ("MONO_COM");
+               if (com_provider_env && !strcmp(com_provider_env, "MS"))
+                       com_provider = MONO_COM_MS;
+
+               register_icall (ves_icall_System_Threading_Thread_ResetAbort, "ves_icall_System_Threading_Thread_ResetAbort", "void", TRUE);
                register_icall (mono_marshal_string_to_utf16, "mono_marshal_string_to_utf16", "ptr obj", FALSE);
+               register_icall (mono_marshal_string_to_utf16_copy, "mono_marshal_string_to_utf16_copy", "ptr obj", FALSE);
                register_icall (mono_string_to_utf16, "mono_string_to_utf16", "ptr obj", FALSE);
                register_icall (mono_string_from_utf16, "mono_string_from_utf16", "obj ptr", FALSE);
                register_icall (mono_string_new_wrapper, "mono_string_new_wrapper", "obj ptr", FALSE);
@@ -521,6 +619,7 @@ mono_marshal_init (void)
                register_icall (mono_marshal_set_last_error, "mono_marshal_set_last_error", "void", FALSE);
                register_icall (mono_marshal_set_last_error_windows, "mono_marshal_set_last_error_windows", "void int32", FALSE);
                register_icall (mono_string_utf8_to_builder, "mono_string_utf8_to_builder", "void ptr ptr", FALSE);
+               register_icall (mono_string_utf8_to_builder2, "mono_string_utf8_to_builder2", "object ptr", FALSE);
                register_icall (mono_string_utf16_to_builder, "mono_string_utf16_to_builder", "void ptr ptr", FALSE);
                register_icall (mono_marshal_free_array, "mono_marshal_free_array", "void ptr int32", FALSE);
                register_icall (mono_string_to_byvalstr, "mono_string_to_byvalstr", "void ptr ptr int32", FALSE);
@@ -541,19 +640,21 @@ mono_marshal_init (void)
                register_icall (mono_upgrade_remote_class_wrapper, "mono_upgrade_remote_class_wrapper", "void object object", FALSE);
                register_icall (type_from_handle, "type_from_handle", "object ptr", FALSE);
                register_icall (mono_gc_wbarrier_generic_store, "wb_generic", "void ptr object", FALSE);
-               register_icall (cominterop_get_method_interface, "cominterop_get_method_interface", "object ptr", FALSE);
+#ifndef DISABLE_COM
+               register_icall (cominterop_get_method_interface, "cominterop_get_method_interface", "ptr ptr", FALSE);
                register_icall (cominterop_get_function_pointer, "cominterop_get_function_pointer", "ptr ptr int32", FALSE);
                register_icall (cominterop_object_is_rcw, "cominterop_object_is_rcw", "int32 object", FALSE);
                register_icall (cominterop_get_ccw, "cominterop_get_ccw", "ptr object ptr", FALSE);
                register_icall (cominterop_get_ccw_object, "cominterop_get_ccw_object", "object ptr int32", FALSE);
                register_icall (cominterop_get_hresult_for_exception, "cominterop_get_hresult_for_exception", "int32 object", FALSE);
+               register_icall (cominterop_get_interface, "cominterop_get_interface", "ptr object ptr int32", FALSE);
+#endif /* DISABLE_COM */
        }
 }
 
 void
 mono_marshal_cleanup (void)
 {
-       g_hash_table_destroy (wrapper_hash);
        TlsFree (load_type_info_tls_id);
        TlsFree (last_error_tls_id);
        DeleteCriticalSection (&marshal_mutex);
@@ -616,7 +717,7 @@ mono_delegate_to_ftnptr (MonoDelegate *delegate)
        klass = ((MonoObject *)delegate)->vtable->klass;
        g_assert (klass->delegate);
 
-       method = delegate->method_info->method;
+       method = delegate->method;
 
        wrapper = mono_marshal_get_managed_wrapper (method, klass, delegate->target);
 
@@ -750,7 +851,7 @@ mono_ftnptr_to_delegate (MonoClass *klass, gpointer ftn)
                g_free (sig);
 
                d = (MonoDelegate*)mono_object_new (mono_domain_get (), klass);
-               mono_delegate_ctor ((MonoObject*)d, NULL, mono_compile_method (wrapper));
+               mono_delegate_ctor_with_method ((MonoObject*)d, NULL, mono_compile_method (wrapper), wrapper);
        }
 
        if (d->object.vtable->domain != mono_domain_get ())
@@ -880,6 +981,43 @@ mono_string_utf8_to_builder (MonoStringBuilder *sb, char *text)
        g_free (ut);
 }
 
+MonoStringBuilder *
+mono_string_utf8_to_builder2 (char *text)
+{
+       int l;
+       MonoStringBuilder *sb;
+       static MonoClass *string_builder_class;
+       static MonoMethod *sb_ctor;
+       void *args [1];
+       MonoObject *exc;
+
+       if (!text)
+               return NULL;
+
+       if (!string_builder_class) {
+               MonoMethodDesc *desc;
+
+               string_builder_class = mono_class_from_name (mono_defaults.corlib, "System.Text", "StringBuilder");
+               g_assert (string_builder_class);
+               desc = mono_method_desc_new (":.ctor(int)", FALSE);
+               sb_ctor = mono_method_desc_search_in_class (desc, string_builder_class);
+               g_assert (sb_ctor);
+               mono_method_desc_free (desc);
+       }
+
+       l = strlen (text);
+
+       sb = (MonoStringBuilder*)mono_object_new (mono_domain_get (), string_builder_class);
+       g_assert (sb);
+       args [0] = &l;
+       mono_runtime_invoke (sb_ctor, sb, args, &exc);
+       g_assert (!exc);
+
+       mono_string_utf8_to_builder (sb, text);
+
+       return sb;
+}
+
 /*
  * FIXME: This routine does not seem to do what it seems to do
  * the @text is never copied into the string builder
@@ -914,8 +1052,7 @@ gpointer
 mono_string_builder_to_utf8 (MonoStringBuilder *sb)
 {
        GError *error = NULL;
-       glong *res;
-       gchar *tmp;
+       gchar *tmp, *res = NULL;
 
        if (!sb)
                return NULL;
@@ -929,14 +1066,12 @@ mono_string_builder_to_utf8 (MonoStringBuilder *sb)
                sb->cached_str = NULL;
        }
 
-       res = mono_marshal_alloc (mono_stringbuilder_capacity (sb) + 1);
-
-       tmp = g_utf16_to_utf8 (mono_string_chars (sb->str), sb->length, NULL, res, &error);
+       tmp = g_utf16_to_utf8 (mono_string_chars (sb->str), sb->length, NULL, NULL, &error);
        if (error) {
                g_error_free (error);
-               mono_marshal_free (res);
                mono_raise_exception (mono_get_exception_execution_engine ("Failed to convert StringBuilder from utf16 to utf8"));
        } else {
+               res = mono_marshal_alloc (mono_stringbuilder_capacity (sb) + 1);
                memcpy (res, tmp, sb->length + 1);
                g_free (tmp);
        }
@@ -1023,46 +1158,134 @@ mono_string_to_ansibstr (MonoString *string_obj)
        return NULL;
 }
 
+typedef gpointer (*SysAllocStringLenFunc)(gunichar* str, guint32 len);
+typedef guint32 (*SysStringLenFunc)(gpointer bstr);
+typedef void (*SysFreeStringFunc)(gunichar* str);
+
+static SysAllocStringLenFunc sys_alloc_string_len_ms = NULL;
+static SysStringLenFunc sys_string_len_ms = NULL;
+static SysFreeStringFunc sys_free_string_ms = NULL;
+
+static gboolean
+init_com_provider_ms (void)
+{
+       static gboolean initialized = FALSE;
+       char *error_msg;
+       MonoDl *module = NULL;
+       const char* scope = "liboleaut32.so";
+
+       if (initialized)
+               return TRUE;
+
+       module = mono_dl_open(scope, MONO_DL_LAZY, &error_msg);
+       if (error_msg) {
+               g_warning ("Error loading COM support library '%s': %s", scope, error_msg);
+               g_assert_not_reached ();
+               return FALSE;
+       }
+       error_msg = mono_dl_symbol (module, "SysAllocStringLen", (gpointer*)&sys_alloc_string_len_ms);
+       if (error_msg) {
+               g_warning ("Error loading entry point '%s' in COM support library '%s': %s", "SysAllocStringLen", scope, error_msg);
+               g_assert_not_reached ();
+               return FALSE;
+       }
+
+       error_msg = mono_dl_symbol (module, "SysStringLen", (gpointer*)&sys_string_len_ms);
+       if (error_msg) {
+               g_warning ("Error loading entry point '%s' in COM support library '%s': %s", "SysStringLen", scope, error_msg);
+               g_assert_not_reached ();
+               return FALSE;
+       }
+
+       error_msg = mono_dl_symbol (module, "SysFreeString", (gpointer*)&sys_free_string_ms);
+       if (error_msg) {
+               g_warning ("Error loading entry point '%s' in COM support library '%s': %s", "SysFreeString", scope, error_msg);
+               g_assert_not_reached ();
+               return FALSE;
+       }
+
+       initialized = TRUE;
+       return TRUE;
+}
+
 gpointer
 mono_string_to_bstr (MonoString *string_obj)
 {
-#ifdef PLATFORM_WIN32
        if (!string_obj)
                return NULL;
+#ifdef PLATFORM_WIN32
        return SysAllocStringLen (mono_string_chars (string_obj), mono_string_length (string_obj));
 #else
-       int slen = mono_string_length (string_obj);
-       char *ret = g_malloc (slen * 2 + 4 + 2);
-       if (ret == NULL)
-               return NULL;
-       memcpy (ret + 4, mono_string_chars (string_obj), slen * 2);
-       * ((guint32 *) ret) = slen * 2;
-       ret [4 + slen * 2] = 0;
-       ret [5 + slen * 2] = 0;
-
-       return ret + 4;
+       if (com_provider == MONO_COM_DEFAULT) {
+               int slen = mono_string_length (string_obj);
+               /* allocate len + 1 utf16 characters plus 4 byte integer for length*/
+               char *ret = g_malloc ((slen + 1) * sizeof(gunichar2) + sizeof(guint32));
+               if (ret == NULL)
+                       return NULL;
+               memcpy (ret + sizeof(guint32), mono_string_chars (string_obj), slen * sizeof(gunichar2));
+               * ((guint32 *) ret) = slen * sizeof(gunichar2);
+               ret [4 + slen * sizeof(gunichar2)] = 0;
+               ret [5 + slen * sizeof(gunichar2)] = 0;
+
+               return ret + 4;
+       } else if (com_provider == MONO_COM_MS && init_com_provider_ms ()) {
+               gpointer ret = NULL;
+               gunichar* str = NULL;
+               guint32 len;
+               len = mono_string_length (string_obj);
+               str = g_utf16_to_ucs4 (mono_string_chars (string_obj), len,
+                       NULL, NULL, NULL);
+               ret = sys_alloc_string_len_ms (str, len);
+               g_free(str);
+               return ret;
+       } else {
+               g_assert_not_reached ();
+       }
 #endif
 }
 
 MonoString *
 mono_string_from_bstr (gpointer bstr)
 {
-#ifdef PLATFORM_WIN32
        if (!bstr)
                return NULL;
+#ifdef PLATFORM_WIN32
        return mono_string_new_utf16 (mono_domain_get (), bstr, SysStringLen (bstr));
 #else
-       return mono_string_new_utf16 (mono_domain_get (), bstr, *(guint32 *)((char *)bstr - 4));
+       if (com_provider == MONO_COM_DEFAULT) {
+               return mono_string_new_utf16 (mono_domain_get (), bstr, *((guint32 *)bstr - 1) / sizeof(gunichar2));
+       } else if (com_provider == MONO_COM_MS && init_com_provider_ms ()) {
+               MonoString* str = NULL;
+               glong written = 0;
+               gunichar2* utf16 = NULL;
+
+               utf16 = g_ucs4_to_utf16 (bstr, sys_string_len_ms (bstr), NULL, &written, NULL);
+               str = mono_string_new_utf16 (mono_domain_get (), utf16, written);
+               g_free (utf16);
+               return str;
+       } else {
+               g_assert_not_reached ();
+       }
+
 #endif
 }
 
 void
 mono_free_bstr (gpointer bstr)
 {
+       if (!bstr)
+               return;
 #ifdef PLATFORM_WIN32
        SysFreeString ((BSTR)bstr);
 #else
-       g_free (((char *)bstr) - 4);
+       if (com_provider == MONO_COM_DEFAULT) {
+               g_free (((char *)bstr) - 4);
+       } else if (com_provider == MONO_COM_MS && init_com_provider_ms ()) {
+               sys_free_string_ms (bstr);
+       } else {
+               g_assert_not_reached ();
+       }
+
 #endif
 }
 
@@ -1126,489 +1349,79 @@ mono_string_to_byvalwstr (gpointer dst, MonoString *src, int size)
        *((gunichar2 *) dst + len) = 0;
 }
 
-void
-mono_mb_free (MonoMethodBuilder *mb)
+static int
+mono_mb_emit_proxy_check (MonoMethodBuilder *mb, int branch_code)
 {
-       g_list_free (mb->locals_list);
-       if (!mb->dynamic) {
-               g_free (mb->method);
-               g_free (mb->name);
-               g_free (mb->code);
-       }
-       g_free (mb);
+       int pos;
+       mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoObject, vtable));
+       mono_mb_emit_byte (mb, CEE_LDIND_I);
+       mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoVTable, klass));
+       mono_mb_emit_byte (mb, CEE_ADD);
+       mono_mb_emit_byte (mb, CEE_LDIND_I);
+       mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
+       mono_mb_emit_byte (mb, CEE_MONO_CLASSCONST);
+       mono_mb_emit_i4 (mb, mono_mb_add_data (mb, mono_defaults.transparent_proxy_class));
+       pos = mono_mb_emit_branch (mb, branch_code);
+       return pos;
 }
 
-MonoMethodBuilder *
-mono_mb_new (MonoClass *klass, const char *name, MonoWrapperType type)
+static int
+mono_mb_emit_xdomain_check (MonoMethodBuilder *mb, int branch_code)
 {
-       MonoMethodBuilder *mb;
-       MonoMethod *m;
-
-       g_assert (klass != NULL);
-       g_assert (name != NULL);
-
-       mb = g_new0 (MonoMethodBuilder, 1);
+       int pos;
+       mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoTransparentProxy, rp));
+       mono_mb_emit_byte (mb, CEE_LDIND_REF);
+       mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoRealProxy, target_domain_id));
+       mono_mb_emit_byte (mb, CEE_LDIND_I4);
+       mono_mb_emit_icon (mb, -1);
+       pos = mono_mb_emit_branch (mb, branch_code);
+       return pos;
+}
 
-       mb->method = m = (MonoMethod *)g_new0 (MonoMethodWrapper, 1);
+static int
+mono_mb_emit_contextbound_check (MonoMethodBuilder *mb, int branch_code)
+{
+       static int offset = -1;
+       static guint8 mask;
 
-       m->klass = klass;
-       m->inline_info = 1;
-       m->wrapper_type = type;
+       if (offset < 0)
+               mono_marshal_find_bitfield_offset (MonoClass, contextbound, &offset, &mask);
 
-       mb->name = g_strdup (name);
-       mb->code_size = 40;
-       mb->code = g_malloc (mb->code_size);
-       
-       return mb;
+       mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoTransparentProxy, remote_class));
+       mono_mb_emit_byte (mb, CEE_LDIND_REF);
+       mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoRemoteClass, proxy_class));
+       mono_mb_emit_byte (mb, CEE_LDIND_REF);
+       mono_mb_emit_ldflda (mb, offset);
+       mono_mb_emit_byte (mb, CEE_LDIND_U1);
+       mono_mb_emit_icon (mb, mask);
+       mono_mb_emit_byte (mb, CEE_AND);
+       mono_mb_emit_icon (mb, 0);
+       return mono_mb_emit_branch (mb, branch_code);
 }
 
-int
-mono_mb_add_local (MonoMethodBuilder *mb, MonoType *type)
+#ifndef DISABLE_COM
+
+static void
+mono_mb_emit_cominterop_call (MonoMethodBuilder *mb, MonoMethodSignature *sig, MonoMethod* method)
 {
-       int res;
+       // get function pointer from 1st arg, the COM interface pointer
+       mono_mb_emit_ldarg (mb, 0);
+       mono_mb_emit_icon (mb, cominterop_get_com_slot_for_method (method));
+       mono_mb_emit_icall (mb, cominterop_get_function_pointer);
 
-       g_assert (mb != NULL);
-       g_assert (type != NULL);
+       mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
+       mono_mb_emit_byte (mb, CEE_MONO_SAVE_LMF);
+       mono_mb_emit_calli (mb, sig);
+       mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
+       mono_mb_emit_byte (mb, CEE_MONO_RESTORE_LMF);
+}
 
-       res = mb->locals;
-       mb->locals_list = g_list_append (mb->locals_list, type);
-       mb->locals++;
+#endif /* DISABLE_COM */
 
-       return res;
-}
-
-/**
- * mono_mb_create_method:
- *
- * Create a MonoMethod from this method builder.
- * Returns: the newly created method.
- *
- * LOCKING: Takes the loader lock.
- */
-MonoMethod *
-mono_mb_create_method (MonoMethodBuilder *mb, MonoMethodSignature *signature, int max_stack)
-{
-       MonoMethodHeader *header;
-       MonoMethodWrapper *mw;
-       MonoMemPool *mp;
-       MonoMethod *method;
-       GList *l;
-       int i;
-
-       g_assert (mb != NULL);
-
-       mp = mb->method->klass->image->mempool;
-
-       mono_loader_lock ();
-       if (mb->dynamic) {
-               method = mb->method;
-
-               method->name = mb->name;
-               method->dynamic = TRUE;
-
-               ((MonoMethodNormal *)method)->header = header = (MonoMethodHeader *) 
-                       g_malloc0 (sizeof (MonoMethodHeader) + mb->locals * sizeof (MonoType *));
-
-               header->code = mb->code;
-       } else {
-               /* Realloc the method info into a mempool */
-
-               method = mono_mempool_alloc (mp, sizeof (MonoMethodWrapper));
-               memcpy (method, mb->method, sizeof (MonoMethodWrapper));
-
-               method->name = mono_mempool_strdup (mp, mb->name);
-
-               ((MonoMethodNormal *)method)->header = header = (MonoMethodHeader *) 
-                       mono_mempool_alloc0 (mp, sizeof (MonoMethodHeader) + mb->locals * sizeof (MonoType *));
-
-               header->code = mono_mempool_alloc (mp, mb->pos);
-               memcpy ((char*)header->code, mb->code, mb->pos);
-       }
-
-       if (max_stack < 8)
-               max_stack = 8;
-
-       header->max_stack = max_stack;
-
-       for (i = 0, l = mb->locals_list; l; l = l->next, i++) {
-               header->locals [i] = (MonoType *)l->data;
-       }
-
-       method->signature = signature;
-
-       header->code_size = mb->pos;
-       header->num_locals = mb->locals;
-       header->init_locals = TRUE;
-
-       mw = (MonoMethodWrapper*) mb->method;
-       i = g_list_length (mw->method_data);
-       if (i) {
-               GList *tmp;
-               void **data;
-               l = g_list_reverse (mw->method_data);
-               if (method->dynamic)
-                       data = g_malloc (sizeof (gpointer) * (i + 1));
-               else
-                       data = mono_mempool_alloc (mp, sizeof (gpointer) * (i + 1));
-               /* store the size in the first element */
-               data [0] = GUINT_TO_POINTER (i);
-               i = 1;
-               for (tmp = l; tmp; tmp = tmp->next) {
-                       data [i++] = tmp->data;
-               }
-               g_list_free (l);
-
-               ((MonoMethodWrapper*)method)->method_data = data;
-       }
-       /*{
-               static int total_code = 0;
-               static int total_alloc = 0;
-               total_code += mb->pos;
-               total_alloc += mb->code_size;
-               g_print ("code size: %d of %d (allocated: %d)\n", mb->pos, total_code, total_alloc);
-       }*/
-
-#ifdef DEBUG_RUNTIME_CODE
-       printf ("RUNTIME CODE FOR %s\n", mono_method_full_name (method, TRUE));
-       printf ("%s\n", mono_disasm_code (&marshal_dh, method, mb->code, mb->code + mb->pos));
-#endif
-
-       mono_loader_unlock ();
-       return method;
-}
-
-guint32
-mono_mb_add_data (MonoMethodBuilder *mb, gpointer data)
-{
-       MonoMethodWrapper *mw;
-
-       g_assert (mb != NULL);
-
-       mw = (MonoMethodWrapper *)mb->method;
-
-       /* one O(n) is enough */
-       mw->method_data = g_list_prepend (mw->method_data, data);
-
-       return g_list_length (mw->method_data);
-}
-
-void
-mono_mb_patch_addr (MonoMethodBuilder *mb, int pos, int value)
-{
-       mb->code [pos] = value & 0xff;
-       mb->code [pos + 1] = (value >> 8) & 0xff;
-       mb->code [pos + 2] = (value >> 16) & 0xff;
-       mb->code [pos + 3] = (value >> 24) & 0xff;
-}
-
-void
-mono_mb_patch_addr_s (MonoMethodBuilder *mb, int pos, gint8 value)
-{
-       *((gint8 *)(&mb->code [pos])) = value;
-}
-
-void
-mono_mb_emit_byte (MonoMethodBuilder *mb, guint8 op)
-{
-       if (mb->pos >= mb->code_size) {
-               mb->code_size += mb->code_size >> 1;
-               mb->code = g_realloc (mb->code, mb->code_size);
-       }
-
-       mb->code [mb->pos++] = op;
-}
-
-void
-mono_mb_emit_ldflda (MonoMethodBuilder *mb, gint32 offset)
-{
-        mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
-        mono_mb_emit_byte (mb, CEE_MONO_OBJADDR);
-
-       if (offset) {
-               mono_mb_emit_icon (mb, offset);
-               mono_mb_emit_byte (mb, CEE_ADD);
-       }
-}
-
-static int
-mono_mb_emit_proxy_check (MonoMethodBuilder *mb, int branch_code)
-{
-       int pos;
-       mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoObject, vtable));
-       mono_mb_emit_byte (mb, CEE_LDIND_I);
-       mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoVTable, klass));
-       mono_mb_emit_byte (mb, CEE_ADD);
-       mono_mb_emit_byte (mb, CEE_LDIND_I);
-       mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
-       mono_mb_emit_byte (mb, CEE_MONO_CLASSCONST);
-       mono_mb_emit_i4 (mb, mono_mb_add_data (mb, mono_defaults.transparent_proxy_class));
-       mono_mb_emit_byte (mb, branch_code);
-       pos = mb->pos;
-       mono_mb_emit_i4 (mb, 0);
-       return pos;
-}
-
-static int
-mono_mb_emit_xdomain_check (MonoMethodBuilder *mb, int branch_code)
-{
-       int pos;
-       mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoTransparentProxy, rp));
-       mono_mb_emit_byte (mb, CEE_LDIND_REF);
-       mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoRealProxy, target_domain_id));
-       mono_mb_emit_byte (mb, CEE_LDIND_I4);
-       mono_mb_emit_icon (mb, -1);
-       mono_mb_emit_byte (mb, branch_code);
-       pos = mb->pos;
-       mono_mb_emit_i4 (mb, 0);
-       return pos;
-}
-
-void
-mono_mb_emit_i4 (MonoMethodBuilder *mb, gint32 data)
-{
-       if ((mb->pos + 4) >= mb->code_size) {
-               mb->code_size += mb->code_size >> 1;
-               mb->code = g_realloc (mb->code, mb->code_size);
-       }
-
-       mono_mb_patch_addr (mb, mb->pos, data);
-       mb->pos += 4;
-}
-
-void
-mono_mb_emit_i2 (MonoMethodBuilder *mb, gint16 data)
-{
-       if ((mb->pos + 2) >= mb->code_size) {
-               mb->code_size += mb->code_size >> 1;
-               mb->code = g_realloc (mb->code, mb->code_size);
-       }
-
-       mb->code [mb->pos] = data & 0xff;
-       mb->code [mb->pos + 1] = (data >> 8) & 0xff;
-       mb->pos += 2;
-}
-
-static inline void
-mono_mb_emit_op (MonoMethodBuilder *mb, guint8 op, gpointer data)
-{
-       mono_mb_emit_byte (mb, op);
-       mono_mb_emit_i4 (mb, mono_mb_add_data (mb, data));
-}
-
-void
-mono_mb_emit_ldstr (MonoMethodBuilder *mb, char *str)
-{
-       mono_mb_emit_op (mb, CEE_LDSTR, str);
-}
-
-void
-mono_mb_emit_ldarg (MonoMethodBuilder *mb, guint argnum)
-{
-       if (argnum < 4) {
-               mono_mb_emit_byte (mb, CEE_LDARG_0 + argnum);
-       } else if (argnum < 256) {
-               mono_mb_emit_byte (mb, CEE_LDARG_S);
-               mono_mb_emit_byte (mb, argnum);
-       } else {
-               mono_mb_emit_byte (mb, CEE_PREFIX1);
-               mono_mb_emit_byte (mb, CEE_LDARG);
-               mono_mb_emit_i2 (mb, argnum);
-       }
-}
-
-void
-mono_mb_emit_ldarg_addr (MonoMethodBuilder *mb, guint argnum)
-{
-       if (argnum < 256) {
-               mono_mb_emit_byte (mb, CEE_LDARGA_S);
-               mono_mb_emit_byte (mb, argnum);
-       } else {
-               mono_mb_emit_byte (mb, CEE_PREFIX1);
-               mono_mb_emit_byte (mb, CEE_LDARGA);
-               mono_mb_emit_i2 (mb, argnum);
-       }
-}
-
-void
-mono_mb_emit_ldloc_addr (MonoMethodBuilder *mb, guint locnum)
-{
-       if (locnum < 256) {
-               mono_mb_emit_byte (mb, CEE_LDLOCA_S);
-               mono_mb_emit_byte (mb, locnum);
-       } else {
-               mono_mb_emit_byte (mb, CEE_PREFIX1);
-               mono_mb_emit_byte (mb, CEE_LDLOCA);
-               mono_mb_emit_i2 (mb, locnum);
-       }
-}
-
-void
-mono_mb_emit_ldloc (MonoMethodBuilder *mb, guint num)
-{
-       if (num < 4) {
-               mono_mb_emit_byte (mb, CEE_LDLOC_0 + num);
-       } else if (num < 256) {
-               mono_mb_emit_byte (mb, CEE_LDLOC_S);
-               mono_mb_emit_byte (mb, num);
-       } else {
-               mono_mb_emit_byte (mb, CEE_PREFIX1);
-               mono_mb_emit_byte (mb, CEE_LDLOC);
-               mono_mb_emit_i2 (mb, num);
-       }
-}
-
-void
-mono_mb_emit_stloc (MonoMethodBuilder *mb, guint num)
-{
-       if (num < 4) {
-               mono_mb_emit_byte (mb, CEE_STLOC_0 + num);
-       } else if (num < 256) {
-               mono_mb_emit_byte (mb, CEE_STLOC_S);
-               mono_mb_emit_byte (mb, num);
-       } else {
-               mono_mb_emit_byte (mb, CEE_PREFIX1);
-               mono_mb_emit_byte (mb, CEE_STLOC);
-               mono_mb_emit_i2 (mb, num);
-       }
-}
-
-void
-mono_mb_emit_icon (MonoMethodBuilder *mb, gint32 value)
-{
-       if (value >= -1 && value < 8) {
-               mono_mb_emit_byte (mb, CEE_LDC_I4_0 + value);
-       } else if (value >= -128 && value <= 127) {
-               mono_mb_emit_byte (mb, CEE_LDC_I4_S);
-               mono_mb_emit_byte (mb, value);
-       } else {
-               mono_mb_emit_byte (mb, CEE_LDC_I4);
-               mono_mb_emit_i4 (mb, value);
-       }
-}
-
-guint32
-mono_mb_emit_branch (MonoMethodBuilder *mb, guint8 op)
-{
-       guint32 res;
-       mono_mb_emit_byte (mb, op);
-       res = mb->pos;
-       mono_mb_emit_i4 (mb, 0);
-       return res;
-}
-
-guint32
-mono_mb_emit_short_branch (MonoMethodBuilder *mb, guint8 op)
-{
-       guint32 res;
-       mono_mb_emit_byte (mb, op);
-       res = mb->pos;
-       mono_mb_emit_byte (mb, 0);
-
-       return res;
-}
-
-static void
-mono_mb_patch_branch (MonoMethodBuilder *mb, guint32 pos)
-{
-       mono_mb_patch_addr (mb, pos, mb->pos - (pos + 4));
-}
-
-static void
-mono_mb_patch_short_branch (MonoMethodBuilder *mb, guint32 pos)
-{
-       mono_mb_patch_addr_s (mb, pos, mb->pos - (pos + 1));
-}
-
-static void
-mono_mb_emit_ptr (MonoMethodBuilder *mb, gpointer ptr)
-{
-       mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
-       mono_mb_emit_op (mb, CEE_MONO_LDPTR, ptr);
-}
-
-static void
-mono_mb_emit_calli (MonoMethodBuilder *mb, MonoMethodSignature *sig)
-{
-       mono_mb_emit_op (mb, CEE_CALLI, sig);
-}
-
-void
-mono_mb_emit_managed_call (MonoMethodBuilder *mb, MonoMethod *method, MonoMethodSignature *opt_sig)
-{
-       mono_mb_emit_op (mb, CEE_CALL, method);
-}
-
-void
-mono_mb_emit_native_call (MonoMethodBuilder *mb, MonoMethodSignature *sig, gpointer func)
-{
-       mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
-       mono_mb_emit_byte (mb, CEE_MONO_SAVE_LMF);
-       mono_mb_emit_ptr (mb, func);
-       mono_mb_emit_calli (mb, sig);
-       mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
-       mono_mb_emit_byte (mb, CEE_MONO_RESTORE_LMF);
-}
-
-static void
-mono_mb_emit_icall (MonoMethodBuilder *mb, gpointer func)
-{
-       mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
-       mono_mb_emit_op (mb, CEE_MONO_ICALL, func);
-}
-
-static void
-mono_mb_emit_cominterop_call (MonoMethodBuilder *mb, MonoMethodSignature *sig, MonoMethod* method)
-{
-       // get function pointer from 1st arg, the COM interface pointer
-       mono_mb_emit_ldarg (mb, 0);
-       mono_mb_emit_icon (mb, cominterop_get_com_slot_for_method (method));
-       mono_mb_emit_icall (mb, cominterop_get_function_pointer);
-
-       mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
-       mono_mb_emit_byte (mb, CEE_MONO_SAVE_LMF);
-       mono_mb_emit_calli (mb, sig);
-       mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
-       mono_mb_emit_byte (mb, CEE_MONO_RESTORE_LMF);
-}
-
-static void
-mono_mb_emit_exception_full (MonoMethodBuilder *mb, const char *exc_nspace, const char *exc_name, const char *msg)
-{
-       MonoMethod *ctor = NULL;
-
-       MonoClass *mme = mono_class_from_name (mono_defaults.corlib, exc_nspace, exc_name);
-       mono_class_init (mme);
-       ctor = mono_class_get_method_from_name (mme, ".ctor", 0);
-       g_assert (ctor);
-       mono_mb_emit_op (mb, CEE_NEWOBJ, ctor);
-       if (msg != NULL) {
-               mono_mb_emit_byte (mb, CEE_DUP);
-               mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoException, message));
-               mono_mb_emit_ldstr (mb, (char*)msg);
-               mono_mb_emit_byte (mb, CEE_STIND_REF);
-       }
-       mono_mb_emit_byte (mb, CEE_THROW);
-}
-
-void
-mono_mb_emit_exception (MonoMethodBuilder *mb, const char *exc_name, const char *msg)
-{
-       mono_mb_emit_exception_full (mb, "System", exc_name, msg);
-}
-
-static void
-mono_mb_emit_exception_marshal_directive (MonoMethodBuilder *mb, const char *msg)
-{
-       mono_mb_emit_exception_full (mb, "System.Runtime.InteropServices", "MarshalDirectiveException", msg);
-}
-
-void
-mono_mb_emit_add_to_local (MonoMethodBuilder *mb, guint16 local, gint32 incr)
-{
-       mono_mb_emit_ldloc (mb, local); 
-       mono_mb_emit_icon (mb, incr);
-       mono_mb_emit_byte (mb, CEE_ADD);
-       mono_mb_emit_stloc (mb, local); 
+static void
+mono_mb_emit_exception_marshal_directive (MonoMethodBuilder *mb, const char *msg)
+{
+       mono_mb_emit_exception_full (mb, "System.Runtime.InteropServices", "MarshalDirectiveException", msg);
 }
 
 guint
@@ -1805,7 +1618,7 @@ emit_ptr_to_object_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv
                        mono_mb_emit_stloc (mb, index_var);
 
                        /* Loop header */
-                       label2 = mb->pos;
+                       label2 = mono_mb_get_label (mb);
                        mono_mb_emit_ldloc (mb, index_var);
                        mono_mb_emit_ldloc (mb, array_var);
                        mono_mb_emit_byte (mb, CEE_LDLEN);
@@ -1825,8 +1638,7 @@ emit_ptr_to_object_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv
                        /* Loop footer */
                        mono_mb_emit_add_to_local (mb, index_var, 1);
 
-                       mono_mb_emit_byte (mb, CEE_BR);
-                       mono_mb_emit_i4 (mb, label2 - (mb->pos + 4));
+                       mono_mb_emit_branch_label (mb, CEE_BR, label2);
 
                        mono_mb_patch_branch (mb, label3);
                
@@ -1869,6 +1681,16 @@ emit_ptr_to_object_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv
                mono_mb_emit_byte (mb, CEE_STIND_REF);          
                break;          
        case MONO_MARSHAL_CONV_STR_LPTSTR:
+               mono_mb_emit_ldloc (mb, 1);
+               mono_mb_emit_ldloc (mb, 0);
+               mono_mb_emit_byte (mb, CEE_LDIND_I);
+#ifdef PLATFORM_WIN32
+               mono_mb_emit_icall (mb, mono_string_from_utf16);
+#else
+               mono_mb_emit_icall (mb, mono_string_new_wrapper);
+#endif
+               mono_mb_emit_byte (mb, CEE_STIND_REF);  
+               break;
        case MONO_MARSHAL_CONV_STR_LPSTR:
                mono_mb_emit_ldloc (mb, 1);
                mono_mb_emit_ldloc (mb, 0);
@@ -1935,6 +1757,8 @@ emit_ptr_to_object_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv
        case MONO_MARSHAL_CONV_ARRAY_LPARRAY:
                g_error ("Structure field of type %s can't be marshalled as LPArray", mono_class_from_mono_type (type)->name);
                break;
+
+#ifndef DISABLE_COM
        case MONO_MARSHAL_CONV_OBJECT_INTERFACE:
        case MONO_MARSHAL_CONV_OBJECT_IUNKNOWN:
        case MONO_MARSHAL_CONV_OBJECT_IDISPATCH: {
@@ -2007,6 +1831,7 @@ emit_ptr_to_object_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv
                mono_mb_patch_short_branch (mb, pos_null);
                break;
        }
+#endif /* DISABLE_COM */
 
        case MONO_MARSHAL_CONV_SAFEHANDLE: {
                /*
@@ -2053,6 +1878,11 @@ conv_to_icall (MonoMarshalConv conv)
        case MONO_MARSHAL_CONV_LPSTR_STR:
                return mono_string_new_wrapper;
        case MONO_MARSHAL_CONV_STR_LPTSTR:
+#ifdef PLATFORM_WIN32
+               return mono_marshal_string_to_utf16;
+#else
+               return mono_string_to_lpstr;
+#endif
        case MONO_MARSHAL_CONV_STR_LPSTR:
                return mono_string_to_lpstr;
        case MONO_MARSHAL_CONV_STR_BSTR:
@@ -2063,8 +1893,13 @@ conv_to_icall (MonoMarshalConv conv)
        case MONO_MARSHAL_CONV_STR_ANSIBSTR:
                return mono_string_to_ansibstr;
        case MONO_MARSHAL_CONV_SB_LPSTR:
+               return mono_string_builder_to_utf8;
        case MONO_MARSHAL_CONV_SB_LPTSTR:
+#ifdef PLATFORM_WIN32
+               return mono_string_builder_to_utf16;
+#else
                return mono_string_builder_to_utf8;
+#endif
        case MONO_MARSHAL_CONV_SB_LPWSTR:
                return mono_string_builder_to_utf16;
        case MONO_MARSHAL_CONV_ARRAY_SAVEARRAY:
@@ -2076,8 +1911,13 @@ conv_to_icall (MonoMarshalConv conv)
        case MONO_MARSHAL_CONV_FTN_DEL:
                return mono_ftnptr_to_delegate;
        case MONO_MARSHAL_CONV_LPSTR_SB:
+               return mono_string_utf8_to_builder;
        case MONO_MARSHAL_CONV_LPTSTR_SB:
+#ifdef PLATFORM_WIN32
+               return mono_string_utf16_to_builder;
+#else
                return mono_string_utf8_to_builder;
+#endif
        case MONO_MARSHAL_CONV_LPWSTR_SB:
                return mono_string_utf16_to_builder;
        case MONO_MARSHAL_FREE_ARRAY:
@@ -2208,7 +2048,7 @@ emit_object_to_ptr_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv
                        mono_mb_emit_stloc (mb, index_var);
 
                        /* Loop header */
-                       label2 = mb->pos;
+                       label2 = mono_mb_get_label (mb);
                        mono_mb_emit_ldloc (mb, index_var);
                        mono_mb_emit_ldloc (mb, array_var);
                        mono_mb_emit_byte (mb, CEE_LDLEN);
@@ -2228,8 +2068,7 @@ emit_object_to_ptr_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv
                        /* Loop footer */
                        mono_mb_emit_add_to_local (mb, index_var, 1);
 
-                       mono_mb_emit_byte (mb, CEE_BR);
-                       mono_mb_emit_i4 (mb, label2 - (mb->pos + 4));
+                       mono_mb_emit_branch_label (mb, CEE_BR, label2);
 
                        mono_mb_patch_branch (mb, label3);
                
@@ -2294,6 +2133,8 @@ emit_object_to_ptr_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv
                mono_mb_patch_branch (mb, pos);
                break;
        }
+
+#ifndef DISABLE_COM
        case MONO_MARSHAL_CONV_OBJECT_INTERFACE:
        case MONO_MARSHAL_CONV_OBJECT_IDISPATCH:
        case MONO_MARSHAL_CONV_OBJECT_IUNKNOWN: {
@@ -2333,13 +2174,10 @@ emit_object_to_ptr_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv
                mono_mb_emit_byte (mb, CEE_LDIND_REF);
 
                if (conv == MONO_MARSHAL_CONV_OBJECT_INTERFACE) {
-                       static MonoMethod* GetInterface = NULL;
-                       
-                       if (!GetInterface)
-                               GetInterface = mono_class_get_method_from_name (mono_defaults.com_object_class, "GetInterface", 1);
-                       mono_mb_emit_ptr (mb, type);
-                       mono_mb_emit_icall (mb, type_from_handle);
-                       mono_mb_emit_managed_call (mb, GetInterface, NULL);
+                       mono_mb_emit_ptr (mb, mono_type_get_class (type));
+                       mono_mb_emit_icon (mb, TRUE);
+                       mono_mb_emit_icall (mb, cominterop_get_interface);
+
                }
                else if (conv == MONO_MARSHAL_CONV_OBJECT_IUNKNOWN) {
                        static MonoProperty* iunknown = NULL;
@@ -2384,6 +2222,7 @@ emit_object_to_ptr_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv
                mono_mb_patch_short_branch (mb, pos_null);
                break;
        }
+#endif /* DISABLE_COM */
 
        case MONO_MARSHAL_CONV_SAFEHANDLE: {
                int dar_release_slot, pos;
@@ -2426,7 +2265,8 @@ emit_object_to_ptr_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv
        case MONO_MARSHAL_CONV_HANDLEREF: {
                mono_mb_emit_ldloc (mb, 1);
                mono_mb_emit_ldloc (mb, 0);
-               mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoHandleRef, handle));
+               mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoHandleRef, handle));
+               mono_mb_emit_byte (mb, CEE_ADD);
                mono_mb_emit_byte (mb, CEE_LDIND_I);
                mono_mb_emit_byte (mb, CEE_STIND_I);
                break;
@@ -2673,7 +2513,7 @@ emit_thread_interrupt_checkpoint_call (MonoMethodBuilder *mb, gpointer checkpoin
 
        mono_mb_emit_icall (mb, checkpoint_func);
        
-       mono_mb_patch_addr (mb, pos_noabort, mb->pos - (pos_noabort + 4));
+       mono_mb_patch_branch (mb, pos_noabort);
 }
 
 static void
@@ -2715,7 +2555,7 @@ mono_delegate_begin_invoke (MonoDelegate *delegate, gpointer *params)
                        MonoObject *exc;
                        MonoArray *out_args;
                        HANDLE handle;
-                       method = delegate->method_info->method;
+                       method = delegate->method;
 
                        msg = mono_method_call_message_new (mono_marshal_method_from_wrapper (method), params, NULL, &async_callback, &state);
                        handle = CreateEvent (NULL, TRUE, FALSE, NULL);
@@ -2801,6 +2641,9 @@ mono_signature_to_name (MonoMethodSignature *sig, const char *prefix)
 
        mono_type_get_desc (res, sig->ret, FALSE);
 
+       if (sig->hasthis)
+               g_string_append (res, "__this__");
+
        for (i = 0; i < sig->param_count; ++i) {
                g_string_append_c (res, '_');
                mono_type_get_desc (res, sig->params [i], FALSE);
@@ -2896,6 +2739,7 @@ mono_marshal_get_ptr_to_string_conv (MonoMethodPInvoke *piinfo, MonoMarshalSpec
 
        switch (encoding) {
        case MONO_NATIVE_LPWSTR:
+               *need_free = FALSE;
                return MONO_MARSHAL_CONV_LPWSTR_STR;
        case MONO_NATIVE_LPSTR:
                return MONO_MARSHAL_CONV_LPSTR_STR;
@@ -2964,6 +2808,25 @@ mono_marshal_need_free (MonoType *t, MonoMethodPInvoke *piinfo, MonoMarshalSpec
        }
 }
 
+/*
+ * Return the hash table pointed to by VAR, lazily creating it if neccesary.
+ */
+static GHashTable*
+get_cache (GHashTable **var, GHashFunc hash_func, GCompareFunc equal_func)
+{
+       if (!(*var)) {
+               mono_marshal_lock ();
+               if (!(*var)) {
+                       GHashTable *cache = 
+                               g_hash_table_new (hash_func, equal_func);
+                       mono_memory_barrier ();
+                       *var = cache;
+               }
+               mono_marshal_unlock ();
+       }
+       return *var;
+}
+
 static inline MonoMethod*
 mono_marshal_find_in_cache (GHashTable *cache, gpointer key)
 {
@@ -2975,6 +2838,18 @@ mono_marshal_find_in_cache (GHashTable *cache, gpointer key)
        return res;
 }
 
+static void
+mono_marshal_method_set_wrapper_data (MonoMethod *method, gpointer data)
+{
+       void **datav;
+       /* assert */
+       if (method->wrapper_type == MONO_WRAPPER_NONE || method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
+               return;
+
+       datav = ((MonoMethodWrapper *)method)->method_data;
+       datav [1] = data;
+}
+
 /* Create the method from the builder and place it in the cache */
 static inline MonoMethod*
 mono_mb_create_and_cache (GHashTable *cache, gpointer key,
@@ -2994,7 +2869,7 @@ mono_mb_create_and_cache (GHashTable *cache, gpointer key,
                if (!res) {
                        res = newm;
                        g_hash_table_insert (cache, key, res);
-                       g_hash_table_insert (wrapper_hash, res, key);
+                       mono_marshal_method_set_wrapper_data (res, key);
                        mono_marshal_unlock ();
                } else {
                        mono_marshal_unlock ();
@@ -3013,7 +2888,10 @@ mono_marshal_remoting_find_in_cache (MonoMethod *method, int wrapper_type)
        MonoRemotingMethods *wrps;
 
        mono_marshal_lock ();
-       wrps = g_hash_table_lookup (method->klass->image->remoting_invoke_cache, method);
+       if (method->klass->image->remoting_invoke_cache)
+               wrps = g_hash_table_lookup (method->klass->image->remoting_invoke_cache, method);
+       else
+               wrps = NULL;
 
        if (wrps) {
                switch (wrapper_type) {
@@ -3039,7 +2917,7 @@ mono_remoting_mb_create_and_cache (MonoMethod *key, MonoMethodBuilder *mb,
 {
        MonoMethod **res = NULL;
        MonoRemotingMethods *wrps;
-       GHashTable *cache = key->klass->image->remoting_invoke_cache;
+       GHashTable *cache = get_cache (&key->klass->image->remoting_invoke_cache, mono_aligned_addr_hash, NULL);
 
        mono_marshal_lock ();
        wrps = g_hash_table_lookup (cache, key);
@@ -3064,7 +2942,7 @@ mono_remoting_mb_create_and_cache (MonoMethod *key, MonoMethodBuilder *mb,
                mono_marshal_lock ();
                if (!*res) {
                        *res = newm;
-                       g_hash_table_insert (wrapper_hash, *res, key);
+                       mono_marshal_method_set_wrapper_data (*res, key);
                        mono_marshal_unlock ();
                } else {
                        mono_marshal_unlock ();
@@ -3078,14 +2956,14 @@ mono_remoting_mb_create_and_cache (MonoMethod *key, MonoMethodBuilder *mb,
 MonoMethod *
 mono_marshal_method_from_wrapper (MonoMethod *wrapper)
 {
-       MonoMethod *res;
+       gpointer res;
 
-       if (wrapper->wrapper_type == MONO_WRAPPER_NONE)
+       if (wrapper->wrapper_type == MONO_WRAPPER_NONE || wrapper->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
                return wrapper;
 
-       mono_marshal_lock ();
-       res = g_hash_table_lookup (wrapper_hash, wrapper);
-       mono_marshal_unlock ();
+       res = mono_method_get_wrapper_data (wrapper, 1);
+       if (res == NULL)
+               return wrapper;
        return res;
 }
 
@@ -3102,26 +2980,25 @@ mono_marshal_get_delegate_begin_invoke (MonoMethod *method)
        g_assert (method && method->klass->parent == mono_defaults.multicastdelegate_class &&
                  !strcmp (method->name, "BeginInvoke"));
 
-       sig = signature_no_pinvoke (method);
+       sig = mono_signature_no_pinvoke (method);
 
-       cache = method->klass->image->delegate_begin_invoke_cache;
+       cache = get_cache (&method->klass->image->delegate_begin_invoke_cache,
+                                          (GHashFunc)mono_signature_hash, 
+                                          (GCompareFunc)mono_metadata_signature_equal);
        if ((res = mono_marshal_find_in_cache (cache, sig)))
                return res;
 
        g_assert (sig->hasthis);
 
        name = mono_signature_to_name (sig, "begin_invoke");
-       mb = mono_mb_new (mono_defaults.multicastdelegate_class, name, MONO_WRAPPER_DELEGATE_BEGIN_INVOKE);
+       mb = mono_mb_new (method->klass, name, MONO_WRAPPER_DELEGATE_BEGIN_INVOKE);
        g_free (name);
 
-       mb->method->save_lmf = 1;
-
        params_var = mono_mb_emit_save_args (mb, sig, FALSE);
 
        mono_mb_emit_ldarg (mb, 0);
        mono_mb_emit_ldloc (mb, params_var);
        mono_mb_emit_icall (mb, mono_delegate_begin_invoke);
-       emit_thread_interrupt_checkpoint (mb);
        mono_mb_emit_byte (mb, CEE_RET);
 
        res = mono_mb_create_and_cache (cache, sig, mb, sig, sig->param_count + 16);
@@ -3143,6 +3020,11 @@ mono_delegate_end_invoke (MonoDelegate *delegate, gpointer *params)
 
        g_assert (delegate);
 
+       if (!delegate->method_info) {
+               g_assert (delegate->method);
+               MONO_OBJECT_SETREF (delegate, method_info, mono_method_get_object (domain, delegate->method, NULL));
+       }
+
        if (!delegate->method_info || !delegate->method_info->method)
                g_assert_not_reached ();
 
@@ -3151,14 +3033,15 @@ mono_delegate_end_invoke (MonoDelegate *delegate, gpointer *params)
        method = mono_class_get_method_from_name (klass, "EndInvoke", -1);
        g_assert (method != NULL);
 
-       sig = signature_no_pinvoke (method);
+       sig = mono_signature_no_pinvoke (method);
 
        msg = mono_method_call_message_new (method, params, NULL, NULL, NULL);
 
        ares = mono_array_get (msg->args, gpointer, sig->param_count - 1);
-       g_assert (ares);
+       if (ares == NULL)
+               mono_raise_exception (mono_exception_from_name_msg (mono_defaults.corlib, "System.Runtime.Remoting", "RemotingException", "The async result object is null or of an unexpected type."));
 
-       if (ares->async_delegate != (MonoObject*)delegate && mono_get_runtime_info ()->framework_version [0] >= '2') {
+       if (ares->async_delegate != (MonoObject*)delegate && mono_framework_version () >= 2) {
                mono_raise_exception (mono_get_exception_invalid_operation (
                        "The IAsyncResult object provided does not match this delegate."));
                return NULL;
@@ -3259,26 +3142,25 @@ mono_marshal_get_delegate_end_invoke (MonoMethod *method)
        g_assert (method && method->klass->parent == mono_defaults.multicastdelegate_class &&
                  !strcmp (method->name, "EndInvoke"));
 
-       sig = signature_no_pinvoke (method);
+       sig = mono_signature_no_pinvoke (method);
 
-       cache = method->klass->image->delegate_end_invoke_cache;
+       cache = get_cache (&method->klass->image->delegate_end_invoke_cache,
+                                          (GHashFunc)mono_signature_hash, 
+                                          (GCompareFunc)mono_metadata_signature_equal);
        if ((res = mono_marshal_find_in_cache (cache, sig)))
                return res;
 
        g_assert (sig->hasthis);
 
        name = mono_signature_to_name (sig, "end_invoke");
-       mb = mono_mb_new (mono_defaults.multicastdelegate_class, name, MONO_WRAPPER_DELEGATE_END_INVOKE);
+       mb = mono_mb_new (method->klass, name, MONO_WRAPPER_DELEGATE_END_INVOKE);
        g_free (name);
 
-       mb->method->save_lmf = 1;
-
        params_var = mono_mb_emit_save_args (mb, sig, FALSE);
 
        mono_mb_emit_ldarg (mb, 0);
        mono_mb_emit_ldloc (mb, params_var);
        mono_mb_emit_icall (mb, mono_delegate_end_invoke);
-       emit_thread_interrupt_checkpoint (mb);
 
        if (sig->ret->type == MONO_TYPE_VOID) {
                mono_mb_emit_byte (mb, CEE_POP);
@@ -3319,10 +3201,15 @@ mono_remoting_wrapper (MonoMethod *method, gpointer *params)
                for (i=0; i<count; i++) {
                        MonoClass *class = mono_class_from_mono_type (sig->params [i]);
                        if (class->valuetype) {
-                               if (sig->params [i]->byref)
+                               if (sig->params [i]->byref) {
                                        mparams[i] = *((gpointer *)params [i]);
-                               else 
-                                       mparams[i] = params [i];
+                               } else {
+                                       /* runtime_invoke expects a boxed instance */
+                                       if (mono_class_is_nullable (mono_class_from_mono_type (sig->params [i])))
+                                               mparams[i] = mono_nullable_box (params [i], class);
+                                       else
+                                               mparams[i] = params [i];
+                               }
                        } else {
                                mparams[i] = *((gpointer**)params [i]);
                        }
@@ -3343,6 +3230,8 @@ mono_remoting_wrapper (MonoMethod *method, gpointer *params)
        return res;
 } 
 
+#ifndef DISABLE_COM
+
 /**
  * cominterop_get_native_wrapper_adjusted:
  * @method: managed COM Interop method
@@ -3364,7 +3253,7 @@ cominterop_get_native_wrapper_adjusted (MonoMethod *method)
 
        // create unmanaged wrapper
        mb_native = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_NATIVE);
-       sig_native = signature_cominterop (method->klass->image, sig);
+       sig_native = cominterop_method_signature (method);
 
        mspecs = g_new (MonoMarshalSpec*, sig_native->param_count+1);
        memset (mspecs, 0, sizeof(MonoMarshalSpec*)*(sig_native->param_count+1));
@@ -3378,13 +3267,53 @@ cominterop_get_native_wrapper_adjusted (MonoMethod *method)
        // first arg is IntPtr for interface
        mspecs[1] = NULL;
 
-       // move return spec to last param
-       if (!MONO_TYPE_IS_VOID (sig->ret))
-               mspecs[sig_native->param_count] = mspecs[0];
+       if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_PRESERVE_SIG)) {
+               // move return spec to last param
+               if (!MONO_TYPE_IS_VOID (sig->ret))
+                       mspecs[sig_native->param_count] = mspecs[0];
 
-       mspecs[0] = NULL;
+               mspecs[0] = NULL;
+       }
 
-       mono_marshal_emit_native_wrapper(mono_defaults.corlib, mb_native, sig_native, piinfo, mspecs, piinfo->addr);
+       for (i = 1; i < sig_native->param_count; i++) {
+               int mspec_index = i + 1;
+               if (mspecs[mspec_index] == NULL) {
+                       // default object to VARIANT
+                       if (sig_native->params[i]->type == MONO_TYPE_OBJECT) {
+                               mspecs[mspec_index] = g_new0 (MonoMarshalSpec, 1);
+                               mspecs[mspec_index]->native = MONO_NATIVE_STRUCT;
+                       }
+                       else if (sig_native->params[i]->type == MONO_TYPE_STRING) {
+                               mspecs[mspec_index] = g_new0 (MonoMarshalSpec, 1);
+                               mspecs[mspec_index]->native = MONO_NATIVE_BSTR;
+                       }
+                       else if (sig_native->params[i]->type == MONO_TYPE_CLASS) {
+                               mspecs[mspec_index] = g_new0 (MonoMarshalSpec, 1);
+                               mspecs[mspec_index]->native = MONO_NATIVE_INTERFACE;
+                       }
+               }
+       }
+
+       if (method->iflags & METHOD_IMPL_ATTRIBUTE_PRESERVE_SIG) {
+               // move return spec to last param
+               if (!MONO_TYPE_IS_VOID (sig->ret) && mspecs[0] == NULL) {                       
+                       // default object to VARIANT
+                       if (sig->ret->type == MONO_TYPE_OBJECT) {
+                               mspecs[0] = g_new0 (MonoMarshalSpec, 1);
+                               mspecs[0]->native = MONO_NATIVE_STRUCT;
+                       }
+                       else if (sig->ret->type == MONO_TYPE_STRING) {
+                               mspecs[0] = g_new0 (MonoMarshalSpec, 1);
+                               mspecs[0]->native = MONO_NATIVE_BSTR;
+                       }
+                       else if (sig->ret->type == MONO_TYPE_CLASS) {
+                               mspecs[0] = g_new0 (MonoMarshalSpec, 1);
+                               mspecs[0]->native = MONO_NATIVE_INTERFACE;
+                       }
+               }
+       }
+
+       mono_marshal_emit_native_wrapper (method->klass->image, mb_native, sig_native, piinfo, mspecs, piinfo->addr, FALSE, TRUE);
 
        res = mono_mb_create_method (mb_native, sig_native, sig_native->param_count + 16);      
 
@@ -3414,12 +3343,18 @@ cominterop_get_native_wrapper (MonoMethod *method)
 
        g_assert (method);
 
-       cache = method->klass->image->cominterop_wrapper_cache;
+       cache = get_cache (&method->klass->image->cominterop_wrapper_cache, mono_aligned_addr_hash, NULL);
        if ((res = mono_marshal_find_in_cache (cache, method)))
                return res;
 
        mono_init_com_types ();
 
+       if (!method->klass->vtable)
+               mono_class_setup_vtable (method->klass);
+       
+       if (!method->klass->methods)
+               mono_class_setup_methods (method->klass);
+
        sig = mono_method_signature (method);
        mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_COMINTEROP);
 
@@ -3441,17 +3376,13 @@ cominterop_get_native_wrapper (MonoMethod *method)
                }
                else {
                        static MonoMethod * ThrowExceptionForHR = NULL;
-                       static MonoMethod * GetInterface = NULL;
                        MonoMethod *adjusted_method;
-                       int hr;
                        int retval = 0;
                        int ptr_this;
                        int i;
-                       if (!GetInterface)
-                               GetInterface = mono_class_get_method_from_name (mono_defaults.com_object_class, "GetInterface", 1);
+                       gboolean preserve_sig = method->iflags & METHOD_IMPL_ATTRIBUTE_PRESERVE_SIG;
 
                        // add local variables
-                       hr = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
                        ptr_this = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
                        if (!MONO_TYPE_IS_VOID (sig->ret))
                                retval =  mono_mb_add_local (mb, sig->ret);
@@ -3461,7 +3392,8 @@ cominterop_get_native_wrapper (MonoMethod *method)
                        mono_mb_emit_ldarg (mb, 0);
                        mono_mb_emit_ptr (mb, method);
                        mono_mb_emit_icall (mb, cominterop_get_method_interface);
-                       mono_mb_emit_managed_call (mb, GetInterface, NULL);
+                       mono_mb_emit_icon (mb, TRUE);
+                       mono_mb_emit_icall (mb, cominterop_get_interface);
                        mono_mb_emit_stloc (mb, ptr_this);
 
                        // arg 1 is unmanaged this pointer
@@ -3472,23 +3404,21 @@ cominterop_get_native_wrapper (MonoMethod *method)
                                mono_mb_emit_ldarg (mb, i);
 
                        // push managed return value as byref last argument
-                       if (!MONO_TYPE_IS_VOID (sig->ret))
+                       if (!MONO_TYPE_IS_VOID (sig->ret) && !preserve_sig)
                                mono_mb_emit_ldloc_addr (mb, retval);
                        
                        adjusted_method = cominterop_get_native_wrapper_adjusted (method);
                        mono_mb_emit_managed_call (mb, adjusted_method, NULL);
 
-                       // store HRESULT to check
-                       mono_mb_emit_stloc (mb, hr);
-
-                       if (!ThrowExceptionForHR)
-                               ThrowExceptionForHR = mono_class_get_method_from_name (mono_defaults.marshal_class, "ThrowExceptionForHR", 1);
-                       mono_mb_emit_ldloc (mb, hr);
-                       mono_mb_emit_managed_call (mb, ThrowExceptionForHR, NULL);
+                       if (!preserve_sig) {
+                               if (!ThrowExceptionForHR)
+                                       ThrowExceptionForHR = mono_class_get_method_from_name (mono_defaults.marshal_class, "ThrowExceptionForHR", 1);
+                               mono_mb_emit_managed_call (mb, ThrowExceptionForHR, NULL);
 
-                       // load return value managed is expecting
-                       if (!MONO_TYPE_IS_VOID (sig->ret))
-                               mono_mb_emit_ldloc (mb, retval);
+                               // load return value managed is expecting
+                               if (!MONO_TYPE_IS_VOID (sig->ret))
+                                       mono_mb_emit_ldloc (mb, retval);
+                       }
 
                        mono_mb_emit_byte (mb, CEE_RET);
                }
@@ -3523,14 +3453,14 @@ cominterop_get_invoke (MonoMethod *method)
        MonoMethodBuilder *mb;
        MonoMethod *res;
        int i, temp_obj;
-       GHashTable* cache = method->klass->image->cominterop_invoke_cache;
+       GHashTable* cache = get_cache (&method->klass->image->cominterop_invoke_cache, mono_aligned_addr_hash, NULL);
 
        g_assert (method);
 
        if ((res = mono_marshal_find_in_cache (cache, method)))
                return res;
 
-       sig = signature_no_pinvoke (method);
+       sig = mono_signature_no_pinvoke (method);
 
        /* we cant remote methods without this pointer */
        if (!sig->hasthis)
@@ -3587,6 +3517,9 @@ cominterop_get_invoke (MonoMethod *method)
 
        return res;
 }
+
+#endif /* DISABLE_COM */
+
 /* Maps a managed object to its unmanaged representation 
  * i.e. it's COM Callable Wrapper (CCW). 
  * Key: MonoObject*
@@ -3622,10 +3555,15 @@ mono_marshal_get_remoting_invoke (MonoMethod *method)
                return method;
 
        /* this seems to be the best plase to put this, as all remoting invokes seem to get filtered through here */
-       if ((method->klass->is_com_object || method->klass == mono_defaults.com_object_class) && !mono_class_vtable (mono_domain_get (), method->klass)->remote)
+       if ((method->klass->is_com_object || method->klass == mono_defaults.com_object_class) && !mono_class_vtable (mono_domain_get (), method->klass)->remote) {
+#ifndef DISABLE_COM
                return cominterop_get_invoke(method);
+#else
+               g_assert_not_reached ();
+#endif
+       }
 
-       sig = signature_no_pinvoke (method);
+       sig = mono_signature_no_pinvoke (method);
 
        /* we cant remote methods without this pointer */
        if (!sig->hasthis)
@@ -3935,8 +3873,10 @@ mono_marshal_get_xappdomain_dispatch (MonoMethod *method, int *marshal_types, in
 
        /* try */
 
-       main_clause = g_new0 (MonoExceptionClause, 1);
-       main_clause->try_offset = mb->pos;
+       mono_loader_lock ();
+       main_clause = mono_image_alloc0 (method->klass->image, sizeof (MonoExceptionClause));
+       mono_loader_unlock ();
+       main_clause->try_offset = mono_mb_get_label (mb);
 
        /* Clean the call context */
 
@@ -3959,7 +3899,7 @@ mono_marshal_get_xappdomain_dispatch (MonoMethod *method, int *marshal_types, in
        else
                mono_mb_emit_byte (mb, CEE_POP);
 
-       mono_mb_patch_addr_s (mb, pos, mb->pos - (pos + 1));
+       mono_mb_patch_short_branch (mb, pos);
 
        /* Get the target object */
        
@@ -4108,21 +4048,21 @@ mono_marshal_get_xappdomain_dispatch (MonoMethod *method, int *marshal_types, in
 
        /* Main exception catch */
        main_clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
-       main_clause->try_len = mb->pos - main_clause->try_offset;
+       main_clause->try_len = mono_mb_get_pos (mb) - main_clause->try_offset;
        main_clause->data.catch_class = mono_defaults.object_class;
        
        /* handler code */
-       main_clause->handler_offset = mb->pos;
+       main_clause->handler_offset = mono_mb_get_label (mb);
        mono_mb_emit_managed_call (mb, method_rs_serialize_exc, NULL);
        mono_mb_emit_stloc (mb, loc_serialized_exc);
        mono_mb_emit_ldarg (mb, 2);
        mono_mb_emit_ldloc (mb, loc_serialized_exc);
        mono_mb_emit_byte (mb, CEE_STIND_REF);
        mono_mb_emit_branch (mb, CEE_LEAVE);
-       main_clause->handler_len = mb->pos - main_clause->handler_offset;
+       main_clause->handler_len = mono_mb_get_pos (mb) - main_clause->handler_offset;
        /* end catch */
 
-       mono_mb_patch_addr (mb, pos_leave, mb->pos - (pos_leave + 4));
+       mono_mb_patch_branch (mb, pos_leave);
        
        if (copy_return)
                mono_mb_emit_ldloc (mb, loc_return);
@@ -4175,7 +4115,7 @@ mono_marshal_get_xappdomain_invoke (MonoMethod *method)
        if ((res = mono_marshal_remoting_find_in_cache (method, MONO_WRAPPER_XDOMAIN_INVOKE)))
                return res;
        
-       sig = signature_no_pinvoke (method);
+       sig = mono_signature_no_pinvoke (method);
 
        mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_XDOMAIN_INVOKE);
        mb->method->save_lmf = 1;
@@ -4375,7 +4315,7 @@ mono_marshal_get_xappdomain_invoke (MonoMethod *method)
        mono_mb_emit_op (mb, CEE_CASTCLASS, mono_defaults.exception_class);
        mono_mb_emit_managed_call (mb, method_exc_fixexc, NULL);
        mono_mb_emit_byte (mb, CEE_THROW);
-       mono_mb_patch_addr_s (mb, pos_noex, mb->pos - pos_noex - 1);
+       mono_mb_patch_short_branch (mb, pos_noex);
 
        /* copy back non-serialized output parameters */
 
@@ -4445,7 +4385,7 @@ mono_marshal_get_xappdomain_invoke (MonoMethod *method)
                pos = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
                mono_marshal_emit_xdomain_copy_value (mb, byte_array_class);
        
-               mono_mb_patch_addr_s (mb, pos, mb->pos - (pos + 1));
+               mono_mb_patch_short_branch (mb, pos);
                mono_mb_emit_managed_call (mb, method_rs_deserialize, NULL);
                mono_mb_emit_byte (mb, CEE_POP);
        }
@@ -4467,12 +4407,17 @@ mono_marshal_get_xappdomain_invoke (MonoMethod *method)
 MonoMethod *
 mono_marshal_get_remoting_invoke_for_target (MonoMethod *method, MonoRemotingTarget target_type)
 {
-       if (target_type == MONO_REMOTING_TARGET_APPDOMAIN)
+       if (target_type == MONO_REMOTING_TARGET_APPDOMAIN) {
                return mono_marshal_get_xappdomain_invoke (method);
-       else if (target_type == MONO_REMOTING_TARGET_COMINTEROP)
+       } else if (target_type == MONO_REMOTING_TARGET_COMINTEROP) {
+#ifndef DISABLE_COM
                return cominterop_get_invoke (method);
-       else
+#else
+               g_assert_not_reached ();
+#endif
+       } else {
                return mono_marshal_get_remoting_invoke (method);
+       }
 }
 
 G_GNUC_UNUSED static gpointer
@@ -4503,7 +4448,7 @@ mono_marshal_get_remoting_invoke_with_check (MonoMethod *method)
        if ((res = mono_marshal_remoting_find_in_cache (method, MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)))
                return res;
 
-       sig = signature_no_pinvoke (method);
+       sig = mono_signature_no_pinvoke (method);
        
        mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK);
 
@@ -4522,7 +4467,7 @@ mono_marshal_get_remoting_invoke_with_check (MonoMethod *method)
                mono_mb_emit_managed_call (mb, native, mono_method_signature (native));
                mono_mb_emit_byte (mb, CEE_RET);
                
-               mono_mb_patch_addr (mb, pos_rem, mb->pos - (pos_rem + 4));
+               mono_mb_patch_branch (mb, pos_rem);
        }
        /* wrapper for normal remote calls */
        native = mono_marshal_get_remoting_invoke (method);
@@ -4540,38 +4485,107 @@ mono_marshal_get_remoting_invoke_with_check (MonoMethod *method)
        return res;
 }
 
+typedef struct
+{
+       MonoMethodSignature *sig;
+       MonoMethod *method;
+} SignatureMethodPair;
+
+static guint
+signature_method_pair_hash (gconstpointer data)
+{
+       SignatureMethodPair *pair = (SignatureMethodPair*)data;
+
+       return mono_signature_hash (pair->sig) ^ mono_aligned_addr_hash (pair->method);
+}
+
+static gboolean
+signature_method_pair_equal (SignatureMethodPair *pair1, SignatureMethodPair *pair2)
+{
+       return mono_metadata_signature_equal (pair1->sig, pair2->sig) && (pair1->method == pair2->method);
+}
+
+static void
+free_signature_method_pair (SignatureMethodPair *pair)
+{
+       g_free (pair);
+}
+
 /*
- * the returned method invokes all methods in a multicast delegate 
+ * the returned method invokes all methods in a multicast delegate.
  */
 MonoMethod *
-mono_marshal_get_delegate_invoke (MonoMethod *method)
+mono_marshal_get_delegate_invoke (MonoMethod *method, MonoDelegate *del)
 {
        MonoMethodSignature *sig, *static_sig;
        int i;
        MonoMethodBuilder *mb;
-       MonoMethod *res;
+       MonoMethod *res, *newm;
        GHashTable *cache;
-       int pos0, pos1;
+       SignatureMethodPair key;
+       SignatureMethodPair *new_key;
+       int local_prev, local_target;
+       int pos0;
        char *name;
+       MonoMethod *target_method = NULL;
+       MonoClass *target_class = NULL;
+       gboolean callvirt = FALSE;
+
+       /*
+        * If the delegate target is null, and the target method is not static, a virtual 
+        * call is made to that method with the first delegate argument as this. This is 
+        * a non-documented .NET feature.
+        */
+       if (del && !del->target && del->method && mono_method_signature (del->method)->hasthis) {
+               callvirt = TRUE;
+               target_method = del->method;
+               if (target_method->is_inflated) {
+                       MonoType *target_type;
+
+                       g_assert (method->signature->hasthis);
+                       target_type = mono_class_inflate_generic_type (method->signature->params [0],
+                               mono_method_get_context (method));
+                       target_class = mono_class_from_mono_type (target_type);
+               } else {
+                       target_class = del->method->klass;
+               }
+       }
 
        g_assert (method && method->klass->parent == mono_defaults.multicastdelegate_class &&
                  !strcmp (method->name, "Invoke"));
                
-       sig = signature_no_pinvoke (method);
+       sig = mono_signature_no_pinvoke (method);
 
-       cache = method->klass->image->delegate_invoke_cache;
-       if ((res = mono_marshal_find_in_cache (cache, sig)))
-               return res;
+       if (callvirt) {
+               /* We need to cache the signature+method pair */
+               mono_marshal_lock ();
+               if (!method->klass->image->delegate_abstract_invoke_cache)
+                       method->klass->image->delegate_abstract_invoke_cache = g_hash_table_new_full (signature_method_pair_hash, (GEqualFunc)signature_method_pair_equal, (GDestroyNotify)free_signature_method_pair, NULL);
+               cache = method->klass->image->delegate_abstract_invoke_cache;
+               key.sig = sig;
+               key.method = target_method;
+               res = g_hash_table_lookup (cache, &key);
+               mono_marshal_unlock ();
+               if (res)
+                       return res;
+       } else {
+               cache = get_cache (&method->klass->image->delegate_invoke_cache,
+                                                  (GHashFunc)mono_signature_hash, 
+                                                  (GCompareFunc)mono_metadata_signature_equal);
+               if ((res = mono_marshal_find_in_cache (cache, sig)))
+                       return res;
+       }
 
        static_sig = signature_dup (method->klass->image, sig);
        static_sig->hasthis = 0;
 
        name = mono_signature_to_name (sig, "invoke");
-       mb = mono_mb_new (mono_defaults.multicastdelegate_class, name,  MONO_WRAPPER_DELEGATE_INVOKE);
+       mb = mono_mb_new (method->klass, name,  MONO_WRAPPER_DELEGATE_INVOKE);
        g_free (name);
 
        /* allocate local 0 (object) */
-       mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
+       local_target = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
+       local_prev = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
 
        g_assert (sig->hasthis);
        
@@ -4588,6 +4602,8 @@ mono_marshal_get_delegate_invoke (MonoMethod *method)
        mono_mb_emit_ldarg (mb, 0);
        mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoMulticastDelegate, prev));
        mono_mb_emit_byte (mb, CEE_LDIND_REF);
+       mono_mb_emit_stloc (mb, local_prev);
+       mono_mb_emit_ldloc (mb, local_prev);
 
        /* if prev != null */
        pos0 = mono_mb_emit_branch (mb, CEE_BRFALSE);
@@ -4597,12 +4613,10 @@ mono_marshal_get_delegate_invoke (MonoMethod *method)
        mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
        mono_mb_emit_byte (mb, CEE_MONO_NOT_TAKEN);
 
-       mono_mb_emit_ldarg (mb, 0);
-       mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoMulticastDelegate, prev));
-       mono_mb_emit_byte (mb, CEE_LDIND_REF);
+       mono_mb_emit_ldloc (mb, local_prev);
        for (i = 0; i < sig->param_count; i++)
                mono_mb_emit_ldarg (mb, i + 1);
-       mono_mb_emit_managed_call (mb, method, mono_method_signature (method));
+       mono_mb_emit_op (mb, CEE_CALLVIRT, method);
        if (sig->ret->type != MONO_TYPE_VOID)
                mono_mb_emit_byte (mb, CEE_POP);
 
@@ -4613,39 +4627,72 @@ mono_marshal_get_delegate_invoke (MonoMethod *method)
        mono_mb_emit_ldarg (mb, 0);
        mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoDelegate, target));
        mono_mb_emit_byte (mb, CEE_LDIND_REF);
-       mono_mb_emit_stloc (mb, 0);
+       mono_mb_emit_stloc (mb, local_target);
 
        /* if target != null */
-       mono_mb_emit_ldloc (mb, 0);
+       mono_mb_emit_ldloc (mb, local_target);
        pos0 = mono_mb_emit_branch (mb, CEE_BRFALSE);
        
        /* then call this->method_ptr nonstatic */
-       mono_mb_emit_ldloc (mb, 0); 
-       for (i = 0; i < sig->param_count; ++i)
-               mono_mb_emit_ldarg (mb, i + 1);
-       mono_mb_emit_ldarg (mb, 0);
-       mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoDelegate, method_ptr));
-       mono_mb_emit_byte (mb, CEE_LDIND_I );
-       mono_mb_emit_op (mb, CEE_CALLI, sig);
+       if (callvirt) {
+               // FIXME:
+               mono_mb_emit_exception_full (mb, "System", "NotImplementedException", "");
+       } else {
+               mono_mb_emit_ldloc (mb, local_target); 
+               for (i = 0; i < sig->param_count; ++i)
+                       mono_mb_emit_ldarg (mb, i + 1);
+               mono_mb_emit_ldarg (mb, 0);
+               mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoDelegate, method_ptr));
+               mono_mb_emit_byte (mb, CEE_LDIND_I );
+               mono_mb_emit_op (mb, CEE_CALLI, sig);
 
-       pos1 = mono_mb_emit_branch (mb, CEE_BR);
+               mono_mb_emit_byte (mb, CEE_RET);
+       }
 
        /* else [target == null] call this->method_ptr static */
        mono_mb_patch_branch (mb, pos0);
 
-       for (i = 0; i < sig->param_count; ++i)
-               mono_mb_emit_ldarg (mb, i + 1);
-       mono_mb_emit_ldarg (mb, 0);
-       mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoDelegate, method_ptr));
-       mono_mb_emit_byte (mb, CEE_LDIND_I );
-       mono_mb_emit_op (mb, CEE_CALLI, static_sig);
+       if (callvirt) {
+               mono_mb_emit_ldarg (mb, 1);
+               mono_mb_emit_op (mb, CEE_CASTCLASS, target_class);
+               for (i = 1; i < sig->param_count; ++i)
+                       mono_mb_emit_ldarg (mb, i + 1);
+               mono_mb_emit_op (mb, CEE_CALLVIRT, target_method);
+       } else {
+               for (i = 0; i < sig->param_count; ++i)
+                       mono_mb_emit_ldarg (mb, i + 1);
+               mono_mb_emit_ldarg (mb, 0);
+               mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoDelegate, method_ptr));
+               mono_mb_emit_byte (mb, CEE_LDIND_I );
+               mono_mb_emit_op (mb, CEE_CALLI, static_sig);
+       }
 
-       /* return */
-       mono_mb_patch_branch (mb, pos1);
        mono_mb_emit_byte (mb, CEE_RET);
 
-       res = mono_mb_create_and_cache (cache, sig,
-                                                                                mb, sig, sig->param_count + 16);
+       if (callvirt) {
+               // From mono_mb_create_and_cache
+               newm = mono_mb_create_method (mb, sig, sig->param_count + 16);
+               newm->skip_visibility = 1;
+               /*We perform double checked locking, so must fence before publishing*/
+               mono_memory_barrier ();
+               mono_marshal_lock ();
+               res = g_hash_table_lookup (cache, &key);
+               if (!res) {
+                       res = newm;
+                       new_key = g_new0 (SignatureMethodPair, 1);
+                       new_key->sig = sig;
+                       new_key->method = target_method;
+                       g_hash_table_insert (cache, new_key, res);
+                       mono_marshal_method_set_wrapper_data (res, new_key);
+                       mono_marshal_unlock ();
+               } else {
+                       mono_marshal_unlock ();
+                       mono_free_method (newm);
+               }
+       } else {
+               res = mono_mb_create_and_cache (cache, sig, mb, sig, sig->param_count + 16);
+               res->skip_visibility = 1;
+       }
        mono_mb_free (mb);
 
        return res;     
@@ -4722,6 +4769,67 @@ add_string_ctor_signature (MonoMethod *method)
        return callsig;
 }
 
+static MonoType*
+get_runtime_invoke_type (MonoType *t)
+{
+       if (t->byref)
+               return &mono_defaults.int_class->byval_arg;
+
+       switch (t->type) {
+       case MONO_TYPE_U1:
+               return &mono_defaults.sbyte_class->byval_arg;
+       case MONO_TYPE_U2:
+               return &mono_defaults.int16_class->byval_arg;
+       case MONO_TYPE_U4:
+               return &mono_defaults.int32_class->byval_arg;
+       case MONO_TYPE_U8:
+               return &mono_defaults.int64_class->byval_arg;
+       case MONO_TYPE_BOOLEAN:
+               return &mono_defaults.byte_class->byval_arg;
+       case MONO_TYPE_CHAR:
+               return &mono_defaults.int16_class->byval_arg;
+       case MONO_TYPE_U:
+               return &mono_defaults.int_class->byval_arg;
+       case MONO_TYPE_VALUETYPE:
+               if (t->data.klass->enumtype)
+                       return mono_type_get_underlying_type (t);
+               else
+                       return t;
+       default:
+               if (MONO_TYPE_IS_REFERENCE (t))
+                       return &mono_defaults.object_class->byval_arg;
+               return t;
+       }
+}
+
+/*
+ * mono_marshal_get_runtime_invoke_sig:
+ *
+ *   Return a common signature used for sharing runtime invoke wrappers.
+ */
+static MonoMethodSignature*
+mono_marshal_get_runtime_invoke_sig (MonoMethodSignature *sig)
+{
+       MonoMethodSignature *res = mono_metadata_signature_dup (sig);
+       int i;
+
+       res->ret = get_runtime_invoke_type (sig->ret);
+       for (i = 0; i < res->param_count; ++i)
+               res->params [i] = get_runtime_invoke_type (sig->params [i]);
+
+       return res;
+}
+
+static gboolean
+runtime_invoke_signature_equal (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
+{
+       /* Can't share wrappers which return a vtype since it needs to be boxed */
+       if (sig1->ret != sig2->ret && !(MONO_TYPE_IS_REFERENCE (sig1->ret) && MONO_TYPE_IS_REFERENCE (sig2->ret)))
+               return FALSE;
+       else
+               return mono_metadata_signature_equal (sig1, sig2);
+}
+
 /*
  * generates IL code for the runtime invoke function 
  * MonoObject *runtime_invoke (MonoObject *this, void **params, MonoObject **exc, void* method)
@@ -4739,12 +4847,42 @@ mono_marshal_get_runtime_invoke (MonoMethod *method)
        MonoClass *target_klass;
        MonoMethod *res = NULL;
        static MonoString *string_dummy = NULL;
-       static MonoMethodSignature *dealy_abort_sig = NULL;
+       static MonoMethodSignature *cctor_signature = NULL;
+       static MonoMethodSignature *finalize_signature = NULL;
        int i, pos, posna;
        char *name;
+       gboolean need_direct_wrapper = FALSE;
 
        g_assert (method);
 
+       if (!cctor_signature) {
+               cctor_signature = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
+               cctor_signature->ret = &mono_defaults.void_class->byval_arg;
+       }
+       if (!finalize_signature) {
+               finalize_signature = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
+               finalize_signature->ret = &mono_defaults.void_class->byval_arg;
+               finalize_signature->hasthis = 1;
+       }
+
+       /* 
+        * Use a separate cache indexed by methods to speed things up and to avoid the
+        * boundless mempool growth caused by the signature_dup stuff below.
+        */
+       cache = get_cache (&method->klass->image->runtime_invoke_direct_cache, mono_aligned_addr_hash, NULL);
+       res = mono_marshal_find_in_cache (cache, method);
+       if (res)
+               return res;
+
+       if (method->klass->rank && (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
+               (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
+               /* 
+                * Array Get/Set/Address methods. The JIT implements them using inline code
+                * so we need to create an invoke wrapper which calls the method directly.
+                */
+               need_direct_wrapper = TRUE;
+       }
+               
        if (method->string_ctor) {
                callsig = lookup_string_ctor_signature (mono_method_signature (method));
                if (!callsig)
@@ -4757,40 +4895,66 @@ mono_marshal_get_runtime_invoke (MonoMethod *method)
                         */
                        callsig = signature_dup_add_this (mono_method_signature (method), method->klass);
                } else {
-                       callsig = mono_method_signature (method);
+                       if (method->dynamic)
+                               callsig = signature_dup (method->klass->image, mono_method_signature (method));
+                       else
+                               callsig = mono_method_signature (method);
                }
        }
 
-       target_klass = mono_defaults.object_class;
-       /* 
-        * if types in the signature belong to non-mscorlib, we cache only
-        * in the method image
+       /*
+        * We try to share runtime invoke wrappers between different methods but have to
+        * be careful about methods whose klass has a type cctor, since putting the wrapper
+        * into that klass would mean that calling a method of klass A might invoke the
+        * type initializer of class B, or throw an exception if the type initializer 
+        * was called before and failed. See #349621 for an example. 
+        * We avoid that for mscorlib methods by putting every wrapper into the object class.
         */
-       if (mono_class_from_mono_type (callsig->ret)->image != mono_defaults.corlib) {
-               target_klass = method->klass;
-       } else {
-               for (i = 0; i < callsig->param_count; i++) {
-                       if (mono_class_from_mono_type (callsig->params [i])->image != mono_defaults.corlib) {
-                               target_klass = method->klass;
-                               break;
-                       }
+       if (method->klass->image == mono_defaults.corlib)
+               target_klass = mono_defaults.object_class;
+       else {
+               /* Try to share wrappers for non-corlib methods with simple signatures */
+               if (mono_metadata_signature_equal (callsig, cctor_signature)) {
+                       callsig = cctor_signature;
+                       target_klass = mono_defaults.object_class;
+               } else if (mono_metadata_signature_equal (callsig, finalize_signature)) {
+                       callsig = finalize_signature;
+                       target_klass = mono_defaults.object_class;
+               } else {
+                       // FIXME: This breaks too many things
+                       /*
+                       if (mono_class_get_cctor (method->klass))
+                               need_direct_wrapper = TRUE;
+                       */
+
+                       /*
+                        * Can't put these wrappers into object, since they reference non-corlib
+                        * metadata (callsig).
+                        */
+                       target_klass = method->klass;
                }
        }
-       cache = target_klass->image->runtime_invoke_cache;
 
-       /* from mono_marshal_find_in_cache */
-       mono_marshal_lock ();
-       res = g_hash_table_lookup (cache, callsig);
-       mono_marshal_unlock ();
+       if (need_direct_wrapper) {
+               /* Already searched at the start */
+       } else {
+               callsig = mono_marshal_get_runtime_invoke_sig (callsig);
 
-       if (res) {
-               return res;
-       }
+               cache = get_cache (&target_klass->image->runtime_invoke_cache, 
+                                                  (GHashFunc)mono_signature_hash, 
+                                                  (GCompareFunc)runtime_invoke_signature_equal);
+
+               /* from mono_marshal_find_in_cache */
+               mono_marshal_lock ();
+               res = g_hash_table_lookup (cache, callsig);
+               mono_marshal_unlock ();
+
+               if (res) {
+                       g_free (callsig);
+                       return res;
+               }
 
-       if (!dealy_abort_sig) {
-               dealy_abort_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
-               dealy_abort_sig->ret = &mono_defaults.void_class->byval_arg;
-               dealy_abort_sig->pinvoke = 0;
+               // FIXME: When to free callsig ?
        }
        
        /* to make it work with our special string constructors */
@@ -4848,10 +5012,21 @@ mono_marshal_get_runtime_invoke (MonoMethod *method)
                        mono_mb_emit_icon (mb, sizeof (gpointer) * i);
                        mono_mb_emit_byte (mb, CEE_ADD);
                }
-               mono_mb_emit_byte (mb, CEE_LDIND_I);
 
-               if (t->byref)
+               if (t->byref) {
+                       mono_mb_emit_byte (mb, CEE_LDIND_I);
+                       /* A Nullable<T> type don't have a boxed form, it's either null or a boxed T.
+                        * So to make this work we unbox it to a local variablee and push a reference to that.
+                        */
+                       if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
+                               int tmp_nullable_local = mono_mb_add_local (mb, &mono_class_from_mono_type (t)->byval_arg);
+
+                               mono_mb_emit_op (mb, CEE_UNBOX_ANY, mono_class_from_mono_type (t));
+                               mono_mb_emit_stloc (mb, tmp_nullable_local);
+                               mono_mb_emit_ldloc_addr (mb, tmp_nullable_local);
+                       }
                        continue;
+               }
 
                type = sig->params [i]->type;
 handle_enum:
@@ -4870,6 +5045,7 @@ handle_enum:
                case MONO_TYPE_R8:
                case MONO_TYPE_I8:
                case MONO_TYPE_U8:
+                       mono_mb_emit_byte (mb, CEE_LDIND_I);
                        mono_mb_emit_byte (mb, mono_type_to_ldind (sig->params [i]));
                        break;
                case MONO_TYPE_STRING:
@@ -4878,11 +5054,11 @@ handle_enum:
                case MONO_TYPE_PTR:
                case MONO_TYPE_SZARRAY:
                case MONO_TYPE_OBJECT:
-                       /* do nothing */
+                       mono_mb_emit_byte (mb, mono_type_to_ldind (sig->params [i]));
                        break;
                case MONO_TYPE_GENERICINST:
                        if (!mono_type_generic_inst_is_valuetype (sig->params [i])) {
-                               /* do nothing */
+                               mono_mb_emit_byte (mb, CEE_LDIND_I);
                                break;
                        }
 
@@ -4892,6 +5068,7 @@ handle_enum:
                                type = t->data.klass->enum_basetype->type;
                                goto handle_enum;
                        }
+                       mono_mb_emit_byte (mb, CEE_LDIND_I);
                        if (mono_class_is_nullable (mono_class_from_mono_type (sig->params [i]))) {
                                /* Need to convert a boxed vtype to an mp to a Nullable struct */
                                mono_mb_emit_op (mb, CEE_UNBOX, mono_class_from_mono_type (sig->params [i]));
@@ -4905,8 +5082,12 @@ handle_enum:
                }               
        }
        
-       mono_mb_emit_ldarg (mb, 3);
-       mono_mb_emit_calli (mb, callsig);
+       if (need_direct_wrapper) {
+               mono_mb_emit_op (mb, CEE_CALL, method);
+       } else {
+               mono_mb_emit_ldarg (mb, 3);
+               mono_mb_emit_calli (mb, callsig);
+       }
 
        if (sig->ret->byref) {
                /* fixme: */
@@ -4956,13 +5137,13 @@ handle_enum:
        pos = mono_mb_emit_branch (mb, CEE_LEAVE);
 
        mono_loader_lock ();
-       clause = mono_mempool_alloc0 (target_klass->image->mempool, sizeof (MonoExceptionClause));
+       clause = mono_image_alloc0 (target_klass->image, sizeof (MonoExceptionClause));
        mono_loader_unlock ();
        clause->flags = MONO_EXCEPTION_CLAUSE_FILTER;
-       clause->try_len = mb->pos;
+       clause->try_len = mono_mb_get_label (mb);
 
        /* filter code */
-       clause->data.filter_offset = mb->pos;
+       clause->data.filter_offset = mono_mb_get_label (mb);
        
        mono_mb_emit_byte (mb, CEE_POP);
        mono_mb_emit_byte (mb, CEE_LDARG_2);
@@ -4972,7 +5153,7 @@ handle_enum:
        mono_mb_emit_byte (mb, CEE_PREFIX1);
        mono_mb_emit_byte (mb, CEE_ENDFILTER);
 
-       clause->handler_offset = mb->pos;
+       clause->handler_offset = mono_mb_get_label (mb);
 
        /* handler code */
        /* store exception */
@@ -4991,41 +5172,46 @@ handle_enum:
        posna = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
 
        /* Delay the abort exception */
-       mono_mb_emit_native_call (mb, dealy_abort_sig, ves_icall_System_Threading_Thread_ResetAbort);
+       mono_mb_emit_icall (mb, ves_icall_System_Threading_Thread_ResetAbort);
 
        mono_mb_patch_short_branch (mb, posna);
        mono_mb_emit_branch (mb, CEE_LEAVE);
 
-       clause->handler_len = mb->pos - clause->handler_offset;
+       clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
 
        /* return result */
        mono_mb_patch_branch (mb, pos);
        mono_mb_emit_ldloc (mb, 0);
        mono_mb_emit_byte (mb, CEE_RET);
 
-       /* taken from mono_mb_create_and_cache */
-       mono_marshal_lock ();
-       res = g_hash_table_lookup (cache, callsig);
-       mono_marshal_unlock ();
-
-       /* Somebody may have created it before us */
-       if (!res) {
-               MonoMethod *newm;
-               newm = mono_mb_create_method (mb, csig, sig->param_count + 16);
-
+       if (need_direct_wrapper) {
+               res = mono_mb_create_and_cache (cache, method, mb, csig, sig->param_count + 16);
+       } else {
+               /* taken from mono_mb_create_and_cache */
                mono_marshal_lock ();
                res = g_hash_table_lookup (cache, callsig);
+               mono_marshal_unlock ();
+
+               /* Somebody may have created it before us */
                if (!res) {
-                       res = newm;
-                       g_hash_table_insert (cache, callsig, res);
-                       g_hash_table_insert (wrapper_hash, res, callsig);
-               } else {
-                       mono_free_method (newm);
+                       MonoMethod *newm;
+                       newm = mono_mb_create_method (mb, csig, sig->param_count + 16);
+
+                       mono_marshal_lock ();
+                       res = g_hash_table_lookup (cache, callsig);
+                       if (!res) {
+                               res = newm;
+                               g_hash_table_insert (cache, callsig, res);
+                               /* Can't insert it into wrapper_hash since the key is a signature */
+                               g_hash_table_insert (method->klass->image->runtime_invoke_direct_cache, method, res);
+                       } else {
+                               mono_free_method (newm);
+                       }
+                       mono_marshal_unlock ();
                }
-               mono_marshal_unlock ();
-       }
 
-       /* end mono_mb_create_and_cache */
+               /* end mono_mb_create_and_cache */
+       }
 
        mono_mb_free (mb);
 
@@ -5036,6 +5222,62 @@ handle_enum:
        return res;     
 }
 
+/*
+ * mono_marshal_get_static_rgctx_invoke:
+ * @method: a method
+ *
+ * Generates a wrapper for calling a generic shared method, either
+ * static or generic.  We need this for virtual generic method lookup
+ * and ldftn when we do generic code sharing.  Instead of producing
+ * the address of the method we produce the address of a wrapper for
+ * the method because the wrapper passes the (method) runtime generic
+ * context argument which calli cannot do.
+ */
+MonoMethod *
+mono_marshal_get_static_rgctx_invoke (MonoMethod *method)
+{
+       static gboolean inited = FALSE;
+       static int num_wrappers = 0;
+
+       MonoMethodBuilder *mb;
+       MonoMethod *res;
+       MonoClass *target_klass = method->klass;
+       MonoMethodSignature *sig = mono_method_signature (method);
+       int i;
+       char *name;
+       GHashTable *cache;
+       MonoImage *image = method->klass->image;
+
+       cache = get_cache (&image->static_rgctx_invoke_cache, mono_aligned_addr_hash, NULL);
+       if ((res = mono_marshal_find_in_cache (cache, method)))
+               return res;
+
+       if (!inited) {
+               mono_counters_register ("static rgctx invoke wrappers",
+                               MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &num_wrappers);
+               inited = TRUE;
+       }
+       ++num_wrappers;
+
+       name = mono_signature_to_name (mono_method_signature (method), "static_rgctx_invoke");
+       mb = mono_mb_new (target_klass, name, MONO_WRAPPER_STATIC_RGCTX_INVOKE);
+       g_free (name);
+
+       for (i = 0; i < sig->param_count + sig->hasthis; i++)
+               mono_mb_emit_ldarg (mb, i);
+       mono_mb_emit_op (mb, CEE_CALL, method);
+       mono_mb_emit_byte (mb, CEE_RET);
+
+       res = mono_mb_create_and_cache (cache, method, mb, mono_method_signature (method),
+               sig->param_count + sig->hasthis + 4);
+       res->skip_visibility = TRUE;
+       res->flags = method->flags;
+
+       mono_mb_free (mb);
+
+       return res;
+}
+
 static void
 mono_mb_emit_auto_layout_exception (MonoMethodBuilder *mb, MonoClass *klass)
 {
@@ -5049,8 +5291,10 @@ mono_mb_emit_auto_layout_exception (MonoMethodBuilder *mb, MonoClass *klass)
  * mono_marshal_get_ldfld_remote_wrapper:
  * @klass: The return type
  *
- * This method generates a wrapper for calling mono_load_remote_field_new with
- * the appropriate return type.
+ * This method generates a wrapper for calling mono_load_remote_field_new.
+ * The return type is ignored for now, as mono_load_remote_field_new () always
+ * returns an object. In the future, to optimize some codepaths, we might
+ * call a different function that takes a pointer to a valuetype, instead.
  */
 MonoMethod *
 mono_marshal_get_ldfld_remote_wrapper (MonoClass *klass)
@@ -5058,20 +5302,16 @@ mono_marshal_get_ldfld_remote_wrapper (MonoClass *klass)
        MonoMethodSignature *sig, *csig;
        MonoMethodBuilder *mb;
        MonoMethod *res;
-       GHashTable *cache;
-       char *name;
+       static MonoMethod* cached = NULL;
 
-       cache = klass->image->ldfld_remote_wrapper_cache;
-       if ((res = mono_marshal_find_in_cache (cache, klass)))
-               return res;
+       mono_marshal_lock ();
+       if (cached) {
+               mono_marshal_unlock ();
+               return cached;
+       }
+       mono_marshal_unlock ();
 
-       /* 
-        * This wrapper is similar to an icall wrapper but all the wrappers
-        * call the same C function, but with a different signature.
-        */
-       name = g_strdup_printf ("__mono_load_remote_field_new_wrapper_%s.%s", klass->name_space, klass->name); 
-       mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_LDFLD_REMOTE);
-       g_free (name);
+       mb = mono_mb_new_no_dup_name (mono_defaults.object_class, "__mono_load_remote_field_new_wrapper", MONO_WRAPPER_LDFLD_REMOTE);
 
        mb->method->save_lmf = 1;
 
@@ -5079,7 +5319,7 @@ mono_marshal_get_ldfld_remote_wrapper (MonoClass *klass)
        sig->params [0] = &mono_defaults.object_class->byval_arg;
        sig->params [1] = &mono_defaults.int_class->byval_arg;
        sig->params [2] = &mono_defaults.int_class->byval_arg;
-       sig->ret = &klass->this_arg;
+       sig->ret = &mono_defaults.object_class->byval_arg;
 
        mono_mb_emit_ldarg (mb, 0);
        mono_mb_emit_ldarg (mb, 1);
@@ -5089,18 +5329,33 @@ mono_marshal_get_ldfld_remote_wrapper (MonoClass *klass)
        csig->params [0] = &mono_defaults.object_class->byval_arg;
        csig->params [1] = &mono_defaults.int_class->byval_arg;
        csig->params [2] = &mono_defaults.int_class->byval_arg;
-       csig->ret = &klass->this_arg;
+       csig->ret = &mono_defaults.object_class->byval_arg;
        csig->pinvoke = 1;
 
        mono_mb_emit_native_call (mb, csig, mono_load_remote_field_new);
        emit_thread_interrupt_checkpoint (mb);
 
        mono_mb_emit_byte (mb, CEE_RET);
-       
-       res = mono_mb_create_and_cache (cache, klass,
-                                                                       mb, sig, sig->param_count + 16);
+       mono_marshal_lock ();
+       res = cached;
+       mono_marshal_unlock ();
+       if (!res) {
+               MonoMethod *newm;
+               newm = mono_mb_create_method (mb, sig, 4);
+               mono_marshal_lock ();
+               res = cached;
+               if (!res) {
+                       res = newm;
+                       cached = res;
+                       mono_marshal_unlock ();
+               } else {
+                       mono_marshal_unlock ();
+                       mono_free_method (newm);
+               }
+       }
        mono_mb_free (mb);
-       
+
        return res;
 }
 
@@ -5148,7 +5403,7 @@ mono_marshal_get_ldfld_wrapper (MonoType *type)
                klass = mono_defaults.int_class;
        }
 
-       cache = klass->image->ldfld_wrapper_cache;
+       cache = get_cache (&klass->image->ldfld_wrapper_cache, mono_aligned_addr_hash, NULL);
        if ((res = mono_marshal_find_in_cache (cache, klass)))
                return res;
 
@@ -5270,7 +5525,7 @@ mono_marshal_get_ldflda_wrapper (MonoType *type)
        MonoClass *klass;
        GHashTable *cache;
        char *name;
-       int t, pos0;
+       int t, pos0, pos1, pos2, pos3;
 
        type = mono_type_get_underlying_type (type);
        t = type->type;
@@ -5297,7 +5552,7 @@ mono_marshal_get_ldflda_wrapper (MonoType *type)
                klass = mono_defaults.int_class;
        }
 
-       cache = klass->image->ldflda_wrapper_cache;
+       cache = get_cache (&klass->image->ldflda_wrapper_cache, mono_aligned_addr_hash, NULL);
        if ((res = mono_marshal_find_in_cache (cache, klass)))
                return res;
 
@@ -5313,12 +5568,50 @@ mono_marshal_get_ldflda_wrapper (MonoType *type)
        sig->params [3] = &mono_defaults.int_class->byval_arg;
        sig->ret = &mono_defaults.int_class->byval_arg;
 
+       /* if typeof (this) != transparent_proxy goto pos0 */
+       mono_mb_emit_ldarg (mb, 0);
+       pos0 = mono_mb_emit_proxy_check (mb, CEE_BNE_UN);
+
+       /* if same_appdomain goto pos1 */
+       mono_mb_emit_ldarg (mb, 0);
+       pos1 = mono_mb_emit_xdomain_check (mb, CEE_BEQ);
+
+       mono_mb_emit_exception_full (mb, "System", "InvalidOperationException", "Attempt to load field address from object in another appdomain.");
+
+       /* same app domain */
+       mono_mb_patch_branch (mb, pos1);
+
+       /* if typeof (this) != contextbound goto pos2 */
+       mono_mb_emit_ldarg (mb, 0);
+       pos2 = mono_mb_emit_contextbound_check (mb, CEE_BEQ);
+
+       /* if this->rp->context == mono_context_get goto pos3 */
+       mono_mb_emit_ldarg (mb, 0);
+       mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoTransparentProxy, rp));
+       mono_mb_emit_byte (mb, CEE_LDIND_REF);
+       mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoRealProxy, context));
+       mono_mb_emit_byte (mb, CEE_LDIND_REF);
+       mono_mb_emit_icall (mb, mono_context_get);
+       pos3 = mono_mb_emit_branch (mb, CEE_BEQ);
+
+       mono_mb_emit_exception_full (mb, "System", "InvalidOperationException", "Attempt to load field address from object in another context.");
+
+       mono_mb_patch_branch (mb, pos2);
+       mono_mb_patch_branch (mb, pos3);
+
+       /* return the address of the field from this->rp->unwrapped_server */
        mono_mb_emit_ldarg (mb, 0);
-       pos0 = mono_mb_emit_proxy_check (mb, CEE_BNE_UN);
-
-       /* FIXME: Only throw this if the object is in another appdomain */
-       mono_mb_emit_exception_full (mb, "System", "InvalidOperationException", "Attempt to load field address from object in another appdomain.");
+       mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoTransparentProxy, rp));
+       mono_mb_emit_byte (mb, CEE_LDIND_REF);
+       mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoRealProxy, unwrapped_server));
+       mono_mb_emit_byte (mb, CEE_LDIND_REF);
+       mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
+       mono_mb_emit_byte (mb, CEE_MONO_OBJADDR);
+       mono_mb_emit_ldarg (mb, 3);
+       mono_mb_emit_byte (mb, CEE_ADD);
+       mono_mb_emit_byte (mb, CEE_RET);
 
+       /* not a proxy: return the address of the field directly */
        mono_mb_patch_branch (mb, pos0);
 
        mono_mb_emit_ldarg (mb, 0);
@@ -5342,6 +5635,8 @@ mono_marshal_get_ldflda_wrapper (MonoType *type)
  *
  *  This function generates a wrapper for calling mono_store_remote_field_new
  * with the appropriate signature.
+ * Similarly to mono_marshal_get_ldfld_remote_wrapper () this doesn't depend on the
+ * klass argument anymore.
  */
 MonoMethod *
 mono_marshal_get_stfld_remote_wrapper (MonoClass *klass)
@@ -5349,16 +5644,16 @@ mono_marshal_get_stfld_remote_wrapper (MonoClass *klass)
        MonoMethodSignature *sig, *csig;
        MonoMethodBuilder *mb;
        MonoMethod *res;
-       GHashTable *cache;
-       char *name;
+       static MonoMethod *cached = NULL;
 
-       cache = klass->image->stfld_remote_wrapper_cache;
-       if ((res = mono_marshal_find_in_cache (cache, klass)))
-               return res;
+       mono_marshal_lock ();
+       if (cached) {
+               mono_marshal_unlock ();
+               return cached;
+       }
+       mono_marshal_unlock ();
 
-       name = g_strdup_printf ("__mono_store_remote_field_new_wrapper_%s.%s", klass->name_space, klass->name); 
-       mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_STFLD_REMOTE);
-       g_free (name);
+       mb = mono_mb_new_no_dup_name (mono_defaults.object_class, "__mono_store_remote_field_new_wrapper", MONO_WRAPPER_STFLD_REMOTE);
 
        mb->method->save_lmf = 1;
 
@@ -5366,7 +5661,7 @@ mono_marshal_get_stfld_remote_wrapper (MonoClass *klass)
        sig->params [0] = &mono_defaults.object_class->byval_arg;
        sig->params [1] = &mono_defaults.int_class->byval_arg;
        sig->params [2] = &mono_defaults.int_class->byval_arg;
-       sig->params [3] = &klass->byval_arg;
+       sig->params [3] = &mono_defaults.object_class->byval_arg;
        sig->ret = &mono_defaults.void_class->byval_arg;
 
        mono_mb_emit_ldarg (mb, 0);
@@ -5374,14 +5669,11 @@ mono_marshal_get_stfld_remote_wrapper (MonoClass *klass)
        mono_mb_emit_ldarg (mb, 2);
        mono_mb_emit_ldarg (mb, 3);
 
-       if (klass->valuetype)
-               mono_mb_emit_op (mb, CEE_BOX, klass);
-
        csig = mono_metadata_signature_alloc (mono_defaults.corlib, 4);
        csig->params [0] = &mono_defaults.object_class->byval_arg;
        csig->params [1] = &mono_defaults.int_class->byval_arg;
        csig->params [2] = &mono_defaults.int_class->byval_arg;
-       csig->params [3] = &klass->byval_arg;
+       csig->params [3] = &mono_defaults.object_class->byval_arg;
        csig->ret = &mono_defaults.void_class->byval_arg;
        csig->pinvoke = 1;
 
@@ -5389,9 +5681,24 @@ mono_marshal_get_stfld_remote_wrapper (MonoClass *klass)
        emit_thread_interrupt_checkpoint (mb);
 
        mono_mb_emit_byte (mb, CEE_RET);
-       
-       res = mono_mb_create_and_cache (cache, klass,
-                                                                       mb, sig, sig->param_count + 16);
+       mono_marshal_lock ();
+       res = cached;
+       mono_marshal_unlock ();
+       if (!res) {
+               MonoMethod *newm;
+               newm = mono_mb_create_method (mb, sig, 6);
+               mono_marshal_lock ();
+               res = cached;
+               if (!res) {
+                       res = newm;
+                       cached = res;
+                       mono_marshal_unlock ();
+               } else {
+                       mono_marshal_unlock ();
+                       mono_free_method (newm);
+               }
+       }
        mono_mb_free (mb);
        
        return res;
@@ -5440,7 +5747,7 @@ mono_marshal_get_stfld_wrapper (MonoType *type)
                klass = mono_defaults.int_class;
        }
 
-       cache = klass->image->stfld_wrapper_cache;
+       cache = get_cache (&klass->image->stfld_wrapper_cache, mono_aligned_addr_hash, NULL);
        if ((res = mono_marshal_find_in_cache (cache, klass)))
                return res;
 
@@ -5464,6 +5771,8 @@ mono_marshal_get_stfld_wrapper (MonoType *type)
        mono_mb_emit_ldarg (mb, 1);
        mono_mb_emit_ldarg (mb, 2);
        mono_mb_emit_ldarg (mb, 4);
+       if (klass->valuetype)
+               mono_mb_emit_op (mb, CEE_BOX, klass);
 
        mono_mb_emit_managed_call (mb, mono_marshal_get_stfld_remote_wrapper (klass), NULL);
 
@@ -5528,7 +5837,7 @@ mono_marshal_get_stfld_wrapper (MonoType *type)
  * calls the unmanaged code in func)
  */
 MonoMethod *
-mono_marshal_get_icall_wrapper (MonoMethodSignature *sig, const char *name, gconstpointer func)
+mono_marshal_get_icall_wrapper (MonoMethodSignature *sig, const char *name, gconstpointer func, gboolean check_exceptions)
 {
        MonoMethodSignature *csig;
        MonoMethodBuilder *mb;
@@ -5550,7 +5859,8 @@ mono_marshal_get_icall_wrapper (MonoMethodSignature *sig, const char *name, gcon
                mono_mb_emit_ldarg (mb, i + sig->hasthis);
 
        mono_mb_emit_native_call (mb, sig, (gpointer) func);
-       emit_thread_interrupt_checkpoint (mb);
+       if (check_exceptions)
+               emit_thread_interrupt_checkpoint (mb);
        mono_mb_emit_byte (mb, CEE_RET);
 
        csig = signature_dup (mono_defaults.corlib, sig);
@@ -5759,7 +6069,7 @@ emit_marshal_custom (EmitMarshalContext *m, int argnum, MonoType *t,
                        mono_mb_emit_ldloc (mb, conv_arg);
                        mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
                        mono_mb_emit_byte (mb, CEE_STIND_REF);
-               } else if (t->attrs &PARAM_ATTRIBUTE_OUT) {
+               } else {
                        mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
 
                        mono_mb_emit_op (mb, CEE_CALL, get_instance);
@@ -5822,6 +6132,9 @@ emit_marshal_custom (EmitMarshalContext *m, int argnum, MonoType *t,
                mono_mb_emit_byte (mb, CEE_LDNULL);
                mono_mb_emit_stloc (mb, conv_arg);
 
+               if (t->byref && t->attrs & PARAM_ATTRIBUTE_OUT)
+                       break;
+
                /* Check for null */
                mono_mb_emit_ldarg (mb, argnum);
                if (t->byref)
@@ -5961,7 +6274,7 @@ emit_marshal_vtype (EmitMarshalContext *m, int argnum, MonoType *t,
        MonoClass *klass;
        int pos = 0, pos2;
 
-       klass = t->data.klass;
+       klass = mono_class_from_mono_type (t);
 
        switch (action) {
        case MARSHAL_ACTION_CONV_IN:
@@ -6214,26 +6527,26 @@ emit_marshal_string (EmitMarshalContext *m, int argnum, MonoType *t,
                break;
 
        case MARSHAL_ACTION_CONV_OUT:
+               conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
+               if (conv == -1) {
+                       char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
+                       mono_mb_emit_exception_marshal_directive (mb, msg);
+                       break;
+               }
+
                if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT)) {
                        mono_mb_emit_ldarg (mb, argnum);
                        mono_mb_emit_ldloc (mb, conv_arg);
-                       if (conv == MONO_MARSHAL_CONV_STR_BSTR) {
-                               mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_BSTR_STR));
-                               // BSTRs always need freed
-                               mono_mb_emit_ldloc (mb, conv_arg);
+                       mono_mb_emit_icall (mb, conv_to_icall (conv));
+                       mono_mb_emit_byte (mb, CEE_STIND_REF);
+               }
+
+               if (need_free || (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT))) {
+                       mono_mb_emit_ldloc (mb, conv_arg);
+                       if (conv == MONO_MARSHAL_CONV_BSTR_STR)
                                mono_mb_emit_icall (mb, mono_free_bstr);
-                       }
                        else
-                               mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_LPSTR_STR));
-                       mono_mb_emit_byte (mb, CEE_STIND_REF);
-               } else {
-                       if (mono_marshal_need_free (t, m->piinfo, spec)) {
-                               mono_mb_emit_ldloc (mb, conv_arg);
-                               if (conv == MONO_MARSHAL_CONV_STR_BSTR)
-                                       mono_mb_emit_icall (mb, mono_free_bstr);
-                               else
-                                       mono_mb_emit_icall (mb, mono_marshal_free);
-                       }
+                               mono_mb_emit_icall (mb, mono_marshal_free);
                }
                break;
 
@@ -6263,16 +6576,12 @@ emit_marshal_string (EmitMarshalContext *m, int argnum, MonoType *t,
                if (conv == MONO_MARSHAL_CONV_BSTR_STR)
                        mono_mb_emit_icall (mb, mono_free_bstr);
                else
-                       mono_mb_emit_icall (mb, g_free);
+                       mono_mb_emit_icall (mb, mono_marshal_free);
                break;
 
        case MARSHAL_ACTION_MANAGED_CONV_IN:
-               if (t->byref) {
-                       conv_arg = 0;
-                       break;
-               }
-
                conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
+
                *conv_arg_type = &mono_defaults.int_class->byval_arg;
 
                conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
@@ -6283,12 +6592,29 @@ emit_marshal_string (EmitMarshalContext *m, int argnum, MonoType *t,
                }
 
                mono_mb_emit_ldarg (mb, argnum);
+               if (t->byref)
+                       mono_mb_emit_byte (mb, CEE_LDIND_I);
                mono_mb_emit_icall (mb, conv_to_icall (conv));
                mono_mb_emit_stloc (mb, conv_arg);
-               break;  
+               break;
+
+       case MARSHAL_ACTION_MANAGED_CONV_OUT:
+               if (t->byref) {
+                       if (conv_arg) {
+                               mono_mb_emit_ldarg (mb, argnum);
+                               mono_mb_emit_ldloc (mb, conv_arg);
+                               mono_mb_emit_icall (mb, conv_to_icall (conv));
+                               mono_mb_emit_byte (mb, CEE_STIND_I);
+                       }
+               }
+               break;
 
        case MARSHAL_ACTION_MANAGED_CONV_RESULT:
-               mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_STR_LPSTR));
+               if (conv_to_icall (conv) == mono_marshal_string_to_utf16)
+                       /* We need to make a copy so the caller is able to free it */
+                       mono_mb_emit_icall (mb, mono_marshal_string_to_utf16_copy);
+               else
+                       mono_mb_emit_icall (mb, conv_to_icall (conv));
                mono_mb_emit_stloc (mb, 3);
                break;
 
@@ -6403,7 +6729,7 @@ emit_marshal_safehandle (EmitMarshalContext *m, int argnum, MonoType *t,
                        label_next = mono_mb_emit_branch (mb, CEE_BRFALSE);
                        mono_mb_emit_ldarg (mb, argnum);
                        mono_mb_emit_managed_call (mb, sh_dangerous_release, NULL);
-                       mono_mb_patch_addr (mb, label_next, mb->pos - (label_next + 4));
+                       mono_mb_patch_branch (mb, label_next);
                }
                break;
        }
@@ -6478,8 +6804,9 @@ emit_marshal_handleref (EmitMarshalContext *m, int argnum, MonoType *t,
                                "HandleRefs can not be returned from unmanaged code (or passed by ref)");
                        break;
                } 
-               mono_mb_emit_ldarg (mb, argnum);
-               mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoHandleRef, handle));
+               mono_mb_emit_ldarg_addr (mb, argnum);
+               mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoHandleRef, handle));
+               mono_mb_emit_byte (mb, CEE_ADD);
                mono_mb_emit_byte (mb, CEE_LDIND_I);
                mono_mb_emit_stloc (mb, conv_arg);
                break;
@@ -6525,7 +6852,7 @@ emit_marshal_object (EmitMarshalContext *m, int argnum, MonoType *t,
                     MarshalAction action)
 {
        MonoMethodBuilder *mb = m->mb;
-       MonoClass *klass = t->data.klass;
+       MonoClass *klass = mono_class_from_mono_type (t);
        int pos, pos2, loc;
 
        if (mono_class_from_mono_type (t) == mono_defaults.object_class) {
@@ -6540,10 +6867,18 @@ emit_marshal_object (EmitMarshalContext *m, int argnum, MonoType *t,
                m->orig_conv_args [argnum] = 0;
                
                if (klass->delegate) {
-                       g_assert (!t->byref);
-                       mono_mb_emit_ldarg (mb, argnum);
-                       mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_DEL_FTN));
-                       mono_mb_emit_stloc (mb, conv_arg);
+                       if (t->byref) {
+                               if (!(t->attrs & PARAM_ATTRIBUTE_OUT)) {
+                                       char *msg = g_strdup_printf ("Byref marshalling of delegates is not implemented.");
+                                       mono_mb_emit_exception_marshal_directive (mb, msg);
+                               }
+                               mono_mb_emit_byte (mb, CEE_LDNULL);
+                               mono_mb_emit_stloc (mb, conv_arg);
+                       } else {
+                               mono_mb_emit_ldarg (mb, argnum);
+                               mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_DEL_FTN));
+                               mono_mb_emit_stloc (mb, conv_arg);
+                       }
                } else if (klass == mono_defaults.stringbuilder_class) {
                        MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
                        MonoMarshalConv conv = mono_marshal_get_stringbuilder_to_ptr_conv (m->piinfo, spec);
@@ -6651,14 +6986,23 @@ emit_marshal_object (EmitMarshalContext *m, int argnum, MonoType *t,
                        break;
                }
 
-               if (klass->delegate)
+               if (klass->delegate) {
+                       if (t->byref) {
+                               mono_mb_emit_ldarg (mb, argnum);
+                               mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
+                               mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
+                               mono_mb_emit_ldloc (mb, conv_arg);
+                               mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL));
+                               mono_mb_emit_byte (mb, CEE_STIND_REF);
+                       }
                        break;
+               }
 
                if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT)) {
                        /* allocate a new object */
                        mono_mb_emit_ldarg (mb, argnum);
                        mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
-                       mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, t->data.klass);
+                       mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, klass);
                        mono_mb_emit_byte (mb, CEE_STIND_REF);
                }
 
@@ -6684,7 +7028,7 @@ emit_marshal_object (EmitMarshalContext *m, int argnum, MonoType *t,
                        mono_mb_emit_stloc (mb, 0);
 
                        /* emit valuetype conversion code */
-                       emit_struct_conv (mb, t->data.klass, TRUE);
+                       emit_struct_conv (mb, klass, TRUE);
 
                        /* Free the structure returned by the native code */
                        emit_struct_free (mb, klass, conv_arg);
@@ -6785,6 +7129,23 @@ emit_marshal_object (EmitMarshalContext *m, int argnum, MonoType *t,
                        break;
                }
 
+               if (klass == mono_defaults.stringbuilder_class) {
+                       MonoMarshalNative encoding;
+
+                       encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
+
+                       // FIXME:
+                       g_assert (encoding == MONO_NATIVE_LPSTR);
+
+                       g_assert (!t->byref);
+                       g_assert (encoding != -1);
+
+                       mono_mb_emit_ldarg (mb, argnum);
+                       mono_mb_emit_icall (mb, mono_string_utf8_to_builder2);
+                       mono_mb_emit_stloc (mb, conv_arg);
+                       break;
+               }
+
                /* The class can not have an automatic layout */
                if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
                        mono_mb_emit_auto_layout_exception (mb, klass);
@@ -6933,6 +7294,8 @@ emit_marshal_object (EmitMarshalContext *m, int argnum, MonoType *t,
        return conv_arg;
 }
 
+#ifndef DISABLE_COM
+
 static int
 emit_marshal_com_interface (EmitMarshalContext *m, int argnum, MonoType *t,
                     MonoMarshalSpec *spec, 
@@ -6945,6 +7308,8 @@ emit_marshal_com_interface (EmitMarshalContext *m, int argnum, MonoType *t,
        static MonoMethod* get_iunknown_for_object_internal = NULL;
        static MonoMethod* get_com_interface_for_object_internal = NULL;
        static MonoMethod* get_idispatch_for_object_internal = NULL;
+       static MonoMethod* marshal_release = NULL;
+       static MonoMethod* AddRef = NULL;
        if (!get_object_for_iunknown)
                get_object_for_iunknown = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetObjectForIUnknown", 1);
        if (!get_iunknown_for_object_internal)
@@ -6953,6 +7318,8 @@ emit_marshal_com_interface (EmitMarshalContext *m, int argnum, MonoType *t,
                get_idispatch_for_object_internal = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetIDispatchForObjectInternal", 1);
        if (!get_com_interface_for_object_internal)
                get_com_interface_for_object_internal = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetComInterfaceForObjectInternal", 2);
+       if (!marshal_release)
+               marshal_release = mono_class_get_method_from_name (mono_defaults.marshal_class, "Release", 1);
 
        /* COM types are initialized lazily */
        mono_init_com_types ();
@@ -7026,6 +7393,7 @@ emit_marshal_com_interface (EmitMarshalContext *m, int argnum, MonoType *t,
                        if (klass && klass != mono_defaults.object_class)
                                mono_mb_emit_op (mb, CEE_CASTCLASS, klass);
                        mono_mb_emit_byte (mb, CEE_STIND_REF);
+
                        pos_end = mono_mb_emit_short_branch (mb, CEE_BR_S);
 
                        /* is already managed object */
@@ -7037,8 +7405,13 @@ emit_marshal_com_interface (EmitMarshalContext *m, int argnum, MonoType *t,
                                mono_mb_emit_op (mb, CEE_CASTCLASS, klass);
                        mono_mb_emit_byte (mb, CEE_STIND_REF);
 
-
                        mono_mb_patch_short_branch (mb, pos_end);
+
+                       /* need to call Release to follow COM rules of ownership */
+                       mono_mb_emit_ldloc (mb, conv_arg);
+                       mono_mb_emit_managed_call (mb, marshal_release, NULL);
+                       mono_mb_emit_byte (mb, CEE_POP);
+
                        /* case if null */
                        mono_mb_patch_short_branch (mb, pos_null);
                }
@@ -7052,8 +7425,50 @@ emit_marshal_com_interface (EmitMarshalContext *m, int argnum, MonoType *t,
                break;
 
        case MARSHAL_ACTION_CONV_RESULT: {
-               char *msg = g_strdup ("Marshalling of COM Objects is not yet implemented.");
-               mono_mb_emit_exception_marshal_directive (mb, msg);
+               int ccw_obj, ret_ptr;
+               guint32 pos_null = 0, pos_ccw = 0, pos_end = 0;
+               ccw_obj = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
+               ret_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
+
+               /* store return value */
+               mono_mb_emit_stloc (mb, ret_ptr);
+
+               mono_mb_emit_ldloc (mb, ret_ptr);
+               pos_null = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
+
+               mono_mb_emit_ldloc (mb, ret_ptr);
+               mono_mb_emit_icon (mb, TRUE);
+               mono_mb_emit_icall (mb, cominterop_get_ccw_object);
+               mono_mb_emit_stloc (mb, ccw_obj);
+               mono_mb_emit_ldloc (mb, ccw_obj);
+               pos_ccw = mono_mb_emit_short_branch (mb, CEE_BRTRUE_S);
+
+               mono_mb_emit_ldloc (mb, ret_ptr);
+               mono_mb_emit_managed_call (mb, get_object_for_iunknown, NULL);
+
+               if (klass && klass != mono_defaults.object_class)
+                       mono_mb_emit_op (mb, CEE_CASTCLASS, klass);
+               mono_mb_emit_stloc (mb, 3);
+
+               pos_end = mono_mb_emit_short_branch (mb, CEE_BR_S);
+
+               /* is already managed object */
+               mono_mb_patch_short_branch (mb, pos_ccw);
+               mono_mb_emit_ldloc (mb, ccw_obj);
+
+               if (klass && klass != mono_defaults.object_class)
+                       mono_mb_emit_op (mb, CEE_CASTCLASS, klass);
+               mono_mb_emit_stloc (mb, 3);
+
+               mono_mb_patch_short_branch (mb, pos_end);
+
+               /* need to call Release to follow COM rules of ownership */
+               mono_mb_emit_ldloc (mb, ret_ptr);
+               mono_mb_emit_managed_call (mb, marshal_release, NULL);
+               mono_mb_emit_byte (mb, CEE_POP);
+
+               /* case if null */
+               mono_mb_patch_short_branch (mb, pos_null);
                break;
        } 
 
@@ -7111,7 +7526,6 @@ emit_marshal_com_interface (EmitMarshalContext *m, int argnum, MonoType *t,
 
        case MARSHAL_ACTION_MANAGED_CONV_OUT: {
                if (t->byref && t->attrs & PARAM_ATTRIBUTE_OUT) {
-                       static MonoMethod* AddRef = NULL;
                        guint32 pos_null = 0;
 
                        if (!AddRef)
@@ -7150,8 +7564,43 @@ emit_marshal_com_interface (EmitMarshalContext *m, int argnum, MonoType *t,
        }
 
        case MARSHAL_ACTION_MANAGED_CONV_RESULT: {
-               char *msg = g_strdup ("Marshalling of COM Objects is not yet implemented.");
-               mono_mb_emit_exception_marshal_directive (mb, msg);
+               guint32 pos_null = 0;
+               int ccw_obj;
+               ccw_obj = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
+
+               if (!AddRef)
+                       AddRef = mono_class_get_method_from_name (mono_defaults.marshal_class, "AddRef", 1);
+
+               /* store return value */
+               mono_mb_emit_stloc (mb, ccw_obj);
+
+               mono_mb_emit_ldloc (mb, ccw_obj);
+
+               /* if null just break, conv arg was already inited to 0 */
+               pos_null = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
+
+               /* to store later */
+               mono_mb_emit_ldloc (mb, ccw_obj);
+               if (klass && klass != mono_defaults.object_class) {
+                       mono_mb_emit_ptr (mb, t);
+                       mono_mb_emit_icall (mb, type_from_handle);
+                       mono_mb_emit_managed_call (mb, get_com_interface_for_object_internal, NULL);
+               }
+               else if (spec->native == MONO_NATIVE_IUNKNOWN)
+                       mono_mb_emit_managed_call (mb, get_iunknown_for_object_internal, NULL);
+               else if (spec->native == MONO_NATIVE_IDISPATCH)
+                       mono_mb_emit_managed_call (mb, get_idispatch_for_object_internal, NULL);
+               else if (!klass && spec->native == MONO_NATIVE_INTERFACE)
+                       mono_mb_emit_managed_call (mb, get_iunknown_for_object_internal, NULL);
+               else
+                       g_assert_not_reached ();
+               mono_mb_emit_stloc (mb, 3);
+               mono_mb_emit_ldloc (mb, 3);
+               
+               mono_mb_emit_managed_call (mb, AddRef, NULL);
+               mono_mb_emit_byte (mb, CEE_POP);
+
+               mono_mb_patch_short_branch (mb, pos_null);
                break;
        }
 
@@ -7162,6 +7611,8 @@ emit_marshal_com_interface (EmitMarshalContext *m, int argnum, MonoType *t,
        return conv_arg;
 }
 
+#endif /* DISABLE_COM */
+
 static int
 emit_marshal_variant (EmitMarshalContext *m, int argnum, MonoType *t,
                     MonoMarshalSpec *spec, 
@@ -7191,7 +7642,7 @@ emit_marshal_variant (EmitMarshalContext *m, int argnum, MonoType *t,
                else
                        *conv_arg_type = &mono_defaults.variant_class->byval_arg;
 
-               if (t->byref && t->attrs & PARAM_ATTRIBUTE_OUT)
+               if (t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && t->attrs & PARAM_ATTRIBUTE_OUT)
                        break;
 
                mono_mb_emit_ldarg (mb, argnum);
@@ -7210,7 +7661,7 @@ emit_marshal_variant (EmitMarshalContext *m, int argnum, MonoType *t,
                g_assert (variant_clear);
 
 
-               if (t->byref) {
+               if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT || !(t->attrs & PARAM_ATTRIBUTE_IN))) {
                        mono_mb_emit_ldarg (mb, argnum);
                        mono_mb_emit_ldloc_addr (mb, conv_arg);
                        mono_mb_emit_managed_call (mb, get_object_for_native_variant, NULL);
@@ -7243,7 +7694,7 @@ emit_marshal_variant (EmitMarshalContext *m, int argnum, MonoType *t,
                else
                        *conv_arg_type = &mono_defaults.variant_class->byval_arg;
 
-               if (t->byref && t->attrs & PARAM_ATTRIBUTE_OUT)
+               if (t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && t->attrs & PARAM_ATTRIBUTE_OUT)
                        break;
 
                if (t->byref)
@@ -7256,7 +7707,7 @@ emit_marshal_variant (EmitMarshalContext *m, int argnum, MonoType *t,
        }
 
        case MARSHAL_ACTION_MANAGED_CONV_OUT: {
-               if (t->byref) {
+               if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT || !(t->attrs & PARAM_ATTRIBUTE_IN))) {
                        mono_mb_emit_ldloc (mb, conv_arg);
                        mono_mb_emit_ldarg (mb, argnum);
                        mono_mb_emit_managed_call (mb, get_native_variant_for_object, NULL);
@@ -7372,7 +7823,7 @@ emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
                        index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);                                
                        mono_mb_emit_byte (mb, CEE_LDC_I4_0);
                        mono_mb_emit_stloc (mb, index_var);
-                       label2 = mb->pos;
+                       label2 = mono_mb_get_label (mb);
                        mono_mb_emit_ldloc (mb, index_var);
                        mono_mb_emit_ldloc (mb, src_var);
                        mono_mb_emit_byte (mb, CEE_LDLEN);
@@ -7405,8 +7856,7 @@ emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
                        mono_mb_emit_add_to_local (mb, index_var, 1);
                        mono_mb_emit_add_to_local (mb, dest_ptr, esize);
                        
-                       mono_mb_emit_byte (mb, CEE_BR);
-                       mono_mb_emit_i4 (mb, label2 - (mb->pos + 4));
+                       mono_mb_emit_branch_label (mb, CEE_BR, label2);
 
                        mono_mb_patch_branch (mb, label3);
 
@@ -7455,7 +7905,7 @@ emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
                        index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);                                
                        mono_mb_emit_byte (mb, CEE_LDC_I4_0);
                        mono_mb_emit_stloc (mb, index_var);
-                       label2 = mb->pos;
+                       label2 = mono_mb_get_label (mb);
                        mono_mb_emit_ldloc (mb, index_var);
                        mono_mb_emit_ldarg (mb, argnum);
                        if (t->byref)
@@ -7510,7 +7960,7 @@ emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
                                        /* set dst_ptr */
                                        mono_mb_emit_ldarg (mb, argnum);
                                        if (t->byref)
-                                               mono_mb_emit_byte (mb, CEE_LDIND_I);
+                                               mono_mb_emit_byte (mb, CEE_LDIND_REF);
                                        mono_mb_emit_ldloc (mb, index_var);
                                        mono_mb_emit_op (mb, CEE_LDELEMA, eklass);
                                        mono_mb_emit_stloc (mb, 1);
@@ -7531,8 +7981,7 @@ emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
                        mono_mb_emit_add_to_local (mb, index_var, 1);
                        mono_mb_emit_add_to_local (mb, src_ptr, esize);
 
-                       mono_mb_emit_byte (mb, CEE_BR);
-                       mono_mb_emit_i4 (mb, label2 - (mb->pos + 4));
+                       mono_mb_emit_branch_label (mb, CEE_BR, label2);
 
                        mono_mb_patch_branch (mb, label1);
                        mono_mb_patch_branch (mb, label3);
@@ -7694,7 +8143,7 @@ emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
                index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
                mono_mb_emit_byte (mb, CEE_LDC_I4_0);
                mono_mb_emit_stloc (mb, index_var);
-               label2 = mb->pos;
+               label2 = mono_mb_get_label (mb);
                mono_mb_emit_ldloc (mb, index_var);
                mono_mb_emit_ldloc (mb, conv_arg);
                mono_mb_emit_byte (mb, CEE_LDLEN);
@@ -7722,8 +8171,7 @@ emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
                mono_mb_emit_add_to_local (mb, index_var, 1);
                mono_mb_emit_add_to_local (mb, src_ptr, esize);
 
-               mono_mb_emit_byte (mb, CEE_BR);
-               mono_mb_emit_i4 (mb, label2 - (mb->pos + 4));
+               mono_mb_emit_branch_label (mb, CEE_BR, label2);
 
                mono_mb_patch_branch (mb, label1);
                mono_mb_patch_branch (mb, label3);
@@ -7812,7 +8260,7 @@ emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
                index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
                mono_mb_emit_byte (mb, CEE_LDC_I4_0);
                mono_mb_emit_stloc (mb, index_var);
-               label2 = mb->pos;
+               label2 = mono_mb_get_label (mb);
                mono_mb_emit_ldloc (mb, index_var);
                mono_mb_emit_ldloc (mb, conv_arg);
                mono_mb_emit_byte (mb, CEE_LDLEN);
@@ -7843,8 +8291,7 @@ emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
                mono_mb_emit_add_to_local (mb, index_var, 1);
                mono_mb_emit_add_to_local (mb, dest_ptr, esize);
 
-               mono_mb_emit_byte (mb, CEE_BR);
-               mono_mb_emit_i4 (mb, label2 - (mb->pos + 4));
+               mono_mb_emit_branch_label (mb, CEE_BR, label2);
 
                mono_mb_patch_branch (mb, label1);
                mono_mb_patch_branch (mb, label3);
@@ -7908,7 +8355,7 @@ emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
                index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
                mono_mb_emit_byte (mb, CEE_LDC_I4_0);
                mono_mb_emit_stloc (mb, index_var);
-               label2 = mb->pos;
+               label2 = mono_mb_get_label (mb);
                mono_mb_emit_ldloc (mb, index_var);
                mono_mb_emit_ldloc (mb, src);
                mono_mb_emit_byte (mb, CEE_LDLEN);
@@ -7939,8 +8386,7 @@ emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
                mono_mb_emit_add_to_local (mb, index_var, 1);
                mono_mb_emit_add_to_local (mb, dest, esize);
 
-               mono_mb_emit_byte (mb, CEE_BR);
-               mono_mb_emit_i4 (mb, label2 - (mb->pos + 4));
+               mono_mb_emit_branch_label (mb, CEE_BR, label2);
 
                mono_mb_patch_branch (mb, label3);
                mono_mb_patch_branch (mb, label1);
@@ -7972,6 +8418,7 @@ emit_marshal_boolean (EmitMarshalContext *m, int argnum, MonoType *t,
                } else {
                        switch (spec->native) {
                        case MONO_NATIVE_I1:
+                       case MONO_NATIVE_U1:
                                local_type = &mono_defaults.byte_class->byval_arg;
                                break;
                        case MONO_NATIVE_VARIANTBOOL:
@@ -8132,10 +8579,12 @@ emit_marshal (EmitMarshalContext *m, int argnum, MonoType *t,
                if (spec && spec->native == MONO_NATIVE_STRUCT)
                        return emit_marshal_variant (m, argnum, t, spec, conv_arg, conv_arg_type, action);
 
+#ifndef DISABLE_COM
                if (spec && (spec->native == MONO_NATIVE_IUNKNOWN ||
                        spec->native == MONO_NATIVE_IDISPATCH ||
                        spec->native == MONO_NATIVE_INTERFACE))
                        return emit_marshal_com_interface (m, argnum, t, spec, conv_arg, conv_arg_type, action);
+#endif
 
                if (mono_defaults.safehandle_class != NULL &&
                    mono_class_is_subclass_of (t->data.klass,  mono_defaults.safehandle_class, FALSE))
@@ -8165,6 +8614,11 @@ emit_marshal (EmitMarshalContext *m, int argnum, MonoType *t,
        case MONO_TYPE_U8:
        case MONO_TYPE_FNPTR:
                return emit_marshal_scalar (m, argnum, t, spec, conv_arg, conv_arg_type, action);
+       case MONO_TYPE_GENERICINST:
+               if (mono_type_generic_inst_is_valuetype (t))
+                       return emit_marshal_vtype (m, argnum, t, spec, conv_arg, conv_arg_type, action);
+               else
+                       return emit_marshal_object (m, argnum, t, spec, conv_arg, conv_arg_type, action);
        }
 
        return conv_arg;
@@ -8176,12 +8630,14 @@ emit_marshal (EmitMarshalContext *m, int argnum, MonoType *t,
  * @sig: The signature of the native function
  * @piinfo: Marshalling information
  * @mspecs: Marshalling information
- * @func: the native function to call
+ * @aot: whenever the created method will be compiled by the AOT compiler
+ * @method: if non-NULL, the pinvoke method to call
+ * @check_exceptions: Whenever to check for pending exceptions after the native call
  *
  * generates IL code for the pinvoke wrapper, the generated code calls @func.
  */
 static void
-mono_marshal_emit_native_wrapper (MonoImage *image, MonoMethodBuilder *mb, MonoMethodSignature *sig, MonoMethodPInvoke *piinfo, MonoMarshalSpec **mspecs, gpointer func)
+mono_marshal_emit_native_wrapper (MonoImage *image, MonoMethodBuilder *mb, MonoMethodSignature *sig, MonoMethodPInvoke *piinfo, MonoMarshalSpec **mspecs, gpointer func, gboolean aot, gboolean check_exceptions)
 {
        EmitMarshalContext m;
        MonoMethodSignature *csig;
@@ -8239,17 +8695,27 @@ mono_marshal_emit_native_wrapper (MonoImage *image, MonoMethodBuilder *mb, MonoM
        if (sig->hasthis)
                mono_mb_emit_byte (mb, CEE_LDARG_0);
 
-
        for (i = 0; i < sig->param_count; i++) {
                emit_marshal (&m, i + sig->hasthis, sig->params [i], mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_PUSH);
        }                       
 
        /* call the native method */
        if (MONO_CLASS_IS_IMPORT (mb->method->klass)) {
+#ifndef DISABLE_COM
                mono_mb_emit_cominterop_call (mb, csig, &piinfo->method);
+#else
+               g_assert_not_reached ();
+#endif
        }
        else {
-               mono_mb_emit_native_call (mb, csig, func);
+               if (aot) {
+                       /* Reuse the ICALL_ADDR opcode for pinvokes too */
+                       mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
+                       mono_mb_emit_op (mb, CEE_MONO_ICALL_ADDR, &piinfo->method);
+                       mono_mb_emit_calli (mb, csig);
+               } else {                        
+                       mono_mb_emit_native_call (mb, csig, func);
+               }
        }
 
        /* Set LastError if needed */
@@ -8314,6 +8780,7 @@ mono_marshal_emit_native_wrapper (MonoImage *image, MonoMethodBuilder *mb, MonoM
                        case MONO_TYPE_SZARRAY:
                        case MONO_TYPE_CHAR:
                        case MONO_TYPE_PTR:
+                       case MONO_TYPE_GENERICINST:
                                emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
                                break;
                        case MONO_TYPE_TYPEDBYREF:
@@ -8330,7 +8797,8 @@ mono_marshal_emit_native_wrapper (MonoImage *image, MonoMethodBuilder *mb, MonoM
         * Need to call this after converting the result since MONO_VTADDR needs 
         * to be adjacent to the call instruction.
         */
-       emit_thread_interrupt_checkpoint (mb);
+       if (check_exceptions)
+               emit_thread_interrupt_checkpoint (mb);
 
        /* we need to convert byref arguments back and free string arrays */
        for (i = 0; i < sig->param_count; i++) {
@@ -8365,12 +8833,13 @@ mono_marshal_emit_native_wrapper (MonoImage *image, MonoMethodBuilder *mb, MonoM
 /**
  * mono_marshal_get_native_wrapper:
  * @method: The MonoMethod to wrap.
+ * @check_exceptions: Whenever to check for pending exceptions
  *
  * generates IL code for the pinvoke wrapper (the generated method
  * calls the unmanaged code in piinfo->addr)
  */
 MonoMethod *
-mono_marshal_get_native_wrapper (MonoMethod *method)
+mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions, gboolean aot)
 {
        MonoMethodSignature *sig, *csig;
        MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
@@ -8391,8 +8860,13 @@ mono_marshal_get_native_wrapper (MonoMethod *method)
        if ((res = mono_marshal_find_in_cache (cache, method)))
                return res;
 
-       if (MONO_CLASS_IS_IMPORT (method->klass))
+       if (MONO_CLASS_IS_IMPORT (method->klass)) {
+#ifndef DISABLE_COM
                return cominterop_get_native_wrapper (method);
+#else
+               g_assert_not_reached ();
+#endif
+       }
 
        sig = mono_method_signature (method);
 
@@ -8402,7 +8876,10 @@ mono_marshal_get_native_wrapper (MonoMethod *method)
 
        if (!piinfo->addr) {
                if (pinvoke)
-                       mono_lookup_pinvoke_call (method, &exc_class, &exc_arg);
+                       if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)
+                               exc_arg = "Method contains unsupported native code";
+                       else
+                               mono_lookup_pinvoke_call (method, &exc_class, &exc_arg);
                else
                        piinfo->addr = mono_lookup_internal_call (method);
        }
@@ -8453,8 +8930,12 @@ mono_marshal_get_native_wrapper (MonoMethod *method)
        mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_NATIVE);
 
        mb->method->save_lmf = 1;
-       
-       if (!piinfo->addr) {
+
+       /*
+        * In AOT mode and embedding scenarios, it is possible that the icall is not
+        * registered in the runtime doing the AOT compilation.
+        */
+       if (!piinfo->addr && !aot) {
                mono_mb_emit_exception (mb, exc_class, exc_arg);
                csig = signature_dup (method->klass->image, sig);
                csig->pinvoke = 0;
@@ -8480,9 +8961,16 @@ mono_marshal_get_native_wrapper (MonoMethod *method)
                for (i = 0; i < sig->param_count; i++)
                        mono_mb_emit_ldarg (mb, i + sig->hasthis);
 
-               g_assert (piinfo->addr);
-               mono_mb_emit_native_call (mb, csig, piinfo->addr);
-               emit_thread_interrupt_checkpoint (mb);
+               if (aot) {
+                       mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
+                       mono_mb_emit_op (mb, CEE_MONO_ICALL_ADDR, &piinfo->method);
+                       mono_mb_emit_calli (mb, csig);
+               } else {
+                       g_assert (piinfo->addr);
+                       mono_mb_emit_native_call (mb, csig, piinfo->addr);
+               }
+               if (check_exceptions)
+                       emit_thread_interrupt_checkpoint (mb);
                mono_mb_emit_byte (mb, CEE_RET);
 
                csig = signature_dup (method->klass->image, csig);
@@ -8494,11 +8982,13 @@ mono_marshal_get_native_wrapper (MonoMethod *method)
        }
 
        g_assert (pinvoke);
+       if (!aot)
+               g_assert (piinfo->addr);
 
        mspecs = g_new (MonoMarshalSpec*, sig->param_count + 1);
        mono_method_get_marshal_info (method, mspecs);
 
-       mono_marshal_emit_native_wrapper (mb->method->klass->image, mb, sig, piinfo, mspecs, piinfo->addr);
+       mono_marshal_emit_native_wrapper (mb->method->klass->image, mb, sig, piinfo, mspecs, piinfo->addr, aot, check_exceptions);
 
        csig = signature_dup (method->klass->image, sig);
        csig->pinvoke = 0;
@@ -8544,7 +9034,7 @@ mono_marshal_get_native_func_wrapper (MonoImage *image, MonoMethodSignature *sig
        mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
        mb->method->save_lmf = 1;
 
-       mono_marshal_emit_native_wrapper (image, mb, sig, piinfo, mspecs, func);
+       mono_marshal_emit_native_wrapper (image, mb, sig, piinfo, mspecs, func, FALSE, TRUE);
 
        csig = signature_dup (image, sig);
        csig->pinvoke = 0;
@@ -8582,17 +9072,6 @@ mono_marshal_emit_managed_wrapper (MonoMethodBuilder *mb, MonoMethodSignature *i
        mono_mb_emit_icon (mb, 0);
        mono_mb_emit_stloc (mb, 2);
 
-       /* fixme: howto handle this ? */
-       if (sig->hasthis) {
-               if (this) {
-                       /* FIXME: need a solution for the moving GC here */
-                       mono_mb_emit_ptr (mb, this);
-               } else {
-                       /* fixme: */
-                       g_assert_not_reached ();
-               }
-       } 
-
        /* we first do all conversions */
        tmp_locals = alloca (sizeof (int) * sig->param_count);
        for (i = 0; i < sig->param_count; i ++) {
@@ -8612,9 +9091,20 @@ mono_marshal_emit_managed_wrapper (MonoMethodBuilder *mb, MonoMethodSignature *i
                        tmp_locals [i] = 0;
                        break;
                }
-       }
-
-       emit_thread_interrupt_checkpoint (mb);
+       }
+
+       emit_thread_interrupt_checkpoint (mb);
+
+       /* fixme: howto handle this ? */
+       if (sig->hasthis) {
+               if (this) {
+                       /* FIXME: need a solution for the moving GC here */
+                       mono_mb_emit_ptr (mb, this);
+               } else {
+                       /* fixme: */
+                       g_assert_not_reached ();
+               }
+       } 
 
        for (i = 0; i < sig->param_count; i++) {
                MonoType *t = sig->params [i];
@@ -8642,6 +9132,7 @@ mono_marshal_emit_managed_wrapper (MonoMethodBuilder *mb, MonoMethodSignature *i
                case MONO_TYPE_BOOLEAN:
                case MONO_TYPE_I1:
                case MONO_TYPE_U1:
+               case MONO_TYPE_CHAR:
                case MONO_TYPE_I2:
                case MONO_TYPE_U2:
                case MONO_TYPE_I4:
@@ -8686,6 +9177,7 @@ mono_marshal_emit_managed_wrapper (MonoMethodBuilder *mb, MonoMethodSignature *i
                        case MONO_TYPE_CLASS:
                        case MONO_TYPE_VALUETYPE:
                        case MONO_TYPE_OBJECT:
+                       case MONO_TYPE_STRING:
                                emit_marshal (m, i, t, mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
                                break;
                        }
@@ -8717,6 +9209,42 @@ mono_marshal_emit_managed_wrapper (MonoMethodBuilder *mb, MonoMethodSignature *i
 }
 
 
+static void 
+mono_marshal_set_callconv_from_modopt (MonoMethod *method, MonoMethodSignature *csig)
+{
+       MonoMethodSignature *sig;
+       int i;
+
+#ifdef PLATFORM_WIN32
+       /* 
+        * Under windows, delegates passed to native code must use the STDCALL
+        * calling convention.
+        */
+       csig->call_convention = MONO_CALL_STDCALL;
+#endif
+
+       sig = mono_method_signature (method);
+
+       /* Change default calling convention if needed */
+       /* Why is this a modopt ? */
+       if (sig->ret && sig->ret->num_mods) {
+               for (i = 0; i < sig->ret->num_mods; ++i) {
+                       MonoClass *cmod_class = mono_class_get (method->klass->image, sig->ret->modifiers [i].token);
+                       g_assert (cmod_class);
+                       if ((cmod_class->image == mono_defaults.corlib) && !strcmp (cmod_class->name_space, "System.Runtime.CompilerServices")) {
+                               if (!strcmp (cmod_class->name, "CallConvCdecl"))
+                                       csig->call_convention = MONO_CALL_C;
+                               else if (!strcmp (cmod_class->name, "CallConvStdcall"))
+                                       csig->call_convention = MONO_CALL_STDCALL;
+                               else if (!strcmp (cmod_class->name, "CallConvFastcall"))
+                                       csig->call_convention = MONO_CALL_FASTCALL;
+                               else if (!strcmp (cmod_class->name, "CallConvThiscall"))
+                                       csig->call_convention = MONO_CALL_THISCALL;
+                       }
+               }
+       }
+}
+
 /*
  * generates IL code to call managed methods from unmanaged code 
  */
@@ -8741,7 +9269,7 @@ mono_marshal_get_managed_wrapper (MonoMethod *method, MonoClass *delegate_klass,
         * could be called with different delegates, thus different marshalling
         * options.
         */
-       cache = method->klass->image->managed_wrapper_cache;
+       cache = get_cache (&method->klass->image->managed_wrapper_cache, mono_aligned_addr_hash, NULL);
        if (!this && (res = mono_marshal_find_in_cache (cache, method)))
                return res;
 
@@ -8757,7 +9285,11 @@ mono_marshal_get_managed_wrapper (MonoMethod *method, MonoClass *delegate_klass,
 
 
        /* we copy the signature, so that we can modify it */
-       csig = signature_dup (method->klass->image, sig);
+       if (this)
+               /* Need to free this later */
+               csig = mono_metadata_signature_dup (sig);
+       else
+               csig = signature_dup (method->klass->image, sig);
        csig->hasthis = 0;
        csig->pinvoke = 1;
 
@@ -8768,32 +9300,7 @@ mono_marshal_get_managed_wrapper (MonoMethod *method, MonoClass *delegate_klass,
        m.csig = csig;
        m.image = method->klass->image;
 
-#ifdef PLATFORM_WIN32
-       /* 
-        * Under windows, delegates passed to native code must use the STDCALL
-        * calling convention.
-        */
-       csig->call_convention = MONO_CALL_STDCALL;
-#endif
-
-       /* Change default calling convention if needed */
-       /* Why is this a modopt ? */
-       if (invoke_sig->ret && invoke_sig->ret->num_mods) {
-               for (i = 0; i < invoke_sig->ret->num_mods; ++i) {
-                       MonoClass *cmod_class = mono_class_get (delegate_klass->image, invoke_sig->ret->modifiers [i].token);
-                       g_assert (cmod_class);
-                       if ((cmod_class->image == mono_defaults.corlib) && !strcmp (cmod_class->name_space, "System.Runtime.CompilerServices")) {
-                               if (!strcmp (cmod_class->name, "CallConvCdecl"))
-                                       csig->call_convention = MONO_CALL_C;
-                               else if (!strcmp (cmod_class->name, "CallConvStdcall"))
-                                       csig->call_convention = MONO_CALL_STDCALL;
-                               else if (!strcmp (cmod_class->name, "CallConvFastcall"))
-                                       csig->call_convention = MONO_CALL_FASTCALL;
-                               else if (!strcmp (cmod_class->name, "CallConvThiscall"))
-                                       csig->call_convention = MONO_CALL_THISCALL;
-                       }
-               }
-       }
+       mono_marshal_set_callconv_from_modopt (invoke, csig);
 
        /* Handle the UnmanagedFunctionPointerAttribute */
        if (!UnmanagedFunctionPointerAttribute)
@@ -8844,6 +9351,80 @@ mono_marshal_get_managed_wrapper (MonoMethod *method, MonoClass *delegate_klass,
        return res;
 }
 
+gpointer
+mono_marshal_get_vtfixup_ftnptr (MonoImage *image, guint32 token, guint16 type)
+{
+       MonoMethod *method;
+       MonoMethodSignature *sig;
+       MonoMethodBuilder *mb;
+       int i, param_count;
+
+       g_assert (token);
+
+       method = mono_get_method (image, token, NULL);
+       g_assert (method);
+
+       if (type & (VTFIXUP_TYPE_FROM_UNMANAGED | VTFIXUP_TYPE_FROM_UNMANAGED_RETAIN_APPDOMAIN)) {
+               MonoMethodSignature *csig;
+               MonoMarshalSpec **mspecs;
+               EmitMarshalContext m;
+
+               sig = mono_method_signature (method);
+               g_assert (!sig->hasthis);
+
+               mspecs = g_new0 (MonoMarshalSpec*, sig->param_count + 1);
+               mono_method_get_marshal_info (method, mspecs);
+
+               mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
+               csig = signature_dup (image, sig);
+               csig->hasthis = 0;
+               csig->pinvoke = 1;
+
+               m.mb = mb;
+               m.sig = sig;
+               m.piinfo = NULL;
+               m.retobj_var = 0;
+               m.csig = csig;
+               m.image = image;
+
+               mono_marshal_set_callconv_from_modopt (method, csig);
+
+               /* FIXME: Implement VTFIXUP_TYPE_FROM_UNMANAGED_RETAIN_APPDOMAIN. */
+
+               mono_marshal_emit_managed_wrapper (mb, sig, mspecs, &m, method, NULL);
+
+               mb->dynamic = 1;
+               method = mono_mb_create_method (mb, csig, sig->param_count + 16);
+               mono_mb_free (mb);
+
+               for (i = sig->param_count; i >= 0; i--)
+                       if (mspecs [i])
+                               mono_metadata_free_marshal_spec (mspecs [i]);
+               g_free (mspecs);
+
+               return mono_compile_method (method);
+       }
+
+       sig = mono_method_signature (method);
+       mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_MANAGED);
+
+       param_count = sig->param_count + sig->hasthis;
+       for (i = 0; i < param_count; i++)
+               mono_mb_emit_ldarg (mb, i);
+
+       if (type & VTFIXUP_TYPE_CALL_MOST_DERIVED)
+               mono_mb_emit_op (mb, CEE_CALLVIRT, method);
+       else
+               mono_mb_emit_op (mb, CEE_CALL, method);
+       mono_mb_emit_byte (mb, CEE_RET);
+
+       mb->dynamic = 1;
+       method = mono_mb_create_method (mb, sig, param_count);
+       mono_mb_free (mb);
+
+       return mono_compile_method (method);
+}
+
 static MonoReflectionType *
 type_from_handle (MonoType *handle)
 {
@@ -8875,7 +9456,7 @@ mono_marshal_get_isinst (MonoClass *klass)
        char *name;
        MonoMethodBuilder *mb;
 
-       cache = klass->image->isinst_cache;
+       cache = get_cache (&klass->image->isinst_cache, mono_aligned_addr_hash, NULL);
        if ((res = mono_marshal_find_in_cache (cache, klass)))
                return res;
 
@@ -8916,20 +9497,20 @@ mono_marshal_get_isinst (MonoClass *klass)
        
        /* fail */
        
-       mono_mb_patch_addr (mb, pos_failed, mb->pos - (pos_failed + 4));
+       mono_mb_patch_branch (mb, pos_failed);
        mono_mb_emit_byte (mb, CEE_LDNULL);
        pos_end2 = mono_mb_emit_branch (mb, CEE_BR);
        
        /* success */
        
-       mono_mb_patch_addr (mb, pos_was_ok, mb->pos - (pos_was_ok + 4));
+       mono_mb_patch_branch (mb, pos_was_ok);
        mono_mb_emit_byte (mb, CEE_POP);
        mono_mb_emit_ldarg (mb, 0);
        
        /* the end */
        
-       mono_mb_patch_addr (mb, pos_end, mb->pos - (pos_end + 4));
-       mono_mb_patch_addr (mb, pos_end2, mb->pos - (pos_end2 + 4));
+       mono_mb_patch_branch (mb, pos_end);
+       mono_mb_patch_branch (mb, pos_end2);
        mono_mb_emit_byte (mb, CEE_RET);
 
        res = mono_mb_create_and_cache (cache, klass, mb, isint_sig, isint_sig->param_count + 16);
@@ -8957,7 +9538,7 @@ mono_marshal_get_castclass (MonoClass *klass)
        char *name;
        MonoMethodBuilder *mb;
 
-       cache = klass->image->castclass_cache;
+       cache = get_cache (&klass->image->castclass_cache, mono_aligned_addr_hash, NULL);
        if ((res = mono_marshal_find_in_cache (cache, klass)))
                return res;
 
@@ -8997,8 +9578,8 @@ mono_marshal_get_castclass (MonoClass *klass)
        mono_mb_emit_exception (mb, "InvalidCastException", NULL);
        
        /* success */
-       mono_mb_patch_addr (mb, pos_was_ok, mb->pos - (pos_was_ok + 4));
-       mono_mb_patch_addr (mb, pos_was_ok2, mb->pos - (pos_was_ok2 + 4));
+       mono_mb_patch_branch (mb, pos_was_ok);
+       mono_mb_patch_branch (mb, pos_was_ok2);
        mono_mb_emit_ldarg (mb, 0);
        
        /* the end */
@@ -9022,7 +9603,7 @@ mono_marshal_get_proxy_cancast (MonoClass *klass)
        MonoMethodDesc *desc;
        MonoMethodBuilder *mb;
 
-       cache = klass->image->proxy_isinst_cache;
+       cache = get_cache (&klass->image->proxy_isinst_cache, mono_aligned_addr_hash, NULL);
        if ((res = mono_marshal_find_in_cache (cache, klass)))
                return res;
 
@@ -9072,12 +9653,12 @@ mono_marshal_get_proxy_cancast (MonoClass *klass)
        
        /* fail */
        
-       mono_mb_patch_addr (mb, pos_failed, mb->pos - (pos_failed + 4));
+       mono_mb_patch_branch (mb, pos_failed);
        mono_mb_emit_byte (mb, CEE_LDNULL);
        
        /* the end */
        
-       mono_mb_patch_addr (mb, pos_end, mb->pos - (pos_end + 4));
+       mono_mb_patch_branch (mb, pos_end);
        mono_mb_emit_byte (mb, CEE_RET);
 
        res = mono_mb_create_and_cache (cache, klass, mb, isint_sig, isint_sig->param_count + 16);
@@ -9153,7 +9734,7 @@ mono_marshal_get_struct_to_ptr (MonoClass *klass)
 
        mono_mb_emit_byte (mb, CEE_RET);
 
-       res = mono_mb_create_method (mb, mono_method_signature (stoptr), 0);
+       res = mono_mb_create_method (mb, mono_signature_no_pinvoke (stoptr), 0);
        mono_mb_free (mb);
 
        klass->marshal_info->str_to_ptr = res;
@@ -9180,11 +9761,18 @@ mono_marshal_get_ptr_to_struct (MonoClass *klass)
        if (klass->marshal_info->ptr_to_str)
                return klass->marshal_info->ptr_to_str;
 
-       if (!ptostr)
+       if (!ptostr) {
+               MonoMethodSignature *sig;
+
                /* Create the signature corresponding to
                          static void PtrToStructure (IntPtr ptr, object structure);
                   defined in class/corlib/System.Runtime.InteropServices/Marshal.cs */
-               ptostr = mono_create_icall_signature ("void ptr object");
+               sig = mono_create_icall_signature ("void ptr object");
+               sig = signature_dup (mono_defaults.corlib, sig);
+               sig->pinvoke = 0;
+               mono_memory_barrier ();
+               ptostr = sig;
+       }
 
        mb = mono_mb_new (klass, "PtrToStructure", MONO_WRAPPER_UNKNOWN);
 
@@ -9230,7 +9818,7 @@ mono_marshal_get_ptr_to_struct (MonoClass *klass)
 MonoMethod *
 mono_marshal_get_synchronized_wrapper (MonoMethod *method)
 {
-       static MonoMethod *enter_method, *exit_method;
+       static MonoMethod *enter_method, *exit_method, *gettypefromhandle_method;
        MonoMethodSignature *sig;
        MonoExceptionClause *clause;
        MonoMethodHeader *header;
@@ -9244,7 +9832,7 @@ mono_marshal_get_synchronized_wrapper (MonoMethod *method)
        if (method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED)
                return method;
 
-       cache = method->klass->image->synchronized_cache;
+       cache = get_cache (&method->klass->image->synchronized_cache, mono_aligned_addr_hash, NULL);
        if ((res = mono_marshal_find_in_cache (cache, method)))
                return res;
 
@@ -9257,14 +9845,34 @@ mono_marshal_get_synchronized_wrapper (MonoMethod *method)
        if (!MONO_TYPE_IS_VOID (sig->ret))
                ret_local = mono_mb_add_local (mb, sig->ret);
 
+       if (method->klass->valuetype && !(method->flags & MONO_METHOD_ATTR_STATIC)) {
+               mono_class_set_failure (method->klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+               /* This will throw the type load exception when the wrapper is compiled */
+               mono_mb_emit_byte (mb, CEE_LDNULL);
+               mono_mb_emit_op (mb, CEE_ISINST, method->klass);
+               mono_mb_emit_byte (mb, CEE_POP);
+
+               if (!MONO_TYPE_IS_VOID (sig->ret))
+                       mono_mb_emit_ldloc (mb, ret_local);
+               mono_mb_emit_byte (mb, CEE_RET);
+
+               res = mono_mb_create_and_cache (cache, method,
+                                                                               mb, sig, sig->param_count + 16);
+               mono_mb_free (mb);
+
+               return res;
+       }
+
        /* this */
        this_local = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
 
        mono_loader_lock ();
-       clause = mono_mempool_alloc0 (method->klass->image->mempool, sizeof (MonoExceptionClause));
+       clause = mono_image_alloc0 (method->klass->image, sizeof (MonoExceptionClause));
        mono_loader_unlock ();
        clause->flags = MONO_EXCEPTION_CLAUSE_FINALLY;
 
+       mono_loader_lock ();
+
        if (!enter_method) {
                MonoMethodDesc *desc;
 
@@ -9272,21 +9880,29 @@ mono_marshal_get_synchronized_wrapper (MonoMethod *method)
                enter_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
                g_assert (enter_method);
                mono_method_desc_free (desc);
+
                desc = mono_method_desc_new ("Monitor:Exit", FALSE);
                exit_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
                g_assert (exit_method);
                mono_method_desc_free (desc);
+
+               desc = mono_method_desc_new ("Type:GetTypeFromHandle", FALSE);
+               gettypefromhandle_method = mono_method_desc_search_in_class (desc, mono_defaults.monotype_class->parent);
+               g_assert (gettypefromhandle_method);
+               mono_method_desc_free (desc);
        }
 
+       mono_loader_unlock ();
+
        /* Push this or the type object */
        if (method->flags & METHOD_ATTRIBUTE_STATIC) {
-               /*
-                * GetTypeFromHandle isn't called as a managed method because it has
-                * a funky calling sequence, e.g. ldtoken+GetTypeFromHandle gets
-                * transformed into something else by the JIT.
-                */
-               mono_mb_emit_ptr (mb, &method->klass->byval_arg);
-               mono_mb_emit_icall (mb, type_from_handle);
+               /* We have special handling for this in the JIT */
+               int index = mono_mb_add_data (mb, method->klass);
+               mono_mb_add_data (mb, mono_defaults.typehandle_class);
+               mono_mb_emit_byte (mb, CEE_LDTOKEN);
+               mono_mb_emit_i4 (mb, index);
+
+               mono_mb_emit_managed_call (mb, gettypefromhandle_method, NULL);
        }
        else
                mono_mb_emit_ldarg (mb, 0);
@@ -9296,34 +9912,30 @@ mono_marshal_get_synchronized_wrapper (MonoMethod *method)
        mono_mb_emit_ldloc (mb, this_local);
        mono_mb_emit_managed_call (mb, enter_method, NULL);
 
-       clause->try_offset = mb->pos;
+       clause->try_offset = mono_mb_get_label (mb);
 
        /* Call the method */
        if (sig->hasthis)
                mono_mb_emit_ldarg (mb, 0);
        for (i = 0; i < sig->param_count; i++)
                mono_mb_emit_ldarg (mb, i + (sig->hasthis == TRUE));
-       
-       /* this is needed to avoid recursion */
-       mono_mb_emit_byte (mb, CEE_PREFIX1);
-       mono_mb_emit_op (mb, CEE_LDFTN, method);
-       mono_mb_emit_calli (mb, mono_method_signature (method));
+
+       mono_mb_emit_managed_call (mb, method, NULL);
 
        if (!MONO_TYPE_IS_VOID (sig->ret))
                mono_mb_emit_stloc (mb, ret_local);
 
        pos = mono_mb_emit_branch (mb, CEE_LEAVE);
 
-       clause->try_len = mb->pos - clause->try_offset;
-       clause->handler_offset = mb->pos;
+       clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
+       clause->handler_offset = mono_mb_get_label (mb);
 
        /* Call Monitor::Exit() */
        mono_mb_emit_ldloc (mb, this_local);
-/*     mono_mb_emit_native_call (mb, exit_sig, mono_monitor_exit); */
        mono_mb_emit_managed_call (mb, exit_method, NULL);
        mono_mb_emit_byte (mb, CEE_ENDFINALLY);
 
-       clause->handler_len = mb->pos - clause->handler_offset;
+       clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
 
        mono_mb_patch_branch (mb, pos);
        if (!MONO_TYPE_IS_VOID (sig->ret))
@@ -9354,7 +9966,7 @@ mono_marshal_get_unbox_wrapper (MonoMethod *method)
        MonoMethod *res;
        GHashTable *cache;
 
-       cache = method->klass->image->unbox_wrapper_cache;
+       cache = get_cache (&method->klass->image->unbox_wrapper_cache, mono_aligned_addr_hash, NULL);
        if ((res = mono_marshal_find_in_cache (cache, method)))
                return res;
 
@@ -9493,7 +10105,7 @@ mono_marshal_get_stelemref ()
        
        b3 = mono_mb_emit_branch (mb, CEE_BNE_UN);
        
-       copy_pos = mb->pos;
+       copy_pos = mono_mb_get_label (mb);
        /* do_store */
        mono_mb_patch_branch (mb, b1);
        mono_mb_emit_ldloc (mb, array_slot_addr);
@@ -9770,6 +10382,19 @@ mono_marshal_string_to_utf16 (MonoString *s)
        return s ? mono_string_chars (s) : NULL;
 }
 
+static void *
+mono_marshal_string_to_utf16_copy (MonoString *s)
+{
+       if (s == NULL) {
+               return NULL;
+       } else {
+               gunichar2 *res = mono_marshal_alloc ((mono_string_length (s) * 2) + 2);
+               memcpy (res, mono_string_chars (s), mono_string_length (s) * 2);
+               res [mono_string_length (s)] = 0;
+               return res;
+       }
+}
+
 /**
  * mono_marshal_set_last_error:
  *
@@ -10079,28 +10704,52 @@ ves_icall_System_Runtime_InteropServices_Marshal_ReleaseInternal (gpointer pUnk)
        return (*(MonoIUnknown**)pUnk)->Release(pUnk);
 }
 
-void*
+#ifndef DISABLE_COM
+
+#define MONO_S_OK 0x00000000L
+#define MONO_E_NOINTERFACE 0x80004002L
+#define MONO_E_NOTIMPL 0x80004001L
+
+static gboolean cominterop_can_support_dispatch (MonoClass* klass)
+{
+       if (!(klass->flags & TYPE_ATTRIBUTE_PUBLIC) )
+               return FALSE;
+
+       if (!cominterop_com_visible (klass))
+               return FALSE;
+
+       return TRUE;
+}
+
+static void*
 cominterop_get_idispatch_for_object (MonoObject* object)
 {
        if (!object)
                return NULL;
 
        if (cominterop_object_is_rcw (object)) {
-               /* FIXME: Implement this case */
-               g_assert_not_reached ();
-               return NULL;
+               return cominterop_get_interface (((MonoComInteropProxy*)((MonoTransparentProxy*)object)->rp)->com_object, 
+                       mono_defaults.idispatch_class, TRUE);
        }
        else {
+               MonoClass* klass = mono_object_class (object);
+               if (!cominterop_can_support_dispatch (klass) )
+                       cominterop_raise_hr_exception (MONO_E_NOINTERFACE);
                return cominterop_get_ccw (object, mono_defaults.idispatch_class);
        }
 }
 
+#endif
+
 void*
 ves_icall_System_Runtime_InteropServices_Marshal_GetIUnknownForObjectInternal (MonoObject* object)
 {
+#ifndef DISABLE_COM
        if (!object)
                return NULL;
 
+       mono_init_com_types ();
+
        if (cominterop_object_is_rcw (object)) {
                MonoClass *klass = NULL;
                MonoRealProxy* real_proxy = NULL;
@@ -10134,11 +10783,15 @@ ves_icall_System_Runtime_InteropServices_Marshal_GetIUnknownForObjectInternal (M
        else {
                return cominterop_get_ccw (object, mono_defaults.iunknown_class);
        }
+#else
+       g_assert_not_reached ();
+#endif
 }
 
 MonoObject*
 ves_icall_System_Runtime_InteropServices_Marshal_GetObjectForCCW (void* pUnk)
 {
+#ifndef DISABLE_COM
        MonoObject* object = NULL;
 
        if (!pUnk)
@@ -10148,17 +10801,27 @@ ves_icall_System_Runtime_InteropServices_Marshal_GetObjectForCCW (void* pUnk)
        object = cominterop_get_ccw_object ((MonoCCWInterface*)pUnk, TRUE);
 
        return object;
+#else
+       g_assert_not_reached ();
+#endif
 }
 
 void*
 ves_icall_System_Runtime_InteropServices_Marshal_GetIDispatchForObjectInternal (MonoObject* object)
 {
+#ifndef DISABLE_COM
+       mono_init_com_types ();
+
        return cominterop_get_idispatch_for_object (object);
+#else
+       g_assert_not_reached ();
+#endif
 }
 
 void*
 ves_icall_System_Runtime_InteropServices_Marshal_GetCCW (MonoObject* object, MonoReflectionType* type)
 {
+#ifndef DISABLE_COM
        MonoClass* klass = NULL;
        void* itf = NULL;
        g_assert (type);
@@ -10168,18 +10831,26 @@ ves_icall_System_Runtime_InteropServices_Marshal_GetCCW (MonoObject* object, Mon
        itf = cominterop_get_ccw (object, klass);
        g_assert (itf);
        return itf;
+#else
+       g_assert_not_reached ();
+#endif
 }
 
 
 MonoBoolean
 ves_icall_System_Runtime_InteropServices_Marshal_IsComObject (MonoObject* object)
 {
+#ifndef DISABLE_COM
        return (MonoBoolean)cominterop_object_is_rcw (object);
+#else
+       g_assert_not_reached ();
+#endif
 }
 
 gint32
 ves_icall_System_Runtime_InteropServices_Marshal_ReleaseComObjectInternal (MonoObject* object)
 {
+#ifndef DISABLE_COM
        MonoComInteropProxy* proxy = NULL;
        gint32 ref_count = 0;
 
@@ -10196,6 +10867,9 @@ ves_icall_System_Runtime_InteropServices_Marshal_ReleaseComObjectInternal (MonoO
                ves_icall_System_ComObject_ReleaseInterfaces (proxy->com_object);
 
        return ref_count;
+#else
+       g_assert_not_reached ();
+#endif
 }
 
 guint32
@@ -10203,7 +10877,11 @@ ves_icall_System_Runtime_InteropServices_Marshal_GetComSlotForMethodInfoInternal
 {
        MONO_ARCH_SAVE_REGS;
 
+#ifndef DISABLE_COM
        return cominterop_get_com_slot_for_method (m->method);
+#else
+       g_assert_not_reached ();
+#endif
 }
 
 guint32 
@@ -10345,7 +11023,7 @@ ves_icall_System_Runtime_InteropServices_Marshal_OffsetOf (MonoReflectionType *t
                while ((field = mono_class_get_fields (klass, &iter))) {
                        if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
                                continue;
-                       if (!strcmp (fname, field->name)) {
+                       if (!strcmp (fname, mono_field_get_name (field))) {
                                match_index = i;
                                break;
                        }
@@ -10379,9 +11057,22 @@ ves_icall_System_Runtime_InteropServices_Marshal_OffsetOf (MonoReflectionType *t
 gpointer
 ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalAnsi (MonoString *string)
 {
-       MONO_ARCH_SAVE_REGS;
+#ifdef PLATFORM_WIN32
+       char* tres, *ret;
+       size_t len;
+       tres = mono_string_to_utf8 (string);
+       if (!tres)
+               return tres;
+
+       len = strlen (tres) + 1;
+       ret = ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (len);
+       memcpy (ret, tres, len);
+       g_free (tres);
+       return ret;
 
+#else
        return mono_string_to_utf8 (string);
+#endif
 }
 
 gpointer
@@ -10392,7 +11083,12 @@ ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalUni (MonoString
        if (string == NULL)
                return NULL;
        else {
-               gunichar2 *res = g_malloc ((mono_string_length (string) + 1) * 2);
+#ifdef PLATFORM_WIN32
+               gunichar2 *res = ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal 
+                       ((mono_string_length (string) + 1) * 2);
+#else
+               gunichar2 *res = g_malloc ((mono_string_length (string) + 1) * 2);              
+#endif
                memcpy (res, mono_string_chars (string), mono_string_length (string) * 2);
                res [mono_string_length (string)] = 0;
                return res;
@@ -10431,8 +11127,13 @@ mono_struct_delete_old (MonoClass *klass, char *ptr)
                case MONO_MARSHAL_CONV_STR_LPWSTR:
                        /* We assume this field points inside a MonoString */
                        break;
-               case MONO_MARSHAL_CONV_STR_LPSTR:
                case MONO_MARSHAL_CONV_STR_LPTSTR:
+#ifdef PLATFORM_WIN32
+                       /* We assume this field points inside a MonoString 
+                        * on Win32 */
+                       break;
+#endif
+               case MONO_MARSHAL_CONV_STR_LPSTR:
                case MONO_MARSHAL_CONV_STR_BSTR:
                case MONO_MARSHAL_CONV_STR_ANSIBSTR:
                case MONO_MARSHAL_CONV_STR_TBSTR:
@@ -10493,7 +11194,7 @@ ves_icall_System_Runtime_InteropServices_Marshal_ReAllocHGlobal (gpointer ptr, i
        }
 
 #ifdef PLATFORM_WIN32
-       res = GlobalReAlloc (ptr, (gulong)size, 0);
+       res = GlobalReAlloc (ptr, (gulong)size, GMEM_MOVEABLE);
 #else
        res = g_try_realloc (ptr, (gulong)size);
 #endif
@@ -10587,7 +11288,7 @@ ves_icall_System_ComObject_CreateRCW (MonoReflectionType *type)
 }
 
 static gboolean    
-cominterop_finalizer (gpointer key, gpointer value, gpointer user_data)
+cominterop_rcw_interface_finalizer (gpointer key, gpointer value, gpointer user_data)
 {
        ves_icall_System_Runtime_InteropServices_Marshal_ReleaseInternal (value);
        return TRUE;
@@ -10606,56 +11307,72 @@ ves_icall_System_ComObject_ReleaseInterfaces (MonoComObject* obj)
                        g_hash_table_remove (rcw_hash, obj->iunknown);
                }
 
-               g_hash_table_foreach_remove (obj->itf_hash, cominterop_finalizer, NULL);
+               g_hash_table_foreach_remove (obj->itf_hash, cominterop_rcw_interface_finalizer, NULL);
+               g_hash_table_destroy (obj->itf_hash);
                ves_icall_System_Runtime_InteropServices_Marshal_ReleaseInternal (obj->iunknown);
                obj->itf_hash = obj->iunknown = NULL;
                mono_cominterop_unlock ();
        }
 }
 
-gpointer
-ves_icall_System_ComObject_FindInterface (MonoComObject* obj, MonoReflectionType* type)
-{
-       MonoClass* klass;
-       gpointer itf = NULL;
-       g_assert(obj);
-       g_assert(type);
-       if (!obj->itf_hash)
-               return NULL;
+#ifndef DISABLE_COM
 
-       klass = mono_object_class (obj);
-       klass = mono_class_from_mono_type (type->type);
+static gboolean    
+cominterop_rcw_finalizer (gpointer key, gpointer value, gpointer user_data)
+{
+       guint32 gchandle = 0;
 
-       mono_cominterop_lock ();
-       itf = g_hash_table_lookup (obj->itf_hash, GUINT_TO_POINTER ((guint)klass->interface_id));
-       mono_cominterop_unlock ();
+       gchandle = GPOINTER_TO_UINT (value);
+       if (gchandle) {
+               MonoComInteropProxy* proxy = (MonoComInteropProxy*)mono_gchandle_get_target (gchandle);
+               
+               if (proxy) {
+                       if (proxy->com_object->itf_hash) {
+                               g_hash_table_foreach_remove (proxy->com_object->itf_hash, cominterop_rcw_interface_finalizer, NULL);
+                               g_hash_table_destroy (proxy->com_object->itf_hash);
+                       }
+                       if (proxy->com_object->iunknown)
+                               ves_icall_System_Runtime_InteropServices_Marshal_ReleaseInternal (proxy->com_object->iunknown);
+                       proxy->com_object->itf_hash = proxy->com_object->iunknown = NULL;
+               }
+               
+               mono_gchandle_free (gchandle);
+       }
 
-       return itf;
+       return TRUE;
 }
 
 void
-ves_icall_System_ComObject_AddInterface (MonoComObject* obj, MonoReflectionType* type, gpointer pItf)
+cominterop_release_all_rcws ()
 {
-       MonoClass* klass;
-       g_assert(obj);
-       g_assert(type);
-       if (!obj->itf_hash) {
-               mono_cominterop_lock ();
-               obj->itf_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
-               mono_cominterop_unlock ();
-       }
-
-       klass = mono_object_class (obj);
-       klass = mono_class_from_mono_type (type->type);
+       if (!rcw_hash)
+               return;
 
        mono_cominterop_lock ();
-       g_hash_table_insert (obj->itf_hash, GUINT_TO_POINTER ((guint)klass->interface_id), pItf);
+
+       g_hash_table_foreach_remove (rcw_hash, cominterop_rcw_finalizer, NULL);
+       g_hash_table_destroy (rcw_hash);
+       rcw_hash = NULL;
+
        mono_cominterop_unlock ();
 }
 
+#endif
+
+gpointer
+ves_icall_System_ComObject_GetInterfaceInternal (MonoComObject* obj, MonoReflectionType* type, MonoBoolean throw_exception)
+{
+#ifndef DISABLE_COM
+       return cominterop_get_interface (obj, mono_type_get_class (type->type), (gboolean)throw_exception);
+#else
+       g_assert_not_reached ();
+#endif
+}
+
 void
 ves_icall_Mono_Interop_ComInteropProxy_AddProxy (gpointer pUnk, MonoComInteropProxy* proxy)
 {
+#ifndef DISABLE_COM
        guint32 gchandle = 0;
        if (!rcw_hash) {
                mono_cominterop_lock ();
@@ -10668,11 +11385,15 @@ ves_icall_Mono_Interop_ComInteropProxy_AddProxy (gpointer pUnk, MonoComInteropPr
        mono_cominterop_lock ();
        g_hash_table_insert (rcw_hash, pUnk, GUINT_TO_POINTER (gchandle));
        mono_cominterop_unlock ();
+#else
+       g_assert_not_reached ();
+#endif
 }
 
 MonoComInteropProxy*
 ves_icall_Mono_Interop_ComInteropProxy_FindProxy (gpointer pUnk)
 {
+#ifndef DISABLE_COM
        MonoComInteropProxy* proxy = NULL;
        guint32 gchandle = 0;
 
@@ -10689,6 +11410,9 @@ ves_icall_Mono_Interop_ComInteropProxy_FindProxy (gpointer pUnk)
                }
        }
        return proxy;
+#else
+       g_assert_not_reached ();
+#endif
 }
 
 /**
@@ -10761,7 +11485,7 @@ mono_marshal_load_type_info (MonoClass* klass)
        layout = klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
 
        /* The mempool is protected by the loader lock */
-       info = mono_mempool_alloc0 (klass->image->mempool, sizeof (MonoMarshalType) + sizeof (MonoMarshalField) * count);
+       info = mono_image_alloc0 (klass->image, sizeof (MonoMarshalType) + sizeof (MonoMarshalField) * count);
        info->num_fields = count;
        
        /* Try to find a size for this type in metadata */
@@ -10774,7 +11498,7 @@ mono_marshal_load_type_info (MonoClass* klass)
                native_size += parent_size;
                info->native_size = parent_size;
        }
-       
+
        iter = NULL;
        j = 0;
        while ((field = mono_class_get_fields (klass, &iter))) {
@@ -10787,13 +11511,13 @@ mono_marshal_load_type_info (MonoClass* klass)
                if (mono_field_is_deleted (field))
                        continue;
                if (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL)
-                       mono_metadata_field_info (klass->image, mono_metadata_token_index (mono_class_get_field_token (field)) - 1, 
+                       mono_metadata_field_info_with_mempool (klass->image->mempool, klass->image, mono_metadata_token_index (mono_class_get_field_token (field)) - 1, 
                                                  NULL, NULL, &info->fields [j].mspec);
 
                info->fields [j].field = field;
 
                if ((mono_class_num_fields (klass) == 1) && (klass->instance_size == sizeof (MonoObject)) &&
-                       (strcmp (field->name, "$PRIVATE$") == 0)) {
+                       (strcmp (mono_field_get_name (field), "$PRIVATE$") == 0)) {
                        /* This field is a hack inserted by MCS to empty structures */
                        continue;
                }
@@ -10844,6 +11568,9 @@ mono_marshal_load_type_info (MonoClass* klass)
        loads_list = g_slist_remove (loads_list, klass);
        TlsSetValue (load_type_info_tls_id, loads_list);
 
+       /*We do double-checking locking on marshal_info */
+       mono_memory_barrier ();
+
        klass->marshal_info = info;
 
        mono_loader_unlock ();
@@ -10862,10 +11589,13 @@ gint32
 mono_class_native_size (MonoClass *klass, guint32 *align)
 {      
        if (!klass->marshal_info) {
-               if (mono_marshal_is_loading_type_info (klass))
+               if (mono_marshal_is_loading_type_info (klass)) {
+                       if (align)
+                               *align = 0;
                        return 0;
-               else
+               } else {
                        mono_marshal_load_type_info (klass);
+               }
        }
 
        if (align)
@@ -10874,6 +11604,11 @@ mono_class_native_size (MonoClass *klass, guint32 *align)
        return klass->marshal_info->native_size;
 }
 
+/* __alignof__ returns the preferred alignment of values not the actual alignment used by
+   the compiler so is wrong e.g. for Linux where doubles are aligned on a 4 byte boundary
+   but __alignof__ returns 8 - using G_STRUCT_OFFSET works better */
+#define ALIGNMENT(type) G_STRUCT_OFFSET(struct { char c; type x; }, x)
+
 /*
  * mono_type_native_stack_size:
  * @t: the type to return the size it uses on the stack
@@ -10891,9 +11626,9 @@ mono_type_native_stack_size (MonoType *t, guint32 *align)
        if (!align)
                align = &tmp;
 
-       if (t->byref) {
-               *align = 4;
-               return 4;
+       if (t->byref) {
+               *align = sizeof (gpointer);
+               return sizeof (gpointer);
        }
 
        switch (t->type){
@@ -10905,6 +11640,8 @@ mono_type_native_stack_size (MonoType *t, guint32 *align)
        case MONO_TYPE_U2:
        case MONO_TYPE_I4:
        case MONO_TYPE_U4:
+               *align = 4;
+               return 4;
        case MONO_TYPE_I:
        case MONO_TYPE_U:
        case MONO_TYPE_STRING:
@@ -10914,24 +11651,33 @@ mono_type_native_stack_size (MonoType *t, guint32 *align)
        case MONO_TYPE_PTR:
        case MONO_TYPE_FNPTR:
        case MONO_TYPE_ARRAY:
-       case MONO_TYPE_TYPEDBYREF:
-               *align = 4;
-               return 4;
+               *align = sizeof (gpointer);
+               return sizeof (gpointer);
        case MONO_TYPE_R4:
                *align = 4;
                return 4;
+       case MONO_TYPE_R8:
+               *align = ALIGNMENT (gdouble);
+               return 8;
        case MONO_TYPE_I8:
        case MONO_TYPE_U8:
-       case MONO_TYPE_R8:
-               *align = 4;
+               *align = ALIGNMENT (glong);
                return 8;
+       case MONO_TYPE_GENERICINST:
+               if (!mono_type_generic_inst_is_valuetype (t)) {
+                       *align = sizeof (gpointer);
+                       return sizeof (gpointer);
+               } 
+               /* Fall through */
+       case MONO_TYPE_TYPEDBYREF:
        case MONO_TYPE_VALUETYPE: {
                guint32 size;
+               MonoClass *klass = mono_class_from_mono_type (t);
 
-               if (t->data.klass->enumtype)
-                       return mono_type_native_stack_size (t->data.klass->enum_basetype, align);
+               if (klass->enumtype)
+                       return mono_type_native_stack_size (klass->enum_basetype, align);
                else {
-                       size = mono_class_native_size (t->data.klass, align);
+                       size = mono_class_native_size (klass, align);
                        *align = *align + 3;
                        *align &= ~3;
                        
@@ -10947,11 +11693,6 @@ mono_type_native_stack_size (MonoType *t, guint32 *align)
        return 0;
 }
 
-/* __alignof__ returns the preferred alignment of values not the actual alignment used by
-   the compiler so is wrong e.g. for Linux where doubles are aligned on a 4 byte boundary
-   but __alignof__ returns 8 - using G_STRUCT_OFFSET works better */
-#define ALIGNMENT(type) G_STRUCT_OFFSET(struct { char c; type x; }, x)
-
 gint32
 mono_marshal_type_size (MonoType *type, MonoMarshalSpec *mspec, guint32 *align,
                        gboolean as_field, gboolean unicode)
@@ -11033,7 +11774,8 @@ mono_marshal_type_size (MonoType *type, MonoMarshalSpec *mspec, guint32 *align,
                return mspec->data.array_data.num_elem * esize;
        }
        case MONO_NATIVE_CUSTOM:
-               g_assert_not_reached ();
+               *align = sizeof (gpointer);
+               return sizeof (gpointer);
                break;
        case MONO_NATIVE_CURRENCY:
        case MONO_NATIVE_VBBYREFSTR:
@@ -11181,7 +11923,7 @@ mono_marshal_get_generic_array_helper (MonoClass *class, MonoClass *iface, gchar
        MonoMethod *res;
        int i;
 
-       mb = mono_mb_new (class, name, MONO_WRAPPER_MANAGED_TO_MANAGED);
+       mb = mono_mb_new_no_dup_name (class, name, MONO_WRAPPER_MANAGED_TO_MANAGED);
        mb->method->slot = -1;
 
        mb->method->flags = METHOD_ATTRIBUTE_PRIVATE | METHOD_ATTRIBUTE_VIRTUAL |
@@ -11199,13 +11941,57 @@ mono_marshal_get_generic_array_helper (MonoClass *class, MonoClass *iface, gchar
 
        res = mono_mb_create_method (mb, csig, csig->param_count + 16);
 
+       /* We can corlib internal methods */
+       res->skip_visibility = TRUE;
+
        mono_mb_free (mb);
 
        return res;
 }
 
+/*
+ * The mono_win32_compat_* functions are implementations of inline
+ * Windows kernel32 APIs, which are DllImport-able under MS.NET,
+ * although not exported by kernel32.
+ *
+ * We map the appropiate kernel32 entries to these functions using
+ * dllmaps declared in the global etc/mono/config.
+ */
+
+void
+mono_win32_compat_CopyMemory (gpointer dest, gconstpointer source, gsize length)
+{
+       if (!dest || !source)
+               return;
+
+       memcpy (dest, source, length);
+}
+
+void
+mono_win32_compat_FillMemory (gpointer dest, gsize length, guchar fill)
+{
+       memset (dest, fill, length);
+}
+
+void
+mono_win32_compat_MoveMemory (gpointer dest, gconstpointer source, gsize length)
+{
+       if (!dest || !source)
+               return;
+
+       memmove (dest, source, length);
+}
+
+void
+mono_win32_compat_ZeroMemory (gpointer dest, gsize length)
+{
+       memset (dest, 0, length);
+}
+
 /* Put COM Interop related stuff here */
 
+#ifndef DISABLE_COM
+
 /**
  * cominterop_get_ccw_object:
  * @ccw_entry: a pointer to the CCWEntry
@@ -11244,7 +12030,13 @@ cominterop_setup_marshal_context (EmitMarshalContext *m, MonoMethod *method)
        /* FIXME: which to use? */
        csig = signature_dup (method->klass->image, sig);
        /* csig = mono_metadata_signature_dup (sig); */
+       
+       /* STDCALL on windows, CDECL everywhere else to work with XPCOM and MainWin COM */
+#ifdef PLATFORM_WIN32
        csig->call_convention = MONO_CALL_STDCALL;
+#else
+       csig->call_convention = MONO_CALL_C;
+#endif
        csig->hasthis = 0;
        csig->pinvoke = 1;
 
@@ -11278,6 +12070,7 @@ cominterop_get_ccw (MonoObject* object, MonoClass* itf)
        int start_slot = 3;
        int method_count = 0;
        GList *ccw_list, *ccw_list_item;
+       MonoCustomAttrInfo *cinfo = NULL;
 
        if (!object)
                return NULL;
@@ -11316,6 +12109,9 @@ cominterop_get_ccw (MonoObject* object, MonoClass* itf)
 
        if (!ccw) {
                ccw = g_new0 (MonoCCW, 1);
+#ifdef PLATFORM_WIN32
+               ccw->free_marshaler = 0;
+#endif
                ccw->vtable_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
                ccw->ref_count = 0;
                /* just alloc a weak handle until we are addref'd*/
@@ -11326,12 +12122,25 @@ cominterop_get_ccw (MonoObject* object, MonoClass* itf)
                        ccw_list->data = ccw;
                }
                else
-                       g_list_append (ccw_list, ccw);
+                       ccw_list = g_list_append (ccw_list, ccw);
                g_hash_table_insert (ccw_hash, GINT_TO_POINTER (mono_object_hash (object)), ccw_list);
                /* register for finalization to clean up ccw */
                mono_object_register_finalizer (object);
        }
 
+       cinfo = mono_custom_attrs_from_class (itf);
+       if (cinfo) {
+               static MonoClass* coclass_attribute = NULL;
+               if (!coclass_attribute)
+                       coclass_attribute = mono_class_from_name (mono_defaults.corlib, "System.Runtime.InteropServices", "CoClassAttribute");
+               if (mono_custom_attrs_has_attr (cinfo, coclass_attribute)) {
+                       g_assert(itf->interface_count && itf->interfaces[0]);
+                       itf = itf->interfaces[0];
+               }
+               if (!cinfo->cached)
+                       mono_custom_attrs_free (cinfo);
+       }
+
        iface = itf;
        if (iface == mono_defaults.iunknown_class) {
                start_slot = 3;
@@ -11340,16 +12149,9 @@ cominterop_get_ccw (MonoObject* object, MonoClass* itf)
                start_slot = 7;
        }
        else {
-               while (iface) {
-                       method_count += iface->method.count;
-                       if (iface->interface_count) {
-                               iface = iface->interfaces [0];
-                       }
-                       else {
-                               start_slot = cominterop_get_com_slot_begin (iface);
-                               iface = NULL;
-                       }
-               }
+               method_count += iface->method.count;
+               start_slot = cominterop_get_com_slot_begin (iface);
+               iface = NULL;
        }
 
        ccw_entry = g_hash_table_lookup (ccw->vtable_hash, itf);
@@ -11357,69 +12159,96 @@ cominterop_get_ccw (MonoObject* object, MonoClass* itf)
        if (!ccw_entry) {
                int vtable_index = method_count-1+start_slot;
                mono_loader_lock ();
-               vtable = mono_mempool_alloc0 (klass->image->mempool, sizeof (gpointer)*(method_count+start_slot));
+               vtable = mono_image_alloc0 (klass->image, sizeof (gpointer)*(method_count+start_slot));
                mono_loader_unlock ();
                memcpy (vtable, iunknown, sizeof (iunknown));
                if (start_slot == 7)
                        memcpy (vtable+3, idispatch, sizeof (idispatch));
 
                iface = itf;
-               while (iface) {
-                       for (i = iface->method.count-1; i >= 0;i--) {
-                               int param_index = 0;
-                               MonoMethodBuilder *mb;
-                               MonoMarshalSpec ** mspecs;
-                               MonoMethod *wrapper_method, *adjust_method;
-                               MonoMethod *method = iface->methods [i];
-                               MonoMethodSignature* sig_adjusted;
-                               MonoMethodSignature* sig = mono_method_signature (method);
-
-
-                               mb = mono_mb_new (iface, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
-                               adjust_method = cominterop_get_managed_wrapper_adjusted (method);
-                               sig_adjusted = mono_method_signature (adjust_method);
-                               
-                               mspecs = g_new (MonoMarshalSpec*, sig_adjusted->param_count + 1);
-                               mono_method_get_marshal_info (method, mspecs);
+               for (i = iface->method.count-1; i >= 0;i--) {
+                       int param_index = 0;
+                       MonoMethodBuilder *mb;
+                       MonoMarshalSpec ** mspecs;
+                       MonoMethod *wrapper_method, *adjust_method;
+                       MonoMethod *method = iface->methods [i];
+                       MonoMethodSignature* sig_adjusted;
+                       MonoMethodSignature* sig = mono_method_signature (method);
+                       gboolean preserve_sig = method->iflags & METHOD_IMPL_ATTRIBUTE_PRESERVE_SIG;
+
+
+                       mb = mono_mb_new (iface, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
+                       adjust_method = cominterop_get_managed_wrapper_adjusted (method);
+                       sig_adjusted = mono_method_signature (adjust_method);
+                       
+                       mspecs = g_new (MonoMarshalSpec*, sig_adjusted->param_count + 1);
+                       mono_method_get_marshal_info (method, mspecs);
 
-                               
-                               /* move managed args up one */
-                               for (param_index = sig->param_count; param_index >= 1; param_index--)
-                                       mspecs [param_index+1] = mspecs [param_index];
+                       
+                       /* move managed args up one */
+                       for (param_index = sig->param_count; param_index >= 1; param_index--) {
+                               int mspec_index = param_index+1;
+                               mspecs [mspec_index] = mspecs [param_index];
+
+                               if (mspecs[mspec_index] == NULL) {
+                                       if (sig_adjusted->params[param_index]->type == MONO_TYPE_OBJECT) {
+                                               mspecs[mspec_index] = g_new0 (MonoMarshalSpec, 1);
+                                               mspecs[mspec_index]->native = MONO_NATIVE_STRUCT;
+                                       }
+                                       else if (sig_adjusted->params[param_index]->type == MONO_TYPE_STRING) {
+                                               mspecs[mspec_index] = g_new0 (MonoMarshalSpec, 1);
+                                               mspecs[mspec_index]->native = MONO_NATIVE_BSTR;
+                                       }
+                                       else if (sig_adjusted->params[param_index]->type == MONO_TYPE_CLASS) {
+                                               mspecs[mspec_index] = g_new0 (MonoMarshalSpec, 1);
+                                               mspecs[mspec_index]->native = MONO_NATIVE_INTERFACE;
+                                       }
+                               }
+                       }
 
-                               /* first arg is IntPtr for interface */
-                               mspecs [1] = NULL;
+                       /* first arg is IntPtr for interface */
+                       mspecs [1] = NULL;
 
-                               /* move return spec to last param */
-                               if (!MONO_TYPE_IS_VOID (sig->ret))
-                                       mspecs [sig_adjusted->param_count] = mspecs [0];
+                       /* move return spec to last param */
+                       if (!preserve_sig && !MONO_TYPE_IS_VOID (sig->ret)) {
+                               if (mspecs [0] == NULL) {
+                                       if (sig_adjusted->params[sig_adjusted->param_count-1]->type == MONO_TYPE_OBJECT) {
+                                               mspecs[0] = g_new0 (MonoMarshalSpec, 1);
+                                               mspecs[0]->native = MONO_NATIVE_STRUCT;
+                                       }
+                                       else if (sig_adjusted->params[sig_adjusted->param_count-1]->type == MONO_TYPE_STRING) {
+                                               mspecs[0] = g_new0 (MonoMarshalSpec, 1);
+                                               mspecs[0]->native = MONO_NATIVE_BSTR;
+                                       }
+                                       else if (sig_adjusted->params[sig_adjusted->param_count-1]->type == MONO_TYPE_CLASS) {
+                                               mspecs[0] = g_new0 (MonoMarshalSpec, 1);
+                                               mspecs[0]->native = MONO_NATIVE_INTERFACE;
+                                       }
+                               }
 
+                               mspecs [sig_adjusted->param_count] = mspecs [0];
                                mspecs [0] = NULL;
+                       }
 
-                               cominterop_setup_marshal_context (&m, adjust_method);
-                               m.mb = mb;
-                               mono_marshal_emit_managed_wrapper (mb, sig_adjusted, mspecs, &m, adjust_method, NULL);
-                               mono_loader_lock ();
-                               mono_marshal_lock ();
-                               wrapper_method = mono_mb_create_method (mb, sig_adjusted, sig_adjusted->param_count + 16);
-                               mono_marshal_unlock ();
-                               mono_loader_unlock ();
+                       cominterop_setup_marshal_context (&m, adjust_method);
+                       m.mb = mb;
+                       mono_marshal_emit_managed_wrapper (mb, sig_adjusted, mspecs, &m, adjust_method, NULL);
+                       mono_loader_lock ();
+                       mono_marshal_lock ();
+                       wrapper_method = mono_mb_create_method (mb, m.csig, m.csig->param_count + 16);
+                       mono_marshal_unlock ();
+                       mono_loader_unlock ();
 
-                               /* skip visiblity since we call internal methods */
-                               wrapper_method->skip_visibility = TRUE;
+                       /* skip visiblity since we call internal methods */
+                       wrapper_method->skip_visibility = TRUE;
 
-                               vtable [vtable_index--] = mono_compile_method (wrapper_method);
+                       vtable [vtable_index--] = mono_compile_method (wrapper_method);
 
-                               
-                               for (param_index = sig_adjusted->param_count; param_index >= 0; param_index--)
-                                       if (mspecs [param_index])
-                                               mono_metadata_free_marshal_spec (mspecs [param_index]);
-                               g_free (mspecs);
-                       }
-                       if (iface->interface_count)
-                               iface = iface->interfaces [0];
-                       else 
-                               iface = NULL;
+                       
+                       for (param_index = sig_adjusted->param_count; param_index >= 0; param_index--)
+                               if (mspecs [param_index])
+                                       mono_metadata_free_marshal_spec (mspecs [param_index]);
+                       g_free (mspecs);
                }
 
                ccw_entry = g_new0 (MonoCCWInterface, 1);
@@ -11487,14 +12316,14 @@ mono_marshal_free_ccw (MonoObject* object)
 
        /* if list is empty remove original address from hash */
        if (g_list_length (ccw_list) == 0)
-               g_hash_table_remove (ccw_hash, ccw_list_orig);
+               g_hash_table_remove (ccw_hash, GINT_TO_POINTER (mono_object_hash (object)));
 
 
        return TRUE;
 }
 
 /**
- * cominterop_get_native_wrapper_adjusted:
+ * cominterop_get_managed_wrapper_adjusted:
  * @method: managed COM Interop method
  *
  * Returns: the generated method to call with signature matching
@@ -11508,11 +12337,12 @@ cominterop_get_managed_wrapper_adjusted (MonoMethod *method)
        MonoMethodBuilder *mb;
        MonoMarshalSpec **mspecs;
        MonoMethodSignature *sig, *sig_native;
-       MonoExceptionClause *main_clause;
+       MonoExceptionClause *main_clause = NULL;
        MonoMethodHeader *header;
        int pos_leave;
-       int hr;
+       int hr = 0;
        int i;
+       gboolean preserve_sig = method->iflags & METHOD_IMPL_ATTRIBUTE_PRESERVE_SIG;
 
        if (!get_hr_for_exception)
                get_hr_for_exception = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetHRForException", -1);
@@ -11522,7 +12352,7 @@ cominterop_get_managed_wrapper_adjusted (MonoMethod *method)
        /* create unmanaged wrapper */
        mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_COMINTEROP);
 
-       sig_native = signature_cominterop (method->klass->image, sig);
+       sig_native = cominterop_method_signature (method);
 
        mspecs = g_new0 (MonoMarshalSpec*, sig_native->param_count+1);
 
@@ -11536,19 +12366,21 @@ cominterop_get_managed_wrapper_adjusted (MonoMethod *method)
        mspecs [1] = NULL;
 
        /* move return spec to last param */
-       if (!MONO_TYPE_IS_VOID (sig->ret))
+       if (!preserve_sig && !MONO_TYPE_IS_VOID (sig->ret))
                mspecs [sig_native->param_count] = mspecs [0];
 
        mspecs [0] = NULL;
 
-       hr = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
-
-       /* try */
+       if (!preserve_sig) {
+               hr = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
 
-       main_clause = g_new0 (MonoExceptionClause, 1);
-       main_clause->try_offset = mb->pos;
+               /* try */
+               main_clause = g_new0 (MonoExceptionClause, 1);
+               main_clause->try_offset = mono_mb_get_label (mb);
+       }
 
-       if (!MONO_TYPE_IS_VOID (sig->ret))
+       /* load last param to store result if not preserve_sig and not void */
+       if (!preserve_sig && !MONO_TYPE_IS_VOID (sig->ret))
                mono_mb_emit_ldarg (mb, sig_native->param_count-1);
 
        /* the CCW -> object conversion */
@@ -11561,29 +12393,31 @@ cominterop_get_managed_wrapper_adjusted (MonoMethod *method)
 
        mono_mb_emit_managed_call (mb, method, NULL);
 
-       /* store result if we have one */
-       if (!MONO_TYPE_IS_VOID (sig->ret))
-               mono_mb_emit_byte (mb, CEE_STIND_REF);
+       if (!preserve_sig) {
+               /* store result if not preserve_sig and we have one */
+               if (!MONO_TYPE_IS_VOID (sig->ret))
+                       mono_mb_emit_byte (mb, mono_type_to_stind (sig->ret));
 
-       pos_leave = mono_mb_emit_branch (mb, CEE_LEAVE);
+               pos_leave = mono_mb_emit_branch (mb, CEE_LEAVE);
 
-       /* Main exception catch */
-       main_clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
-       main_clause->try_len = mb->pos - main_clause->try_offset;
-       main_clause->data.catch_class = mono_defaults.object_class;
-       
-       /* handler code */
-       main_clause->handler_offset = mb->pos;
-       mono_mb_emit_managed_call (mb, get_hr_for_exception, NULL);
-       mono_mb_emit_stloc (mb, hr);
-       mono_mb_emit_branch (mb, CEE_LEAVE);
-       main_clause->handler_len = mb->pos - main_clause->handler_offset;
-       /* end catch */
+               /* Main exception catch */
+               main_clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
+               main_clause->try_len = mono_mb_get_pos (mb) - main_clause->try_offset;
+               main_clause->data.catch_class = mono_defaults.object_class;
+               
+               /* handler code */
+               main_clause->handler_offset = mono_mb_get_label (mb);
+               mono_mb_emit_managed_call (mb, get_hr_for_exception, NULL);
+               mono_mb_emit_stloc (mb, hr);
+               mono_mb_emit_branch (mb, CEE_LEAVE);
+               main_clause->handler_len = mono_mb_get_pos (mb) - main_clause->handler_offset;
+               /* end catch */
 
-       mono_mb_patch_addr (mb, pos_leave, mb->pos - (pos_leave + 4));
+               mono_mb_patch_branch (mb, pos_leave);
+
+               mono_mb_emit_ldloc (mb, hr);
+       }
 
-       /* FIXME: need to emit try/catch block and return failure code if exception */
-       mono_mb_emit_ldloc (mb, hr);
        mono_mb_emit_byte (mb, CEE_RET);
 
        mono_loader_lock ();
@@ -11599,9 +12433,11 @@ cominterop_get_managed_wrapper_adjusted (MonoMethod *method)
                        mono_metadata_free_marshal_spec (mspecs [i]);
        g_free (mspecs);
 
-       header = ((MonoMethodNormal *)res)->header;
-       header->num_clauses = 1;
-       header->clauses = main_clause;
+       if (!preserve_sig) {
+               header = ((MonoMethodNormal *)res)->header;
+               header->num_clauses = 1;
+               header->clauses = main_clause;
+       }
 
        return res;
 }
@@ -11612,7 +12448,7 @@ cominterop_get_managed_wrapper_adjusted (MonoMethod *method)
  * Converts the standard string representation of a GUID 
  * to a 16 byte Microsoft GUID.
  */
-void
+static void
 cominterop_mono_string_to_guid (const MonoString* string, guint8 *guid) {
        gunichar2 * chars = mono_string_chars (string);
        int i = 0;
@@ -11620,48 +12456,14 @@ cominterop_mono_string_to_guid (const MonoString* string, guint8 *guid) {
 
        for (i = 0; i < sizeof(indexes); i++)
                guid [i] = g_unichar_xdigit_value (chars [indexes [i]]) + (g_unichar_xdigit_value (chars [indexes [i] - 1]) << 4);
-
-       //guid [0] = g_unichar_xdigit_value (chars [7]) + (g_unichar_xdigit_value (chars [6]) << 4);
-       //guid [1] = g_unichar_xdigit_value (chars [5]) + (g_unichar_xdigit_value (chars [4]) << 4);
-       //guid [2] = g_unichar_xdigit_value (chars [3]) + (g_unichar_xdigit_value (chars [2]) << 4);
-       //guid [3] = g_unichar_xdigit_value (chars [1]) + (g_unichar_xdigit_value (chars [0]) << 4);
-       //guid [4] = g_unichar_xdigit_value (chars [12]) + (g_unichar_xdigit_value (chars [11]) << 4);
-       //guid [5] = g_unichar_xdigit_value (chars [10]) + (g_unichar_xdigit_value (chars [9]) << 4);
-       //guid [6] = g_unichar_xdigit_value (chars [17]) + (g_unichar_xdigit_value (chars [16]) << 4);
-       //guid [7] = g_unichar_xdigit_value (chars [15]) + (g_unichar_xdigit_value (chars [14]) << 4);
-       //guid [8] = g_unichar_xdigit_value (chars [20]) + (g_unichar_xdigit_value (chars [19]) << 4);
-       //guid [9] = g_unichar_xdigit_value (chars [22]) + (g_unichar_xdigit_value (chars [21]) << 4);
-       //guid [10] = g_unichar_xdigit_value (chars [25]) + (g_unichar_xdigit_value (chars [24]) << 4);
-       //guid [11] = g_unichar_xdigit_value (chars [27]) + (g_unichar_xdigit_value (chars [26]) << 4);
-       //guid [12] = g_unichar_xdigit_value (chars [29]) + (g_unichar_xdigit_value (chars [28]) << 4);
-       //guid [13] = g_unichar_xdigit_value (chars [31]) + (g_unichar_xdigit_value (chars [30]) << 4);
-       //guid [14] = g_unichar_xdigit_value (chars [33]) + (g_unichar_xdigit_value (chars [32]) << 4);
-       //guid [15] = g_unichar_xdigit_value (chars [35]) + (g_unichar_xdigit_value (chars [34]) << 4);
 }
 
 static gboolean
 cominterop_class_guid_equal (guint8* guid, MonoClass* klass)
 {
-       static MonoClass *GuidAttribute = NULL;
-       MonoCustomAttrInfo *cinfo;
-
-       /* Handle the GuidAttribute */
-       if (!GuidAttribute)
-               GuidAttribute = mono_class_from_name (mono_defaults.corlib, "System.Runtime.InteropServices", "GuidAttribute");
-
-       cinfo = mono_custom_attrs_from_class (klass);   
-       if (cinfo) {
-               guint8 klass_guid [16];
-               MonoReflectionGuidAttribute *attr = (MonoReflectionGuidAttribute*)mono_custom_attrs_get_attr (cinfo, GuidAttribute);
-
-               if (!attr)
-                       return FALSE;
-               if (!cinfo->cached)
-                       mono_custom_attrs_free (cinfo);
-
-               cominterop_mono_string_to_guid (attr->guid, klass_guid);
+       guint8 klass_guid [16];
+       if (cominterop_class_guid (klass, klass_guid))
                return !memcmp (guid, klass_guid, sizeof (klass_guid));
-       }
        return FALSE;
 }
 
@@ -11673,7 +12475,7 @@ cominterop_ccw_addref (MonoCCWInterface* ccwe)
        g_assert (ccw);
        g_assert (ccw->gc_handle);
        g_assert (ccw->ref_count >= 0);
-       ref_count = InterlockedIncrement (&ccw->ref_count);
+       ref_count = InterlockedIncrement ((gint32*)&ccw->ref_count);
        if (ref_count == 1) {
                guint32 oldhandle = ccw->gc_handle;
                g_assert (oldhandle);
@@ -11691,20 +12493,50 @@ cominterop_ccw_release (MonoCCWInterface* ccwe)
        MonoCCW* ccw = ccwe->ccw;
        g_assert (ccw);
        g_assert (ccw->ref_count > 0);
-       ref_count = InterlockedDecrement (&ccw->ref_count);
+       ref_count = InterlockedDecrement ((gint32*)&ccw->ref_count);
        if (ref_count == 0) {
                /* allow gc of object */
                guint32 oldhandle = ccw->gc_handle;
                g_assert (oldhandle);
+#ifdef PLATFORM_WIN32
+               if (ccw->free_marshaler)
+                       ves_icall_System_Runtime_InteropServices_Marshal_ReleaseInternal (ccw->free_marshaler);
+#endif
                ccw->gc_handle = mono_gchandle_new_weakref (mono_gchandle_get_target (oldhandle), FALSE);
                mono_gchandle_free (oldhandle);
        }
        return ref_count;
 }
 
-#define MONO_S_OK 0x00000000L
-#define MONO_E_NOINTERFACE 0x80004002L
-#define MONO_E_NOTIMPL 0x80004001L
+#ifdef PLATFORM_WIN32
+static const IID MONO_IID_IMarshal = {0x3, 0x0, 0x0, {0xC0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x46}};
+#endif
+
+#ifdef PLATFORM_WIN32
+/* All ccw objects are free threaded */
+static int
+cominterop_ccw_getfreethreadedmarshaler (MonoCCW* ccw, MonoObject* object, gpointer* ppv)
+{
+#ifdef PLATFORM_WIN32
+       if (!ccw->free_marshaler) {
+               int ret = 0;
+               gpointer tunk;
+               tunk = cominterop_get_ccw (object, mono_defaults.iunknown_class);
+               /* remember to addref on QI */
+               cominterop_ccw_addref (tunk);
+               ret = CoCreateFreeThreadedMarshaler (tunk, (LPUNKNOWN*)&ccw->free_marshaler);
+               cominterop_ccw_release(tunk);
+       }
+               
+       if (!ccw->free_marshaler)
+               return MONO_E_NOINTERFACE;
+
+       return ves_icall_System_Runtime_InteropServices_Marshal_QueryInterfaceInternal (ccw->free_marshaler, (IID*)&MONO_IID_IMarshal, ppv);
+#else
+       return MONO_E_NOINTERFACE;
+#endif
+}
+#endif
 
 static int STDCALL 
 cominterop_ccw_queryinterface (MonoCCWInterface* ccwe, guint8* riid, gpointer* ppv)
@@ -11722,6 +12554,9 @@ cominterop_ccw_queryinterface (MonoCCWInterface* ccwe, guint8* riid, gpointer* p
        if (ppv)
                *ppv = NULL;
 
+       if (!mono_domain_get ())
+               mono_thread_attach (mono_get_root_domain ());
+
        /* handle IUnknown special */
        if (cominterop_class_guid_equal (riid, mono_defaults.iunknown_class)) {
                *ppv = cominterop_get_ccw (object, mono_defaults.iunknown_class);
@@ -11732,12 +12567,22 @@ cominterop_ccw_queryinterface (MonoCCWInterface* ccwe, guint8* riid, gpointer* p
 
        /* handle IDispatch special */
        if (cominterop_class_guid_equal (riid, mono_defaults.idispatch_class)) {
+               if (!cominterop_can_support_dispatch (klass))
+                       return MONO_E_NOINTERFACE;
+               
                *ppv = cominterop_get_ccw (object, mono_defaults.idispatch_class);
                /* remember to addref on QI */
                cominterop_ccw_addref (*ppv);
                return MONO_S_OK;
        }
 
+#ifdef PLATFORM_WIN32
+       /* handle IMarshal special */
+       if (0 == memcmp (riid, &MONO_IID_IMarshal, sizeof (IID))) {
+               return cominterop_ccw_getfreethreadedmarshaler (ccw, object, ppv);      
+       }
+#endif
+
        ifaces = mono_class_get_implemented_interfaces (klass);
        if (ifaces) {
                for (i = 0; i < ifaces->len; ++i) {
@@ -11789,3 +12634,182 @@ cominterop_ccw_invoke (MonoCCWInterface* ccwe, guint32 dispIdMember,
 {
        return MONO_E_NOTIMPL;
 }
+
+#else /* DISABLE_COM */
+
+gboolean
+mono_marshal_free_ccw (MonoObject* object)
+{
+       return FALSE;
+}
+
+#endif /* DISABLE_COM */
+
+void
+mono_marshal_find_nonzero_bit_offset (guint8 *buf, int len, int *byte_offset, guint8 *bitmask)
+{
+       int i;
+       guint8 byte;
+
+       for (i = 0; i < len; ++i)
+               if (buf [i])
+                       break;
+
+       g_assert (i < len);
+
+       byte = buf [i];
+       while (byte && !(byte & 1))
+               byte >>= 1;
+       g_assert (byte == 1);
+
+       *byte_offset = i;
+       *bitmask = buf [i];
+}
+
+MonoMethod *
+mono_marshal_get_thunk_invoke_wrapper (MonoMethod *method)
+{
+       MonoMethodBuilder *mb;
+       MonoMethodSignature *sig, *csig;
+       MonoExceptionClause *clause;
+       MonoMethodHeader *header;
+       MonoImage *image;
+       MonoClass *klass;
+       GHashTable *cache;
+       MonoMethod *res;
+       int i, param_count, sig_size, pos_leave;
+
+       g_assert (method);
+
+       klass = method->klass;
+       image = method->klass->image;
+       cache = get_cache (&image->thunk_invoke_cache, mono_aligned_addr_hash, NULL);
+
+       if ((res = mono_marshal_find_in_cache (cache, method)))
+               return res;
+
+       sig = mono_method_signature (method);
+       mb = mono_mb_new (klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
+
+       /* add "this" and exception param */
+       param_count = sig->param_count + sig->hasthis + 1;
+
+       /* dup & extend signature */
+       csig = mono_metadata_signature_alloc (image, param_count);
+       sig_size = sizeof (MonoMethodSignature) + ((sig->param_count - MONO_ZERO_LEN_ARRAY) * sizeof (MonoType *));
+       memcpy (csig, sig, sig_size);
+       csig->param_count = param_count;
+       csig->hasthis = 0;
+       csig->pinvoke = 1;
+       csig->call_convention = MONO_CALL_DEFAULT;
+
+       if (sig->hasthis) {
+               /* add "this" */
+               csig->params [0] = &klass->byval_arg;
+               /* move params up by one */
+               for (i = 0; i < sig->param_count; i++)
+                       csig->params [i + 1] = sig->params [i];
+       }
+
+       /* setup exception param as byref+[out] */
+       csig->params [param_count - 1] = mono_metadata_type_dup (image->mempool,
+                &mono_defaults.exception_class->byval_arg);
+       csig->params [param_count - 1]->byref = 1;
+       csig->params [param_count - 1]->attrs = PARAM_ATTRIBUTE_OUT;
+
+       /* convert struct return to object */
+       if (MONO_TYPE_ISSTRUCT (sig->ret))
+               csig->ret = &mono_defaults.object_class->byval_arg;
+
+       /* local 0 (temp for exception object) */
+       mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
+
+       /* local 1 (temp for result) */
+       if (!MONO_TYPE_IS_VOID (sig->ret))
+               mono_mb_add_local (mb, sig->ret);
+
+       /* clear exception arg */
+       mono_mb_emit_ldarg (mb, param_count - 1);
+       mono_mb_emit_byte (mb, CEE_LDNULL);
+       mono_mb_emit_byte (mb, CEE_STIND_REF);
+
+       /* try */
+       mono_loader_lock ();
+       clause = mono_image_alloc0 (image, sizeof (MonoExceptionClause));
+       mono_loader_unlock ();
+       clause->try_offset = mono_mb_get_label (mb);
+
+       /* push method's args */
+       for (i = 0; i < param_count - 1; i++) {
+               MonoType *type;
+               MonoClass *klass;
+
+               mono_mb_emit_ldarg (mb, i);
+
+               /* get the byval type of the param */
+               klass = mono_class_from_mono_type (csig->params [i]);
+               type = &klass->byval_arg;
+
+               /* unbox struct args */
+               if (MONO_TYPE_ISSTRUCT (type)) {
+                       mono_mb_emit_op (mb, CEE_UNBOX, klass);
+
+                       /* byref args & and the "this" arg must remain a ptr.
+                          Otherwise make a copy of the value type */
+                       if (!(csig->params [i]->byref || (i == 0 && sig->hasthis)))
+                               mono_mb_emit_op (mb, CEE_LDOBJ, klass);
+
+                       csig->params [i] = &mono_defaults.object_class->byval_arg;
+               }
+       }
+
+       /* call */
+       if (method->flags & METHOD_ATTRIBUTE_VIRTUAL)
+               mono_mb_emit_op (mb, CEE_CALLVIRT, method);
+       else
+               mono_mb_emit_op (mb, CEE_CALL, method);
+
+       /* save result at local 1 */
+       if (!MONO_TYPE_IS_VOID (sig->ret))
+               mono_mb_emit_stloc (mb, 1);
+
+       pos_leave = mono_mb_emit_branch (mb, CEE_LEAVE);
+
+       /* catch */
+       clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
+       clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
+       clause->data.catch_class = mono_defaults.object_class;
+
+       clause->handler_offset = mono_mb_get_label (mb);
+
+       /* store exception at local 0 */
+       mono_mb_emit_stloc (mb, 0);
+       mono_mb_emit_ldarg (mb, param_count - 1);
+       mono_mb_emit_ldloc (mb, 0);
+       mono_mb_emit_byte (mb, CEE_STIND_REF);
+       mono_mb_emit_branch (mb, CEE_LEAVE);
+
+       clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
+
+       mono_mb_patch_branch (mb, pos_leave);
+       /* end-try */
+
+       if (!MONO_TYPE_IS_VOID (sig->ret)) {
+               mono_mb_emit_ldloc (mb, 1);
+
+               /* box the return value */
+               if (MONO_TYPE_ISSTRUCT (sig->ret))
+                       mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (sig->ret));
+       }
+
+       mono_mb_emit_byte (mb, CEE_RET);
+
+       res = mono_mb_create_and_cache (cache, method, mb, csig, param_count + 16);
+       mono_mb_free (mb);
+
+       header = ((MonoMethodNormal *)res)->header;
+       header->num_clauses = 1;
+       header->clauses = clause;
+
+       return res;
+}