[exdoc] Handle punctuation better in code formatting.
[mono.git] / mono / metadata / marshal.c
index 360938c244a1255313cd6af34e80af5cce8b8056..c794ccc053572343ccb6ad68e7692d81130da7ec 100644 (file)
@@ -1,5 +1,6 @@
-/*
- * marshal.c: Routines for marshaling complex types in P/Invoke methods.
+/**
+ * \file
+ * Routines for marshaling complex types in P/Invoke methods.
  * 
  * Author:
  *   Paolo Molaro (lupus@ximian.com)
@@ -36,7 +37,6 @@
 #include "mono/metadata/threads-types.h"
 #include "mono/metadata/string-icalls.h"
 #include "mono/metadata/attrdefs.h"
-#include "mono/metadata/gc-internals.h"
 #include "mono/metadata/cominterop.h"
 #include "mono/metadata/remoting.h"
 #include "mono/metadata/reflection-internals.h"
@@ -216,11 +216,11 @@ static void
 mono_icall_end (MonoThreadInfo *info, HandleStackMark *stackmark, MonoError *error);
 
 /* Lazy class loading functions */
-static GENERATE_GET_CLASS_WITH_CACHE (string_builder, System.Text, StringBuilder);
-static GENERATE_GET_CLASS_WITH_CACHE (date_time, System, DateTime);
-static GENERATE_GET_CLASS_WITH_CACHE (fixed_buffer_attribute, System.Runtime.CompilerServices, FixedBufferAttribute);
-static GENERATE_TRY_GET_CLASS_WITH_CACHE (unmanaged_function_pointer_attribute, System.Runtime.InteropServices, UnmanagedFunctionPointerAttribute);
-static GENERATE_TRY_GET_CLASS_WITH_CACHE (icustom_marshaler, System.Runtime.InteropServices, ICustomMarshaler);
+static GENERATE_GET_CLASS_WITH_CACHE (string_builder, "System.Text", "StringBuilder");
+static GENERATE_GET_CLASS_WITH_CACHE (date_time, "System", "DateTime");
+static GENERATE_GET_CLASS_WITH_CACHE (fixed_buffer_attribute, "System.Runtime.CompilerServices", "FixedBufferAttribute");
+static GENERATE_TRY_GET_CLASS_WITH_CACHE (unmanaged_function_pointer_attribute, "System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute");
+static GENERATE_TRY_GET_CLASS_WITH_CACHE (icustom_marshaler, "System.Runtime.InteropServices", "ICustomMarshaler");
 
 /* MonoMethod pointers to SafeHandle::DangerousAddRef and ::DangerousRelease */
 static MonoMethod *sh_dangerous_add_ref;
@@ -243,6 +243,14 @@ register_icall (gpointer func, const char *name, const char *sigstr, gboolean no
        mono_register_jit_icall (func, name, sig, no_wrapper);
 }
 
+static void
+register_icall_no_wrapper (gpointer func, const char *name, const char *sigstr)
+{
+       MonoMethodSignature *sig = mono_create_icall_signature (sigstr);
+
+       mono_register_jit_icall (func, name, sig, TRUE);
+}
+
 MonoMethodSignature*
 mono_signature_no_pinvoke (MonoMethod *method)
 {
@@ -336,7 +344,7 @@ mono_marshal_init (void)
                register_icall (mono_string_to_byvalstr, "mono_string_to_byvalstr", "void ptr ptr int32", FALSE);
                register_icall (mono_string_to_byvalwstr, "mono_string_to_byvalwstr", "void ptr ptr int32", FALSE);
                register_icall (g_free, "g_free", "void ptr", FALSE);
-               register_icall (mono_object_isinst_icall, "mono_object_isinst_icall", "object object ptr", FALSE);
+               register_icall_no_wrapper (mono_object_isinst_icall, "mono_object_isinst_icall", "object object ptr");
                register_icall (mono_struct_delete_old, "mono_struct_delete_old", "void ptr ptr", FALSE);
                register_icall (mono_delegate_begin_invoke, "mono_delegate_begin_invoke", "object object ptr", FALSE);
                register_icall (mono_delegate_end_invoke, "mono_delegate_end_invoke", "object object ptr", FALSE);
@@ -353,7 +361,7 @@ mono_marshal_init (void)
                register_icall (mono_threads_detach_coop, "mono_threads_detach_coop", "void ptr ptr", TRUE);
                register_icall (mono_icall_start, "mono_icall_start", "ptr ptr ptr", TRUE);
                register_icall (mono_icall_end, "mono_icall_end", "void ptr ptr ptr", TRUE);
-               register_icall (mono_handle_new, "mono_handle_new", "ptr ptr", TRUE);
+               register_icall (mono_handle_new_full, "mono_handle_new_full", "ptr ptr bool", TRUE);
 
                mono_cominterop_init ();
                mono_remoting_init ();
@@ -427,7 +435,9 @@ mono_delegate_to_ftnptr (MonoDelegate *delegate)
                target_handle = mono_gchandle_new_weakref (delegate->target, FALSE);
        }
 
