3 * Routines for marshaling complex types in P/Invoke methods.
6 * Paolo Molaro (lupus@ximian.com)
8 * Copyright 2002-2003 Ximian, Inc (http://www.ximian.com)
9 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
10 * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
12 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
23 #include "metadata/marshal.h"
24 #include "metadata/marshal-internals.h"
25 #include "metadata/method-builder.h"
26 #include "metadata/tabledefs.h"
27 #include "metadata/exception.h"
28 #include "metadata/appdomain.h"
29 #include "mono/metadata/abi-details.h"
30 #include "mono/metadata/debug-helpers.h"
31 #include "mono/metadata/threads.h"
32 #include "mono/metadata/monitor.h"
33 #include "mono/metadata/class-internals.h"
34 #include "mono/metadata/metadata-internals.h"
35 #include "mono/metadata/domain-internals.h"
36 #include "mono/metadata/gc-internals.h"
37 #include "mono/metadata/threads-types.h"
38 #include "mono/metadata/string-icalls.h"
39 #include "mono/metadata/attrdefs.h"
40 #include "mono/metadata/cominterop.h"
41 #include "mono/metadata/remoting.h"
42 #include "mono/metadata/reflection-internals.h"
43 #include "mono/metadata/threadpool.h"
44 #include "mono/metadata/handle.h"
45 #include "mono/utils/mono-counters.h"
46 #include "mono/utils/mono-tls.h"
47 #include "mono/utils/mono-memory-model.h"
48 #include "mono/utils/atomic.h"
49 #include <mono/utils/mono-threads.h>
50 #include <mono/utils/mono-threads-coop.h>
51 #include <mono/utils/mono-error-internals.h>
56 /* #define DEBUG_RUNTIME_CODE */
58 #define OPDEF(a,b,c,d,e,f,g,h,i,j) \
62 #include "mono/cil/opcode.def"
68 * This mutex protects the various marshalling related caches in MonoImage
69 * and a few other data structures static to this file.
71 * The marshal lock is a non-recursive complex lock that sits below the domain lock in the
72 * runtime locking latice. Which means it can take simple locks suck as the image lock.
74 #define mono_marshal_lock() mono_locks_os_acquire (&marshal_mutex, MarshalLock)
75 #define mono_marshal_unlock() mono_locks_os_release (&marshal_mutex, MarshalLock)
76 static mono_mutex_t marshal_mutex;
77 static gboolean marshal_mutex_initialized;
79 static MonoNativeTlsKey last_error_tls_id;
81 static MonoNativeTlsKey load_type_info_tls_id;
83 static gboolean use_aot_wrappers;
85 static int class_marshal_info_count;
87 static void ftnptr_eh_callback_default (guint32 gchandle);
89 static MonoFtnPtrEHCallback ftnptr_eh_callback = ftnptr_eh_callback_default;
92 delegate_hash_table_add (MonoDelegateHandle d);
95 delegate_hash_table_remove (MonoDelegate *d);
98 emit_struct_conv (MonoMethodBuilder *mb, MonoClass *klass, gboolean to_object);
101 emit_struct_conv_full (MonoMethodBuilder *mb, MonoClass *klass, gboolean to_object, int offset_of_first_child_field, MonoMarshalNative string_encoding);
104 mono_struct_delete_old (MonoClass *klass, char *ptr);
107 mono_marshal_string_to_utf16 (MonoString *s);
110 mono_marshal_string_to_utf16_copy (MonoString *s);
114 mono_string_to_utf8str (MonoString *string_obj);
117 static MonoStringBuilder *
118 mono_string_utf8_to_builder2 (char *text);
120 static MonoStringBuilder *
121 mono_string_utf16_to_builder2 (gunichar2 *text);
124 mono_string_new_len_wrapper (const char *text, guint length);
127 mono_string_from_byvalstr (const char *data, int len);
130 mono_string_from_byvalwstr (gunichar2 *data, int len);
133 mono_byvalarray_to_array (MonoArray *arr, gpointer native_arr, MonoClass *eltype, guint32 elnum);
136 mono_byvalarray_to_byte_array (MonoArray *arr, gpointer native_arr, guint32 elnum);
139 mono_array_to_byvalarray (gpointer native_arr, MonoArray *arr, MonoClass *eltype, guint32 elnum);
142 mono_array_to_byte_byvalarray (gpointer native_arr, MonoArray *arr, guint32 elnum);
144 static MonoAsyncResult *
145 mono_delegate_begin_invoke (MonoDelegate *delegate, gpointer *params);
148 mono_delegate_end_invoke (MonoDelegate *delegate, gpointer *params);
151 mono_marshal_set_last_error_windows (int error);
154 mono_marshal_isinst_with_cache (MonoObject *obj, MonoClass *klass, uintptr_t *cache);
156 static void init_safe_handle (void);
159 ves_icall_marshal_alloc (gsize size);
162 mono_string_utf8_to_builder (MonoStringBuilder *sb, char *text);
165 mono_string_utf16_to_builder (MonoStringBuilder *sb, gunichar2 *text);
168 mono_string_builder_to_utf8 (MonoStringBuilder *sb);
171 mono_string_builder_to_utf16 (MonoStringBuilder *sb);
174 mono_string_to_byvalstr (gpointer dst, MonoString *src, int size);
177 mono_string_to_byvalwstr (gpointer dst, MonoString *src, int size);
180 mono_delegate_to_ftnptr (MonoDelegate *delegate);
183 mono_delegate_handle_to_ftnptr (MonoDelegateHandle delegate, MonoError *error);
186 mono_ftnptr_to_delegate (MonoClass *klass, gpointer ftn);
189 mono_ftnptr_to_delegate_handle (MonoClass *klass, gpointer ftn, MonoError *error);
192 mono_array_to_savearray (MonoArray *array);
195 mono_array_to_lparray (MonoArray *array);
198 mono_free_lparray (MonoArray *array, gpointer* nativeArray);
201 mono_marshal_asany (MonoObject *obj, MonoMarshalNative string_encoding, int param_attrs);
204 mono_marshal_free_asany (MonoObject *o, gpointer ptr, MonoMarshalNative string_encoding, int param_attrs);
207 mono_array_to_savearray (MonoArray *array);
210 mono_array_to_lparray (MonoArray *array);
213 mono_free_lparray (MonoArray *array, gpointer* nativeArray);
216 mono_marshal_ftnptr_eh_callback (guint32 gchandle);
218 static MonoThreadInfo*
219 mono_icall_start (HandleStackMark *stackmark, MonoError *error);
222 mono_icall_end (MonoThreadInfo *info, HandleStackMark *stackmark, MonoError *error);
224 static MonoObjectHandle
225 mono_icall_handle_new (gpointer rawobj);
227 static MonoObjectHandle
228 mono_icall_handle_new_interior (gpointer rawobj);
230 /* Lazy class loading functions */
231 static GENERATE_GET_CLASS_WITH_CACHE (string_builder, "System.Text", "StringBuilder");
232 static GENERATE_GET_CLASS_WITH_CACHE (date_time, "System", "DateTime");
233 static GENERATE_GET_CLASS_WITH_CACHE (fixed_buffer_attribute, "System.Runtime.CompilerServices", "FixedBufferAttribute");
234 static GENERATE_TRY_GET_CLASS_WITH_CACHE (unmanaged_function_pointer_attribute, "System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute");
235 static GENERATE_TRY_GET_CLASS_WITH_CACHE (icustom_marshaler, "System.Runtime.InteropServices", "ICustomMarshaler");
237 /* MonoMethod pointers to SafeHandle::DangerousAddRef and ::DangerousRelease */
238 static MonoMethod *sh_dangerous_add_ref;
239 static MonoMethod *sh_dangerous_release;
244 sh_dangerous_add_ref = mono_class_get_method_from_name (
245 mono_class_try_get_safehandle_class (), "DangerousAddRef", 1);
246 sh_dangerous_release = mono_class_get_method_from_name (
247 mono_class_try_get_safehandle_class (), "DangerousRelease", 0);
251 register_icall (gpointer func, const char *name, const char *sigstr, gboolean no_wrapper)
253 MonoMethodSignature *sig = mono_create_icall_signature (sigstr);
255 mono_register_jit_icall (func, name, sig, no_wrapper);
259 register_icall_no_wrapper (gpointer func, const char *name, const char *sigstr)
261 MonoMethodSignature *sig = mono_create_icall_signature (sigstr);
263 mono_register_jit_icall (func, name, sig, TRUE);
267 mono_signature_no_pinvoke (MonoMethod *method)
269 MonoMethodSignature *sig = mono_method_signature (method);
271 sig = mono_metadata_signature_dup_full (method->klass->image, sig);
272 sig->pinvoke = FALSE;
279 mono_marshal_init_tls (void)
281 mono_native_tls_alloc (&last_error_tls_id, NULL);
282 mono_native_tls_alloc (&load_type_info_tls_id, NULL);
286 mono_object_isinst_icall (MonoObject *obj, MonoClass *klass)
291 /* This is called from stelemref so it is expected to succeed */
293 if (mono_class_is_interface (klass)) {
294 MonoVTable *vt = obj->vtable;
297 mono_class_init (klass);
299 if (MONO_VTABLE_IMPLEMENTS_INTERFACE (vt, klass->interface_id))
304 MonoObject *result = mono_object_isinst_checked (obj, klass, &error);
305 mono_error_set_pending_exception (&error);
310 ves_icall_mono_string_from_utf16 (gunichar2 *data)
313 MonoString *result = mono_string_from_utf16_checked (data, &error);
314 mono_error_set_pending_exception (&error);
319 ves_icall_mono_string_to_utf8 (MonoString *str)
322 char *result = mono_string_to_utf8_checked (str, &error);
323 mono_error_set_pending_exception (&error);
328 ves_icall_string_new_wrapper (const char *text)
332 MonoString *res = mono_string_new_checked (mono_domain_get (), text, &error);
333 mono_error_set_pending_exception (&error);
341 mono_marshal_init (void)
343 static gboolean module_initialized = FALSE;
345 if (!module_initialized) {
346 module_initialized = TRUE;
347 mono_os_mutex_init_recursive (&marshal_mutex);
348 marshal_mutex_initialized = TRUE;
350 register_icall (ves_icall_System_Threading_Thread_ResetAbort, "ves_icall_System_Threading_Thread_ResetAbort", "void", TRUE);
351 register_icall (mono_marshal_string_to_utf16, "mono_marshal_string_to_utf16", "ptr obj", FALSE);
352 register_icall (mono_marshal_string_to_utf16_copy, "mono_marshal_string_to_utf16_copy", "ptr obj", FALSE);
353 register_icall (mono_string_to_utf16, "mono_string_to_utf16", "ptr obj", FALSE);
354 register_icall (ves_icall_mono_string_from_utf16, "ves_icall_mono_string_from_utf16", "obj ptr", FALSE);
355 register_icall (mono_string_from_byvalstr, "mono_string_from_byvalstr", "obj ptr int", FALSE);
356 register_icall (mono_string_from_byvalwstr, "mono_string_from_byvalwstr", "obj ptr int", FALSE);
357 register_icall (mono_string_new_wrapper, "mono_string_new_wrapper", "obj ptr", FALSE);
358 register_icall (ves_icall_string_new_wrapper, "ves_icall_string_new_wrapper", "obj ptr", FALSE);
359 register_icall (mono_string_new_len_wrapper, "mono_string_new_len_wrapper", "obj ptr int", FALSE);
360 register_icall (ves_icall_mono_string_to_utf8, "ves_icall_mono_string_to_utf8", "ptr obj", FALSE);
361 register_icall (mono_string_to_utf8str, "mono_string_to_utf8str", "ptr obj", FALSE);
362 register_icall (mono_string_to_ansibstr, "mono_string_to_ansibstr", "ptr object", FALSE);
363 register_icall (mono_string_builder_to_utf8, "mono_string_builder_to_utf8", "ptr object", FALSE);
364 register_icall (mono_string_builder_to_utf16, "mono_string_builder_to_utf16", "ptr object", FALSE);
365 register_icall (mono_array_to_savearray, "mono_array_to_savearray", "ptr object", FALSE);
366 register_icall (mono_array_to_lparray, "mono_array_to_lparray", "ptr object", FALSE);
367 register_icall (mono_free_lparray, "mono_free_lparray", "void object ptr", FALSE);
368 register_icall (mono_byvalarray_to_array, "mono_byvalarray_to_array", "void object ptr ptr int32", FALSE);
369 register_icall (mono_byvalarray_to_byte_array, "mono_byvalarray_to_byte_array", "void object ptr int32", FALSE);
370 register_icall (mono_array_to_byvalarray, "mono_array_to_byvalarray", "void ptr object ptr int32", FALSE);
371 register_icall (mono_array_to_byte_byvalarray, "mono_array_to_byte_byvalarray", "void ptr object int32", FALSE);
372 register_icall (mono_delegate_to_ftnptr, "mono_delegate_to_ftnptr", "ptr object", FALSE);
373 register_icall (mono_ftnptr_to_delegate, "mono_ftnptr_to_delegate", "object ptr ptr", FALSE);
374 register_icall (mono_marshal_asany, "mono_marshal_asany", "ptr object int32 int32", FALSE);
375 register_icall (mono_marshal_free_asany, "mono_marshal_free_asany", "void object ptr int32 int32", FALSE);
376 register_icall (ves_icall_marshal_alloc, "ves_icall_marshal_alloc", "ptr ptr", FALSE);
377 register_icall (mono_marshal_free, "mono_marshal_free", "void ptr", FALSE);
378 register_icall (mono_marshal_set_last_error, "mono_marshal_set_last_error", "void", FALSE);
379 register_icall (mono_marshal_set_last_error_windows, "mono_marshal_set_last_error_windows", "void int32", FALSE);
380 register_icall (mono_string_utf8_to_builder, "mono_string_utf8_to_builder", "void ptr ptr", FALSE);
381 register_icall (mono_string_utf8_to_builder2, "mono_string_utf8_to_builder2", "object ptr", FALSE);
382 register_icall (mono_string_utf16_to_builder, "mono_string_utf16_to_builder", "void ptr ptr", FALSE);
383 register_icall (mono_string_utf16_to_builder2, "mono_string_utf16_to_builder2", "object ptr", FALSE);
384 register_icall (mono_marshal_free_array, "mono_marshal_free_array", "void ptr int32", FALSE);
385 register_icall (mono_string_to_byvalstr, "mono_string_to_byvalstr", "void ptr ptr int32", FALSE);
386 register_icall (mono_string_to_byvalwstr, "mono_string_to_byvalwstr", "void ptr ptr int32", FALSE);
387 register_icall (g_free, "g_free", "void ptr", FALSE);
388 register_icall_no_wrapper (mono_object_isinst_icall, "mono_object_isinst_icall", "object object ptr");
389 register_icall (mono_struct_delete_old, "mono_struct_delete_old", "void ptr ptr", FALSE);
390 register_icall (mono_delegate_begin_invoke, "mono_delegate_begin_invoke", "object object ptr", FALSE);
391 register_icall (mono_delegate_end_invoke, "mono_delegate_end_invoke", "object object ptr", FALSE);
392 register_icall (mono_gc_wbarrier_generic_nostore, "wb_generic", "void ptr", FALSE);
393 register_icall (mono_gchandle_get_target, "mono_gchandle_get_target", "object int32", TRUE);
394 register_icall (mono_gchandle_new, "mono_gchandle_new", "uint32 object bool", TRUE);
395 register_icall (mono_marshal_isinst_with_cache, "mono_marshal_isinst_with_cache", "object object ptr ptr", FALSE);
396 register_icall (mono_marshal_ftnptr_eh_callback, "mono_marshal_ftnptr_eh_callback", "void uint32", TRUE);
397 register_icall (mono_threads_enter_gc_safe_region_unbalanced, "mono_threads_enter_gc_safe_region_unbalanced", "ptr ptr", TRUE);
398 register_icall (mono_threads_exit_gc_safe_region_unbalanced, "mono_threads_exit_gc_safe_region_unbalanced", "void ptr ptr", TRUE);
399 register_icall (mono_threads_attach_coop, "mono_threads_attach_coop", "ptr ptr ptr", TRUE);
400 register_icall (mono_threads_detach_coop, "mono_threads_detach_coop", "void ptr ptr", TRUE);
401 register_icall (mono_icall_start, "mono_icall_start", "ptr ptr ptr", TRUE);
402 register_icall (mono_icall_end, "mono_icall_end", "void ptr ptr ptr", TRUE);
403 register_icall (mono_icall_handle_new, "mono_icall_handle_new", "ptr ptr", TRUE);
404 register_icall (mono_icall_handle_new_interior, "mono_icall_handle_new_interior", "ptr ptr", TRUE);
406 mono_cominterop_init ();
407 mono_remoting_init ();
409 mono_counters_register ("MonoClass::class_marshal_info_count count",
410 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &class_marshal_info_count);
416 mono_marshal_cleanup (void)
418 mono_cominterop_cleanup ();
420 mono_native_tls_free (load_type_info_tls_id);
421 mono_native_tls_free (last_error_tls_id);
422 mono_os_mutex_destroy (&marshal_mutex);
423 marshal_mutex_initialized = FALSE;
427 mono_marshal_lock_internal (void)
429 mono_marshal_lock ();
433 mono_marshal_unlock_internal (void)
435 mono_marshal_unlock ();
438 /* This is a JIT icall, it sets the pending exception and return NULL on error */
440 mono_delegate_to_ftnptr (MonoDelegate *delegate_raw)
442 HANDLE_FUNCTION_ENTER ();
444 MONO_HANDLE_DCL (MonoDelegate, delegate);
445 gpointer result = mono_delegate_handle_to_ftnptr (delegate, &error);
446 mono_error_set_pending_exception (&error);
447 HANDLE_FUNCTION_RETURN_VAL (result);
451 mono_delegate_handle_to_ftnptr (MonoDelegateHandle delegate, MonoError *error)
453 HANDLE_FUNCTION_ENTER ();
454 gpointer result = NULL;
456 MonoMethod *method, *wrapper;
458 uint32_t target_handle = 0;
460 if (MONO_HANDLE_IS_NULL (delegate))
463 if (MONO_HANDLE_GETVAL (delegate, delegate_trampoline)) {
464 result = MONO_HANDLE_GETVAL (delegate, delegate_trampoline);
468 klass = mono_handle_class (delegate);
469 g_assert (klass->delegate);
471 method = MONO_HANDLE_GETVAL (delegate, method);
472 if (MONO_HANDLE_GETVAL (delegate, method_is_virtual)) {
473 MonoObjectHandle delegate_target = MONO_HANDLE_NEW_GET (MonoObject, delegate, target);
474 method = mono_object_handle_get_virtual_method (delegate_target, method, error);
479 if (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
480 const char *exc_class, *exc_arg;
483 ftnptr = mono_lookup_pinvoke_call (method, &exc_class, &exc_arg);
485 g_assert (exc_class);
486 mono_error_set_generic_error (error, "System", exc_class, "%s", exc_arg);
493 MonoObjectHandle delegate_target = MONO_HANDLE_NEW_GET (MonoObject, delegate, target);
494 if (!MONO_HANDLE_IS_NULL (delegate_target)) {
495 /* Produce a location which can be embedded in JITted code */
496 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 */
499 wrapper = mono_marshal_get_managed_wrapper (method, klass, target_handle, error);
503 MONO_HANDLE_SETVAL (delegate, delegate_trampoline, gpointer, mono_compile_method_checked (wrapper, error));
507 // Add the delegate to the delegate hash table
508 delegate_hash_table_add (delegate);
510 /* when the object is collected, collect the dynamic method, too */
511 mono_object_register_finalizer ((MonoObject*) MONO_HANDLE_RAW (delegate));
513 result = MONO_HANDLE_GETVAL (delegate, delegate_trampoline);
516 if (!is_ok (error) && target_handle != 0)
517 mono_gchandle_free (target_handle);
518 HANDLE_FUNCTION_RETURN_VAL (result);
522 * this hash table maps from a delegate trampoline object to a weak reference
523 * of the delegate. As an optimizations with a non-moving GC we store the
524 * object pointer itself, otherwise we use a GC handle.
526 static GHashTable *delegate_hash_table;
529 delegate_hash_table_new (void) {
530 return g_hash_table_new (NULL, NULL);
534 delegate_hash_table_remove (MonoDelegate *d)
536 guint32 gchandle = 0;
538 mono_marshal_lock ();
539 if (delegate_hash_table == NULL)
540 delegate_hash_table = delegate_hash_table_new ();
541 if (mono_gc_is_moving ())
542 gchandle = GPOINTER_TO_UINT (g_hash_table_lookup (delegate_hash_table, d->delegate_trampoline));
543 g_hash_table_remove (delegate_hash_table, d->delegate_trampoline);
544 mono_marshal_unlock ();
545 if (gchandle && mono_gc_is_moving ())
546 mono_gchandle_free (gchandle);
550 delegate_hash_table_add (MonoDelegateHandle d)
553 guint32 old_gchandle;
555 mono_marshal_lock ();
556 if (delegate_hash_table == NULL)
557 delegate_hash_table = delegate_hash_table_new ();
558 gpointer delegate_trampoline = MONO_HANDLE_GETVAL (d, delegate_trampoline);
559 if (mono_gc_is_moving ()) {
560 gchandle = mono_gchandle_new_weakref ((MonoObject*) MONO_HANDLE_RAW (d), FALSE);
561 old_gchandle = GPOINTER_TO_UINT (g_hash_table_lookup (delegate_hash_table, delegate_trampoline));
562 g_hash_table_insert (delegate_hash_table, delegate_trampoline, GUINT_TO_POINTER (gchandle));
564 mono_gchandle_free (old_gchandle);
566 g_hash_table_insert (delegate_hash_table, delegate_trampoline, MONO_HANDLE_RAW (d));
568 mono_marshal_unlock ();
572 * mono_marshal_use_aot_wrappers:
574 * Instructs this module to use AOT compatible wrappers.
577 mono_marshal_use_aot_wrappers (gboolean use)
579 use_aot_wrappers = use;
583 parse_unmanaged_function_pointer_attr (MonoClass *klass, MonoMethodPInvoke *piinfo)
586 MonoCustomAttrInfo *cinfo;
587 MonoReflectionUnmanagedFunctionPointerAttribute *attr;
589 /* The attribute is only available in Net 2.0 */
590 if (mono_class_try_get_unmanaged_function_pointer_attribute_class ()) {
592 * The pinvoke attributes are stored in a real custom attribute so we have to
595 cinfo = mono_custom_attrs_from_class_checked (klass, &error);
596 if (!mono_error_ok (&error)) {
597 g_warning ("Could not load UnmanagedFunctionPointerAttribute due to %s", mono_error_get_message (&error));
598 mono_error_cleanup (&error);
600 if (cinfo && !mono_runtime_get_no_exec ()) {
601 attr = (MonoReflectionUnmanagedFunctionPointerAttribute*)mono_custom_attrs_get_attr_checked (cinfo, mono_class_try_get_unmanaged_function_pointer_attribute_class (), &error);
603 piinfo->piflags = (attr->call_conv << 8) | (attr->charset ? (attr->charset - 1) * 2 : 1) | attr->set_last_error;
605 if (!mono_error_ok (&error)) {
606 g_warning ("Could not load UnmanagedFunctionPointerAttribute due to %s", mono_error_get_message (&error));
607 mono_error_cleanup (&error);
611 mono_custom_attrs_free (cinfo);
616 /* This is a JIT icall, it sets the pending exception and returns NULL on error */
618 mono_ftnptr_to_delegate (MonoClass *klass, gpointer ftn)
620 HANDLE_FUNCTION_ENTER ();
622 MonoDelegateHandle result = mono_ftnptr_to_delegate_handle (klass, ftn, &error);
623 mono_error_set_pending_exception (&error);
624 HANDLE_FUNCTION_RETURN_OBJ (result);
628 mono_ftnptr_to_delegate_handle (MonoClass *klass, gpointer ftn, MonoError *error)
630 HANDLE_FUNCTION_ENTER ();
633 MonoDelegateHandle d = MONO_HANDLE_NEW (MonoDelegate, NULL);
638 mono_marshal_lock ();
639 if (delegate_hash_table == NULL)
640 delegate_hash_table = delegate_hash_table_new ();
642 if (mono_gc_is_moving ()) {
643 gchandle = GPOINTER_TO_UINT (g_hash_table_lookup (delegate_hash_table, ftn));
644 mono_marshal_unlock ();
646 MONO_HANDLE_ASSIGN (d, MONO_HANDLE_CAST (MonoDelegate, mono_gchandle_get_target_handle (gchandle)));
648 MONO_HANDLE_ASSIGN (d, MONO_HANDLE_NEW (MonoDelegate, g_hash_table_lookup (delegate_hash_table, ftn)));
649 mono_marshal_unlock ();
651 if (MONO_HANDLE_IS_NULL (d)) {
652 /* This is a native function, so construct a delegate for it */
653 MonoMethodSignature *sig;
655 MonoMarshalSpec **mspecs;
656 MonoMethod *invoke = mono_get_delegate_invoke (klass);
657 MonoMethodPInvoke piinfo;
658 MonoObjectHandle this_obj;
661 if (use_aot_wrappers) {
662 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
663 this_obj = MONO_HANDLE_NEW (MonoObject, mono_value_box_checked (mono_domain_get (), mono_defaults.int_class, &ftn, error));
667 memset (&piinfo, 0, sizeof (piinfo));
668 parse_unmanaged_function_pointer_attr (klass, &piinfo);
670 mspecs = g_new0 (MonoMarshalSpec*, mono_method_signature (invoke)->param_count + 1);
671 mono_method_get_marshal_info (invoke, mspecs);
672 /* Freed below so don't alloc from mempool */
673 sig = mono_metadata_signature_dup (mono_method_signature (invoke));
676 wrapper = mono_marshal_get_native_func_wrapper (klass->image, sig, &piinfo, mspecs, ftn);
677 this_obj = MONO_HANDLE_NEW (MonoObject, NULL);
679 for (i = mono_method_signature (invoke)->param_count; i >= 0; i--)
681 mono_metadata_free_marshal_spec (mspecs [i]);
686 MONO_HANDLE_ASSIGN (d, MONO_HANDLE_NEW (MonoDelegate, mono_object_new_checked (mono_domain_get (), klass, error)));
689 gpointer compiled_ptr = mono_compile_method_checked (wrapper, error);
693 mono_delegate_ctor_with_method (MONO_HANDLE_CAST (MonoObject, d), this_obj, compiled_ptr, wrapper, error);
698 g_assert (!MONO_HANDLE_IS_NULL (d));
699 if (MONO_HANDLE_DOMAIN (d) != mono_domain_get ())
700 mono_error_set_not_supported (error, "Delegates cannot be marshalled from native code into a domain other than their home domain");
703 HANDLE_FUNCTION_RETURN_REF (MonoDelegate, d);
707 mono_delegate_free_ftnptr (MonoDelegate *delegate)
712 delegate_hash_table_remove (delegate);
714 ptr = (gpointer)InterlockedExchangePointer (&delegate->delegate_trampoline, NULL);
716 if (!delegate->target) {
717 /* The wrapper method is shared between delegates -> no need to free it */
726 ji = mono_jit_info_table_find (mono_domain_get (), (char *)mono_get_addr_from_ftnptr (ptr));
729 method = mono_jit_info_get_method (ji);
730 method_data = (void **)((MonoMethodWrapper*)method)->method_data;
732 /*the target gchandle is the first entry after size and the wrapper itself.*/
733 gchandle = GPOINTER_TO_UINT (method_data [2]);
736 mono_gchandle_free (gchandle);
738 mono_runtime_free_method (mono_object_domain (delegate), method);
742 /* This is a JIT icall, it sets the pending exception and returns NULL on error */
744 mono_string_from_byvalstr (const char *data, int max_len)
747 MonoDomain *domain = mono_domain_get ();
753 while (len < max_len - 1 && data [len])
756 MonoString *result = mono_string_new_len_checked (domain, data, len, &error);
757 mono_error_set_pending_exception (&error);
761 /* This is a JIT icall, it sets the pending exception and return NULL on error */
763 mono_string_from_byvalwstr (gunichar2 *data, int max_len)
766 MonoString *res = NULL;
767 MonoDomain *domain = mono_domain_get ();
773 while (data [len]) len++;
775 res = mono_string_new_utf16_checked (domain, data, MIN (len, max_len), &error);
776 if (!mono_error_ok (&error)) {
777 mono_error_set_pending_exception (&error);
784 mono_array_to_savearray (MonoArray *array)
789 g_assert_not_reached ();
794 mono_array_to_lparray (MonoArray *array)
797 gpointer *nativeArray = NULL;
798 int nativeArraySize = 0;
808 klass = array->obj.vtable->klass;
810 switch (klass->element_class->byval_arg.type) {
812 g_assert_not_reached ();
814 case MONO_TYPE_CLASS:
815 nativeArraySize = array->max_length;
816 nativeArray = (void **)malloc(sizeof(gpointer) * nativeArraySize);
817 for(i = 0; i < nativeArraySize; ++i)
818 nativeArray[i] = ves_icall_System_Runtime_InteropServices_Marshal_GetIUnknownForObjectInternal(((MonoObject **)array->vector)[i]);
821 case MONO_TYPE_BOOLEAN:
834 case MONO_TYPE_VALUETYPE:
838 case MONO_TYPE_GENERICINST:
839 case MONO_TYPE_OBJECT:
840 case MONO_TYPE_ARRAY:
841 case MONO_TYPE_SZARRAY:
842 case MONO_TYPE_STRING:
844 g_warning ("type 0x%x not handled", klass->element_class->byval_arg.type);
845 g_assert_not_reached ();
848 return array->vector;
852 mono_free_lparray (MonoArray *array, gpointer* nativeArray)
863 klass = array->obj.vtable->klass;
865 if (klass->element_class->byval_arg.type == MONO_TYPE_CLASS) {
866 for(i = 0; i < array->max_length; ++i)
867 mono_marshal_free_ccw (mono_array_get (array, MonoObject*, i));
868 g_free (nativeArray);
874 mono_byvalarray_to_array (MonoArray *arr, gpointer native_arr, MonoClass *elclass, guint32 elnum)
876 g_assert (arr->obj.vtable->klass->element_class == mono_defaults.char_class);
878 if (elclass == mono_defaults.byte_class) {
879 GError *error = NULL;
883 ut = g_utf8_to_utf16 ((const gchar *)native_arr, elnum, NULL, &items_written, &error);
886 memcpy (mono_array_addr (arr, guint16, 0), ut, items_written * sizeof (guint16));
890 g_error_free (error);
893 g_assert_not_reached ();
897 mono_byvalarray_to_byte_array (MonoArray *arr, gpointer native_arr, guint32 elnum)
899 mono_byvalarray_to_array (arr, native_arr, mono_defaults.byte_class, elnum);
902 /* This is a JIT icall, it sets the pending exception and returns on error */
904 mono_array_to_byvalarray (gpointer native_arr, MonoArray *arr, MonoClass *elclass, guint32 elnum)
906 g_assert (arr->obj.vtable->klass->element_class == mono_defaults.char_class);
908 if (elclass == mono_defaults.byte_class) {
910 GError *error = NULL;
912 as = g_utf16_to_utf8 (mono_array_addr (arr, gunichar2, 0), mono_array_length (arr), NULL, NULL, &error);
914 mono_set_pending_exception (mono_get_exception_argument ("string", error->message));
915 g_error_free (error);
919 memcpy (native_arr, as, MIN (strlen (as), elnum));
922 g_assert_not_reached ();
927 mono_array_to_byte_byvalarray (gpointer native_arr, MonoArray *arr, guint32 elnum)
929 mono_array_to_byvalarray (native_arr, arr, mono_defaults.byte_class, elnum);
932 static MonoStringBuilder *
933 mono_string_builder_new (int starting_string_length)
935 static MonoClass *string_builder_class;
936 static MonoMethod *sb_ctor;
937 static void *args [1];
940 int initial_len = starting_string_length;
946 MonoMethodDesc *desc;
949 string_builder_class = mono_class_get_string_builder_class ();
950 g_assert (string_builder_class);
951 desc = mono_method_desc_new (":.ctor(int)", FALSE);
952 m = mono_method_desc_search_in_class (desc, string_builder_class);
954 mono_method_desc_free (desc);
955 mono_memory_barrier ();
959 // We make a new array in the _to_builder function, so this
960 // array will always be garbage collected.
961 args [0] = &initial_len;
963 MonoStringBuilder *sb = (MonoStringBuilder*)mono_object_new_checked (mono_domain_get (), string_builder_class, &error);
964 mono_error_assert_ok (&error);
967 mono_runtime_try_invoke (sb_ctor, sb, args, &exc, &error);
968 g_assert (exc == NULL);
969 mono_error_assert_ok (&error);
971 g_assert (sb->chunkChars->max_length >= initial_len);
977 mono_string_utf16_to_builder_copy (MonoStringBuilder *sb, gunichar2 *text, size_t string_len)
979 gunichar2 *charDst = (gunichar2 *)sb->chunkChars->vector;
980 gunichar2 *charSrc = (gunichar2 *)text;
981 memcpy (charDst, charSrc, sizeof (gunichar2) * string_len);
983 sb->chunkLength = string_len;
989 mono_string_utf16_to_builder2 (gunichar2 *text)
995 for (len = 0; text [len] != 0; ++len);
997 MonoStringBuilder *sb = mono_string_builder_new (len);
998 mono_string_utf16_to_builder (sb, text);
1004 mono_string_utf8_to_builder (MonoStringBuilder *sb, char *text)
1009 GError *error = NULL;
1011 gunichar2* ut = g_utf8_to_utf16 (text, strlen (text), NULL, &copied, &error);
1012 int capacity = mono_string_builder_capacity (sb);
1014 if (copied > capacity)
1018 MONO_OBJECT_SETREF (sb, chunkPrevious, NULL);
1019 mono_string_utf16_to_builder_copy (sb, ut, copied);
1021 g_error_free (error);
1027 mono_string_utf8_to_builder2 (char *text)
1032 int len = strlen (text);
1033 MonoStringBuilder *sb = mono_string_builder_new (len);
1034 mono_string_utf8_to_builder (sb, text);
1040 mono_string_utf16_to_builder (MonoStringBuilder *sb, gunichar2 *text)
1046 for (len = 0; text [len] != 0; ++len);
1048 if (len > mono_string_builder_capacity (sb))
1049 len = mono_string_builder_capacity (sb);
1051 mono_string_utf16_to_builder_copy (sb, text, len);
1055 * mono_string_builder_to_utf8:
1056 * \param sb the string builder
1058 * Converts to utf8 the contents of the \c MonoStringBuilder .
1060 * \returns a utf8 string with the contents of the \c StringBuilder .
1062 * The return value must be released with mono_marshal_free.
1064 * This is a JIT icall, it sets the pending exception and returns NULL on error.
1067 mono_string_builder_to_utf8 (MonoStringBuilder *sb)
1070 GError *gerror = NULL;
1075 gunichar2 *str_utf16 = mono_string_builder_to_utf16 (sb);
1077 guint str_len = mono_string_builder_string_length (sb);
1079 gchar *tmp = g_utf16_to_utf8 (str_utf16, str_len, NULL, &byte_count, &gerror);
1082 g_error_free (gerror);
1083 mono_marshal_free (str_utf16);
1084 mono_set_pending_exception (mono_get_exception_execution_engine ("Failed to convert StringBuilder from utf16 to utf8"));
1087 guint len = mono_string_builder_capacity (sb) + 1;
1088 gchar *res = (gchar *)mono_marshal_alloc (MAX (byte_count+1, len * sizeof (gchar)), &error);
1089 if (!mono_error_ok (&error)) {
1090 mono_marshal_free (str_utf16);
1092 mono_error_set_pending_exception (&error);
1096 memcpy (res, tmp, byte_count);
1097 res[byte_count] = '\0';
1099 mono_marshal_free (str_utf16);
1106 * mono_string_builder_to_utf16:
1107 * \param sb the string builder
1109 * Converts to utf16 the contents of the \c MonoStringBuilder .
1111 * Returns: a utf16 string with the contents of the \c StringBuilder .
1113 * The return value must be released with mono_marshal_free.
1115 * This is a JIT icall, it sets the pending exception and returns NULL on error.
1118 mono_string_builder_to_utf16 (MonoStringBuilder *sb)
1125 g_assert (sb->chunkChars);
1127 guint len = mono_string_builder_capacity (sb);
1132 gunichar2 *str = (gunichar2 *)mono_marshal_alloc ((len + 1) * sizeof (gunichar2), &error);
1133 if (!mono_error_ok (&error)) {
1134 mono_error_set_pending_exception (&error);
1143 MonoStringBuilder* chunk = sb;
1145 if (chunk->chunkLength > 0) {
1146 // Check that we will not overrun our boundaries.
1147 gunichar2 *source = (gunichar2 *)chunk->chunkChars->vector;
1149 if (chunk->chunkLength <= len) {
1150 memcpy (str + chunk->chunkOffset, source, chunk->chunkLength * sizeof(gunichar2));
1152 g_error ("A chunk in the StringBuilder had a length longer than expected from the offset.");
1155 len -= chunk->chunkLength;
1157 chunk = chunk->chunkPrevious;
1158 } while (chunk != NULL);
1164 /* This is a JIT icall, it sets the pending exception and returns NULL on error. */
1166 mono_string_to_utf8str (MonoString *s)
1169 char *result = mono_string_to_utf8_checked (s, &error);
1170 mono_error_set_pending_exception (&error);
1176 mono_string_to_ansibstr (MonoString *string_obj)
1178 g_error ("UnmanagedMarshal.BStr is not implemented.");
1183 * mono_string_to_byvalstr:
1184 * \param dst Where to store the null-terminated utf8 decoded string.
1185 * \param src the \c MonoString to copy.
1186 * \param size the maximum number of bytes to copy.
1188 * Copies the \c MonoString pointed to by \p src as a utf8 string
1189 * into \p dst, it copies at most \p size bytes into the destination.
1192 mono_string_to_byvalstr (gpointer dst, MonoString *src, int size)
1198 g_assert (dst != NULL);
1199 g_assert (size > 0);
1201 memset (dst, 0, size);
1205 s = mono_string_to_utf8_checked (src, &error);
1206 if (mono_error_set_pending_exception (&error))
1208 len = MIN (size, strlen (s));
1211 memcpy (dst, s, len);
1216 * mono_string_to_byvalwstr:
1217 * \param dst Where to store the null-terminated utf16 decoded string.
1218 * \param src the \c MonoString to copy.
1219 * \param size the maximum number of wide characters to copy (each consumes 2 bytes)
1221 * Copies the \c MonoString pointed to by \p src as a utf16 string into
1222 * \p dst, it copies at most \p size bytes into the destination (including
1223 * a terminating 16-bit zero terminator).
1226 mono_string_to_byvalwstr (gpointer dst, MonoString *src, int size)
1230 g_assert (dst != NULL);
1231 g_assert (size > 1);
1234 memset (dst, 0, size * 2);
1238 len = MIN (size, (mono_string_length (src)));
1239 memcpy (dst, mono_string_chars (src), len * 2);
1240 if (size <= mono_string_length (src))
1242 *((gunichar2 *) dst + len) = 0;
1245 /* this is an icall, it sets the pending exception and returns NULL on error */
1247 mono_string_new_len_wrapper (const char *text, guint length)
1250 MonoString *result = mono_string_new_len_checked (mono_domain_get (), text, length, &error);
1251 mono_error_set_pending_exception (&error);
1255 #ifdef HAVE_ONLINE_VES
1258 * mono_mb_emit_exception_marshal_directive:
1260 * This function assumes ownership of MSG, which should be malloc-ed.
1263 mono_mb_emit_exception_marshal_directive (MonoMethodBuilder *mb, char *msg)
1268 s = mono_image_strdup (mb->method->klass->image, msg);
1273 mono_mb_emit_exception_full (mb, "System.Runtime.InteropServices", "MarshalDirectiveException", s);
1275 #endif /* HAVE_ONLINE_VES */
1278 mono_type_to_ldind (MonoType *type)
1284 switch (type->type) {
1286 return CEE_LDIND_I1;
1288 case MONO_TYPE_BOOLEAN:
1289 return CEE_LDIND_U1;
1291 return CEE_LDIND_I2;
1293 case MONO_TYPE_CHAR:
1294 return CEE_LDIND_U2;
1296 return CEE_LDIND_I4;
1298 return CEE_LDIND_U4;
1302 case MONO_TYPE_FNPTR:
1304 case MONO_TYPE_CLASS:
1305 case MONO_TYPE_STRING:
1306 case MONO_TYPE_OBJECT:
1307 case MONO_TYPE_SZARRAY:
1308 case MONO_TYPE_ARRAY:
1309 return CEE_LDIND_REF;
1312 return CEE_LDIND_I8;
1314 return CEE_LDIND_R4;
1316 return CEE_LDIND_R8;
1317 case MONO_TYPE_VALUETYPE:
1318 if (type->data.klass->enumtype) {
1319 type = mono_class_enum_basetype (type->data.klass);
1323 case MONO_TYPE_TYPEDBYREF:
1325 case MONO_TYPE_GENERICINST:
1326 type = &type->data.generic_class->container_class->byval_arg;
1329 g_error ("unknown type 0x%02x in type_to_ldind", type->type);
1335 mono_type_to_stind (MonoType *type)
1338 return MONO_TYPE_IS_REFERENCE (type) ? CEE_STIND_REF : CEE_STIND_I;
1342 switch (type->type) {
1345 case MONO_TYPE_BOOLEAN:
1346 return CEE_STIND_I1;
1349 case MONO_TYPE_CHAR:
1350 return CEE_STIND_I2;
1353 return CEE_STIND_I4;
1357 case MONO_TYPE_FNPTR:
1359 case MONO_TYPE_CLASS:
1360 case MONO_TYPE_STRING:
1361 case MONO_TYPE_OBJECT:
1362 case MONO_TYPE_SZARRAY:
1363 case MONO_TYPE_ARRAY:
1364 return CEE_STIND_REF;
1367 return CEE_STIND_I8;
1369 return CEE_STIND_R4;
1371 return CEE_STIND_R8;
1372 case MONO_TYPE_VALUETYPE:
1373 if (type->data.klass->enumtype) {
1374 type = mono_class_enum_basetype (type->data.klass);
1378 case MONO_TYPE_TYPEDBYREF:
1380 case MONO_TYPE_GENERICINST:
1381 type = &type->data.generic_class->container_class->byval_arg;
1384 g_error ("unknown type 0x%02x in type_to_stind", type->type);
1389 #ifdef HAVE_ONLINE_VES
1392 emit_ptr_to_object_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv conv, MonoMarshalSpec *mspec)
1395 case MONO_MARSHAL_CONV_BOOL_I4:
1396 mono_mb_emit_ldloc (mb, 1);
1397 mono_mb_emit_ldloc (mb, 0);
1398 mono_mb_emit_byte (mb, CEE_LDIND_I4);
1399 mono_mb_emit_byte (mb, CEE_BRFALSE_S);
1400 mono_mb_emit_byte (mb, 3);
1401 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
1402 mono_mb_emit_byte (mb, CEE_BR_S);
1403 mono_mb_emit_byte (mb, 1);
1404 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
1405 mono_mb_emit_byte (mb, CEE_STIND_I1);
1407 case MONO_MARSHAL_CONV_BOOL_VARIANTBOOL:
1408 mono_mb_emit_ldloc (mb, 1);
1409 mono_mb_emit_ldloc (mb, 0);
1410 mono_mb_emit_byte (mb, CEE_LDIND_I2);
1411 mono_mb_emit_byte (mb, CEE_BRFALSE_S);
1412 mono_mb_emit_byte (mb, 3);
1413 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
1414 mono_mb_emit_byte (mb, CEE_BR_S);
1415 mono_mb_emit_byte (mb, 1);
1416 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
1417 mono_mb_emit_byte (mb, CEE_STIND_I1);
1419 case MONO_MARSHAL_CONV_ARRAY_BYVALARRAY: {
1420 MonoClass *eklass = NULL;
1423 if (type->type == MONO_TYPE_SZARRAY) {
1424 eklass = type->data.klass;
1426 g_assert_not_reached ();
1429 esize = mono_class_native_size (eklass, NULL);
1431 /* create a new array */
1432 mono_mb_emit_ldloc (mb, 1);
1433 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1434 mono_mb_emit_op (mb, CEE_NEWARR, eklass);
1435 mono_mb_emit_byte (mb, CEE_STIND_REF);
1437 if (eklass->blittable) {
1438 /* copy the elements */
1439 mono_mb_emit_ldloc (mb, 1);
1440 mono_mb_emit_byte (mb, CEE_LDIND_I);
1441 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
1442 mono_mb_emit_byte (mb, CEE_ADD);
1443 mono_mb_emit_ldloc (mb, 0);
1444 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem * esize);
1445 mono_mb_emit_byte (mb, CEE_PREFIX1);
1446 mono_mb_emit_byte (mb, CEE_CPBLK);
1449 int array_var, src_var, dst_var, index_var;
1450 guint32 label2, label3;
1452 array_var = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
1453 src_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1454 dst_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1457 mono_mb_emit_ldloc (mb, 1);
1458 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1459 mono_mb_emit_stloc (mb, array_var);
1461 /* save the old src pointer */
1462 mono_mb_emit_ldloc (mb, 0);
1463 mono_mb_emit_stloc (mb, src_var);
1464 /* save the old dst pointer */
1465 mono_mb_emit_ldloc (mb, 1);
1466 mono_mb_emit_stloc (mb, dst_var);
1468 /* Emit marshalling loop */
1469 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1470 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
1471 mono_mb_emit_stloc (mb, index_var);
1474 label2 = mono_mb_get_label (mb);
1475 mono_mb_emit_ldloc (mb, index_var);
1476 mono_mb_emit_ldloc (mb, array_var);
1477 mono_mb_emit_byte (mb, CEE_LDLEN);
1478 label3 = mono_mb_emit_branch (mb, CEE_BGE);
1480 /* src is already set */
1483 mono_mb_emit_ldloc (mb, array_var);
1484 mono_mb_emit_ldloc (mb, index_var);
1485 mono_mb_emit_op (mb, CEE_LDELEMA, eklass);
1486 mono_mb_emit_stloc (mb, 1);
1488 /* Do the conversion */
1489 emit_struct_conv (mb, eklass, TRUE);
1492 mono_mb_emit_add_to_local (mb, index_var, 1);
1494 mono_mb_emit_branch_label (mb, CEE_BR, label2);
1496 mono_mb_patch_branch (mb, label3);
1498 /* restore the old src pointer */
1499 mono_mb_emit_ldloc (mb, src_var);
1500 mono_mb_emit_stloc (mb, 0);
1501 /* restore the old dst pointer */
1502 mono_mb_emit_ldloc (mb, dst_var);
1503 mono_mb_emit_stloc (mb, 1);
1507 case MONO_MARSHAL_CONV_ARRAY_BYVALCHARARRAY: {
1508 MonoClass *eclass = mono_defaults.char_class;
1510 /* create a new array */
1511 mono_mb_emit_ldloc (mb, 1);
1512 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1513 mono_mb_emit_op (mb, CEE_NEWARR, eclass);
1514 mono_mb_emit_byte (mb, CEE_STIND_REF);
1516 mono_mb_emit_ldloc (mb, 1);
1517 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1518 mono_mb_emit_ldloc (mb, 0);
1519 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1520 mono_mb_emit_icall (mb, mono_byvalarray_to_byte_array);
1523 case MONO_MARSHAL_CONV_STR_BYVALSTR:
1524 if (mspec && mspec->native == MONO_NATIVE_BYVALTSTR && mspec->data.array_data.num_elem) {
1525 mono_mb_emit_ldloc (mb, 1);
1526 mono_mb_emit_ldloc (mb, 0);
1527 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1528 mono_mb_emit_icall (mb, mono_string_from_byvalstr);
1530 mono_mb_emit_ldloc (mb, 1);
1531 mono_mb_emit_ldloc (mb, 0);
1532 mono_mb_emit_icall (mb, ves_icall_string_new_wrapper);
1534 mono_mb_emit_byte (mb, CEE_STIND_REF);
1536 case MONO_MARSHAL_CONV_STR_BYVALWSTR:
1537 if (mspec && mspec->native == MONO_NATIVE_BYVALTSTR && mspec->data.array_data.num_elem) {
1538 mono_mb_emit_ldloc (mb, 1);
1539 mono_mb_emit_ldloc (mb, 0);
1540 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1541 mono_mb_emit_icall (mb, mono_string_from_byvalwstr);
1543 mono_mb_emit_ldloc (mb, 1);
1544 mono_mb_emit_ldloc (mb, 0);
1545 mono_mb_emit_icall (mb, ves_icall_mono_string_from_utf16);
1547 mono_mb_emit_byte (mb, CEE_STIND_REF);
1549 case MONO_MARSHAL_CONV_STR_LPTSTR:
1550 mono_mb_emit_ldloc (mb, 1);
1551 mono_mb_emit_ldloc (mb, 0);
1552 mono_mb_emit_byte (mb, CEE_LDIND_I);
1554 mono_mb_emit_icall (mb, ves_icall_mono_string_from_utf16);
1556 mono_mb_emit_icall (mb, ves_icall_string_new_wrapper);
1558 mono_mb_emit_byte (mb, CEE_STIND_REF);
1561 // In Mono historically LPSTR was treated as a UTF8STR
1562 case MONO_MARSHAL_CONV_STR_LPSTR:
1563 case MONO_MARSHAL_CONV_STR_UTF8STR:
1564 mono_mb_emit_ldloc (mb, 1);
1565 mono_mb_emit_ldloc (mb, 0);
1566 mono_mb_emit_byte (mb, CEE_LDIND_I);
1567 mono_mb_emit_icall (mb, ves_icall_string_new_wrapper);
1568 mono_mb_emit_byte (mb, CEE_STIND_REF);
1570 case MONO_MARSHAL_CONV_STR_LPWSTR:
1571 mono_mb_emit_ldloc (mb, 1);
1572 mono_mb_emit_ldloc (mb, 0);
1573 mono_mb_emit_byte (mb, CEE_LDIND_I);
1574 mono_mb_emit_icall (mb, ves_icall_mono_string_from_utf16);
1575 mono_mb_emit_byte (mb, CEE_STIND_REF);
1577 case MONO_MARSHAL_CONV_OBJECT_STRUCT: {
1578 MonoClass *klass = mono_class_from_mono_type (type);
1579 int src_var, dst_var;
1581 src_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1582 dst_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1584 /* *dst = new object */
1585 mono_mb_emit_ldloc (mb, 1);
1586 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
1587 mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, klass);
1588 mono_mb_emit_byte (mb, CEE_STIND_REF);
1590 /* save the old src pointer */
1591 mono_mb_emit_ldloc (mb, 0);
1592 mono_mb_emit_stloc (mb, src_var);
1593 /* save the old dst pointer */
1594 mono_mb_emit_ldloc (mb, 1);
1595 mono_mb_emit_stloc (mb, dst_var);
1597 /* dst = pointer to newly created object data */
1598 mono_mb_emit_ldloc (mb, 1);
1599 mono_mb_emit_byte (mb, CEE_LDIND_I);
1600 mono_mb_emit_icon (mb, sizeof (MonoObject));
1601 mono_mb_emit_byte (mb, CEE_ADD);
1602 mono_mb_emit_stloc (mb, 1);
1604 emit_struct_conv (mb, klass, TRUE);
1606 /* restore the old src pointer */
1607 mono_mb_emit_ldloc (mb, src_var);
1608 mono_mb_emit_stloc (mb, 0);
1609 /* restore the old dst pointer */
1610 mono_mb_emit_ldloc (mb, dst_var);
1611 mono_mb_emit_stloc (mb, 1);
1614 case MONO_MARSHAL_CONV_DEL_FTN: {
1615 MonoClass *klass = mono_class_from_mono_type (type);
1617 mono_mb_emit_ldloc (mb, 1);
1618 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
1619 mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
1620 mono_mb_emit_ldloc (mb, 0);
1621 mono_mb_emit_byte (mb, CEE_LDIND_I);
1622 mono_mb_emit_icall (mb, mono_ftnptr_to_delegate);
1623 mono_mb_emit_byte (mb, CEE_STIND_REF);
1626 case MONO_MARSHAL_CONV_ARRAY_LPARRAY:
1627 g_error ("Structure field of type %s can't be marshalled as LPArray", mono_class_from_mono_type (type)->name);
1631 case MONO_MARSHAL_CONV_OBJECT_INTERFACE:
1632 case MONO_MARSHAL_CONV_OBJECT_IUNKNOWN:
1633 case MONO_MARSHAL_CONV_OBJECT_IDISPATCH:
1634 mono_cominterop_emit_ptr_to_object_conv (mb, type, conv, mspec);
1636 #endif /* DISABLE_COM */
1638 case MONO_MARSHAL_CONV_SAFEHANDLE: {
1640 * Passing SafeHandles as ref does not allow the unmanaged code
1641 * to change the SafeHandle value. If the value is changed,
1642 * we should issue a diagnostic exception (NotSupportedException)
1643 * that informs the user that changes to handles in unmanaged code
1646 * Since we currently have no access to the original
1647 * SafeHandle that was used during the marshalling,
1648 * for now we just ignore this, and ignore/discard any
1649 * changes that might have happened to the handle.
1654 case MONO_MARSHAL_CONV_HANDLEREF: {
1656 * Passing HandleRefs in a struct that is ref()ed does not
1657 * copy the values back to the HandleRef
1662 case MONO_MARSHAL_CONV_STR_BSTR:
1663 case MONO_MARSHAL_CONV_STR_ANSIBSTR:
1664 case MONO_MARSHAL_CONV_STR_TBSTR:
1665 case MONO_MARSHAL_CONV_ARRAY_SAVEARRAY:
1667 char *msg = g_strdup_printf ("marshaling conversion %d not implemented", conv);
1669 mono_mb_emit_exception_marshal_directive (mb, msg);
1676 conv_to_icall (MonoMarshalConv conv, int *ind_store_type)
1679 if (!ind_store_type)
1680 ind_store_type = &dummy;
1681 *ind_store_type = CEE_STIND_I;
1683 case MONO_MARSHAL_CONV_STR_LPWSTR:
1684 return mono_marshal_string_to_utf16;
1685 case MONO_MARSHAL_CONV_LPWSTR_STR:
1686 *ind_store_type = CEE_STIND_REF;
1687 return ves_icall_mono_string_from_utf16;
1688 case MONO_MARSHAL_CONV_LPTSTR_STR:
1689 *ind_store_type = CEE_STIND_REF;
1690 return ves_icall_string_new_wrapper;
1691 case MONO_MARSHAL_CONV_UTF8STR_STR:
1692 case MONO_MARSHAL_CONV_LPSTR_STR:
1693 *ind_store_type = CEE_STIND_REF;
1694 return ves_icall_string_new_wrapper;
1695 case MONO_MARSHAL_CONV_STR_LPTSTR:
1697 return mono_marshal_string_to_utf16;
1699 return mono_string_to_utf8str;
1701 // In Mono historically LPSTR was treated as a UTF8STR
1702 case MONO_MARSHAL_CONV_STR_UTF8STR:
1703 case MONO_MARSHAL_CONV_STR_LPSTR:
1704 return mono_string_to_utf8str;
1705 case MONO_MARSHAL_CONV_STR_BSTR:
1706 return mono_string_to_bstr;
1707 case MONO_MARSHAL_CONV_BSTR_STR:
1708 *ind_store_type = CEE_STIND_REF;
1709 return mono_string_from_bstr_icall;
1710 case MONO_MARSHAL_CONV_STR_TBSTR:
1711 case MONO_MARSHAL_CONV_STR_ANSIBSTR:
1712 return mono_string_to_ansibstr;
1713 case MONO_MARSHAL_CONV_SB_UTF8STR:
1714 case MONO_MARSHAL_CONV_SB_LPSTR:
1715 return mono_string_builder_to_utf8;
1716 case MONO_MARSHAL_CONV_SB_LPTSTR:
1718 return mono_string_builder_to_utf16;
1720 return mono_string_builder_to_utf8;
1722 case MONO_MARSHAL_CONV_SB_LPWSTR:
1723 return mono_string_builder_to_utf16;
1724 case MONO_MARSHAL_CONV_ARRAY_SAVEARRAY:
1725 return mono_array_to_savearray;
1726 case MONO_MARSHAL_CONV_ARRAY_LPARRAY:
1727 return mono_array_to_lparray;
1728 case MONO_MARSHAL_FREE_LPARRAY:
1729 return mono_free_lparray;
1730 case MONO_MARSHAL_CONV_DEL_FTN:
1731 return mono_delegate_to_ftnptr;
1732 case MONO_MARSHAL_CONV_FTN_DEL:
1733 *ind_store_type = CEE_STIND_REF;
1734 return mono_ftnptr_to_delegate;
1735 case MONO_MARSHAL_CONV_UTF8STR_SB:
1736 case MONO_MARSHAL_CONV_LPSTR_SB:
1737 *ind_store_type = CEE_STIND_REF;
1738 return mono_string_utf8_to_builder;
1739 case MONO_MARSHAL_CONV_LPTSTR_SB:
1740 *ind_store_type = CEE_STIND_REF;
1742 return mono_string_utf16_to_builder;
1744 return mono_string_utf8_to_builder;
1746 case MONO_MARSHAL_CONV_LPWSTR_SB:
1747 *ind_store_type = CEE_STIND_REF;
1748 return mono_string_utf16_to_builder;
1749 case MONO_MARSHAL_FREE_ARRAY:
1750 return mono_marshal_free_array;
1751 case MONO_MARSHAL_CONV_STR_BYVALSTR:
1752 return mono_string_to_byvalstr;
1753 case MONO_MARSHAL_CONV_STR_BYVALWSTR:
1754 return mono_string_to_byvalwstr;
1756 g_assert_not_reached ();
1763 emit_object_to_ptr_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv conv, MonoMarshalSpec *mspec)
1769 case MONO_MARSHAL_CONV_BOOL_I4:
1770 mono_mb_emit_ldloc (mb, 1);
1771 mono_mb_emit_ldloc (mb, 0);
1772 mono_mb_emit_byte (mb, CEE_LDIND_U1);
1773 mono_mb_emit_byte (mb, CEE_STIND_I4);
1775 case MONO_MARSHAL_CONV_BOOL_VARIANTBOOL:
1776 mono_mb_emit_ldloc (mb, 1);
1777 mono_mb_emit_ldloc (mb, 0);
1778 mono_mb_emit_byte (mb, CEE_LDIND_U1);
1779 mono_mb_emit_byte (mb, CEE_NEG);
1780 mono_mb_emit_byte (mb, CEE_STIND_I2);
1782 // In Mono historically LPSTR was treated as a UTF8STR
1783 case MONO_MARSHAL_CONV_STR_UTF8STR:
1784 case MONO_MARSHAL_CONV_STR_LPWSTR:
1785 case MONO_MARSHAL_CONV_STR_LPSTR:
1786 case MONO_MARSHAL_CONV_STR_LPTSTR:
1787 case MONO_MARSHAL_CONV_STR_BSTR:
1788 case MONO_MARSHAL_CONV_STR_ANSIBSTR:
1789 case MONO_MARSHAL_CONV_STR_TBSTR: {
1792 /* free space if free == true */
1793 mono_mb_emit_ldloc (mb, 2);
1794 pos = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
1795 mono_mb_emit_ldloc (mb, 1);
1796 mono_mb_emit_byte (mb, CEE_LDIND_I);
1797 mono_mb_emit_icall (mb, g_free);
1798 mono_mb_patch_short_branch (mb, pos);
1800 mono_mb_emit_ldloc (mb, 1);
1801 mono_mb_emit_ldloc (mb, 0);
1802 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1803 mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
1804 mono_mb_emit_byte (mb, stind_op);
1807 case MONO_MARSHAL_CONV_ARRAY_SAVEARRAY:
1808 case MONO_MARSHAL_CONV_ARRAY_LPARRAY:
1809 case MONO_MARSHAL_CONV_DEL_FTN:
1810 mono_mb_emit_ldloc (mb, 1);
1811 mono_mb_emit_ldloc (mb, 0);
1812 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1813 mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
1814 mono_mb_emit_byte (mb, stind_op);
1816 case MONO_MARSHAL_CONV_STR_BYVALSTR:
1817 case MONO_MARSHAL_CONV_STR_BYVALWSTR: {
1820 mono_mb_emit_ldloc (mb, 1); /* dst */
1821 mono_mb_emit_ldloc (mb, 0);
1822 mono_mb_emit_byte (mb, CEE_LDIND_REF); /* src String */
1823 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1824 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
1827 case MONO_MARSHAL_CONV_ARRAY_BYVALARRAY: {
1828 MonoClass *eklass = NULL;
1831 if (type->type == MONO_TYPE_SZARRAY) {
1832 eklass = type->data.klass;
1834 g_assert_not_reached ();
1837 if (eklass->valuetype)
1838 esize = mono_class_native_size (eklass, NULL);
1840 esize = sizeof (gpointer);
1842 mono_mb_emit_ldloc (mb, 0);
1843 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1844 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
1846 if (eklass->blittable) {
1847 mono_mb_emit_ldloc (mb, 1);
1848 mono_mb_emit_ldloc (mb, 0);
1849 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1850 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
1851 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem * esize);
1852 mono_mb_emit_byte (mb, CEE_PREFIX1);
1853 mono_mb_emit_byte (mb, CEE_CPBLK);
1855 int array_var, src_var, dst_var, index_var;
1856 guint32 label2, label3;
1858 array_var = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
1859 src_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1860 dst_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1863 mono_mb_emit_ldloc (mb, 0);
1864 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1865 mono_mb_emit_stloc (mb, array_var);
1867 /* save the old src pointer */
1868 mono_mb_emit_ldloc (mb, 0);
1869 mono_mb_emit_stloc (mb, src_var);
1870 /* save the old dst pointer */
1871 mono_mb_emit_ldloc (mb, 1);
1872 mono_mb_emit_stloc (mb, dst_var);
1874 /* Emit marshalling loop */
1875 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1876 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
1877 mono_mb_emit_stloc (mb, index_var);
1880 label2 = mono_mb_get_label (mb);
1881 mono_mb_emit_ldloc (mb, index_var);
1882 mono_mb_emit_ldloc (mb, array_var);
1883 mono_mb_emit_byte (mb, CEE_LDLEN);
1884 label3 = mono_mb_emit_branch (mb, CEE_BGE);
1887 mono_mb_emit_ldloc (mb, array_var);
1888 mono_mb_emit_ldloc (mb, index_var);
1889 mono_mb_emit_op (mb, CEE_LDELEMA, eklass);
1890 mono_mb_emit_stloc (mb, 0);
1892 /* dst is already set */
1894 /* Do the conversion */
1895 emit_struct_conv (mb, eklass, FALSE);
1898 mono_mb_emit_add_to_local (mb, index_var, 1);
1900 mono_mb_emit_branch_label (mb, CEE_BR, label2);
1902 mono_mb_patch_branch (mb, label3);
1904 /* restore the old src pointer */
1905 mono_mb_emit_ldloc (mb, src_var);
1906 mono_mb_emit_stloc (mb, 0);
1907 /* restore the old dst pointer */
1908 mono_mb_emit_ldloc (mb, dst_var);
1909 mono_mb_emit_stloc (mb, 1);
1912 mono_mb_patch_branch (mb, pos);
1915 case MONO_MARSHAL_CONV_ARRAY_BYVALCHARARRAY: {
1916 mono_mb_emit_ldloc (mb, 0);
1917 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1918 pos = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
1920 mono_mb_emit_ldloc (mb, 1);
1921 mono_mb_emit_ldloc (mb, 0);
1922 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1923 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1924 mono_mb_emit_icall (mb, mono_array_to_byte_byvalarray);
1925 mono_mb_patch_short_branch (mb, pos);
1928 case MONO_MARSHAL_CONV_OBJECT_STRUCT: {
1929 int src_var, dst_var;
1931 src_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1932 dst_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1934 mono_mb_emit_ldloc (mb, 0);
1935 mono_mb_emit_byte (mb, CEE_LDIND_I);
1936 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
1938 /* save the old src pointer */
1939 mono_mb_emit_ldloc (mb, 0);
1940 mono_mb_emit_stloc (mb, src_var);
1941 /* save the old dst pointer */
1942 mono_mb_emit_ldloc (mb, 1);
1943 mono_mb_emit_stloc (mb, dst_var);
1945 /* src = pointer to object data */
1946 mono_mb_emit_ldloc (mb, 0);
1947 mono_mb_emit_byte (mb, CEE_LDIND_I);
1948 mono_mb_emit_icon (mb, sizeof (MonoObject));
1949 mono_mb_emit_byte (mb, CEE_ADD);
1950 mono_mb_emit_stloc (mb, 0);
1952 emit_struct_conv (mb, mono_class_from_mono_type (type), FALSE);
1954 /* restore the old src pointer */
1955 mono_mb_emit_ldloc (mb, src_var);
1956 mono_mb_emit_stloc (mb, 0);
1957 /* restore the old dst pointer */
1958 mono_mb_emit_ldloc (mb, dst_var);
1959 mono_mb_emit_stloc (mb, 1);
1961 mono_mb_patch_branch (mb, pos);
1966 case MONO_MARSHAL_CONV_OBJECT_INTERFACE:
1967 case MONO_MARSHAL_CONV_OBJECT_IDISPATCH:
1968 case MONO_MARSHAL_CONV_OBJECT_IUNKNOWN:
1969 mono_cominterop_emit_object_to_ptr_conv (mb, type, conv, mspec);
1971 #endif /* DISABLE_COM */
1973 case MONO_MARSHAL_CONV_SAFEHANDLE: {
1976 mono_mb_emit_ldloc (mb, 0);
1977 mono_mb_emit_byte (mb, CEE_LDIND_I);
1978 pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
1979 mono_mb_emit_exception (mb, "ArgumentNullException", NULL);
1980 mono_mb_patch_branch (mb, pos);
1982 /* Pull the handle field from SafeHandle */
1983 mono_mb_emit_ldloc (mb, 1);
1984 mono_mb_emit_ldloc (mb, 0);
1985 mono_mb_emit_byte (mb, CEE_LDIND_I);
1986 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoSafeHandle, handle));
1987 mono_mb_emit_byte (mb, CEE_LDIND_I);
1988 mono_mb_emit_byte (mb, CEE_STIND_I);
1992 case MONO_MARSHAL_CONV_HANDLEREF: {
1993 mono_mb_emit_ldloc (mb, 1);
1994 mono_mb_emit_ldloc (mb, 0);
1995 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoHandleRef, handle));
1996 mono_mb_emit_byte (mb, CEE_ADD);
1997 mono_mb_emit_byte (mb, CEE_LDIND_I);
1998 mono_mb_emit_byte (mb, CEE_STIND_I);
2003 g_error ("marshalling conversion %d not implemented", conv);
2009 offset_of_first_nonstatic_field (MonoClass *klass)
2012 int fcount = mono_class_get_field_count (klass);
2013 mono_class_setup_fields (klass);
2014 for (i = 0; i < fcount; i++) {
2015 if (!(klass->fields[i].type->attrs & FIELD_ATTRIBUTE_STATIC) && !mono_field_is_deleted (&klass->fields[i]))
2016 return klass->fields[i].offset - sizeof (MonoObject);
2023 get_fixed_buffer_attr (MonoClassField *field, MonoType **out_etype, int *out_len)
2026 MonoCustomAttrInfo *cinfo;
2027 MonoCustomAttrEntry *attr;
2030 cinfo = mono_custom_attrs_from_field_checked (field->parent, field, &error);
2031 if (!is_ok (&error))
2035 for (aindex = 0; aindex < cinfo->num_attrs; ++aindex) {
2036 MonoClass *ctor_class = cinfo->attrs [aindex].ctor->klass;
2037 if (mono_class_has_parent (ctor_class, mono_class_get_fixed_buffer_attribute_class ())) {
2038 attr = &cinfo->attrs [aindex];
2044 MonoArray *typed_args, *named_args;
2045 CattrNamedArg *arginfo;
2048 mono_reflection_create_custom_attr_data_args (mono_defaults.corlib, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
2049 if (!is_ok (&error))
2051 g_assert (mono_array_length (typed_args) == 2);
2054 o = mono_array_get (typed_args, MonoObject*, 0);
2055 *out_etype = monotype_cast (o)->type;
2056 o = mono_array_get (typed_args, MonoObject*, 1);
2057 g_assert (o->vtable->klass == mono_defaults.int32_class);
2058 *out_len = *(gint32*)mono_object_unbox (o);
2061 if (cinfo && !cinfo->cached)
2062 mono_custom_attrs_free (cinfo);
2063 return attr != NULL;
2067 emit_fixed_buf_conv (MonoMethodBuilder *mb, MonoType *type, MonoType *etype, int len, gboolean to_object, int *out_usize)
2069 MonoClass *klass = mono_class_from_mono_type (type);
2070 MonoClass *eklass = mono_class_from_mono_type (etype);
2073 esize = mono_class_native_size (eklass, NULL);
2075 MonoMarshalNative string_encoding = klass->unicode ? MONO_NATIVE_LPWSTR : MONO_NATIVE_LPSTR;
2076 int usize = mono_class_value_size (eklass, NULL);
2077 int msize = mono_class_value_size (eklass, NULL);
2079 //printf ("FIXED: %s %d %d\n", mono_type_full_name (type), eklass->blittable, string_encoding);
2081 if (eklass->blittable) {
2082 /* copy the elements */
2083 mono_mb_emit_ldloc (mb, 1);
2084 mono_mb_emit_ldloc (mb, 0);
2085 mono_mb_emit_icon (mb, len * esize);
2086 mono_mb_emit_byte (mb, CEE_PREFIX1);
2087 mono_mb_emit_byte (mb, CEE_CPBLK);
2090 guint32 label2, label3;
2092 /* Emit marshalling loop */
2093 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
2094 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
2095 mono_mb_emit_stloc (mb, index_var);
2098 label2 = mono_mb_get_label (mb);
2099 mono_mb_emit_ldloc (mb, index_var);
2100 mono_mb_emit_icon (mb, len);
2101 label3 = mono_mb_emit_branch (mb, CEE_BGE);
2103 /* src/dst is already set */
2105 /* Do the conversion */
2106 MonoTypeEnum t = etype->type;
2112 case MONO_TYPE_BOOLEAN:
2115 case MONO_TYPE_CHAR:
2121 mono_mb_emit_ldloc (mb, 1);
2122 mono_mb_emit_ldloc (mb, 0);
2123 if (t == MONO_TYPE_CHAR && string_encoding != MONO_NATIVE_LPWSTR) {
2125 mono_mb_emit_byte (mb, CEE_LDIND_U1);
2126 mono_mb_emit_byte (mb, CEE_STIND_I2);
2128 mono_mb_emit_byte (mb, CEE_LDIND_U2);
2129 mono_mb_emit_byte (mb, CEE_STIND_I1);
2133 mono_mb_emit_byte (mb, mono_type_to_ldind (etype));
2134 mono_mb_emit_byte (mb, mono_type_to_stind (etype));
2138 g_assert_not_reached ();
2143 mono_mb_emit_add_to_local (mb, 0, usize);
2144 mono_mb_emit_add_to_local (mb, 1, msize);
2146 mono_mb_emit_add_to_local (mb, 0, msize);
2147 mono_mb_emit_add_to_local (mb, 1, usize);
2151 mono_mb_emit_add_to_local (mb, index_var, 1);
2153 mono_mb_emit_branch_label (mb, CEE_BR, label2);
2155 mono_mb_patch_branch (mb, label3);
2158 *out_usize = usize * len;
2162 emit_struct_conv_full (MonoMethodBuilder *mb, MonoClass *klass, gboolean to_object,
2163 int offset_of_first_child_field, MonoMarshalNative string_encoding)
2165 MonoMarshalType *info;
2169 emit_struct_conv_full (mb, klass->parent, to_object, offset_of_first_nonstatic_field (klass), string_encoding);
2171 info = mono_marshal_load_type_info (klass);
2173 if (info->native_size == 0)
2176 if (klass->blittable) {
2177 int usize = mono_class_value_size (klass, NULL);
2178 g_assert (usize == info->native_size);
2179 mono_mb_emit_ldloc (mb, 1);
2180 mono_mb_emit_ldloc (mb, 0);
2181 mono_mb_emit_icon (mb, usize);
2182 mono_mb_emit_byte (mb, CEE_PREFIX1);
2183 mono_mb_emit_byte (mb, CEE_CPBLK);
2186 mono_mb_emit_add_to_local (mb, 0, usize);
2187 mono_mb_emit_add_to_local (mb, 1, offset_of_first_child_field);
2189 mono_mb_emit_add_to_local (mb, 0, offset_of_first_child_field);
2190 mono_mb_emit_add_to_local (mb, 1, usize);
2195 if (klass != mono_class_try_get_safehandle_class ()) {
2196 if (mono_class_is_auto_layout (klass)) {
2197 char *msg = g_strdup_printf ("Type %s which is passed to unmanaged code must have a StructLayout attribute.",
2198 mono_type_full_name (&klass->byval_arg));
2199 mono_mb_emit_exception_marshal_directive (mb, msg);
2204 for (i = 0; i < info->num_fields; i++) {
2205 MonoMarshalNative ntype;
2206 MonoMarshalConv conv;
2207 MonoType *ftype = info->fields [i].field->type;
2210 gboolean last_field = i < (info->num_fields -1) ? 0 : 1;
2212 if (ftype->attrs & FIELD_ATTRIBUTE_STATIC)
2215 ntype = (MonoMarshalNative)mono_type_to_unmanaged (ftype, info->fields [i].mspec, TRUE, klass->unicode, &conv);
2218 msize = klass->instance_size - info->fields [i].field->offset;
2219 usize = info->native_size - info->fields [i].offset;
2221 msize = info->fields [i + 1].field->offset - info->fields [i].field->offset;
2222 usize = info->fields [i + 1].offset - info->fields [i].offset;
2225 if (klass != mono_class_try_get_safehandle_class ()){
2227 * FIXME: Should really check for usize==0 and msize>0, but we apply
2228 * the layout to the managed structure as well.
2231 if (mono_class_is_explicit_layout (klass) && (usize == 0)) {
2232 if (MONO_TYPE_IS_REFERENCE (info->fields [i].field->type) ||
2233 ((!last_field && MONO_TYPE_IS_REFERENCE (info->fields [i + 1].field->type))))
2234 g_error ("Type %s which has an [ExplicitLayout] attribute cannot have a "
2235 "reference field at the same offset as another field.",
2236 mono_type_full_name (&klass->byval_arg));
2241 case MONO_MARSHAL_CONV_NONE: {
2244 //XXX a byref field!?!? that's not allowed! and worse, it might miss a WB
2245 g_assert (!ftype->byref);
2246 if (ftype->type == MONO_TYPE_I || ftype->type == MONO_TYPE_U) {
2247 mono_mb_emit_ldloc (mb, 1);
2248 mono_mb_emit_ldloc (mb, 0);
2249 mono_mb_emit_byte (mb, CEE_LDIND_I);
2250 mono_mb_emit_byte (mb, CEE_STIND_I);
2261 case MONO_TYPE_BOOLEAN:
2264 case MONO_TYPE_CHAR:
2270 mono_mb_emit_ldloc (mb, 1);
2271 mono_mb_emit_ldloc (mb, 0);
2272 if (t == MONO_TYPE_CHAR && ntype == MONO_NATIVE_U1 && string_encoding != MONO_NATIVE_LPWSTR) {
2274 mono_mb_emit_byte (mb, CEE_LDIND_U1);
2275 mono_mb_emit_byte (mb, CEE_STIND_I2);
2277 mono_mb_emit_byte (mb, CEE_LDIND_U2);
2278 mono_mb_emit_byte (mb, CEE_STIND_I1);
2281 mono_mb_emit_byte (mb, mono_type_to_ldind (ftype));
2282 mono_mb_emit_byte (mb, mono_type_to_stind (ftype));
2285 case MONO_TYPE_VALUETYPE: {
2286 int src_var, dst_var;
2290 if (ftype->data.klass->enumtype) {
2291 ftype = mono_class_enum_basetype (ftype->data.klass);
2295 src_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
2296 dst_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
2298 /* save the old src pointer */
2299 mono_mb_emit_ldloc (mb, 0);
2300 mono_mb_emit_stloc (mb, src_var);
2301 /* save the old dst pointer */
2302 mono_mb_emit_ldloc (mb, 1);
2303 mono_mb_emit_stloc (mb, dst_var);
2305 if (get_fixed_buffer_attr (info->fields [i].field, &etype, &len)) {
2306 emit_fixed_buf_conv (mb, ftype, etype, len, to_object, &usize);
2308 emit_struct_conv (mb, ftype->data.klass, to_object);
2311 /* restore the old src pointer */
2312 mono_mb_emit_ldloc (mb, src_var);
2313 mono_mb_emit_stloc (mb, 0);
2314 /* restore the old dst pointer */
2315 mono_mb_emit_ldloc (mb, dst_var);
2316 mono_mb_emit_stloc (mb, 1);
2319 case MONO_TYPE_OBJECT: {
2322 static MonoMethod *variant_clear = NULL;
2323 static MonoMethod *get_object_for_native_variant = NULL;
2326 variant_clear = mono_class_get_method_from_name (mono_class_get_variant_class (), "Clear", 0);
2327 if (!get_object_for_native_variant)
2328 get_object_for_native_variant = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetObjectForNativeVariant", 1);
2329 mono_mb_emit_ldloc (mb, 1);
2330 mono_mb_emit_ldloc (mb, 0);
2331 mono_mb_emit_managed_call (mb, get_object_for_native_variant, NULL);
2332 mono_mb_emit_byte (mb, CEE_STIND_REF);
2334 mono_mb_emit_ldloc (mb, 0);
2335 mono_mb_emit_managed_call (mb, variant_clear, NULL);
2338 static MonoMethod *get_native_variant_for_object = NULL;
2340 if (!get_native_variant_for_object)
2341 get_native_variant_for_object = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetNativeVariantForObject", 2);
2343 mono_mb_emit_ldloc (mb, 0);
2344 mono_mb_emit_byte(mb, CEE_LDIND_REF);
2345 mono_mb_emit_ldloc (mb, 1);
2346 mono_mb_emit_managed_call (mb, get_native_variant_for_object, NULL);
2349 char *msg = g_strdup_printf ("COM support was disabled at compilation time.");
2350 mono_mb_emit_exception_marshal_directive (mb, msg);
2356 g_warning ("marshaling type %02x not implemented", ftype->type);
2357 g_assert_not_reached ();
2362 int src_var, dst_var;
2364 src_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
2365 dst_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
2367 /* save the old src pointer */
2368 mono_mb_emit_ldloc (mb, 0);
2369 mono_mb_emit_stloc (mb, src_var);
2370 /* save the old dst pointer */
2371 mono_mb_emit_ldloc (mb, 1);
2372 mono_mb_emit_stloc (mb, dst_var);
2375 emit_ptr_to_object_conv (mb, ftype, conv, info->fields [i].mspec);
2377 emit_object_to_ptr_conv (mb, ftype, conv, info->fields [i].mspec);
2379 /* restore the old src pointer */
2380 mono_mb_emit_ldloc (mb, src_var);
2381 mono_mb_emit_stloc (mb, 0);
2382 /* restore the old dst pointer */
2383 mono_mb_emit_ldloc (mb, dst_var);
2384 mono_mb_emit_stloc (mb, 1);
2389 mono_mb_emit_add_to_local (mb, 0, usize);
2390 mono_mb_emit_add_to_local (mb, 1, msize);
2392 mono_mb_emit_add_to_local (mb, 0, msize);
2393 mono_mb_emit_add_to_local (mb, 1, usize);
2399 emit_struct_conv (MonoMethodBuilder *mb, MonoClass *klass, gboolean to_object)
2401 emit_struct_conv_full (mb, klass, to_object, 0, (MonoMarshalNative)-1);
2405 emit_struct_free (MonoMethodBuilder *mb, MonoClass *klass, int struct_var)
2407 /* Call DestroyStructure */
2408 /* FIXME: Only do this if needed */
2409 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
2410 mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
2411 mono_mb_emit_ldloc (mb, struct_var);
2412 mono_mb_emit_icall (mb, mono_struct_delete_old);
2416 emit_thread_interrupt_checkpoint_call (MonoMethodBuilder *mb, gpointer checkpoint_func)
2418 int pos_noabort, pos_noex;
2420 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
2421 mono_mb_emit_byte (mb, CEE_MONO_LDPTR_INT_REQ_FLAG);
2422 mono_mb_emit_byte (mb, CEE_LDIND_U4);
2423 pos_noabort = mono_mb_emit_branch (mb, CEE_BRFALSE);
2425 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
2426 mono_mb_emit_byte (mb, CEE_MONO_NOT_TAKEN);
2428 mono_mb_emit_icall (mb, checkpoint_func);
2429 /* Throw the exception returned by the checkpoint function, if any */
2430 mono_mb_emit_byte (mb, CEE_DUP);
2431 pos_noex = mono_mb_emit_branch (mb, CEE_BRFALSE);
2432 mono_mb_emit_byte (mb, CEE_THROW);
2433 mono_mb_patch_branch (mb, pos_noex);
2434 mono_mb_emit_byte (mb, CEE_POP);
2436 mono_mb_patch_branch (mb, pos_noabort);
2440 emit_thread_interrupt_checkpoint (MonoMethodBuilder *mb)
2442 if (strstr (mb->name, "mono_thread_interruption_checkpoint"))
2445 emit_thread_interrupt_checkpoint_call (mb, mono_thread_interruption_checkpoint);
2449 emit_thread_force_interrupt_checkpoint (MonoMethodBuilder *mb)
2451 emit_thread_interrupt_checkpoint_call (mb, mono_thread_force_interruption_checkpoint_noraise);
2455 mono_marshal_emit_thread_interrupt_checkpoint (MonoMethodBuilder *mb)
2457 emit_thread_interrupt_checkpoint (mb);
2461 mono_marshal_emit_thread_force_interrupt_checkpoint (MonoMethodBuilder *mb)
2463 emit_thread_force_interrupt_checkpoint (mb);
2466 #endif /* HAVE_ONLINE_VES */
2468 /* This is a JIT icall, it sets the pending exception and returns NULL on error. */
2469 static MonoAsyncResult *
2470 mono_delegate_begin_invoke (MonoDelegate *delegate, gpointer *params)
2473 MonoMulticastDelegate *mcast_delegate;
2477 g_assert (delegate);
2478 mcast_delegate = (MonoMulticastDelegate *) delegate;
2479 if (mcast_delegate->delegates != NULL) {
2480 mono_set_pending_exception (mono_get_exception_argument (NULL, "The delegate must have only one target"));
2484 #ifndef DISABLE_REMOTING
2485 if (delegate->target && mono_object_is_transparent_proxy (delegate->target)) {
2486 MonoTransparentProxy* tp = (MonoTransparentProxy *)delegate->target;
2487 if (!mono_class_is_contextbound (tp->remote_class->proxy_class) || tp->rp->context != (MonoObject *) mono_context_get ()) {
2488 /* If the target is a proxy, make a direct call. Is proxy's work
2489 // to make the call asynchronous.
2491 MonoMethodMessage *msg;
2492 MonoDelegate *async_callback;
2494 MonoAsyncResult *ares;
2496 MonoArray *out_args;
2497 method = delegate->method;
2499 msg = mono_method_call_message_new (mono_marshal_method_from_wrapper (method), params, NULL, &async_callback, &state, &error);
2500 if (mono_error_set_pending_exception (&error))
2502 ares = mono_async_result_new (mono_domain_get (), NULL, state, NULL, NULL, &error);
2503 if (mono_error_set_pending_exception (&error))
2505 MONO_OBJECT_SETREF (ares, async_delegate, (MonoObject *)delegate);
2506 MONO_OBJECT_SETREF (ares, async_callback, (MonoObject *)async_callback);
2507 MONO_OBJECT_SETREF (msg, async_result, ares);
2508 msg->call_type = CallType_BeginInvoke;
2511 mono_remoting_invoke ((MonoObject *)tp->rp, msg, &exc, &out_args, &error);
2512 if (!mono_error_ok (&error)) {
2513 mono_error_set_pending_exception (&error);
2517 mono_set_pending_exception ((MonoException *) exc);
2523 klass = delegate->object.vtable->klass;
2525 method = mono_class_get_method_from_name (klass, "BeginInvoke", -1);
2527 method = mono_get_delegate_invoke (klass);
2530 MonoAsyncResult *result = mono_threadpool_begin_invoke (mono_domain_get (), (MonoObject*) delegate, method, params, &error);
2531 mono_error_set_pending_exception (&error);
2535 #ifdef HAVE_ONLINE_VES
2538 mono_mb_emit_save_args (MonoMethodBuilder *mb, MonoMethodSignature *sig, gboolean save_this)
2540 int i, params_var, tmp_var;
2542 /* allocate local (pointer) *params[] */
2543 params_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
2544 /* allocate local (pointer) tmp */
2545 tmp_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
2547 /* alloate space on stack to store an array of pointers to the arguments */
2548 mono_mb_emit_icon (mb, sizeof (gpointer) * (sig->param_count + 1));
2549 mono_mb_emit_byte (mb, CEE_PREFIX1);
2550 mono_mb_emit_byte (mb, CEE_LOCALLOC);
2551 mono_mb_emit_stloc (mb, params_var);
2554 mono_mb_emit_ldloc (mb, params_var);
2555 mono_mb_emit_stloc (mb, tmp_var);
2557 if (save_this && sig->hasthis) {
2558 mono_mb_emit_ldloc (mb, tmp_var);
2559 mono_mb_emit_ldarg_addr (mb, 0);
2560 mono_mb_emit_byte (mb, CEE_STIND_I);
2561 /* tmp = tmp + sizeof (gpointer) */
2562 if (sig->param_count)
2563 mono_mb_emit_add_to_local (mb, tmp_var, sizeof (gpointer));
2567 for (i = 0; i < sig->param_count; i++) {
2568 mono_mb_emit_ldloc (mb, tmp_var);
2569 mono_mb_emit_ldarg_addr (mb, i + sig->hasthis);
2570 mono_mb_emit_byte (mb, CEE_STIND_I);
2571 /* tmp = tmp + sizeof (gpointer) */
2572 if (i < (sig->param_count - 1))
2573 mono_mb_emit_add_to_local (mb, tmp_var, sizeof (gpointer));
2579 #endif /* HAVE_ONLINE_VES */
2582 mono_signature_to_name (MonoMethodSignature *sig, const char *prefix)
2586 GString *res = g_string_new ("");
2589 g_string_append (res, prefix);
2590 g_string_append_c (res, '_');
2593 mono_type_get_desc (res, sig->ret, FALSE);
2596 g_string_append (res, "__this__");
2598 for (i = 0; i < sig->param_count; ++i) {
2599 g_string_append_c (res, '_');
2600 mono_type_get_desc (res, sig->params [i], FALSE);
2603 g_string_free (res, FALSE);
2608 * mono_marshal_get_string_encoding:
2610 * Return the string encoding which should be used for a given parameter.
2612 static MonoMarshalNative
2613 mono_marshal_get_string_encoding (MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec)
2615 /* First try the parameter marshal info */
2617 if (spec->native == MONO_NATIVE_LPARRAY) {
2618 if ((spec->data.array_data.elem_type != 0) && (spec->data.array_data.elem_type != MONO_NATIVE_MAX))
2619 return spec->data.array_data.elem_type;
2622 return spec->native;
2626 return MONO_NATIVE_LPSTR;
2628 /* Then try the method level marshal info */
2629 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
2630 case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
2631 return MONO_NATIVE_LPSTR;
2632 case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
2633 return MONO_NATIVE_LPWSTR;
2634 case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
2636 return MONO_NATIVE_LPWSTR;
2638 return MONO_NATIVE_LPSTR;
2641 return MONO_NATIVE_LPSTR;
2645 static MonoMarshalConv
2646 mono_marshal_get_string_to_ptr_conv (MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec)
2648 MonoMarshalNative encoding = mono_marshal_get_string_encoding (piinfo, spec);
2651 case MONO_NATIVE_LPWSTR:
2652 return MONO_MARSHAL_CONV_STR_LPWSTR;
2653 case MONO_NATIVE_LPSTR:
2654 case MONO_NATIVE_VBBYREFSTR:
2655 return MONO_MARSHAL_CONV_STR_LPSTR;
2656 case MONO_NATIVE_LPTSTR:
2657 return MONO_MARSHAL_CONV_STR_LPTSTR;
2658 case MONO_NATIVE_BSTR:
2659 return MONO_MARSHAL_CONV_STR_BSTR;
2660 case MONO_NATIVE_UTF8STR:
2661 return MONO_MARSHAL_CONV_STR_UTF8STR;
2663 return MONO_MARSHAL_CONV_INVALID;
2667 static MonoMarshalConv
2668 mono_marshal_get_stringbuilder_to_ptr_conv (MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec)
2670 MonoMarshalNative encoding = mono_marshal_get_string_encoding (piinfo, spec);
2673 case MONO_NATIVE_LPWSTR:
2674 return MONO_MARSHAL_CONV_SB_LPWSTR;
2675 case MONO_NATIVE_LPSTR:
2676 return MONO_MARSHAL_CONV_SB_LPSTR;
2677 case MONO_NATIVE_UTF8STR:
2678 return MONO_MARSHAL_CONV_SB_UTF8STR;
2679 case MONO_NATIVE_LPTSTR:
2680 return MONO_MARSHAL_CONV_SB_LPTSTR;
2682 return MONO_MARSHAL_CONV_INVALID;
2686 static MonoMarshalConv
2687 mono_marshal_get_ptr_to_string_conv (MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec, gboolean *need_free)
2689 MonoMarshalNative encoding = mono_marshal_get_string_encoding (piinfo, spec);
2694 case MONO_NATIVE_LPWSTR:
2696 return MONO_MARSHAL_CONV_LPWSTR_STR;
2697 case MONO_NATIVE_UTF8STR:
2698 return MONO_MARSHAL_CONV_UTF8STR_STR;
2699 case MONO_NATIVE_LPSTR:
2700 case MONO_NATIVE_VBBYREFSTR:
2701 return MONO_MARSHAL_CONV_LPSTR_STR;
2702 case MONO_NATIVE_LPTSTR:
2706 return MONO_MARSHAL_CONV_LPTSTR_STR;
2707 case MONO_NATIVE_BSTR:
2708 return MONO_MARSHAL_CONV_BSTR_STR;
2710 return MONO_MARSHAL_CONV_INVALID;
2714 static MonoMarshalConv
2715 mono_marshal_get_ptr_to_stringbuilder_conv (MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec, gboolean *need_free)
2717 MonoMarshalNative encoding = mono_marshal_get_string_encoding (piinfo, spec);
2722 case MONO_NATIVE_LPWSTR:
2724 * mono_string_builder_to_utf16 does not allocate a
2725 * new buffer, so no need to free it.
2728 return MONO_MARSHAL_CONV_LPWSTR_SB;
2729 case MONO_NATIVE_UTF8STR:
2730 return MONO_MARSHAL_CONV_UTF8STR_SB;
2731 case MONO_NATIVE_LPSTR:
2732 return MONO_MARSHAL_CONV_LPSTR_SB;
2734 case MONO_NATIVE_LPTSTR:
2735 return MONO_MARSHAL_CONV_LPTSTR_SB;
2738 return MONO_MARSHAL_CONV_INVALID;
2743 * Return whenever a field of a native structure or an array member needs to
2747 mono_marshal_need_free (MonoType *t, MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec)
2749 MonoMarshalNative encoding;
2752 case MONO_TYPE_VALUETYPE:
2753 /* FIXME: Optimize this */
2755 case MONO_TYPE_OBJECT:
2756 case MONO_TYPE_CLASS:
2757 if (t->data.klass == mono_defaults.stringbuilder_class) {
2759 mono_marshal_get_ptr_to_stringbuilder_conv (piinfo, spec, &need_free);
2763 case MONO_TYPE_STRING:
2764 encoding = mono_marshal_get_string_encoding (piinfo, spec);
2765 return (encoding == MONO_NATIVE_LPWSTR) ? FALSE : TRUE;
2772 * Return the hash table pointed to by VAR, lazily creating it if neccesary.
2775 get_cache (GHashTable **var, GHashFunc hash_func, GCompareFunc equal_func)
2778 mono_marshal_lock ();
2781 g_hash_table_new (hash_func, equal_func);
2782 mono_memory_barrier ();
2785 mono_marshal_unlock ();
2791 mono_marshal_get_cache (GHashTable **var, GHashFunc hash_func, GCompareFunc equal_func)
2793 return get_cache (var, hash_func, equal_func);
2797 mono_marshal_find_in_cache (GHashTable *cache, gpointer key)
2801 mono_marshal_lock ();
2802 res = (MonoMethod *)g_hash_table_lookup (cache, key);
2803 mono_marshal_unlock ();
2810 * Create a MonoMethod from MB, set INFO as wrapper info.
2813 mono_mb_create (MonoMethodBuilder *mb, MonoMethodSignature *sig,
2814 int max_stack, WrapperInfo *info)
2818 res = mono_mb_create_method (mb, sig, max_stack);
2820 mono_marshal_set_wrapper_info (res, info);
2824 /* Create the method from the builder and place it in the cache */
2826 mono_mb_create_and_cache_full (GHashTable *cache, gpointer key,
2827 MonoMethodBuilder *mb, MonoMethodSignature *sig,
2828 int max_stack, WrapperInfo *info, gboolean *out_found)
2835 mono_marshal_lock ();
2836 res = (MonoMethod *)g_hash_table_lookup (cache, key);
2837 mono_marshal_unlock ();
2840 newm = mono_mb_create_method (mb, sig, max_stack);
2841 mono_marshal_lock ();
2842 res = (MonoMethod *)g_hash_table_lookup (cache, key);
2845 g_hash_table_insert (cache, key, res);
2846 mono_marshal_set_wrapper_info (res, info);
2847 mono_marshal_unlock ();
2851 mono_marshal_unlock ();
2852 mono_free_method (newm);
2860 mono_mb_create_and_cache (GHashTable *cache, gpointer key,
2861 MonoMethodBuilder *mb, MonoMethodSignature *sig,
2864 return mono_mb_create_and_cache_full (cache, key, mb, sig, max_stack, NULL, NULL);
2868 * mono_marshal_method_from_wrapper:
2871 mono_marshal_method_from_wrapper (MonoMethod *wrapper)
2874 int wrapper_type = wrapper->wrapper_type;
2877 if (wrapper_type == MONO_WRAPPER_NONE || wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
2880 info = mono_marshal_get_wrapper_info (wrapper);
2882 switch (wrapper_type) {
2883 case MONO_WRAPPER_REMOTING_INVOKE:
2884 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2885 case MONO_WRAPPER_XDOMAIN_INVOKE:
2886 m = info->d.remoting.method;
2887 if (wrapper->is_inflated) {
2891 * A method cannot be inflated and a wrapper at the same time, so the wrapper info
2892 * contains an uninflated method.
2894 result = mono_class_inflate_generic_method_checked (m, mono_method_get_context (wrapper), &error);
2895 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
2899 case MONO_WRAPPER_SYNCHRONIZED:
2900 m = info->d.synchronized.method;
2901 if (wrapper->is_inflated) {
2904 result = mono_class_inflate_generic_method_checked (m, mono_method_get_context (wrapper), &error);
2905 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
2909 case MONO_WRAPPER_UNBOX:
2910 return info->d.unbox.method;
2911 case MONO_WRAPPER_MANAGED_TO_NATIVE:
2912 if (info && (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT || info->subtype == WRAPPER_SUBTYPE_PINVOKE))
2913 return info->d.managed_to_native.method;
2916 case MONO_WRAPPER_RUNTIME_INVOKE:
2917 if (info && (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL))
2918 return info->d.runtime_invoke.method;
2921 case MONO_WRAPPER_DELEGATE_INVOKE:
2923 return info->d.delegate_invoke.method;
2932 * mono_marshal_get_wrapper_info:
2934 * Retrieve the WrapperInfo structure associated with WRAPPER.
2937 mono_marshal_get_wrapper_info (MonoMethod *wrapper)
2939 g_assert (wrapper->wrapper_type);
2941 return (WrapperInfo *)mono_method_get_wrapper_data (wrapper, 1);
2945 * mono_marshal_set_wrapper_info:
2947 * Set the WrapperInfo structure associated with the wrapper
2948 * method METHOD to INFO.
2951 mono_marshal_set_wrapper_info (MonoMethod *method, WrapperInfo *info)
2955 if (method->wrapper_type == MONO_WRAPPER_NONE || method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
2958 datav = (void **)((MonoMethodWrapper *)method)->method_data;
2963 mono_wrapper_info_create (MonoMethodBuilder *mb, WrapperSubtype subtype)
2967 info = (WrapperInfo *)mono_image_alloc0 (mb->method->klass->image, sizeof (WrapperInfo));
2968 info->subtype = subtype;
2973 * get_wrapper_target_class:
2975 * Return the class where a wrapper method should be placed.
2978 get_wrapper_target_class (MonoImage *image)
2985 * - can't put all wrappers into an mscorlib class, because they reference
2986 * metadata (signature) so they should be put into the same image as the
2987 * method they wrap, so they are unloaded together.
2988 * - putting them into a class with a type initalizer could cause the
2989 * initializer to be executed which can be a problem if the wrappers are
2991 * - putting them into an inflated class can cause problems if the the
2992 * class is deleted because it references an image which is unloaded.
2993 * To avoid these problems, we put the wrappers into the <Module> class of
2996 if (image_is_dynamic (image)) {
2997 klass = ((MonoDynamicImage*)image)->wrappers_type;
2999 klass = mono_class_get_checked (image, mono_metadata_make_token (MONO_TABLE_TYPEDEF, 1), &error);
3000 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3008 * Wrappers for generic methods should be instances of generic wrapper methods, i.e .the wrapper for Sort<int> should be
3009 * an instance of the wrapper for Sort<T>. This is required for full-aot to work.
3013 * check_generic_wrapper_cache:
3015 * Check CACHE for the wrapper of the generic instance ORIG_METHOD, and return it if it is found.
3016 * KEY should be the key for ORIG_METHOD in the cache, while DEF_KEY should be the key of its
3017 * generic method definition.
3020 check_generic_wrapper_cache (GHashTable *cache, MonoMethod *orig_method, gpointer key, gpointer def_key)
3023 MonoMethod *inst, *def;
3024 MonoGenericContext *ctx;
3026 g_assert (orig_method->is_inflated);
3027 ctx = mono_method_get_context (orig_method);
3030 * Look for the instance
3032 res = mono_marshal_find_in_cache (cache, key);
3037 * Look for the definition
3039 def = mono_marshal_find_in_cache (cache, def_key);
3042 inst = mono_class_inflate_generic_method_checked (def, ctx, &error);
3043 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3045 mono_memory_barrier ();
3046 mono_marshal_lock ();
3047 res = (MonoMethod *)g_hash_table_lookup (cache, key);
3049 g_hash_table_insert (cache, key, inst);
3052 mono_marshal_unlock ();
3059 cache_generic_wrapper (GHashTable *cache, MonoMethod *orig_method, MonoMethod *def, MonoGenericContext *ctx, gpointer key)
3062 MonoMethod *inst, *res;
3065 * We use the same cache for the generic definition and the instances.
3067 inst = mono_class_inflate_generic_method_checked (def, ctx, &error);
3068 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3069 mono_memory_barrier ();
3070 mono_marshal_lock ();
3071 res = (MonoMethod *)g_hash_table_lookup (cache, key);
3073 g_hash_table_insert (cache, key, inst);
3076 mono_marshal_unlock ();
3081 check_generic_delegate_wrapper_cache (GHashTable *cache, MonoMethod *orig_method, MonoMethod *def_method, MonoGenericContext *ctx)
3085 MonoMethod *inst, *def;
3088 * Look for the instance
3090 res = mono_marshal_find_in_cache (cache, orig_method->klass);
3095 * Look for the definition
3097 def = mono_marshal_find_in_cache (cache, def_method->klass);
3099 inst = mono_class_inflate_generic_method_checked (def, ctx, &error);
3100 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3103 mono_memory_barrier ();
3104 mono_marshal_lock ();
3105 res = (MonoMethod *)g_hash_table_lookup (cache, orig_method->klass);
3107 g_hash_table_insert (cache, orig_method->klass, inst);
3110 mono_marshal_unlock ();
3117 cache_generic_delegate_wrapper (GHashTable *cache, MonoMethod *orig_method, MonoMethod *def, MonoGenericContext *ctx)
3120 MonoMethod *inst, *res;
3121 WrapperInfo *ginfo, *info;
3124 * We use the same cache for the generic definition and the instances.
3126 inst = mono_class_inflate_generic_method_checked (def, ctx, &error);
3127 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3129 ginfo = mono_marshal_get_wrapper_info (def);
3131 info = (WrapperInfo *)mono_image_alloc0 (def->klass->image, sizeof (WrapperInfo));
3132 info->subtype = ginfo->subtype;
3133 if (info->subtype == WRAPPER_SUBTYPE_NONE) {
3134 info->d.delegate_invoke.method = mono_class_inflate_generic_method_checked (ginfo->d.delegate_invoke.method, ctx, &error);
3135 mono_error_assert_ok (&error);
3139 mono_memory_barrier ();
3140 mono_marshal_lock ();
3141 res = (MonoMethod *)g_hash_table_lookup (cache, orig_method->klass);
3143 g_hash_table_insert (cache, orig_method->klass, inst);
3146 mono_marshal_unlock ();
3151 * mono_marshal_get_delegate_begin_invoke:
3154 mono_marshal_get_delegate_begin_invoke (MonoMethod *method)
3156 MonoMethodSignature *sig;
3157 MonoMethodBuilder *mb;
3162 MonoGenericContext *ctx = NULL;
3163 MonoMethod *orig_method = NULL;
3165 g_assert (method && method->klass->parent == mono_defaults.multicastdelegate_class &&
3166 !strcmp (method->name, "BeginInvoke"));
3169 * For generic delegates, create a generic wrapper, and returns an instance to help AOT.
3171 if (method->is_inflated) {
3172 orig_method = method;
3173 ctx = &((MonoMethodInflated*)method)->context;
3174 method = ((MonoMethodInflated*)method)->declaring;
3177 sig = mono_signature_no_pinvoke (method);
3183 cache = get_cache (&((MonoMethodInflated*)orig_method)->owner->wrapper_caches.delegate_begin_invoke_cache, mono_aligned_addr_hash, NULL);
3184 res = check_generic_delegate_wrapper_cache (cache, orig_method, method, ctx);
3188 cache = get_cache (&method->klass->image->wrapper_caches.delegate_begin_invoke_cache,
3189 (GHashFunc)mono_signature_hash,
3190 (GCompareFunc)mono_metadata_signature_equal);
3191 if ((res = mono_marshal_find_in_cache (cache, sig)))
3195 g_assert (sig->hasthis);
3197 name = mono_signature_to_name (sig, "begin_invoke");
3199 mb = mono_mb_new (method->klass, name, MONO_WRAPPER_DELEGATE_BEGIN_INVOKE);
3201 mb = mono_mb_new (get_wrapper_target_class (method->klass->image), name, MONO_WRAPPER_DELEGATE_BEGIN_INVOKE);
3204 #ifdef HAVE_ONLINE_VES
3205 params_var = mono_mb_emit_save_args (mb, sig, FALSE);
3207 mono_mb_emit_ldarg (mb, 0);
3208 mono_mb_emit_ldloc (mb, params_var);
3209 mono_mb_emit_icall (mb, mono_delegate_begin_invoke);
3210 mono_mb_emit_byte (mb, CEE_RET);
3215 def = mono_mb_create_and_cache (cache, method->klass, mb, sig, sig->param_count + 16);
3216 res = cache_generic_delegate_wrapper (cache, orig_method, def, ctx);
3218 res = mono_mb_create_and_cache (cache, sig, mb, sig, sig->param_count + 16);
3225 /* This is a JIT icall, it sets the pending exception and returns NULL on error. */
3227 mono_delegate_end_invoke (MonoDelegate *delegate, gpointer *params)
3230 MonoDomain *domain = mono_domain_get ();
3231 MonoAsyncResult *ares;
3232 MonoMethod *method = NULL;
3233 MonoMethodSignature *sig;
3234 MonoMethodMessage *msg;
3235 MonoObject *res, *exc;
3236 MonoArray *out_args;
3239 g_assert (delegate);
3241 if (!delegate->method_info) {
3242 g_assert (delegate->method);
3243 MonoReflectionMethod *rm = mono_method_get_object_checked (domain, delegate->method, NULL, &error);
3244 if (!mono_error_ok (&error)) {
3245 mono_error_set_pending_exception (&error);
3248 MONO_OBJECT_SETREF (delegate, method_info, rm);
3251 if (!delegate->method_info || !delegate->method_info->method)
3252 g_assert_not_reached ();
3254 klass = delegate->object.vtable->klass;
3256 method = mono_class_get_method_from_name (klass, "EndInvoke", -1);
3257 g_assert (method != NULL);
3259 sig = mono_signature_no_pinvoke (method);
3261 msg = mono_method_call_message_new (method, params, NULL, NULL, NULL, &error);
3262 if (mono_error_set_pending_exception (&error))
3265 ares = (MonoAsyncResult *)mono_array_get (msg->args, gpointer, sig->param_count - 1);
3267 mono_set_pending_exception (mono_exception_from_name_msg (mono_defaults.corlib, "System.Runtime.Remoting", "RemotingException", "The async result object is null or of an unexpected type."));
3271 if (ares->async_delegate != (MonoObject*)delegate) {
3272 mono_set_pending_exception (mono_get_exception_invalid_operation (
3273 "The IAsyncResult object provided does not match this delegate."));
3277 #ifndef DISABLE_REMOTING
3278 if (delegate->target && mono_object_is_transparent_proxy (delegate->target)) {
3279 MonoTransparentProxy* tp = (MonoTransparentProxy *)delegate->target;
3280 msg = (MonoMethodMessage *)mono_object_new_checked (domain, mono_defaults.mono_method_message_class, &error);
3281 if (!mono_error_ok (&error)) {
3282 mono_error_set_pending_exception (&error);
3285 mono_message_init (domain, msg, delegate->method_info, NULL, &error);
3286 if (mono_error_set_pending_exception (&error))
3288 msg->call_type = CallType_EndInvoke;
3289 MONO_OBJECT_SETREF (msg, async_result, ares);
3290 res = mono_remoting_invoke ((MonoObject *)tp->rp, msg, &exc, &out_args, &error);
3291 if (!mono_error_ok (&error)) {
3292 mono_error_set_pending_exception (&error);
3298 res = mono_threadpool_end_invoke (ares, &out_args, &exc, &error);
3299 if (mono_error_set_pending_exception (&error))
3304 if (((MonoException*)exc)->stack_trace) {
3305 MonoError inner_error;
3306 char *strace = mono_string_to_utf8_checked (((MonoException*)exc)->stack_trace, &inner_error);
3307 if (is_ok (&inner_error)) {
3309 tmp = g_strdup_printf ("%s\nException Rethrown at:\n", strace);
3311 MonoString *tmp_str = mono_string_new_checked (domain, tmp, &inner_error);
3313 if (is_ok (&inner_error))
3314 MONO_OBJECT_SETREF (((MonoException*)exc), stack_trace, tmp_str);
3316 if (!is_ok (&inner_error))
3317 mono_error_cleanup (&inner_error); /* no stack trace, but at least throw the original exception */
3319 mono_set_pending_exception ((MonoException*)exc);
3322 mono_method_return_message_restore (method, params, out_args, &error);
3323 mono_error_set_pending_exception (&error);
3327 #ifdef HAVE_ONLINE_VES
3330 mono_mb_emit_restore_result (MonoMethodBuilder *mb, MonoType *return_type)
3332 MonoType *t = mono_type_get_underlying_type (return_type);
3334 if (return_type->byref)
3335 return_type = &mono_defaults.int_class->byval_arg;
3338 case MONO_TYPE_VOID:
3339 g_assert_not_reached ();
3342 case MONO_TYPE_STRING:
3343 case MONO_TYPE_CLASS:
3344 case MONO_TYPE_OBJECT:
3345 case MONO_TYPE_ARRAY:
3346 case MONO_TYPE_SZARRAY:
3350 case MONO_TYPE_BOOLEAN:
3353 case MONO_TYPE_CHAR:
3363 mono_mb_emit_op (mb, CEE_UNBOX, mono_class_from_mono_type (return_type));
3364 mono_mb_emit_byte (mb, mono_type_to_ldind (return_type));
3366 case MONO_TYPE_GENERICINST:
3367 if (!mono_type_generic_inst_is_valuetype (t))
3370 case MONO_TYPE_VALUETYPE: {
3371 MonoClass *klass = mono_class_from_mono_type (return_type);
3372 mono_mb_emit_op (mb, CEE_UNBOX, klass);
3373 mono_mb_emit_op (mb, CEE_LDOBJ, klass);
3377 case MONO_TYPE_MVAR: {
3378 MonoClass *klass = mono_class_from_mono_type (return_type);
3379 mono_mb_emit_op (mb, CEE_UNBOX_ANY, klass);
3383 g_warning ("type 0x%x not handled", return_type->type);
3384 g_assert_not_reached ();
3387 mono_mb_emit_byte (mb, CEE_RET);
3390 #endif /* HAVE_ONLINE_VES */
3393 * mono_marshal_get_delegate_end_invoke:
3396 mono_marshal_get_delegate_end_invoke (MonoMethod *method)
3398 MonoMethodSignature *sig;
3399 MonoMethodBuilder *mb;
3404 MonoGenericContext *ctx = NULL;
3405 MonoMethod *orig_method = NULL;
3407 g_assert (method && method->klass->parent == mono_defaults.multicastdelegate_class &&
3408 !strcmp (method->name, "EndInvoke"));
3411 * For generic delegates, create a generic wrapper, and returns an instance to help AOT.
3413 if (method->is_inflated) {
3414 orig_method = method;
3415 ctx = &((MonoMethodInflated*)method)->context;
3416 method = ((MonoMethodInflated*)method)->declaring;
3419 sig = mono_signature_no_pinvoke (method);
3425 cache = get_cache (&((MonoMethodInflated*)orig_method)->owner->wrapper_caches.delegate_end_invoke_cache, mono_aligned_addr_hash, NULL);
3426 res = check_generic_delegate_wrapper_cache (cache, orig_method, method, ctx);
3430 cache = get_cache (&method->klass->image->wrapper_caches.delegate_end_invoke_cache,
3431 (GHashFunc)mono_signature_hash,
3432 (GCompareFunc)mono_metadata_signature_equal);
3433 if ((res = mono_marshal_find_in_cache (cache, sig)))
3437 g_assert (sig->hasthis);
3439 name = mono_signature_to_name (sig, "end_invoke");
3441 mb = mono_mb_new (method->klass, name, MONO_WRAPPER_DELEGATE_END_INVOKE);
3443 mb = mono_mb_new (get_wrapper_target_class (method->klass->image), name, MONO_WRAPPER_DELEGATE_END_INVOKE);
3446 #ifdef HAVE_ONLINE_VES
3447 params_var = mono_mb_emit_save_args (mb, sig, FALSE);
3449 mono_mb_emit_ldarg (mb, 0);
3450 mono_mb_emit_ldloc (mb, params_var);
3451 mono_mb_emit_icall (mb, mono_delegate_end_invoke);
3453 if (sig->ret->type == MONO_TYPE_VOID) {
3454 mono_mb_emit_byte (mb, CEE_POP);
3455 mono_mb_emit_byte (mb, CEE_RET);
3457 mono_mb_emit_restore_result (mb, sig->ret);
3462 def = mono_mb_create_and_cache (cache, method->klass, mb, sig, sig->param_count + 16);
3463 res = cache_generic_delegate_wrapper (cache, orig_method, def, ctx);
3465 res = mono_mb_create_and_cache (cache, sig,
3466 mb, sig, sig->param_count + 16);
3475 MonoMethodSignature *sig;
3477 } SignaturePointerPair;
3480 signature_pointer_pair_hash (gconstpointer data)
3482 SignaturePointerPair *pair = (SignaturePointerPair*)data;
3484 return mono_signature_hash (pair->sig) ^ mono_aligned_addr_hash (pair->pointer);
3488 signature_pointer_pair_equal (gconstpointer data1, gconstpointer data2)
3490 SignaturePointerPair *pair1 = (SignaturePointerPair*) data1, *pair2 = (SignaturePointerPair*) data2;
3491 return mono_metadata_signature_equal (pair1->sig, pair2->sig) && (pair1->pointer == pair2->pointer);
3495 signature_pointer_pair_matches_pointer (gpointer key, gpointer value, gpointer user_data)
3497 SignaturePointerPair *pair = (SignaturePointerPair*)key;
3499 return pair->pointer == user_data;
3503 free_signature_pointer_pair (SignaturePointerPair *pair)
3509 mono_marshal_get_delegate_invoke_internal (MonoMethod *method, gboolean callvirt, gboolean static_method_with_first_arg_bound, MonoMethod *target_method)
3511 MonoMethodSignature *sig, *static_sig, *invoke_sig;
3513 MonoMethodBuilder *mb;
3516 gpointer cache_key = NULL;
3517 SignaturePointerPair key = { NULL, NULL };
3518 SignaturePointerPair *new_key;
3519 int local_i, local_len, local_delegates, local_d, local_target, local_res;
3520 int pos0, pos1, pos2;
3522 MonoClass *target_class = NULL;
3523 gboolean closed_over_null = FALSE;
3524 MonoGenericContext *ctx = NULL;
3525 MonoGenericContainer *container = NULL;
3526 MonoMethod *orig_method = method;
3528 WrapperSubtype subtype = WRAPPER_SUBTYPE_NONE;
3532 g_assert (method && method->klass->parent == mono_defaults.multicastdelegate_class &&
3533 !strcmp (method->name, "Invoke"));
3535 invoke_sig = sig = mono_signature_no_pinvoke (method);
3538 * If the delegate target is null, and the target method is not static, a virtual
3539 * call is made to that method with the first delegate argument as this. This is
3540 * a non-documented .NET feature.
3543 subtype = WRAPPER_SUBTYPE_DELEGATE_INVOKE_VIRTUAL;
3544 if (target_method->is_inflated) {
3546 MonoType *target_type;
3548 g_assert (method->signature->hasthis);
3549 target_type = mono_class_inflate_generic_type_checked (method->signature->params [0],
3550 mono_method_get_context (method), &error);
3551 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
3552 target_class = mono_class_from_mono_type (target_type);
3554 target_class = target_method->klass;
3557 closed_over_null = sig->param_count == mono_method_signature (target_method)->param_count;
3560 if (static_method_with_first_arg_bound) {
3561 subtype = WRAPPER_SUBTYPE_DELEGATE_INVOKE_BOUND;
3562 g_assert (!callvirt);
3563 invoke_sig = mono_method_signature (target_method);
3567 * For generic delegates, create a generic wrapper, and return an instance to help AOT.
3569 if (method->is_inflated && subtype == WRAPPER_SUBTYPE_NONE) {
3570 ctx = &((MonoMethodInflated*)method)->context;
3571 method = ((MonoMethodInflated*)method)->declaring;
3573 container = mono_method_get_generic_container (method);
3575 container = mono_class_try_get_generic_container (method->klass); //FIXME is this a case of a try?
3576 g_assert (container);
3578 invoke_sig = sig = mono_signature_no_pinvoke (method);
3585 cache = get_cache (&((MonoMethodInflated*)orig_method)->owner->wrapper_caches.delegate_invoke_cache, mono_aligned_addr_hash, NULL);
3586 res = check_generic_delegate_wrapper_cache (cache, orig_method, method, ctx);
3589 cache_key = method->klass;
3590 } else if (static_method_with_first_arg_bound) {
3591 cache = get_cache (&method->klass->image->delegate_bound_static_invoke_cache,
3592 (GHashFunc)mono_signature_hash,
3593 (GCompareFunc)mono_metadata_signature_equal);
3595 * The wrapper is based on sig+invoke_sig, but sig can be derived from invoke_sig.
3597 res = mono_marshal_find_in_cache (cache, invoke_sig);
3600 cache_key = invoke_sig;
3601 } else if (callvirt) {
3602 GHashTable **cache_ptr;
3604 cache_ptr = &mono_method_get_wrapper_cache (method)->delegate_abstract_invoke_cache;
3606 /* We need to cache the signature+method pair */
3607 mono_marshal_lock ();
3609 *cache_ptr = g_hash_table_new_full (signature_pointer_pair_hash, (GEqualFunc)signature_pointer_pair_equal, (GDestroyNotify)free_signature_pointer_pair, NULL);
3611 key.sig = invoke_sig;
3612 key.pointer = target_method;
3613 res = (MonoMethod *)g_hash_table_lookup (cache, &key);
3614 mono_marshal_unlock ();
3618 // Inflated methods should not be in this cache because it's not stored on the imageset.
3619 g_assert (!method->is_inflated);
3620 cache = get_cache (&method->klass->image->wrapper_caches.delegate_invoke_cache,
3621 (GHashFunc)mono_signature_hash,
3622 (GCompareFunc)mono_metadata_signature_equal);
3623 res = mono_marshal_find_in_cache (cache, sig);
3629 static_sig = mono_metadata_signature_dup_full (method->klass->image, sig);
3630 static_sig->hasthis = 0;
3631 if (!static_method_with_first_arg_bound)
3632 invoke_sig = static_sig;
3634 if (static_method_with_first_arg_bound)
3635 name = mono_signature_to_name (invoke_sig, "invoke_bound");
3636 else if (closed_over_null)
3637 name = mono_signature_to_name (invoke_sig, "invoke_closed_over_null");
3639 name = mono_signature_to_name (invoke_sig, "invoke_callvirt");
3641 name = mono_signature_to_name (invoke_sig, "invoke");
3643 mb = mono_mb_new (method->klass, name, MONO_WRAPPER_DELEGATE_INVOKE);
3645 mb = mono_mb_new (get_wrapper_target_class (method->klass->image), name, MONO_WRAPPER_DELEGATE_INVOKE);
3648 #ifdef HAVE_ONLINE_VES
3649 void_ret = sig->ret->type == MONO_TYPE_VOID && !method->string_ctor;
3651 /* allocate local 0 (object) */
3652 local_i = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
3653 local_len = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
3654 local_delegates = mono_mb_add_local (mb, &mono_defaults.array_class->byval_arg);
3655 local_d = mono_mb_add_local (mb, &mono_defaults.multicastdelegate_class->byval_arg);
3656 local_target = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
3659 local_res = mono_mb_add_local (mb, &mono_class_from_mono_type (sig->ret)->byval_arg);
3661 g_assert (sig->hasthis);
3664 * {type: sig->ret} res;
3665 * if (delegates == null) {
3666 * return this.<target> ( args .. );
3668 * int i = 0, len = this.delegates.Length;
3670 * res = this.delegates [i].Invoke ( args .. );
3671 * } while (++i < len);
3676 /* this wrapper can be used in unmanaged-managed transitions */
3677 emit_thread_interrupt_checkpoint (mb);
3679 /* delegates = this.delegates */
3680 mono_mb_emit_ldarg (mb, 0);
3681 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoMulticastDelegate, delegates));
3682 mono_mb_emit_byte (mb, CEE_LDIND_REF);
3683 mono_mb_emit_stloc (mb, local_delegates);
3685 /* if (delegates == null) */
3686 mono_mb_emit_ldloc (mb, local_delegates);
3687 pos2 = mono_mb_emit_branch (mb, CEE_BRTRUE);
3689 /* return target.<target_method|method_ptr> ( args .. ); */
3691 /* target = d.target; */
3692 mono_mb_emit_ldarg (mb, 0);
3693 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoDelegate, target));
3694 mono_mb_emit_byte (mb, CEE_LDIND_REF);
3695 mono_mb_emit_stloc (mb, local_target);
3697 /*static methods with bound first arg can have null target and still be bound*/
3698 if (!static_method_with_first_arg_bound) {
3699 /* if target != null */
3700 mono_mb_emit_ldloc (mb, local_target);
3701 pos0 = mono_mb_emit_branch (mb, CEE_BRFALSE);
3703 /* then call this->method_ptr nonstatic */
3706 mono_mb_emit_exception_full (mb, "System", "NotImplementedException", "");
3708 mono_mb_emit_ldloc (mb, local_target);
3709 for (i = 0; i < sig->param_count; ++i)
3710 mono_mb_emit_ldarg (mb, i + 1);
3711 mono_mb_emit_ldarg (mb, 0);
3712 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoDelegate, extra_arg));
3713 mono_mb_emit_byte (mb, CEE_LDIND_I);
3714 mono_mb_emit_ldarg (mb, 0);
3715 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoDelegate, method_ptr));
3716 mono_mb_emit_byte (mb, CEE_LDIND_I);
3717 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
3718 mono_mb_emit_op (mb, CEE_MONO_CALLI_EXTRA_ARG, sig);
3719 mono_mb_emit_byte (mb, CEE_RET);
3722 /* else [target == null] call this->method_ptr static */
3723 mono_mb_patch_branch (mb, pos0);
3727 if (!closed_over_null) {
3728 if (target_class->valuetype) {
3729 mono_mb_emit_ldarg (mb, 1);
3730 for (i = 1; i < sig->param_count; ++i)
3731 mono_mb_emit_ldarg (mb, i + 1);
3732 mono_mb_emit_op (mb, CEE_CALL, target_method);
3734 mono_mb_emit_ldarg (mb, 1);
3735 mono_mb_emit_op (mb, CEE_CASTCLASS, target_class);
3736 for (i = 1; i < sig->param_count; ++i)
3737 mono_mb_emit_ldarg (mb, i + 1);
3738 mono_mb_emit_op (mb, CEE_CALLVIRT, target_method);
3741 mono_mb_emit_byte (mb, CEE_LDNULL);
3742 for (i = 0; i < sig->param_count; ++i)
3743 mono_mb_emit_ldarg (mb, i + 1);
3744 mono_mb_emit_op (mb, CEE_CALL, target_method);
3747 if (static_method_with_first_arg_bound) {
3748 mono_mb_emit_ldloc (mb, local_target);
3749 if (!MONO_TYPE_IS_REFERENCE (invoke_sig->params[0]))
3750 mono_mb_emit_op (mb, CEE_UNBOX_ANY, mono_class_from_mono_type (invoke_sig->params[0]));
3752 for (i = 0; i < sig->param_count; ++i)
3753 mono_mb_emit_ldarg (mb, i + 1);
3754 mono_mb_emit_ldarg (mb, 0);
3755 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoDelegate, extra_arg));
3756 mono_mb_emit_byte (mb, CEE_LDIND_I);
3757 mono_mb_emit_ldarg (mb, 0);
3758 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoDelegate, method_ptr));
3759 mono_mb_emit_byte (mb, CEE_LDIND_I);
3760 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
3761 mono_mb_emit_op (mb, CEE_MONO_CALLI_EXTRA_ARG, invoke_sig);
3764 mono_mb_emit_byte (mb, CEE_RET);
3766 /* else [delegates != null] */
3767 mono_mb_patch_branch (mb, pos2);
3769 /* len = delegates.Length; */
3770 mono_mb_emit_ldloc (mb, local_delegates);
3771 mono_mb_emit_byte (mb, CEE_LDLEN);
3772 mono_mb_emit_byte (mb, CEE_CONV_I4);
3773 mono_mb_emit_stloc (mb, local_len);
3776 mono_mb_emit_icon (mb, 0);
3777 mono_mb_emit_stloc (mb, local_i);
3779 pos1 = mono_mb_get_label (mb);
3781 /* d = delegates [i]; */
3782 mono_mb_emit_ldloc (mb, local_delegates);
3783 mono_mb_emit_ldloc (mb, local_i);
3784 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
3785 mono_mb_emit_stloc (mb, local_d);
3787 /* res = d.Invoke ( args .. ); */
3788 mono_mb_emit_ldloc (mb, local_d);
3789 for (i = 0; i < sig->param_count; i++)
3790 mono_mb_emit_ldarg (mb, i + 1);
3792 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
3795 mono_mb_emit_op (mb, CEE_CALLVIRT, mono_class_inflate_generic_method_checked (method, &container->context, &error));
3796 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3799 mono_mb_emit_stloc (mb, local_res);
3802 mono_mb_emit_add_to_local (mb, local_i, 1);
3805 mono_mb_emit_ldloc (mb, local_i);
3806 mono_mb_emit_ldloc (mb, local_len);
3807 mono_mb_emit_branch_label (mb, CEE_BLT, pos1);
3811 mono_mb_emit_ldloc (mb, local_res);
3812 mono_mb_emit_byte (mb, CEE_RET);
3814 mb->skip_visibility = 1;
3815 #endif /* HAVE_ONLINE_VES */
3817 info = mono_wrapper_info_create (mb, subtype);
3818 info->d.delegate_invoke.method = method;
3823 def = mono_mb_create_and_cache_full (cache, cache_key, mb, sig, sig->param_count + 16, info, NULL);
3824 res = cache_generic_delegate_wrapper (cache, orig_method, def, ctx);
3825 } else if (callvirt) {
3826 new_key = g_new0 (SignaturePointerPair, 1);
3829 res = mono_mb_create_and_cache_full (cache, new_key, mb, sig, sig->param_count + 16, info, &found);
3833 res = mono_mb_create_and_cache_full (cache, cache_key, mb, sig, sig->param_count + 16, info, NULL);
3837 /* mono_method_print_code (res); */
3843 * mono_marshal_get_delegate_invoke:
3844 * The returned method invokes all methods in a multicast delegate.
3847 mono_marshal_get_delegate_invoke (MonoMethod *method, MonoDelegate *del)
3849 gboolean callvirt = FALSE;
3850 gboolean static_method_with_first_arg_bound = FALSE;
3851 MonoMethod *target_method = NULL;
3852 MonoMethodSignature *sig;
3854 sig = mono_signature_no_pinvoke (method);
3856 if (del && !del->target && del->method && mono_method_signature (del->method)->hasthis) {
3858 target_method = del->method;
3861 if (del && del->method && mono_method_signature (del->method)->param_count == sig->param_count + 1 && (del->method->flags & METHOD_ATTRIBUTE_STATIC)) {
3862 static_method_with_first_arg_bound = TRUE;
3863 target_method = del->method;
3866 return mono_marshal_get_delegate_invoke_internal (method, callvirt, static_method_with_first_arg_bound, target_method);
3870 MonoMethodSignature *ctor_sig;
3871 MonoMethodSignature *sig;
3874 /* protected by the marshal lock, contains CtorSigPair pointers */
3875 static GSList *strsig_list = NULL;
3877 static MonoMethodSignature *
3878 lookup_string_ctor_signature (MonoMethodSignature *sig)
3880 MonoMethodSignature *callsig;
3884 mono_marshal_lock ();
3886 for (item = strsig_list; item; item = item->next) {
3887 cs = (CtorSigPair *)item->data;
3888 /* mono_metadata_signature_equal () is safe to call with the marshal lock
3889 * because it is lock-free.
3891 if (mono_metadata_signature_equal (sig, cs->ctor_sig)) {
3896 mono_marshal_unlock ();
3900 static MonoMethodSignature *
3901 add_string_ctor_signature (MonoMethod *method)
3903 MonoMethodSignature *callsig;
3906 callsig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
3907 callsig->ret = &mono_defaults.string_class->byval_arg;
3908 cs = g_new (CtorSigPair, 1);
3910 cs->ctor_sig = mono_method_signature (method);
3912 mono_marshal_lock ();
3913 strsig_list = g_slist_prepend (strsig_list, cs);
3914 mono_marshal_unlock ();
3919 * mono_marshal_get_string_ctor_signature:
3921 * Return the modified signature used by string ctors (they return the newly created
3924 MonoMethodSignature*
3925 mono_marshal_get_string_ctor_signature (MonoMethod *method)
3927 MonoMethodSignature *sig = lookup_string_ctor_signature (mono_method_signature (method));
3929 sig = add_string_ctor_signature (method);
3935 get_runtime_invoke_type (MonoType *t, gboolean ret)
3938 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t)))
3940 /* Can't share this with 'I' as that needs another indirection */
3941 return &mono_defaults.int_class->this_arg;
3944 if (MONO_TYPE_IS_REFERENCE (t))
3945 return &mono_defaults.object_class->byval_arg;
3948 /* The result needs to be boxed */
3953 /* Can't share these as the argument needs to be loaded using sign/zero extension */
3956 return &mono_defaults.sbyte_class->byval_arg;
3958 return &mono_defaults.int16_class->byval_arg;
3960 return &mono_defaults.int32_class->byval_arg;
3963 return &mono_defaults.int64_class->byval_arg;
3964 case MONO_TYPE_BOOLEAN:
3965 return &mono_defaults.byte_class->byval_arg;
3966 case MONO_TYPE_CHAR:
3967 return &mono_defaults.uint16_class->byval_arg;
3969 return &mono_defaults.int_class->byval_arg;
3970 case MONO_TYPE_VALUETYPE:
3971 if (t->data.klass->enumtype) {
3972 t = mono_class_enum_basetype (t->data.klass);
3982 * mono_marshal_get_runtime_invoke_sig:
3984 * Return a common signature used for sharing runtime invoke wrappers.
3986 static MonoMethodSignature*
3987 mono_marshal_get_runtime_invoke_sig (MonoMethodSignature *sig)
3989 MonoMethodSignature *res = mono_metadata_signature_dup (sig);
3992 res->generic_param_count = 0;
3993 res->ret = get_runtime_invoke_type (sig->ret, TRUE);
3994 for (i = 0; i < res->param_count; ++i)
3995 res->params [i] = get_runtime_invoke_type (sig->params [i], FALSE);
4001 runtime_invoke_signature_equal (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
4003 /* Can't share wrappers which return a vtype since it needs to be boxed */
4004 if (sig1->ret != sig2->ret && !(MONO_TYPE_IS_REFERENCE (sig1->ret) && MONO_TYPE_IS_REFERENCE (sig2->ret)) && !mono_metadata_type_equal (sig1->ret, sig2->ret))
4007 return mono_metadata_signature_equal (sig1, sig2);
4010 #ifdef HAVE_ONLINE_VES
4015 * Emit the call to the wrapper method from a runtime invoke wrapper.
4018 emit_invoke_call (MonoMethodBuilder *mb, MonoMethod *method,
4019 MonoMethodSignature *sig, MonoMethodSignature *callsig,
4021 gboolean virtual_, gboolean need_direct_wrapper)
4023 static MonoString *string_dummy = NULL;
4025 int *tmp_nullable_locals;
4026 gboolean void_ret = FALSE;
4027 gboolean string_ctor = method && method->string_ctor;
4029 /* to make it work with our special string constructors */
4030 if (!string_dummy) {
4031 MONO_GC_REGISTER_ROOT_SINGLE (string_dummy, MONO_ROOT_SOURCE_MARSHAL, "dummy marshal string");
4032 string_dummy = mono_string_new_wrapper ("dummy");
4036 g_assert (sig->hasthis);
4037 g_assert (method->flags & METHOD_ATTRIBUTE_VIRTUAL);
4042 if (mono_gc_is_moving ()) {
4043 mono_mb_emit_ptr (mb, &string_dummy);
4044 mono_mb_emit_byte (mb, CEE_LDIND_REF);
4046 mono_mb_emit_ptr (mb, string_dummy);
4049 mono_mb_emit_ldarg (mb, 0);
4053 tmp_nullable_locals = g_new0 (int, sig->param_count);
4055 for (i = 0; i < sig->param_count; i++) {
4056 MonoType *t = sig->params [i];
4059 mono_mb_emit_ldarg (mb, 1);
4061 mono_mb_emit_icon (mb, sizeof (gpointer) * i);
4062 mono_mb_emit_byte (mb, CEE_ADD);
4066 mono_mb_emit_byte (mb, CEE_LDIND_I);
4067 /* A Nullable<T> type don't have a boxed form, it's either null or a boxed T.
4068 * So to make this work we unbox it to a local variablee and push a reference to that.
4070 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
4071 tmp_nullable_locals [i] = mono_mb_add_local (mb, &mono_class_from_mono_type (t)->byval_arg);
4073 mono_mb_emit_op (mb, CEE_UNBOX_ANY, mono_class_from_mono_type (t));
4074 mono_mb_emit_stloc (mb, tmp_nullable_locals [i]);
4075 mono_mb_emit_ldloc_addr (mb, tmp_nullable_locals [i]);
4080 /*FIXME 'this doesn't handle generic enums. Shouldn't we?*/
4081 type = sig->params [i]->type;
4085 case MONO_TYPE_BOOLEAN:
4089 case MONO_TYPE_CHAR:
4098 mono_mb_emit_byte (mb, CEE_LDIND_I);
4099 mono_mb_emit_byte (mb, mono_type_to_ldind (sig->params [i]));
4101 case MONO_TYPE_STRING:
4102 case MONO_TYPE_CLASS:
4103 case MONO_TYPE_ARRAY:
4105 case MONO_TYPE_SZARRAY:
4106 case MONO_TYPE_OBJECT:
4107 mono_mb_emit_byte (mb, mono_type_to_ldind (sig->params [i]));
4109 case MONO_TYPE_GENERICINST:
4110 if (!mono_type_generic_inst_is_valuetype (sig->params [i])) {
4111 mono_mb_emit_byte (mb, mono_type_to_ldind (sig->params [i]));
4116 case MONO_TYPE_VALUETYPE:
4117 if (type == MONO_TYPE_VALUETYPE && t->data.klass->enumtype) {
4118 type = mono_class_enum_basetype (t->data.klass)->type;
4121 mono_mb_emit_byte (mb, CEE_LDIND_I);
4122 if (mono_class_is_nullable (mono_class_from_mono_type (sig->params [i]))) {
4123 /* Need to convert a boxed vtype to an mp to a Nullable struct */
4124 mono_mb_emit_op (mb, CEE_UNBOX, mono_class_from_mono_type (sig->params [i]));
4125 mono_mb_emit_op (mb, CEE_LDOBJ, mono_class_from_mono_type (sig->params [i]));
4127 mono_mb_emit_op (mb, CEE_LDOBJ, mono_class_from_mono_type (sig->params [i]));
4131 g_assert_not_reached ();
4136 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
4137 } else if (need_direct_wrapper) {
4138 mono_mb_emit_op (mb, CEE_CALL, method);
4140 mono_mb_emit_ldarg (mb, 3);
4141 mono_mb_emit_calli (mb, callsig);
4144 if (sig->ret->byref) {
4146 g_assert_not_reached ();
4149 switch (sig->ret->type) {
4150 case MONO_TYPE_VOID:
4154 case MONO_TYPE_BOOLEAN:
4155 case MONO_TYPE_CHAR:
4168 case MONO_TYPE_VALUETYPE:
4169 case MONO_TYPE_TYPEDBYREF:
4170 case MONO_TYPE_GENERICINST:
4171 /* box value types */
4172 mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (sig->ret));
4174 case MONO_TYPE_STRING:
4175 case MONO_TYPE_CLASS:
4176 case MONO_TYPE_ARRAY:
4177 case MONO_TYPE_SZARRAY:
4178 case MONO_TYPE_OBJECT:
4182 /* The result is an IntPtr */
4183 mono_mb_emit_op (mb, CEE_BOX, mono_defaults.int_class);
4186 g_assert_not_reached ();
4190 mono_mb_emit_stloc (mb, loc_res);
4192 /* Convert back nullable-byref arguments */
4193 for (i = 0; i < sig->param_count; i++) {
4194 MonoType *t = sig->params [i];
4197 * Box the result and put it back into the array, the caller will have
4198 * to obtain it from there.
4200 if (t->byref && t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
4201 mono_mb_emit_ldarg (mb, 1);
4202 mono_mb_emit_icon (mb, sizeof (gpointer) * i);
4203 mono_mb_emit_byte (mb, CEE_ADD);
4205 mono_mb_emit_ldloc (mb, tmp_nullable_locals [i]);
4206 mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (t));
4208 mono_mb_emit_byte (mb, CEE_STIND_REF);
4212 g_free (tmp_nullable_locals);
4216 emit_runtime_invoke_body (MonoMethodBuilder *mb, MonoImage *image, MonoMethod *method,
4217 MonoMethodSignature *sig, MonoMethodSignature *callsig,
4218 gboolean virtual_, gboolean need_direct_wrapper)
4221 MonoExceptionClause *clause;
4222 int loc_res, loc_exc;
4224 /* The wrapper looks like this:
4230 * } catch (Exception e) {
4238 /* allocate local 0 (object) tmp */
4239 loc_res = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
4240 /* allocate local 1 (object) exc */
4241 loc_exc = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
4243 /* *exc is assumed to be initialized to NULL by the caller */
4245 mono_mb_emit_byte (mb, CEE_LDARG_2);
4246 labels [0] = mono_mb_emit_branch (mb, CEE_BRFALSE);
4251 labels [1] = mono_mb_get_label (mb);
4252 emit_thread_force_interrupt_checkpoint (mb);
4253 emit_invoke_call (mb, method, sig, callsig, loc_res, virtual_, need_direct_wrapper);
4255 labels [2] = mono_mb_emit_branch (mb, CEE_LEAVE);
4257 /* Add a try clause around the call */
4258 clause = (MonoExceptionClause *)mono_image_alloc0 (image, sizeof (MonoExceptionClause));
4259 clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
4260 clause->data.catch_class = mono_defaults.exception_class;
4261 clause->try_offset = labels [1];
4262 clause->try_len = mono_mb_get_label (mb) - labels [1];
4264 clause->handler_offset = mono_mb_get_label (mb);
4267 mono_mb_emit_stloc (mb, loc_exc);
4268 mono_mb_emit_byte (mb, CEE_LDARG_2);
4269 mono_mb_emit_ldloc (mb, loc_exc);
4270 mono_mb_emit_byte (mb, CEE_STIND_REF);
4272 mono_mb_emit_branch (mb, CEE_LEAVE);
4274 clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
4276 mono_mb_set_clauses (mb, 1, clause);
4278 mono_mb_patch_branch (mb, labels [2]);
4279 mono_mb_emit_ldloc (mb, loc_res);
4280 mono_mb_emit_byte (mb, CEE_RET);
4285 mono_mb_patch_branch (mb, labels [0]);
4286 emit_thread_force_interrupt_checkpoint (mb);
4287 emit_invoke_call (mb, method, sig, callsig, loc_res, virtual_, need_direct_wrapper);
4289 mono_mb_emit_ldloc (mb, 0);
4290 mono_mb_emit_byte (mb, CEE_RET);
4295 * mono_marshal_get_runtime_invoke:
4296 * Generates IL code for the runtime invoke function:
4298 * <code>MonoObject *runtime_invoke (MonoObject *this_obj, void **params, MonoObject **exc, void* method)</code>
4300 * We also catch exceptions if \p exc is not NULL.
4301 * If \p virtual is TRUE, then \p method is invoked virtually on \p this. This is useful since
4302 * it means that the compiled code for \p method does not have to be looked up
4303 * before calling the runtime invoke wrapper. In this case, the wrapper ignores
4304 * its \p method argument.
4307 mono_marshal_get_runtime_invoke (MonoMethod *method, gboolean virtual_)
4309 MonoMethodSignature *sig, *csig, *callsig;
4310 MonoMethodBuilder *mb;
4311 GHashTable *cache = NULL;
4312 MonoClass *target_klass;
4313 MonoMethod *res = NULL;
4314 static MonoMethodSignature *cctor_signature = NULL;
4315 static MonoMethodSignature *finalize_signature = NULL;
4317 const char *param_names [16];
4318 gboolean need_direct_wrapper = FALSE;
4323 if (!cctor_signature) {
4324 cctor_signature = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4325 cctor_signature->ret = &mono_defaults.void_class->byval_arg;
4327 if (!finalize_signature) {
4328 finalize_signature = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4329 finalize_signature->ret = &mono_defaults.void_class->byval_arg;
4330 finalize_signature->hasthis = 1;
4334 need_direct_wrapper = TRUE;
4337 * Use a separate cache indexed by methods to speed things up and to avoid the
4338 * boundless mempool growth caused by the signature_dup stuff below.
4341 cache = get_cache (&method->klass->image->runtime_invoke_vcall_cache, mono_aligned_addr_hash, NULL);
4343 cache = get_cache (&mono_method_get_wrapper_cache (method)->runtime_invoke_direct_cache, mono_aligned_addr_hash, NULL);
4345 res = mono_marshal_find_in_cache (cache, method);
4349 if (method->klass->rank && (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
4350 (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
4352 * Array Get/Set/Address methods. The JIT implements them using inline code
4353 * so we need to create an invoke wrapper which calls the method directly.
4355 need_direct_wrapper = TRUE;
4358 if (method->string_ctor) {
4359 callsig = lookup_string_ctor_signature (mono_method_signature (method));
4361 callsig = add_string_ctor_signature (method);
4362 /* Can't share this as we push a string as this */
4363 need_direct_wrapper = TRUE;
4365 if (method_is_dynamic (method))
4366 callsig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
4368 callsig = mono_method_signature (method);
4371 sig = mono_method_signature (method);
4373 target_klass = get_wrapper_target_class (method->klass->image);
4375 /* Try to share wrappers for non-corlib methods with simple signatures */
4376 if (mono_metadata_signature_equal (callsig, cctor_signature)) {
4377 callsig = cctor_signature;
4378 target_klass = mono_defaults.object_class;
4379 } else if (mono_metadata_signature_equal (callsig, finalize_signature)) {
4380 callsig = finalize_signature;
4381 target_klass = mono_defaults.object_class;
4384 if (need_direct_wrapper) {
4385 /* Already searched at the start */
4387 MonoMethodSignature *tmp_sig;
4389 callsig = mono_marshal_get_runtime_invoke_sig (callsig);
4390 GHashTable **cache_table = NULL;
4392 if (method->klass->valuetype && mono_method_signature (method)->hasthis)
4393 cache_table = &mono_method_get_wrapper_cache (method)->runtime_invoke_vtype_cache;
4395 cache_table = &mono_method_get_wrapper_cache (method)->runtime_invoke_cache;
4397 cache = get_cache (cache_table, (GHashFunc)mono_signature_hash,
4398 (GCompareFunc)runtime_invoke_signature_equal);
4400 /* from mono_marshal_find_in_cache */
4401 mono_marshal_lock ();
4402 res = (MonoMethod *)g_hash_table_lookup (cache, callsig);
4403 mono_marshal_unlock ();
4410 /* Make a copy of the signature from the image mempool */
4412 callsig = mono_metadata_signature_dup_full (target_klass->image, callsig);
4416 csig = mono_metadata_signature_alloc (target_klass->image, 4);
4418 csig->ret = &mono_defaults.object_class->byval_arg;
4419 if (method->klass->valuetype && mono_method_signature (method)->hasthis)
4420 csig->params [0] = get_runtime_invoke_type (&method->klass->this_arg, FALSE);
4422 csig->params [0] = &mono_defaults.object_class->byval_arg;
4423 csig->params [1] = &mono_defaults.int_class->byval_arg;
4424 csig->params [2] = &mono_defaults.int_class->byval_arg;
4425 csig->params [3] = &mono_defaults.int_class->byval_arg;
4428 /* This is called from runtime code so it has to be cdecl */
4429 csig->call_convention = MONO_CALL_C;
4432 name = mono_signature_to_name (callsig, virtual_ ? "runtime_invoke_virtual" : "runtime_invoke");
4433 mb = mono_mb_new (target_klass, name, MONO_WRAPPER_RUNTIME_INVOKE);
4436 #ifdef HAVE_ONLINE_VES
4437 param_names [0] = "this";
4438 param_names [1] = "params";
4439 param_names [2] = "exc";
4440 param_names [3] = "method";
4441 mono_mb_set_param_names (mb, param_names);
4443 emit_runtime_invoke_body (mb, target_klass->image, method, sig, callsig, virtual_, need_direct_wrapper);
4446 if (need_direct_wrapper) {
4447 #ifdef HAVE_ONLINE_VES
4448 mb->skip_visibility = 1;
4450 info = mono_wrapper_info_create (mb, virtual_ ? WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL : WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT);
4451 info->d.runtime_invoke.method = method;
4452 res = mono_mb_create_and_cache_full (cache, method, mb, csig, sig->param_count + 16, info, NULL);
4454 /* taken from mono_mb_create_and_cache */
4455 mono_marshal_lock ();
4456 res = (MonoMethod *)g_hash_table_lookup (cache, callsig);
4457 mono_marshal_unlock ();
4459 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL);
4460 info->d.runtime_invoke.sig = callsig;
4462 /* Somebody may have created it before us */
4465 newm = mono_mb_create (mb, csig, sig->param_count + 16, info);
4467 mono_marshal_lock ();
4468 res = (MonoMethod *)g_hash_table_lookup (cache, callsig);
4470 GHashTable *direct_cache;
4472 g_hash_table_insert (cache, callsig, res);
4473 /* Can't insert it into wrapper_hash since the key is a signature */
4474 direct_cache = mono_method_get_wrapper_cache (method)->runtime_invoke_direct_cache;
4476 g_hash_table_insert (direct_cache, method, res);
4478 mono_free_method (newm);
4480 mono_marshal_unlock ();
4483 /* end mono_mb_create_and_cache */
4492 * mono_marshal_get_runtime_invoke_dynamic:
4494 * Return a method which can be used to invoke managed methods from native code
4496 * The signature of the returned method is given by RuntimeInvokeDynamicFunction:
4497 * void runtime_invoke (void *args, MonoObject **exc, void *compiled_method)
4498 * ARGS should point to an architecture specific structure containing
4499 * the arguments and space for the return value.
4500 * The other arguments are the same as for runtime_invoke (), except that
4501 * ARGS should contain the this argument too.
4502 * This wrapper serves the same purpose as the runtime-invoke wrappers, but there
4503 * is only one copy of it, which is useful in full-aot.
4506 mono_marshal_get_runtime_invoke_dynamic (void)
4508 static MonoMethod *method;
4509 MonoMethodSignature *csig;
4510 MonoExceptionClause *clause;
4511 MonoMethodBuilder *mb;
4519 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 4);
4521 csig->ret = &mono_defaults.void_class->byval_arg;
4522 csig->params [0] = &mono_defaults.int_class->byval_arg;
4523 csig->params [1] = &mono_defaults.int_class->byval_arg;
4524 csig->params [2] = &mono_defaults.int_class->byval_arg;
4525 csig->params [3] = &mono_defaults.int_class->byval_arg;
4527 name = g_strdup ("runtime_invoke_dynamic");
4528 mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_RUNTIME_INVOKE);
4531 #ifdef HAVE_ONLINE_VES
4532 /* allocate local 0 (object) tmp */
4533 mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
4534 /* allocate local 1 (object) exc */
4535 mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
4537 /* cond set *exc to null */
4538 mono_mb_emit_byte (mb, CEE_LDARG_1);
4539 mono_mb_emit_byte (mb, CEE_BRFALSE_S);
4540 mono_mb_emit_byte (mb, 3);
4541 mono_mb_emit_byte (mb, CEE_LDARG_1);
4542 mono_mb_emit_byte (mb, CEE_LDNULL);
4543 mono_mb_emit_byte (mb, CEE_STIND_REF);
4545 emit_thread_force_interrupt_checkpoint (mb);
4547 mono_mb_emit_byte (mb, CEE_LDARG_0);
4548 mono_mb_emit_byte (mb, CEE_LDARG_2);
4549 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
4550 mono_mb_emit_byte (mb, CEE_MONO_DYN_CALL);
4552 pos = mono_mb_emit_branch (mb, CEE_LEAVE);
4554 clause = (MonoExceptionClause *)mono_image_alloc0 (mono_defaults.corlib, sizeof (MonoExceptionClause));
4555 clause->flags = MONO_EXCEPTION_CLAUSE_FILTER;
4556 clause->try_len = mono_mb_get_label (mb);
4559 clause->data.filter_offset = mono_mb_get_label (mb);
4561 mono_mb_emit_byte (mb, CEE_POP);
4562 mono_mb_emit_byte (mb, CEE_LDARG_1);
4563 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
4564 mono_mb_emit_byte (mb, CEE_PREFIX1);
4565 mono_mb_emit_byte (mb, CEE_CGT_UN);
4566 mono_mb_emit_byte (mb, CEE_PREFIX1);
4567 mono_mb_emit_byte (mb, CEE_ENDFILTER);
4569 clause->handler_offset = mono_mb_get_label (mb);
4572 /* store exception */
4573 mono_mb_emit_stloc (mb, 1);
4575 mono_mb_emit_byte (mb, CEE_LDARG_1);
4576 mono_mb_emit_ldloc (mb, 1);
4577 mono_mb_emit_byte (mb, CEE_STIND_REF);
4579 mono_mb_emit_byte (mb, CEE_LDNULL);
4580 mono_mb_emit_stloc (mb, 0);
4582 mono_mb_emit_branch (mb, CEE_LEAVE);
4584 clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
4586 mono_mb_set_clauses (mb, 1, clause);
4589 mono_mb_patch_branch (mb, pos);
4590 //mono_mb_emit_ldloc (mb, 0);
4591 mono_mb_emit_byte (mb, CEE_RET);
4592 #endif /* HAVE_ONLINE_VES */
4594 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC);
4596 mono_marshal_lock ();
4597 /* double-checked locking */
4599 method = mono_mb_create (mb, csig, 16, info);
4601 mono_marshal_unlock ();
4609 * mono_marshal_get_runtime_invoke_for_sig:
4611 * Return a runtime invoke wrapper for a given signature.
4614 mono_marshal_get_runtime_invoke_for_sig (MonoMethodSignature *sig)
4616 MonoMethodSignature *csig, *callsig;
4617 MonoMethodBuilder *mb;
4619 GHashTable *cache = NULL;
4620 GHashTable **cache_table = NULL;
4621 MonoMethod *res = NULL;
4623 const char *param_names [16];
4626 /* A simplified version of mono_marshal_get_runtime_invoke */
4628 image = mono_defaults.corlib;
4630 callsig = mono_marshal_get_runtime_invoke_sig (sig);
4632 cache_table = &image->wrapper_caches.runtime_invoke_sig_cache;
4634 cache = get_cache (cache_table, (GHashFunc)mono_signature_hash,
4635 (GCompareFunc)runtime_invoke_signature_equal);
4637 /* from mono_marshal_find_in_cache */
4638 mono_marshal_lock ();
4639 res = (MonoMethod *)g_hash_table_lookup (cache, callsig);
4640 mono_marshal_unlock ();
4647 /* Make a copy of the signature from the image mempool */
4648 callsig = mono_metadata_signature_dup_full (image, callsig);
4650 csig = mono_metadata_signature_alloc (image, 4);
4651 csig->ret = &mono_defaults.object_class->byval_arg;
4652 csig->params [0] = &mono_defaults.object_class->byval_arg;
4653 csig->params [1] = &mono_defaults.int_class->byval_arg;
4654 csig->params [2] = &mono_defaults.int_class->byval_arg;
4655 csig->params [3] = &mono_defaults.int_class->byval_arg;
4658 /* This is called from runtime code so it has to be cdecl */
4659 csig->call_convention = MONO_CALL_C;
4662 name = mono_signature_to_name (callsig, "runtime_invoke_sig");
4663 mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_RUNTIME_INVOKE);
4666 #ifdef HAVE_ONLINE_VES
4667 param_names [0] = "this";
4668 param_names [1] = "params";
4669 param_names [2] = "exc";
4670 param_names [3] = "method";
4671 mono_mb_set_param_names (mb, param_names);
4673 emit_runtime_invoke_body (mb, image, NULL, sig, callsig, FALSE, FALSE);
4676 /* taken from mono_mb_create_and_cache */
4677 mono_marshal_lock ();
4678 res = (MonoMethod *)g_hash_table_lookup (cache, callsig);
4679 mono_marshal_unlock ();
4681 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL);
4682 info->d.runtime_invoke.sig = callsig;
4684 /* Somebody may have created it before us */
4687 newm = mono_mb_create (mb, csig, sig->param_count + 16, info);
4689 mono_marshal_lock ();
4690 res = (MonoMethod *)g_hash_table_lookup (cache, callsig);
4693 g_hash_table_insert (cache, callsig, res);
4695 mono_free_method (newm);
4697 mono_marshal_unlock ();
4700 /* end mono_mb_create_and_cache */
4707 #ifdef HAVE_ONLINE_VES
4709 mono_mb_emit_auto_layout_exception (MonoMethodBuilder *mb, MonoClass *klass)
4711 char *msg = g_strdup_printf ("The type `%s.%s' layout needs to be Sequential or Explicit",
4712 klass->name_space, klass->name);
4714 mono_mb_emit_exception_marshal_directive (mb, msg);
4719 * mono_marshal_get_icall_wrapper:
4720 * Generates IL code for the icall wrapper. The generated method
4721 * calls the unmanaged code in \p func.
4724 mono_marshal_get_icall_wrapper (MonoMethodSignature *sig, const char *name, gconstpointer func, gboolean check_exceptions)
4726 MonoMethodSignature *csig, *csig2;
4727 MonoMethodBuilder *mb;
4732 GHashTable *cache = get_cache (&mono_defaults.object_class->image->icall_wrapper_cache, mono_aligned_addr_hash, NULL);
4733 if ((res = mono_marshal_find_in_cache (cache, (gpointer) func)))
4736 g_assert (sig->pinvoke);
4738 mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
4740 mb->method->save_lmf = 1;
4742 /* Add an explicit this argument */
4744 csig2 = mono_metadata_signature_dup_add_this (mono_defaults.corlib, sig, mono_defaults.object_class);
4746 csig2 = mono_metadata_signature_dup_full (mono_defaults.corlib, sig);
4748 #ifdef HAVE_ONLINE_VES
4750 mono_mb_emit_byte (mb, CEE_LDARG_0);
4752 for (i = 0; i < sig->param_count; i++)
4753 mono_mb_emit_ldarg (mb, i + sig->hasthis);
4755 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
4756 mono_mb_emit_op (mb, CEE_MONO_JIT_ICALL_ADDR, (gpointer)func);
4757 mono_mb_emit_calli (mb, csig2);
4758 if (check_exceptions)
4759 emit_thread_interrupt_checkpoint (mb);
4760 mono_mb_emit_byte (mb, CEE_RET);
4763 csig = mono_metadata_signature_dup_full (mono_defaults.corlib, sig);
4765 if (csig->call_convention == MONO_CALL_VARARG)
4766 csig->call_convention = 0;
4768 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ICALL_WRAPPER);
4769 info->d.icall.func = (gpointer)func;
4770 res = mono_mb_create_and_cache_full (cache, (gpointer) func, mb, csig, csig->param_count + 16, info, NULL);
4777 emit_marshal_custom (EmitMarshalContext *m, int argnum, MonoType *t,
4778 MonoMarshalSpec *spec,
4779 int conv_arg, MonoType **conv_arg_type,
4780 MarshalAction action)
4782 #ifndef HAVE_ONLINE_VES
4783 if (action == MARSHAL_ACTION_CONV_IN && t->type == MONO_TYPE_VALUETYPE)
4784 *conv_arg_type = &mono_defaults.int_class->byval_arg;
4790 static MonoClass *ICustomMarshaler = NULL;
4791 static MonoMethod *cleanup_native, *cleanup_managed;
4792 static MonoMethod *marshal_managed_to_native, *marshal_native_to_managed;
4793 MonoMethod *get_instance = NULL;
4794 MonoMethodBuilder *mb = m->mb;
4795 char *exception_msg = NULL;
4799 if (!ICustomMarshaler) {
4800 MonoClass *klass = mono_class_try_get_icustom_marshaler_class ();
4802 exception_msg = g_strdup ("Current profile doesn't support ICustomMarshaler");
4803 goto handle_exception;
4806 cleanup_native = mono_class_get_method_from_name (klass, "CleanUpNativeData", 1);
4807 g_assert (cleanup_native);
4808 cleanup_managed = mono_class_get_method_from_name (klass, "CleanUpManagedData", 1);
4809 g_assert (cleanup_managed);
4810 marshal_managed_to_native = mono_class_get_method_from_name (klass, "MarshalManagedToNative", 1);
4811 g_assert (marshal_managed_to_native);
4812 marshal_native_to_managed = mono_class_get_method_from_name (klass, "MarshalNativeToManaged", 1);
4813 g_assert (marshal_native_to_managed);
4815 mono_memory_barrier ();
4816 ICustomMarshaler = klass;
4819 if (spec->data.custom_data.image)
4820 mtype = mono_reflection_type_from_name_checked (spec->data.custom_data.custom_name, spec->data.custom_data.image, &error);
4822 mtype = mono_reflection_type_from_name_checked (spec->data.custom_data.custom_name, m->image, &error);
4823 g_assert (mtype != NULL);
4824 mono_error_assert_ok (&error);
4825 mklass = mono_class_from_mono_type (mtype);
4826 g_assert (mklass != NULL);
4828 if (!mono_class_is_assignable_from (ICustomMarshaler, mklass))
4829 exception_msg = g_strdup_printf ("Custom marshaler '%s' does not implement the ICustomMarshaler interface.", mklass->name);
4831 get_instance = mono_class_get_method_from_name_flags (mklass, "GetInstance", 1, METHOD_ATTRIBUTE_STATIC);
4833 MonoMethodSignature *get_sig = mono_method_signature (get_instance);
4834 if ((get_sig->ret->type != MONO_TYPE_CLASS) ||
4835 (mono_class_from_mono_type (get_sig->ret) != ICustomMarshaler) ||
4836 (get_sig->params [0]->type != MONO_TYPE_STRING))
4837 get_instance = NULL;
4841 exception_msg = g_strdup_printf ("Custom marshaler '%s' does not implement a static GetInstance method that takes a single string parameter and returns an ICustomMarshaler.", mklass->name);
4844 /* Throw exception and emit compensation code if neccesary */
4845 if (exception_msg) {
4847 case MARSHAL_ACTION_CONV_IN:
4848 case MARSHAL_ACTION_CONV_RESULT:
4849 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
4850 if ((action == MARSHAL_ACTION_CONV_RESULT) || (action == MARSHAL_ACTION_MANAGED_CONV_RESULT))
4851 mono_mb_emit_byte (mb, CEE_POP);
4853 mono_mb_emit_exception_full (mb, "System", "ApplicationException", exception_msg);
4856 case MARSHAL_ACTION_PUSH:
4857 mono_mb_emit_byte (mb, CEE_LDNULL);
4865 /* FIXME: MS.NET seems to create one instance for each klass + cookie pair */
4866 /* FIXME: MS.NET throws an exception if GetInstance returns null */
4869 case MARSHAL_ACTION_CONV_IN:
4871 case MONO_TYPE_CLASS:
4872 case MONO_TYPE_OBJECT:
4873 case MONO_TYPE_STRING:
4874 case MONO_TYPE_ARRAY:
4875 case MONO_TYPE_SZARRAY:
4876 case MONO_TYPE_VALUETYPE:
4880 g_warning ("custom marshalling of type %x is currently not supported", t->type);
4881 g_assert_not_reached ();
4885 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
4887 mono_mb_emit_byte (mb, CEE_LDNULL);
4888 mono_mb_emit_stloc (mb, conv_arg);
4890 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT))
4893 /* Minic MS.NET behavior */
4894 if (!t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT) && !(t->attrs & PARAM_ATTRIBUTE_IN))
4897 /* Check for null */
4898 mono_mb_emit_ldarg (mb, argnum);
4900 mono_mb_emit_byte (mb, CEE_LDIND_I);
4901 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4903 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4905 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4907 mono_mb_emit_ldarg (mb, argnum);
4909 mono_mb_emit_byte (mb, CEE_LDIND_REF);
4911 if (t->type == MONO_TYPE_VALUETYPE) {
4913 * Since we can't determine the type of the argument, we
4914 * will assume the unmanaged function takes a pointer.
4916 *conv_arg_type = &mono_defaults.int_class->byval_arg;
4918 mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (t));
4921 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_managed_to_native);
4922 mono_mb_emit_stloc (mb, conv_arg);
4924 mono_mb_patch_branch (mb, pos2);
4927 case MARSHAL_ACTION_CONV_OUT:
4928 /* Check for null */
4929 mono_mb_emit_ldloc (mb, conv_arg);
4930 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4933 mono_mb_emit_ldarg (mb, argnum);
4935 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4937 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4939 mono_mb_emit_ldloc (mb, conv_arg);
4940 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
4941 mono_mb_emit_byte (mb, CEE_STIND_REF);
4942 } else if (t->attrs & PARAM_ATTRIBUTE_OUT) {
4943 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4945 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4947 mono_mb_emit_ldloc (mb, conv_arg);
4948 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
4950 /* We have nowhere to store the result */
4951 mono_mb_emit_byte (mb, CEE_POP);
4954 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4956 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4958 mono_mb_emit_ldloc (mb, conv_arg);
4960 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_native);
4962 mono_mb_patch_branch (mb, pos2);
4965 case MARSHAL_ACTION_PUSH:
4967 mono_mb_emit_ldloc_addr (mb, conv_arg);
4969 mono_mb_emit_ldloc (mb, conv_arg);
4972 case MARSHAL_ACTION_CONV_RESULT:
4973 loc1 = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
4975 mono_mb_emit_stloc (mb, 3);
4977 mono_mb_emit_ldloc (mb, 3);
4978 mono_mb_emit_stloc (mb, loc1);
4980 /* Check for null */
4981 mono_mb_emit_ldloc (mb, 3);
4982 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4984 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4986 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4987 mono_mb_emit_byte (mb, CEE_DUP);
4989 mono_mb_emit_ldloc (mb, 3);
4990 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
4991 mono_mb_emit_stloc (mb, 3);
4993 mono_mb_emit_ldloc (mb, loc1);
4994 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_native);
4996 mono_mb_patch_branch (mb, pos2);
4999 case MARSHAL_ACTION_MANAGED_CONV_IN:
5000 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
5002 mono_mb_emit_byte (mb, CEE_LDNULL);
5003 mono_mb_emit_stloc (mb, conv_arg);
5005 if (t->byref && t->attrs & PARAM_ATTRIBUTE_OUT)
5008 /* Check for null */
5009 mono_mb_emit_ldarg (mb, argnum);
5011 mono_mb_emit_byte (mb, CEE_LDIND_I);
5012 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
5014 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
5015 mono_mb_emit_op (mb, CEE_CALL, get_instance);
5017 mono_mb_emit_ldarg (mb, argnum);
5019 mono_mb_emit_byte (mb, CEE_LDIND_I);
5021 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
5022 mono_mb_emit_stloc (mb, conv_arg);
5024 mono_mb_patch_branch (mb, pos2);
5027 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5028 g_assert (!t->byref);
5030 loc1 = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
5032 mono_mb_emit_stloc (mb, 3);
5034 mono_mb_emit_ldloc (mb, 3);
5035 mono_mb_emit_stloc (mb, loc1);
5037 /* Check for null */
5038 mono_mb_emit_ldloc (mb, 3);
5039 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
5041 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
5042 mono_mb_emit_op (mb, CEE_CALL, get_instance);
5043 mono_mb_emit_byte (mb, CEE_DUP);
5045 mono_mb_emit_ldloc (mb, 3);
5046 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_managed_to_native);
5047 mono_mb_emit_stloc (mb, 3);
5049 mono_mb_emit_ldloc (mb, loc1);
5050 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_managed);
5052 mono_mb_patch_branch (mb, pos2);
5055 case MARSHAL_ACTION_MANAGED_CONV_OUT:
5057 /* Check for null */
5058 mono_mb_emit_ldloc (mb, conv_arg);
5059 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
5062 mono_mb_emit_ldarg (mb, argnum);
5064 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
5066 mono_mb_emit_op (mb, CEE_CALL, get_instance);
5068 mono_mb_emit_ldloc (mb, conv_arg);
5069 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_managed_to_native);
5070 mono_mb_emit_byte (mb, CEE_STIND_I);
5073 /* Call CleanUpManagedData */
5074 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
5076 mono_mb_emit_op (mb, CEE_CALL, get_instance);
5078 mono_mb_emit_ldloc (mb, conv_arg);
5079 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_managed);
5081 mono_mb_patch_branch (mb, pos2);
5085 g_assert_not_reached ();
5093 emit_marshal_asany (EmitMarshalContext *m, int argnum, MonoType *t,
5094 MonoMarshalSpec *spec,
5095 int conv_arg, MonoType **conv_arg_type,
5096 MarshalAction action)
5098 #ifdef HAVE_ONLINE_VES
5099 MonoMethodBuilder *mb = m->mb;
5102 case MARSHAL_ACTION_CONV_IN: {
5103 MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, NULL);
5105 g_assert (t->type == MONO_TYPE_OBJECT);
5106 g_assert (!t->byref);
5108 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5109 mono_mb_emit_ldarg (mb, argnum);
5110 mono_mb_emit_icon (mb, encoding);
5111 mono_mb_emit_icon (mb, t->attrs);
5112 mono_mb_emit_icall (mb, mono_marshal_asany);
5113 mono_mb_emit_stloc (mb, conv_arg);
5117 case MARSHAL_ACTION_PUSH:
5118 mono_mb_emit_ldloc (mb, conv_arg);
5121 case MARSHAL_ACTION_CONV_OUT: {
5122 MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, NULL);
5124 mono_mb_emit_ldarg (mb, argnum);
5125 mono_mb_emit_ldloc (mb, conv_arg);
5126 mono_mb_emit_icon (mb, encoding);
5127 mono_mb_emit_icon (mb, t->attrs);
5128 mono_mb_emit_icall (mb, mono_marshal_free_asany);
5133 g_assert_not_reached ();
5140 emit_marshal_vtype (EmitMarshalContext *m, int argnum, MonoType *t,
5141 MonoMarshalSpec *spec,
5142 int conv_arg, MonoType **conv_arg_type,
5143 MarshalAction action)
5145 #ifdef HAVE_ONLINE_VES
5146 MonoMethodBuilder *mb = m->mb;
5147 MonoClass *klass, *date_time_class;
5150 klass = mono_class_from_mono_type (t);
5152 date_time_class = mono_class_get_date_time_class ();
5155 case MARSHAL_ACTION_CONV_IN:
5156 if (klass == date_time_class) {
5157 /* Convert it to an OLE DATE type */
5158 static MonoMethod *to_oadate;
5161 to_oadate = mono_class_get_method_from_name (date_time_class, "ToOADate", 0);
5162 g_assert (to_oadate);
5164 conv_arg = mono_mb_add_local (mb, &mono_defaults.double_class->byval_arg);
5167 mono_mb_emit_ldarg (mb, argnum);
5168 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5171 if (!(t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && (t->attrs & PARAM_ATTRIBUTE_OUT))) {
5173 m->csig->params [argnum - m->csig->hasthis] = &mono_defaults.double_class->byval_arg;
5175 mono_mb_emit_ldarg_addr (mb, argnum);
5176 mono_mb_emit_managed_call (mb, to_oadate, NULL);
5177 mono_mb_emit_stloc (mb, conv_arg);
5181 mono_mb_patch_branch (mb, pos);
5185 if (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype)
5188 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5190 /* store the address of the source into local variable 0 */
5192 mono_mb_emit_ldarg (mb, argnum);
5194 mono_mb_emit_ldarg_addr (mb, argnum);
5196 mono_mb_emit_stloc (mb, 0);
5198 /* allocate space for the native struct and
5199 * store the address into local variable 1 (dest) */
5200 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
5201 mono_mb_emit_byte (mb, CEE_PREFIX1);
5202 mono_mb_emit_byte (mb, CEE_LOCALLOC);
5203 mono_mb_emit_stloc (mb, conv_arg);
5206 mono_mb_emit_ldloc (mb, 0);
5207 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5210 if (!(t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && (t->attrs & PARAM_ATTRIBUTE_OUT))) {
5212 mono_mb_emit_ldloc (mb, conv_arg);
5213 mono_mb_emit_stloc (mb, 1);
5215 /* emit valuetype conversion code */
5216 emit_struct_conv (mb, klass, FALSE);
5220 mono_mb_patch_branch (mb, pos);
5223 case MARSHAL_ACTION_PUSH:
5224 if (spec && spec->native == MONO_NATIVE_LPSTRUCT) {
5226 g_assert (!t->byref);
5228 /* Have to change the signature since the vtype is passed byref */
5229 m->csig->params [argnum - m->csig->hasthis] = &mono_defaults.int_class->byval_arg;
5231 if (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype)
5232 mono_mb_emit_ldarg_addr (mb, argnum);
5234 mono_mb_emit_ldloc (mb, conv_arg);
5238 if (klass == date_time_class) {
5240 mono_mb_emit_ldloc_addr (mb, conv_arg);
5242 mono_mb_emit_ldloc (mb, conv_arg);
5246 if (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype) {
5247 mono_mb_emit_ldarg (mb, argnum);
5250 mono_mb_emit_ldloc (mb, conv_arg);
5252 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5253 mono_mb_emit_op (mb, CEE_MONO_LDNATIVEOBJ, klass);
5257 case MARSHAL_ACTION_CONV_OUT:
5258 if (klass == date_time_class) {
5259 /* Convert from an OLE DATE type */
5260 static MonoMethod *from_oadate;
5265 if (!((t->attrs & PARAM_ATTRIBUTE_IN) && !(t->attrs & PARAM_ATTRIBUTE_OUT))) {
5267 from_oadate = mono_class_get_method_from_name (date_time_class, "FromOADate", 1);
5268 g_assert (from_oadate);
5270 mono_mb_emit_ldarg (mb, argnum);
5271 mono_mb_emit_ldloc (mb, conv_arg);
5272 mono_mb_emit_managed_call (mb, from_oadate, NULL);
5273 mono_mb_emit_op (mb, CEE_STOBJ, date_time_class);
5278 if (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype)
5282 /* dst = argument */
5283 mono_mb_emit_ldarg (mb, argnum);
5284 mono_mb_emit_stloc (mb, 1);
5286 mono_mb_emit_ldloc (mb, 1);
5287 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5289 if (!((t->attrs & PARAM_ATTRIBUTE_IN) && !(t->attrs & PARAM_ATTRIBUTE_OUT))) {
5290 /* src = tmp_locals [i] */
5291 mono_mb_emit_ldloc (mb, conv_arg);
5292 mono_mb_emit_stloc (mb, 0);
5294 /* emit valuetype conversion code */
5295 emit_struct_conv (mb, klass, TRUE);
5299 emit_struct_free (mb, klass, conv_arg);
5302 mono_mb_patch_branch (mb, pos);
5305 case MARSHAL_ACTION_CONV_RESULT:
5306 if (mono_class_is_explicit_layout (klass) || klass->blittable) {
5307 mono_mb_emit_stloc (mb, 3);
5311 /* load pointer to returned value type */
5312 g_assert (m->vtaddr_var);
5313 mono_mb_emit_ldloc (mb, m->vtaddr_var);
5314 /* store the address of the source into local variable 0 */
5315 mono_mb_emit_stloc (mb, 0);
5317 mono_mb_emit_ldloc_addr (mb, 3);
5318 mono_mb_emit_stloc (mb, 1);
5320 /* emit valuetype conversion code */
5321 emit_struct_conv (mb, klass, TRUE);
5324 case MARSHAL_ACTION_MANAGED_CONV_IN:
5325 if (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype) {
5330 conv_arg = mono_mb_add_local (mb, &klass->byval_arg);
5332 if (t->attrs & PARAM_ATTRIBUTE_OUT)
5336 mono_mb_emit_ldarg (mb, argnum);
5338 mono_mb_emit_ldarg_addr (mb, argnum);
5339 mono_mb_emit_stloc (mb, 0);
5342 mono_mb_emit_ldloc (mb, 0);
5343 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5346 mono_mb_emit_ldloc_addr (mb, conv_arg);
5347 mono_mb_emit_stloc (mb, 1);
5349 /* emit valuetype conversion code */
5350 emit_struct_conv (mb, klass, TRUE);
5353 mono_mb_patch_branch (mb, pos);
5356 case MARSHAL_ACTION_MANAGED_CONV_OUT:
5357 if (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype)
5359 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_IN) && !(t->attrs & PARAM_ATTRIBUTE_OUT))
5362 /* Check for null */
5363 mono_mb_emit_ldarg (mb, argnum);
5364 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
5367 mono_mb_emit_ldloc_addr (mb, conv_arg);
5368 mono_mb_emit_stloc (mb, 0);
5371 mono_mb_emit_ldarg (mb, argnum);
5372 mono_mb_emit_stloc (mb, 1);
5374 /* emit valuetype conversion code */
5375 emit_struct_conv (mb, klass, FALSE);
5377 mono_mb_patch_branch (mb, pos2);
5380 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5381 if (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype) {
5382 mono_mb_emit_stloc (mb, 3);
5387 /* load pointer to returned value type */
5388 g_assert (m->vtaddr_var);
5389 mono_mb_emit_ldloc (mb, m->vtaddr_var);
5391 /* store the address of the source into local variable 0 */
5392 mono_mb_emit_stloc (mb, 0);
5393 /* allocate space for the native struct and
5394 * store the address into dst_ptr */
5395 m->retobj_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5396 m->retobj_class = klass;
5397 g_assert (m->retobj_var);
5398 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
5399 mono_mb_emit_byte (mb, CEE_CONV_I);
5400 mono_mb_emit_icall (mb, ves_icall_marshal_alloc);
5401 mono_mb_emit_stloc (mb, 1);
5402 mono_mb_emit_ldloc (mb, 1);
5403 mono_mb_emit_stloc (mb, m->retobj_var);
5405 /* emit valuetype conversion code */
5406 emit_struct_conv (mb, klass, FALSE);
5410 g_assert_not_reached ();
5417 emit_marshal_string (EmitMarshalContext *m, int argnum, MonoType *t,
5418 MonoMarshalSpec *spec,
5419 int conv_arg, MonoType **conv_arg_type,
5420 MarshalAction action)
5422 #ifndef HAVE_ONLINE_VES
5424 case MARSHAL_ACTION_CONV_IN:
5425 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5427 case MARSHAL_ACTION_MANAGED_CONV_IN:
5428 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5432 MonoMethodBuilder *mb = m->mb;
5433 MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
5434 MonoMarshalConv conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
5438 case MARSHAL_ACTION_CONV_IN:
5439 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5440 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5443 if (t->attrs & PARAM_ATTRIBUTE_OUT)
5446 mono_mb_emit_ldarg (mb, argnum);
5447 mono_mb_emit_byte (mb, CEE_LDIND_I);
5449 mono_mb_emit_ldarg (mb, argnum);
5452 if (conv == MONO_MARSHAL_CONV_INVALID) {
5453 char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
5454 mono_mb_emit_exception_marshal_directive (mb, msg);
5456 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
5458 mono_mb_emit_stloc (mb, conv_arg);
5462 case MARSHAL_ACTION_CONV_OUT:
5463 conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
5464 if (conv == MONO_MARSHAL_CONV_INVALID) {
5465 char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
5466 mono_mb_emit_exception_marshal_directive (mb, msg);
5470 if (encoding == MONO_NATIVE_VBBYREFSTR) {
5471 static MonoMethod *m;
5474 m = mono_class_get_method_from_name_flags (mono_defaults.string_class, "get_Length", -1, 0);
5479 char *msg = g_strdup_printf ("VBByRefStr marshalling requires a ref parameter.", encoding);
5480 mono_mb_emit_exception_marshal_directive (mb, msg);
5485 * Have to allocate a new string with the same length as the original, and
5486 * copy the contents of the buffer pointed to by CONV_ARG into it.
5488 g_assert (t->byref);
5489 mono_mb_emit_ldarg (mb, argnum);
5490 mono_mb_emit_ldloc (mb, conv_arg);
5491 mono_mb_emit_ldarg (mb, argnum);
5492 mono_mb_emit_byte (mb, CEE_LDIND_I);
5493 mono_mb_emit_managed_call (mb, m, NULL);
5494 mono_mb_emit_icall (mb, mono_string_new_len_wrapper);
5495 mono_mb_emit_byte (mb, CEE_STIND_REF);
5496 } else if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT || !(t->attrs & PARAM_ATTRIBUTE_IN))) {
5498 mono_mb_emit_ldarg (mb, argnum);
5499 mono_mb_emit_ldloc (mb, conv_arg);
5500 mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
5501 mono_mb_emit_byte (mb, stind_op);
5506 mono_mb_emit_ldloc (mb, conv_arg);
5507 if (conv == MONO_MARSHAL_CONV_BSTR_STR)
5508 mono_mb_emit_icall (mb, mono_free_bstr);
5510 mono_mb_emit_icall (mb, mono_marshal_free);
5514 case MARSHAL_ACTION_PUSH:
5515 if (t->byref && encoding != MONO_NATIVE_VBBYREFSTR)
5516 mono_mb_emit_ldloc_addr (mb, conv_arg);
5518 mono_mb_emit_ldloc (mb, conv_arg);
5521 case MARSHAL_ACTION_CONV_RESULT:
5522 mono_mb_emit_stloc (mb, 0);
5524 conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
5525 if (conv == MONO_MARSHAL_CONV_INVALID) {
5526 char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
5527 mono_mb_emit_exception_marshal_directive (mb, msg);
5531 mono_mb_emit_ldloc (mb, 0);
5532 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
5533 mono_mb_emit_stloc (mb, 3);
5535 /* free the string */
5536 mono_mb_emit_ldloc (mb, 0);
5537 if (conv == MONO_MARSHAL_CONV_BSTR_STR)
5538 mono_mb_emit_icall (mb, mono_free_bstr);
5540 mono_mb_emit_icall (mb, mono_marshal_free);
5543 case MARSHAL_ACTION_MANAGED_CONV_IN:
5544 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
5546 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5549 if (t->attrs & PARAM_ATTRIBUTE_OUT)
5553 conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
5554 if (conv == MONO_MARSHAL_CONV_INVALID) {
5555 char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
5556 mono_mb_emit_exception_marshal_directive (mb, msg);
5560 mono_mb_emit_ldarg (mb, argnum);
5562 mono_mb_emit_byte (mb, CEE_LDIND_I);
5563 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
5564 mono_mb_emit_stloc (mb, conv_arg);
5567 case MARSHAL_ACTION_MANAGED_CONV_OUT:
5571 mono_mb_emit_ldarg (mb, argnum);
5572 mono_mb_emit_ldloc (mb, conv_arg);
5573 mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
5574 mono_mb_emit_byte (mb, stind_op);
5579 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5580 if (conv_to_icall (conv, NULL) == mono_marshal_string_to_utf16)
5581 /* We need to make a copy so the caller is able to free it */
5582 mono_mb_emit_icall (mb, mono_marshal_string_to_utf16_copy);
5584 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
5585 mono_mb_emit_stloc (mb, 3);
5589 g_assert_not_reached ();
5597 emit_marshal_safehandle (EmitMarshalContext *m, int argnum, MonoType *t,
5598 MonoMarshalSpec *spec, int conv_arg,
5599 MonoType **conv_arg_type, MarshalAction action)
5601 #ifndef HAVE_ONLINE_VES
5602 if (action == MARSHAL_ACTION_CONV_IN)
5603 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5605 MonoMethodBuilder *mb = m->mb;
5608 case MARSHAL_ACTION_CONV_IN: {
5609 MonoType *intptr_type;
5610 int dar_release_slot, pos;
5612 intptr_type = &mono_defaults.int_class->byval_arg;
5613 conv_arg = mono_mb_add_local (mb, intptr_type);
5614 *conv_arg_type = intptr_type;
5616 if (!sh_dangerous_add_ref)
5617 init_safe_handle ();
5619 mono_mb_emit_ldarg (mb, argnum);
5620 pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
5621 mono_mb_emit_exception (mb, "ArgumentNullException", NULL);
5623 mono_mb_patch_branch (mb, pos);
5626 * My tests in show that ref SafeHandles are not really
5627 * passed as ref objects. Instead a NULL is passed as the
5630 mono_mb_emit_icon (mb, 0);
5631 mono_mb_emit_stloc (mb, conv_arg);
5635 /* Create local to hold the ref parameter to DangerousAddRef */
5636 dar_release_slot = mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
5638 /* set release = false; */
5639 mono_mb_emit_icon (mb, 0);
5640 mono_mb_emit_stloc (mb, dar_release_slot);
5642 /* safehandle.DangerousAddRef (ref release) */
5643 mono_mb_emit_ldarg (mb, argnum);
5644 mono_mb_emit_ldloc_addr (mb, dar_release_slot);
5645 mono_mb_emit_managed_call (mb, sh_dangerous_add_ref, NULL);
5647 /* Pull the handle field from SafeHandle */
5648 mono_mb_emit_ldarg (mb, argnum);
5649 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoSafeHandle, handle));
5650 mono_mb_emit_byte (mb, CEE_LDIND_I);
5651 mono_mb_emit_stloc (mb, conv_arg);
5656 case MARSHAL_ACTION_PUSH:
5658 mono_mb_emit_ldloc_addr (mb, conv_arg);
5660 mono_mb_emit_ldloc (mb, conv_arg);
5663 case MARSHAL_ACTION_CONV_OUT: {
5664 /* The slot for the boolean is the next temporary created after conv_arg, see the CONV_IN code */
5665 int dar_release_slot = conv_arg + 1;
5668 if (!sh_dangerous_release)
5669 init_safe_handle ();
5675 * My tests indicate that ref SafeHandles parameters are not actually
5676 * passed by ref, but instead a new Handle is created regardless of
5677 * whether a change happens in the unmanaged side.
5679 * Also, the Handle is created before calling into unmanaged code,
5680 * but we do not support that mechanism (getting to the original
5681 * handle) and it makes no difference where we create this
5683 ctor = mono_class_get_method_from_name (t->data.klass, ".ctor", 0);
5685 mono_mb_emit_exception (mb, "MissingMethodException", "paramterless constructor required");
5688 /* refval = new SafeHandleDerived ()*/
5689 mono_mb_emit_ldarg (mb, argnum);
5690 mono_mb_emit_op (mb, CEE_NEWOBJ, ctor);
5691 mono_mb_emit_byte (mb, CEE_STIND_REF);
5693 /* refval.handle = returned_handle */
5694 mono_mb_emit_ldarg (mb, argnum);
5695 mono_mb_emit_byte (mb, CEE_LDIND_REF);
5696 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoSafeHandle, handle));
5697 mono_mb_emit_ldloc (mb, conv_arg);
5698 mono_mb_emit_byte (mb, CEE_STIND_I);
5700 mono_mb_emit_ldloc (mb, dar_release_slot);
5701 label_next = mono_mb_emit_branch (mb, CEE_BRFALSE);
5702 mono_mb_emit_ldarg (mb, argnum);
5703 mono_mb_emit_managed_call (mb, sh_dangerous_release, NULL);
5704 mono_mb_patch_branch (mb, label_next);
5709 case MARSHAL_ACTION_CONV_RESULT: {
5710 MonoMethod *ctor = NULL;
5711 int intptr_handle_slot;
5713 if (mono_class_is_abstract (t->data.klass)) {
5714 mono_mb_emit_byte (mb, CEE_POP);
5715 mono_mb_emit_exception_marshal_directive (mb, g_strdup ("Returned SafeHandles should not be abstract"));
5719 ctor = mono_class_get_method_from_name (t->data.klass, ".ctor", 0);
5721 mono_mb_emit_byte (mb, CEE_POP);
5722 mono_mb_emit_exception (mb, "MissingMethodException", "paramterless constructor required");
5725 /* Store the IntPtr results into a local */
5726 intptr_handle_slot = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5727 mono_mb_emit_stloc (mb, intptr_handle_slot);
5729 /* Create return value */
5730 mono_mb_emit_op (mb, CEE_NEWOBJ, ctor);
5731 mono_mb_emit_stloc (mb, 3);
5733 /* Set the return.handle to the value, am using ldflda, not sure if thats a good idea */
5734 mono_mb_emit_ldloc (mb, 3);
5735 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoSafeHandle, handle));
5736 mono_mb_emit_ldloc (mb, intptr_handle_slot);
5737 mono_mb_emit_byte (mb, CEE_STIND_I);
5741 case MARSHAL_ACTION_MANAGED_CONV_IN:
5742 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_IN\n");
5745 case MARSHAL_ACTION_MANAGED_CONV_OUT:
5746 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_OUT\n");
5749 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5750 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_RESULT\n");
5753 printf ("Unhandled case for MarshalAction: %d\n", action);
5761 emit_marshal_handleref (EmitMarshalContext *m, int argnum, MonoType *t,
5762 MonoMarshalSpec *spec, int conv_arg,
5763 MonoType **conv_arg_type, MarshalAction action)
5765 #ifndef HAVE_ONLINE_VES
5766 if (action == MARSHAL_ACTION_CONV_IN)
5767 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5769 MonoMethodBuilder *mb = m->mb;
5772 case MARSHAL_ACTION_CONV_IN: {
5773 MonoType *intptr_type;
5775 intptr_type = &mono_defaults.int_class->byval_arg;
5776 conv_arg = mono_mb_add_local (mb, intptr_type);
5777 *conv_arg_type = intptr_type;
5780 char *msg = g_strdup ("HandleRefs can not be returned from unmanaged code (or passed by ref)");
5781 mono_mb_emit_exception_marshal_directive (mb, msg);
5784 mono_mb_emit_ldarg_addr (mb, argnum);
5785 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoHandleRef, handle));
5786 mono_mb_emit_byte (mb, CEE_ADD);
5787 mono_mb_emit_byte (mb, CEE_LDIND_I);
5788 mono_mb_emit_stloc (mb, conv_arg);
5792 case MARSHAL_ACTION_PUSH:
5793 mono_mb_emit_ldloc (mb, conv_arg);
5796 case MARSHAL_ACTION_CONV_OUT: {
5797 /* no resource release required */
5801 case MARSHAL_ACTION_CONV_RESULT: {
5802 char *msg = g_strdup ("HandleRefs can not be returned from unmanaged code (or passed by ref)");
5803 mono_mb_emit_exception_marshal_directive (mb, msg);
5807 case MARSHAL_ACTION_MANAGED_CONV_IN:
5808 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_IN\n");
5811 case MARSHAL_ACTION_MANAGED_CONV_OUT:
5812 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_OUT\n");
5815 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5816 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_RESULT\n");
5819 fprintf (stderr, "Unhandled case for MarshalAction: %d\n", action);
5827 emit_marshal_object (EmitMarshalContext *m, int argnum, MonoType *t,
5828 MonoMarshalSpec *spec,
5829 int conv_arg, MonoType **conv_arg_type,
5830 MarshalAction action)
5832 #ifndef HAVE_ONLINE_VES
5833 if (action == MARSHAL_ACTION_CONV_IN)
5834 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5836 MonoMethodBuilder *mb = m->mb;
5837 MonoClass *klass = mono_class_from_mono_type (t);
5841 case MARSHAL_ACTION_CONV_IN:
5842 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5843 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5845 m->orig_conv_args [argnum] = 0;
5847 if (mono_class_from_mono_type (t) == mono_defaults.object_class) {
5848 char *msg = g_strdup_printf ("Marshalling of type object is not implemented");
5849 mono_mb_emit_exception_marshal_directive (mb, msg);
5853 if (klass->delegate) {
5855 if (!(t->attrs & PARAM_ATTRIBUTE_OUT)) {
5856 char *msg = g_strdup_printf ("Byref marshalling of delegates is not implemented.");
5857 mono_mb_emit_exception_marshal_directive (mb, msg);
5859 mono_mb_emit_byte (mb, CEE_LDNULL);
5860 mono_mb_emit_stloc (mb, conv_arg);
5862 mono_mb_emit_ldarg (mb, argnum);
5863 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_DEL_FTN, NULL));
5864 mono_mb_emit_stloc (mb, conv_arg);
5866 } else if (klass == mono_defaults.stringbuilder_class) {
5867 MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
5868 MonoMarshalConv conv = mono_marshal_get_stringbuilder_to_ptr_conv (m->piinfo, spec);
5872 if (!(t->attrs & PARAM_ATTRIBUTE_OUT)) {
5873 char *msg = g_strdup_printf ("Byref marshalling of stringbuilders is not implemented.");
5874 mono_mb_emit_exception_marshal_directive (mb, msg);
5880 if (t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && (t->attrs & PARAM_ATTRIBUTE_OUT))
5883 if (conv == MONO_MARSHAL_CONV_INVALID) {
5884 char *msg = g_strdup_printf ("stringbuilder marshalling conversion %d not implemented", encoding);
5885 mono_mb_emit_exception_marshal_directive (mb, msg);
5889 mono_mb_emit_ldarg (mb, argnum);
5891 mono_mb_emit_byte (mb, CEE_LDIND_I);
5893 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
5894 mono_mb_emit_stloc (mb, conv_arg);
5895 } else if (klass->blittable) {
5896 mono_mb_emit_byte (mb, CEE_LDNULL);
5897 mono_mb_emit_stloc (mb, conv_arg);
5899 mono_mb_emit_ldarg (mb, argnum);
5900 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5902 mono_mb_emit_ldarg (mb, argnum);
5903 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5904 mono_mb_emit_stloc (mb, conv_arg);
5906 mono_mb_patch_branch (mb, pos);
5909 mono_mb_emit_byte (mb, CEE_LDNULL);
5910 mono_mb_emit_stloc (mb, conv_arg);
5913 /* we dont need any conversions for out parameters */
5914 if (t->attrs & PARAM_ATTRIBUTE_OUT)
5917 mono_mb_emit_ldarg (mb, argnum);
5918 mono_mb_emit_byte (mb, CEE_LDIND_I);
5921 mono_mb_emit_ldarg (mb, argnum);
5922 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5923 mono_mb_emit_byte (mb, CEE_MONO_OBJADDR);
5926 /* store the address of the source into local variable 0 */
5927 mono_mb_emit_stloc (mb, 0);
5928 mono_mb_emit_ldloc (mb, 0);
5929 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5931 /* allocate space for the native struct and store the address */
5932 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
5933 mono_mb_emit_byte (mb, CEE_PREFIX1);
5934 mono_mb_emit_byte (mb, CEE_LOCALLOC);
5935 mono_mb_emit_stloc (mb, conv_arg);
5938 /* Need to store the original buffer so we can free it later */
5939 m->orig_conv_args [argnum] = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5940 mono_mb_emit_ldloc (mb, conv_arg);
5941 mono_mb_emit_stloc (mb, m->orig_conv_args [argnum]);
5944 /* set the src_ptr */
5945 mono_mb_emit_ldloc (mb, 0);
5946 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5947 mono_mb_emit_stloc (mb, 0);
5950 mono_mb_emit_ldloc (mb, conv_arg);
5951 mono_mb_emit_stloc (mb, 1);
5953 /* emit valuetype conversion code */
5954 emit_struct_conv (mb, klass, FALSE);
5956 mono_mb_patch_branch (mb, pos);
5960 case MARSHAL_ACTION_CONV_OUT:
5961 if (klass == mono_defaults.stringbuilder_class) {
5963 MonoMarshalNative encoding;
5964 MonoMarshalConv conv;
5966 encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
5967 conv = mono_marshal_get_ptr_to_stringbuilder_conv (m->piinfo, spec, &need_free);
5969 g_assert (encoding != -1);
5972 //g_assert (!(t->attrs & PARAM_ATTRIBUTE_OUT));
5976 mono_mb_emit_ldarg (mb, argnum);
5977 mono_mb_emit_ldloc (mb, conv_arg);
5980 case MONO_NATIVE_LPWSTR:
5981 mono_mb_emit_icall (mb, mono_string_utf16_to_builder2);
5983 case MONO_NATIVE_LPSTR:
5984 mono_mb_emit_icall (mb, mono_string_utf8_to_builder2);
5986 case MONO_NATIVE_UTF8STR:
5987 mono_mb_emit_icall (mb, mono_string_utf8_to_builder2);
5990 g_assert_not_reached ();
5993 mono_mb_emit_byte (mb, CEE_STIND_REF);
5995 mono_mb_emit_ldarg (mb, argnum);
5996 mono_mb_emit_ldloc (mb, conv_arg);
5998 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
6002 mono_mb_emit_ldloc (mb, conv_arg);
6003 mono_mb_emit_icall (mb, mono_marshal_free);
6008 if (klass->delegate) {
6010 mono_mb_emit_ldarg (mb, argnum);
6011 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
6012 mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
6013 mono_mb_emit_ldloc (mb, conv_arg);
6014 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL, NULL));
6015 mono_mb_emit_byte (mb, CEE_STIND_REF);
6020 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT)) {
6021 /* allocate a new object */
6022 mono_mb_emit_ldarg (mb, argnum);
6023 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
6024 mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, klass);
6025 mono_mb_emit_byte (mb, CEE_STIND_REF);
6028 /* dst = *argument */
6029 mono_mb_emit_ldarg (mb, argnum);
6032 mono_mb_emit_byte (mb, CEE_LDIND_I);
6034 mono_mb_emit_stloc (mb, 1);
6036 mono_mb_emit_ldloc (mb, 1);
6037 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
6039 if (t->byref || (t->attrs & PARAM_ATTRIBUTE_OUT)) {
6040 mono_mb_emit_ldloc (mb, 1);
6041 mono_mb_emit_icon (mb, sizeof (MonoObject));
6042 mono_mb_emit_byte (mb, CEE_ADD);
6043 mono_mb_emit_stloc (mb, 1);
6045 /* src = tmp_locals [i] */
6046 mono_mb_emit_ldloc (mb, conv_arg);
6047 mono_mb_emit_stloc (mb, 0);
6049 /* emit valuetype conversion code */
6050 emit_struct_conv (mb, klass, TRUE);
6052 /* Free the structure returned by the native code */
6053 emit_struct_free (mb, klass, conv_arg);
6055 if (m->orig_conv_args [argnum]) {
6057 * If the native function changed the pointer, then free
6058 * the original structure plus the new pointer.
6060 mono_mb_emit_ldloc (mb, m->orig_conv_args [argnum]);
6061 mono_mb_emit_ldloc (mb, conv_arg);
6062 pos2 = mono_mb_emit_branch (mb, CEE_BEQ);
6064 if (!(t->attrs & PARAM_ATTRIBUTE_OUT)) {
6065 g_assert (m->orig_conv_args [argnum]);
6067 emit_struct_free (mb, klass, m->orig_conv_args [argnum]);
6070 mono_mb_emit_ldloc (mb, conv_arg);
6071 mono_mb_emit_icall (mb, mono_marshal_free);
6073 mono_mb_patch_branch (mb, pos2);
6077 /* Free the original structure passed to native code */
6078 emit_struct_free (mb, klass, conv_arg);
6080 mono_mb_patch_branch (mb, pos);
6083 case MARSHAL_ACTION_PUSH:
6085 mono_mb_emit_ldloc_addr (mb, conv_arg);
6087 mono_mb_emit_ldloc (mb, conv_arg);
6090 case MARSHAL_ACTION_CONV_RESULT:
6091 if (klass->delegate) {
6092 g_assert (!t->byref);
6093 mono_mb_emit_stloc (mb, 0);
6094 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
6095 mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
6096 mono_mb_emit_ldloc (mb, 0);
6097 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL, NULL));
6098 mono_mb_emit_stloc (mb, 3);
6099 } else if (klass == mono_defaults.stringbuilder_class) {
6101 char *msg = g_strdup_printf ("Return marshalling of stringbuilders is not implemented.");
6102 mono_mb_emit_exception_marshal_directive (mb, msg);
6105 mono_mb_emit_stloc (mb, 0);
6107 /* Make a copy since emit_conv modifies local 0 */
6108 loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6109 mono_mb_emit_ldloc (mb, 0);
6110 mono_mb_emit_stloc (mb, loc);
6112 mono_mb_emit_byte (mb, CEE_LDNULL);
6113 mono_mb_emit_stloc (mb, 3);
6115 mono_mb_emit_ldloc (mb, 0);
6116 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
6118 /* allocate result object */
6120 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
6121 mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, klass);
6122 mono_mb_emit_stloc (mb, 3);
6126 mono_mb_emit_ldloc (mb, 3);
6127 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
6128 mono_mb_emit_stloc (mb, 1);
6130 /* emit conversion code */
6131 emit_struct_conv (mb, klass, TRUE);
6133 emit_struct_free (mb, klass, loc);
6135 /* Free the pointer allocated by unmanaged code */
6136 mono_mb_emit_ldloc (mb, loc);
6137 mono_mb_emit_icall (mb, mono_marshal_free);
6138 mono_mb_patch_branch (mb, pos);
6142 case MARSHAL_ACTION_MANAGED_CONV_IN:
6143 conv_arg = mono_mb_add_local (mb, &klass->byval_arg);
6145 if (klass->delegate) {
6146 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
6147 mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
6148 mono_mb_emit_ldarg (mb, argnum);
6150 mono_mb_emit_byte (mb, CEE_LDIND_I);
6151 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL, NULL));
6152 mono_mb_emit_stloc (mb, conv_arg);
6156 if (klass == mono_defaults.stringbuilder_class) {
6157 MonoMarshalNative encoding;
6159 encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
6162 g_assert (encoding == MONO_NATIVE_LPSTR || encoding == MONO_NATIVE_UTF8STR);
6164 g_assert (!t->byref);
6165 g_assert (encoding != -1);
6167 mono_mb_emit_ldarg (mb, argnum);
6168 mono_mb_emit_icall (mb, mono_string_utf8_to_builder2);
6169 mono_mb_emit_stloc (mb, conv_arg);
6173 /* The class can not have an automatic layout */
6174 if (mono_class_is_auto_layout (klass)) {
6175 mono_mb_emit_auto_layout_exception (mb, klass);
6179 if (t->attrs & PARAM_ATTRIBUTE_OUT) {
6180 mono_mb_emit_byte (mb, CEE_LDNULL);
6181 mono_mb_emit_stloc (mb, conv_arg);
6186 mono_mb_emit_ldarg (mb, argnum);
6190 /* Check for NULL and raise an exception */
6191 pos2 = mono_mb_emit_branch (mb, CEE_BRTRUE);
6193 mono_mb_emit_exception (mb, "ArgumentNullException", NULL);
6195 mono_mb_patch_branch (mb, pos2);
6196 mono_mb_emit_ldarg (mb, argnum);
6197 mono_mb_emit_byte (mb, CEE_LDIND_I);
6200 mono_mb_emit_stloc (mb, 0);
6202 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6203 mono_mb_emit_stloc (mb, conv_arg);
6205 mono_mb_emit_ldloc (mb, 0);
6206 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
6208 /* Create and set dst */
6209 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
6210 mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, klass);
6211 mono_mb_emit_stloc (mb, conv_arg);
6212 mono_mb_emit_ldloc (mb, conv_arg);
6213 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
6214 mono_mb_emit_stloc (mb, 1);
6216 /* emit valuetype conversion code */
6217 emit_struct_conv (mb, klass, TRUE);
6219 mono_mb_patch_branch (mb, pos);
6222 case MARSHAL_ACTION_MANAGED_CONV_OUT:
6223 if (klass->delegate) {
6226 mono_mb_emit_ldarg (mb, argnum);
6227 mono_mb_emit_ldloc (mb, conv_arg);
6228 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_DEL_FTN, &stind_op));
6229 mono_mb_emit_byte (mb, stind_op);
6235 /* Check for null */
6236 mono_mb_emit_ldloc (mb, conv_arg);
6237 pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
6238 mono_mb_emit_ldarg (mb, argnum);
6239 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6240 mono_mb_emit_byte (mb, CEE_STIND_REF);
6241 pos2 = mono_mb_emit_branch (mb, CEE_BR);
6243 mono_mb_patch_branch (mb, pos);
6246 mono_mb_emit_ldloc (mb, conv_arg);
6247 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
6248 mono_mb_emit_stloc (mb, 0);
6250 /* Allocate and set dest */
6251 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
6252 mono_mb_emit_byte (mb, CEE_CONV_I);
6253 mono_mb_emit_icall (mb, ves_icall_marshal_alloc);
6254 mono_mb_emit_stloc (mb, 1);
6256 /* Update argument pointer */
6257 mono_mb_emit_ldarg (mb, argnum);
6258 mono_mb_emit_ldloc (mb, 1);
6259 mono_mb_emit_byte (mb, CEE_STIND_I);
6261 /* emit valuetype conversion code */
6262 emit_struct_conv (mb, klass, FALSE);
6264 mono_mb_patch_branch (mb, pos2);
6265 } else if (klass == mono_defaults.stringbuilder_class) {
6266 // FIXME: What to do here ?
6268 /* byval [Out] marshalling */
6270 /* FIXME: Handle null */
6273 mono_mb_emit_ldloc (mb, conv_arg);
6274 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
6275 mono_mb_emit_stloc (mb, 0);
6278 mono_mb_emit_ldarg (mb, argnum);
6279 mono_mb_emit_stloc (mb, 1);
6281 /* emit valuetype conversion code */
6282 emit_struct_conv (mb, klass, FALSE);
6286 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
6287 if (klass->delegate) {
6288 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_DEL_FTN, NULL));
6289 mono_mb_emit_stloc (mb, 3);
6293 /* The class can not have an automatic layout */
6294 if (mono_class_is_auto_layout (klass)) {
6295 mono_mb_emit_auto_layout_exception (mb, klass);
6299 mono_mb_emit_stloc (mb, 0);
6300 /* Check for null */
6301 mono_mb_emit_ldloc (mb, 0);
6302 pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
6303 mono_mb_emit_byte (mb, CEE_LDNULL);
6304 mono_mb_emit_stloc (mb, 3);
6305 pos2 = mono_mb_emit_branch (mb, CEE_BR);
6307 mono_mb_patch_branch (mb, pos);
6310 mono_mb_emit_ldloc (mb, 0);
6311 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
6312 mono_mb_emit_stloc (mb, 0);
6314 /* Allocate and set dest */
6315 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
6316 mono_mb_emit_byte (mb, CEE_CONV_I);
6317 mono_mb_emit_icall (mb, ves_icall_marshal_alloc);
6318 mono_mb_emit_byte (mb, CEE_DUP);
6319 mono_mb_emit_stloc (mb, 1);
6320 mono_mb_emit_stloc (mb, 3);
6322 emit_struct_conv (mb, klass, FALSE);
6324 mono_mb_patch_branch (mb, pos2);
6328 g_assert_not_reached ();
6334 #ifdef HAVE_ONLINE_VES
6338 emit_marshal_variant (EmitMarshalContext *m, int argnum, MonoType *t,
6339 MonoMarshalSpec *spec,
6340 int conv_arg, MonoType **conv_arg_type,
6341 MarshalAction action)
6343 MonoMethodBuilder *mb = m->mb;
6344 static MonoMethod *get_object_for_native_variant = NULL;
6345 static MonoMethod *get_native_variant_for_object = NULL;
6347 if (!get_object_for_native_variant)
6348 get_object_for_native_variant = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetObjectForNativeVariant", 1);
6349 g_assert (get_object_for_native_variant);
6351 if (!get_native_variant_for_object)
6352 get_native_variant_for_object = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetNativeVariantForObject", 2);
6353 g_assert (get_native_variant_for_object);
6356 case MARSHAL_ACTION_CONV_IN: {
6357 conv_arg = mono_mb_add_local (mb, &mono_class_get_variant_class ()->byval_arg);
6360 *conv_arg_type = &mono_class_get_variant_class ()->this_arg;
6362 *conv_arg_type = &mono_class_get_variant_class ()->byval_arg;
6364 if (t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && t->attrs & PARAM_ATTRIBUTE_OUT)
6367 mono_mb_emit_ldarg (mb, argnum);
6369 mono_mb_emit_byte(mb, CEE_LDIND_REF);
6370 mono_mb_emit_ldloc_addr (mb, conv_arg);
6371 mono_mb_emit_managed_call (mb, get_native_variant_for_object, NULL);
6375 case MARSHAL_ACTION_CONV_OUT: {
6376 static MonoMethod *variant_clear = NULL;
6379 variant_clear = mono_class_get_method_from_name (mono_class_get_variant_class (), "Clear", 0);
6380 g_assert (variant_clear);
6383 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT || !(t->attrs & PARAM_ATTRIBUTE_IN))) {
6384 mono_mb_emit_ldarg (mb, argnum);
6385 mono_mb_emit_ldloc_addr (mb, conv_arg);
6386 mono_mb_emit_managed_call (mb, get_object_for_native_variant, NULL);
6387 mono_mb_emit_byte (mb, CEE_STIND_REF);
6390 mono_mb_emit_ldloc_addr (mb, conv_arg);
6391 mono_mb_emit_managed_call (mb, variant_clear, NULL);
6395 case MARSHAL_ACTION_PUSH:
6397 mono_mb_emit_ldloc_addr (mb, conv_arg);
6399 mono_mb_emit_ldloc (mb, conv_arg);
6402 case MARSHAL_ACTION_CONV_RESULT: {
6403 char *msg = g_strdup ("Marshalling of VARIANT not supported as a return type.");
6404 mono_mb_emit_exception_marshal_directive (mb, msg);
6408 case MARSHAL_ACTION_MANAGED_CONV_IN: {
6409 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6412 *conv_arg_type = &mono_class_get_variant_class ()->this_arg;
6414 *conv_arg_type = &mono_class_get_variant_class ()->byval_arg;
6416 if (t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && t->attrs & PARAM_ATTRIBUTE_OUT)
6420 mono_mb_emit_ldarg (mb, argnum);
6422 mono_mb_emit_ldarg_addr (mb, argnum);
6423 mono_mb_emit_managed_call (mb, get_object_for_native_variant, NULL);
6424 mono_mb_emit_stloc (mb, conv_arg);
6428 case MARSHAL_ACTION_MANAGED_CONV_OUT: {
6429 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT || !(t->attrs & PARAM_ATTRIBUTE_IN))) {
6430 mono_mb_emit_ldloc (mb, conv_arg);
6431 mono_mb_emit_ldarg (mb, argnum);
6432 mono_mb_emit_managed_call (mb, get_native_variant_for_object, NULL);
6437 case MARSHAL_ACTION_MANAGED_CONV_RESULT: {
6438 char *msg = g_strdup ("Marshalling of VARIANT not supported as a return type.");
6439 mono_mb_emit_exception_marshal_directive (mb, msg);
6444 g_assert_not_reached ();
6450 #endif /* DISABLE_COM */
6451 #endif /* HAVE_ONLINE_VES */
6454 mono_pinvoke_is_unicode (MonoMethodPInvoke *piinfo)
6456 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
6457 case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
6459 case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
6461 case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
6473 emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
6474 MonoMarshalSpec *spec,
6475 int conv_arg, MonoType **conv_arg_type,
6476 MarshalAction action)
6478 #ifndef HAVE_ONLINE_VES
6480 case MARSHAL_ACTION_CONV_IN:
6481 *conv_arg_type = &mono_defaults.object_class->byval_arg;
6483 case MARSHAL_ACTION_MANAGED_CONV_IN:
6484 *conv_arg_type = &mono_defaults.int_class->byval_arg;
6488 MonoMethodBuilder *mb = m->mb;
6489 MonoClass *klass = mono_class_from_mono_type (t);
6490 gboolean need_convert, need_free;
6491 MonoMarshalNative encoding;
6493 encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
6496 case MARSHAL_ACTION_CONV_IN:
6497 *conv_arg_type = &mono_defaults.object_class->byval_arg;
6498 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6500 if (klass->element_class->blittable) {
6501 mono_mb_emit_ldarg (mb, argnum);
6503 mono_mb_emit_byte (mb, CEE_LDIND_I);
6504 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_ARRAY_LPARRAY, NULL));
6505 mono_mb_emit_stloc (mb, conv_arg);
6508 guint32 label1, label2, label3;
6509 int index_var, src_var, dest_ptr, esize;
6510 MonoMarshalConv conv;
6511 gboolean is_string = FALSE;
6513 dest_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6515 eklass = klass->element_class;
6517 if (eklass == mono_defaults.string_class) {
6519 conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
6521 else if (eklass == mono_defaults.stringbuilder_class) {
6523 conv = mono_marshal_get_stringbuilder_to_ptr_conv (m->piinfo, spec);
6526 conv = MONO_MARSHAL_CONV_INVALID;
6528 if (is_string && conv == MONO_MARSHAL_CONV_INVALID) {
6529 char *msg = g_strdup_printf ("string/stringbuilder marshalling conversion %d not implemented", encoding);
6530 mono_mb_emit_exception_marshal_directive (mb, msg);
6534 src_var = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6535 mono_mb_emit_ldarg (mb, argnum);
6537 mono_mb_emit_byte (mb, CEE_LDIND_I);
6538 mono_mb_emit_stloc (mb, src_var);
6541 mono_mb_emit_ldloc (mb, src_var);
6542 mono_mb_emit_stloc (mb, conv_arg);
6543 mono_mb_emit_ldloc (mb, src_var);
6544 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6547 esize = sizeof (gpointer);
6548 else if (eklass == mono_defaults.char_class) /*can't call mono_marshal_type_size since it causes all sorts of asserts*/
6549 esize = mono_pinvoke_is_unicode (m->piinfo) ? 2 : 1;
6551 esize = mono_class_native_size (eklass, NULL);
6553 /* allocate space for the native struct and store the address */
6554 mono_mb_emit_icon (mb, esize);
6555 mono_mb_emit_ldloc (mb, src_var);
6556 mono_mb_emit_byte (mb, CEE_LDLEN);
6558 if (eklass == mono_defaults.string_class) {
6559 /* Make the array bigger for the terminating null */
6560 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
6561 mono_mb_emit_byte (mb, CEE_ADD);
6563 mono_mb_emit_byte (mb, CEE_MUL);
6564 mono_mb_emit_byte (mb, CEE_PREFIX1);
6565 mono_mb_emit_byte (mb, CEE_LOCALLOC);
6566 mono_mb_emit_stloc (mb, conv_arg);
6568 mono_mb_emit_ldloc (mb, conv_arg);
6569 mono_mb_emit_stloc (mb, dest_ptr);
6571 /* Emit marshalling loop */
6572 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6573 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6574 mono_mb_emit_stloc (mb, index_var);
6575 label2 = mono_mb_get_label (mb);
6576 mono_mb_emit_ldloc (mb, index_var);
6577 mono_mb_emit_ldloc (mb, src_var);
6578 mono_mb_emit_byte (mb, CEE_LDLEN);
6579 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6581 /* Emit marshalling code */
6585 mono_mb_emit_ldloc (mb, dest_ptr);
6586 mono_mb_emit_ldloc (mb, src_var);
6587 mono_mb_emit_ldloc (mb, index_var);
6588 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
6589 mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
6590 mono_mb_emit_byte (mb, stind_op);
6592 /* set the src_ptr */
6593 mono_mb_emit_ldloc (mb, src_var);
6594 mono_mb_emit_ldloc (mb, index_var);
6595 mono_mb_emit_op (mb, CEE_LDELEMA, eklass);
6596 mono_mb_emit_stloc (mb, 0);
6599 mono_mb_emit_ldloc (mb, dest_ptr);
6600 mono_mb_emit_stloc (mb, 1);
6602 /* emit valuetype conversion code */
6603 emit_struct_conv_full (mb, eklass, FALSE, 0, eklass == mono_defaults.char_class ? encoding : (MonoMarshalNative)-1);
6606 mono_mb_emit_add_to_local (mb, index_var, 1);
6607 mono_mb_emit_add_to_local (mb, dest_ptr, esize);
6609 mono_mb_emit_branch_label (mb, CEE_BR, label2);
6611 mono_mb_patch_branch (mb, label3);
6613 if (eklass == mono_defaults.string_class) {
6614 /* Null terminate */
6615 mono_mb_emit_ldloc (mb, dest_ptr);
6616 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6617 mono_mb_emit_byte (mb, CEE_STIND_REF);
6620 mono_mb_patch_branch (mb, label1);
6625 case MARSHAL_ACTION_CONV_OUT:
6626 /* Unicode character arrays are implicitly marshalled as [Out] under MS.NET */
6627 need_convert = ((klass->element_class == mono_defaults.char_class) && (encoding == MONO_NATIVE_LPWSTR)) || (klass->element_class == mono_defaults.stringbuilder_class) || (t->attrs & PARAM_ATTRIBUTE_OUT);
6628 need_free = mono_marshal_need_free (&klass->element_class->byval_arg,
6631 if ((t->attrs & PARAM_ATTRIBUTE_OUT) && spec && spec->native == MONO_NATIVE_LPARRAY && spec->data.array_data.param_num != -1) {
6632 int param_num = spec->data.array_data.param_num;
6633 MonoType *param_type;
6635 param_type = m->sig->params [param_num];
6637 if (param_type->byref && param_type->type != MONO_TYPE_I4) {
6638 char *msg = g_strdup ("Not implemented.");
6639 mono_mb_emit_exception_marshal_directive (mb, msg);
6644 mono_mb_emit_ldarg (mb, argnum);
6646 /* Create the managed array */
6647 mono_mb_emit_ldarg (mb, param_num);
6648 if (m->sig->params [param_num]->byref)
6649 // FIXME: Support other types
6650 mono_mb_emit_byte (mb, CEE_LDIND_I4);
6651 mono_mb_emit_byte (mb, CEE_CONV_OVF_I);
6652 mono_mb_emit_op (mb, CEE_NEWARR, klass->element_class);
6653 /* Store into argument */
6654 mono_mb_emit_byte (mb, CEE_STIND_REF);
6658 if (need_convert || need_free) {
6659 /* FIXME: Optimize blittable case */
6661 guint32 label1, label2, label3;
6662 int index_var, src_ptr, loc, esize;
6664 eklass = klass->element_class;
6665 if ((eklass == mono_defaults.stringbuilder_class) || (eklass == mono_defaults.string_class))
6666 esize = sizeof (gpointer);
6667 else if (eklass == mono_defaults.char_class)
6668 esize = mono_pinvoke_is_unicode (m->piinfo) ? 2 : 1;
6670 esize = mono_class_native_size (eklass, NULL);
6671 src_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6672 loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6675 mono_mb_emit_ldarg (mb, argnum);
6677 mono_mb_emit_byte (mb, CEE_LDIND_I);
6678 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6680 mono_mb_emit_ldloc (mb, conv_arg);
6681 mono_mb_emit_stloc (mb, src_ptr);
6683 /* Emit marshalling loop */
6684 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6685 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6686 mono_mb_emit_stloc (mb, index_var);
6687 label2 = mono_mb_get_label (mb);
6688 mono_mb_emit_ldloc (mb, index_var);
6689 mono_mb_emit_ldarg (mb, argnum);
6691 mono_mb_emit_byte (mb, CEE_LDIND_REF);
6692 mono_mb_emit_byte (mb, CEE_LDLEN);
6693 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6695 /* Emit marshalling code */
6697 if (eklass == mono_defaults.stringbuilder_class) {
6698 gboolean need_free2;
6699 MonoMarshalConv conv = mono_marshal_get_ptr_to_stringbuilder_conv (m->piinfo, spec, &need_free2);
6701 g_assert (conv != MONO_MARSHAL_CONV_INVALID);
6704 mono_mb_emit_ldarg (mb, argnum);
6706 mono_mb_emit_byte (mb, CEE_LDIND_I);
6707 mono_mb_emit_ldloc (mb, index_var);
6708 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
6711 mono_mb_emit_ldloc (mb, src_ptr);
6712 mono_mb_emit_byte (mb, CEE_LDIND_I);
6714 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
6718 mono_mb_emit_ldloc (mb, src_ptr);
6719 mono_mb_emit_byte (mb, CEE_LDIND_I);
6721 mono_mb_emit_icall (mb, mono_marshal_free);
6724 else if (eklass == mono_defaults.string_class) {
6727 mono_mb_emit_ldloc (mb, src_ptr);
6728 mono_mb_emit_byte (mb, CEE_LDIND_I);
6730 mono_mb_emit_icall (mb, mono_marshal_free);
6735 /* set the src_ptr */
6736 mono_mb_emit_ldloc (mb, src_ptr);
6737 mono_mb_emit_stloc (mb, 0);
6740 mono_mb_emit_ldarg (mb, argnum);
6742 mono_mb_emit_byte (mb, CEE_LDIND_REF);
6743 mono_mb_emit_ldloc (mb, index_var);
6744 mono_mb_emit_op (mb, CEE_LDELEMA, eklass);
6745 mono_mb_emit_stloc (mb, 1);
6747 /* emit valuetype conversion code */
6748 emit_struct_conv_full (mb, eklass, TRUE, 0, eklass == mono_defaults.char_class ? encoding : (MonoMarshalNative)-1);
6752 mono_mb_emit_ldloc (mb, src_ptr);
6753 mono_mb_emit_stloc (mb, loc);
6754 mono_mb_emit_ldloc (mb, loc);
6756 emit_struct_free (mb, eklass, loc);
6760 mono_mb_emit_add_to_local (mb, index_var, 1);
6761 mono_mb_emit_add_to_local (mb, src_ptr, esize);
6763 mono_mb_emit_branch_label (mb, CEE_BR, label2);
6765 mono_mb_patch_branch (mb, label1);
6766 mono_mb_patch_branch (mb, label3);
6769 if (klass->element_class->blittable) {
6770 /* free memory allocated (if any) by MONO_MARSHAL_CONV_ARRAY_LPARRAY */
6772 mono_mb_emit_ldarg (mb, argnum);
6774 mono_mb_emit_byte (mb, CEE_LDIND_REF);
6775 mono_mb_emit_ldloc (mb, conv_arg);
6776 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_FREE_LPARRAY, NULL));
6781 case MARSHAL_ACTION_PUSH:
6783 mono_mb_emit_ldloc_addr (mb, conv_arg);
6785 mono_mb_emit_ldloc (mb, conv_arg);
6788 case MARSHAL_ACTION_CONV_RESULT:
6789 /* fixme: we need conversions here */
6790 mono_mb_emit_stloc (mb, 3);
6793 case MARSHAL_ACTION_MANAGED_CONV_IN: {
6795 guint32 label1, label2, label3;
6796 int index_var, src_ptr, esize, param_num, num_elem;
6797 MonoMarshalConv conv;
6798 gboolean is_string = FALSE;
6800 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6801 *conv_arg_type = &mono_defaults.int_class->byval_arg;
6804 char *msg = g_strdup ("Byref array marshalling to managed code is not implemented.");
6805 mono_mb_emit_exception_marshal_directive (mb, msg);
6809 char *msg = g_strdup ("[MarshalAs] attribute required to marshal arrays to managed code.");
6810 mono_mb_emit_exception_marshal_directive (mb, msg);
6813 if (spec->native != MONO_NATIVE_LPARRAY) {
6814 char *msg = g_strdup ("Non LPArray marshalling of arrays to managed code is not implemented.");
6815 mono_mb_emit_exception_marshal_directive (mb, msg);
6819 /* FIXME: t is from the method which is wrapped, not the delegate type */
6820 /* g_assert (t->attrs & PARAM_ATTRIBUTE_IN); */
6822 param_num = spec->data.array_data.param_num;
6823 num_elem = spec->data.array_data.num_elem;
6824 if (spec->data.array_data.elem_mult == 0)
6825 /* param_num is not specified */
6828 if (param_num == -1) {
6829 if (num_elem <= 0) {
6830 char *msg = g_strdup ("Either SizeConst or SizeParamIndex should be specified when marshalling arrays to managed code.");
6831 mono_mb_emit_exception_marshal_directive (mb, msg);
6836 /* FIXME: Optimize blittable case */
6838 eklass = klass->element_class;
6839 if (eklass == mono_defaults.string_class) {
6841 conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
6843 else if (eklass == mono_defaults.stringbuilder_class) {
6845 conv = mono_marshal_get_ptr_to_stringbuilder_conv (m->piinfo, spec, &need_free);
6848 conv = MONO_MARSHAL_CONV_INVALID;
6850 mono_marshal_load_type_info (eklass);
6853 esize = sizeof (gpointer);
6855 esize = mono_class_native_size (eklass, NULL);
6856 src_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6858 mono_mb_emit_byte (mb, CEE_LDNULL);
6859 mono_mb_emit_stloc (mb, conv_arg);
6861 /* Check param index */
6862 if (param_num != -1) {
6863 if (param_num >= m->sig->param_count) {
6864 char *msg = g_strdup ("Array size control parameter index is out of range.");
6865 mono_mb_emit_exception_marshal_directive (mb, msg);
6868 switch (m->sig->params [param_num]->type) {
6881 char *msg = g_strdup ("Array size control parameter must be an integral type.");
6882 mono_mb_emit_exception_marshal_directive (mb, msg);
6889 mono_mb_emit_ldarg (mb, argnum);
6890 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6892 mono_mb_emit_ldarg (mb, argnum);
6893 mono_mb_emit_stloc (mb, src_ptr);
6895 /* Create managed array */
6897 * The LPArray marshalling spec says that sometimes param_num starts
6898 * from 1, sometimes it starts from 0. But MS seems to allways start
6902 if (param_num == -1) {
6903 mono_mb_emit_icon (mb, num_elem);
6905 mono_mb_emit_ldarg (mb, param_num);
6907 mono_mb_emit_icon (mb, num_elem);
6908 mono_mb_emit_byte (mb, CEE_ADD);
6910 mono_mb_emit_byte (mb, CEE_CONV_OVF_I);
6913 mono_mb_emit_op (mb, CEE_NEWARR, eklass);
6914 mono_mb_emit_stloc (mb, conv_arg);
6916 if (eklass->blittable) {
6917 mono_mb_emit_ldloc (mb, conv_arg);
6918 mono_mb_emit_byte (mb, CEE_CONV_I);
6919 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
6920 mono_mb_emit_byte (mb, CEE_ADD);
6921 mono_mb_emit_ldarg (mb, argnum);
6922 mono_mb_emit_ldloc (mb, conv_arg);
6923 mono_mb_emit_byte (mb, CEE_LDLEN);
6924 mono_mb_emit_icon (mb, esize);
6925 mono_mb_emit_byte (mb, CEE_MUL);
6926 mono_mb_emit_byte (mb, CEE_PREFIX1);
6927 mono_mb_emit_byte (mb, CEE_CPBLK);
6928 mono_mb_patch_branch (mb, label1);
6932 /* Emit marshalling loop */
6933 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6934 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6935 mono_mb_emit_stloc (mb, index_var);
6936 label2 = mono_mb_get_label (mb);
6937 mono_mb_emit_ldloc (mb, index_var);
6938 mono_mb_emit_ldloc (mb, conv_arg);
6939 mono_mb_emit_byte (mb, CEE_LDLEN);
6940 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6942 /* Emit marshalling code */
6944 g_assert (conv != MONO_MARSHAL_CONV_INVALID);
6946 mono_mb_emit_ldloc (mb, conv_arg);
6947 mono_mb_emit_ldloc (mb, index_var);
6949 mono_mb_emit_ldloc (mb, src_ptr);
6950 mono_mb_emit_byte (mb, CEE_LDIND_I);
6952 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
6953 mono_mb_emit_byte (mb, CEE_STELEM_REF);
6956 char *msg = g_strdup ("Marshalling of non-string and non-blittable arrays to managed code is not implemented.");
6957 mono_mb_emit_exception_marshal_directive (mb, msg);
6961 mono_mb_emit_add_to_local (mb, index_var, 1);
6962 mono_mb_emit_add_to_local (mb, src_ptr, esize);
6964 mono_mb_emit_branch_label (mb, CEE_BR, label2);
6966 mono_mb_patch_branch (mb, label1);
6967 mono_mb_patch_branch (mb, label3);
6971 case MARSHAL_ACTION_MANAGED_CONV_OUT: {
6973 guint32 label1, label2, label3;
6974 int index_var, dest_ptr, esize, param_num, num_elem;
6975 MonoMarshalConv conv;
6976 gboolean is_string = FALSE;
6979 /* Already handled in CONV_IN */
6982 /* These are already checked in CONV_IN */
6983 g_assert (!t->byref);
6984 g_assert (spec->native == MONO_NATIVE_LPARRAY);
6985 g_assert (t->attrs & PARAM_ATTRIBUTE_OUT);
6987 param_num = spec->data.array_data.param_num;
6988 num_elem = spec->data.array_data.num_elem;
6990 if (spec->data.array_data.elem_mult == 0)
6991 /* param_num is not specified */
6994 if (param_num == -1) {
6995 if (num_elem <= 0) {
6996 g_assert_not_reached ();
7000 /* FIXME: Optimize blittable case */
7002 eklass = klass->element_class;
7003 if (eklass == mono_defaults.string_class) {
7005 conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
7007 else if (eklass == mono_defaults.stringbuilder_class) {
7009 conv = mono_marshal_get_stringbuilder_to_ptr_conv (m->piinfo, spec);
7012 conv = MONO_MARSHAL_CONV_INVALID;
7014 mono_marshal_load_type_info (eklass);
7017 esize = sizeof (gpointer);
7019 esize = mono_class_native_size (eklass, NULL);
7021 dest_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7024 mono_mb_emit_ldloc (mb, conv_arg);
7025 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
7027 mono_mb_emit_ldarg (mb, argnum);
7028 mono_mb_emit_stloc (mb, dest_ptr);
7030 if (eklass->blittable) {
7032 mono_mb_emit_ldarg (mb, argnum);
7034 mono_mb_emit_ldloc (mb, conv_arg);
7035 mono_mb_emit_byte (mb, CEE_CONV_I);
7036 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
7037 mono_mb_emit_byte (mb, CEE_ADD);
7039 mono_mb_emit_ldloc (mb, conv_arg);
7040 mono_mb_emit_byte (mb, CEE_LDLEN);
7041 mono_mb_emit_icon (mb, esize);
7042 mono_mb_emit_byte (mb, CEE_MUL);
7043 mono_mb_emit_byte (mb, CEE_PREFIX1);
7044 mono_mb_emit_byte (mb, CEE_CPBLK);
7048 /* Emit marshalling loop */
7049 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7050 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
7051 mono_mb_emit_stloc (mb, index_var);
7052 label2 = mono_mb_get_label (mb);
7053 mono_mb_emit_ldloc (mb, index_var);
7054 mono_mb_emit_ldloc (mb, conv_arg);
7055 mono_mb_emit_byte (mb, CEE_LDLEN);
7056 label3 = mono_mb_emit_branch (mb, CEE_BGE);
7058 /* Emit marshalling code */
7061 g_assert (conv != MONO_MARSHAL_CONV_INVALID);
7064 mono_mb_emit_ldloc (mb, dest_ptr);
7067 mono_mb_emit_ldloc (mb, conv_arg);
7068 mono_mb_emit_ldloc (mb, index_var);
7070 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
7072 mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
7073 mono_mb_emit_byte (mb, stind_op);
7076 char *msg = g_strdup ("Marshalling of non-string and non-blittable arrays to managed code is not implemented.");
7077 mono_mb_emit_exception_marshal_directive (mb, msg);
7081 mono_mb_emit_add_to_local (mb, index_var, 1);
7082 mono_mb_emit_add_to_local (mb, dest_ptr, esize);
7084 mono_mb_emit_branch_label (mb, CEE_BR, label2);
7086 mono_mb_patch_branch (mb, label1);
7087 mono_mb_patch_branch (mb, label3);
7091 case MARSHAL_ACTION_MANAGED_CONV_RESULT: {
7093 guint32 label1, label2, label3;
7094 int index_var, src, dest, esize;
7095 MonoMarshalConv conv = MONO_MARSHAL_CONV_INVALID;
7096 gboolean is_string = FALSE;
7098 g_assert (!t->byref);
7100 eklass = klass->element_class;
7102 mono_marshal_load_type_info (eklass);
7104 if (eklass == mono_defaults.string_class) {
7106 conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
7109 g_assert_not_reached ();
7113 esize = sizeof (gpointer);
7114 else if (eklass == mono_defaults.char_class)
7115 esize = mono_pinvoke_is_unicode (m->piinfo) ? 2 : 1;
7117 esize = mono_class_native_size (eklass, NULL);
7119 src = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
7120 dest = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7122 mono_mb_emit_stloc (mb, src);
7123 mono_mb_emit_ldloc (mb, src);
7124 mono_mb_emit_stloc (mb, 3);
7126 /* Check for null */
7127 mono_mb_emit_ldloc (mb, src);
7128 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
7130 /* Allocate native array */
7131 mono_mb_emit_icon (mb, esize);
7132 mono_mb_emit_ldloc (mb, src);
7133 mono_mb_emit_byte (mb, CEE_LDLEN);
7135 if (eklass == mono_defaults.string_class) {
7136 /* Make the array bigger for the terminating null */
7137 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
7138 mono_mb_emit_byte (mb, CEE_ADD);
7140 mono_mb_emit_byte (mb, CEE_MUL);
7141 mono_mb_emit_icall (mb, ves_icall_marshal_alloc);
7142 mono_mb_emit_stloc (mb, dest);
7143 mono_mb_emit_ldloc (mb, dest);
7144 mono_mb_emit_stloc (mb, 3);
7146 /* Emit marshalling loop */
7147 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7148 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
7149 mono_mb_emit_stloc (mb, index_var);
7150 label2 = mono_mb_get_label (mb);
7151 mono_mb_emit_ldloc (mb, index_var);
7152 mono_mb_emit_ldloc (mb, src);
7153 mono_mb_emit_byte (mb, CEE_LDLEN);
7154 label3 = mono_mb_emit_branch (mb, CEE_BGE);
7156 /* Emit marshalling code */
7159 g_assert (conv != MONO_MARSHAL_CONV_INVALID);
7162 mono_mb_emit_ldloc (mb, dest);
7165 mono_mb_emit_ldloc (mb, src);
7166 mono_mb_emit_ldloc (mb, index_var);
7168 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
7170 mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
7171 mono_mb_emit_byte (mb, stind_op);
7174 char *msg = g_strdup ("Marshalling of non-string arrays to managed code is not implemented.");
7175 mono_mb_emit_exception_marshal_directive (mb, msg);
7179 mono_mb_emit_add_to_local (mb, index_var, 1);
7180 mono_mb_emit_add_to_local (mb, dest, esize);
7182 mono_mb_emit_branch_label (mb, CEE_BR, label2);
7184 mono_mb_patch_branch (mb, label3);
7185 mono_mb_patch_branch (mb, label1);
7189 g_assert_not_reached ();
7196 marshal_boolean_conv_in_get_local_type (MonoMarshalSpec *spec, guint8 *ldc_op /*out*/)
7199 return &mono_defaults.int32_class->byval_arg;
7201 switch (spec->native) {
7202 case MONO_NATIVE_I1:
7203 case MONO_NATIVE_U1:
7204 return &mono_defaults.byte_class->byval_arg;
7205 case MONO_NATIVE_VARIANTBOOL:
7206 if (ldc_op) *ldc_op = CEE_LDC_I4_M1;
7207 return &mono_defaults.int16_class->byval_arg;
7208 case MONO_NATIVE_BOOLEAN:
7209 return &mono_defaults.int32_class->byval_arg;
7211 g_warning ("marshalling bool as native type %x is currently not supported", spec->native);
7212 return &mono_defaults.int32_class->byval_arg;
7218 marshal_boolean_managed_conv_in_get_conv_arg_class (MonoMarshalSpec *spec, guint8 *ldop/*out*/)
7220 MonoClass* conv_arg_class = mono_defaults.int32_class;
7222 switch (spec->native) {
7223 case MONO_NATIVE_I1:
7224 case MONO_NATIVE_U1:
7225 conv_arg_class = mono_defaults.byte_class;
7226 if (ldop) *ldop = CEE_LDIND_I1;
7228 case MONO_NATIVE_VARIANTBOOL:
7229 conv_arg_class = mono_defaults.int16_class;
7230 if (ldop) *ldop = CEE_LDIND_I2;
7232 case MONO_NATIVE_BOOLEAN:
7235 g_warning ("marshalling bool as native type %x is currently not supported", spec->native);
7238 return conv_arg_class;
7242 emit_marshal_boolean (EmitMarshalContext *m, int argnum, MonoType *t,
7243 MonoMarshalSpec *spec,
7244 int conv_arg, MonoType **conv_arg_type,
7245 MarshalAction action)
7247 #ifndef HAVE_ONLINE_VES
7249 case MARSHAL_ACTION_CONV_IN:
7251 *conv_arg_type = &mono_defaults.int_class->byval_arg;
7253 *conv_arg_type = marshal_boolean_conv_in_get_local_type (spec, NULL);
7256 case MARSHAL_ACTION_MANAGED_CONV_IN: {
7257 MonoClass* conv_arg_class = marshal_boolean_managed_conv_in_get_conv_arg_class (spec, NULL);
7259 *conv_arg_type = &conv_arg_class->this_arg;
7261 *conv_arg_type = &conv_arg_class->byval_arg;
7267 MonoMethodBuilder *mb = m->mb;
7270 case MARSHAL_ACTION_CONV_IN: {
7271 MonoType *local_type;
7273 guint8 ldc_op = CEE_LDC_I4_1;
7275 local_type = marshal_boolean_conv_in_get_local_type (spec, &ldc_op);
7277 *conv_arg_type = &mono_defaults.int_class->byval_arg;
7279 *conv_arg_type = local_type;
7280 conv_arg = mono_mb_add_local (mb, local_type);
7282 mono_mb_emit_ldarg (mb, argnum);
7284 mono_mb_emit_byte (mb, CEE_LDIND_I1);
7285 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
7286 mono_mb_emit_byte (mb, ldc_op);
7287 mono_mb_emit_stloc (mb, conv_arg);
7288 mono_mb_patch_branch (mb, label_false);
7293 case MARSHAL_ACTION_CONV_OUT:
7295 int label_false, label_end;
7299 mono_mb_emit_ldarg (mb, argnum);
7300 mono_mb_emit_ldloc (mb, conv_arg);
7302 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
7303 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
7305 label_end = mono_mb_emit_branch (mb, CEE_BR);
7306 mono_mb_patch_branch (mb, label_false);
7307 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
7308 mono_mb_patch_branch (mb, label_end);
7310 mono_mb_emit_byte (mb, CEE_STIND_I1);
7314 case MARSHAL_ACTION_PUSH:
7316 mono_mb_emit_ldloc_addr (mb, conv_arg);
7318 mono_mb_emit_ldloc (mb, conv_arg);
7320 mono_mb_emit_ldarg (mb, argnum);
7323 case MARSHAL_ACTION_CONV_RESULT:
7324 /* maybe we need to make sure that it fits within 8 bits */
7325 mono_mb_emit_stloc (mb, 3);
7328 case MARSHAL_ACTION_MANAGED_CONV_IN: {
7329 MonoClass* conv_arg_class = mono_defaults.int32_class;
7330 guint8 ldop = CEE_LDIND_I4;
7331 int label_null, label_false;
7333 conv_arg_class = marshal_boolean_managed_conv_in_get_conv_arg_class (spec, &ldop);
7334 conv_arg = mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
7337 *conv_arg_type = &conv_arg_class->this_arg;
7339 *conv_arg_type = &conv_arg_class->byval_arg;
7342 mono_mb_emit_ldarg (mb, argnum);
7346 label_null = mono_mb_emit_branch (mb, CEE_BRFALSE);
7347 mono_mb_emit_ldarg (mb, argnum);
7348 mono_mb_emit_byte (mb, ldop);
7352 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
7353 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
7354 mono_mb_emit_stloc (mb, conv_arg);
7355 mono_mb_patch_branch (mb, label_false);
7358 mono_mb_patch_branch (mb, label_null);
7362 case MARSHAL_ACTION_MANAGED_CONV_OUT: {
7363 guint8 stop = CEE_STIND_I4;
7364 guint8 ldc_op = CEE_LDC_I4_1;
7365 int label_null,label_false, label_end;;
7370 switch (spec->native) {
7371 case MONO_NATIVE_I1:
7372 case MONO_NATIVE_U1:
7373 stop = CEE_STIND_I1;
7375 case MONO_NATIVE_VARIANTBOOL:
7376 stop = CEE_STIND_I2;
7377 ldc_op = CEE_LDC_I4_M1;
7385 mono_mb_emit_ldarg (mb, argnum);
7386 label_null = mono_mb_emit_branch (mb, CEE_BRFALSE);
7388 mono_mb_emit_ldarg (mb, argnum);
7389 mono_mb_emit_ldloc (mb, conv_arg);
7391 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
7392 mono_mb_emit_byte (mb, ldc_op);
7393 label_end = mono_mb_emit_branch (mb, CEE_BR);
7395 mono_mb_patch_branch (mb, label_false);
7396 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
7397 mono_mb_patch_branch (mb, label_end);
7399 mono_mb_emit_byte (mb, stop);
7400 mono_mb_patch_branch (mb, label_null);
7405 g_assert_not_reached ();
7412 emit_marshal_ptr (EmitMarshalContext *m, int argnum, MonoType *t,
7413 MonoMarshalSpec *spec, int conv_arg,
7414 MonoType **conv_arg_type, MarshalAction action)
7416 #ifdef HAVE_ONLINE_VES
7417 MonoMethodBuilder *mb = m->mb;
7420 case MARSHAL_ACTION_CONV_IN:
7421 /* MS seems to allow this in some cases, ie. bxc #158 */
7423 if (MONO_TYPE_ISSTRUCT (t->data.type) && !mono_class_from_mono_type (t->data.type)->blittable) {
7424 char *msg = g_strdup_printf ("Can not marshal 'parameter #%d': Pointers can not reference marshaled structures. Use byref instead.", argnum + 1);
7425 mono_mb_emit_exception_marshal_directive (m->mb, msg);
7430 case MARSHAL_ACTION_PUSH:
7431 mono_mb_emit_ldarg (mb, argnum);
7434 case MARSHAL_ACTION_CONV_RESULT:
7435 /* no conversions necessary */
7436 mono_mb_emit_stloc (mb, 3);
7447 emit_marshal_char (EmitMarshalContext *m, int argnum, MonoType *t,
7448 MonoMarshalSpec *spec, int conv_arg,
7449 MonoType **conv_arg_type, MarshalAction action)
7451 #ifdef HAVE_ONLINE_VES
7452 MonoMethodBuilder *mb = m->mb;
7455 case MARSHAL_ACTION_PUSH:
7456 /* fixme: dont know how to marshal that. We cant simply
7457 * convert it to a one byte UTF8 character, because an
7458 * unicode character may need more that one byte in UTF8 */
7459 mono_mb_emit_ldarg (mb, argnum);
7462 case MARSHAL_ACTION_CONV_RESULT:
7463 /* fixme: we need conversions here */
7464 mono_mb_emit_stloc (mb, 3);
7475 emit_marshal_scalar (EmitMarshalContext *m, int argnum, MonoType *t,
7476 MonoMarshalSpec *spec, int conv_arg,
7477 MonoType **conv_arg_type, MarshalAction action)
7479 #ifdef HAVE_ONLINE_VES
7480 MonoMethodBuilder *mb = m->mb;
7483 case MARSHAL_ACTION_PUSH:
7484 mono_mb_emit_ldarg (mb, argnum);
7487 case MARSHAL_ACTION_CONV_RESULT:
7488 /* no conversions necessary */
7489 mono_mb_emit_stloc (mb, 3);
7500 emit_marshal (EmitMarshalContext *m, int argnum, MonoType *t,
7501 MonoMarshalSpec *spec, int conv_arg,
7502 MonoType **conv_arg_type, MarshalAction action)
7504 /* Ensure that we have marshalling info for this param */
7505 mono_marshal_load_type_info (mono_class_from_mono_type (t));
7507 if (spec && spec->native == MONO_NATIVE_CUSTOM)
7508 return emit_marshal_custom (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7510 if (spec && spec->native == MONO_NATIVE_ASANY)
7511 return emit_marshal_asany (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7514 case MONO_TYPE_VALUETYPE:
7515 if (t->data.klass == mono_defaults.handleref_class)
7516 return emit_marshal_handleref (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7518 return emit_marshal_vtype (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7519 case MONO_TYPE_STRING:
7520 return emit_marshal_string (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7521 case MONO_TYPE_CLASS:
7522 case MONO_TYPE_OBJECT:
7523 #if !defined(DISABLE_COM) && defined(HAVE_ONLINE_VES)
7524 if (spec && spec->native == MONO_NATIVE_STRUCT)
7525 return emit_marshal_variant (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7528 #if !defined(DISABLE_COM)
7529 if (spec && (spec->native == MONO_NATIVE_IUNKNOWN ||
7530 spec->native == MONO_NATIVE_IDISPATCH ||
7531 spec->native == MONO_NATIVE_INTERFACE))
7532 return mono_cominterop_emit_marshal_com_interface (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7533 if (spec && (spec->native == MONO_NATIVE_SAFEARRAY) &&
7534 (spec->data.safearray_data.elem_type == MONO_VARIANT_VARIANT) &&
7535 ((action == MARSHAL_ACTION_CONV_OUT) || (action == MARSHAL_ACTION_CONV_IN) || (action == MARSHAL_ACTION_PUSH)))
7536 return mono_cominterop_emit_marshal_safearray (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7539 if (mono_class_try_get_safehandle_class () != NULL && t->data.klass &&
7540 mono_class_is_subclass_of (t->data.klass, mono_class_try_get_safehandle_class (), FALSE))
7541 return emit_marshal_safehandle (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7543 return emit_marshal_object (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7544 case MONO_TYPE_ARRAY:
7545 case MONO_TYPE_SZARRAY:
7546 return emit_marshal_array (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7547 case MONO_TYPE_BOOLEAN:
7548 return emit_marshal_boolean (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7550 return emit_marshal_ptr (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7551 case MONO_TYPE_CHAR:
7552 return emit_marshal_char (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7565 case MONO_TYPE_FNPTR:
7566 return emit_marshal_scalar (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7567 case MONO_TYPE_GENERICINST:
7568 if (mono_type_generic_inst_is_valuetype (t))
7569 return emit_marshal_vtype (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7571 return emit_marshal_object (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7577 /* How the arguments of an icall should be wrapped */
7579 /* Don't wrap at all, pass the argument as is */
7580 ICALL_HANDLES_WRAP_NONE,
7581 /* Wrap the argument in an object handle, pass the handle to the icall */
7582 ICALL_HANDLES_WRAP_OBJ,
7583 /* Wrap the argument in an object handle, pass the handle to the icall,
7584 write the value out from the handle when the icall returns */
7585 ICALL_HANDLES_WRAP_OBJ_INOUT,
7586 /* Initialized an object handle to null, pass to the icalls,
7587 write the value out from the handle when the icall returns */
7588 ICALL_HANDLES_WRAP_OBJ_OUT,
7589 /* Wrap the argument (a valuetype reference) in a handle to pin its enclosing object,
7590 but pass the raw reference to the icall */
7591 ICALL_HANDLES_WRAP_VALUETYPE_REF,
7595 IcallHandlesWrap wrap;
7596 /* if wrap is NONE or OBJ or VALUETYPE_REF, this is not meaningful.
7597 if wrap is OBJ_INOUT it's the local var that holds the MonoObjectHandle.
7600 } IcallHandlesLocal;
7603 * Describes how to wrap the given parameter.
7606 static IcallHandlesWrap
7607 signature_param_uses_handles (MonoMethodSignature *sig, int param)
7609 if (MONO_TYPE_IS_REFERENCE (sig->params [param])) {
7610 if (mono_signature_param_is_out (sig, param))
7611 return ICALL_HANDLES_WRAP_OBJ_OUT;
7612 else if (mono_type_is_byref (sig->params [param]))
7613 return ICALL_HANDLES_WRAP_OBJ_INOUT;
7615 return ICALL_HANDLES_WRAP_OBJ;
7616 } else if (mono_type_is_byref (sig->params [param]))
7617 return ICALL_HANDLES_WRAP_VALUETYPE_REF;
7619 return ICALL_HANDLES_WRAP_NONE;
7623 #ifdef HAVE_ONLINE_VES
7625 * mono_marshal_emit_native_wrapper:
7626 * \param image the image to use for looking up custom marshallers
7627 * \param sig The signature of the native function
7628 * \param piinfo Marshalling information
7629 * \param mspecs Marshalling information
7630 * \param aot whenever the created method will be compiled by the AOT compiler
7631 * \param method if non-NULL, the pinvoke method to call
7632 * \param check_exceptions Whenever to check for pending exceptions after the native call
7633 * \param func_param the function to call is passed as a boxed IntPtr as the first parameter
7635 * generates IL code for the pinvoke wrapper, the generated code calls \p func .
7638 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)
7640 EmitMarshalContext m;
7641 MonoMethodSignature *csig;
7643 int i, argnum, *tmp_locals;
7644 int type, param_shift = 0;
7645 int coop_gc_stack_dummy, coop_gc_var;
7647 memset (&m, 0, sizeof (m));
7652 /* we copy the signature, so that we can set pinvoke to 0 */
7654 /* The function address is passed as the first argument */
7655 g_assert (!sig->hasthis);
7658 csig = mono_metadata_signature_dup_full (mb->method->klass->image, sig);
7666 /* we allocate local for use with emit_struct_conv() */
7667 /* allocate local 0 (pointer) src_ptr */
7668 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7669 /* allocate local 1 (pointer) dst_ptr */
7670 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7671 /* allocate local 2 (boolean) delete_old */
7672 mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
7674 /* delete_old = FALSE */
7675 mono_mb_emit_icon (mb, 0);
7676 mono_mb_emit_stloc (mb, 2);
7678 if (!MONO_TYPE_IS_VOID (sig->ret)) {
7679 /* allocate local 3 to store the return value */
7680 mono_mb_add_local (mb, sig->ret);
7683 if (mono_threads_is_coop_enabled ()) {
7684 /* local 4, dummy local used to get a stack address for suspend funcs */
7685 coop_gc_stack_dummy = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7686 /* local 5, the local to be used when calling the suspend funcs */
7687 coop_gc_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7691 * cookie = mono_threads_enter_gc_safe_region_unbalanced (ref dummy);
7693 * ret = method (...);
7695 * mono_threads_exit_gc_safe_region_unbalanced (cookie, ref dummy);
7702 if (MONO_TYPE_ISSTRUCT (sig->ret))
7703 m.vtaddr_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7705 if (mspecs [0] && mspecs [0]->native == MONO_NATIVE_CUSTOM) {
7706 /* Return type custom marshaling */
7708 * Since we can't determine the return type of the unmanaged function,
7709 * we assume it returns a pointer, and pass that pointer to
7710 * MarshalNativeToManaged.
7712 csig->ret = &mono_defaults.int_class->byval_arg;
7715 /* we first do all conversions */
7716 tmp_locals = (int *)alloca (sizeof (int) * sig->param_count);
7717 m.orig_conv_args = (int *)alloca (sizeof (int) * (sig->param_count + 1));
7719 for (i = 0; i < sig->param_count; i ++) {
7720 tmp_locals [i] = emit_marshal (&m, i + param_shift, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_CONV_IN);
7723 // In coop mode need to register blocking state during native call
7724 if (mono_threads_is_coop_enabled ()) {
7725 // Perform an extra, early lookup of the function address, so any exceptions
7726 // potentially resulting from the lookup occur before entering blocking mode.
7727 if (!func_param && !MONO_CLASS_IS_IMPORT (mb->method->klass) && aot) {
7728 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7729 mono_mb_emit_op (mb, CEE_MONO_ICALL_ADDR, &piinfo->method);
7730 mono_mb_emit_byte (mb, CEE_POP); // Result not needed yet
7733 mono_mb_emit_ldloc_addr (mb, coop_gc_stack_dummy);
7734 mono_mb_emit_icall (mb, mono_threads_enter_gc_safe_region_unbalanced);
7735 mono_mb_emit_stloc (mb, coop_gc_var);
7738 /* push all arguments */
7741 mono_mb_emit_byte (mb, CEE_LDARG_0);
7743 for (i = 0; i < sig->param_count; i++) {
7744 emit_marshal (&m, i + param_shift, sig->params [i], mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_PUSH);
7747 /* call the native method */
7749 mono_mb_emit_byte (mb, CEE_LDARG_0);
7750 mono_mb_emit_op (mb, CEE_UNBOX, mono_defaults.int_class);
7751 mono_mb_emit_byte (mb, CEE_LDIND_I);
7752 mono_mb_emit_calli (mb, csig);
7753 } else if (MONO_CLASS_IS_IMPORT (mb->method->klass)) {
7755 mono_mb_emit_cominterop_call (mb, csig, &piinfo->method);
7757 g_assert_not_reached ();
7761 /* Reuse the ICALL_ADDR opcode for pinvokes too */
7762 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7763 mono_mb_emit_op (mb, CEE_MONO_ICALL_ADDR, &piinfo->method);
7764 mono_mb_emit_calli (mb, csig);
7766 mono_mb_emit_native_call (mb, csig, func);
7770 /* Set LastError if needed */
7771 if (piinfo->piflags & PINVOKE_ATTRIBUTE_SUPPORTS_LAST_ERROR) {
7774 static MonoMethodSignature *get_last_error_sig = NULL;
7775 if (!get_last_error_sig) {
7776 get_last_error_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
7777 get_last_error_sig->ret = &mono_defaults.int_class->byval_arg;
7778 get_last_error_sig->pinvoke = 1;
7782 * Have to call GetLastError () early and without a wrapper, since various runtime components could
7783 * clobber its value.
7785 mono_mb_emit_native_call (mb, get_last_error_sig, GetLastError);
7786 mono_mb_emit_icall (mb, mono_marshal_set_last_error_windows);
7788 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7789 mono_mb_emit_byte (mb, CEE_MONO_GET_LAST_ERROR);
7790 mono_mb_emit_icall (mb, mono_marshal_set_last_error_windows);
7793 mono_mb_emit_icall (mb, mono_marshal_set_last_error);
7797 if (MONO_TYPE_ISSTRUCT (sig->ret)) {
7798 MonoClass *klass = mono_class_from_mono_type (sig->ret);
7799 mono_class_init (klass);
7800 if (!(mono_class_is_explicit_layout (klass) || klass->blittable)) {
7801 /* This is used by emit_marshal_vtype (), but it needs to go right before the call */
7802 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7803 mono_mb_emit_byte (mb, CEE_MONO_VTADDR);
7804 mono_mb_emit_stloc (mb, m.vtaddr_var);
7808 /* Unblock before converting the result, since that can involve calls into the runtime */
7809 if (mono_threads_is_coop_enabled ()) {
7810 mono_mb_emit_ldloc (mb, coop_gc_var);
7811 mono_mb_emit_ldloc_addr (mb, coop_gc_stack_dummy);
7812 mono_mb_emit_icall (mb, mono_threads_exit_gc_safe_region_unbalanced);
7815 /* convert the result */
7816 if (!sig->ret->byref) {
7817 MonoMarshalSpec *spec = mspecs [0];
7818 type = sig->ret->type;
7820 if (spec && spec->native == MONO_NATIVE_CUSTOM) {
7821 emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7825 case MONO_TYPE_VOID:
7827 case MONO_TYPE_VALUETYPE:
7828 klass = sig->ret->data.klass;
7829 if (klass->enumtype) {
7830 type = mono_class_enum_basetype (sig->ret->data.klass)->type;
7833 emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7847 case MONO_TYPE_FNPTR:
7848 case MONO_TYPE_STRING:
7849 case MONO_TYPE_CLASS:
7850 case MONO_TYPE_OBJECT:
7851 case MONO_TYPE_BOOLEAN:
7852 case MONO_TYPE_ARRAY:
7853 case MONO_TYPE_SZARRAY:
7854 case MONO_TYPE_CHAR:
7856 case MONO_TYPE_GENERICINST:
7857 emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7859 case MONO_TYPE_TYPEDBYREF:
7861 g_warning ("return type 0x%02x unknown", sig->ret->type);
7862 g_assert_not_reached ();
7866 mono_mb_emit_stloc (mb, 3);
7870 * Need to call this after converting the result since MONO_VTADDR needs
7871 * to be adjacent to the call instruction.
7873 if (check_exceptions)
7874 emit_thread_interrupt_checkpoint (mb);
7876 /* we need to convert byref arguments back and free string arrays */
7877 for (i = 0; i < sig->param_count; i++) {
7878 MonoType *t = sig->params [i];
7879 MonoMarshalSpec *spec = mspecs [i + 1];
7881 argnum = i + param_shift;
7883 if (spec && ((spec->native == MONO_NATIVE_CUSTOM) || (spec->native == MONO_NATIVE_ASANY))) {
7884 emit_marshal (&m, argnum, t, spec, tmp_locals [i], NULL, MARSHAL_ACTION_CONV_OUT);
7889 case MONO_TYPE_STRING:
7890 case MONO_TYPE_VALUETYPE:
7891 case MONO_TYPE_CLASS:
7892 case MONO_TYPE_OBJECT:
7893 case MONO_TYPE_SZARRAY:
7894 case MONO_TYPE_BOOLEAN:
7895 emit_marshal (&m, argnum, t, spec, tmp_locals [i], NULL, MARSHAL_ACTION_CONV_OUT);
7902 if (!MONO_TYPE_IS_VOID(sig->ret))
7903 mono_mb_emit_ldloc (mb, 3);
7905 mono_mb_emit_byte (mb, CEE_RET);
7907 #endif /* HAVE_ONLINE_VES */
7910 * mono_marshal_get_native_wrapper:
7911 * \param method The \c MonoMethod to wrap.
7912 * \param check_exceptions Whenever to check for pending exceptions
7914 * Generates IL code for the pinvoke wrapper. The generated method
7915 * calls the unmanaged code in \c piinfo->addr.
7918 mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions, gboolean aot)
7920 MonoMethodSignature *sig, *csig;
7921 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
7922 MonoMethodBuilder *mb;
7923 MonoMarshalSpec **mspecs;
7926 gboolean pinvoke = FALSE;
7929 const char *exc_class = "MissingMethodException";
7930 const char *exc_arg = NULL;
7933 g_assert (method != NULL);
7934 g_assert (mono_method_signature (method)->pinvoke);
7936 GHashTable **cache_ptr;
7939 if (check_exceptions)
7940 cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_aot_check_cache;
7942 cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_aot_cache;
7944 if (check_exceptions)
7945 cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_check_cache;
7947 cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_cache;
7950 cache = get_cache (cache_ptr, mono_aligned_addr_hash, NULL);
7952 if ((res = mono_marshal_find_in_cache (cache, method)))
7955 if (MONO_CLASS_IS_IMPORT (method->klass)) {
7956 /* The COM code is not AOT compatible, it calls mono_custom_attrs_get_attr_checked () */
7960 return mono_cominterop_get_native_wrapper (method);
7962 g_assert_not_reached ();
7966 sig = mono_method_signature (method);
7968 if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
7969 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7972 if (!piinfo->addr) {
7974 if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)
7975 exc_arg = "Method contains unsupported native code";
7977 mono_lookup_pinvoke_call (method, &exc_class, &exc_arg);
7979 piinfo->addr = mono_lookup_internal_call (method);
7983 /* hack - redirect certain string constructors to CreateString */
7984 if (piinfo->addr == ves_icall_System_String_ctor_RedirectToCreateString) {
7985 g_assert (!pinvoke);
7986 g_assert (method->string_ctor);
7987 g_assert (sig->hasthis);
7989 /* CreateString returns a value */
7990 csig = mono_metadata_signature_dup_full (method->klass->image, sig);
7991 csig->ret = &mono_defaults.string_class->byval_arg;
7995 while ((res = mono_class_get_methods (mono_defaults.string_class, &iter))) {
7996 if (!strcmp ("CreateString", res->name) &&
7997 mono_metadata_signature_equal (csig, mono_method_signature (res))) {
8000 g_assert (!(res->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL));
8001 g_assert (!(res->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL));
8003 /* create a wrapper to preserve .ctor in stack trace */
8004 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_MANAGED);
8006 #ifdef HAVE_ONLINE_VES
8007 mono_mb_emit_byte (mb, CEE_LDARG_0);
8008 for (i = 1; i <= csig->param_count; i++)
8009 mono_mb_emit_ldarg (mb, i);
8010 mono_mb_emit_managed_call (mb, res, NULL);
8011 mono_mb_emit_byte (mb, CEE_RET);
8014 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_STRING_CTOR);
8015 info->d.string_ctor.method = method;
8017 /* use native_wrapper_cache because internal calls are looked up there */
8018 res = mono_mb_create_and_cache_full (cache, method, mb, csig,
8019 csig->param_count + 1, info, NULL);
8026 /* exception will be thrown */
8027 piinfo->addr = NULL;
8028 g_warning ("cannot find CreateString for .ctor");
8031 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_NATIVE);
8033 mb->method->save_lmf = 1;
8036 * In AOT mode and embedding scenarios, it is possible that the icall is not
8037 * registered in the runtime doing the AOT compilation.
8039 if (!piinfo->addr && !aot) {
8040 #ifdef HAVE_ONLINE_VES
8041 mono_mb_emit_exception (mb, exc_class, exc_arg);
8043 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
8044 info->d.managed_to_native.method = method;
8046 csig = mono_metadata_signature_dup_full (method->klass->image, sig);
8048 res = mono_mb_create_and_cache_full (cache, method, mb, csig,
8049 csig->param_count + 16, info, NULL);
8055 /* internal calls: we simply push all arguments and call the method (no conversions) */
8056 if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
8058 csig = mono_metadata_signature_dup_add_this (method->klass->image, sig, method->klass);
8060 csig = mono_metadata_signature_dup_full (method->klass->image, sig);
8062 //printf ("%s\n", mono_method_full_name (method, 1));
8064 /* hack - string constructors returns a value */
8065 if (method->string_ctor)
8066 csig->ret = &mono_defaults.string_class->byval_arg;
8068 #ifdef HAVE_ONLINE_VES
8070 MonoClass *handle_stack_mark_class;
8071 MonoClass *error_class;
8072 int thread_info_var = -1, stack_mark_var = -1, error_var = -1;
8073 MonoMethodSignature *call_sig = csig;
8074 gboolean uses_handles = FALSE;
8075 gboolean save_handles_to_locals = FALSE;
8076 IcallHandlesLocal *handles_locals = NULL;
8078 (void) mono_lookup_internal_call_full (method, &uses_handles);
8080 /* If it uses handles and MonoError, it had better check exceptions */
8081 g_assert (!uses_handles || check_exceptions);
8084 MonoMethodSignature *ret;
8086 /* Add a MonoError argument and figure out which args need to be wrapped in handles */
8087 // FIXME: The stuff from mono_metadata_signature_dup_internal_with_padding ()
8088 ret = mono_metadata_signature_alloc (method->klass->image, csig->param_count + 1);
8090 ret->param_count = csig->param_count + 1;
8091 ret->ret = csig->ret;
8093 handles_locals = g_new0 (IcallHandlesLocal, csig->param_count);
8094 for (int i = 0; i < csig->param_count; ++i) {
8095 IcallHandlesWrap w = signature_param_uses_handles (csig, i);
8096 handles_locals [i].wrap = w;
8098 case ICALL_HANDLES_WRAP_OBJ:
8099 case ICALL_HANDLES_WRAP_OBJ_INOUT:
8100 case ICALL_HANDLES_WRAP_OBJ_OUT:
8101 ret->params [i] = mono_class_get_byref_type (mono_class_from_mono_type(csig->params[i]));
8102 if (w == ICALL_HANDLES_WRAP_OBJ_OUT || w == ICALL_HANDLES_WRAP_OBJ_INOUT)
8103 save_handles_to_locals = TRUE;
8105 case ICALL_HANDLES_WRAP_NONE:
8106 case ICALL_HANDLES_WRAP_VALUETYPE_REF:
8107 ret->params [i] = csig->params [i];
8110 g_assert_not_reached ();
8113 /* Add MonoError* param */
8114 ret->params [csig->param_count] = &mono_get_intptr_class ()->byval_arg;
8115 ret->pinvoke = csig->pinvoke;
8121 handle_stack_mark_class = mono_class_load_from_name (mono_get_corlib (), "Mono", "RuntimeStructs/HandleStackMark");
8122 error_class = mono_class_load_from_name (mono_get_corlib (), "Mono", "RuntimeStructs/MonoError");
8124 thread_info_var = mono_mb_add_local (mb, &mono_get_intptr_class ()->byval_arg);
8125 stack_mark_var = mono_mb_add_local (mb, &handle_stack_mark_class->byval_arg);
8126 error_var = mono_mb_add_local (mb, &error_class->byval_arg);
8128 if (save_handles_to_locals) {
8129 /* add a local var to hold the handles for each out arg */
8130 for (int i = 0; i < sig->param_count; ++i) {
8131 int j = i + sig->hasthis;
8132 switch (handles_locals[j].wrap) {
8133 case ICALL_HANDLES_WRAP_NONE:
8134 case ICALL_HANDLES_WRAP_OBJ:
8135 case ICALL_HANDLES_WRAP_VALUETYPE_REF:
8136 handles_locals [j].handle = -1;
8138 case ICALL_HANDLES_WRAP_OBJ_INOUT:
8139 case ICALL_HANDLES_WRAP_OBJ_OUT:
8140 handles_locals [j].handle = mono_mb_add_local (mb, sig->params [i]);
8143 g_assert_not_reached ();
8153 * Add a null check since public icalls can be called with 'call' which
8154 * does no such check.
8156 mono_mb_emit_byte (mb, CEE_LDARG_0);
8157 pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
8158 mono_mb_emit_exception (mb, "NullReferenceException", NULL);
8159 mono_mb_patch_branch (mb, pos);
8163 mono_mb_emit_ldloc_addr (mb, stack_mark_var);
8164 mono_mb_emit_ldloc_addr (mb, error_var);
8165 mono_mb_emit_icall (mb, mono_icall_start);
8166 mono_mb_emit_stloc (mb, thread_info_var);
8169 mono_mb_emit_byte (mb, CEE_LDARG_0);
8170 /* TODO support adding wrappers to non-static struct methods */
8171 g_assert (!mono_class_is_valuetype(mono_method_get_class (method)));
8172 mono_mb_emit_icall (mb, mono_icall_handle_new);
8174 for (i = 0; i < sig->param_count; i++) {
8175 /* load each argument. references into the managed heap get wrapped in handles */
8176 int j = i + sig->hasthis;
8177 switch (handles_locals[j].wrap) {
8178 case ICALL_HANDLES_WRAP_NONE:
8179 mono_mb_emit_ldarg (mb, j);
8181 case ICALL_HANDLES_WRAP_OBJ:
8182 /* argI = mono_handle_new (argI_raw) */
8183 mono_mb_emit_ldarg (mb, j);
8184 mono_mb_emit_icall (mb, mono_icall_handle_new);
8186 case ICALL_HANDLES_WRAP_OBJ_INOUT:
8187 case ICALL_HANDLES_WRAP_OBJ_OUT:
8189 * handleI = argI = mono_handle_new (*argI_raw)
8191 * handleI = argI = mono_handle_new (NULL)
8193 if (handles_locals[j].wrap == ICALL_HANDLES_WRAP_OBJ_INOUT) {
8194 mono_mb_emit_ldarg (mb, j);
8195 mono_mb_emit_byte (mb, CEE_LDIND_REF);
8197 mono_mb_emit_byte (mb, CEE_LDNULL);
8198 mono_mb_emit_icall (mb, mono_icall_handle_new);
8200 mono_mb_emit_byte (mb, CEE_DUP);
8202 mono_mb_emit_stloc (mb, handles_locals[j].handle);
8204 case ICALL_HANDLES_WRAP_VALUETYPE_REF:
8205 /* (void) mono_handle_new (argI); argI */
8206 mono_mb_emit_ldarg (mb, j);
8207 mono_mb_emit_byte (mb, CEE_DUP);
8208 mono_mb_emit_icall (mb, mono_icall_handle_new_interior);
8209 mono_mb_emit_byte (mb, CEE_POP);
8211 fprintf (stderr, " Method %s.%s.%s has byref valuetype argument %d\n", method->klass->name_space, method->klass->name, method->name, i);
8215 g_assert_not_reached ();
8218 mono_mb_emit_ldloc_addr (mb, error_var);
8221 mono_mb_emit_byte (mb, CEE_LDARG_0);
8222 for (i = 0; i < sig->param_count; i++)
8223 mono_mb_emit_ldarg (mb, i + sig->hasthis);
8227 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8228 mono_mb_emit_op (mb, CEE_MONO_ICALL_ADDR, &piinfo->method);
8229 mono_mb_emit_calli (mb, call_sig);
8231 g_assert (piinfo->addr);
8232 mono_mb_emit_native_call (mb, call_sig, piinfo->addr);
8236 if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
8237 // if (ret != NULL_HANDLE) {
8238 // ret = MONO_HANDLE_RAW(ret)
8240 mono_mb_emit_byte (mb, CEE_DUP);
8241 int pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
8242 mono_mb_emit_ldflda (mb, MONO_HANDLE_PAYLOAD_OFFSET (MonoObject));
8243 mono_mb_emit_byte (mb, CEE_LDIND_REF);
8244 mono_mb_patch_branch (mb, pos);
8246 if (save_handles_to_locals) {
8247 for (i = 0; i < sig->param_count; i++) {
8248 int j = i + sig->hasthis;
8249 switch (handles_locals [j].wrap) {
8250 case ICALL_HANDLES_WRAP_NONE:
8251 case ICALL_HANDLES_WRAP_OBJ:
8252 case ICALL_HANDLES_WRAP_VALUETYPE_REF:
8254 case ICALL_HANDLES_WRAP_OBJ_INOUT:
8255 case ICALL_HANDLES_WRAP_OBJ_OUT:
8256 /* *argI_raw = MONO_HANDLE_RAW (handleI) */
8259 mono_mb_emit_ldarg (mb, j);
8261 mono_mb_emit_ldloc (mb, handles_locals [j].handle);
8262 /* MONO_HANDLE_RAW(handleI) */
8263 mono_mb_emit_ldflda (mb, MONO_HANDLE_PAYLOAD_OFFSET (MonoObject));
8264 mono_mb_emit_byte (mb, CEE_LDIND_REF);
8265 /* *argI_raw = MONO_HANDLE_RAW(handleI) */
8266 mono_mb_emit_byte (mb, CEE_STIND_REF);
8269 g_assert_not_reached ();
8273 g_free (handles_locals);
8275 mono_mb_emit_ldloc (mb, thread_info_var);
8276 mono_mb_emit_ldloc_addr (mb, stack_mark_var);
8277 mono_mb_emit_ldloc_addr (mb, error_var);
8278 mono_mb_emit_icall (mb, mono_icall_end);
8281 if (check_exceptions)
8282 emit_thread_interrupt_checkpoint (mb);
8283 mono_mb_emit_byte (mb, CEE_RET);
8285 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
8286 info->d.managed_to_native.method = method;
8288 csig = mono_metadata_signature_dup_full (method->klass->image, csig);
8290 res = mono_mb_create_and_cache_full (cache, method, mb, csig, csig->param_count + 16,
8299 g_assert (piinfo->addr);
8301 #ifdef HAVE_ONLINE_VES
8302 mspecs = g_new (MonoMarshalSpec*, sig->param_count + 1);
8303 mono_method_get_marshal_info (method, mspecs);
8305 mono_marshal_emit_native_wrapper (mb->method->klass->image, mb, sig, piinfo, mspecs, piinfo->addr, aot, check_exceptions, FALSE);
8307 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_PINVOKE);
8308 info->d.managed_to_native.method = method;
8310 csig = mono_metadata_signature_dup_full (method->klass->image, sig);
8312 res = mono_mb_create_and_cache_full (cache, method, mb, csig, csig->param_count + 16,
8316 #ifdef HAVE_ONLINE_VES
8317 for (i = sig->param_count; i >= 0; i--)
8319 mono_metadata_free_marshal_spec (mspecs [i]);
8323 /* mono_method_print_code (res); */
8329 * mono_marshal_get_native_func_wrapper:
8330 * \param image The image to use for memory allocation and for looking up custom marshallers.
8331 * \param sig The signature of the function
8332 * \param func The native function to wrap
8334 * \returns a wrapper method around native functions, similar to the pinvoke
8338 mono_marshal_get_native_func_wrapper (MonoImage *image, MonoMethodSignature *sig,
8339 MonoMethodPInvoke *piinfo, MonoMarshalSpec **mspecs, gpointer func)
8341 MonoMethodSignature *csig;
8343 SignaturePointerPair key, *new_key;
8344 MonoMethodBuilder *mb;
8353 // Generic types are not safe to place in MonoImage caches.
8354 g_assert (!sig->is_inflated);
8356 cache = get_cache (&image->native_func_wrapper_cache, signature_pointer_pair_hash, signature_pointer_pair_equal);
8357 if ((res = mono_marshal_find_in_cache (cache, &key)))
8360 name = g_strdup_printf ("wrapper_native_%p", func);
8361 mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
8362 mb->method->save_lmf = 1;
8364 #ifdef HAVE_ONLINE_VES
8365 mono_marshal_emit_native_wrapper (image, mb, sig, piinfo, mspecs, func, FALSE, TRUE, FALSE);
8368 csig = mono_metadata_signature_dup_full (image, sig);
8371 new_key = g_new (SignaturePointerPair,1);
8372 new_key->sig = csig;
8373 new_key->pointer = func;
8375 res = mono_mb_create_and_cache_full (cache, new_key, mb, csig, csig->param_count + 16, NULL, &found);
8381 mono_marshal_set_wrapper_info (res, NULL);
8387 * The wrapper receives the native function as a boxed IntPtr as its 'this' argument. This is easier to support in
8391 mono_marshal_get_native_func_wrapper_aot (MonoClass *klass)
8393 MonoMethodSignature *sig, *csig;
8394 MonoMethodBuilder *mb;
8399 MonoMethodPInvoke mpiinfo;
8400 MonoMethodPInvoke *piinfo = &mpiinfo;
8401 MonoMarshalSpec **mspecs;
8402 MonoMethod *invoke = mono_get_delegate_invoke (klass);
8403 MonoImage *image = invoke->klass->image;
8406 // FIXME: include UnmanagedFunctionPointerAttribute info
8409 * The wrapper is associated with the delegate type, to pick up the marshalling info etc.
8411 cache = get_cache (&mono_method_get_wrapper_cache (invoke)->native_func_wrapper_aot_cache, mono_aligned_addr_hash, NULL);
8413 if ((res = mono_marshal_find_in_cache (cache, invoke)))
8416 memset (&mpiinfo, 0, sizeof (mpiinfo));
8417 parse_unmanaged_function_pointer_attr (klass, &mpiinfo);
8419 mspecs = g_new0 (MonoMarshalSpec*, mono_method_signature (invoke)->param_count + 1);
8420 mono_method_get_marshal_info (invoke, mspecs);
8421 /* Freed below so don't alloc from mempool */
8422 sig = mono_metadata_signature_dup (mono_method_signature (invoke));
8425 name = g_strdup_printf ("wrapper_aot_native");
8426 mb = mono_mb_new (invoke->klass, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
8427 mb->method->save_lmf = 1;
8429 #ifdef HAVE_ONLINE_VES
8430 mono_marshal_emit_native_wrapper (image, mb, sig, piinfo, mspecs, NULL, FALSE, TRUE, TRUE);
8433 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NATIVE_FUNC_AOT);
8434 info->d.managed_to_native.method = invoke;
8436 g_assert (!sig->hasthis);
8437 csig = mono_metadata_signature_dup_add_this (image, sig, mono_defaults.object_class);
8439 res = mono_mb_create_and_cache_full (cache, invoke,
8440 mb, csig, csig->param_count + 16,
8444 for (i = mono_method_signature (invoke)->param_count; i >= 0; i--)
8446 mono_metadata_free_marshal_spec (mspecs [i]);
8454 * mono_marshal_emit_managed_wrapper:
8456 * Emit the body of a native-to-managed wrapper. INVOKE_SIG is the signature of
8457 * the delegate which wraps the managed method to be called. For closed delegates,
8458 * it could have fewer parameters than the method it wraps.
8459 * THIS_LOC is the memory location where the target of the delegate is stored.
8462 mono_marshal_emit_managed_wrapper (MonoMethodBuilder *mb, MonoMethodSignature *invoke_sig, MonoMarshalSpec **mspecs, EmitMarshalContext* m, MonoMethod *method, uint32_t target_handle)
8464 #ifndef HAVE_ONLINE_VES
8465 MonoMethodSignature *sig, *csig;
8471 /* we first do all conversions */
8472 for (i = 0; i < sig->param_count; i ++) {
8473 MonoType *t = sig->params [i];
8476 case MONO_TYPE_OBJECT:
8477 case MONO_TYPE_CLASS:
8478 case MONO_TYPE_VALUETYPE:
8479 case MONO_TYPE_ARRAY:
8480 case MONO_TYPE_SZARRAY:
8481 case MONO_TYPE_STRING:
8482 case MONO_TYPE_BOOLEAN:
8483 emit_marshal (m, i, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_MANAGED_CONV_IN);
8487 if (!sig->ret->byref) {
8488 switch (sig->ret->type) {
8489 case MONO_TYPE_STRING:
8490 csig->ret = &mono_defaults.int_class->byval_arg;
8497 MonoMethodSignature *sig, *csig;
8498 MonoExceptionClause *clauses, *clause_finally, *clause_catch;
8499 int i, *tmp_locals, ex_local, e_local, attach_cookie_local, attach_dummy_local;
8500 int leave_try_pos, leave_catch_pos, ex_m1_pos;
8501 gboolean closed = FALSE;
8506 /* allocate local 0 (pointer) src_ptr */
8507 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8508 /* allocate local 1 (pointer) dst_ptr */
8509 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8510 /* allocate local 2 (boolean) delete_old */
8511 mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
8513 if (!sig->hasthis && sig->param_count != invoke_sig->param_count) {
8514 /* Closed delegate */
8515 g_assert (sig->param_count == invoke_sig->param_count + 1);
8517 /* Use a new signature without the first argument */
8518 sig = mono_metadata_signature_dup (sig);
8519 memmove (&sig->params [0], &sig->params [1], (sig->param_count - 1) * sizeof (MonoType*));
8520 sig->param_count --;
8523 if (!MONO_TYPE_IS_VOID(sig->ret)) {
8524 /* allocate local 3 to store the return value */
8525 mono_mb_add_local (mb, sig->ret);
8528 if (MONO_TYPE_ISSTRUCT (sig->ret))
8529 m->vtaddr_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8531 ex_local = mono_mb_add_local (mb, &mono_defaults.uint32_class->byval_arg);
8532 e_local = mono_mb_add_local (mb, &mono_defaults.exception_class->byval_arg);
8534 attach_cookie_local = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8535 attach_dummy_local = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8540 * // does (STARTING|RUNNING|BLOCKING) -> RUNNING + set/switch domain
8541 * mono_threads_attach_coop ();
8545 * ret = method (...);
8546 * } catch (Exception e) {
8547 * ex = mono_gchandle_new (e, false);
8549 * // does RUNNING -> (RUNNING|BLOCKING) + unset/switch domain
8550 * mono_threads_detach_coop ();
8553 * mono_marshal_ftnptr_eh_callback (ex);
8559 clauses = g_new0 (MonoExceptionClause, 2);
8561 clause_catch = &clauses [0];
8562 clause_catch->flags = MONO_EXCEPTION_CLAUSE_NONE;
8563 clause_catch->data.catch_class = mono_defaults.exception_class;
8565 clause_finally = &clauses [1];
8566 clause_finally->flags = MONO_EXCEPTION_CLAUSE_FINALLY;
8568 mono_mb_emit_icon (mb, 0);
8569 mono_mb_emit_stloc (mb, 2);
8571 mono_mb_emit_icon (mb, -1);
8572 mono_mb_emit_byte (mb, CEE_CONV_U4);
8573 mono_mb_emit_stloc (mb, ex_local);
8576 clause_catch->try_offset = clause_finally->try_offset = mono_mb_get_label (mb);
8578 if (!mono_threads_is_coop_enabled ()) {
8579 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8580 mono_mb_emit_byte (mb, CEE_MONO_JIT_ATTACH);
8582 /* mono_threads_attach_coop (); */
8583 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8584 mono_mb_emit_byte (mb, CEE_MONO_LDDOMAIN);
8585 mono_mb_emit_ldloc_addr (mb, attach_dummy_local);
8586 mono_mb_emit_icall (mb, mono_threads_attach_coop);
8587 mono_mb_emit_stloc (mb, attach_cookie_local);
8590 /* <interrupt check> */
8591 emit_thread_interrupt_checkpoint (mb);
8593 /* we first do all conversions */
8594 tmp_locals = (int *)alloca (sizeof (int) * sig->param_count);
8595 for (i = 0; i < sig->param_count; i ++) {
8596 MonoType *t = sig->params [i];
8599 case MONO_TYPE_OBJECT:
8600 case MONO_TYPE_CLASS:
8601 case MONO_TYPE_VALUETYPE:
8602 case MONO_TYPE_ARRAY:
8603 case MONO_TYPE_SZARRAY:
8604 case MONO_TYPE_STRING:
8605 case MONO_TYPE_BOOLEAN:
8606 tmp_locals [i] = emit_marshal (m, i, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_MANAGED_CONV_IN);
8616 if (target_handle) {
8617 mono_mb_emit_icon (mb, (gint32)target_handle);
8618 mono_mb_emit_icall (mb, mono_gchandle_get_target);
8621 g_assert_not_reached ();
8623 } else if (closed) {
8624 mono_mb_emit_icon (mb, (gint32)target_handle);
8625 mono_mb_emit_icall (mb, mono_gchandle_get_target);
8628 for (i = 0; i < sig->param_count; i++) {
8629 MonoType *t = sig->params [i];
8631 if (tmp_locals [i]) {
8633 mono_mb_emit_ldloc_addr (mb, tmp_locals [i]);
8635 mono_mb_emit_ldloc (mb, tmp_locals [i]);
8638 mono_mb_emit_ldarg (mb, i);
8641 /* ret = method (...) */
8642 mono_mb_emit_managed_call (mb, method, NULL);
8644 if (MONO_TYPE_ISSTRUCT (sig->ret)) {
8645 MonoClass *klass = mono_class_from_mono_type (sig->ret);
8646 mono_class_init (klass);
8647 if (!(mono_class_is_explicit_layout (klass) || klass->blittable)) {
8648 /* This is used by emit_marshal_vtype (), but it needs to go right before the call */
8649 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8650 mono_mb_emit_byte (mb, CEE_MONO_VTADDR);
8651 mono_mb_emit_stloc (mb, m->vtaddr_var);
8655 if (mspecs [0] && mspecs [0]->native == MONO_NATIVE_CUSTOM) {
8656 emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
8657 } else if (!sig->ret->byref) {
8658 switch (sig->ret->type) {
8659 case MONO_TYPE_VOID:
8661 case MONO_TYPE_BOOLEAN:
8664 case MONO_TYPE_CHAR:
8676 case MONO_TYPE_OBJECT:
8677 mono_mb_emit_stloc (mb, 3);
8679 case MONO_TYPE_STRING:
8680 csig->ret = &mono_defaults.int_class->byval_arg;
8681 emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
8683 case MONO_TYPE_VALUETYPE:
8684 case MONO_TYPE_CLASS:
8685 case MONO_TYPE_SZARRAY:
8686 emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
8689 g_warning ("return type 0x%02x unknown", sig->ret->type);
8690 g_assert_not_reached ();
8693 mono_mb_emit_stloc (mb, 3);
8696 /* Convert byref arguments back */
8697 for (i = 0; i < sig->param_count; i ++) {
8698 MonoType *t = sig->params [i];
8699 MonoMarshalSpec *spec = mspecs [i + 1];
8701 if (spec && spec->native == MONO_NATIVE_CUSTOM) {
8702 emit_marshal (m, i, t, mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
8704 else if (t->byref) {
8706 case MONO_TYPE_CLASS:
8707 case MONO_TYPE_VALUETYPE:
8708 case MONO_TYPE_OBJECT:
8709 case MONO_TYPE_STRING:
8710 case MONO_TYPE_BOOLEAN:
8711 emit_marshal (m, i, t, mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
8717 else if (invoke_sig->params [i]->attrs & PARAM_ATTRIBUTE_OUT) {
8718 /* The [Out] information is encoded in the delegate signature */
8720 case MONO_TYPE_SZARRAY:
8721 case MONO_TYPE_CLASS:
8722 case MONO_TYPE_VALUETYPE:
8723 emit_marshal (m, i, invoke_sig->params [i], mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
8726 g_assert_not_reached ();
8731 leave_try_pos = mono_mb_emit_branch (mb, CEE_LEAVE);
8735 /* catch (Exception e) { */
8736 clause_catch->try_len = mono_mb_get_label (mb) - clause_catch->try_offset;
8737 clause_catch->handler_offset = mono_mb_get_label (mb);
8739 mono_mb_emit_stloc (mb, e_local);
8741 /* ex = mono_gchandle_new (e, false); */
8742 mono_mb_emit_ldloc (mb, e_local);
8743 mono_mb_emit_icon (mb, 0);
8744 mono_mb_emit_icall (mb, mono_gchandle_new);
8745 mono_mb_emit_stloc (mb, ex_local);
8747 leave_catch_pos = mono_mb_emit_branch (mb, CEE_LEAVE);
8750 clause_catch->handler_len = mono_mb_get_pos (mb) - clause_catch->handler_offset;
8753 clause_finally->try_len = mono_mb_get_label (mb) - clause_finally->try_offset;
8754 clause_finally->handler_offset = mono_mb_get_label (mb);
8756 if (!mono_threads_is_coop_enabled ()) {
8757 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8758 mono_mb_emit_byte (mb, CEE_MONO_JIT_DETACH);
8760 /* mono_threads_detach_coop (); */
8761 mono_mb_emit_ldloc (mb, attach_cookie_local);
8762 mono_mb_emit_ldloc_addr (mb, attach_dummy_local);
8763 mono_mb_emit_icall (mb, mono_threads_detach_coop);
8767 mono_mb_emit_ldloc (mb, ex_local);
8768 mono_mb_emit_icon (mb, -1);
8769 mono_mb_emit_byte (mb, CEE_CONV_U4);
8770 ex_m1_pos = mono_mb_emit_branch (mb, CEE_BEQ);
8772 /* mono_marshal_ftnptr_eh_callback (ex) */
8773 mono_mb_emit_ldloc (mb, ex_local);
8774 mono_mb_emit_icall (mb, mono_marshal_ftnptr_eh_callback);
8777 mono_mb_patch_branch (mb, ex_m1_pos);
8779 mono_mb_emit_byte (mb, CEE_ENDFINALLY);
8781 /* } [endfinally] */
8782 clause_finally->handler_len = mono_mb_get_pos (mb) - clause_finally->handler_offset;
8784 mono_mb_patch_branch (mb, leave_try_pos);
8785 mono_mb_patch_branch (mb, leave_catch_pos);
8788 if (m->retobj_var) {
8789 mono_mb_emit_ldloc (mb, m->retobj_var);
8790 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8791 mono_mb_emit_op (mb, CEE_MONO_RETOBJ, m->retobj_class);
8794 if (!MONO_TYPE_IS_VOID(sig->ret))
8795 mono_mb_emit_ldloc (mb, 3);
8796 mono_mb_emit_byte (mb, CEE_RET);
8799 mono_mb_set_clauses (mb, 2, clauses);
8807 mono_marshal_set_callconv_from_modopt (MonoMethod *method, MonoMethodSignature *csig)
8809 MonoMethodSignature *sig;
8814 * Under windows, delegates passed to native code must use the STDCALL
8815 * calling convention.
8817 csig->call_convention = MONO_CALL_STDCALL;
8820 sig = mono_method_signature (method);
8822 /* Change default calling convention if needed */
8823 /* Why is this a modopt ? */
8824 if (sig->ret && sig->ret->num_mods) {
8825 for (i = 0; i < sig->ret->num_mods; ++i) {
8827 MonoClass *cmod_class = mono_class_get_checked (method->klass->image, sig->ret->modifiers [i].token, &error);
8828 g_assert (mono_error_ok (&error));
8829 if ((cmod_class->image == mono_defaults.corlib) && !strcmp (cmod_class->name_space, "System.Runtime.CompilerServices")) {
8830 if (!strcmp (cmod_class->name, "CallConvCdecl"))
8831 csig->call_convention = MONO_CALL_C;
8832 else if (!strcmp (cmod_class->name, "CallConvStdcall"))
8833 csig->call_convention = MONO_CALL_STDCALL;
8834 else if (!strcmp (cmod_class->name, "CallConvFastcall"))
8835 csig->call_convention = MONO_CALL_FASTCALL;
8836 else if (!strcmp (cmod_class->name, "CallConvThiscall"))
8837 csig->call_convention = MONO_CALL_THISCALL;
8844 * mono_marshal_get_managed_wrapper:
8845 * Generates IL code to call managed methods from unmanaged code
8846 * If \p target_handle is \c 0, the wrapper info will be a \c WrapperInfo structure.
8849 mono_marshal_get_managed_wrapper (MonoMethod *method, MonoClass *delegate_klass, uint32_t target_handle, MonoError *error)
8851 MonoMethodSignature *sig, *csig, *invoke_sig;
8852 MonoMethodBuilder *mb;
8853 MonoMethod *res, *invoke;
8854 MonoMarshalSpec **mspecs;
8855 MonoMethodPInvoke piinfo;
8858 EmitMarshalContext m;
8860 g_assert (method != NULL);
8863 if (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
8864 mono_error_set_invalid_program (error, "Failed because method (%s) marked PInvokeCallback (managed method) and extern (unmanaged) simultaneously.", mono_method_full_name (method, TRUE));
8869 * FIXME: Should cache the method+delegate type pair, since the same method
8870 * could be called with different delegates, thus different marshalling
8873 cache = get_cache (&mono_method_get_wrapper_cache (method)->managed_wrapper_cache, mono_aligned_addr_hash, NULL);
8875 if (!target_handle && (res = mono_marshal_find_in_cache (cache, method)))
8878 invoke = mono_get_delegate_invoke (delegate_klass);
8879 invoke_sig = mono_method_signature (invoke);
8881 mspecs = g_new0 (MonoMarshalSpec*, mono_method_signature (invoke)->param_count + 1);
8882 mono_method_get_marshal_info (invoke, mspecs);
8884 sig = mono_method_signature (method);
8886 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
8888 /*the target gchandle must be the first entry after size and the wrapper itself.*/
8889 mono_mb_add_data (mb, GUINT_TO_POINTER (target_handle));
8891 /* we copy the signature, so that we can modify it */
8893 /* Need to free this later */
8894 csig = mono_metadata_signature_dup (invoke_sig);
8896 csig = mono_metadata_signature_dup_full (method->klass->image, invoke_sig);
8900 memset (&m, 0, sizeof (m));
8906 m.image = method->klass->image;
8908 mono_marshal_set_callconv_from_modopt (invoke, csig);
8910 /* The attribute is only available in Net 2.0 */
8911 if (mono_class_try_get_unmanaged_function_pointer_attribute_class ()) {
8912 MonoCustomAttrInfo *cinfo;
8913 MonoCustomAttrEntry *attr;
8916 * The pinvoke attributes are stored in a real custom attribute. Obtain the
8917 * contents of the attribute without constructing it, as that might not be
8918 * possible when running in cross-compiling mode.
8920 cinfo = mono_custom_attrs_from_class_checked (delegate_klass, error);
8921 mono_error_assert_ok (error);
8924 for (i = 0; i < cinfo->num_attrs; ++i) {
8925 MonoClass *ctor_class = cinfo->attrs [i].ctor->klass;
8926 if (mono_class_has_parent (ctor_class, mono_class_try_get_unmanaged_function_pointer_attribute_class ())) {
8927 attr = &cinfo->attrs [i];
8933 MonoArray *typed_args, *named_args;
8934 CattrNamedArg *arginfo;
8938 MonoBoolean set_last_error = 0;
8941 mono_reflection_create_custom_attr_data_args (mono_defaults.corlib, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
8942 g_assert (mono_error_ok (&error));
8943 g_assert (mono_array_length (typed_args) == 1);
8946 o = mono_array_get (typed_args, MonoObject*, 0);
8947 call_conv = *(gint32*)mono_object_unbox (o);
8950 for (i = 0; i < mono_array_length (named_args); ++i) {
8951 CattrNamedArg *narg = &arginfo [i];
8953 o = mono_array_get (named_args, MonoObject*, i);
8955 g_assert (narg->field);
8956 if (!strcmp (narg->field->name, "CharSet")) {
8957 charset = *(gint32*)mono_object_unbox (o);
8958 } else if (!strcmp (narg->field->name, "SetLastError")) {
8959 set_last_error = *(MonoBoolean*)mono_object_unbox (o);
8960 } else if (!strcmp (narg->field->name, "BestFitMapping")) {
8961 // best_fit_mapping = *(MonoBoolean*)mono_object_unbox (o);
8962 } else if (!strcmp (narg->field->name, "ThrowOnUnmappableChar")) {
8963 // throw_on_unmappable = *(MonoBoolean*)mono_object_unbox (o);
8965 g_assert_not_reached ();
8971 memset (&piinfo, 0, sizeof (piinfo));
8973 piinfo.piflags = (call_conv << 8) | (charset ? (charset - 1) * 2 : 1) | set_last_error;
8975 csig->call_convention = call_conv - 1;
8978 if (cinfo && !cinfo->cached)
8979 mono_custom_attrs_free (cinfo);
8982 mono_marshal_emit_managed_wrapper (mb, invoke_sig, mspecs, &m, method, target_handle);
8984 if (!target_handle) {
8987 // FIXME: Associate it with the method+delegate_klass pair
8988 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
8989 info->d.native_to_managed.method = method;
8990 info->d.native_to_managed.klass = delegate_klass;
8992 res = mono_mb_create_and_cache_full (cache, method,
8993 mb, csig, sig->param_count + 16,
8996 #ifdef HAVE_ONLINE_VES
8999 res = mono_mb_create (mb, csig, sig->param_count + 16, NULL);
9003 for (i = mono_method_signature (invoke)->param_count; i >= 0; i--)
9005 mono_metadata_free_marshal_spec (mspecs [i]);
9008 /* mono_method_print_code (res); */
9014 mono_marshal_get_vtfixup_ftnptr (MonoImage *image, guint32 token, guint16 type)
9018 MonoMethodSignature *sig;
9019 MonoMethodBuilder *mb;
9024 method = mono_get_method_checked (image, token, NULL, NULL, &error);
9026 g_error ("Could not load vtfixup token 0x%x due to %s", token, mono_error_get_message (&error));
9029 if (type & (VTFIXUP_TYPE_FROM_UNMANAGED | VTFIXUP_TYPE_FROM_UNMANAGED_RETAIN_APPDOMAIN)) {
9030 MonoMethodSignature *csig;
9031 MonoMarshalSpec **mspecs;
9032 EmitMarshalContext m;
9034 sig = mono_method_signature (method);
9035 g_assert (!sig->hasthis);
9037 mspecs = g_new0 (MonoMarshalSpec*, sig->param_count + 1);
9038 mono_method_get_marshal_info (method, mspecs);
9040 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
9041 csig = mono_metadata_signature_dup_full (image, sig);
9045 memset (&m, 0, sizeof (m));
9053 mono_marshal_set_callconv_from_modopt (method, csig);
9055 /* FIXME: Implement VTFIXUP_TYPE_FROM_UNMANAGED_RETAIN_APPDOMAIN. */
9057 mono_marshal_emit_managed_wrapper (mb, sig, mspecs, &m, method, 0);
9059 #ifdef HAVE_ONLINE_VES
9062 method = mono_mb_create (mb, csig, sig->param_count + 16, NULL);
9065 for (i = sig->param_count; i >= 0; i--)
9067 mono_metadata_free_marshal_spec (mspecs [i]);
9070 gpointer compiled_ptr = mono_compile_method_checked (method, &error);
9071 mono_error_assert_ok (&error);
9072 return compiled_ptr;
9075 sig = mono_method_signature (method);
9076 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_MANAGED);
9078 param_count = sig->param_count + sig->hasthis;
9079 #ifdef HAVE_ONLINE_VES
9080 for (i = 0; i < param_count; i++)
9081 mono_mb_emit_ldarg (mb, i);
9083 if (type & VTFIXUP_TYPE_CALL_MOST_DERIVED)
9084 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
9086 mono_mb_emit_op (mb, CEE_CALL, method);
9087 mono_mb_emit_byte (mb, CEE_RET);
9092 method = mono_mb_create (mb, sig, param_count, NULL);
9095 gpointer compiled_ptr = mono_compile_method_checked (method, &error);
9096 mono_error_assert_ok (&error);
9097 return compiled_ptr;
9100 #ifdef HAVE_ONLINE_VES
9103 * The code directly following this is the cache hit, value positive branch
9105 * This function takes a new method builder with 0 locals and adds two locals
9106 * to create multiple out-branches and the fall through state of having the object
9107 * on the stack after a cache miss
9110 generate_check_cache (int obj_arg_position, int class_arg_position, int cache_arg_position, // In-parameters
9111 int *null_obj, int *cache_hit_neg, int *cache_hit_pos, // Out-parameters
9112 MonoMethodBuilder *mb)
9116 /* allocate local 0 (pointer) obj_vtable */
9117 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9118 /* allocate local 1 (pointer) cached_vtable */
9119 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9122 mono_mb_emit_ldarg (mb, obj_arg_position);
9123 *null_obj = mono_mb_emit_branch (mb, CEE_BRFALSE);
9125 /*obj_vtable = obj->vtable;*/
9126 mono_mb_emit_ldarg (mb, obj_arg_position);
9127 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9128 mono_mb_emit_byte (mb, CEE_LDIND_I);
9129 mono_mb_emit_stloc (mb, 0);
9131 /* cached_vtable = *cache*/
9132 mono_mb_emit_ldarg (mb, cache_arg_position);
9133 mono_mb_emit_byte (mb, CEE_LDIND_I);
9134 mono_mb_emit_stloc (mb, 1);
9136 mono_mb_emit_ldloc (mb, 1);
9137 mono_mb_emit_byte (mb, CEE_LDC_I4);
9138 mono_mb_emit_i4 (mb, ~0x1);
9139 mono_mb_emit_byte (mb, CEE_CONV_I);
9140 mono_mb_emit_byte (mb, CEE_AND);
9141 mono_mb_emit_ldloc (mb, 0);
9142 /*if ((cached_vtable & ~0x1)== obj_vtable)*/
9143 cache_miss_pos = mono_mb_emit_branch (mb, CEE_BNE_UN);
9145 /*return (cached_vtable & 0x1) ? NULL : obj;*/
9146 mono_mb_emit_ldloc (mb, 1);
9147 mono_mb_emit_byte(mb, CEE_LDC_I4_1);
9148 mono_mb_emit_byte (mb, CEE_CONV_U);
9149 mono_mb_emit_byte (mb, CEE_AND);
9150 *cache_hit_neg = mono_mb_emit_branch (mb, CEE_BRTRUE);
9151 *cache_hit_pos = mono_mb_emit_branch (mb, CEE_BR);
9154 mono_mb_patch_branch (mb, cache_miss_pos);
9157 mono_mb_emit_ldarg (mb, obj_arg_position);
9158 mono_mb_emit_ldarg (mb, class_arg_position);
9159 mono_mb_emit_ldarg (mb, cache_arg_position);
9160 mono_mb_emit_icall (mb, mono_marshal_isinst_with_cache);
9163 #endif /* HAVE_ONLINE_VES */
9166 * mono_marshal_get_castclass_with_cache:
9167 * This does the equivalent of \c mono_object_castclass_with_cache.
9170 mono_marshal_get_castclass_with_cache (void)
9172 static MonoMethod *cached;
9174 MonoMethodBuilder *mb;
9175 MonoMethodSignature *sig;
9176 int return_null_pos, positive_cache_hit_pos, negative_cache_hit_pos, invalid_cast_pos;
9179 const int obj_arg_position = 0;
9180 const int class_arg_position = 1;
9181 const int cache_arg_position = 2;
9186 mb = mono_mb_new (mono_defaults.object_class, "__castclass_with_cache", MONO_WRAPPER_CASTCLASS);
9187 sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
9188 sig->params [obj_arg_position] = &mono_defaults.object_class->byval_arg;
9189 sig->params [class_arg_position] = &mono_defaults.int_class->byval_arg;
9190 sig->params [cache_arg_position] = &mono_defaults.int_class->byval_arg;
9191 sig->ret = &mono_defaults.object_class->byval_arg;
9194 #ifdef HAVE_ONLINE_VES
9195 generate_check_cache (obj_arg_position, class_arg_position, cache_arg_position,
9196 &return_null_pos, &negative_cache_hit_pos, &positive_cache_hit_pos, mb);
9197 invalid_cast_pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
9200 mono_mb_patch_branch (mb, positive_cache_hit_pos);
9201 mono_mb_emit_ldarg (mb, obj_arg_position);
9202 mono_mb_emit_byte (mb, CEE_RET);
9205 mono_mb_patch_branch (mb, negative_cache_hit_pos);
9206 mono_mb_patch_branch (mb, invalid_cast_pos);
9207 mono_mb_emit_exception (mb, "InvalidCastException", NULL);
9210 mono_mb_patch_branch (mb, return_null_pos);
9211 mono_mb_emit_byte (mb, CEE_LDNULL);
9212 mono_mb_emit_byte (mb, CEE_RET);
9213 #endif /* HAVE_ONLINE_VES */
9215 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE);
9216 res = mono_mb_create (mb, sig, 8, info);
9219 if (InterlockedCompareExchangePointer ((volatile gpointer *)&cached, res, NULL)) {
9220 mono_free_method (res);
9221 mono_metadata_free_method_signature (sig);
9228 /* this is an icall */
9230 mono_marshal_isinst_with_cache (MonoObject *obj, MonoClass *klass, uintptr_t *cache)
9233 MonoObject *isinst = mono_object_isinst_checked (obj, klass, &error);
9234 if (mono_error_set_pending_exception (&error))
9237 if (mono_object_is_transparent_proxy (obj))
9240 uintptr_t cache_update = (uintptr_t)obj->vtable;
9242 cache_update = cache_update | 0x1;
9244 *cache = cache_update;
9250 * mono_marshal_get_isinst_with_cache:
9251 * This does the equivalent of \c mono_marshal_isinst_with_cache.
9254 mono_marshal_get_isinst_with_cache (void)
9256 static MonoMethod *cached;
9258 MonoMethodBuilder *mb;
9259 MonoMethodSignature *sig;
9260 int return_null_pos, positive_cache_hit_pos, negative_cache_hit_pos;
9263 const int obj_arg_position = 0;
9264 const int class_arg_position = 1;
9265 const int cache_arg_position = 2;
9270 mb = mono_mb_new (mono_defaults.object_class, "__isinst_with_cache", MONO_WRAPPER_CASTCLASS);
9271 sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
9273 sig->params [obj_arg_position] = &mono_defaults.object_class->byval_arg;
9275 sig->params [class_arg_position] = &mono_defaults.int_class->byval_arg;
9277 sig->params [cache_arg_position] = &mono_defaults.int_class->byval_arg;
9278 sig->ret = &mono_defaults.object_class->byval_arg;
9281 #ifdef HAVE_ONLINE_VES
9282 generate_check_cache (obj_arg_position, class_arg_position, cache_arg_position,
9283 &return_null_pos, &negative_cache_hit_pos, &positive_cache_hit_pos, mb);
9284 // Return the object gotten via the slow path.
9285 mono_mb_emit_byte (mb, CEE_RET);
9288 mono_mb_patch_branch (mb, negative_cache_hit_pos);
9289 mono_mb_patch_branch (mb, return_null_pos);
9290 mono_mb_emit_byte (mb, CEE_LDNULL);
9291 mono_mb_emit_byte (mb, CEE_RET);
9294 mono_mb_patch_branch (mb, positive_cache_hit_pos);
9295 mono_mb_emit_ldarg (mb, obj_arg_position);
9296 mono_mb_emit_byte (mb, CEE_RET);
9299 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ISINST_WITH_CACHE);
9300 res = mono_mb_create (mb, sig, 8, info);
9303 if (InterlockedCompareExchangePointer ((volatile gpointer *)&cached, res, NULL)) {
9304 mono_free_method (res);
9305 mono_metadata_free_method_signature (sig);
9313 * mono_marshal_get_struct_to_ptr:
9314 * \param klass \c MonoClass
9316 * Generates IL code for <code>StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld)</code>
9319 mono_marshal_get_struct_to_ptr (MonoClass *klass)
9321 MonoMethodBuilder *mb;
9322 static MonoMethod *stoptr = NULL;
9326 g_assert (klass != NULL);
9328 mono_marshal_load_type_info (klass);
9330 MonoMarshalType *marshal_info = mono_class_get_marshal_info (klass);
9331 if (marshal_info->str_to_ptr)
9332 return marshal_info->str_to_ptr;
9335 stoptr = mono_class_get_method_from_name (mono_defaults.marshal_class, "StructureToPtr", 3);
9338 mb = mono_mb_new (klass, stoptr->name, MONO_WRAPPER_UNKNOWN);
9340 #ifdef HAVE_ONLINE_VES
9341 if (klass->blittable) {
9342 mono_mb_emit_byte (mb, CEE_LDARG_1);
9343 mono_mb_emit_byte (mb, CEE_LDARG_0);
9344 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
9345 mono_mb_emit_icon (mb, mono_class_value_size (klass, NULL));
9346 mono_mb_emit_byte (mb, CEE_PREFIX1);
9347 mono_mb_emit_byte (mb, CEE_CPBLK);
9350 /* allocate local 0 (pointer) src_ptr */
9351 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9352 /* allocate local 1 (pointer) dst_ptr */
9353 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9354 /* allocate local 2 (boolean) delete_old */
9355 mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
9356 mono_mb_emit_byte (mb, CEE_LDARG_2);
9357 mono_mb_emit_stloc (mb, 2);
9359 /* initialize src_ptr to point to the start of object data */
9360 mono_mb_emit_byte (mb, CEE_LDARG_0);
9361 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
9362 mono_mb_emit_stloc (mb, 0);
9364 /* initialize dst_ptr */
9365 mono_mb_emit_byte (mb, CEE_LDARG_1);
9366 mono_mb_emit_stloc (mb, 1);
9368 emit_struct_conv (mb, klass, FALSE);
9371 mono_mb_emit_byte (mb, CEE_RET);
9373 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_STRUCTURE_TO_PTR);
9374 res = mono_mb_create (mb, mono_signature_no_pinvoke (stoptr), 0, info);
9377 mono_marshal_lock ();
9378 if (!marshal_info->str_to_ptr)
9379 marshal_info->str_to_ptr = res;
9381 res = marshal_info->str_to_ptr;
9382 mono_marshal_unlock ();
9387 * mono_marshal_get_ptr_to_struct:
9388 * \param klass \c MonoClass
9389 * Generates IL code for <code>PtrToStructure (IntPtr src, object structure)</code>
9392 mono_marshal_get_ptr_to_struct (MonoClass *klass)
9394 MonoMethodBuilder *mb;
9395 static MonoMethodSignature *ptostr = NULL;
9399 g_assert (klass != NULL);
9401 mono_marshal_load_type_info (klass);
9403 MonoMarshalType *marshal_info = mono_class_get_marshal_info (klass);
9404 if (marshal_info->ptr_to_str)
9405 return marshal_info->ptr_to_str;
9408 MonoMethodSignature *sig;
9410 /* Create the signature corresponding to
9411 static void PtrToStructure (IntPtr ptr, object structure);
9412 defined in class/corlib/System.Runtime.InteropServices/Marshal.cs */
9413 sig = mono_create_icall_signature ("void ptr object");
9414 sig = mono_metadata_signature_dup_full (mono_defaults.corlib, sig);
9416 mono_memory_barrier ();
9420 mb = mono_mb_new (klass, "PtrToStructure", MONO_WRAPPER_UNKNOWN);
9422 #ifdef HAVE_ONLINE_VES
9423 if (klass->blittable) {
9424 mono_mb_emit_byte (mb, CEE_LDARG_1);
9425 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
9426 mono_mb_emit_byte (mb, CEE_LDARG_0);
9427 mono_mb_emit_icon (mb, mono_class_value_size (klass, NULL));
9428 mono_mb_emit_byte (mb, CEE_PREFIX1);
9429 mono_mb_emit_byte (mb, CEE_CPBLK);
9432 /* allocate local 0 (pointer) src_ptr */
9433 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9434 /* allocate local 1 (pointer) dst_ptr */
9435 mono_mb_add_local (mb, &klass->this_arg);
9437 /* initialize src_ptr to point to the start of object data */
9438 mono_mb_emit_byte (mb, CEE_LDARG_0);
9439 mono_mb_emit_stloc (mb, 0);
9441 /* initialize dst_ptr */
9442 mono_mb_emit_byte (mb, CEE_LDARG_1);
9443 mono_mb_emit_op (mb, CEE_UNBOX, klass);
9444 mono_mb_emit_stloc (mb, 1);
9446 emit_struct_conv (mb, klass, TRUE);
9449 mono_mb_emit_byte (mb, CEE_RET);
9451 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_PTR_TO_STRUCTURE);
9452 res = mono_mb_create (mb, ptostr, 0, info);
9455 mono_marshal_lock ();
9456 if (!marshal_info->ptr_to_str)
9457 marshal_info->ptr_to_str = res;
9459 res = marshal_info->ptr_to_str;
9460 mono_marshal_unlock ();
9465 * Return a dummy wrapper for METHOD which is called by synchronized wrappers.
9466 * This is used to avoid infinite recursion since it is hard to determine where to
9467 * replace a method with its synchronized wrapper, and where not.
9468 * The runtime should execute METHOD instead of the wrapper.
9471 mono_marshal_get_synchronized_inner_wrapper (MonoMethod *method)
9473 MonoMethodBuilder *mb;
9475 MonoMethodSignature *sig;
9477 MonoGenericContext *ctx = NULL;
9478 MonoGenericContainer *container = NULL;
9480 if (method->is_inflated && !mono_method_get_context (method)->method_inst) {
9481 ctx = &((MonoMethodInflated*)method)->context;
9482 method = ((MonoMethodInflated*)method)->declaring;
9483 container = mono_method_get_generic_container (method);
9485 container = mono_class_try_get_generic_container (method->klass); //FIXME is this a case of a try?
9486 g_assert (container);
9489 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNKNOWN);
9490 #ifdef HAVE_ONLINE_VES
9491 mono_mb_emit_exception_full (mb, "System", "ExecutionEngineException", "Shouldn't be called.");
9492 mono_mb_emit_byte (mb, CEE_RET);
9494 sig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
9496 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_SYNCHRONIZED_INNER);
9497 info->d.synchronized_inner.method = method;
9498 res = mono_mb_create (mb, sig, 0, info);
9502 res = mono_class_inflate_generic_method_checked (res, ctx, &error);
9503 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9509 * mono_marshal_get_synchronized_wrapper:
9510 * Generates IL code for the synchronized wrapper: the generated method
9511 * calls \p method while locking \c this or the parent type.
9514 mono_marshal_get_synchronized_wrapper (MonoMethod *method)
9516 static MonoMethod *enter_method, *exit_method, *gettypefromhandle_method;
9517 MonoMethodSignature *sig;
9518 MonoExceptionClause *clause;
9519 MonoMethodBuilder *mb;
9523 int i, pos, pos2, this_local, taken_local, ret_local = 0;
9524 MonoGenericContext *ctx = NULL;
9525 MonoMethod *orig_method = NULL;
9526 MonoGenericContainer *container = NULL;
9530 if (method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED)
9533 /* FIXME: Support generic methods too */
9534 if (method->is_inflated && !mono_method_get_context (method)->method_inst) {
9535 orig_method = method;
9536 ctx = &((MonoMethodInflated*)method)->context;
9537 method = ((MonoMethodInflated*)method)->declaring;
9538 container = mono_method_get_generic_container (method);
9540 container = mono_class_try_get_generic_container (method->klass); //FIXME is this a case of a try?
9541 g_assert (container);
9548 cache = get_cache (&((MonoMethodInflated*)orig_method)->owner->wrapper_caches.synchronized_cache, mono_aligned_addr_hash, NULL);
9549 res = check_generic_wrapper_cache (cache, orig_method, orig_method, method);
9553 cache = get_cache (&method->klass->image->wrapper_caches.synchronized_cache, mono_aligned_addr_hash, NULL);
9554 if ((res = mono_marshal_find_in_cache (cache, method)))
9558 sig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
9561 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_SYNCHRONIZED);
9563 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
9564 info->d.synchronized.method = method;
9566 #ifdef HAVE_ONLINE_VES
9567 mb->skip_visibility = 1;
9569 if (!MONO_TYPE_IS_VOID (sig->ret))
9570 ret_local = mono_mb_add_local (mb, sig->ret);
9573 if (method->klass->valuetype && !(method->flags & MONO_METHOD_ATTR_STATIC)) {
9574 /* FIXME Is this really the best way to signal an error here? Isn't this called much later after class setup? -AK */
9575 mono_class_set_type_load_failure (method->klass, "");
9576 #ifdef HAVE_ONLINE_VES
9577 /* This will throw the type load exception when the wrapper is compiled */
9578 mono_mb_emit_byte (mb, CEE_LDNULL);
9579 mono_mb_emit_op (mb, CEE_ISINST, method->klass);
9580 mono_mb_emit_byte (mb, CEE_POP);
9582 if (!MONO_TYPE_IS_VOID (sig->ret))
9583 mono_mb_emit_ldloc (mb, ret_local);
9584 mono_mb_emit_byte (mb, CEE_RET);
9587 res = mono_mb_create_and_cache_full (cache, method,
9588 mb, sig, sig->param_count + 16, info, NULL);
9594 #ifdef HAVE_ONLINE_VES
9596 this_local = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
9597 taken_local = mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
9599 clause = (MonoExceptionClause *)mono_image_alloc0 (method->klass->image, sizeof (MonoExceptionClause));
9600 clause->flags = MONO_EXCEPTION_CLAUSE_FINALLY;
9603 mono_marshal_lock ();
9605 if (!enter_method) {
9606 MonoMethodDesc *desc;
9608 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
9609 enter_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
9610 g_assert (enter_method);
9611 mono_method_desc_free (desc);
9613 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
9614 exit_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
9615 g_assert (exit_method);
9616 mono_method_desc_free (desc);
9618 desc = mono_method_desc_new ("Type:GetTypeFromHandle", FALSE);
9619 gettypefromhandle_method = mono_method_desc_search_in_class (desc, mono_defaults.systemtype_class);
9620 g_assert (gettypefromhandle_method);
9621 mono_method_desc_free (desc);
9624 mono_marshal_unlock ();
9626 #ifdef HAVE_ONLINE_VES
9627 /* Push this or the type object */
9628 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
9629 /* We have special handling for this in the JIT */
9630 int index = mono_mb_add_data (mb, method->klass);
9631 mono_mb_add_data (mb, mono_defaults.typehandle_class);
9632 mono_mb_emit_byte (mb, CEE_LDTOKEN);
9633 mono_mb_emit_i4 (mb, index);
9635 mono_mb_emit_managed_call (mb, gettypefromhandle_method, NULL);
9638 mono_mb_emit_ldarg (mb, 0);
9639 mono_mb_emit_stloc (mb, this_local);
9641 /* Call Monitor::Enter() */
9642 mono_mb_emit_ldloc (mb, this_local);
9643 mono_mb_emit_ldloc_addr (mb, taken_local);
9644 mono_mb_emit_managed_call (mb, enter_method, NULL);
9646 clause->try_offset = mono_mb_get_label (mb);
9648 /* Call the method */
9650 mono_mb_emit_ldarg (mb, 0);
9651 for (i = 0; i < sig->param_count; i++)
9652 mono_mb_emit_ldarg (mb, i + (sig->hasthis == TRUE));
9656 mono_mb_emit_managed_call (mb, mono_class_inflate_generic_method_checked (method, &container->context, &error), NULL);
9657 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9659 mono_mb_emit_managed_call (mb, method, NULL);
9662 if (!MONO_TYPE_IS_VOID (sig->ret))
9663 mono_mb_emit_stloc (mb, ret_local);
9665 pos = mono_mb_emit_branch (mb, CEE_LEAVE);
9667 clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
9668 clause->handler_offset = mono_mb_get_label (mb);
9670 /* Call Monitor::Exit() if needed */
9671 mono_mb_emit_ldloc (mb, taken_local);
9672 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9673 mono_mb_emit_ldloc (mb, this_local);
9674 mono_mb_emit_managed_call (mb, exit_method, NULL);
9675 mono_mb_patch_branch (mb, pos2);
9676 mono_mb_emit_byte (mb, CEE_ENDFINALLY);
9678 clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
9680 mono_mb_patch_branch (mb, pos);
9681 if (!MONO_TYPE_IS_VOID (sig->ret))
9682 mono_mb_emit_ldloc (mb, ret_local);
9683 mono_mb_emit_byte (mb, CEE_RET);
9685 mono_mb_set_clauses (mb, 1, clause);
9690 def = mono_mb_create_and_cache_full (cache, method, mb, sig, sig->param_count + 16, info, NULL);
9691 res = cache_generic_wrapper (cache, orig_method, def, ctx, orig_method);
9693 res = mono_mb_create_and_cache_full (cache, method,
9694 mb, sig, sig->param_count + 16, info, NULL);
9703 * mono_marshal_get_unbox_wrapper:
9704 * The returned method calls \p method unboxing the \c this argument.
9707 mono_marshal_get_unbox_wrapper (MonoMethod *method)
9709 MonoMethodSignature *sig = mono_method_signature (method);
9711 MonoMethodBuilder *mb;
9716 cache = get_cache (&mono_method_get_wrapper_cache (method)->unbox_wrapper_cache, mono_aligned_addr_hash, NULL);
9718 if ((res = mono_marshal_find_in_cache (cache, method)))
9721 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNBOX);
9723 g_assert (sig->hasthis);
9725 #ifdef HAVE_ONLINE_VES
9726 mono_mb_emit_ldarg (mb, 0);
9727 mono_mb_emit_icon (mb, sizeof (MonoObject));
9728 mono_mb_emit_byte (mb, CEE_ADD);
9729 for (i = 0; i < sig->param_count; ++i)
9730 mono_mb_emit_ldarg (mb, i + 1);
9731 mono_mb_emit_managed_call (mb, method, NULL);
9732 mono_mb_emit_byte (mb, CEE_RET);
9735 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
9736 info->d.unbox.method = method;
9738 res = mono_mb_create_and_cache_full (cache, method,
9739 mb, sig, sig->param_count + 16, info, NULL);
9742 /* mono_method_print_code (res); */
9748 STELEMREF_OBJECT, /*no check at all*/
9749 STELEMREF_SEALED_CLASS, /*check vtable->klass->element_type */
9750 STELEMREF_CLASS, /*only the klass->parents check*/
9751 STELEMREF_CLASS_SMALL_IDEPTH, /* like STELEMREF_CLASS bit without the idepth check */
9752 STELEMREF_INTERFACE, /*interfaces without variant generic arguments. */
9753 STELEMREF_COMPLEX, /*arrays, MBR or types with variant generic args - go straight to icalls*/
9754 STELEMREF_KIND_COUNT
9757 static const char *strelemref_wrapper_name[] = {
9758 "object", "sealed_class", "class", "class_small_idepth", "interface", "complex"
9762 is_monomorphic_array (MonoClass *klass)
9764 MonoClass *element_class;
9765 if (klass->rank != 1)
9768 element_class = klass->element_class;
9769 return mono_class_is_sealed (element_class) || element_class->valuetype;
9773 get_virtual_stelemref_kind (MonoClass *element_class)
9775 if (element_class == mono_defaults.object_class)
9776 return STELEMREF_OBJECT;
9777 if (is_monomorphic_array (element_class))
9778 return STELEMREF_SEALED_CLASS;
9779 /* Compressed interface bitmaps require code that is quite complex, so don't optimize for it. */
9780 if (MONO_CLASS_IS_INTERFACE (element_class) && !mono_class_has_variant_generic_params (element_class))
9781 #ifdef COMPRESSED_INTERFACE_BITMAP
9782 return STELEMREF_COMPLEX;
9784 return STELEMREF_INTERFACE;
9786 /*Arrays are sealed but are covariant on their element type, We can't use any of the fast paths.*/
9787 if (mono_class_is_marshalbyref (element_class) || element_class->rank || mono_class_has_variant_generic_params (element_class))
9788 return STELEMREF_COMPLEX;
9789 if (mono_class_is_sealed (element_class))
9790 return STELEMREF_SEALED_CLASS;
9791 if (element_class->idepth <= MONO_DEFAULT_SUPERTABLE_SIZE)
9792 return STELEMREF_CLASS_SMALL_IDEPTH;
9794 return STELEMREF_CLASS;
9797 #ifdef HAVE_ONLINE_VES
9800 load_array_element_address (MonoMethodBuilder *mb)
9802 mono_mb_emit_ldarg (mb, 0);
9803 mono_mb_emit_ldarg (mb, 1);
9804 mono_mb_emit_op (mb, CEE_LDELEMA, mono_defaults.object_class);
9808 load_array_class (MonoMethodBuilder *mb, int aklass)
9810 mono_mb_emit_ldarg (mb, 0);
9811 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9812 mono_mb_emit_byte (mb, CEE_LDIND_I);
9813 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
9814 mono_mb_emit_byte (mb, CEE_LDIND_I);
9815 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, element_class));
9816 mono_mb_emit_byte (mb, CEE_LDIND_I);
9817 mono_mb_emit_stloc (mb, aklass);
9821 load_value_class (MonoMethodBuilder *mb, int vklass)
9823 mono_mb_emit_ldarg (mb, 2);
9824 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9825 mono_mb_emit_byte (mb, CEE_LDIND_I);
9826 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
9827 mono_mb_emit_byte (mb, CEE_LDIND_I);
9828 mono_mb_emit_stloc (mb, vklass);
9834 record_slot_vstore (MonoObject *array, size_t index, MonoObject *value)
9836 char *name = mono_type_get_full_name (array->vtable->klass->element_class);
9837 printf ("slow vstore of %s\n", name);
9844 * - Separate simple interfaces from variant interfaces or mbr types. This way we can avoid the icall for them.
9845 * - Emit a (new) mono bytecode that produces OP_COND_EXC_NE_UN to raise ArrayTypeMismatch
9846 * - Maybe mve some MonoClass field into the vtable to reduce the number of loads
9847 * - Add a case for arrays of arrays.
9850 get_virtual_stelemref_wrapper (int kind)
9852 static MonoMethod *cached_methods [STELEMREF_KIND_COUNT] = { NULL }; /*object iface sealed regular*/
9853 static MonoMethodSignature *signature;
9854 MonoMethodBuilder *mb;
9857 const char *param_names [16];
9858 guint32 b1, b2, b3, b4;
9859 int aklass, vklass, vtable, uiid;
9860 int array_slot_addr;
9863 if (cached_methods [kind])
9864 return cached_methods [kind];
9866 name = g_strdup_printf ("virt_stelemref_%s", strelemref_wrapper_name [kind]);
9867 mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_STELEMREF);
9871 MonoMethodSignature *sig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
9873 /* void this::stelemref (size_t idx, void* value) */
9874 sig->ret = &mono_defaults.void_class->byval_arg;
9875 sig->hasthis = TRUE;
9876 sig->params [0] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
9877 sig->params [1] = &mono_defaults.object_class->byval_arg;
9881 #ifdef HAVE_ONLINE_VES
9882 param_names [0] = "index";
9883 param_names [1] = "value";
9884 mono_mb_set_param_names (mb, param_names);
9886 /*For now simply call plain old stelemref*/
9888 case STELEMREF_OBJECT:
9889 /* ldelema (implicit bound check) */
9890 load_array_element_address (mb);
9892 mono_mb_emit_ldarg (mb, 2);
9893 mono_mb_emit_byte (mb, CEE_STIND_REF);
9894 mono_mb_emit_byte (mb, CEE_RET);
9897 case STELEMREF_COMPLEX: {
9900 <ldelema (bound check)>
9903 if (!mono_object_isinst (value, aklass))
9907 *array_slot_addr = value;
9910 throw new ArrayTypeMismatchException ();
9913 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9914 vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9915 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9919 /*Use this to debug/record stores that are going thru the slow path*/
9920 MonoMethodSignature *csig;
9921 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
9922 csig->ret = &mono_defaults.void_class->byval_arg;
9923 csig->params [0] = &mono_defaults.object_class->byval_arg;
9924 csig->params [1] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
9925 csig->params [2] = &mono_defaults.object_class->byval_arg;
9926 mono_mb_emit_ldarg (mb, 0);
9927 mono_mb_emit_ldarg (mb, 1);
9928 mono_mb_emit_ldarg (mb, 2);
9929 mono_mb_emit_native_call (mb, csig, record_slot_vstore);
9933 /* ldelema (implicit bound check) */
9934 load_array_element_address (mb);
9935 mono_mb_emit_stloc (mb, array_slot_addr);
9937 /* if (!value) goto do_store */
9938 mono_mb_emit_ldarg (mb, 2);
9939 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9941 /* aklass = array->vtable->klass->element_class */
9942 load_array_class (mb, aklass);
9943 /* vklass = value->vtable->klass */
9944 load_value_class (mb, vklass);
9947 mono_mb_emit_ldloc (mb, vklass);
9948 mono_mb_emit_ldloc (mb, aklass);
9949 b_fast = mono_mb_emit_branch (mb, CEE_BEQ);
9951 /*if (mono_object_isinst (value, aklass)) */
9952 mono_mb_emit_ldarg (mb, 2);
9953 mono_mb_emit_ldloc (mb, aklass);
9954 mono_mb_emit_icall (mb, mono_object_isinst_icall);
9955 b2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9958 mono_mb_patch_branch (mb, b1);
9959 mono_mb_patch_branch (mb, b_fast);
9960 mono_mb_emit_ldloc (mb, array_slot_addr);
9961 mono_mb_emit_ldarg (mb, 2);
9962 mono_mb_emit_byte (mb, CEE_STIND_REF);
9963 mono_mb_emit_byte (mb, CEE_RET);
9966 mono_mb_patch_branch (mb, b2);
9968 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9971 case STELEMREF_SEALED_CLASS:
9973 <ldelema (bound check)>
9977 aklass = array->vtable->klass->element_class;
9978 vklass = value->vtable->klass;
9980 if (vklass != aklass)
9984 *array_slot_addr = value;
9987 throw new ArrayTypeMismatchException ();
9989 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9990 vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9991 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9993 /* ldelema (implicit bound check) */
9994 load_array_element_address (mb);
9995 mono_mb_emit_stloc (mb, array_slot_addr);
9997 /* if (!value) goto do_store */
9998 mono_mb_emit_ldarg (mb, 2);
9999 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
10001 /* aklass = array->vtable->klass->element_class */
10002 load_array_class (mb, aklass);
10004 /* vklass = value->vtable->klass */
10005 load_value_class (mb, vklass);
10007 /*if (vklass != aklass) goto do_exception; */
10008 mono_mb_emit_ldloc (mb, aklass);
10009 mono_mb_emit_ldloc (mb, vklass);
10010 b2 = mono_mb_emit_branch (mb, CEE_BNE_UN);
10013 mono_mb_patch_branch (mb, b1);
10014 mono_mb_emit_ldloc (mb, array_slot_addr);
10015 mono_mb_emit_ldarg (mb, 2);
10016 mono_mb_emit_byte (mb, CEE_STIND_REF);
10017 mono_mb_emit_byte (mb, CEE_RET);
10019 /* do_exception: */
10020 mono_mb_patch_branch (mb, b2);
10021 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
10024 case STELEMREF_CLASS: {
10027 <ldelema (bound check)>
10031 aklass = array->vtable->klass->element_class;
10032 vklass = value->vtable->klass;
10034 if (vklass->idepth < aklass->idepth)
10037 if (vklass->supertypes [aklass->idepth - 1] != aklass)
10041 *array_slot_addr = value;
10045 throw new ArrayTypeMismatchException ();
10047 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10048 vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10049 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
10051 /* ldelema (implicit bound check) */
10052 load_array_element_address (mb);
10053 mono_mb_emit_stloc (mb, array_slot_addr);
10055 /* if (!value) goto do_store */
10056 mono_mb_emit_ldarg (mb, 2);
10057 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
10059 /* aklass = array->vtable->klass->element_class */
10060 load_array_class (mb, aklass);
10062 /* vklass = value->vtable->klass */
10063 load_value_class (mb, vklass);
10065 /* if (vklass->idepth < aklass->idepth) goto failue */
10066 mono_mb_emit_ldloc (mb, vklass);
10067 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
10068 mono_mb_emit_byte (mb, CEE_LDIND_U2);
10070 mono_mb_emit_ldloc (mb, aklass);
10071 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
10072 mono_mb_emit_byte (mb, CEE_LDIND_U2);
10074 b3 = mono_mb_emit_branch (mb, CEE_BLT_UN);
10076 /* if (vklass->supertypes [aklass->idepth - 1] != aklass) goto failure */
10077 mono_mb_emit_ldloc (mb, vklass);
10078 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, supertypes));
10079 mono_mb_emit_byte (mb, CEE_LDIND_I);
10081 mono_mb_emit_ldloc (mb, aklass);
10082 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
10083 mono_mb_emit_byte (mb, CEE_LDIND_U2);
10084 mono_mb_emit_icon (mb, 1);
10085 mono_mb_emit_byte (mb, CEE_SUB);
10086 mono_mb_emit_icon (mb, sizeof (void*));
10087 mono_mb_emit_byte (mb, CEE_MUL);
10088 mono_mb_emit_byte (mb, CEE_ADD);
10089 mono_mb_emit_byte (mb, CEE_LDIND_I);
10091 mono_mb_emit_ldloc (mb, aklass);
10092 b4 = mono_mb_emit_branch (mb, CEE_BNE_UN);
10095 mono_mb_patch_branch (mb, b1);
10096 mono_mb_emit_ldloc (mb, array_slot_addr);
10097 mono_mb_emit_ldarg (mb, 2);
10098 mono_mb_emit_byte (mb, CEE_STIND_REF);
10099 mono_mb_emit_byte (mb, CEE_RET);
10101 /* do_exception: */
10102 mono_mb_patch_branch (mb, b3);
10103 mono_mb_patch_branch (mb, b4);
10105 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
10109 case STELEMREF_CLASS_SMALL_IDEPTH:
10112 <ldelema (bound check)>
10116 aklass = array->vtable->klass->element_class;
10117 vklass = value->vtable->klass;
10119 if (vklass->supertypes [aklass->idepth - 1] != aklass)
10123 *array_slot_addr = value;
10127 throw new ArrayTypeMismatchException ();
10129 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10130 vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10131 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
10133 /* ldelema (implicit bound check) */
10134 load_array_element_address (mb);
10135 mono_mb_emit_stloc (mb, array_slot_addr);
10137 /* if (!value) goto do_store */
10138 mono_mb_emit_ldarg (mb, 2);
10139 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
10141 /* aklass = array->vtable->klass->element_class */
10142 load_array_class (mb, aklass);
10144 /* vklass = value->vtable->klass */
10145 load_value_class (mb, vklass);
10147 /* if (vklass->supertypes [aklass->idepth - 1] != aklass) goto failure */
10148 mono_mb_emit_ldloc (mb, vklass);
10149 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, supertypes));
10150 mono_mb_emit_byte (mb, CEE_LDIND_I);
10152 mono_mb_emit_ldloc (mb, aklass);
10153 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
10154 mono_mb_emit_byte (mb, CEE_LDIND_U2);
10155 mono_mb_emit_icon (mb, 1);
10156 mono_mb_emit_byte (mb, CEE_SUB);
10157 mono_mb_emit_icon (mb, sizeof (void*));
10158 mono_mb_emit_byte (mb, CEE_MUL);
10159 mono_mb_emit_byte (mb, CEE_ADD);
10160 mono_mb_emit_byte (mb, CEE_LDIND_I);
10162 mono_mb_emit_ldloc (mb, aklass);
10163 b4 = mono_mb_emit_branch (mb, CEE_BNE_UN);
10166 mono_mb_patch_branch (mb, b1);
10167 mono_mb_emit_ldloc (mb, array_slot_addr);
10168 mono_mb_emit_ldarg (mb, 2);
10169 mono_mb_emit_byte (mb, CEE_STIND_REF);
10170 mono_mb_emit_byte (mb, CEE_RET);
10172 /* do_exception: */
10173 mono_mb_patch_branch (mb, b4);
10175 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
10178 case STELEMREF_INTERFACE:
10185 klass = array->obj.vtable->klass->element_class;
10186 vt = value->vtable;
10187 uiid = klass->interface_id;
10188 if (uiid > vt->max_interface_id)
10190 if (!(vt->interface_bitmap [(uiid) >> 3] & (1 << ((uiid)&7))))
10193 mono_array_setref (array, index, value);
10196 mono_raise_exception (mono_get_exception_array_type_mismatch ());*/
10198 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
10199 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10200 vtable = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10201 uiid = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
10203 /* ldelema (implicit bound check) */
10204 load_array_element_address (mb);
10205 mono_mb_emit_stloc (mb, array_slot_addr);
10207 /* if (!value) goto do_store */
10208 mono_mb_emit_ldarg (mb, 2);
10209 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
10211 /* klass = array->vtable->klass->element_class */
10212 load_array_class (mb, aklass);
10214 /* vt = value->vtable */
10215 mono_mb_emit_ldarg (mb, 2);
10216 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
10217 mono_mb_emit_byte (mb, CEE_LDIND_I);
10218 mono_mb_emit_stloc (mb, vtable);
10220 /* uiid = klass->interface_id; */
10221 mono_mb_emit_ldloc (mb, aklass);
10222 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, interface_id));
10223 mono_mb_emit_byte (mb, CEE_LDIND_U4);
10224 mono_mb_emit_stloc (mb, uiid);
10226 /*if (uiid > vt->max_interface_id)*/
10227 mono_mb_emit_ldloc (mb, uiid);
10228 mono_mb_emit_ldloc (mb, vtable);
10229 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, max_interface_id));
10230 mono_mb_emit_byte (mb, CEE_LDIND_U4);
10231 b2 = mono_mb_emit_branch (mb, CEE_BGT_UN);
10233 /* if (!(vt->interface_bitmap [(uiid) >> 3] & (1 << ((uiid)&7)))) */
10235 /*vt->interface_bitmap*/
10236 mono_mb_emit_ldloc (mb, vtable);
10237 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, interface_bitmap));
10238 mono_mb_emit_byte (mb, CEE_LDIND_I);
10241 mono_mb_emit_ldloc (mb, uiid);
10242 mono_mb_emit_icon (mb, 3);
10243 mono_mb_emit_byte (mb, CEE_SHR_UN);
10245 /*vt->interface_bitmap [(uiid) >> 3]*/
10246 mono_mb_emit_byte (mb, CEE_ADD); /*interface_bitmap is a guint8 array*/
10247 mono_mb_emit_byte (mb, CEE_LDIND_U1);
10249 /*(1 << ((uiid)&7)))*/
10250 mono_mb_emit_icon (mb, 1);
10251 mono_mb_emit_ldloc (mb, uiid);
10252 mono_mb_emit_icon (mb, 7);
10253 mono_mb_emit_byte (mb, CEE_AND);
10254 mono_mb_emit_byte (mb, CEE_SHL);
10256 /*bitwise and the whole thing*/
10257 mono_mb_emit_byte (mb, CEE_AND);
10258 b3 = mono_mb_emit_branch (mb, CEE_BRFALSE);
10261 mono_mb_patch_branch (mb, b1);
10262 mono_mb_emit_ldloc (mb, array_slot_addr);
10263 mono_mb_emit_ldarg (mb, 2);
10264 mono_mb_emit_byte (mb, CEE_STIND_REF);
10265 mono_mb_emit_byte (mb, CEE_RET);
10267 /* do_exception: */
10268 mono_mb_patch_branch (mb, b2);
10269 mono_mb_patch_branch (mb, b3);
10270 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
10274 mono_mb_emit_ldarg (mb, 0);
10275 mono_mb_emit_ldarg (mb, 1);
10276 mono_mb_emit_ldarg (mb, 2);
10277 mono_mb_emit_managed_call (mb, mono_marshal_get_stelemref (), NULL);
10278 mono_mb_emit_byte (mb, CEE_RET);
10281 #endif /* HAVE_ONLINE_VES */
10282 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_VIRTUAL_STELEMREF);
10283 info->d.virtual_stelemref.kind = kind;
10284 res = mono_mb_create (mb, signature, 4, info);
10285 res->flags |= METHOD_ATTRIBUTE_VIRTUAL;
10287 mono_marshal_lock ();
10288 if (!cached_methods [kind]) {
10289 cached_methods [kind] = res;
10290 mono_marshal_unlock ();
10292 mono_marshal_unlock ();
10293 mono_free_method (res);
10297 return cached_methods [kind];
10301 mono_marshal_get_virtual_stelemref (MonoClass *array_class)
10305 g_assert (array_class->rank == 1);
10306 kind = get_virtual_stelemref_kind (array_class->element_class);
10308 return get_virtual_stelemref_wrapper (kind);
10312 mono_marshal_get_virtual_stelemref_wrappers (int *nwrappers)
10317 *nwrappers = STELEMREF_KIND_COUNT;
10318 res = (MonoMethod **)g_malloc0 (STELEMREF_KIND_COUNT * sizeof (MonoMethod*));
10319 for (i = 0; i < STELEMREF_KIND_COUNT; ++i)
10320 res [i] = get_virtual_stelemref_wrapper (i);
10325 * mono_marshal_get_stelemref:
10328 mono_marshal_get_stelemref (void)
10330 static MonoMethod* ret = NULL;
10331 MonoMethodSignature *sig;
10332 MonoMethodBuilder *mb;
10335 guint32 b1, b2, b3, b4;
10337 int aklass, vklass;
10338 int array_slot_addr;
10343 mb = mono_mb_new (mono_defaults.object_class, "stelemref", MONO_WRAPPER_STELEMREF);
10346 sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
10348 /* void stelemref (void* array, int idx, void* value) */
10349 sig->ret = &mono_defaults.void_class->byval_arg;
10350 sig->params [0] = &mono_defaults.object_class->byval_arg;
10351 sig->params [1] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
10352 sig->params [2] = &mono_defaults.object_class->byval_arg;
10354 #ifdef HAVE_ONLINE_VES
10355 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10356 vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10357 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
10361 <ldelema (bound check)>
10365 aklass = array->vtable->klass->element_class;
10366 vklass = value->vtable->klass;
10368 if (vklass->idepth < aklass->idepth)
10371 if (vklass->supertypes [aklass->idepth - 1] != aklass)
10375 *array_slot_addr = value;
10379 if (mono_object_isinst (value, aklass))
10382 throw new ArrayTypeMismatchException ();
10385 /* ldelema (implicit bound check) */
10386 mono_mb_emit_ldarg (mb, 0);
10387 mono_mb_emit_ldarg (mb, 1);
10388 mono_mb_emit_op (mb, CEE_LDELEMA, mono_defaults.object_class);
10389 mono_mb_emit_stloc (mb, array_slot_addr);
10391 /* if (!value) goto do_store */
10392 mono_mb_emit_ldarg (mb, 2);
10393 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
10395 /* aklass = array->vtable->klass->element_class */
10396 mono_mb_emit_ldarg (mb, 0);
10397 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
10398 mono_mb_emit_byte (mb, CEE_LDIND_I);
10399 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
10400 mono_mb_emit_byte (mb, CEE_LDIND_I);
10401 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, element_class));
10402 mono_mb_emit_byte (mb, CEE_LDIND_I);
10403 mono_mb_emit_stloc (mb, aklass);
10405 /* vklass = value->vtable->klass */
10406 mono_mb_emit_ldarg (mb, 2);
10407 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
10408 mono_mb_emit_byte (mb, CEE_LDIND_I);
10409 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
10410 mono_mb_emit_byte (mb, CEE_LDIND_I);
10411 mono_mb_emit_stloc (mb, vklass);
10413 /* if (vklass->idepth < aklass->idepth) goto failue */
10414 mono_mb_emit_ldloc (mb, vklass);
10415 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
10416 mono_mb_emit_byte (mb, CEE_LDIND_U2);
10418 mono_mb_emit_ldloc (mb, aklass);
10419 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
10420 mono_mb_emit_byte (mb, CEE_LDIND_U2);
10422 b2 = mono_mb_emit_branch (mb, CEE_BLT_UN);
10424 /* if (vklass->supertypes [aklass->idepth - 1] != aklass) goto failure */
10425 mono_mb_emit_ldloc (mb, vklass);
10426 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, supertypes));
10427 mono_mb_emit_byte (mb, CEE_LDIND_I);
10429 mono_mb_emit_ldloc (mb, aklass);
10430 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
10431 mono_mb_emit_byte (mb, CEE_LDIND_U2);
10432 mono_mb_emit_icon (mb, 1);
10433 mono_mb_emit_byte (mb, CEE_SUB);
10434 mono_mb_emit_icon (mb, sizeof (void*));
10435 mono_mb_emit_byte (mb, CEE_MUL);
10436 mono_mb_emit_byte (mb, CEE_ADD);
10437 mono_mb_emit_byte (mb, CEE_LDIND_I);
10439 mono_mb_emit_ldloc (mb, aklass);
10441 b3 = mono_mb_emit_branch (mb, CEE_BNE_UN);
10443 copy_pos = mono_mb_get_label (mb);
10445 mono_mb_patch_branch (mb, b1);
10446 mono_mb_emit_ldloc (mb, array_slot_addr);
10447 mono_mb_emit_ldarg (mb, 2);
10448 mono_mb_emit_byte (mb, CEE_STIND_REF);
10450 mono_mb_emit_byte (mb, CEE_RET);
10453 mono_mb_patch_branch (mb, b2);
10454 mono_mb_patch_branch (mb, b3);
10456 mono_mb_emit_ldarg (mb, 2);
10457 mono_mb_emit_ldloc (mb, aklass);
10458 mono_mb_emit_icall (mb, mono_object_isinst_icall);
10460 b4 = mono_mb_emit_branch (mb, CEE_BRTRUE);
10461 mono_mb_patch_addr (mb, b4, copy_pos - (b4 + 4));
10462 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
10464 mono_mb_emit_byte (mb, CEE_RET);
10466 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
10467 ret = mono_mb_create (mb, sig, 4, info);
10474 * mono_marshal_get_gsharedvt_in_wrapper:
10476 * This wrapper handles calls from normal code to gsharedvt code.
10479 mono_marshal_get_gsharedvt_in_wrapper (void)
10481 static MonoMethod* ret = NULL;
10482 MonoMethodSignature *sig;
10483 MonoMethodBuilder *mb;
10489 mb = mono_mb_new (mono_defaults.object_class, "gsharedvt_in", MONO_WRAPPER_UNKNOWN);
10491 sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
10492 sig->ret = &mono_defaults.void_class->byval_arg;
10494 #ifdef HAVE_ONLINE_VES
10496 * The body is generated by the JIT, we use a wrapper instead of a trampoline so EH works.
10498 mono_mb_emit_byte (mb, CEE_RET);
10500 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_GSHAREDVT_IN);
10501 ret = mono_mb_create (mb, sig, 4, info);
10508 * mono_marshal_get_gsharedvt_out_wrapper:
10510 * This wrapper handles calls from gsharedvt code to normal code.
10513 mono_marshal_get_gsharedvt_out_wrapper (void)
10515 static MonoMethod* ret = NULL;
10516 MonoMethodSignature *sig;
10517 MonoMethodBuilder *mb;
10523 mb = mono_mb_new (mono_defaults.object_class, "gsharedvt_out", MONO_WRAPPER_UNKNOWN);
10525 sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
10526 sig->ret = &mono_defaults.void_class->byval_arg;
10528 #ifdef HAVE_ONLINE_VES
10530 * The body is generated by the JIT, we use a wrapper instead of a trampoline so EH works.
10532 mono_mb_emit_byte (mb, CEE_RET);
10534 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_GSHAREDVT_OUT);
10535 ret = mono_mb_create (mb, sig, 4, info);
10544 MonoMethod *method;
10547 /* LOCKING: vars accessed under the marshal lock */
10548 static ArrayElemAddr *elem_addr_cache = NULL;
10549 static int elem_addr_cache_size = 0;
10550 static int elem_addr_cache_next = 0;
10553 * mono_marshal_get_array_address:
10554 * \param rank rank of the array type
10555 * \param elem_size size in bytes of an element of an array.
10557 * Returns a MonoMethod that implements the code to get the address
10558 * of an element in a multi-dimenasional array of \p rank dimensions.
10559 * The returned method takes an array as the first argument and then
10560 * \p rank indexes for the \p rank dimensions.
10561 * If ELEM_SIZE is 0, read the array size from the array object.
10564 mono_marshal_get_array_address (int rank, int elem_size)
10567 MonoMethodBuilder *mb;
10568 MonoMethodSignature *sig;
10571 int i, bounds, ind, realidx;
10572 int branch_pos, *branch_positions;
10576 mono_marshal_lock ();
10577 for (i = 0; i < elem_addr_cache_next; ++i) {
10578 if (elem_addr_cache [i].rank == rank && elem_addr_cache [i].elem_size == elem_size) {
10579 ret = elem_addr_cache [i].method;
10583 mono_marshal_unlock ();
10587 branch_positions = g_new0 (int, rank);
10589 sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1 + rank);
10591 /* void* address (void* array, int idx0, int idx1, int idx2, ...) */
10592 sig->ret = &mono_defaults.int_class->byval_arg;
10593 sig->params [0] = &mono_defaults.object_class->byval_arg;
10594 for (i = 0; i < rank; ++i) {
10595 sig->params [i + 1] = &mono_defaults.int32_class->byval_arg;
10598 name = g_strdup_printf ("ElementAddr_%d", elem_size);
10599 mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_MANAGED);
10602 #ifdef HAVE_ONLINE_VES
10603 bounds = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10604 ind = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
10605 realidx = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
10607 /* bounds = array->bounds; */
10608 mono_mb_emit_ldarg (mb, 0);
10609 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoArray, bounds));
10610 mono_mb_emit_byte (mb, CEE_LDIND_I);
10611 mono_mb_emit_stloc (mb, bounds);
10613 /* ind is the overall element index, realidx is the partial index in a single dimension */
10614 /* ind = idx0 - bounds [0].lower_bound */
10615 mono_mb_emit_ldarg (mb, 1);
10616 mono_mb_emit_ldloc (mb, bounds);
10617 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
10618 mono_mb_emit_byte (mb, CEE_ADD);
10619 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10620 mono_mb_emit_byte (mb, CEE_SUB);
10621 mono_mb_emit_stloc (mb, ind);
10622 /* if (ind >= bounds [0].length) goto exeception; */
10623 mono_mb_emit_ldloc (mb, ind);
10624 mono_mb_emit_ldloc (mb, bounds);
10625 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArrayBounds, length));
10626 mono_mb_emit_byte (mb, CEE_ADD);
10627 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10628 /* note that we use unsigned comparison */
10629 branch_pos = mono_mb_emit_branch (mb, CEE_BGE_UN);
10631 /* For large ranks (> 4?) use a loop n IL later to reduce code size.
10632 * We could also decide to ignore the passed elem_size and get it
10633 * from the array object, to reduce the number of methods we generate:
10634 * the additional cost is 3 memory loads and a non-immediate mul.
10636 for (i = 1; i < rank; ++i) {
10637 /* realidx = idxi - bounds [i].lower_bound */
10638 mono_mb_emit_ldarg (mb, 1 + i);
10639 mono_mb_emit_ldloc (mb, bounds);
10640 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
10641 mono_mb_emit_byte (mb, CEE_ADD);
10642 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10643 mono_mb_emit_byte (mb, CEE_SUB);
10644 mono_mb_emit_stloc (mb, realidx);
10645 /* if (realidx >= bounds [i].length) goto exeception; */
10646 mono_mb_emit_ldloc (mb, realidx);
10647 mono_mb_emit_ldloc (mb, bounds);
10648 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + MONO_STRUCT_OFFSET (MonoArrayBounds, length));
10649 mono_mb_emit_byte (mb, CEE_ADD);
10650 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10651 branch_positions [i] = mono_mb_emit_branch (mb, CEE_BGE_UN);
10652 /* ind = ind * bounds [i].length + realidx */
10653 mono_mb_emit_ldloc (mb, ind);
10654 mono_mb_emit_ldloc (mb, bounds);
10655 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + MONO_STRUCT_OFFSET (MonoArrayBounds, length));
10656 mono_mb_emit_byte (mb, CEE_ADD);
10657 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10658 mono_mb_emit_byte (mb, CEE_MUL);
10659 mono_mb_emit_ldloc (mb, realidx);
10660 mono_mb_emit_byte (mb, CEE_ADD);
10661 mono_mb_emit_stloc (mb, ind);
10664 /* return array->vector + ind * element_size */
10665 mono_mb_emit_ldarg (mb, 0);
10666 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
10667 mono_mb_emit_ldloc (mb, ind);
10669 mono_mb_emit_icon (mb, elem_size);
10671 /* Load arr->vtable->klass->sizes.element_class */
10672 mono_mb_emit_ldarg (mb, 0);
10673 mono_mb_emit_byte (mb, CEE_CONV_I);
10674 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
10675 mono_mb_emit_byte (mb, CEE_ADD);
10676 mono_mb_emit_byte (mb, CEE_LDIND_I);
10677 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
10678 mono_mb_emit_byte (mb, CEE_ADD);
10679 mono_mb_emit_byte (mb, CEE_LDIND_I);
10680 /* sizes is an union, so this reads sizes.element_size */
10681 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoClass, sizes));
10682 mono_mb_emit_byte (mb, CEE_ADD);
10683 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10685 mono_mb_emit_byte (mb, CEE_MUL);
10686 mono_mb_emit_byte (mb, CEE_ADD);
10687 mono_mb_emit_byte (mb, CEE_RET);
10689 /* patch the branches to get here and throw */
10690 for (i = 1; i < rank; ++i) {
10691 mono_mb_patch_branch (mb, branch_positions [i]);
10693 mono_mb_patch_branch (mb, branch_pos);
10694 /* throw exception */
10695 mono_mb_emit_exception (mb, "IndexOutOfRangeException", NULL);
10697 g_free (branch_positions);
10698 #endif /* HAVE_ONLINE_VES */
10700 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ELEMENT_ADDR);
10701 info->d.element_addr.rank = rank;
10702 info->d.element_addr.elem_size = elem_size;
10703 ret = mono_mb_create (mb, sig, 4, info);
10706 /* cache the result */
10708 mono_marshal_lock ();
10709 for (i = 0; i < elem_addr_cache_next; ++i) {
10710 if (elem_addr_cache [i].rank == rank && elem_addr_cache [i].elem_size == elem_size) {
10711 /* FIXME: free ret */
10712 ret = elem_addr_cache [i].method;
10718 if (elem_addr_cache_next >= elem_addr_cache_size) {
10719 int new_size = elem_addr_cache_size + 4;
10720 ArrayElemAddr *new_array = g_new0 (ArrayElemAddr, new_size);
10721 memcpy (new_array, elem_addr_cache, elem_addr_cache_size * sizeof (ArrayElemAddr));
10722 g_free (elem_addr_cache);
10723 elem_addr_cache = new_array;
10724 elem_addr_cache_size = new_size;
10726 elem_addr_cache [elem_addr_cache_next].rank = rank;
10727 elem_addr_cache [elem_addr_cache_next].elem_size = elem_size;
10728 elem_addr_cache [elem_addr_cache_next].method = ret;
10729 elem_addr_cache_next ++;
10731 mono_marshal_unlock ();
10736 * mono_marshal_get_array_accessor_wrapper:
10738 * Return a wrapper which just calls METHOD, which should be an Array Get/Set/Address method.
10741 mono_marshal_get_array_accessor_wrapper (MonoMethod *method)
10743 MonoMethodSignature *sig;
10744 MonoMethodBuilder *mb;
10748 MonoGenericContext *ctx = NULL;
10749 MonoMethod *orig_method = NULL;
10750 MonoGenericContainer *container = NULL;
10754 * These wrappers are needed to avoid the JIT replacing the calls to these methods with intrinsics
10755 * inside runtime invoke wrappers, thereby making the wrappers not unshareable.
10756 * FIXME: Use generic methods.
10763 g_assert_not_reached ();
10765 cache = get_cache (&method->klass->image->array_accessor_cache, mono_aligned_addr_hash, NULL);
10766 if ((res = mono_marshal_find_in_cache (cache, method)))
10770 sig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
10773 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNKNOWN);
10775 #ifdef HAVE_ONLINE_VES
10776 /* Call the method */
10778 mono_mb_emit_ldarg (mb, 0);
10779 for (i = 0; i < sig->param_count; i++)
10780 mono_mb_emit_ldarg (mb, i + (sig->hasthis == TRUE));
10784 mono_mb_emit_managed_call (mb, mono_class_inflate_generic_method_checked (method, &container->context, &error), NULL);
10785 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
10787 mono_mb_emit_managed_call (mb, method, NULL);
10789 mono_mb_emit_byte (mb, CEE_RET);
10792 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ARRAY_ACCESSOR);
10793 info->d.array_accessor.method = method;
10797 def = mono_mb_create_and_cache_full (cache, method, mb, sig, sig->param_count + 16, info, NULL);
10798 res = cache_generic_wrapper (cache, orig_method, def, ctx, orig_method);
10800 res = mono_mb_create_and_cache_full (cache, method,
10801 mb, sig, sig->param_count + 16,
10810 static inline void*
10811 mono_marshal_alloc_co_task_mem (size_t size)
10813 if ((gulong)size == 0)
10814 /* This returns a valid pointer for size 0 on MS.NET */
10817 return g_try_malloc ((gulong)size);
10822 * mono_marshal_alloc:
10825 mono_marshal_alloc (gsize size, MonoError *error)
10829 error_init (error);
10831 res = mono_marshal_alloc_co_task_mem (size);
10833 mono_error_set_out_of_memory (error, "Could not allocate %lu bytes", size);
10838 /* This is a JIT icall, it sets the pending exception and returns NULL on error. */
10840 ves_icall_marshal_alloc (gsize size)
10843 void *ret = mono_marshal_alloc (size, &error);
10844 if (!mono_error_ok (&error)) {
10845 mono_error_set_pending_exception (&error);
10854 mono_marshal_free_co_task_mem (void *ptr)
10862 * mono_marshal_free:
10865 mono_marshal_free (gpointer ptr)
10867 mono_marshal_free_co_task_mem (ptr);
10871 * mono_marshal_free_array:
10874 mono_marshal_free_array (gpointer *ptr, int size)
10881 for (i = 0; i < size; i++)
10887 mono_marshal_string_to_utf16 (MonoString *s)
10889 return s ? mono_string_chars (s) : NULL;
10892 /* This is a JIT icall, it sets the pending exception and returns NULL on error. */
10894 mono_marshal_string_to_utf16_copy (MonoString *s)
10900 gunichar2 *res = (gunichar2 *)mono_marshal_alloc ((mono_string_length (s) * 2) + 2, &error);
10901 if (!mono_error_ok (&error)) {
10902 mono_error_set_pending_exception (&error);
10905 memcpy (res, mono_string_chars (s), mono_string_length (s) * 2);
10906 res [mono_string_length (s)] = 0;
10912 * mono_marshal_set_last_error:
10914 * This function is invoked to set the last error value from a P/Invoke call
10915 * which has \c SetLastError set.
10918 mono_marshal_set_last_error (void)
10921 mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (GetLastError ()));
10923 mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (errno));
10928 mono_marshal_set_last_error_windows (int error)
10931 mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (error));
10936 ves_icall_System_Runtime_InteropServices_Marshal_copy_to_unmanaged (MonoArray *src, gint32 start_index,
10937 gpointer dest, gint32 length)
10942 MONO_CHECK_ARG_NULL (src,);
10943 MONO_CHECK_ARG_NULL (dest,);
10945 if (src->obj.vtable->klass->rank != 1) {
10946 mono_set_pending_exception (mono_get_exception_argument ("array", "array is multi-dimensional"));
10949 if (start_index < 0) {
10950 mono_set_pending_exception (mono_get_exception_argument ("startIndex", "Must be >= 0"));
10954 mono_set_pending_exception (mono_get_exception_argument ("length", "Must be >= 0"));
10957 if (start_index + length > mono_array_length (src)) {
10958 mono_set_pending_exception (mono_get_exception_argument ("length", "start_index + length > array length"));
10962 element_size = mono_array_element_size (src->obj.vtable->klass);
10964 /* no references should be involved */
10965 source_addr = mono_array_addr_with_size_fast (src, element_size, start_index);
10967 memcpy (dest, source_addr, length * element_size);
10971 ves_icall_System_Runtime_InteropServices_Marshal_copy_from_unmanaged (gpointer src, gint32 start_index,
10972 MonoArray *dest, gint32 length)
10977 MONO_CHECK_ARG_NULL (src,);
10978 MONO_CHECK_ARG_NULL (dest,);
10980 if (dest->obj.vtable->klass->rank != 1) {
10981 mono_set_pending_exception (mono_get_exception_argument ("array", "array is multi-dimensional"));
10984 if (start_index < 0) {
10985 mono_set_pending_exception (mono_get_exception_argument ("startIndex", "Must be >= 0"));
10989 mono_set_pending_exception (mono_get_exception_argument ("length", "Must be >= 0"));
10992 if (start_index + length > mono_array_length (dest)) {
10993 mono_set_pending_exception (mono_get_exception_argument ("length", "start_index + length > array length"));
10996 element_size = mono_array_element_size (dest->obj.vtable->klass);
10998 /* no references should be involved */
10999 dest_addr = mono_array_addr_with_size_fast (dest, element_size, start_index);
11001 memcpy (dest_addr, src, length * element_size);
11005 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi (char *ptr, MonoError *error)
11007 error_init (error);
11009 return MONO_HANDLE_CAST (MonoString, NULL_HANDLE);
11011 return mono_string_new_handle (mono_domain_get (), ptr, error);
11015 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi_len (char *ptr, gint32 len)
11018 MonoString *result = NULL;
11019 error_init (&error);
11021 mono_error_set_argument_null (&error, "ptr", "");
11023 result = mono_string_new_len_checked (mono_domain_get (), ptr, len, &error);
11024 mono_error_set_pending_exception (&error);
11029 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni (guint16 *ptr)
11032 MonoString *res = NULL;
11033 MonoDomain *domain = mono_domain_get ();
11043 res = mono_string_new_utf16_checked (domain, ptr, len, &error);
11044 if (!mono_error_ok (&error)) {
11045 mono_error_set_pending_exception (&error);
11052 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni_len (guint16 *ptr, gint32 len)
11055 MonoString *res = NULL;
11056 MonoDomain *domain = mono_domain_get ();
11058 error_init (&error);
11062 mono_error_set_argument_null (&error, "ptr", "");
11064 res = mono_string_new_utf16_checked (domain, ptr, len, &error);
11067 if (!mono_error_ok (&error))
11068 mono_error_set_pending_exception (&error);
11073 ves_icall_System_Runtime_InteropServices_Marshal_GetLastWin32Error (void)
11075 return (GPOINTER_TO_INT (mono_native_tls_get_value (last_error_tls_id)));
11079 ves_icall_System_Runtime_InteropServices_Marshal_SizeOf (MonoReflectionTypeHandle rtype, MonoError *error)
11085 error_init (error);
11087 if (MONO_HANDLE_IS_NULL (rtype)) {
11088 mono_error_set_argument_null (error, "type", "");
11092 type = MONO_HANDLE_GETVAL (rtype, type);
11093 klass = mono_class_from_mono_type (type);
11094 if (!mono_class_init (klass)) {
11095 mono_error_set_for_class_failure (error, klass);
11099 layout = (mono_class_get_flags (klass) & TYPE_ATTRIBUTE_LAYOUT_MASK);
11101 if (type->type == MONO_TYPE_PTR || type->type == MONO_TYPE_FNPTR) {
11102 return sizeof (gpointer);
11103 } else if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
11104 mono_error_set_argument (error, "t", "Type %s cannot be marshaled as an unmanaged structure.", klass->name);
11108 return mono_class_native_size (klass, NULL);
11112 ves_icall_System_Runtime_InteropServices_Marshal_StructureToPtr (MonoObject *obj, gpointer dst, MonoBoolean delete_old)
11115 MonoMethod *method;
11118 MONO_CHECK_ARG_NULL (obj,);
11119 MONO_CHECK_ARG_NULL (dst,);
11121 method = mono_marshal_get_struct_to_ptr (obj->vtable->klass);
11125 pa [2] = &delete_old;
11127 mono_runtime_invoke_checked (method, NULL, pa, &error);
11128 if (!mono_error_ok (&error))
11129 mono_error_set_pending_exception (&error);
11133 ptr_to_structure (gpointer src, MonoObject *dst, MonoError *error)
11135 MonoMethod *method;
11138 error_init (error);
11140 method = mono_marshal_get_ptr_to_struct (dst->vtable->klass);
11145 mono_runtime_invoke_checked (method, NULL, pa, error);
11149 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure (gpointer src, MonoObject *dst)
11154 MONO_CHECK_ARG_NULL (src,);
11155 MONO_CHECK_ARG_NULL (dst,);
11157 t = mono_type_get_underlying_type (mono_class_get_type (dst->vtable->klass));
11159 if (t->type == MONO_TYPE_VALUETYPE) {
11160 MonoException *exc;
11163 tmp = g_strdup_printf ("Destination is a boxed value type.");
11164 exc = mono_get_exception_argument ("dst", tmp);
11167 mono_set_pending_exception (exc);
11171 ptr_to_structure (src, dst, &error);
11172 if (!mono_error_ok (&error))
11173 mono_error_set_pending_exception (&error);
11177 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure_type (gpointer src, MonoReflectionType *type)
11181 MonoDomain *domain = mono_domain_get ();
11186 MONO_CHECK_ARG_NULL (type, NULL);
11188 klass = mono_class_from_mono_type (type->type);
11189 if (!mono_class_init (klass)) {
11190 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
11194 res = mono_object_new_checked (domain, klass, &error);
11195 if (!mono_error_ok (&error)) {
11196 mono_error_set_pending_exception (&error);
11200 ptr_to_structure (src, res, &error);
11201 if (!mono_error_ok (&error)) {
11202 mono_error_set_pending_exception (&error);
11210 ves_icall_System_Runtime_InteropServices_Marshal_OffsetOf (MonoReflectionTypeHandle ref_type, MonoStringHandle field_name, MonoError *error)
11212 error_init (error);
11213 if (MONO_HANDLE_IS_NULL (ref_type)) {
11214 mono_error_set_argument_null (error, "type", "");
11217 if (MONO_HANDLE_IS_NULL (field_name)) {
11218 mono_error_set_argument_null (error, "fieldName", "");
11222 char *fname = mono_string_handle_to_utf8 (field_name, error);
11223 return_val_if_nok (error, 0);
11225 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
11226 MonoClass *klass = mono_class_from_mono_type (type);
11227 if (!mono_class_init (klass)) {
11228 mono_error_set_for_class_failure (error, klass);
11232 int match_index = -1;
11233 while (klass && match_index == -1) {
11234 MonoClassField* field;
11236 gpointer iter = NULL;
11237 while ((field = mono_class_get_fields (klass, &iter))) {
11238 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
11240 if (!strcmp (fname, mono_field_get_name (field))) {
11247 if (match_index == -1)
11248 klass = klass->parent;
11253 if(match_index == -1) {
11254 /* Get back original class instance */
11255 klass = mono_class_from_mono_type (type);
11257 mono_error_set_argument (error, "fieldName", "Field passed in is not a marshaled member of the type %s", klass->name);
11261 MonoMarshalType *info = mono_marshal_load_type_info (klass);
11262 return info->fields [match_index].offset;
11267 ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalAnsi (MonoString *string)
11270 char *ret = mono_string_to_utf8_checked (string, &error);
11271 mono_error_set_pending_exception (&error);
11276 ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalUni (MonoString *string)
11278 if (string == NULL)
11281 gunichar2 *res = (gunichar2 *)g_malloc ((mono_string_length (string) + 1) * 2);
11283 memcpy (res, mono_string_chars (string), mono_string_length (string) * 2);
11284 res [mono_string_length (string)] = 0;
11288 #endif /* !HOST_WIN32 */
11291 mono_struct_delete_old (MonoClass *klass, char *ptr)
11293 MonoMarshalType *info;
11296 info = mono_marshal_load_type_info (klass);
11298 for (i = 0; i < info->num_fields; i++) {
11299 MonoMarshalConv conv;
11300 MonoType *ftype = info->fields [i].field->type;
11303 if (ftype->attrs & FIELD_ATTRIBUTE_STATIC)
11306 mono_type_to_unmanaged (ftype, info->fields [i].mspec, TRUE,
11307 klass->unicode, &conv);
11309 cpos = ptr + info->fields [i].offset;
11312 case MONO_MARSHAL_CONV_NONE:
11313 if (MONO_TYPE_ISSTRUCT (ftype)) {
11314 mono_struct_delete_old (ftype->data.klass, cpos);
11318 case MONO_MARSHAL_CONV_STR_LPWSTR:
11319 /* We assume this field points inside a MonoString */
11321 case MONO_MARSHAL_CONV_STR_LPTSTR:
11322 #ifdef TARGET_WIN32
11323 /* We assume this field points inside a MonoString
11327 case MONO_MARSHAL_CONV_STR_LPSTR:
11328 case MONO_MARSHAL_CONV_STR_BSTR:
11329 case MONO_MARSHAL_CONV_STR_ANSIBSTR:
11330 case MONO_MARSHAL_CONV_STR_TBSTR:
11331 case MONO_MARSHAL_CONV_STR_UTF8STR:
11332 mono_marshal_free (*(gpointer *)cpos);
11342 ves_icall_System_Runtime_InteropServices_Marshal_DestroyStructure (gpointer src, MonoReflectionType *type)
11346 MONO_CHECK_ARG_NULL (src,);
11347 MONO_CHECK_ARG_NULL (type,);
11349 klass = mono_class_from_mono_type (type->type);
11350 if (!mono_class_init (klass)) {
11351 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
11355 mono_struct_delete_old (klass, (char *)src);
11359 static inline void *
11360 mono_marshal_alloc_hglobal (size_t size)
11362 return g_try_malloc (size);
11367 ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (gpointer size)
11370 size_t s = (size_t)size;
11373 /* This returns a valid pointer for size 0 on MS.NET */
11376 res = mono_marshal_alloc_hglobal (s);
11379 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11387 static inline gpointer
11388 mono_marshal_realloc_hglobal (gpointer ptr, size_t size)
11390 return g_try_realloc (ptr, size);
11395 ves_icall_System_Runtime_InteropServices_Marshal_ReAllocHGlobal (gpointer ptr, gpointer size)
11398 size_t s = (size_t)size;
11401 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11405 res = mono_marshal_realloc_hglobal (ptr, s);
11408 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11417 mono_marshal_free_hglobal (gpointer ptr)
11425 ves_icall_System_Runtime_InteropServices_Marshal_FreeHGlobal (void *ptr)
11427 mono_marshal_free_hglobal (ptr);
11431 ves_icall_System_Runtime_InteropServices_Marshal_AllocCoTaskMem (int size)
11433 void *res = mono_marshal_alloc_co_task_mem (size);
11436 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11443 ves_icall_System_Runtime_InteropServices_Marshal_AllocCoTaskMemSize (gulong size)
11445 void *res = mono_marshal_alloc_co_task_mem (size);
11448 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11455 ves_icall_System_Runtime_InteropServices_Marshal_FreeCoTaskMem (void *ptr)
11457 mono_marshal_free_co_task_mem (ptr);
11462 static inline gpointer
11463 mono_marshal_realloc_co_task_mem (gpointer ptr, size_t size)
11465 return g_try_realloc (ptr, (gulong)size);
11470 ves_icall_System_Runtime_InteropServices_Marshal_ReAllocCoTaskMem (gpointer ptr, int size)
11472 void *res = mono_marshal_realloc_co_task_mem (ptr, size);
11475 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11482 ves_icall_System_Runtime_InteropServices_Marshal_UnsafeAddrOfPinnedArrayElement (MonoArray *arrayobj, int index)
11484 return mono_array_addr_with_size_fast (arrayobj, mono_array_element_size (arrayobj->obj.vtable->klass), index);
11488 ves_icall_System_Runtime_InteropServices_Marshal_GetDelegateForFunctionPointerInternal (void *ftn, MonoReflectionTypeHandle type, MonoError *error)
11490 error_init (error);
11491 MonoClass *klass = mono_type_get_class (MONO_HANDLE_GETVAL (type, type));
11492 if (!mono_class_init (klass)) {
11493 mono_error_set_for_class_failure (error, klass);
11497 return mono_ftnptr_to_delegate_handle (klass, ftn, error);
11501 ves_icall_System_Runtime_InteropServices_Marshal_GetFunctionPointerForDelegateInternal (MonoDelegateHandle delegate, MonoError *error)
11503 error_init (error);
11504 return mono_delegate_handle_to_ftnptr (delegate, error);
11508 * mono_marshal_is_loading_type_info:
11510 * Return whenever mono_marshal_load_type_info () is being executed for KLASS by this
11514 mono_marshal_is_loading_type_info (MonoClass *klass)
11516 GSList *loads_list = (GSList *)mono_native_tls_get_value (load_type_info_tls_id);
11518 return g_slist_find (loads_list, klass) != NULL;
11522 * mono_marshal_load_type_info:
11524 * Initialize \c klass::marshal_info using information from metadata. This function can
11525 * recursively call itself, and the caller is responsible to avoid that by calling
11526 * \c mono_marshal_is_loading_type_info beforehand.
11528 * LOCKING: Acquires the loader lock.
11531 mono_marshal_load_type_info (MonoClass* klass)
11534 guint32 native_size = 0, min_align = 1, packing;
11535 MonoMarshalType *info;
11536 MonoClassField* field;
11539 GSList *loads_list;
11541 g_assert (klass != NULL);
11543 info = mono_class_get_marshal_info (klass);
11547 if (!klass->inited)
11548 mono_class_init (klass);
11550 info = mono_class_get_marshal_info (klass);
11555 * This function can recursively call itself, so we keep the list of classes which are
11556 * under initialization in a TLS list.
11558 g_assert (!mono_marshal_is_loading_type_info (klass));
11559 loads_list = (GSList *)mono_native_tls_get_value (load_type_info_tls_id);
11560 loads_list = g_slist_prepend (loads_list, klass);
11561 mono_native_tls_set_value (load_type_info_tls_id, loads_list);
11564 while ((field = mono_class_get_fields (klass, &iter))) {
11565 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
11567 if (mono_field_is_deleted (field))
11572 layout = mono_class_get_flags (klass) & TYPE_ATTRIBUTE_LAYOUT_MASK;
11574 /* The mempool is protected by the loader lock */
11575 info = (MonoMarshalType *)mono_image_alloc0 (klass->image, MONO_SIZEOF_MARSHAL_TYPE + sizeof (MonoMarshalField) * count);
11576 info->num_fields = count;
11578 /* Try to find a size for this type in metadata */
11579 mono_metadata_packing_from_typedef (klass->image, klass->type_token, NULL, &native_size);
11581 if (klass->parent) {
11582 int parent_size = mono_class_native_size (klass->parent, NULL);
11584 /* Add parent size to real size */
11585 native_size += parent_size;
11586 info->native_size = parent_size;
11589 packing = klass->packing_size ? klass->packing_size : 8;
11592 while ((field = mono_class_get_fields (klass, &iter))) {
11596 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
11599 if (mono_field_is_deleted (field))
11601 if (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL)
11602 mono_metadata_field_info_with_mempool (klass->image, mono_metadata_token_index (mono_class_get_field_token (field)) - 1,
11603 NULL, NULL, &info->fields [j].mspec);
11605 info->fields [j].field = field;
11607 if ((mono_class_num_fields (klass) == 1) && (klass->instance_size == sizeof (MonoObject)) &&
11608 (strcmp (mono_field_get_name (field), "$PRIVATE$") == 0)) {
11609 /* This field is a hack inserted by MCS to empty structures */
11614 case TYPE_ATTRIBUTE_AUTO_LAYOUT:
11615 case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
11616 size = mono_marshal_type_size (field->type, info->fields [j].mspec,
11617 &align, TRUE, klass->unicode);
11618 align = klass->packing_size ? MIN (klass->packing_size, align): align;
11619 min_align = MAX (align, min_align);
11620 info->fields [j].offset = info->native_size;
11621 info->fields [j].offset += align - 1;
11622 info->fields [j].offset &= ~(align - 1);
11623 info->native_size = info->fields [j].offset + size;
11625 case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
11626 size = mono_marshal_type_size (field->type, info->fields [j].mspec,
11627 &align, TRUE, klass->unicode);
11628 min_align = MAX (align, min_align);
11629 info->fields [j].offset = field->offset - sizeof (MonoObject);
11630 info->native_size = MAX (info->native_size, info->fields [j].offset + size);
11636 if (klass->byval_arg.type == MONO_TYPE_PTR)
11637 info->native_size = sizeof (gpointer);
11639 if (layout != TYPE_ATTRIBUTE_AUTO_LAYOUT) {
11640 info->native_size = MAX (native_size, info->native_size);
11642 * If the provided Size is equal or larger than the calculated size, and there
11643 * was no Pack attribute, we set min_align to 1 to avoid native_size being increased
11645 if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
11646 if (native_size && native_size == info->native_size && klass->packing_size == 0)
11649 min_align = MIN (min_align, packing);
11653 if (info->native_size & (min_align - 1)) {
11654 info->native_size += min_align - 1;
11655 info->native_size &= ~(min_align - 1);
11658 info->min_align = min_align;
11660 /* Update the class's blittable info, if the layouts don't match */
11661 if (info->native_size != mono_class_value_size (klass, NULL))
11662 klass->blittable = FALSE;
11664 /* If this is an array type, ensure that we have element info */
11665 if (klass->rank && !mono_marshal_is_loading_type_info (klass->element_class)) {
11666 mono_marshal_load_type_info (klass->element_class);
11669 loads_list = (GSList *)mono_native_tls_get_value (load_type_info_tls_id);
11670 loads_list = g_slist_remove (loads_list, klass);
11671 mono_native_tls_set_value (load_type_info_tls_id, loads_list);
11673 mono_marshal_lock ();
11674 MonoMarshalType *info2 = mono_class_get_marshal_info (klass);
11676 /*We do double-checking locking on marshal_info */
11677 mono_memory_barrier ();
11678 mono_class_set_marshal_info (klass, info);
11679 ++class_marshal_info_count;
11682 mono_marshal_unlock ();
11688 * mono_class_native_size:
11689 * \param klass a class
11690 * \returns the native size of an object instance (when marshaled
11691 * to unmanaged code)
11694 mono_class_native_size (MonoClass *klass, guint32 *align)
11696 MonoMarshalType *info = mono_class_get_marshal_info (klass);
11698 if (mono_marshal_is_loading_type_info (klass)) {
11703 mono_marshal_load_type_info (klass);
11705 info = mono_class_get_marshal_info (klass);
11709 *align = info->min_align;
11711 return info->native_size;
11715 * mono_type_native_stack_size:
11716 * @t: the type to return the size it uses on the stack
11718 * Returns: the number of bytes required to hold an instance of this
11719 * type on the native stack
11722 mono_type_native_stack_size (MonoType *t, guint32 *align)
11726 g_assert (t != NULL);
11732 *align = sizeof (gpointer);
11733 return sizeof (gpointer);
11737 case MONO_TYPE_BOOLEAN:
11738 case MONO_TYPE_CHAR:
11749 case MONO_TYPE_STRING:
11750 case MONO_TYPE_OBJECT:
11751 case MONO_TYPE_CLASS:
11752 case MONO_TYPE_SZARRAY:
11753 case MONO_TYPE_PTR:
11754 case MONO_TYPE_FNPTR:
11755 case MONO_TYPE_ARRAY:
11756 *align = sizeof (gpointer);
11757 return sizeof (gpointer);
11762 *align = MONO_ABI_ALIGNOF (double);
11766 *align = MONO_ABI_ALIGNOF (gint64);
11768 case MONO_TYPE_GENERICINST:
11769 if (!mono_type_generic_inst_is_valuetype (t)) {
11770 *align = sizeof (gpointer);
11771 return sizeof (gpointer);
11774 case MONO_TYPE_TYPEDBYREF:
11775 case MONO_TYPE_VALUETYPE: {
11777 MonoClass *klass = mono_class_from_mono_type (t);
11779 if (klass->enumtype)
11780 return mono_type_native_stack_size (mono_class_enum_basetype (klass), align);
11782 size = mono_class_native_size (klass, align);
11783 *align = *align + 3;
11793 g_error ("type 0x%02x unknown", t->type);
11799 * mono_marshal_type_size:
11802 mono_marshal_type_size (MonoType *type, MonoMarshalSpec *mspec, guint32 *align,
11803 gboolean as_field, gboolean unicode)
11805 MonoMarshalNative native_type = mono_type_to_unmanaged (type, mspec, as_field, unicode, NULL);
11808 switch (native_type) {
11809 case MONO_NATIVE_BOOLEAN:
11812 case MONO_NATIVE_I1:
11813 case MONO_NATIVE_U1:
11816 case MONO_NATIVE_I2:
11817 case MONO_NATIVE_U2:
11818 case MONO_NATIVE_VARIANTBOOL:
11821 case MONO_NATIVE_I4:
11822 case MONO_NATIVE_U4:
11823 case MONO_NATIVE_ERROR:
11826 case MONO_NATIVE_I8:
11827 case MONO_NATIVE_U8:
11828 *align = MONO_ABI_ALIGNOF (gint64);
11830 case MONO_NATIVE_R4:
11833 case MONO_NATIVE_R8:
11834 *align = MONO_ABI_ALIGNOF (double);
11836 case MONO_NATIVE_INT:
11837 case MONO_NATIVE_UINT:
11838 case MONO_NATIVE_LPSTR:
11839 case MONO_NATIVE_LPWSTR:
11840 case MONO_NATIVE_LPTSTR:
11841 case MONO_NATIVE_BSTR:
11842 case MONO_NATIVE_ANSIBSTR:
11843 case MONO_NATIVE_TBSTR:
11844 case MONO_NATIVE_UTF8STR:
11845 case MONO_NATIVE_LPARRAY:
11846 case MONO_NATIVE_SAFEARRAY:
11847 case MONO_NATIVE_IUNKNOWN:
11848 case MONO_NATIVE_IDISPATCH:
11849 case MONO_NATIVE_INTERFACE:
11850 case MONO_NATIVE_ASANY:
11851 case MONO_NATIVE_FUNC:
11852 case MONO_NATIVE_LPSTRUCT:
11853 *align = MONO_ABI_ALIGNOF (gpointer);
11854 return sizeof (gpointer);
11855 case MONO_NATIVE_STRUCT:
11856 klass = mono_class_from_mono_type (type);
11857 if (klass == mono_defaults.object_class &&
11858 (mspec && mspec->native == MONO_NATIVE_STRUCT)) {
11862 return mono_class_native_size (klass, align);
11863 case MONO_NATIVE_BYVALTSTR: {
11864 int esize = unicode ? 2: 1;
11867 return mspec->data.array_data.num_elem * esize;
11869 case MONO_NATIVE_BYVALARRAY: {
11870 // FIXME: Have to consider ArraySubType
11872 klass = mono_class_from_mono_type (type);
11873 if (klass->element_class == mono_defaults.char_class) {
11874 esize = unicode ? 2 : 1;
11877 esize = mono_class_native_size (klass->element_class, align);
11880 return mspec->data.array_data.num_elem * esize;
11882 case MONO_NATIVE_CUSTOM:
11883 *align = sizeof (gpointer);
11884 return sizeof (gpointer);
11886 case MONO_NATIVE_CURRENCY:
11887 case MONO_NATIVE_VBBYREFSTR:
11889 g_error ("native type %02x not implemented", native_type);
11892 g_assert_not_reached ();
11897 * mono_marshal_asany:
11898 * This is a JIT icall, it sets the pending exception and returns NULL on error.
11901 mono_marshal_asany (MonoObject *o, MonoMarshalNative string_encoding, int param_attrs)
11910 t = &o->vtable->klass->byval_arg;
11914 case MONO_TYPE_PTR:
11917 case MONO_TYPE_BOOLEAN:
11920 case MONO_TYPE_CHAR:
11925 return mono_object_unbox (o);
11927 case MONO_TYPE_STRING:
11928 switch (string_encoding) {
11929 case MONO_NATIVE_LPWSTR:
11930 return mono_marshal_string_to_utf16_copy ((MonoString*)o);
11931 case MONO_NATIVE_LPSTR:
11932 case MONO_NATIVE_UTF8STR:
11933 // Same code path, because in Mono, we treated strings as Utf8
11934 return mono_string_to_utf8str ((MonoString*)o);
11936 g_warning ("marshaling conversion %d not implemented", string_encoding);
11937 g_assert_not_reached ();
11940 case MONO_TYPE_CLASS:
11941 case MONO_TYPE_VALUETYPE: {
11942 MonoMethod *method;
11945 MonoBoolean delete_old = FALSE;
11947 klass = t->data.klass;
11949 if (mono_class_is_auto_layout (klass))
11952 if (klass->valuetype && (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype))
11953 return mono_object_unbox (o);
11955 res = mono_marshal_alloc (mono_class_native_size (klass, NULL), &error);
11956 if (!mono_error_ok (&error)) {
11957 mono_error_set_pending_exception (&error);
11961 if (!((param_attrs & PARAM_ATTRIBUTE_OUT) && !(param_attrs & PARAM_ATTRIBUTE_IN))) {
11962 method = mono_marshal_get_struct_to_ptr (o->vtable->klass);
11966 pa [2] = &delete_old;
11968 mono_runtime_invoke_checked (method, NULL, pa, &error);
11969 if (!mono_error_ok (&error)) {
11970 mono_error_set_pending_exception (&error);
11980 mono_set_pending_exception (mono_get_exception_argument ("", "No PInvoke conversion exists for value passed to Object-typed parameter."));
11985 * mono_marshal_free_asany:
11986 * This is a JIT icall, it sets the pending exception
11989 mono_marshal_free_asany (MonoObject *o, gpointer ptr, MonoMarshalNative string_encoding, int param_attrs)
11998 t = &o->vtable->klass->byval_arg;
12000 case MONO_TYPE_STRING:
12001 switch (string_encoding) {
12002 case MONO_NATIVE_LPWSTR:
12003 case MONO_NATIVE_LPSTR:
12004 case MONO_NATIVE_UTF8STR:
12005 mono_marshal_free (ptr);
12008 g_warning ("marshaling conversion %d not implemented", string_encoding);
12009 g_assert_not_reached ();
12012 case MONO_TYPE_CLASS:
12013 case MONO_TYPE_VALUETYPE: {
12014 klass = t->data.klass;
12016 if (klass->valuetype && (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype))
12019 if (param_attrs & PARAM_ATTRIBUTE_OUT) {
12020 MonoMethod *method = mono_marshal_get_ptr_to_struct (o->vtable->klass);
12026 mono_runtime_invoke_checked (method, NULL, pa, &error);
12027 if (!mono_error_ok (&error)) {
12028 mono_error_set_pending_exception (&error);
12033 if (!((param_attrs & PARAM_ATTRIBUTE_OUT) && !(param_attrs & PARAM_ATTRIBUTE_IN))) {
12034 mono_struct_delete_old (klass, (char *)ptr);
12037 mono_marshal_free (ptr);
12046 * mono_marshal_get_generic_array_helper:
12048 * Return a wrapper which is used to implement the implicit interfaces on arrays.
12049 * The wrapper routes calls to METHOD, which is one of the InternalArray_ methods in Array.
12052 mono_marshal_get_generic_array_helper (MonoClass *klass, gchar *name, MonoMethod *method)
12054 MonoMethodSignature *sig, *csig;
12055 MonoMethodBuilder *mb;
12060 mb = mono_mb_new_no_dup_name (klass, name, MONO_WRAPPER_MANAGED_TO_MANAGED);
12061 mb->method->slot = -1;
12063 mb->method->flags = METHOD_ATTRIBUTE_PRIVATE | METHOD_ATTRIBUTE_VIRTUAL |
12064 METHOD_ATTRIBUTE_NEW_SLOT | METHOD_ATTRIBUTE_HIDE_BY_SIG | METHOD_ATTRIBUTE_FINAL;
12066 sig = mono_method_signature (method);
12067 csig = mono_metadata_signature_dup_full (method->klass->image, sig);
12068 csig->generic_param_count = 0;
12070 #ifdef HAVE_ONLINE_VES
12071 mono_mb_emit_ldarg (mb, 0);
12072 for (i = 0; i < csig->param_count; i++)
12073 mono_mb_emit_ldarg (mb, i + 1);
12074 mono_mb_emit_managed_call (mb, method, NULL);
12075 mono_mb_emit_byte (mb, CEE_RET);
12077 /* We can corlib internal methods */
12078 mb->skip_visibility = TRUE;
12080 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER);
12081 info->d.generic_array_helper.method = method;
12082 res = mono_mb_create (mb, csig, csig->param_count + 16, info);
12090 * The mono_win32_compat_* functions are implementations of inline
12091 * Windows kernel32 APIs, which are DllImport-able under MS.NET,
12092 * although not exported by kernel32.
12094 * We map the appropiate kernel32 entries to these functions using
12095 * dllmaps declared in the global etc/mono/config.
12099 mono_win32_compat_CopyMemory (gpointer dest, gconstpointer source, gsize length)
12101 if (!dest || !source)
12104 memcpy (dest, source, length);
12108 mono_win32_compat_FillMemory (gpointer dest, gsize length, guchar fill)
12110 memset (dest, fill, length);
12114 mono_win32_compat_MoveMemory (gpointer dest, gconstpointer source, gsize length)
12116 if (!dest || !source)
12119 memmove (dest, source, length);
12123 mono_win32_compat_ZeroMemory (gpointer dest, gsize length)
12125 memset (dest, 0, length);
12129 mono_marshal_find_nonzero_bit_offset (guint8 *buf, int len, int *byte_offset, guint8 *bitmask)
12134 for (i = 0; i < len; ++i)
12138 g_assert (i < len);
12141 while (byte && !(byte & 1))
12143 g_assert (byte == 1);
12146 *bitmask = buf [i];
12150 mono_marshal_get_thunk_invoke_wrapper (MonoMethod *method)
12152 MonoMethodBuilder *mb;
12153 MonoMethodSignature *sig, *csig;
12154 MonoExceptionClause *clause;
12159 int i, param_count, sig_size, pos_leave;
12163 // FIXME: we need to store the exception into a MonoHandle
12164 g_assert (!mono_threads_is_coop_enabled ());
12166 klass = method->klass;
12167 image = method->klass->image;
12169 cache = get_cache (&mono_method_get_wrapper_cache (method)->thunk_invoke_cache, mono_aligned_addr_hash, NULL);
12171 if ((res = mono_marshal_find_in_cache (cache, method)))
12174 sig = mono_method_signature (method);
12175 mb = mono_mb_new (klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
12177 /* add "this" and exception param */
12178 param_count = sig->param_count + sig->hasthis + 1;
12180 /* dup & extend signature */
12181 csig = mono_metadata_signature_alloc (image, param_count);
12182 sig_size = MONO_SIZEOF_METHOD_SIGNATURE + sig->param_count * sizeof (MonoType *);
12183 memcpy (csig, sig, sig_size);
12184 csig->param_count = param_count;
12187 csig->call_convention = MONO_CALL_DEFAULT;
12189 if (sig->hasthis) {
12191 csig->params [0] = &klass->byval_arg;
12192 /* move params up by one */
12193 for (i = 0; i < sig->param_count; i++)
12194 csig->params [i + 1] = sig->params [i];
12197 /* setup exception param as byref+[out] */
12198 csig->params [param_count - 1] = mono_metadata_type_dup (image,
12199 &mono_defaults.exception_class->byval_arg);
12200 csig->params [param_count - 1]->byref = 1;
12201 csig->params [param_count - 1]->attrs = PARAM_ATTRIBUTE_OUT;
12203 /* convert struct return to object */
12204 if (MONO_TYPE_ISSTRUCT (sig->ret))
12205 csig->ret = &mono_defaults.object_class->byval_arg;
12207 #ifdef HAVE_ONLINE_VES
12208 /* local 0 (temp for exception object) */
12209 mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
12211 /* local 1 (temp for result) */
12212 if (!MONO_TYPE_IS_VOID (sig->ret))
12213 mono_mb_add_local (mb, sig->ret);
12215 /* clear exception arg */
12216 mono_mb_emit_ldarg (mb, param_count - 1);
12217 mono_mb_emit_byte (mb, CEE_LDNULL);
12218 mono_mb_emit_byte (mb, CEE_STIND_REF);
12221 clause = (MonoExceptionClause *)mono_image_alloc0 (image, sizeof (MonoExceptionClause));
12222 clause->try_offset = mono_mb_get_label (mb);
12224 /* push method's args */
12225 for (i = 0; i < param_count - 1; i++) {
12229 mono_mb_emit_ldarg (mb, i);
12231 /* get the byval type of the param */
12232 klass = mono_class_from_mono_type (csig->params [i]);
12233 type = &klass->byval_arg;
12235 /* unbox struct args */
12236 if (MONO_TYPE_ISSTRUCT (type)) {
12237 mono_mb_emit_op (mb, CEE_UNBOX, klass);
12239 /* byref args & and the "this" arg must remain a ptr.
12240 Otherwise make a copy of the value type */
12241 if (!(csig->params [i]->byref || (i == 0 && sig->hasthis)))
12242 mono_mb_emit_op (mb, CEE_LDOBJ, klass);
12244 csig->params [i] = &mono_defaults.object_class->byval_arg;
12249 if (method->flags & METHOD_ATTRIBUTE_VIRTUAL)
12250 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
12252 mono_mb_emit_op (mb, CEE_CALL, method);
12254 /* save result at local 1 */
12255 if (!MONO_TYPE_IS_VOID (sig->ret))
12256 mono_mb_emit_stloc (mb, 1);
12258 pos_leave = mono_mb_emit_branch (mb, CEE_LEAVE);
12261 clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
12262 clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
12263 clause->data.catch_class = mono_defaults.object_class;
12265 clause->handler_offset = mono_mb_get_label (mb);
12267 /* store exception at local 0 */
12268 mono_mb_emit_stloc (mb, 0);
12269 mono_mb_emit_ldarg (mb, param_count - 1);
12270 mono_mb_emit_ldloc (mb, 0);
12271 mono_mb_emit_byte (mb, CEE_STIND_REF);
12272 mono_mb_emit_branch (mb, CEE_LEAVE);
12274 clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
12276 mono_mb_set_clauses (mb, 1, clause);
12278 mono_mb_patch_branch (mb, pos_leave);
12281 if (!MONO_TYPE_IS_VOID (sig->ret)) {
12282 mono_mb_emit_ldloc (mb, 1);
12284 /* box the return value */
12285 if (MONO_TYPE_ISSTRUCT (sig->ret))
12286 mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (sig->ret));
12289 mono_mb_emit_byte (mb, CEE_RET);
12292 res = mono_mb_create_and_cache (cache, method, mb, csig, param_count + 16);
12299 * mono_marshal_free_dynamic_wrappers:
12301 * Free wrappers of the dynamic method METHOD.
12304 mono_marshal_free_dynamic_wrappers (MonoMethod *method)
12306 MonoImage *image = method->klass->image;
12308 g_assert (method_is_dynamic (method));
12310 /* This could be called during shutdown */
12311 if (marshal_mutex_initialized)
12312 mono_marshal_lock ();
12314 * FIXME: We currently leak the wrappers. Freeing them would be tricky as
12315 * they could be shared with other methods ?
12317 if (image->wrapper_caches.runtime_invoke_direct_cache)
12318 g_hash_table_remove (image->wrapper_caches.runtime_invoke_direct_cache, method);
12319 if (image->wrapper_caches.delegate_abstract_invoke_cache)
12320 g_hash_table_foreach_remove (image->wrapper_caches.delegate_abstract_invoke_cache, signature_pointer_pair_matches_pointer, method);
12321 // FIXME: Need to clear the caches in other images as well
12322 if (image->delegate_bound_static_invoke_cache)
12323 g_hash_table_remove (image->delegate_bound_static_invoke_cache, mono_method_signature (method));
12325 if (marshal_mutex_initialized)
12326 mono_marshal_unlock ();
12330 mono_marshal_ftnptr_eh_callback (guint32 gchandle)
12332 g_assert (ftnptr_eh_callback);
12333 ftnptr_eh_callback (gchandle);
12337 ftnptr_eh_callback_default (guint32 gchandle)
12339 MonoException *exc;
12340 gpointer stackdata;
12342 mono_threads_enter_gc_unsafe_region_unbalanced (&stackdata);
12344 exc = (MonoException*) mono_gchandle_get_target (gchandle);
12346 mono_gchandle_free (gchandle);
12348 mono_raise_exception (exc);
12352 * mono_install_ftnptr_eh_callback:
12354 * Install a callback that should be called when there is a managed exception
12355 * in a native-to-managed wrapper. This is mainly used by iOS to convert a
12356 * managed exception to a native exception, to properly unwind the native
12357 * stack; this native exception will then be converted back to a managed
12358 * exception in their managed-to-native wrapper.
12361 mono_install_ftnptr_eh_callback (MonoFtnPtrEHCallback callback)
12363 ftnptr_eh_callback = callback;
12366 static MonoThreadInfo*
12367 mono_icall_start (HandleStackMark *stackmark, MonoError *error)
12369 MonoThreadInfo *info = mono_thread_info_current ();
12371 mono_stack_mark_init (info, stackmark);
12372 error_init (error);
12377 mono_icall_end (MonoThreadInfo *info, HandleStackMark *stackmark, MonoError *error)
12379 mono_stack_mark_pop (info, stackmark);
12380 if (G_UNLIKELY (!is_ok (error)))
12381 mono_error_set_pending_exception (error);
12384 static MonoObjectHandle
12385 mono_icall_handle_new (gpointer rawobj)
12387 #ifdef MONO_HANDLE_TRACK_OWNER
12388 return mono_handle_new (rawobj, "<marshal args>");
12390 return mono_handle_new (rawobj);
12394 static MonoObjectHandle
12395 mono_icall_handle_new_interior (gpointer rawobj)
12397 #ifdef MONO_HANDLE_TRACK_OWNER
12398 return mono_handle_new_interior (rawobj, "<marshal args>");
12400 return mono_handle_new_interior (rawobj);