Merge pull request #5714 from alexischr/update_bockbuild
[mono.git] / mono / metadata / marshal.c
index 555a96122b7aec0a200cdae2863adecc460ba02a..05b23fddf3feae116697913694a6033b94c022df 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)
@@ -88,7 +89,7 @@ static void ftnptr_eh_callback_default (guint32 gchandle);
 static MonoFtnPtrEHCallback ftnptr_eh_callback = ftnptr_eh_callback_default;
 
 static void
-delegate_hash_table_add (MonoDelegate *d);
+delegate_hash_table_add (MonoDelegateHandle d);
 
 static void
 delegate_hash_table_remove (MonoDelegate *d);
@@ -155,7 +156,7 @@ mono_marshal_isinst_with_cache (MonoObject *obj, MonoClass *klass, uintptr_t *ca
 static void init_safe_handle (void);
 
 static void*
-ves_icall_marshal_alloc (gulong size);
+ves_icall_marshal_alloc (gsize size);
 
 void
 mono_string_utf8_to_builder (MonoStringBuilder *sb, char *text);
@@ -178,9 +179,15 @@ mono_string_to_byvalwstr (gpointer dst, MonoString *src, int size);
 gpointer
 mono_delegate_to_ftnptr (MonoDelegate *delegate);
 
+gpointer
+mono_delegate_handle_to_ftnptr (MonoDelegateHandle delegate, MonoError *error);
+
 MonoDelegate*
 mono_ftnptr_to_delegate (MonoClass *klass, gpointer ftn);
 
+MonoDelegateHandle
+mono_ftnptr_to_delegate_handle (MonoClass *klass, gpointer ftn, MonoError *error);
+
 gpointer
 mono_array_to_savearray (MonoArray *array);
 
@@ -214,6 +221,12 @@ mono_icall_start (HandleStackMark *stackmark, MonoError *error);
 static void
 mono_icall_end (MonoThreadInfo *info, HandleStackMark *stackmark, MonoError *error);
 
+static MonoObjectHandle
+mono_icall_handle_new (gpointer rawobj);
+
+static MonoObjectHandle
+mono_icall_handle_new_interior (gpointer rawobj);
+
 /* 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");
@@ -272,6 +285,21 @@ mono_marshal_init_tls (void)
 static MonoObject*
 mono_object_isinst_icall (MonoObject *obj, MonoClass *klass)
 {
+       if (!klass)
+               return NULL;
+
+       /* This is called from stelemref so it is expected to succeed */
+       /* Fastpath */
+       if (mono_class_is_interface (klass)) {
+               MonoVTable *vt = obj->vtable;
+
+               if (!klass->inited)
+                       mono_class_init (klass);
+
+               if (MONO_VTABLE_IMPLEMENTS_INTERFACE (vt, klass->interface_id))
+                       return obj;
+       }
+
        MonoError error;
        MonoObject *result = mono_object_isinst_checked (obj, klass, &error);
        mono_error_set_pending_exception (&error);
@@ -296,6 +324,19 @@ ves_icall_mono_string_to_utf8 (MonoString *str)
        return result;
 }
 
+static MonoString*
+ves_icall_string_new_wrapper (const char *text)
+{
+       if (text) {
+               MonoError error;
+               MonoString *res = mono_string_new_checked (mono_domain_get (), text, &error);
+               mono_error_set_pending_exception (&error);
+               return res;
+       }
+
+       return NULL;
+}
+
 void
 mono_marshal_init (void)
 {
@@ -314,6 +355,7 @@ mono_marshal_init (void)
                register_icall (mono_string_from_byvalstr, "mono_string_from_byvalstr", "obj ptr int", FALSE);
                register_icall (mono_string_from_byvalwstr, "mono_string_from_byvalwstr", "obj ptr int", FALSE);
                register_icall (mono_string_new_wrapper, "mono_string_new_wrapper", "obj ptr", FALSE);
+               register_icall (ves_icall_string_new_wrapper, "ves_icall_string_new_wrapper", "obj ptr", FALSE);
                register_icall (mono_string_new_len_wrapper, "mono_string_new_len_wrapper", "obj ptr int", FALSE);
                register_icall (ves_icall_mono_string_to_utf8, "ves_icall_mono_string_to_utf8", "ptr obj", FALSE);
                register_icall (mono_string_to_utf8str, "mono_string_to_utf8str", "ptr obj", FALSE);
@@ -331,10 +373,10 @@ mono_marshal_init (void)
                register_icall (mono_ftnptr_to_delegate, "mono_ftnptr_to_delegate", "object ptr ptr", FALSE);
                register_icall (mono_marshal_asany, "mono_marshal_asany", "ptr object int32 int32", FALSE);
                register_icall (mono_marshal_free_asany, "mono_marshal_free_asany", "void object ptr int32 int32", FALSE);
-               register_icall (ves_icall_marshal_alloc, "ves_icall_marshal_alloc", "ptr int32", FALSE);
+               register_icall (ves_icall_marshal_alloc, "ves_icall_marshal_alloc", "ptr ptr", FALSE);
                register_icall (mono_marshal_free, "mono_marshal_free", "void ptr", FALSE);
-               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_marshal_set_last_error, "mono_marshal_set_last_error", "void", TRUE);
+               register_icall (mono_marshal_set_last_error_windows, "mono_marshal_set_last_error_windows", "void int32", TRUE);
                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);
@@ -347,8 +389,6 @@ mono_marshal_init (void)
                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);
-               register_icall (mono_context_get, "mono_context_get", "object", FALSE);
-               register_icall (mono_context_set, "mono_context_set", "void object", FALSE);
                register_icall (mono_gc_wbarrier_generic_nostore, "wb_generic", "void ptr", FALSE);
                register_icall (mono_gchandle_get_target, "mono_gchandle_get_target", "object int32", TRUE);
                register_icall (mono_gchandle_new, "mono_gchandle_new", "uint32 object bool", TRUE);
@@ -360,7 +400,8 @@ 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_full, "mono_handle_new_full", "ptr ptr bool", TRUE);
+               register_icall (mono_icall_handle_new, "mono_icall_handle_new", "ptr ptr", TRUE);
+               register_icall (mono_icall_handle_new_interior, "mono_icall_handle_new_interior", "ptr ptr", TRUE);
 
                mono_cominterop_init ();
                mono_remoting_init ();
@@ -396,25 +437,44 @@ mono_marshal_unlock_internal (void)
 
 /* This is a JIT icall, it sets the pending exception and return NULL on error */
 gpointer