-       wrapper = mono_marshal_get_managed_wrapper (method, klass, target_handle);
+       wrapper = mono_marshal_get_managed_wrapper (method, klass, target_handle, &error);
+       if (!is_ok (&error))
+               goto fail;
 
        delegate->delegate_trampoline = mono_compile_method_checked (wrapper, &error);
        if (!is_ok (&error))
@@ -976,11 +986,11 @@ mono_string_utf16_to_builder (MonoStringBuilder *sb, gunichar2 *text)
 
 /**
  * mono_string_builder_to_utf8:
- * @sb: the string builder
+ * \param sb the string builder
  *
- * Converts to utf8 the contents of the MonoStringBuilder.
+ * Converts to utf8 the contents of the \c MonoStringBuilder .
  *
- * Returns: a utf8 string with the contents of the StringBuilder.
+ * \returns a utf8 string with the contents of the \c StringBuilder .
  *
  * The return value must be released with mono_marshal_free.
  *
@@ -1027,11 +1037,11 @@ mono_string_builder_to_utf8 (MonoStringBuilder *sb)
 
 /**
  * mono_string_builder_to_utf16:
- * @sb: the string builder
+ * \param sb the string builder
  *
- * Converts to utf16 the contents of the MonoStringBuilder.
+ * Converts to utf16 the contents of the \c MonoStringBuilder .
  *
- * Returns: a utf16 string with the contents of the StringBuilder.
+ * Returns: a utf16 string with the contents of the \c StringBuilder .
  *
  * The return value must be released with mono_marshal_free.
  *
@@ -1104,12 +1114,12 @@ mono_string_to_ansibstr (MonoString *string_obj)
 
 /**
  * mono_string_to_byvalstr:
- * @dst: Where to store the null-terminated utf8 decoded string.
- * @src: the MonoString to copy.
- * @size: the maximum number of bytes to copy.
+ * \param dst Where to store the null-terminated utf8 decoded string.
+ * \param src the \c MonoString to copy.
+ * \param size the maximum number of bytes to copy.
  *
- * Copies the MonoString pointed to by @src as a utf8 string
- * into @dst, it copies at most @size bytes into the destination.
+ * Copies the \c MonoString pointed to by \p src as a utf8 string
+ * into \p dst, it copies at most \p size bytes into the destination.
  */
 void
 mono_string_to_byvalstr (gpointer dst, MonoString *src, int size)
@@ -1137,12 +1147,12 @@ mono_string_to_byvalstr (gpointer dst, MonoString *src, int size)
 
 /**
  * mono_string_to_byvalwstr:
- * @dst: Where to store the null-terminated utf16 decoded string.
- * @src: the MonoString to copy.
- * @size: the maximum number of wide characters to copy (each consumes 2 bytes)
+ * \param dst Where to store the null-terminated utf16 decoded string.
+ * \param src the \c MonoString to copy.
+ * \param size the maximum number of wide characters to copy (each consumes 2 bytes)
  *
- * Copies the MonoString pointed to by @src as a utf16 string into
- * @dst, it copies at most @size bytes into the destination (including
+ * Copies the \c MonoString pointed to by \p src as a utf16 string into
+ * \p dst, it copies at most \p size bytes into the destination (including
  * a terminating 16-bit zero terminator).
  */
 void
@@ -2406,7 +2416,7 @@ mono_delegate_begin_invoke (MonoDelegate *delegate, gpointer *params)
        }
 
 #ifndef DISABLE_REMOTING