-mono_delegate_to_ftnptr (MonoDelegate *delegate)
+mono_delegate_to_ftnptr (MonoDelegate *delegate_raw)
 {
+       HANDLE_FUNCTION_ENTER ();
        MonoError error;
+       MONO_HANDLE_DCL (MonoDelegate, delegate);
+       gpointer result = mono_delegate_handle_to_ftnptr (delegate, &error);
+       mono_error_set_pending_exception (&error);
+       HANDLE_FUNCTION_RETURN_VAL (result);
+}
+
+gpointer
+mono_delegate_handle_to_ftnptr (MonoDelegateHandle delegate, MonoError *error)
+{
+       HANDLE_FUNCTION_ENTER ();
+       gpointer result = NULL;
+       error_init (error);
        MonoMethod *method, *wrapper;
        MonoClass *klass;
        uint32_t target_handle = 0;
 
-       if (!delegate)
-               return NULL;
+       if (MONO_HANDLE_IS_NULL (delegate))
+               goto leave;
 
-       if (delegate->delegate_trampoline)
-               return delegate->delegate_trampoline;
+       if (MONO_HANDLE_GETVAL (delegate, delegate_trampoline)) {
+               result = MONO_HANDLE_GETVAL (delegate, delegate_trampoline);
+               goto leave;
+       }
 
-       klass = ((MonoObject *)delegate)->vtable->klass;
+       klass = mono_handle_class (delegate);
        g_assert (klass->delegate);
 
-       method = delegate->method;
-       if (delegate->method_is_virtual)
-               method = mono_object_get_virtual_method (delegate->target, method);
+       method = MONO_HANDLE_GETVAL (delegate, method);
+       if (MONO_HANDLE_GETVAL (delegate, method_is_virtual)) {
+               MonoObjectHandle delegate_target = MONO_HANDLE_NEW_GET (MonoObject, delegate, target);
+               method = mono_object_handle_get_virtual_method (delegate_target, method, error);
+               if (!is_ok (error))
+                       goto leave;
+       }
 
        if (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
                const char *exc_class, *exc_arg;
@@ -423,38 +483,39 @@ mono_delegate_to_ftnptr (MonoDelegate *delegate)
                ftnptr = mono_lookup_pinvoke_call (method, &exc_class, &exc_arg);
                if (!ftnptr) {
                        g_assert (exc_class);
-                       mono_set_pending_exception (mono_exception_from_name_msg (mono_defaults.corlib, "System", exc_class, exc_arg));
-                       return NULL;
+                       mono_error_set_generic_error (error, "System", exc_class, "%s", exc_arg);
+                       goto leave;
                }
-               return ftnptr;
+               result = ftnptr;
+               goto leave;
        }
 
-       if (delegate->target) {
+       MonoObjectHandle delegate_target = MONO_HANDLE_NEW_GET (MonoObject, delegate, target);
+       if (!MONO_HANDLE_IS_NULL (delegate_target)) {
                /* Produce a location which can be embedded in JITted code */
-               target_handle = mono_gchandle_new_weakref (delegate->target, FALSE);
+               target_handle = mono_gchandle_new_weakref (MONO_HANDLE_RAW (delegate_target), FALSE); /* FIXME: a version of mono_gchandle_new_weakref that takes a coop handle */
        }
 
-       wrapper = mono_marshal_get_managed_wrapper (method, klass, target_handle, &error);
-       if (!is_ok (&error))
-               goto fail;
+       wrapper = mono_marshal_get_managed_wrapper (method, klass, target_handle, error);
+       if (!is_ok (error))
+               goto leave;
 
-       delegate->delegate_trampoline = mono_compile_method_checked (wrapper, &error);
-       if (!is_ok (&error))
-               goto fail;
+       MONO_HANDLE_SETVAL (delegate, delegate_trampoline, gpointer, mono_compile_method_checked (wrapper, error));
+       if (!is_ok (error))
+               goto leave;
 
        // Add the delegate to the delegate hash table
        delegate_hash_table_add (delegate);
 
        /* when the object is collected, collect the dynamic method, too */
-       mono_object_register_finalizer ((MonoObject*)delegate);
+       mono_object_register_finalizer ((MonoObject*) MONO_HANDLE_RAW (delegate));
 
-       return delegate->delegate_trampoline;
+       result = MONO_HANDLE_GETVAL (delegate, delegate_trampoline);
 
-fail:
-       if (target_handle != 0)
+leave:
+       if (!is_ok (error) && target_handle != 0)
                mono_gchandle_free (target_handle);
-       mono_error_set_pending_exception (&error);
-       return NULL;
+       HANDLE_FUNCTION_RETURN_VAL (result);
 }
 
 /* 
@@ -486,7 +547,7 @@ delegate_hash_table_remove (MonoDelegate *d)
 }
 
 static void
-delegate_hash_table_add (MonoDelegate *d)
+delegate_hash_table_add (MonoDelegateHandle d)
 {
        guint32 gchandle;
        guint32 old_gchandle;
@@ -494,14 +555,15 @@ delegate_hash_table_add (MonoDelegate *d)
        mono_marshal_lock ();
        if (delegate_hash_table == NULL)
                delegate_hash_table = delegate_hash_table_new ();
+       gpointer delegate_trampoline = MONO_HANDLE_GETVAL (d, delegate_trampoline);
        if (mono_gc_is_moving ()) {
-               gchandle = mono_gchandle_new_weakref ((MonoObject*)d, FALSE);
-               old_gchandle = GPOINTER_TO_UINT (g_hash_table_lookup (delegate_hash_table, d->delegate_trampoline));
-               g_hash_table_insert (delegate_hash_table, d->delegate_trampoline, GUINT_TO_POINTER (gchandle));
+               gchandle = mono_gchandle_new_weakref ((MonoObject*) MONO_HANDLE_RAW (d), FALSE);
+               old_gchandle = GPOINTER_TO_UINT (g_hash_table_lookup (delegate_hash_table, delegate_trampoline));
+               g_hash_table_insert (delegate_hash_table, delegate_trampoline, GUINT_TO_POINTER (gchandle));
                if (old_gchandle)
                        mono_gchandle_free (old_gchandle);
        } else {
-               g_hash_table_insert (delegate_hash_table, d->delegate_trampoline, d);
+               g_hash_table_insert (delegate_hash_table, delegate_trampoline, MONO_HANDLE_RAW (d));
        }
        mono_marshal_unlock ();
 }
@@ -555,12 +617,23 @@ parse_unmanaged_function_pointer_attr (MonoClass *klass, MonoMethodPInvoke *piin
 MonoDelegate*
 mono_ftnptr_to_delegate (MonoClass *klass, gpointer ftn)
 {
+       HANDLE_FUNCTION_ENTER ();
        MonoError error;
+       MonoDelegateHandle result = mono_ftnptr_to_delegate_handle (klass, ftn, &error);
+       mono_error_set_pending_exception (&error);
+       HANDLE_FUNCTION_RETURN_OBJ (result);
+}
+
+MonoDelegateHandle
+mono_ftnptr_to_delegate_handle (MonoClass *klass, gpointer ftn, MonoError *error)
+{
+       HANDLE_FUNCTION_ENTER ();
+       error_init (error);
        guint32 gchandle;
-       MonoDelegate *d;
+       MonoDelegateHandle d = MONO_HANDLE_NEW (MonoDelegate, NULL);
 
        if (ftn == NULL)
-               return NULL;
+               goto leave;
 
        mono_marshal_lock ();
        if (delegate_hash_table == NULL)
@@ -570,30 +643,26 @@ mono_ftnptr_to_delegate (MonoClass *klass, gpointer ftn)
                gchandle = GPOINTER_TO_UINT (g_hash_table_lookup (delegate_hash_table, ftn));
                mono_marshal_unlock ();
                if (gchandle)
-                       d = (MonoDelegate*)mono_gchandle_get_target (gchandle);
-               else
-                       d = NULL;
+                       MONO_HANDLE_ASSIGN (d, MONO_HANDLE_CAST (MonoDelegate, mono_gchandle_get_target_handle (gchandle)));
        } else {
-               d = (MonoDelegate *)g_hash_table_lookup (delegate_hash_table, ftn);
+               MONO_HANDLE_ASSIGN (d, MONO_HANDLE_NEW (MonoDelegate, g_hash_table_lookup (delegate_hash_table, ftn)));
                mono_marshal_unlock ();
        }
-       if (d == NULL) {
+       if (MONO_HANDLE_IS_NULL (d)) {
                /* This is a native function, so construct a delegate for it */
                MonoMethodSignature *sig;
                MonoMethod *wrapper;
                MonoMarshalSpec **mspecs;
                MonoMethod *invoke = mono_get_delegate_invoke (klass);
                MonoMethodPInvoke piinfo;
-               MonoObject *this_obj;
+               MonoObjectHandle  this_obj;
                int i;
 
                if (use_aot_wrappers) {
                        wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
-                       this_obj = mono_value_box_checked (mono_domain_get (), mono_defaults.int_class, &ftn, &error);
-                       if (!is_ok (&error)) {
-                               mono_error_set_pending_exception (&error);
-                               return NULL;
-                       }
+                       this_obj = MONO_HANDLE_NEW (MonoObject, mono_value_box_checked (mono_domain_get (), mono_defaults.int_class, &ftn, error));
+                       if (!is_ok (error))
+                               goto leave;
                } else {
                        memset (&piinfo, 0, sizeof (piinfo));
                        parse_unmanaged_function_pointer_attr (klass, &piinfo);
@@ -605,7 +674,7 @@ mono_ftnptr_to_delegate (MonoClass *klass, gpointer ftn)
                        sig->hasthis = 0;
 
                        wrapper = mono_marshal_get_native_func_wrapper (klass->image, sig, &piinfo, mspecs, ftn);
-                       this_obj = NULL;
+                       this_obj = MONO_HANDLE_NEW (MonoObject, NULL);
 
                        for (i = mono_method_signature (invoke)->param_count; i >= 0; i--)
                                if (mspecs [i])
@@ -614,25 +683,24 @@ mono_ftnptr_to_delegate (MonoClass *klass, gpointer ftn)
                        g_free (sig);
                }
 
-               d = (MonoDelegate*)mono_object_new_checked (mono_domain_get (), klass, &error);
-               if (!mono_error_ok (&error)) {
-                       mono_error_set_pending_exception (&error);
-                       return NULL;
-               }
-               gpointer compiled_ptr = mono_compile_method_checked (wrapper, &error);
-               if (mono_error_set_pending_exception (&error))
-                       return NULL;
-               mono_delegate_ctor_with_method ((MonoObject*)d, this_obj, compiled_ptr, wrapper, &error);
-               if (mono_error_set_pending_exception (&error))
-                       return NULL;
-       }
+               MONO_HANDLE_ASSIGN (d, MONO_HANDLE_NEW (MonoDelegate, mono_object_new_checked (mono_domain_get (), klass, error)));
+               if (!is_ok (error))
+                       goto leave;
+               gpointer compiled_ptr = mono_compile_method_checked (wrapper, error);
+               if (!is_ok (error))
+                       goto leave;
 
-       if (d->object.vtable->domain != mono_domain_get ()) {
-               mono_set_pending_exception (mono_get_exception_not_supported ("Delegates cannot be marshalled from native code into a domain other than their home domain"));
-               return NULL;
+               mono_delegate_ctor_with_method (MONO_HANDLE_CAST (MonoObject, d), this_obj, compiled_ptr, wrapper, error);
+               if (!is_ok (error))
+                       goto leave;
        }
 
-       return d;
+       g_assert (!MONO_HANDLE_IS_NULL (d));
+       if (MONO_HANDLE_DOMAIN (d) != mono_domain_get ())
+               mono_error_set_not_supported (error, "Delegates cannot be marshalled from native code into a domain other than their home domain");
+
+leave:
+       HANDLE_FUNCTION_RETURN_REF (MonoDelegate, d);
 }
 
 void
@@ -731,12 +799,13 @@ mono_array_to_lparray (MonoArray *array)
 
        int i = 0;
        MonoClass *klass;
+       MonoError error;
 #endif
 
        if (!array)
                return NULL;
 #ifndef DISABLE_COM
-
+       error_init (&error);
        klass = array->obj.vtable->klass;
 
        switch (klass->element_class->byval_arg.type) {
@@ -745,9 +814,12 @@ mono_array_to_lparray (MonoArray *array)
                break;
        case MONO_TYPE_CLASS:
                nativeArraySize = array->max_length;
-               nativeArray = (void **)malloc(sizeof(gpointer) * nativeArraySize);
-               for(i = 0; i < nativeArraySize; ++i)    
-                       nativeArray[i] = ves_icall_System_Runtime_InteropServices_Marshal_GetIUnknownForObjectInternal(((MonoObject **)array->vector)[i]);
+               nativeArray = (void **)g_malloc (sizeof(gpointer) * nativeArraySize);
+               for(i = 0; i < nativeArraySize; ++i) {
+                       nativeArray[i] = mono_cominterop_get_com_interface (((MonoObject **)array->vector)[i], klass->element_class, &error);
+                       if (mono_error_set_pending_exception (&error))
+                               break;
+               }
                return nativeArray;
        case MONO_TYPE_U1:
        case MONO_TYPE_BOOLEAN:
@@ -785,7 +857,6 @@ mono_free_lparray (MonoArray *array, gpointer* nativeArray)
 {
 #ifndef DISABLE_COM
        MonoClass *klass;
-       int i = 0;
 
        if (!array)
                return;
@@ -794,11 +865,8 @@ mono_free_lparray (MonoArray *array, gpointer* nativeArray)
                return;
        klass = array->obj.vtable->klass;
 
-       if (klass->element_class->byval_arg.type == MONO_TYPE_CLASS) {
-               for(i = 0; i < array->max_length; ++i)
-                       mono_marshal_free_ccw (mono_array_get (array, MonoObject*, i));
+       if (klass->element_class->byval_arg.type == MONO_TYPE_CLASS)
                g_free (nativeArray);
-       }
 #endif
 }
 
@@ -985,11 +1053,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.
  *
@@ -1036,11 +1104,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.
  *
@@ -1113,12 +1181,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)
@@ -1146,12 +1214,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
@@ -1184,7 +1252,7 @@ mono_string_new_len_wrapper (const char *text, guint length)
        return result;
 }
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
 
 /*
  * mono_mb_emit_exception_marshal_directive:
@@ -1204,8 +1272,7 @@ mono_mb_emit_exception_marshal_directive (MonoMethodBuilder *mb, char *msg)
        }
        mono_mb_emit_exception_full (mb, "System.Runtime.InteropServices", "MarshalDirectiveException", s);
 }
-
-#endif /* !DISABLE_JIT */
+#endif /* ENABLE_ILGEN */
 
 guint
 mono_type_to_ldind (MonoType *type)
@@ -1319,7 +1386,7 @@ handle_enum:
        return -1;
 }
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
 
 static void
 emit_ptr_to_object_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv conv, MonoMarshalSpec *mspec)
@@ -1462,7 +1529,7 @@ emit_ptr_to_object_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv
                } else {
                        mono_mb_emit_ldloc (mb, 1);
                        mono_mb_emit_ldloc (mb, 0);
-                       mono_mb_emit_icall (mb, mono_string_new_wrapper);
+                       mono_mb_emit_icall (mb, ves_icall_string_new_wrapper);
                }
                mono_mb_emit_byte (mb, CEE_STIND_REF);          
                break;
@@ -1486,7 +1553,7 @@ emit_ptr_to_object_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv
 #ifdef TARGET_WIN32
                mono_mb_emit_icall (mb, ves_icall_mono_string_from_utf16);
 #else
-               mono_mb_emit_icall (mb, mono_string_new_wrapper);
+               mono_mb_emit_icall (mb, ves_icall_string_new_wrapper);
 #endif
                mono_mb_emit_byte (mb, CEE_STIND_REF);  
                break;
@@ -1497,7 +1564,7 @@ emit_ptr_to_object_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv
                mono_mb_emit_ldloc (mb, 1);
                mono_mb_emit_ldloc (mb, 0);
                mono_mb_emit_byte (mb, CEE_LDIND_I);
-               mono_mb_emit_icall (mb, mono_string_new_wrapper);
+               mono_mb_emit_icall (mb, ves_icall_string_new_wrapper);
                mono_mb_emit_byte (mb, CEE_STIND_REF);          
                break;
        case MONO_MARSHAL_CONV_STR_LPWSTR:
@@ -1620,11 +1687,11 @@ conv_to_icall (MonoMarshalConv conv, int *ind_store_type)
                return ves_icall_mono_string_from_utf16;
        case MONO_MARSHAL_CONV_LPTSTR_STR:
                *ind_store_type = CEE_STIND_REF;
-               return mono_string_new_wrapper;
+               return ves_icall_string_new_wrapper;
        case MONO_MARSHAL_CONV_UTF8STR_STR:
        case MONO_MARSHAL_CONV_LPSTR_STR:
                *ind_store_type = CEE_STIND_REF;
-               return mono_string_new_wrapper;
+               return ves_icall_string_new_wrapper;
        case MONO_MARSHAL_CONV_STR_LPTSTR:
 #ifdef TARGET_WIN32
                return mono_marshal_string_to_utf16;
@@ -2396,7 +2463,7 @@ mono_marshal_emit_thread_force_interrupt_checkpoint (MonoMethodBuilder *mb)
        emit_thread_force_interrupt_checkpoint (mb);
 }
 
-#endif /* DISABLE_JIT */
+#endif /* ENABLE_ILGEN */
 
 /* This is a JIT icall, it sets the pending exception and returns NULL on error. */
 static MonoAsyncResult *
@@ -2465,7 +2532,7 @@ mono_delegate_begin_invoke (MonoDelegate *delegate, gpointer *params)
        return result;
 }
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
 
 int
 mono_mb_emit_save_args (MonoMethodBuilder *mb, MonoMethodSignature *sig, gboolean save_this)
@@ -2509,7 +2576,7 @@ mono_mb_emit_save_args (MonoMethodBuilder *mb, MonoMethodSignature *sig, gboolea
        return params_var;
 }
 
-#endif /* DISABLE_JIT */
+#endif /* ENABLE_ILGEN */
 
 static char*
 mono_signature_to_name (MonoMethodSignature *sig, const char *prefix)
@@ -2797,6 +2864,9 @@ mono_mb_create_and_cache (GHashTable *cache, gpointer key,
        return mono_mb_create_and_cache_full (cache, key, mb, sig, max_stack, NULL, NULL);
 }
 
+/**
+ * mono_marshal_method_from_wrapper:
+ */
 MonoMethod *
 mono_marshal_method_from_wrapper (MonoMethod *wrapper)
 {
@@ -3077,6 +3147,9 @@ cache_generic_delegate_wrapper (GHashTable *cache, MonoMethod *orig_method, Mono
        return res;
 }
 
+/**
+ * mono_marshal_get_delegate_begin_invoke:
+ */
 MonoMethod *
 mono_marshal_get_delegate_begin_invoke (MonoMethod *method)
 {
@@ -3128,7 +3201,7 @@ mono_marshal_get_delegate_begin_invoke (MonoMethod *method)
                mb = mono_mb_new (get_wrapper_target_class (method->klass->image), name, MONO_WRAPPER_DELEGATE_BEGIN_INVOKE);
        g_free (name);
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        params_var = mono_mb_emit_save_args (mb, sig, FALSE);
 
        mono_mb_emit_ldarg (mb, 0);
@@ -3234,10 +3307,13 @@ mono_delegate_end_invoke (MonoDelegate *delegate, gpointer *params)
                        if (is_ok (&inner_error)) {
                                char  *tmp;
                                tmp = g_strdup_printf ("%s\nException Rethrown at:\n", strace);
-                               g_free (strace);        
-                               MONO_OBJECT_SETREF (((MonoException*)exc), stack_trace, mono_string_new (domain, tmp));
+                               g_free (strace);
+                               MonoString *tmp_str = mono_string_new_checked (domain, tmp, &inner_error);
                                g_free (tmp);
-                       } else
+                               if (is_ok (&inner_error))
+                                       MONO_OBJECT_SETREF (((MonoException*)exc), stack_trace, tmp_str);
+                       };
+                       if (!is_ok (&inner_error))
                                mono_error_cleanup (&inner_error); /* no stack trace, but at least throw the original exception */
                }
                mono_set_pending_exception ((MonoException*)exc);
@@ -3248,7 +3324,7 @@ mono_delegate_end_invoke (MonoDelegate *delegate, gpointer *params)
        return res;
 }
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
 
 void
 mono_mb_emit_restore_result (MonoMethodBuilder *mb, MonoType *return_type)
@@ -3311,8 +3387,11 @@ mono_mb_emit_restore_result (MonoMethodBuilder *mb, MonoType *return_type)
        mono_mb_emit_byte (mb, CEE_RET);
 }
 
-#endif /* DISABLE_JIT */
+#endif /* ENABLE_ILGEN */
 