-       if (delegate->target && mono_object_class (delegate->target) == mono_defaults.transparent_proxy_class) {
+       if (delegate->target && mono_object_is_transparent_proxy (delegate->target)) {
                MonoTransparentProxy* tp = (MonoTransparentProxy *)delegate->target;
                if (!mono_class_is_contextbound (tp->remote_class->proxy_class) || tp->rp->context != (MonoObject *) mono_context_get ()) {
                        /* If the target is a proxy, make a direct call. Is proxy's work
@@ -4418,7 +4428,7 @@ mono_marshal_get_runtime_invoke_dynamic (void)
        MonoMethodSignature *csig;
        MonoExceptionClause *clause;
        MonoMethodBuilder *mb;
-       int pos, posna;
+       int pos;
        char *name;
        WrapperInfo *info;
 
@@ -4488,15 +4498,6 @@ mono_marshal_get_runtime_invoke_dynamic (void)
        mono_mb_emit_byte (mb, CEE_LDNULL);
        mono_mb_emit_stloc (mb, 0);
 
-       /* Check for the abort exception */
-       mono_mb_emit_ldloc (mb, 1);
-       mono_mb_emit_op (mb, CEE_ISINST, mono_defaults.threadabortexception_class);
-       posna = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
-
-       /* Delay the abort exception */
-       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 = mono_mb_get_pos (mb) - clause->handler_offset;
@@ -7491,19 +7492,57 @@ emit_marshal (EmitMarshalContext *m, int argnum, MonoType *t,
        }
 }
 
+/* How the arguments of an icall should be wrapped */
+typedef enum {
+       /* Don't wrap at all, pass the argument as is */
+       ICALL_HANDLES_WRAP_NONE,
+       /* Wrap the argument in an object handle, pass the handle to the icall */
+       ICALL_HANDLES_WRAP_OBJ,
+       /* Wrap the argument in an object handle, pass the handle to the icall,
+          write the value out from the handle when the icall returns */
+       ICALL_HANDLES_WRAP_OBJ_INOUT,
+       /* Wrap the argument (a valuetype reference) in a handle to pin its enclosing object,
+          but pass the raw reference to the icall */
+       ICALL_HANDLES_WRAP_VALUETYPE_REF,
+} IcallHandlesWrap;
+
+typedef struct {
+       IcallHandlesWrap wrap;
+       /* if wrap is NONE or OBJ or VALUETYPE_REF, this is not meaningful.
+          if wrap is OBJ_INOUT it's the local var that holds the MonoObjectHandle.
+       */
+       int handle;
+}  IcallHandlesLocal;
+
+/*
+ * Describes how to wrap the given parameter.
+ *
+ */
+static IcallHandlesWrap
+signature_param_uses_handles (MonoMethodSignature *sig, int param)
+{
+       if (MONO_TYPE_IS_REFERENCE (sig->params [param])) {
+               return mono_signature_param_is_out (sig, param) ? ICALL_HANDLES_WRAP_OBJ_INOUT : ICALL_HANDLES_WRAP_OBJ;
+       } else if (mono_type_is_byref (sig->params [param]))
+               return ICALL_HANDLES_WRAP_VALUETYPE_REF;
+       else
+               return ICALL_HANDLES_WRAP_NONE;
+}
+
+
 #ifndef DISABLE_JIT
 /**
  * mono_marshal_emit_native_wrapper:
- * @image: the image to use for looking up custom marshallers
- * @sig: The signature of the native function
- * @piinfo: Marshalling information
- * @mspecs: Marshalling information
- * @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
- * @func_param: the function to call is passed as a boxed IntPtr as the first parameter
+ * \param image the image to use for looking up custom marshallers
+ * \param sig The signature of the native function
+ * \param piinfo Marshalling information
+ * \param mspecs Marshalling information
+ * \param aot whenever the created method will be compiled by the AOT compiler
+ * \param method if non-NULL, the pinvoke method to call
+ * \param check_exceptions Whenever to check for pending exceptions after the native call
+ * \param func_param the function to call is passed as a boxed IntPtr as the first parameter
  *
- * generates IL code for the pinvoke wrapper, the generated code calls @func.
+ * generates IL code for the pinvoke wrapper, the generated code calls \p func .
  */
 void
 mono_marshal_emit_native_wrapper (MonoImage *image, MonoMethodBuilder *mb, MonoMethodSignature *sig, MonoMethodPInvoke *piinfo, MonoMarshalSpec **mspecs, gpointer func, gboolean aot, gboolean check_exceptions, gboolean func_param)
@@ -7779,8 +7818,8 @@ 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
+ * \param method The MonoMethod to wrap.
+ * \param 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)
@@ -7943,8 +7982,8 @@ mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions,
                int thread_info_var = -1, stack_mark_var = -1, error_var = -1;
                MonoMethodSignature *call_sig = csig;
                gboolean uses_handles = FALSE;
-               gboolean has_outarg_handles = FALSE;
-               int *outarg_handle = NULL;
+               gboolean save_handles_to_locals = FALSE;
+               IcallHandlesLocal *handles_locals = NULL;
                (void) mono_lookup_internal_call_full (method, &uses_handles);
 
 
@@ -7954,22 +7993,36 @@ mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions,
                if (uses_handles) {
                        MonoMethodSignature *ret;
 
-                       /* Add a MonoError argument */
+                       /* Add a MonoError argument and figure out which args need to be wrapped in handles */
                        // FIXME: The stuff from mono_metadata_signature_dup_internal_with_padding ()
                        ret = mono_metadata_signature_alloc (method->klass->image, csig->param_count + 1);
 
                        ret->param_count = csig->param_count + 1;
                        ret->ret = csig->ret;
+
+                       handles_locals = g_new0 (IcallHandlesLocal, csig->param_count);
                        for (int i = 0; i < csig->param_count; ++i) {
-                               if (MONO_TYPE_IS_REFERENCE (csig->params[i])) {
+                               IcallHandlesWrap w = signature_param_uses_handles (csig, i);
+                               handles_locals [i].wrap = w;
+                               switch (w) {
+                               case ICALL_HANDLES_WRAP_OBJ:
+                               case ICALL_HANDLES_WRAP_OBJ_INOUT:
                                        ret->params [i] = mono_class_get_byref_type (mono_class_from_mono_type(csig->params[i]));
-                                       if (mono_signature_param_is_out (csig, i)) {
-                                               has_outarg_handles = TRUE;
-                                       }
-                               } else
+                                       if (w == ICALL_HANDLES_WRAP_OBJ_INOUT)
+                                               save_handles_to_locals = TRUE;
+                                       break;
+                               case ICALL_HANDLES_WRAP_NONE:
+                               case ICALL_HANDLES_WRAP_VALUETYPE_REF:
                                        ret->params [i] = csig->params [i];
+                                       break;
+                               default:
+                                       g_assert_not_reached ();
+                               }
                        }
+                       /* Add MonoError* param */
                        ret->params [csig->param_count] = &mono_get_intptr_class ()->byval_arg;
+                       ret->pinvoke = csig->pinvoke;
+
                        call_sig = ret;
                }
 
@@ -7981,15 +8034,22 @@ mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions,
                        stack_mark_var = mono_mb_add_local (mb, &handle_stack_mark_class->byval_arg);
                        error_var = mono_mb_add_local (mb, &error_class->byval_arg);
 
-                       if (has_outarg_handles) {
-                               outarg_handle = g_new0 (int, sig->param_count);
-
+                       if (save_handles_to_locals) {
                                /* add a local var to hold the handles for each out arg */
                                for (int i = 0; i < sig->param_count; ++i) {
-                                       if (mono_signature_param_is_out (sig, i) && MONO_TYPE_IS_REFERENCE (sig->params[i])) {
-                                               outarg_handle[i] = mono_mb_add_local (mb, sig->params[i]);
-                                       } else if (outarg_handle != NULL)
-                                               outarg_handle[i] = -1;
+                                       int j = i + sig->hasthis;
+                                       switch (handles_locals[j].wrap) {
+                                       case ICALL_HANDLES_WRAP_NONE:
+                                       case ICALL_HANDLES_WRAP_OBJ:
+                                       case ICALL_HANDLES_WRAP_VALUETYPE_REF:
+                                               handles_locals [j].handle = -1;
+                                               break;
+                                       case ICALL_HANDLES_WRAP_OBJ_INOUT:
+                                               handles_locals [j].handle = mono_mb_add_local (mb, sig->params [i]);
+                                               break;
+                                       default:
+                                               g_assert_not_reached ();
+                                       }
                                }
                        }
                }
@@ -8015,27 +8075,47 @@ mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions,
 
                        if (sig->hasthis) {
                                mono_mb_emit_byte (mb, CEE_LDARG_0);
-                               mono_mb_emit_icall (mb, mono_handle_new);
+                               /* TODO support adding wrappers to non-static struct methods */
+                               g_assert (!mono_class_is_valuetype(mono_method_get_class (method)));
+                               mono_mb_emit_byte (mb, CEE_LDC_I4_0);
+                               mono_mb_emit_icall (mb, mono_handle_new_full);
                        }
                        for (i = 0; i < sig->param_count; i++) {
-                               /* load each argument. object reference arguments get wrapped in handles */
-
-                               if (!MONO_TYPE_IS_REFERENCE (sig->params [i])) {
-                                       mono_mb_emit_ldarg (mb, i + sig->hasthis);
-                               } else {
-                                       if (outarg_handle && outarg_handle[i] != -1) {
-                                               /* handleI = argI = mono_handle_new (NULL) */
-                                               mono_mb_emit_byte (mb, CEE_LDNULL);
-                                               mono_mb_emit_icall (mb, mono_handle_new);
-                                               /* tmp = argI */
-                                               mono_mb_emit_byte (mb, CEE_DUP);
-                                               /* handleI = tmp */
-                                               mono_mb_emit_stloc (mb, outarg_handle[i]);
-                                       } else {
-                                               /* argI = mono_handle_new (argI_raw) */
-                                               mono_mb_emit_ldarg (mb, i + sig->hasthis);
-                                               mono_mb_emit_icall (mb, mono_handle_new);
-                                       }
+                               /* load each argument. references into the managed heap get wrapped in handles */
+                               int j = i + sig->hasthis;
+                               switch (handles_locals[j].wrap) {
+                               case ICALL_HANDLES_WRAP_NONE:
+                                       mono_mb_emit_ldarg (mb, j);
+                                       break;
+                               case ICALL_HANDLES_WRAP_OBJ:
+                                       /* argI = mono_handle_new_full (argI_raw, FALSE) */
+                                       mono_mb_emit_ldarg (mb, j);
+                                       mono_mb_emit_byte (mb, CEE_LDC_I4_0);
+                                       mono_mb_emit_icall (mb, mono_handle_new_full);
+                                       break;
+                               case ICALL_HANDLES_WRAP_OBJ_INOUT:
+                                       /* handleI = argI = mono_handle_new_full (NULL, FALSE) */
+                                       mono_mb_emit_byte (mb, CEE_LDNULL);
+                                       mono_mb_emit_byte (mb, CEE_LDC_I4_0);
+                                       mono_mb_emit_icall (mb, mono_handle_new_full);
+                                       /* tmp = argI */
+                                       mono_mb_emit_byte (mb, CEE_DUP);
+                                       /* handleI = tmp */
+                                       mono_mb_emit_stloc (mb, handles_locals[j].handle);
+                                       break;
+                               case ICALL_HANDLES_WRAP_VALUETYPE_REF:
+                                       /* (void) mono_handle_new_full (argI, TRUE); argI */
+                                       mono_mb_emit_ldarg (mb, j);
+                                       mono_mb_emit_byte (mb, CEE_DUP);
+                                       mono_mb_emit_byte (mb, CEE_LDC_I4_1);
+                                       mono_mb_emit_icall (mb, mono_handle_new_full);
+                                       mono_mb_emit_byte (mb, CEE_POP);
+#if 0
+                                       fprintf (stderr, " Method %s.%s.%s has byref valuetype argument %d\n", method->klass->name_space, method->klass->name, method->name, i);
+#endif
+                                       break;
+                               default:
+                                       g_assert_not_reached ();
                                }
                        }
                        mono_mb_emit_ldloc_addr (mb, error_var);
@@ -8066,25 +8146,34 @@ mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions,
                                mono_mb_emit_byte (mb, CEE_LDIND_REF);
                                mono_mb_patch_branch (mb, pos);
                        }
-                       if (outarg_handle != NULL) {
+                       if (save_handles_to_locals) {
                                for (i = 0; i < sig->param_count; i++) {
-                                       if (outarg_handle[i] != -1) {
+                                       int j = i + sig->hasthis;
+                                       switch (handles_locals [j].wrap) {
+                                       case ICALL_HANDLES_WRAP_NONE:
+                                       case ICALL_HANDLES_WRAP_OBJ:
+                                       case ICALL_HANDLES_WRAP_VALUETYPE_REF:
+                                               break;
+                                       case ICALL_HANDLES_WRAP_OBJ_INOUT:
                                                /* *argI_raw = MONO_HANDLE_RAW (handleI) */
 
                                                /* argI_raw */
-                                               mono_mb_emit_ldarg (mb, i + sig->hasthis);
+                                               mono_mb_emit_ldarg (mb, j);
                                                /* handleI */
-                                               mono_mb_emit_ldloc (mb, outarg_handle[i]);
+                                               mono_mb_emit_ldloc (mb, handles_locals [j].handle);
                                                /* MONO_HANDLE_RAW(handleI) */
                                                mono_mb_emit_ldflda (mb, MONO_HANDLE_PAYLOAD_OFFSET (MonoObject));
                                                mono_mb_emit_byte (mb, CEE_LDIND_REF);
                                                /* *argI_raw = MONO_HANDLE_RAW(handleI) */
                                                mono_mb_emit_byte (mb, CEE_STIND_REF);
+                                               break;
+                                       default:
+                                               g_assert_not_reached ();
                                        }
                                }
-                               g_free (outarg_handle);
-                               outarg_handle = NULL;
                        }
+                       g_free (handles_locals);
+
                        mono_mb_emit_ldloc (mb, thread_info_var);
                        mono_mb_emit_ldloc_addr (mb, stack_mark_var);
                        mono_mb_emit_ldloc_addr (mb, error_var);
@@ -8140,11 +8229,11 @@ mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions,
 
 /**
  * mono_marshal_get_native_func_wrapper:
- * @image: The image to use for memory allocation and for looking up custom marshallers.
- * @sig: The signature of the function
- * @func: The native function to wrap
+ * \param image The image to use for memory allocation and for looking up custom marshallers.
+ * \param sig The signature of the function
+ * \param func The native function to wrap
  *
- *   Returns a wrapper method around native functions, similar to the pinvoke
+ * \returns a wrapper method around native functions, similar to the pinvoke
  * wrapper.
  */
 MonoMethod *
@@ -8658,9 +8747,8 @@ mono_marshal_set_callconv_from_modopt (MonoMethod *method, MonoMethodSignature *
  * If target_handle==0, the wrapper info will be a WrapperInfo structure.
  */
 MonoMethod *
-mono_marshal_get_managed_wrapper (MonoMethod *method, MonoClass *delegate_klass, uint32_t target_handle)
+mono_marshal_get_managed_wrapper (MonoMethod *method, MonoClass *delegate_klass, uint32_t target_handle, MonoError *error)
 {
-       MonoError error;
        MonoMethodSignature *sig, *csig, *invoke_sig;
        MonoMethodBuilder *mb;
        MonoMethod *res, *invoke;
@@ -8671,7 +8759,12 @@ mono_marshal_get_managed_wrapper (MonoMethod *method, MonoClass *delegate_klass,
        EmitMarshalContext m;
 
        g_assert (method != NULL);
-       g_assert (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL));
+       error_init (error);
+
+       if (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
+               mono_error_set_invalid_program (error, "Failed because method (%s) marked PInvokeCallback (managed method) and extern (unmanaged) simultaneously.", mono_method_full_name (method, TRUE));
+               return NULL;
+       }
 
        /* 
         * FIXME: Should cache the method+delegate type pair, since the same method
@@ -8725,8 +8818,8 @@ mono_marshal_get_managed_wrapper (MonoMethod *method, MonoClass *delegate_klass,
                 * contents of the attribute without constructing it, as that might not be
                 * possible when running in cross-compiling mode.
                 */
-               cinfo = mono_custom_attrs_from_class_checked (delegate_klass, &error);
-               mono_error_assert_ok (&error);
+               cinfo = mono_custom_attrs_from_class_checked (delegate_klass, error);
+               mono_error_assert_ok (error);
                attr = NULL;
                if (cinfo) {
                        for (i = 0; i < cinfo->num_attrs; ++i) {
@@ -9041,10 +9134,8 @@ mono_marshal_isinst_with_cache (MonoObject *obj, MonoClass *klass, uintptr_t *ca
        if (mono_error_set_pending_exception (&error))
                return NULL;
 
-#ifndef DISABLE_REMOTING
-       if (obj->vtable->klass == mono_defaults.transparent_proxy_class)
+       if (mono_object_is_transparent_proxy (obj))
                return isinst;
-#endif
 
        uintptr_t cache_update = (uintptr_t)obj->vtable;
        if (!isinst)
@@ -9119,7 +9210,7 @@ mono_marshal_get_isinst_with_cache (void)
 
 /**
  * mono_marshal_get_struct_to_ptr:
- * @klass:
+ * \param klass \c MonoClass
  *
  * generates IL code for StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld)
  */
@@ -9193,7 +9284,7 @@ mono_marshal_get_struct_to_ptr (MonoClass *klass)
 
 /**
  * mono_marshal_get_ptr_to_struct:
- * @klass:
+ * \param klass \c MonoClass
  *
  * generates IL code for PtrToStructure (IntPtr src, object structure)
  */
@@ -9697,7 +9788,8 @@ get_virtual_stelemref_wrapper (int kind)
                mono_mb_emit_byte (mb, CEE_RET);
                break;
 
-       case STELEMREF_COMPLEX:
+       case STELEMREF_COMPLEX: {
+               int b_fast;
                /*
                <ldelema (bound check)>
                if (!value)
@@ -9713,6 +9805,7 @@ get_virtual_stelemref_wrapper (int kind)
                */
 
                aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
+               vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
                array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
 
 #if 0
@@ -9741,6 +9834,13 @@ get_virtual_stelemref_wrapper (int kind)
 
                /* aklass = array->vtable->klass->element_class */
                load_array_class (mb, aklass);
+               /* vklass = value->vtable->klass */
+               load_value_class (mb, vklass);
+
+               /* fastpath */
+               mono_mb_emit_ldloc (mb, vklass);
+               mono_mb_emit_ldloc (mb, aklass);
+               b_fast = mono_mb_emit_branch (mb, CEE_BEQ);
 
                /*if (mono_object_isinst (value, aklass)) */
                mono_mb_emit_ldarg (mb, 2);
@@ -9750,6 +9850,7 @@ get_virtual_stelemref_wrapper (int kind)
 
                /* do_store: */
                mono_mb_patch_branch (mb, b1);
+               mono_mb_patch_branch (mb, b_fast);
                mono_mb_emit_ldloc (mb, array_slot_addr);
                mono_mb_emit_ldarg (mb, 2);
                mono_mb_emit_byte (mb, CEE_STIND_REF);
@@ -9760,7 +9861,7 @@ get_virtual_stelemref_wrapper (int kind)
 
                mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
                break;
-
+       }
        case STELEMREF_SEALED_CLASS:
                /*
                <ldelema (bound check)>
@@ -9783,7 +9884,6 @@ get_virtual_stelemref_wrapper (int kind)
                vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
                array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
 
-
                /* ldelema (implicit bound check) */
                load_array_element_address (mb);
                mono_mb_emit_stloc (mb, array_slot_addr);
@@ -9815,7 +9915,9 @@ get_virtual_stelemref_wrapper (int kind)
                mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
                break;
 
-       case STELEMREF_CLASS:
+       case STELEMREF_CLASS: {
+               int b_fast;
+
                /*
                the method:
                <ldelema (bound check)>
@@ -9856,6 +9958,11 @@ get_virtual_stelemref_wrapper (int kind)
                /* vklass = value->vtable->klass */
                load_value_class (mb, vklass);
 
+               /* fastpath */
+               mono_mb_emit_ldloc (mb, vklass);
+               mono_mb_emit_ldloc (mb, aklass);
+               b_fast = mono_mb_emit_branch (mb, CEE_BEQ);
+
                /*if (mono_object_isinst (value, aklass)) */
                mono_mb_emit_ldarg (mb, 2);
                mono_mb_emit_ldloc (mb, aklass);
@@ -9893,6 +10000,7 @@ get_virtual_stelemref_wrapper (int kind)
 
                /* do_store: */
                mono_mb_patch_branch (mb, b1);
+               mono_mb_patch_branch (mb, b_fast);
                mono_mb_emit_ldloc (mb, array_slot_addr);
                mono_mb_emit_ldarg (mb, 2);
                mono_mb_emit_byte (mb, CEE_STIND_REF);
@@ -9905,7 +10013,7 @@ get_virtual_stelemref_wrapper (int kind)
 
                mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
                break;
-
+       }
        case STELEMREF_INTERFACE:
                /*Mono *klass;
                MonoVTable *vt;
@@ -10279,13 +10387,13 @@ static int elem_addr_cache_next = 0;
 
 /**
  * mono_marshal_get_array_address:
- * @rank: rank of the array type
- * @elem_size: size in bytes of an element of an array.
+ * \param rank rank of the array type
+ * \param elem_size size in bytes of an element of an array.
  *
  * Returns a MonoMethod that implements the code to get the address
- * of an element in a multi-dimenasional array of @rank dimensions.
+ * of an element in a multi-dimenasional array of \p rank dimensions.
  * The returned method takes an array as the first argument and then
- * @rank indexes for the @rank dimensions.
+ * \p rank indexes for the \p rank dimensions.
  * If ELEM_SIZE is 0, read the array size from the array object.
  */
 MonoMethod*
@@ -10551,7 +10659,7 @@ mono_marshal_alloc (gulong size, MonoError *error)
 {
        gpointer res;
 
-       mono_error_init (error);
+       error_init (error);
 
        res = mono_marshal_alloc_co_task_mem (size);
        if (!res)
@@ -10734,7 +10842,7 @@ ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi_len (char *ptr,
 {
        MonoError error;
        MonoString *result = NULL;
-       mono_error_init (&error);
+       error_init (&error);
        if (ptr == NULL)
                mono_error_set_argument_null (&error, "ptr", "");
        else
@@ -10773,7 +10881,7 @@ ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni_len (guint16 *pt
        MonoString *res = NULL;
        MonoDomain *domain = mono_domain_get (); 
 
-       mono_error_init (&error);
+       error_init (&error);
 
        if (ptr == NULL) {
                res = NULL;
@@ -10854,7 +10962,7 @@ ptr_to_structure (gpointer src, MonoObject *dst, MonoError *error)
        MonoMethod *method;
        gpointer pa [2];
 
-       mono_error_init (error);
+       error_init (error);
 
        method = mono_marshal_get_ptr_to_struct (dst->vtable->klass);
 
@@ -11407,9 +11515,8 @@ mono_marshal_load_type_info (MonoClass* klass)
 
 /**
  * mono_class_native_size:
- * @klass: a class 
- * 
- * Returns: the native size of an object instance (when marshaled 
+ * \param klass a class 
+ * \returns the native size of an object instance (when marshaled 
  * to unmanaged code) 
  */
 gint32
@@ -11755,8 +11862,14 @@ mono_marshal_free_asany (MonoObject *o, gpointer ptr, MonoMarshalNative string_e
        }
 }
 
+/*
+ * mono_marshal_get_generic_array_helper:
+ *
+ *   Return a wrapper which is used to implement the implicit interfaces on arrays.
+ * The wrapper routes calls to METHOD, which is one of the InternalArray_ methods in Array.
+ */
 MonoMethod *
-mono_marshal_get_generic_array_helper (MonoClass *klass, MonoClass *iface, gchar *name, MonoMethod *method)
+mono_marshal_get_generic_array_helper (MonoClass *klass, gchar *name, MonoMethod *method)
 {
        MonoMethodSignature *sig, *csig;
        MonoMethodBuilder *mb;
@@ -12076,7 +12189,7 @@ mono_icall_start (HandleStackMark *stackmark, MonoError *error)
        MonoThreadInfo *info = mono_thread_info_current ();
 
        mono_stack_mark_init (info, stackmark);
-       mono_error_init (error);
+       error_init (error);
        return info;
 }
 
@@ -12084,5 +12197,6 @@ static void
 mono_icall_end (MonoThreadInfo *info, HandleStackMark *stackmark, MonoError *error)
 {
        mono_stack_mark_pop (info, stackmark);
-       mono_error_set_pending_exception (error);
+       if (G_UNLIKELY (!is_ok (error)))
+               mono_error_set_pending_exception (error);
 }