+/**
+ * mono_marshal_get_delegate_end_invoke:
+ */
 MonoMethod *
 mono_marshal_get_delegate_end_invoke (MonoMethod *method)
 {
@@ -3364,7 +3443,7 @@ mono_marshal_get_delegate_end_invoke (MonoMethod *method)
                mb = mono_mb_new (get_wrapper_target_class (method->klass->image), name, MONO_WRAPPER_DELEGATE_END_INVOKE);
        g_free (name);
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        params_var = mono_mb_emit_save_args (mb, sig, FALSE);
 
        mono_mb_emit_ldarg (mb, 0);
@@ -3566,7 +3645,7 @@ mono_marshal_get_delegate_invoke_internal (MonoMethod *method, gboolean callvirt
                mb = mono_mb_new (get_wrapper_target_class (method->klass->image), name, MONO_WRAPPER_DELEGATE_INVOKE);
        g_free (name);
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        void_ret = sig->ret->type == MONO_TYPE_VOID && !method->string_ctor;
 
        /* allocate local 0 (object) */
@@ -3733,7 +3812,7 @@ mono_marshal_get_delegate_invoke_internal (MonoMethod *method, gboolean callvirt
        mono_mb_emit_byte (mb, CEE_RET);
 
        mb->skip_visibility = 1;
-#endif /* DISABLE_JIT */
+#endif /* ENABLE_ILGEN */
 
        info = mono_wrapper_info_create (mb, subtype);
        info->d.delegate_invoke.method = method;
@@ -3760,8 +3839,9 @@ mono_marshal_get_delegate_invoke_internal (MonoMethod *method, gboolean callvirt
        return res;     
 }
 
-/*
- * the returned method invokes all methods in a multicast delegate.
+/**
+ * mono_marshal_get_delegate_invoke:
+ * The returned method invokes all methods in a multicast delegate.
  */
 MonoMethod *
 mono_marshal_get_delegate_invoke (MonoMethod *method, MonoDelegate *del)
@@ -3927,7 +4007,7 @@ runtime_invoke_signature_equal (MonoMethodSignature *sig1, MonoMethodSignature *
                return mono_metadata_signature_equal (sig1, sig2);
 }
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
 
 /*
  * emit_invoke_call:
@@ -3948,8 +4028,10 @@ emit_invoke_call (MonoMethodBuilder *mb, MonoMethod *method,
 
        /* to make it work with our special string constructors */
        if (!string_dummy) {
+               MonoError error;
                MONO_GC_REGISTER_ROOT_SINGLE (string_dummy, MONO_ROOT_SOURCE_MARSHAL, "dummy marshal string");
-               string_dummy = mono_string_new_wrapper ("dummy");
+               string_dummy = mono_string_new_checked (mono_get_root_domain (), "dummy", &error);
+               mono_error_assert_ok (&error);
        }
 
        if (virtual_) {
@@ -4211,18 +4293,20 @@ emit_runtime_invoke_body (MonoMethodBuilder *mb, MonoImage *image, MonoMethod *m
 }
 #endif
 
-/*
- * generates IL code for the runtime invoke function 
- * MonoObject *runtime_invoke (MonoObject *this_obj, void **params, MonoObject **exc, void* method)
+/**
+ * mono_marshal_get_runtime_invoke:
+ * Generates IL code for the runtime invoke function:
+ *
+ * <code>MonoObject *runtime_invoke (MonoObject *this_obj, void **params, MonoObject **exc, void* method)</code>
  *
- * we also catch exceptions if exc != null
- * If VIRTUAL is TRUE, then METHOD is invoked virtually on THIS. This is useful since
- * it means that the compiled code for METHOD does not have to be looked up 
+ * We also catch exceptions if \p exc is not NULL.
+ * If \p virtual is TRUE, then \p method is invoked virtually on \p this. This is useful since
+ * it means that the compiled code for \p method does not have to be looked up 
  * before calling the runtime invoke wrapper. In this case, the wrapper ignores
- * its METHOD argument.
+ * its \p method argument.
  */
 MonoMethod *
-mono_marshal_get_runtime_invoke (MonoMethod *method, gboolean virtual_)
+mono_marshal_get_runtime_invoke_full (MonoMethod *method, gboolean virtual_, gboolean need_direct_wrapper)
 {
        MonoMethodSignature *sig, *csig, *callsig;
        MonoMethodBuilder *mb;
@@ -4233,7 +4317,6 @@ mono_marshal_get_runtime_invoke (MonoMethod *method, gboolean virtual_)
        static MonoMethodSignature *finalize_signature = NULL;
        char *name;
        const char *param_names [16];
-       gboolean need_direct_wrapper = FALSE;
        WrapperInfo *info;
 
        g_assert (method);
@@ -4248,9 +4331,6 @@ mono_marshal_get_runtime_invoke (MonoMethod *method, gboolean virtual_)
                finalize_signature->hasthis = 1;
        }
 
-       if (virtual_)
-               need_direct_wrapper = TRUE;
-
        /* 
         * 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.
@@ -4264,21 +4344,10 @@ mono_marshal_get_runtime_invoke (MonoMethod *method, gboolean virtual_)
        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)
                        callsig = add_string_ctor_signature (method);
-               /* Can't share this as we push a string as this */
-               need_direct_wrapper = TRUE;
        } else {
                if (method_is_dynamic (method))
                        callsig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
@@ -4347,11 +4416,11 @@ mono_marshal_get_runtime_invoke (MonoMethod *method, gboolean virtual_)
        csig->call_convention = MONO_CALL_C;
 #endif
 
-       name = mono_signature_to_name (callsig, virtual_ ? "runtime_invoke_virtual" : "runtime_invoke");
+       name = mono_signature_to_name (callsig, virtual_ ? "runtime_invoke_virtual" : (need_direct_wrapper ? "runtime_invoke_direct" : "runtime_invoke"));
        mb = mono_mb_new (target_klass, name,  MONO_WRAPPER_RUNTIME_INVOKE);
        g_free (name);
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        param_names [0] = "this";
        param_names [1] = "params";
        param_names [2] = "exc";
@@ -4362,7 +4431,7 @@ mono_marshal_get_runtime_invoke (MonoMethod *method, gboolean virtual_)
 #endif
 
        if (need_direct_wrapper) {
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
                mb->skip_visibility = 1;
 #endif
                info = mono_wrapper_info_create (mb, virtual_ ? WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL : WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT);
@@ -4406,6 +4475,34 @@ mono_marshal_get_runtime_invoke (MonoMethod *method, gboolean virtual_)
        return res;     
 }
 
+MonoMethod *
+mono_marshal_get_runtime_invoke (MonoMethod *method, gboolean virtual_)
+{
+       gboolean need_direct_wrapper = FALSE;
+
+       if (virtual_)
+               need_direct_wrapper = TRUE;
+
+       if (method->dynamic)
+               need_direct_wrapper = TRUE;
+
+       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) {
+               /* Can't share this as we push a string as this */
+               need_direct_wrapper = TRUE;
+       }
+
+       return mono_marshal_get_runtime_invoke_full (method, virtual_, need_direct_wrapper);
+}
+
 /*
  * mono_marshal_get_runtime_invoke_dynamic:
  *
@@ -4446,7 +4543,7 @@ mono_marshal_get_runtime_invoke_dynamic (void)
        mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_RUNTIME_INVOKE);
        g_free (name);
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        /* allocate local 0 (object) tmp */
        mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
        /* allocate local 1 (object) exc */
@@ -4507,7 +4604,7 @@ mono_marshal_get_runtime_invoke_dynamic (void)
        mono_mb_patch_branch (mb, pos);
        //mono_mb_emit_ldloc (mb, 0);
        mono_mb_emit_byte (mb, CEE_RET);
-#endif /* DISABLE_JIT */
+#endif /* ENABLE_ILGEN */
 
        info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC);
 
@@ -4581,7 +4678,7 @@ mono_marshal_get_runtime_invoke_for_sig (MonoMethodSignature *sig)
        mb = mono_mb_new (mono_defaults.object_class, name,  MONO_WRAPPER_RUNTIME_INVOKE);
        g_free (name);
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        param_names [0] = "this";
        param_names [1] = "params";
        param_names [2] = "exc";
@@ -4622,7 +4719,7 @@ mono_marshal_get_runtime_invoke_for_sig (MonoMethodSignature *sig)
        return res;
 }
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
 static void
 mono_mb_emit_auto_layout_exception (MonoMethodBuilder *mb, MonoClass *klass)
 {
@@ -4633,9 +4730,10 @@ mono_mb_emit_auto_layout_exception (MonoMethodBuilder *mb, MonoClass *klass)
 }
 #endif
 
-/*
- * generates IL code for the icall wrapper (the generated method
- * calls the unmanaged code in func)
+/**
+ * mono_marshal_get_icall_wrapper:
+ * Generates IL code for the icall wrapper. The generated method
+ * calls the unmanaged code in \p func.
  */
 MonoMethod *
 mono_marshal_get_icall_wrapper (MonoMethodSignature *sig, const char *name, gconstpointer func, gboolean check_exceptions)
@@ -4662,7 +4760,7 @@ mono_marshal_get_icall_wrapper (MonoMethodSignature *sig, const char *name, gcon
        else
                csig2 = mono_metadata_signature_dup_full (mono_defaults.corlib, sig);
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        if (sig->hasthis)
                mono_mb_emit_byte (mb, CEE_LDARG_0);
 
@@ -4696,7 +4794,7 @@ emit_marshal_custom (EmitMarshalContext *m, int argnum, MonoType *t,
                                         int conv_arg, MonoType **conv_arg_type, 
                                         MarshalAction action)
 {
-#ifdef DISABLE_JIT
+#ifndef ENABLE_ILGEN
        if (action == MARSHAL_ACTION_CONV_IN && t->type == MONO_TYPE_VALUETYPE)
                *conv_arg_type = &mono_defaults.int_class->byval_arg;
        return conv_arg;
@@ -4768,7 +4866,6 @@ handle_exception:
                                mono_mb_emit_byte (mb, CEE_POP);
 
                        mono_mb_emit_exception_full (mb, "System", "ApplicationException", exception_msg);
-                       g_free (exception_msg);
 
                        break;
                case MARSHAL_ACTION_PUSH:
@@ -5013,7 +5110,7 @@ emit_marshal_asany (EmitMarshalContext *m, int argnum, MonoType *t,
                                        int conv_arg, MonoType **conv_arg_type, 
                                        MarshalAction action)
 {
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        MonoMethodBuilder *mb = m->mb;
 
        switch (action) {
@@ -5060,7 +5157,7 @@ emit_marshal_vtype (EmitMarshalContext *m, int argnum, MonoType *t,
                                        int conv_arg, MonoType **conv_arg_type, 
                                        MarshalAction action)
 {
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        MonoMethodBuilder *mb = m->mb;
        MonoClass *klass, *date_time_class;
        int pos = 0, pos2;
@@ -5337,7 +5434,7 @@ emit_marshal_string (EmitMarshalContext *m, int argnum, MonoType *t,
                                         int conv_arg, MonoType **conv_arg_type, 
                                         MarshalAction action)
 {
-#ifdef DISABLE_JIT
+#ifndef ENABLE_ILGEN
        switch (action) {
        case MARSHAL_ACTION_CONV_IN:
                *conv_arg_type = &mono_defaults.int_class->byval_arg;
@@ -5516,7 +5613,7 @@ emit_marshal_safehandle (EmitMarshalContext *m, int argnum, MonoType *t,
                         MonoMarshalSpec *spec, int conv_arg, 
                         MonoType **conv_arg_type, MarshalAction action)
 {
-#ifdef DISABLE_JIT
+#ifndef ENABLE_ILGEN
        if (action == MARSHAL_ACTION_CONV_IN)
                *conv_arg_type = &mono_defaults.int_class->byval_arg;
 #else
@@ -5680,7 +5777,7 @@ emit_marshal_handleref (EmitMarshalContext *m, int argnum, MonoType *t,
                        MonoMarshalSpec *spec, int conv_arg, 
                        MonoType **conv_arg_type, MarshalAction action)
 {
-#ifdef DISABLE_JIT
+#ifndef ENABLE_ILGEN
        if (action == MARSHAL_ACTION_CONV_IN)
                *conv_arg_type = &mono_defaults.int_class->byval_arg;
 #else
@@ -5747,7 +5844,7 @@ emit_marshal_object (EmitMarshalContext *m, int argnum, MonoType *t,
                     int conv_arg, MonoType **conv_arg_type, 
                     MarshalAction action)
 {
-#ifdef DISABLE_JIT
+#ifndef ENABLE_ILGEN
        if (action == MARSHAL_ACTION_CONV_IN)
                *conv_arg_type = &mono_defaults.int_class->byval_arg;
 #else
@@ -6014,8 +6111,10 @@ emit_marshal_object (EmitMarshalContext *m, int argnum, MonoType *t,
                        mono_mb_emit_ldloc (mb, 0);
                        mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL, NULL));
                        mono_mb_emit_stloc (mb, 3);
-               } else if (klass == mono_defaults.stringbuilder_class){
-                       // FIXME: implement
+               } else if (klass == mono_defaults.stringbuilder_class) {
+                       // FIXME:
+                       char *msg = g_strdup_printf ("Return marshalling of stringbuilders is not implemented.");
+                       mono_mb_emit_exception_marshal_directive (mb, msg);
                } else {
                        /* set src */
                        mono_mb_emit_stloc (mb, 0);
@@ -6247,8 +6346,7 @@ emit_marshal_object (EmitMarshalContext *m, int argnum, MonoType *t,
        return conv_arg;
 }
 
-#ifndef DISABLE_JIT
-
+#ifdef ENABLE_ILGEN
 #ifndef DISABLE_COM
 
 static int
@@ -6365,7 +6463,7 @@ emit_marshal_variant (EmitMarshalContext *m, int argnum, MonoType *t,
 }
 
 #endif /* DISABLE_COM */
-#endif /* DISABLE_JIT */
+#endif /* ENABLE_ILGEN */
 
 static gboolean
 mono_pinvoke_is_unicode (MonoMethodPInvoke *piinfo)
@@ -6392,7 +6490,7 @@ emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
                                        int conv_arg, MonoType **conv_arg_type, 
                                        MarshalAction action)
 {
-#ifdef DISABLE_JIT
+#ifndef ENABLE_ILGEN
        switch (action) {
        case MARSHAL_ACTION_CONV_IN:
                *conv_arg_type = &mono_defaults.object_class->byval_arg;
@@ -7161,7 +7259,7 @@ emit_marshal_boolean (EmitMarshalContext *m, int argnum, MonoType *t,
                      int conv_arg, MonoType **conv_arg_type, 
                      MarshalAction action)
 {
-#ifdef DISABLE_JIT
+#ifndef ENABLE_ILGEN
        switch (action) {
        case MARSHAL_ACTION_CONV_IN:
                if (t->byref)
@@ -7330,7 +7428,7 @@ emit_marshal_ptr (EmitMarshalContext *m, int argnum, MonoType *t,
                  MonoMarshalSpec *spec, int conv_arg, 
                  MonoType **conv_arg_type, MarshalAction action)
 {
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        MonoMethodBuilder *mb = m->mb;
 
        switch (action) {
@@ -7365,7 +7463,7 @@ emit_marshal_char (EmitMarshalContext *m, int argnum, MonoType *t,
                   MonoMarshalSpec *spec, int conv_arg, 
                   MonoType **conv_arg_type, MarshalAction action)
 {
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        MonoMethodBuilder *mb = m->mb;
 
        switch (action) {
@@ -7393,7 +7491,7 @@ emit_marshal_scalar (EmitMarshalContext *m, int argnum, MonoType *t,
                     MonoMarshalSpec *spec, int conv_arg, 
                     MonoType **conv_arg_type, MarshalAction action)
 {
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        MonoMethodBuilder *mb = m->mb;
 
        switch (action) {
@@ -7437,7 +7535,7 @@ emit_marshal (EmitMarshalContext *m, int argnum, MonoType *t,
                return emit_marshal_string (m, argnum, t, spec, conv_arg, conv_arg_type, action);
        case MONO_TYPE_CLASS:
        case MONO_TYPE_OBJECT:
-#if !defined(DISABLE_COM) && !defined(DISABLE_JIT)
+#if !defined(DISABLE_COM) && defined(ENABLE_ILGEN)
                if (spec && spec->native == MONO_NATIVE_STRUCT)
                        return emit_marshal_variant (m, argnum, t, spec, conv_arg, conv_arg_type, action);
 #endif
@@ -7500,6 +7598,9 @@ typedef enum {
        /* 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,
+       /* Initialized an object handle to null, pass to the icalls,
+          write the value out from the handle when the icall returns */
+       ICALL_HANDLES_WRAP_OBJ_OUT,
        /* 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,
@@ -7521,7 +7622,12 @@ 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;
+               if (mono_signature_param_is_out (sig, param))
+                       return ICALL_HANDLES_WRAP_OBJ_OUT;
+               else if (mono_type_is_byref (sig->params [param]))
+                       return ICALL_HANDLES_WRAP_OBJ_INOUT;
+               else
+                       return ICALL_HANDLES_WRAP_OBJ;
        } else if (mono_type_is_byref (sig->params [param]))
                return ICALL_HANDLES_WRAP_VALUETYPE_REF;
        else
@@ -7529,19 +7635,19 @@ signature_param_uses_handles (MonoMethodSignature *sig, int param)
 }
 
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
 /**
  * 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)
@@ -7552,6 +7658,9 @@ mono_marshal_emit_native_wrapper (MonoImage *image, MonoMethodBuilder *mb, MonoM
        int i, argnum, *tmp_locals;
        int type, param_shift = 0;
        int coop_gc_stack_dummy, coop_gc_var;
+#ifndef DISABLE_COM
+       int coop_cominterop_fnptr;
+#endif
 
        memset (&m, 0, sizeof (m));
        m.mb = mb;
@@ -7589,11 +7698,16 @@ mono_marshal_emit_native_wrapper (MonoImage *image, MonoMethodBuilder *mb, MonoM
                mono_mb_add_local (mb, sig->ret);
        }
 
-       if (mono_threads_is_coop_enabled ()) {
+       if (mono_threads_is_blocking_transition_enabled ()) {
                /* local 4, dummy local used to get a stack address for suspend funcs */
                coop_gc_stack_dummy = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
                /* local 5, the local to be used when calling the suspend funcs */
                coop_gc_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
+#ifndef DISABLE_COM
+               if (!func_param && MONO_CLASS_IS_IMPORT (mb->method->klass)) {
+                       coop_cominterop_fnptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
+               }
+#endif
        }
 
        /*
@@ -7630,7 +7744,7 @@ mono_marshal_emit_native_wrapper (MonoImage *image, MonoMethodBuilder *mb, MonoM
        }
 
        // In coop mode need to register blocking state during native call
-       if (mono_threads_is_coop_enabled ()) {
+       if (mono_threads_is_blocking_transition_enabled ()) {
                // Perform an extra, early lookup of the function address, so any exceptions
                // potentially resulting from the lookup occur before entering blocking mode.
                if (!func_param && !MONO_CLASS_IS_IMPORT (mb->method->klass) && aot) {
@@ -7639,6 +7753,13 @@ mono_marshal_emit_native_wrapper (MonoImage *image, MonoMethodBuilder *mb, MonoM
                        mono_mb_emit_byte (mb, CEE_POP); // Result not needed yet
                }
 
+#ifndef DISABLE_COM
+               if (!func_param && MONO_CLASS_IS_IMPORT (mb->method->klass)) {
+                       mono_mb_emit_cominterop_get_function_pointer (mb, &piinfo->method);
+                       mono_mb_emit_stloc (mb, coop_cominterop_fnptr);
+               }
+#endif
+
                mono_mb_emit_ldloc_addr (mb, coop_gc_stack_dummy);
                mono_mb_emit_icall (mb, mono_threads_enter_gc_safe_region_unbalanced);
                mono_mb_emit_stloc (mb, coop_gc_var);
@@ -7661,7 +7782,12 @@ mono_marshal_emit_native_wrapper (MonoImage *image, MonoMethodBuilder *mb, MonoM
                mono_mb_emit_calli (mb, csig);
        } else if (MONO_CLASS_IS_IMPORT (mb->method->klass)) {
 #ifndef DISABLE_COM
-               mono_mb_emit_cominterop_call (mb, csig, &piinfo->method);
+               if (!mono_threads_is_blocking_transition_enabled ()) {
+                       mono_mb_emit_cominterop_call (mb, csig, &piinfo->method);
+               } else {
+                       mono_mb_emit_ldloc (mb, coop_cominterop_fnptr);
+                       mono_mb_emit_cominterop_call_function_pointer (mb, csig);
+               }
 #else
                g_assert_not_reached ();
 #endif
@@ -7715,7 +7841,7 @@ mono_marshal_emit_native_wrapper (MonoImage *image, MonoMethodBuilder *mb, MonoM
        }
 
        /* Unblock before converting the result, since that can involve calls into the runtime */
-       if (mono_threads_is_coop_enabled ()) {
+       if (mono_threads_is_blocking_transition_enabled ()) {
                mono_mb_emit_ldloc (mb, coop_gc_var);
                mono_mb_emit_ldloc_addr (mb, coop_gc_stack_dummy);
                mono_mb_emit_icall (mb, mono_threads_exit_gc_safe_region_unbalanced);
@@ -7813,15 +7939,15 @@ mono_marshal_emit_native_wrapper (MonoImage *image, MonoMethodBuilder *mb, MonoM
 
        mono_mb_emit_byte (mb, CEE_RET);
 }
-#endif /* DISABLE_JIT */
+#endif /* ENABLE_ILGEN */
 
 /**
  * mono_marshal_get_native_wrapper:
- * @method: The MonoMethod to wrap.
- * @check_exceptions: Whenever to check for pending exceptions
+ * \param method The \c 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)
+ * Generates IL code for the pinvoke wrapper. The generated method
+ * calls the unmanaged code in \c piinfo->addr.
  */
 MonoMethod *
 mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions, gboolean aot)
@@ -7912,7 +8038,7 @@ mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions,
                                /* create a wrapper to preserve .ctor in stack trace */
                                mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_MANAGED);
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
                                mono_mb_emit_byte (mb, CEE_LDARG_0);
                                for (i = 1; i <= csig->param_count; i++)
                                        mono_mb_emit_ldarg (mb, i);
@@ -7946,7 +8072,7 @@ mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions,
         * registered in the runtime doing the AOT compilation.
         */
        if (!piinfo->addr && !aot) {
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
                mono_mb_emit_exception (mb, exc_class, exc_arg);
 #endif
                info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
@@ -7974,7 +8100,7 @@ mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions,
                if (method->string_ctor)
                        csig->ret = &mono_defaults.string_class->byval_arg;
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
                // FIXME:
                MonoClass *handle_stack_mark_class;
                MonoClass *error_class;
@@ -7983,8 +8109,8 @@ mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions,
                gboolean uses_handles = FALSE;
                gboolean save_handles_to_locals = FALSE;
                IcallHandlesLocal *handles_locals = NULL;
-               (void) mono_lookup_internal_call_full (method, &uses_handles);
 
+               (void) mono_lookup_internal_call_full (method, &uses_handles);
 
                /* If it uses handles and MonoError, it had better check exceptions */
                g_assert (!uses_handles || check_exceptions);
@@ -8006,8 +8132,9 @@ mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions,
                                switch (w) {
                                case ICALL_HANDLES_WRAP_OBJ:
                                case ICALL_HANDLES_WRAP_OBJ_INOUT:
+                               case ICALL_HANDLES_WRAP_OBJ_OUT:
                                        ret->params [i] = mono_class_get_byref_type (mono_class_from_mono_type(csig->params[i]));
-                                       if (w == ICALL_HANDLES_WRAP_OBJ_INOUT)
+                                       if (w == ICALL_HANDLES_WRAP_OBJ_OUT || w == ICALL_HANDLES_WRAP_OBJ_INOUT)
                                                save_handles_to_locals = TRUE;
                                        break;
                                case ICALL_HANDLES_WRAP_NONE:
@@ -8044,6 +8171,7 @@ mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions,
                                                handles_locals [j].handle = -1;
                                                break;
                                        case ICALL_HANDLES_WRAP_OBJ_INOUT:
+                                       case ICALL_HANDLES_WRAP_OBJ_OUT:
                                                handles_locals [j].handle = mono_mb_add_local (mb, sig->params [i]);
                                                break;
                                        default:
@@ -8076,8 +8204,7 @@ mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions,
                                mono_mb_emit_byte (mb, CEE_LDARG_0);
                                /* 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);
+                               mono_mb_emit_icall (mb, mono_icall_handle_new);
                        }
                        for (i = 0; i < sig->param_count; i++) {
                                /* load each argument. references into the managed heap get wrapped in handles */
@@ -8087,27 +8214,33 @@ mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions,
                                        mono_mb_emit_ldarg (mb, j);
                                        break;
                                case ICALL_HANDLES_WRAP_OBJ:
-                                       /* argI = mono_handle_new_full (argI_raw, FALSE) */
+                                       /* argI = mono_handle_new (argI_raw) */
                                        mono_mb_emit_ldarg (mb, j);
-                                       mono_mb_emit_byte (mb, CEE_LDC_I4_0);
-                                       mono_mb_emit_icall (mb, mono_handle_new_full);
+                                       mono_mb_emit_icall (mb, mono_icall_handle_new);
                                        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);
+                               case ICALL_HANDLES_WRAP_OBJ_OUT:
+                                       /* if inout:
+                                        *   handleI = argI = mono_handle_new (*argI_raw)
+                                        * otherwise:
+                                        *   handleI = argI = mono_handle_new (NULL)
+                                        */
+                                       if (handles_locals[j].wrap == ICALL_HANDLES_WRAP_OBJ_INOUT) {
+                                               mono_mb_emit_ldarg (mb, j);
+                                               mono_mb_emit_byte (mb, CEE_LDIND_REF);
+                                       } else
+                                               mono_mb_emit_byte (mb, CEE_LDNULL);
+                                       mono_mb_emit_icall (mb, mono_icall_handle_new);
                                        /* 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 */
+                                       /* (void) mono_handle_new (argI); 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_icall (mb, mono_icall_handle_new_interior);
                                        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);
@@ -8154,6 +8287,7 @@ mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions,
                                        case ICALL_HANDLES_WRAP_VALUETYPE_REF:
                                                break;
                                        case ICALL_HANDLES_WRAP_OBJ_INOUT:
+                                       case ICALL_HANDLES_WRAP_OBJ_OUT:
                                                /* *argI_raw = MONO_HANDLE_RAW (handleI) */
 
                                                /* argI_raw */
@@ -8199,7 +8333,7 @@ mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions,
        if (!aot)
                g_assert (piinfo->addr);
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        mspecs = g_new (MonoMarshalSpec*, sig->param_count + 1);
        mono_method_get_marshal_info (method, mspecs);
 
@@ -8214,7 +8348,7 @@ mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions,
                                                                                 info, NULL);
        mono_mb_free (mb);
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        for (i = sig->param_count; i >= 0; i--)
                if (mspecs [i])
                        mono_metadata_free_marshal_spec (mspecs [i]);
@@ -8228,11 +8362,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 *
@@ -8262,7 +8396,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;
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        mono_marshal_emit_native_wrapper (image, mb, sig, piinfo, mspecs, func, FALSE, TRUE, FALSE);
 #endif
 
@@ -8327,7 +8461,7 @@ mono_marshal_get_native_func_wrapper_aot (MonoClass *klass)
        mb = mono_mb_new (invoke->klass, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
        mb->method->save_lmf = 1;
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        mono_marshal_emit_native_wrapper (image, mb, sig, piinfo, mspecs, NULL, FALSE, TRUE, TRUE);
 #endif
 
@@ -8362,7 +8496,7 @@ mono_marshal_get_native_func_wrapper_aot (MonoClass *klass)
 void
 mono_marshal_emit_managed_wrapper (MonoMethodBuilder *mb, MonoMethodSignature *invoke_sig, MonoMarshalSpec **mspecs, EmitMarshalContext* m, MonoMethod *method, uint32_t target_handle)
 {
-#ifdef DISABLE_JIT
+#ifndef ENABLE_ILGEN
        MonoMethodSignature *sig, *csig;
        int i;
 
@@ -8476,7 +8610,7 @@ mono_marshal_emit_managed_wrapper (MonoMethodBuilder *mb, MonoMethodSignature *i
        /* try { */
        clause_catch->try_offset = clause_finally->try_offset = mono_mb_get_label (mb);
 
-       if (!mono_threads_is_coop_enabled ()) {
+       if (!mono_threads_is_blocking_transition_enabled ()) {
                mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
                mono_mb_emit_byte (mb, CEE_MONO_JIT_ATTACH);
        } else {
@@ -8484,6 +8618,10 @@ mono_marshal_emit_managed_wrapper (MonoMethodBuilder *mb, MonoMethodSignature *i
                mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
                mono_mb_emit_byte (mb, CEE_MONO_LDDOMAIN);
                mono_mb_emit_ldloc_addr (mb, attach_dummy_local);
+               /*
+                * This icall is special cased in the JIT so it works in native-to-managed wrappers in unattached threads.
+                * Keep this in sync with the CEE_JIT_ICALL code in the JIT.
+                */
                mono_mb_emit_icall (mb, mono_threads_attach_coop);
                mono_mb_emit_stloc (mb, attach_cookie_local);
        }
@@ -8654,7 +8792,7 @@ mono_marshal_emit_managed_wrapper (MonoMethodBuilder *mb, MonoMethodSignature *i
        clause_finally->try_len = mono_mb_get_label (mb) - clause_finally->try_offset;
        clause_finally->handler_offset = mono_mb_get_label (mb);
 
-       if (!mono_threads_is_coop_enabled ()) {
+       if (!mono_threads_is_blocking_transition_enabled ()) {
                mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
                mono_mb_emit_byte (mb, CEE_MONO_JIT_DETACH);
        } else {
@@ -8741,9 +8879,10 @@ mono_marshal_set_callconv_from_modopt (MonoMethod *method, MonoMethodSignature *
        }
 }
 
-/*
- * generates IL code to call managed methods from unmanaged code 
- * If target_handle==0, the wrapper info will be a WrapperInfo structure.
+/**
+ * mono_marshal_get_managed_wrapper:
+ * Generates IL code to call managed methods from unmanaged code 
+ * If \p target_handle is \c 0, the wrapper info will be a \c WrapperInfo structure.
  */
 MonoMethod *
 mono_marshal_get_managed_wrapper (MonoMethod *method, MonoClass *delegate_klass, uint32_t target_handle, MonoError *error)
@@ -8893,7 +9032,7 @@ mono_marshal_get_managed_wrapper (MonoMethod *method, MonoClass *delegate_klass,
                                                                                         mb, csig, sig->param_count + 16,
                                                                                         info, NULL);
        } else {
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
                mb->dynamic = TRUE;
 #endif
                res = mono_mb_create (mb, csig, sig->param_count + 16, NULL);
@@ -8956,7 +9095,7 @@ mono_marshal_get_vtfixup_ftnptr (MonoImage *image, guint32 token, guint16 type)
 
                mono_marshal_emit_managed_wrapper (mb, sig, mspecs, &m, method, 0);
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
                mb->dynamic = TRUE;
 #endif
                method = mono_mb_create (mb, csig, sig->param_count + 16, NULL);
@@ -8976,7 +9115,7 @@ mono_marshal_get_vtfixup_ftnptr (MonoImage *image, guint32 token, guint16 type)
        mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_MANAGED);
 
        param_count = sig->param_count + sig->hasthis;
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        for (i = 0; i < param_count; i++)
                mono_mb_emit_ldarg (mb, i);
 
@@ -8997,7 +9136,7 @@ mono_marshal_get_vtfixup_ftnptr (MonoImage *image, guint32 token, guint16 type)
        return compiled_ptr;
 }
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
 
 /*
  * The code directly following this is the cache hit, value positive branch
@@ -9060,10 +9199,11 @@ generate_check_cache (int obj_arg_position, int class_arg_position, int cache_ar
        mono_mb_emit_icall (mb, mono_marshal_isinst_with_cache);
 }
 
-#endif /* DISABLE_JIT */
+#endif /* ENABLE_ILGEN */
 
-/*
- * This does the equivalent of mono_object_castclass_with_cache.
+/**
+ * mono_marshal_get_castclass_with_cache:
+ * This does the equivalent of \c mono_object_castclass_with_cache.
  */
 MonoMethod *
 mono_marshal_get_castclass_with_cache (void)
@@ -9090,7 +9230,7 @@ mono_marshal_get_castclass_with_cache (void)
        sig->ret = &mono_defaults.object_class->byval_arg;
        sig->pinvoke = 0;
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        generate_check_cache (obj_arg_position, class_arg_position, cache_arg_position, 
                                                                                                &return_null_pos, &negative_cache_hit_pos, &positive_cache_hit_pos, mb);
        invalid_cast_pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
@@ -9109,7 +9249,7 @@ mono_marshal_get_castclass_with_cache (void)
        mono_mb_patch_branch (mb, return_null_pos);
        mono_mb_emit_byte (mb, CEE_LDNULL);
        mono_mb_emit_byte (mb, CEE_RET);
-#endif /* DISABLE_JIT */
+#endif /* ENABLE_ILGEN */
 
        info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE);
        res = mono_mb_create (mb, sig, 8, info);
@@ -9145,8 +9285,9 @@ mono_marshal_isinst_with_cache (MonoObject *obj, MonoClass *klass, uintptr_t *ca
        return isinst;
 }
 
-/*
- * This does the equivalent of mono_object_isinst_with_cache.
+/**
+ * mono_marshal_get_isinst_with_cache:
+ * This does the equivalent of \c mono_marshal_isinst_with_cache.
  */
 MonoMethod *
 mono_marshal_get_isinst_with_cache (void)
@@ -9176,7 +9317,7 @@ mono_marshal_get_isinst_with_cache (void)
        sig->ret = &mono_defaults.object_class->byval_arg;
        sig->pinvoke = 0;
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        generate_check_cache (obj_arg_position, class_arg_position, cache_arg_position, 
                &return_null_pos, &negative_cache_hit_pos, &positive_cache_hit_pos, mb);
        // Return the object gotten via the slow path.
@@ -9209,9 +9350,9 @@ 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)
+ * Generates IL code for <code>StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld)</code>
  */
 MonoMethod *
 mono_marshal_get_struct_to_ptr (MonoClass *klass)
@@ -9235,7 +9376,7 @@ mono_marshal_get_struct_to_ptr (MonoClass *klass)
 
        mb = mono_mb_new (klass, stoptr->name, MONO_WRAPPER_UNKNOWN);
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        if (klass->blittable) {
                mono_mb_emit_byte (mb, CEE_LDARG_1);
                mono_mb_emit_byte (mb, CEE_LDARG_0);
@@ -9283,9 +9424,8 @@ mono_marshal_get_struct_to_ptr (MonoClass *klass)
 
 /**
  * mono_marshal_get_ptr_to_struct:
- * @klass:
- *
- * generates IL code for PtrToStructure (IntPtr src, object structure)
+ * \param klass \c MonoClass
+ * Generates IL code for <code>PtrToStructure (IntPtr src, object structure)</code>
  */
 MonoMethod *
 mono_marshal_get_ptr_to_struct (MonoClass *klass)
@@ -9318,7 +9458,7 @@ mono_marshal_get_ptr_to_struct (MonoClass *klass)
 
        mb = mono_mb_new (klass, "PtrToStructure", MONO_WRAPPER_UNKNOWN);
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        if (klass->blittable) {
                mono_mb_emit_byte (mb, CEE_LDARG_1);
                mono_mb_emit_ldflda (mb, sizeof (MonoObject));
@@ -9386,7 +9526,7 @@ mono_marshal_get_synchronized_inner_wrapper (MonoMethod *method)
        }
 
        mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNKNOWN);
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        mono_mb_emit_exception_full (mb, "System", "ExecutionEngineException", "Shouldn't be called.");
        mono_mb_emit_byte (mb, CEE_RET);
 #endif
@@ -9404,9 +9544,10 @@ mono_marshal_get_synchronized_inner_wrapper (MonoMethod *method)
        return res;
 }
 
-/*
- * generates IL code for the synchronized wrapper: the generated method
- * calls METHOD while locking 'this' or the parent type.
+/**
+ * mono_marshal_get_synchronized_wrapper:
+ * Generates IL code for the synchronized wrapper: the generated method
+ * calls \p method while locking \c this or the parent type.
  */
 MonoMethod *
 mono_marshal_get_synchronized_wrapper (MonoMethod *method)
@@ -9461,7 +9602,7 @@ mono_marshal_get_synchronized_wrapper (MonoMethod *method)
        info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
        info->d.synchronized.method = method;
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        mb->skip_visibility = 1;
        /* result */
        if (!MONO_TYPE_IS_VOID (sig->ret))
@@ -9471,7 +9612,7 @@ mono_marshal_get_synchronized_wrapper (MonoMethod *method)
        if (method->klass->valuetype && !(method->flags & MONO_METHOD_ATTR_STATIC)) {
                /* FIXME Is this really the best way to signal an error here?  Isn't this called much later after class setup? -AK */
                mono_class_set_type_load_failure (method->klass, "");
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
                /* 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);
@@ -9489,7 +9630,7 @@ mono_marshal_get_synchronized_wrapper (MonoMethod *method)
                return res;
        }
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        /* this */
        this_local = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
        taken_local = mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
@@ -9521,7 +9662,7 @@ mono_marshal_get_synchronized_wrapper (MonoMethod *method)
 
        mono_marshal_unlock ();
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        /* Push this or the type object */
        if (method->flags & METHOD_ATTRIBUTE_STATIC) {
                /* We have special handling for this in the JIT */
@@ -9597,8 +9738,9 @@ mono_marshal_get_synchronized_wrapper (MonoMethod *method)
 }
 
 
-/*
- * the returned method calls 'method' unboxing the this argument
+/**
+ * mono_marshal_get_unbox_wrapper:
+ * The returned method calls \p method unboxing the \c this argument.
  */
 MonoMethod *
 mono_marshal_get_unbox_wrapper (MonoMethod *method)
@@ -9619,7 +9761,7 @@ mono_marshal_get_unbox_wrapper (MonoMethod *method)
 
        g_assert (sig->hasthis);
        
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        mono_mb_emit_ldarg (mb, 0); 
        mono_mb_emit_icon (mb, sizeof (MonoObject));
        mono_mb_emit_byte (mb, CEE_ADD);
@@ -9645,13 +9787,14 @@ enum {
        STELEMREF_OBJECT, /*no check at all*/
        STELEMREF_SEALED_CLASS, /*check vtable->klass->element_type */
        STELEMREF_CLASS, /*only the klass->parents check*/
+       STELEMREF_CLASS_SMALL_IDEPTH, /* like STELEMREF_CLASS bit without the idepth check */
        STELEMREF_INTERFACE, /*interfaces without variant generic arguments. */
        STELEMREF_COMPLEX, /*arrays, MBR or types with variant generic args - go straight to icalls*/
        STELEMREF_KIND_COUNT
 };
 
 static const char *strelemref_wrapper_name[] = {
-       "object", "sealed_class", "class", "interface", "complex"
+       "object", "sealed_class", "class", "class_small_idepth", "interface", "complex"
 };
 
 static gboolean
@@ -9684,10 +9827,13 @@ get_virtual_stelemref_kind (MonoClass *element_class)
                return STELEMREF_COMPLEX;
        if (mono_class_is_sealed (element_class))
                return STELEMREF_SEALED_CLASS;
+       if (element_class->idepth <= MONO_DEFAULT_SUPERTABLE_SIZE)
+               return STELEMREF_CLASS_SMALL_IDEPTH;
+
        return STELEMREF_CLASS;
 }
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
 
 static void
 load_array_element_address (MonoMethodBuilder *mb)
@@ -9771,7 +9917,7 @@ get_virtual_stelemref_wrapper (int kind)
                signature = sig;
        }
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        param_names [0] = "index";
        param_names [1] = "value";
        mono_mb_set_param_names (mb, param_names);
@@ -9915,8 +10061,6 @@ get_virtual_stelemref_wrapper (int kind)
                break;
 
        case STELEMREF_CLASS: {
-               int b_fast;
-
                /*
                the method:
                <ldelema (bound check)>
@@ -9957,17 +10101,6 @@ 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);
-               mono_mb_emit_icall (mb, mono_object_isinst_icall);
-               b2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
-
                /* if (vklass->idepth < aklass->idepth) goto failue */
                mono_mb_emit_ldloc (mb, vklass);
                mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
@@ -9999,20 +10132,88 @@ 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);
                mono_mb_emit_byte (mb, CEE_RET);
 
                /* do_exception: */
-               mono_mb_patch_branch (mb, b2);
                mono_mb_patch_branch (mb, b3);
                mono_mb_patch_branch (mb, b4);
 
                mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
                break;
        }
+
+       case STELEMREF_CLASS_SMALL_IDEPTH:
+               /*
+               the method:
+               <ldelema (bound check)>
+               if (!value)
+                       goto do_store;
+
+               aklass = array->vtable->klass->element_class;
+               vklass = value->vtable->klass;
+
+               if (vklass->supertypes [aklass->idepth - 1] != aklass)
+                       goto do_exception;
+
+               do_store:
+                       *array_slot_addr = value;
+                       return;
+
+               long:
+                       throw new ArrayTypeMismatchException ();
+               */
+               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);
+
+               /* ldelema (implicit bound check) */
+               load_array_element_address (mb);
+               mono_mb_emit_stloc (mb, array_slot_addr);
+
+               /* if (!value) goto do_store */
+               mono_mb_emit_ldarg (mb, 2);
+               b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
+
+               /* aklass = array->vtable->klass->element_class */
+               load_array_class (mb, aklass);
+
+               /* vklass = value->vtable->klass */
+               load_value_class (mb, vklass);
+
+               /* if (vklass->supertypes [aklass->idepth - 1] != aklass) goto failure */
+               mono_mb_emit_ldloc (mb, vklass);
+               mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, supertypes));
+               mono_mb_emit_byte (mb, CEE_LDIND_I);
+
+               mono_mb_emit_ldloc (mb, aklass);
+               mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
+               mono_mb_emit_byte (mb, CEE_LDIND_U2);
+               mono_mb_emit_icon (mb, 1);
+               mono_mb_emit_byte (mb, CEE_SUB);
+               mono_mb_emit_icon (mb, sizeof (void*));
+               mono_mb_emit_byte (mb, CEE_MUL);
+               mono_mb_emit_byte (mb, CEE_ADD);
+               mono_mb_emit_byte (mb, CEE_LDIND_I);
+
+               mono_mb_emit_ldloc (mb, aklass);
+               b4 = mono_mb_emit_branch (mb, CEE_BNE_UN);
+
+               /* do_store: */
+               mono_mb_patch_branch (mb, b1);
+               mono_mb_emit_ldloc (mb, array_slot_addr);
+               mono_mb_emit_ldarg (mb, 2);
+               mono_mb_emit_byte (mb, CEE_STIND_REF);
+               mono_mb_emit_byte (mb, CEE_RET);
+
+               /* do_exception: */
+               mono_mb_patch_branch (mb, b4);
+
+               mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
+               break;
+
        case STELEMREF_INTERFACE:
                /*Mono *klass;
                MonoVTable *vt;
@@ -10116,7 +10317,7 @@ get_virtual_stelemref_wrapper (int kind)
                mono_mb_emit_byte (mb, CEE_RET);
                g_assert (0);
        }
-#endif /* DISABLE_JIT */
+#endif /* ENABLE_ILGEN */
        info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_VIRTUAL_STELEMREF);
        info->d.virtual_stelemref.kind = kind;
        res = mono_mb_create (mb, signature, 4, info);
@@ -10159,6 +10360,9 @@ mono_marshal_get_virtual_stelemref_wrappers (int *nwrappers)
        return res;
 }
 
+/**
+ * mono_marshal_get_stelemref:
+ */
 MonoMethod*
 mono_marshal_get_stelemref (void)
 {
@@ -10186,7 +10390,7 @@ mono_marshal_get_stelemref (void)
        sig->params [1] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
        sig->params [2] = &mono_defaults.object_class->byval_arg;
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        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);
@@ -10326,7 +10530,7 @@ mono_marshal_get_gsharedvt_in_wrapper (void)
        sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
        sig->ret = &mono_defaults.void_class->byval_arg;
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        /*
         * The body is generated by the JIT, we use a wrapper instead of a trampoline so EH works.
         */
@@ -10360,7 +10564,7 @@ mono_marshal_get_gsharedvt_out_wrapper (void)
        sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
        sig->ret = &mono_defaults.void_class->byval_arg;
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        /*
         * The body is generated by the JIT, we use a wrapper instead of a trampoline so EH works.
         */
@@ -10386,13 +10590,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*
@@ -10434,7 +10638,7 @@ mono_marshal_get_array_address (int rank, int elem_size)
        mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_MANAGED);
        g_free (name);
        
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        bounds = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
        ind = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
        realidx = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
@@ -10530,7 +10734,7 @@ mono_marshal_get_array_address (int rank, int elem_size)
        mono_mb_emit_exception (mb, "IndexOutOfRangeException", NULL);
 
        g_free (branch_positions);
-#endif /* DISABLE_JIT */
+#endif /* ENABLE_ILGEN */
 
        info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ELEMENT_ADDR);
        info->d.element_addr.rank = rank;
@@ -10607,7 +10811,7 @@ mono_marshal_get_array_accessor_wrapper (MonoMethod *method)
 
        mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNKNOWN);
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        /* Call the method */
        if (sig->hasthis)
                mono_mb_emit_ldarg (mb, 0);
@@ -10653,8 +10857,11 @@ mono_marshal_alloc_co_task_mem (size_t size)
 }
 #endif
 
+/**
+ * mono_marshal_alloc:
+ */
 void*
-mono_marshal_alloc (gulong size, MonoError *error)
+mono_marshal_alloc (gsize size, MonoError *error)
 {
        gpointer res;
 
@@ -10669,7 +10876,7 @@ mono_marshal_alloc (gulong size, MonoError *error)
 
 /* This is a JIT icall, it sets the pending exception and returns NULL on error. */
 static void*
-ves_icall_marshal_alloc (gulong size)
+ves_icall_marshal_alloc (gsize size)
 {
        MonoError error;
        void *ret = mono_marshal_alloc (size, &error);
@@ -10690,12 +10897,18 @@ mono_marshal_free_co_task_mem (void *ptr)
 }
 #endif
 
+/**
+ * mono_marshal_free:
+ */
 void
 mono_marshal_free (gpointer ptr)
 {
        mono_marshal_free_co_task_mem (ptr);
 }
 
+/**
+ * mono_marshal_free_array:
+ */
 void
 mono_marshal_free_array (gpointer *ptr, int size) 
 {
@@ -10738,11 +10951,14 @@ mono_marshal_string_to_utf16_copy (MonoString *s)
  * mono_marshal_set_last_error:
  *
  * This function is invoked to set the last error value from a P/Invoke call
- * which has SetLastError set.
+ * which has \c SetLastError set.
  */
 void
 mono_marshal_set_last_error (void)
 {
+       /* This icall is called just after a P/Invoke call before the P/Invoke
+        * wrapper transitions the runtime back to running mode. */
+       MONO_REQ_GC_SAFE_MODE;
 #ifdef WIN32
        mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (GetLastError ()));
 #else
@@ -10754,6 +10970,9 @@ static void
 mono_marshal_set_last_error_windows (int error)
 {
 #ifdef WIN32
+       /* This icall is called just after a P/Invoke call before the P/Invoke
+        * wrapper transitions the runtime back to running mode. */
+       MONO_REQ_GC_SAFE_MODE;
        mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (error));
 #endif
 }
@@ -10827,13 +11046,14 @@ ves_icall_System_Runtime_InteropServices_Marshal_copy_from_unmanaged (gpointer s
        memcpy (dest_addr, src, length * element_size);
 }
 
-MonoString *
-ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi (char *ptr)
+MonoStringHandle
+ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi (char *ptr, MonoError *error)
 {
+       error_init (error);
        if (ptr == NULL)
-               return NULL;
+               return MONO_HANDLE_CAST (MonoString, NULL_HANDLE);
        else
-               return mono_string_new (mono_domain_get (), ptr);
+               return mono_string_new_handle (mono_domain_get (), ptr, error);
 }
 
 MonoString *
@@ -10901,18 +11121,23 @@ ves_icall_System_Runtime_InteropServices_Marshal_GetLastWin32Error (void)
 }
 
 guint32 
-ves_icall_System_Runtime_InteropServices_Marshal_SizeOf (MonoReflectionType *rtype)
+ves_icall_System_Runtime_InteropServices_Marshal_SizeOf (MonoReflectionTypeHandle rtype, MonoError *error)
 {
        MonoClass *klass;
        MonoType *type;
        guint32 layout;
 
-       MONO_CHECK_ARG_NULL (rtype, 0);
+       error_init (error);
+
+       if (MONO_HANDLE_IS_NULL (rtype)) {
+               mono_error_set_argument_null (error, "type", "");
+               return 0;
+       }
 
-       type = rtype->type;
+       type = MONO_HANDLE_GETVAL (rtype, type);
        klass = mono_class_from_mono_type (type);
        if (!mono_class_init (klass)) {
-               mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
+               mono_error_set_for_class_failure (error, klass);
                return 0;
        }
 
@@ -10921,13 +11146,7 @@ ves_icall_System_Runtime_InteropServices_Marshal_SizeOf (MonoReflectionType *rty
        if (type->type == MONO_TYPE_PTR || type->type == MONO_TYPE_FNPTR) {
                return sizeof (gpointer);
        } else if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
-               gchar *msg;
-               MonoException *exc;
-
-               msg = g_strdup_printf ("Type %s cannot be marshaled as an unmanaged structure.", klass->name);
-               exc = mono_get_exception_argument ("t", msg);
-               g_free (msg);
-               mono_set_pending_exception (exc);
+               mono_error_set_argument (error, "t", "Type %s cannot be marshaled as an unmanaged structure.", klass->name);
                return 0;
        }
 
@@ -11033,26 +11252,29 @@ ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure_type (gpointer s
 }
 
 int
-ves_icall_System_Runtime_InteropServices_Marshal_OffsetOf (MonoReflectionType *type, MonoString *field_name)
+ves_icall_System_Runtime_InteropServices_Marshal_OffsetOf (MonoReflectionTypeHandle ref_type, MonoStringHandle field_name, MonoError *error)
 {
-       MonoError error;
-       MonoMarshalType *info;
-       MonoClass *klass;
-       char *fname;
-       int match_index = -1;
-       
-       MONO_CHECK_ARG_NULL (type, 0);
-       MONO_CHECK_ARG_NULL (field_name, 0);
-
-       fname = mono_string_to_utf8_checked (field_name, &error);
-       if (mono_error_set_pending_exception (&error))
+       error_init (error);
+       if (MONO_HANDLE_IS_NULL (ref_type)) {
+               mono_error_set_argument_null (error, "type", "");
                return 0;
-       klass = mono_class_from_mono_type (type->type);
+       }
+       if (MONO_HANDLE_IS_NULL (field_name)) {
+               mono_error_set_argument_null (error, "fieldName", "");
+               return 0;
+       }
+
+       char *fname = mono_string_handle_to_utf8 (field_name, error);
+       return_val_if_nok (error, 0);
+
+       MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
+       MonoClass *klass = mono_class_from_mono_type (type);
        if (!mono_class_init (klass)) {
-               mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
+               mono_error_set_for_class_failure (error, klass);
                return 0;
        }
 
+       int match_index = -1;
        while (klass && match_index == -1) {
                MonoClassField* field;
                int i = 0;
@@ -11074,21 +11296,14 @@ ves_icall_System_Runtime_InteropServices_Marshal_OffsetOf (MonoReflectionType *t
        g_free (fname);
 
        if(match_index == -1) {
-               MonoException* exc;
-               gchar *tmp;
-
                /* Get back original class instance */
-               klass = mono_class_from_mono_type (type->type);
+               klass = mono_class_from_mono_type (type);
 
-               tmp = g_strdup_printf ("Field passed in is not a marshaled member of the type %s", klass->name);
-               exc = mono_get_exception_argument ("fieldName", tmp);
-               g_free (tmp);
-               mono_set_pending_exception ((MonoException*)exc);
+               mono_error_set_argument (error, "fieldName", "Field passed in is not a marshaled member of the type %s", klass->name);
                return 0;
        }
 
-       info = mono_marshal_load_type_info (klass);     
+       MonoMarshalType *info = mono_marshal_load_type_info (klass);
        return info->fields [match_index].offset;
 }
 
@@ -11314,22 +11529,24 @@ ves_icall_System_Runtime_InteropServices_Marshal_UnsafeAddrOfPinnedArrayElement
        return mono_array_addr_with_size_fast (arrayobj, mono_array_element_size (arrayobj->obj.vtable->klass), index);
 }
 
-MonoDelegate*
-ves_icall_System_Runtime_InteropServices_Marshal_GetDelegateForFunctionPointerInternal (void *ftn, MonoReflectionType *type)
+MonoDelegateHandle
+ves_icall_System_Runtime_InteropServices_Marshal_GetDelegateForFunctionPointerInternal (void *ftn, MonoReflectionTypeHandle type, MonoError *error)
 {
-       MonoClass *klass = mono_type_get_class (type->type);
+       error_init (error);
+       MonoClass *klass = mono_type_get_class (MONO_HANDLE_GETVAL (type, type));
        if (!mono_class_init (klass)) {
-               mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
+               mono_error_set_for_class_failure (error, klass);
                return NULL;
        }
 
-       return mono_ftnptr_to_delegate (klass, ftn);
+       return mono_ftnptr_to_delegate_handle (klass, ftn, error);
 }
 
 gpointer
-ves_icall_System_Runtime_InteropServices_Marshal_GetFunctionPointerForDelegateInternal (MonoDelegate *delegate)
+ves_icall_System_Runtime_InteropServices_Marshal_GetFunctionPointerForDelegateInternal (MonoDelegateHandle delegate, MonoError *error)
 {
-       return mono_delegate_to_ftnptr (delegate);
+       error_init (error);
+       return mono_delegate_handle_to_ftnptr (delegate, error);
 }
 
 /**
@@ -11349,9 +11566,9 @@ mono_marshal_is_loading_type_info (MonoClass *klass)
 /**
  * mono_marshal_load_type_info:
  *
- *  Initialize klass::marshal_info using information from metadata. This function can
+ * Initialize \c klass::marshal_info using information from metadata. This function can
  * recursively call itself, and the caller is responsible to avoid that by calling 
- * mono_marshal_is_loading_type_info () beforehand.
+ * \c mono_marshal_is_loading_type_info beforehand.
  *
  * LOCKING: Acquires the loader lock.
  */
@@ -11399,7 +11616,6 @@ mono_marshal_load_type_info (MonoClass* klass)
 
        layout = mono_class_get_flags (klass) & TYPE_ATTRIBUTE_LAYOUT_MASK;
 
-       /* The mempool is protected by the loader lock */
        info = (MonoMarshalType *)mono_image_alloc0 (klass->image, MONO_SIZEOF_MARSHAL_TYPE + sizeof (MonoMarshalField) * count);
        info->num_fields = count;
        
@@ -11486,8 +11702,11 @@ mono_marshal_load_type_info (MonoClass* klass)
        info->min_align = min_align;
 
        /* Update the class's blittable info, if the layouts don't match */
-       if (info->native_size != mono_class_value_size (klass, NULL))
+       if (info->native_size != mono_class_value_size (klass, NULL)) {
+               mono_loader_lock ();
                klass->blittable = FALSE;
+               mono_loader_unlock ();
+       }
 
        /* If this is an array type, ensure that we have element info */
        if (klass->rank && !mono_marshal_is_loading_type_info (klass->element_class)) {
@@ -11514,9 +11733,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
@@ -11624,6 +11842,9 @@ mono_type_native_stack_size (MonoType *t, guint32 *align)
        return 0;
 }
 
+/**
+ * mono_marshal_type_size:
+ */
 gint32
 mono_marshal_type_size (MonoType *type, MonoMarshalSpec *mspec, guint32 *align,
                        gboolean as_field, gboolean unicode)
@@ -11719,7 +11940,10 @@ mono_marshal_type_size (MonoType *type, MonoMarshalSpec *mspec, guint32 *align,
        return 0;
 }
 
-/* This is a JIT icall, it sets the pending exception and return NULL on error */
+/**
+ * mono_marshal_asany:
+ * This is a JIT icall, it sets the pending exception and returns NULL on error.
+ */
 gpointer
 mono_marshal_asany (MonoObject *o, MonoMarshalNative string_encoding, int param_attrs)
 {
@@ -11804,7 +12028,10 @@ mono_marshal_asany (MonoObject *o, MonoMarshalNative string_encoding, int param_
        return NULL;
 }
 
-/* This is a JIT icall, it sets the pending exception */
+/**
+ * mono_marshal_free_asany:
+ * This is a JIT icall, it sets the pending exception
+ */
 void
 mono_marshal_free_asany (MonoObject *o, gpointer ptr, MonoMarshalNative string_encoding, int param_attrs)
 {
@@ -11887,7 +12114,7 @@ mono_marshal_get_generic_array_helper (MonoClass *klass, gchar *name, MonoMethod
        csig = mono_metadata_signature_dup_full (method->klass->image, sig);
        csig->generic_param_count = 0;
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        mono_mb_emit_ldarg (mb, 0);
        for (i = 0; i < csig->param_count; i++)
                mono_mb_emit_ldarg (mb, i + 1);
@@ -12024,7 +12251,7 @@ mono_marshal_get_thunk_invoke_wrapper (MonoMethod *method)
        if (MONO_TYPE_ISSTRUCT (sig->ret))
                csig->ret = &mono_defaults.object_class->byval_arg;
 
-#ifndef DISABLE_JIT
+#ifdef ENABLE_ILGEN
        /* local 0 (temp for exception object) */
        mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
 
@@ -12165,7 +12392,7 @@ ftnptr_eh_callback_default (guint32 gchandle)
 
        mono_gchandle_free (gchandle);
 
-       mono_raise_exception (exc);
+       mono_reraise_exception (exc);
 }
 
 /*
@@ -12200,3 +12427,23 @@ mono_icall_end (MonoThreadInfo *info, HandleStackMark *stackmark, MonoError *err
        if (G_UNLIKELY (!is_ok (error)))
                mono_error_set_pending_exception (error);
 }
+
+static MonoObjectHandle
+mono_icall_handle_new (gpointer rawobj)
+{
+#ifdef MONO_HANDLE_TRACK_OWNER
+       return mono_handle_new (rawobj, "<marshal args>");
+#else
+       return mono_handle_new (rawobj);
+#endif
+}
+
+static MonoObjectHandle
+mono_icall_handle_new_interior (gpointer rawobj)
+{
+#ifdef MONO_HANDLE_TRACK_OWNER
+       return mono_handle_new_interior (rawobj, "<marshal args>");
+#else
+       return mono_handle_new_interior (rawobj);
+#endif
+}