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) {
4032 MONO_GC_REGISTER_ROOT_SINGLE (string_dummy, MONO_ROOT_SOURCE_MARSHAL, "dummy marshal string");
4033 string_dummy = mono_string_new_checked (mono_get_root_domain (), "dummy", &error);
4034 mono_error_assert_ok (&error);
4038 g_assert (sig->hasthis);
4039 g_assert (method->flags & METHOD_ATTRIBUTE_VIRTUAL);
4044 if (mono_gc_is_moving ()) {
4045 mono_mb_emit_ptr (mb, &string_dummy);
4046 mono_mb_emit_byte (mb, CEE_LDIND_REF);
4048 mono_mb_emit_ptr (mb, string_dummy);
4051 mono_mb_emit_ldarg (mb, 0);
4055 tmp_nullable_locals = g_new0 (int, sig->param_count);
4057 for (i = 0; i < sig->param_count; i++) {
4058 MonoType *t = sig->params [i];
4061 mono_mb_emit_ldarg (mb, 1);
4063 mono_mb_emit_icon (mb, sizeof (gpointer) * i);
4064 mono_mb_emit_byte (mb, CEE_ADD);
4068 mono_mb_emit_byte (mb, CEE_LDIND_I);
4069 /* A Nullable<T> type don't have a boxed form, it's either null or a boxed T.
4070 * So to make this work we unbox it to a local variablee and push a reference to that.
4072 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
4073 tmp_nullable_locals [i] = mono_mb_add_local (mb, &mono_class_from_mono_type (t)->byval_arg);
4075 mono_mb_emit_op (mb, CEE_UNBOX_ANY, mono_class_from_mono_type (t));
4076 mono_mb_emit_stloc (mb, tmp_nullable_locals [i]);
4077 mono_mb_emit_ldloc_addr (mb, tmp_nullable_locals [i]);
4082 /*FIXME 'this doesn't handle generic enums. Shouldn't we?*/
4083 type = sig->params [i]->type;
4087 case MONO_TYPE_BOOLEAN:
4091 case MONO_TYPE_CHAR:
4100 mono_mb_emit_byte (mb, CEE_LDIND_I);
4101 mono_mb_emit_byte (mb, mono_type_to_ldind (sig->params [i]));
4103 case MONO_TYPE_STRING:
4104 case MONO_TYPE_CLASS:
4105 case MONO_TYPE_ARRAY:
4107 case MONO_TYPE_SZARRAY:
4108 case MONO_TYPE_OBJECT:
4109 mono_mb_emit_byte (mb, mono_type_to_ldind (sig->params [i]));
4111 case MONO_TYPE_GENERICINST:
4112 if (!mono_type_generic_inst_is_valuetype (sig->params [i])) {
4113 mono_mb_emit_byte (mb, mono_type_to_ldind (sig->params [i]));
4118 case MONO_TYPE_VALUETYPE:
4119 if (type == MONO_TYPE_VALUETYPE && t->data.klass->enumtype) {
4120 type = mono_class_enum_basetype (t->data.klass)->type;
4123 mono_mb_emit_byte (mb, CEE_LDIND_I);
4124 if (mono_class_is_nullable (mono_class_from_mono_type (sig->params [i]))) {
4125 /* Need to convert a boxed vtype to an mp to a Nullable struct */
4126 mono_mb_emit_op (mb, CEE_UNBOX, mono_class_from_mono_type (sig->params [i]));
4127 mono_mb_emit_op (mb, CEE_LDOBJ, mono_class_from_mono_type (sig->params [i]));
4129 mono_mb_emit_op (mb, CEE_LDOBJ, mono_class_from_mono_type (sig->params [i]));
4133 g_assert_not_reached ();
4138 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
4139 } else if (need_direct_wrapper) {
4140 mono_mb_emit_op (mb, CEE_CALL, method);
4142 mono_mb_emit_ldarg (mb, 3);
4143 mono_mb_emit_calli (mb, callsig);
4146 if (sig->ret->byref) {
4148 g_assert_not_reached ();
4151 switch (sig->ret->type) {
4152 case MONO_TYPE_VOID:
4156 case MONO_TYPE_BOOLEAN:
4157 case MONO_TYPE_CHAR:
4170 case MONO_TYPE_VALUETYPE:
4171 case MONO_TYPE_TYPEDBYREF:
4172 case MONO_TYPE_GENERICINST:
4173 /* box value types */
4174 mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (sig->ret));
4176 case MONO_TYPE_STRING:
4177 case MONO_TYPE_CLASS:
4178 case MONO_TYPE_ARRAY:
4179 case MONO_TYPE_SZARRAY:
4180 case MONO_TYPE_OBJECT:
4184 /* The result is an IntPtr */
4185 mono_mb_emit_op (mb, CEE_BOX, mono_defaults.int_class);
4188 g_assert_not_reached ();
4192 mono_mb_emit_stloc (mb, loc_res);
4194 /* Convert back nullable-byref arguments */
4195 for (i = 0; i < sig->param_count; i++) {
4196 MonoType *t = sig->params [i];
4199 * Box the result and put it back into the array, the caller will have
4200 * to obtain it from there.
4202 if (t->byref && t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
4203 mono_mb_emit_ldarg (mb, 1);
4204 mono_mb_emit_icon (mb, sizeof (gpointer) * i);
4205 mono_mb_emit_byte (mb, CEE_ADD);
4207 mono_mb_emit_ldloc (mb, tmp_nullable_locals [i]);
4208 mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (t));
4210 mono_mb_emit_byte (mb, CEE_STIND_REF);
4214 g_free (tmp_nullable_locals);
4218 emit_runtime_invoke_body (MonoMethodBuilder *mb, MonoImage *image, MonoMethod *method,
4219 MonoMethodSignature *sig, MonoMethodSignature *callsig,
4220 gboolean virtual_, gboolean need_direct_wrapper)
4223 MonoExceptionClause *clause;
4224 int loc_res, loc_exc;
4226 /* The wrapper looks like this:
4232 * } catch (Exception e) {
4240 /* allocate local 0 (object) tmp */
4241 loc_res = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
4242 /* allocate local 1 (object) exc */
4243 loc_exc = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
4245 /* *exc is assumed to be initialized to NULL by the caller */
4247 mono_mb_emit_byte (mb, CEE_LDARG_2);
4248 labels [0] = mono_mb_emit_branch (mb, CEE_BRFALSE);
4253 labels [1] = mono_mb_get_label (mb);
4254 emit_thread_force_interrupt_checkpoint (mb);
4255 emit_invoke_call (mb, method, sig, callsig, loc_res, virtual_, need_direct_wrapper);
4257 labels [2] = mono_mb_emit_branch (mb, CEE_LEAVE);
4259 /* Add a try clause around the call */
4260 clause = (MonoExceptionClause *)mono_image_alloc0 (image, sizeof (MonoExceptionClause));
4261 clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
4262 clause->data.catch_class = mono_defaults.exception_class;
4263 clause->try_offset = labels [1];
4264 clause->try_len = mono_mb_get_label (mb) - labels [1];
4266 clause->handler_offset = mono_mb_get_label (mb);
4269 mono_mb_emit_stloc (mb, loc_exc);
4270 mono_mb_emit_byte (mb, CEE_LDARG_2);
4271 mono_mb_emit_ldloc (mb, loc_exc);
4272 mono_mb_emit_byte (mb, CEE_STIND_REF);
4274 mono_mb_emit_branch (mb, CEE_LEAVE);
4276 clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
4278 mono_mb_set_clauses (mb, 1, clause);
4280 mono_mb_patch_branch (mb, labels [2]);
4281 mono_mb_emit_ldloc (mb, loc_res);
4282 mono_mb_emit_byte (mb, CEE_RET);
4287 mono_mb_patch_branch (mb, labels [0]);
4288 emit_thread_force_interrupt_checkpoint (mb);
4289 emit_invoke_call (mb, method, sig, callsig, loc_res, virtual_, need_direct_wrapper);
4291 mono_mb_emit_ldloc (mb, 0);
4292 mono_mb_emit_byte (mb, CEE_RET);
4297 * mono_marshal_get_runtime_invoke:
4298 * Generates IL code for the runtime invoke function:
4300 * <code>MonoObject *runtime_invoke (MonoObject *this_obj, void **params, MonoObject **exc, void* method)</code>
4302 * We also catch exceptions if \p exc is not NULL.
4303 * If \p virtual is TRUE, then \p method is invoked virtually on \p this. This is useful since
4304 * it means that the compiled code for \p method does not have to be looked up
4305 * before calling the runtime invoke wrapper. In this case, the wrapper ignores
4306 * its \p method argument.
4309 mono_marshal_get_runtime_invoke (MonoMethod *method, gboolean virtual_)
4311 MonoMethodSignature *sig, *csig, *callsig;
4312 MonoMethodBuilder *mb;
4313 GHashTable *cache = NULL;
4314 MonoClass *target_klass;
4315 MonoMethod *res = NULL;
4316 static MonoMethodSignature *cctor_signature = NULL;
4317 static MonoMethodSignature *finalize_signature = NULL;
4319 const char *param_names [16];
4320 gboolean need_direct_wrapper = FALSE;
4325 if (!cctor_signature) {
4326 cctor_signature = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4327 cctor_signature->ret = &mono_defaults.void_class->byval_arg;
4329 if (!finalize_signature) {
4330 finalize_signature = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4331 finalize_signature->ret = &mono_defaults.void_class->byval_arg;
4332 finalize_signature->hasthis = 1;
4336 need_direct_wrapper = TRUE;
4339 * Use a separate cache indexed by methods to speed things up and to avoid the
4340 * boundless mempool growth caused by the signature_dup stuff below.
4343 cache = get_cache (&method->klass->image->runtime_invoke_vcall_cache, mono_aligned_addr_hash, NULL);
4345 cache = get_cache (&mono_method_get_wrapper_cache (method)->runtime_invoke_direct_cache, mono_aligned_addr_hash, NULL);
4347 res = mono_marshal_find_in_cache (cache, method);
4351 if (method->klass->rank && (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
4352 (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
4354 * Array Get/Set/Address methods. The JIT implements them using inline code
4355 * so we need to create an invoke wrapper which calls the method directly.
4357 need_direct_wrapper = TRUE;
4360 if (method->string_ctor) {
4361 callsig = lookup_string_ctor_signature (mono_method_signature (method));
4363 callsig = add_string_ctor_signature (method);
4364 /* Can't share this as we push a string as this */
4365 need_direct_wrapper = TRUE;
4367 if (method_is_dynamic (method))
4368 callsig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
4370 callsig = mono_method_signature (method);
4373 sig = mono_method_signature (method);
4375 target_klass = get_wrapper_target_class (method->klass->image);
4377 /* Try to share wrappers for non-corlib methods with simple signatures */
4378 if (mono_metadata_signature_equal (callsig, cctor_signature)) {
4379 callsig = cctor_signature;
4380 target_klass = mono_defaults.object_class;
4381 } else if (mono_metadata_signature_equal (callsig, finalize_signature)) {
4382 callsig = finalize_signature;
4383 target_klass = mono_defaults.object_class;
4386 if (need_direct_wrapper) {
4387 /* Already searched at the start */
4389 MonoMethodSignature *tmp_sig;
4391 callsig = mono_marshal_get_runtime_invoke_sig (callsig);
4392 GHashTable **cache_table = NULL;
4394 if (method->klass->valuetype && mono_method_signature (method)->hasthis)
4395 cache_table = &mono_method_get_wrapper_cache (method)->runtime_invoke_vtype_cache;
4397 cache_table = &mono_method_get_wrapper_cache (method)->runtime_invoke_cache;
4399 cache = get_cache (cache_table, (GHashFunc)mono_signature_hash,
4400 (GCompareFunc)runtime_invoke_signature_equal);
4402 /* from mono_marshal_find_in_cache */
4403 mono_marshal_lock ();
4404 res = (MonoMethod *)g_hash_table_lookup (cache, callsig);
4405 mono_marshal_unlock ();
4412 /* Make a copy of the signature from the image mempool */
4414 callsig = mono_metadata_signature_dup_full (target_klass->image, callsig);
4418 csig = mono_metadata_signature_alloc (target_klass->image, 4);
4420 csig->ret = &mono_defaults.object_class->byval_arg;
4421 if (method->klass->valuetype && mono_method_signature (method)->hasthis)
4422 csig->params [0] = get_runtime_invoke_type (&method->klass->this_arg, FALSE);
4424 csig->params [0] = &mono_defaults.object_class->byval_arg;
4425 csig->params [1] = &mono_defaults.int_class->byval_arg;
4426 csig->params [2] = &mono_defaults.int_class->byval_arg;
4427 csig->params [3] = &mono_defaults.int_class->byval_arg;
4430 /* This is called from runtime code so it has to be cdecl */
4431 csig->call_convention = MONO_CALL_C;
4434 name = mono_signature_to_name (callsig, virtual_ ? "runtime_invoke_virtual" : "runtime_invoke");
4435 mb = mono_mb_new (target_klass, name, MONO_WRAPPER_RUNTIME_INVOKE);
4438 #ifdef HAVE_ONLINE_VES
4439 param_names [0] = "this";
4440 param_names [1] = "params";
4441 param_names [2] = "exc";
4442 param_names [3] = "method";
4443 mono_mb_set_param_names (mb, param_names);
4445 emit_runtime_invoke_body (mb, target_klass->image, method, sig, callsig, virtual_, need_direct_wrapper);
4448 if (need_direct_wrapper) {
4449 #ifdef HAVE_ONLINE_VES
4450 mb->skip_visibility = 1;
4452 info = mono_wrapper_info_create (mb, virtual_ ? WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL : WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT);
4453 info->d.runtime_invoke.method = method;
4454 res = mono_mb_create_and_cache_full (cache, method, mb, csig, sig->param_count + 16, info, NULL);
4456 /* taken from mono_mb_create_and_cache */
4457 mono_marshal_lock ();
4458 res = (MonoMethod *)g_hash_table_lookup (cache, callsig);
4459 mono_marshal_unlock ();
4461 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL);
4462 info->d.runtime_invoke.sig = callsig;
4464 /* Somebody may have created it before us */
4467 newm = mono_mb_create (mb, csig, sig->param_count + 16, info);
4469 mono_marshal_lock ();
4470 res = (MonoMethod *)g_hash_table_lookup (cache, callsig);
4472 GHashTable *direct_cache;
4474 g_hash_table_insert (cache, callsig, res);
4475 /* Can't insert it into wrapper_hash since the key is a signature */
4476 direct_cache = mono_method_get_wrapper_cache (method)->runtime_invoke_direct_cache;
4478 g_hash_table_insert (direct_cache, method, res);
4480 mono_free_method (newm);
4482 mono_marshal_unlock ();
4485 /* end mono_mb_create_and_cache */
4494 * mono_marshal_get_runtime_invoke_dynamic:
4496 * Return a method which can be used to invoke managed methods from native code
4498 * The signature of the returned method is given by RuntimeInvokeDynamicFunction:
4499 * void runtime_invoke (void *args, MonoObject **exc, void *compiled_method)
4500 * ARGS should point to an architecture specific structure containing
4501 * the arguments and space for the return value.
4502 * The other arguments are the same as for runtime_invoke (), except that
4503 * ARGS should contain the this argument too.
4504 * This wrapper serves the same purpose as the runtime-invoke wrappers, but there
4505 * is only one copy of it, which is useful in full-aot.
4508 mono_marshal_get_runtime_invoke_dynamic (void)
4510 static MonoMethod *method;
4511 MonoMethodSignature *csig;
4512 MonoExceptionClause *clause;
4513 MonoMethodBuilder *mb;
4521 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 4);
4523 csig->ret = &mono_defaults.void_class->byval_arg;
4524 csig->params [0] = &mono_defaults.int_class->byval_arg;
4525 csig->params [1] = &mono_defaults.int_class->byval_arg;
4526 csig->params [2] = &mono_defaults.int_class->byval_arg;
4527 csig->params [3] = &mono_defaults.int_class->byval_arg;
4529 name = g_strdup ("runtime_invoke_dynamic");
4530 mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_RUNTIME_INVOKE);
4533 #ifdef HAVE_ONLINE_VES
4534 /* allocate local 0 (object) tmp */
4535 mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
4536 /* allocate local 1 (object) exc */
4537 mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
4539 /* cond set *exc to null */
4540 mono_mb_emit_byte (mb, CEE_LDARG_1);
4541 mono_mb_emit_byte (mb, CEE_BRFALSE_S);
4542 mono_mb_emit_byte (mb, 3);
4543 mono_mb_emit_byte (mb, CEE_LDARG_1);
4544 mono_mb_emit_byte (mb, CEE_LDNULL);
4545 mono_mb_emit_byte (mb, CEE_STIND_REF);
4547 emit_thread_force_interrupt_checkpoint (mb);
4549 mono_mb_emit_byte (mb, CEE_LDARG_0);
4550 mono_mb_emit_byte (mb, CEE_LDARG_2);
4551 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
4552 mono_mb_emit_byte (mb, CEE_MONO_DYN_CALL);
4554 pos = mono_mb_emit_branch (mb, CEE_LEAVE);
4556 clause = (MonoExceptionClause *)mono_image_alloc0 (mono_defaults.corlib, sizeof (MonoExceptionClause));
4557 clause->flags = MONO_EXCEPTION_CLAUSE_FILTER;
4558 clause->try_len = mono_mb_get_label (mb);
4561 clause->data.filter_offset = mono_mb_get_label (mb);
4563 mono_mb_emit_byte (mb, CEE_POP);
4564 mono_mb_emit_byte (mb, CEE_LDARG_1);
4565 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
4566 mono_mb_emit_byte (mb, CEE_PREFIX1);
4567 mono_mb_emit_byte (mb, CEE_CGT_UN);
4568 mono_mb_emit_byte (mb, CEE_PREFIX1);
4569 mono_mb_emit_byte (mb, CEE_ENDFILTER);
4571 clause->handler_offset = mono_mb_get_label (mb);
4574 /* store exception */
4575 mono_mb_emit_stloc (mb, 1);
4577 mono_mb_emit_byte (mb, CEE_LDARG_1);
4578 mono_mb_emit_ldloc (mb, 1);
4579 mono_mb_emit_byte (mb, CEE_STIND_REF);
4581 mono_mb_emit_byte (mb, CEE_LDNULL);
4582 mono_mb_emit_stloc (mb, 0);
4584 mono_mb_emit_branch (mb, CEE_LEAVE);
4586 clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
4588 mono_mb_set_clauses (mb, 1, clause);
4591 mono_mb_patch_branch (mb, pos);
4592 //mono_mb_emit_ldloc (mb, 0);
4593 mono_mb_emit_byte (mb, CEE_RET);
4594 #endif /* HAVE_ONLINE_VES */
4596 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC);
4598 mono_marshal_lock ();
4599 /* double-checked locking */
4601 method = mono_mb_create (mb, csig, 16, info);
4603 mono_marshal_unlock ();
4611 * mono_marshal_get_runtime_invoke_for_sig:
4613 * Return a runtime invoke wrapper for a given signature.
4616 mono_marshal_get_runtime_invoke_for_sig (MonoMethodSignature *sig)
4618 MonoMethodSignature *csig, *callsig;
4619 MonoMethodBuilder *mb;
4621 GHashTable *cache = NULL;
4622 GHashTable **cache_table = NULL;
4623 MonoMethod *res = NULL;
4625 const char *param_names [16];
4628 /* A simplified version of mono_marshal_get_runtime_invoke */
4630 image = mono_defaults.corlib;
4632 callsig = mono_marshal_get_runtime_invoke_sig (sig);
4634 cache_table = &image->wrapper_caches.runtime_invoke_sig_cache;
4636 cache = get_cache (cache_table, (GHashFunc)mono_signature_hash,
4637 (GCompareFunc)runtime_invoke_signature_equal);
4639 /* from mono_marshal_find_in_cache */
4640 mono_marshal_lock ();
4641 res = (MonoMethod *)g_hash_table_lookup (cache, callsig);
4642 mono_marshal_unlock ();
4649 /* Make a copy of the signature from the image mempool */
4650 callsig = mono_metadata_signature_dup_full (image, callsig);
4652 csig = mono_metadata_signature_alloc (image, 4);
4653 csig->ret = &mono_defaults.object_class->byval_arg;
4654 csig->params [0] = &mono_defaults.object_class->byval_arg;
4655 csig->params [1] = &mono_defaults.int_class->byval_arg;
4656 csig->params [2] = &mono_defaults.int_class->byval_arg;
4657 csig->params [3] = &mono_defaults.int_class->byval_arg;
4660 /* This is called from runtime code so it has to be cdecl */
4661 csig->call_convention = MONO_CALL_C;
4664 name = mono_signature_to_name (callsig, "runtime_invoke_sig");
4665 mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_RUNTIME_INVOKE);
4668 #ifdef HAVE_ONLINE_VES
4669 param_names [0] = "this";
4670 param_names [1] = "params";
4671 param_names [2] = "exc";
4672 param_names [3] = "method";
4673 mono_mb_set_param_names (mb, param_names);
4675 emit_runtime_invoke_body (mb, image, NULL, sig, callsig, FALSE, FALSE);
4678 /* taken from mono_mb_create_and_cache */
4679 mono_marshal_lock ();
4680 res = (MonoMethod *)g_hash_table_lookup (cache, callsig);
4681 mono_marshal_unlock ();
4683 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL);
4684 info->d.runtime_invoke.sig = callsig;
4686 /* Somebody may have created it before us */
4689 newm = mono_mb_create (mb, csig, sig->param_count + 16, info);
4691 mono_marshal_lock ();
4692 res = (MonoMethod *)g_hash_table_lookup (cache, callsig);
4695 g_hash_table_insert (cache, callsig, res);
4697 mono_free_method (newm);
4699 mono_marshal_unlock ();
4702 /* end mono_mb_create_and_cache */
4709 #ifdef HAVE_ONLINE_VES
4711 mono_mb_emit_auto_layout_exception (MonoMethodBuilder *mb, MonoClass *klass)
4713 char *msg = g_strdup_printf ("The type `%s.%s' layout needs to be Sequential or Explicit",
4714 klass->name_space, klass->name);
4716 mono_mb_emit_exception_marshal_directive (mb, msg);
4721 * mono_marshal_get_icall_wrapper:
4722 * Generates IL code for the icall wrapper. The generated method
4723 * calls the unmanaged code in \p func.
4726 mono_marshal_get_icall_wrapper (MonoMethodSignature *sig, const char *name, gconstpointer func, gboolean check_exceptions)
4728 MonoMethodSignature *csig, *csig2;
4729 MonoMethodBuilder *mb;
4734 GHashTable *cache = get_cache (&mono_defaults.object_class->image->icall_wrapper_cache, mono_aligned_addr_hash, NULL);
4735 if ((res = mono_marshal_find_in_cache (cache, (gpointer) func)))
4738 g_assert (sig->pinvoke);
4740 mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
4742 mb->method->save_lmf = 1;
4744 /* Add an explicit this argument */
4746 csig2 = mono_metadata_signature_dup_add_this (mono_defaults.corlib, sig, mono_defaults.object_class);
4748 csig2 = mono_metadata_signature_dup_full (mono_defaults.corlib, sig);
4750 #ifdef HAVE_ONLINE_VES
4752 mono_mb_emit_byte (mb, CEE_LDARG_0);
4754 for (i = 0; i < sig->param_count; i++)
4755 mono_mb_emit_ldarg (mb, i + sig->hasthis);
4757 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
4758 mono_mb_emit_op (mb, CEE_MONO_JIT_ICALL_ADDR, (gpointer)func);
4759 mono_mb_emit_calli (mb, csig2);
4760 if (check_exceptions)
4761 emit_thread_interrupt_checkpoint (mb);
4762 mono_mb_emit_byte (mb, CEE_RET);
4765 csig = mono_metadata_signature_dup_full (mono_defaults.corlib, sig);
4767 if (csig->call_convention == MONO_CALL_VARARG)
4768 csig->call_convention = 0;
4770 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ICALL_WRAPPER);
4771 info->d.icall.func = (gpointer)func;
4772 res = mono_mb_create_and_cache_full (cache, (gpointer) func, mb, csig, csig->param_count + 16, info, NULL);
4779 emit_marshal_custom (EmitMarshalContext *m, int argnum, MonoType *t,
4780 MonoMarshalSpec *spec,
4781 int conv_arg, MonoType **conv_arg_type,
4782 MarshalAction action)
4784 #ifndef HAVE_ONLINE_VES
4785 if (action == MARSHAL_ACTION_CONV_IN && t->type == MONO_TYPE_VALUETYPE)
4786 *conv_arg_type = &mono_defaults.int_class->byval_arg;
4792 static MonoClass *ICustomMarshaler = NULL;
4793 static MonoMethod *cleanup_native, *cleanup_managed;
4794 static MonoMethod *marshal_managed_to_native, *marshal_native_to_managed;
4795 MonoMethod *get_instance = NULL;
4796 MonoMethodBuilder *mb = m->mb;
4797 char *exception_msg = NULL;
4801 if (!ICustomMarshaler) {
4802 MonoClass *klass = mono_class_try_get_icustom_marshaler_class ();
4804 exception_msg = g_strdup ("Current profile doesn't support ICustomMarshaler");
4805 goto handle_exception;
4808 cleanup_native = mono_class_get_method_from_name (klass, "CleanUpNativeData", 1);
4809 g_assert (cleanup_native);
4810 cleanup_managed = mono_class_get_method_from_name (klass, "CleanUpManagedData", 1);
4811 g_assert (cleanup_managed);
4812 marshal_managed_to_native = mono_class_get_method_from_name (klass, "MarshalManagedToNative", 1);
4813 g_assert (marshal_managed_to_native);
4814 marshal_native_to_managed = mono_class_get_method_from_name (klass, "MarshalNativeToManaged", 1);
4815 g_assert (marshal_native_to_managed);
4817 mono_memory_barrier ();
4818 ICustomMarshaler = klass;
4821 if (spec->data.custom_data.image)
4822 mtype = mono_reflection_type_from_name_checked (spec->data.custom_data.custom_name, spec->data.custom_data.image, &error);
4824 mtype = mono_reflection_type_from_name_checked (spec->data.custom_data.custom_name, m->image, &error);
4825 g_assert (mtype != NULL);
4826 mono_error_assert_ok (&error);
4827 mklass = mono_class_from_mono_type (mtype);
4828 g_assert (mklass != NULL);
4830 if (!mono_class_is_assignable_from (ICustomMarshaler, mklass))
4831 exception_msg = g_strdup_printf ("Custom marshaler '%s' does not implement the ICustomMarshaler interface.", mklass->name);
4833 get_instance = mono_class_get_method_from_name_flags (mklass, "GetInstance", 1, METHOD_ATTRIBUTE_STATIC);
4835 MonoMethodSignature *get_sig = mono_method_signature (get_instance);
4836 if ((get_sig->ret->type != MONO_TYPE_CLASS) ||
4837 (mono_class_from_mono_type (get_sig->ret) != ICustomMarshaler) ||
4838 (get_sig->params [0]->type != MONO_TYPE_STRING))
4839 get_instance = NULL;
4843 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);
4846 /* Throw exception and emit compensation code if neccesary */
4847 if (exception_msg) {
4849 case MARSHAL_ACTION_CONV_IN:
4850 case MARSHAL_ACTION_CONV_RESULT:
4851 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
4852 if ((action == MARSHAL_ACTION_CONV_RESULT) || (action == MARSHAL_ACTION_MANAGED_CONV_RESULT))
4853 mono_mb_emit_byte (mb, CEE_POP);
4855 mono_mb_emit_exception_full (mb, "System", "ApplicationException", exception_msg);
4858 case MARSHAL_ACTION_PUSH:
4859 mono_mb_emit_byte (mb, CEE_LDNULL);
4867 /* FIXME: MS.NET seems to create one instance for each klass + cookie pair */
4868 /* FIXME: MS.NET throws an exception if GetInstance returns null */
4871 case MARSHAL_ACTION_CONV_IN:
4873 case MONO_TYPE_CLASS:
4874 case MONO_TYPE_OBJECT:
4875 case MONO_TYPE_STRING:
4876 case MONO_TYPE_ARRAY:
4877 case MONO_TYPE_SZARRAY:
4878 case MONO_TYPE_VALUETYPE:
4882 g_warning ("custom marshalling of type %x is currently not supported", t->type);
4883 g_assert_not_reached ();
4887 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
4889 mono_mb_emit_byte (mb, CEE_LDNULL);
4890 mono_mb_emit_stloc (mb, conv_arg);
4892 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT))
4895 /* Minic MS.NET behavior */
4896 if (!t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT) && !(t->attrs & PARAM_ATTRIBUTE_IN))
4899 /* Check for null */
4900 mono_mb_emit_ldarg (mb, argnum);
4902 mono_mb_emit_byte (mb, CEE_LDIND_I);
4903 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4905 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4907 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4909 mono_mb_emit_ldarg (mb, argnum);
4911 mono_mb_emit_byte (mb, CEE_LDIND_REF);
4913 if (t->type == MONO_TYPE_VALUETYPE) {
4915 * Since we can't determine the type of the argument, we
4916 * will assume the unmanaged function takes a pointer.
4918 *conv_arg_type = &mono_defaults.int_class->byval_arg;
4920 mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (t));
4923 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_managed_to_native);
4924 mono_mb_emit_stloc (mb, conv_arg);
4926 mono_mb_patch_branch (mb, pos2);
4929 case MARSHAL_ACTION_CONV_OUT:
4930 /* Check for null */
4931 mono_mb_emit_ldloc (mb, conv_arg);
4932 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4935 mono_mb_emit_ldarg (mb, argnum);
4937 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4939 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4941 mono_mb_emit_ldloc (mb, conv_arg);
4942 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
4943 mono_mb_emit_byte (mb, CEE_STIND_REF);
4944 } else if (t->attrs & PARAM_ATTRIBUTE_OUT) {
4945 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4947 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4949 mono_mb_emit_ldloc (mb, conv_arg);
4950 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
4952 /* We have nowhere to store the result */
4953 mono_mb_emit_byte (mb, CEE_POP);
4956 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4958 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4960 mono_mb_emit_ldloc (mb, conv_arg);
4962 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_native);
4964 mono_mb_patch_branch (mb, pos2);
4967 case MARSHAL_ACTION_PUSH:
4969 mono_mb_emit_ldloc_addr (mb, conv_arg);
4971 mono_mb_emit_ldloc (mb, conv_arg);
4974 case MARSHAL_ACTION_CONV_RESULT:
4975 loc1 = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
4977 mono_mb_emit_stloc (mb, 3);
4979 mono_mb_emit_ldloc (mb, 3);
4980 mono_mb_emit_stloc (mb, loc1);
4982 /* Check for null */
4983 mono_mb_emit_ldloc (mb, 3);
4984 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4986 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4988 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4989 mono_mb_emit_byte (mb, CEE_DUP);
4991 mono_mb_emit_ldloc (mb, 3);
4992 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
4993 mono_mb_emit_stloc (mb, 3);
4995 mono_mb_emit_ldloc (mb, loc1);
4996 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_native);
4998 mono_mb_patch_branch (mb, pos2);
5001 case MARSHAL_ACTION_MANAGED_CONV_IN:
5002 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
5004 mono_mb_emit_byte (mb, CEE_LDNULL);
5005 mono_mb_emit_stloc (mb, conv_arg);
5007 if (t->byref && t->attrs & PARAM_ATTRIBUTE_OUT)
5010 /* Check for null */
5011 mono_mb_emit_ldarg (mb, argnum);
5013 mono_mb_emit_byte (mb, CEE_LDIND_I);
5014 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
5016 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
5017 mono_mb_emit_op (mb, CEE_CALL, get_instance);
5019 mono_mb_emit_ldarg (mb, argnum);
5021 mono_mb_emit_byte (mb, CEE_LDIND_I);
5023 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
5024 mono_mb_emit_stloc (mb, conv_arg);
5026 mono_mb_patch_branch (mb, pos2);
5029 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5030 g_assert (!t->byref);
5032 loc1 = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
5034 mono_mb_emit_stloc (mb, 3);
5036 mono_mb_emit_ldloc (mb, 3);
5037 mono_mb_emit_stloc (mb, loc1);
5039 /* Check for null */
5040 mono_mb_emit_ldloc (mb, 3);
5041 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
5043 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
5044 mono_mb_emit_op (mb, CEE_CALL, get_instance);
5045 mono_mb_emit_byte (mb, CEE_DUP);
5047 mono_mb_emit_ldloc (mb, 3);
5048 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_managed_to_native);
5049 mono_mb_emit_stloc (mb, 3);
5051 mono_mb_emit_ldloc (mb, loc1);
5052 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_managed);
5054 mono_mb_patch_branch (mb, pos2);
5057 case MARSHAL_ACTION_MANAGED_CONV_OUT:
5059 /* Check for null */
5060 mono_mb_emit_ldloc (mb, conv_arg);
5061 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
5064 mono_mb_emit_ldarg (mb, argnum);
5066 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
5068 mono_mb_emit_op (mb, CEE_CALL, get_instance);
5070 mono_mb_emit_ldloc (mb, conv_arg);
5071 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_managed_to_native);
5072 mono_mb_emit_byte (mb, CEE_STIND_I);
5075 /* Call CleanUpManagedData */
5076 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
5078 mono_mb_emit_op (mb, CEE_CALL, get_instance);
5080 mono_mb_emit_ldloc (mb, conv_arg);
5081 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_managed);
5083 mono_mb_patch_branch (mb, pos2);
5087 g_assert_not_reached ();
5095 emit_marshal_asany (EmitMarshalContext *m, int argnum, MonoType *t,
5096 MonoMarshalSpec *spec,
5097 int conv_arg, MonoType **conv_arg_type,
5098 MarshalAction action)
5100 #ifdef HAVE_ONLINE_VES
5101 MonoMethodBuilder *mb = m->mb;
5104 case MARSHAL_ACTION_CONV_IN: {
5105 MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, NULL);
5107 g_assert (t->type == MONO_TYPE_OBJECT);
5108 g_assert (!t->byref);
5110 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5111 mono_mb_emit_ldarg (mb, argnum);
5112 mono_mb_emit_icon (mb, encoding);
5113 mono_mb_emit_icon (mb, t->attrs);
5114 mono_mb_emit_icall (mb, mono_marshal_asany);
5115 mono_mb_emit_stloc (mb, conv_arg);
5119 case MARSHAL_ACTION_PUSH:
5120 mono_mb_emit_ldloc (mb, conv_arg);
5123 case MARSHAL_ACTION_CONV_OUT: {
5124 MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, NULL);
5126 mono_mb_emit_ldarg (mb, argnum);
5127 mono_mb_emit_ldloc (mb, conv_arg);
5128 mono_mb_emit_icon (mb, encoding);
5129 mono_mb_emit_icon (mb, t->attrs);
5130 mono_mb_emit_icall (mb, mono_marshal_free_asany);
5135 g_assert_not_reached ();
5142 emit_marshal_vtype (EmitMarshalContext *m, int argnum, MonoType *t,
5143 MonoMarshalSpec *spec,
5144 int conv_arg, MonoType **conv_arg_type,
5145 MarshalAction action)
5147 #ifdef HAVE_ONLINE_VES
5148 MonoMethodBuilder *mb = m->mb;
5149 MonoClass *klass, *date_time_class;
5152 klass = mono_class_from_mono_type (t);
5154 date_time_class = mono_class_get_date_time_class ();
5157 case MARSHAL_ACTION_CONV_IN:
5158 if (klass == date_time_class) {
5159 /* Convert it to an OLE DATE type */
5160 static MonoMethod *to_oadate;
5163 to_oadate = mono_class_get_method_from_name (date_time_class, "ToOADate", 0);
5164 g_assert (to_oadate);
5166 conv_arg = mono_mb_add_local (mb, &mono_defaults.double_class->byval_arg);
5169 mono_mb_emit_ldarg (mb, argnum);
5170 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5173 if (!(t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && (t->attrs & PARAM_ATTRIBUTE_OUT))) {
5175 m->csig->params [argnum - m->csig->hasthis] = &mono_defaults.double_class->byval_arg;
5177 mono_mb_emit_ldarg_addr (mb, argnum);
5178 mono_mb_emit_managed_call (mb, to_oadate, NULL);
5179 mono_mb_emit_stloc (mb, conv_arg);
5183 mono_mb_patch_branch (mb, pos);
5187 if (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype)
5190 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5192 /* store the address of the source into local variable 0 */
5194 mono_mb_emit_ldarg (mb, argnum);
5196 mono_mb_emit_ldarg_addr (mb, argnum);
5198 mono_mb_emit_stloc (mb, 0);
5200 /* allocate space for the native struct and
5201 * store the address into local variable 1 (dest) */
5202 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
5203 mono_mb_emit_byte (mb, CEE_PREFIX1);
5204 mono_mb_emit_byte (mb, CEE_LOCALLOC);
5205 mono_mb_emit_stloc (mb, conv_arg);
5208 mono_mb_emit_ldloc (mb, 0);
5209 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5212 if (!(t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && (t->attrs & PARAM_ATTRIBUTE_OUT))) {
5214 mono_mb_emit_ldloc (mb, conv_arg);
5215 mono_mb_emit_stloc (mb, 1);
5217 /* emit valuetype conversion code */
5218 emit_struct_conv (mb, klass, FALSE);
5222 mono_mb_patch_branch (mb, pos);
5225 case MARSHAL_ACTION_PUSH:
5226 if (spec && spec->native == MONO_NATIVE_LPSTRUCT) {
5228 g_assert (!t->byref);
5230 /* Have to change the signature since the vtype is passed byref */
5231 m->csig->params [argnum - m->csig->hasthis] = &mono_defaults.int_class->byval_arg;
5233 if (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype)
5234 mono_mb_emit_ldarg_addr (mb, argnum);
5236 mono_mb_emit_ldloc (mb, conv_arg);
5240 if (klass == date_time_class) {
5242 mono_mb_emit_ldloc_addr (mb, conv_arg);
5244 mono_mb_emit_ldloc (mb, conv_arg);
5248 if (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype) {
5249 mono_mb_emit_ldarg (mb, argnum);
5252 mono_mb_emit_ldloc (mb, conv_arg);
5254 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5255 mono_mb_emit_op (mb, CEE_MONO_LDNATIVEOBJ, klass);
5259 case MARSHAL_ACTION_CONV_OUT:
5260 if (klass == date_time_class) {
5261 /* Convert from an OLE DATE type */
5262 static MonoMethod *from_oadate;
5267 if (!((t->attrs & PARAM_ATTRIBUTE_IN) && !(t->attrs & PARAM_ATTRIBUTE_OUT))) {
5269 from_oadate = mono_class_get_method_from_name (date_time_class, "FromOADate", 1);
5270 g_assert (from_oadate);
5272 mono_mb_emit_ldarg (mb, argnum);
5273 mono_mb_emit_ldloc (mb, conv_arg);
5274 mono_mb_emit_managed_call (mb, from_oadate, NULL);
5275 mono_mb_emit_op (mb, CEE_STOBJ, date_time_class);
5280 if (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype)
5284 /* dst = argument */
5285 mono_mb_emit_ldarg (mb, argnum);
5286 mono_mb_emit_stloc (mb, 1);
5288 mono_mb_emit_ldloc (mb, 1);
5289 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5291 if (!((t->attrs & PARAM_ATTRIBUTE_IN) && !(t->attrs & PARAM_ATTRIBUTE_OUT))) {
5292 /* src = tmp_locals [i] */
5293 mono_mb_emit_ldloc (mb, conv_arg);
5294 mono_mb_emit_stloc (mb, 0);
5296 /* emit valuetype conversion code */
5297 emit_struct_conv (mb, klass, TRUE);
5301 emit_struct_free (mb, klass, conv_arg);
5304 mono_mb_patch_branch (mb, pos);
5307 case MARSHAL_ACTION_CONV_RESULT:
5308 if (mono_class_is_explicit_layout (klass) || klass->blittable) {
5309 mono_mb_emit_stloc (mb, 3);
5313 /* load pointer to returned value type */
5314 g_assert (m->vtaddr_var);
5315 mono_mb_emit_ldloc (mb, m->vtaddr_var);
5316 /* store the address of the source into local variable 0 */
5317 mono_mb_emit_stloc (mb, 0);
5319 mono_mb_emit_ldloc_addr (mb, 3);
5320 mono_mb_emit_stloc (mb, 1);
5322 /* emit valuetype conversion code */
5323 emit_struct_conv (mb, klass, TRUE);
5326 case MARSHAL_ACTION_MANAGED_CONV_IN:
5327 if (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype) {
5332 conv_arg = mono_mb_add_local (mb, &klass->byval_arg);
5334 if (t->attrs & PARAM_ATTRIBUTE_OUT)
5338 mono_mb_emit_ldarg (mb, argnum);
5340 mono_mb_emit_ldarg_addr (mb, argnum);
5341 mono_mb_emit_stloc (mb, 0);
5344 mono_mb_emit_ldloc (mb, 0);
5345 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5348 mono_mb_emit_ldloc_addr (mb, conv_arg);
5349 mono_mb_emit_stloc (mb, 1);
5351 /* emit valuetype conversion code */
5352 emit_struct_conv (mb, klass, TRUE);
5355 mono_mb_patch_branch (mb, pos);
5358 case MARSHAL_ACTION_MANAGED_CONV_OUT:
5359 if (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype)
5361 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_IN) && !(t->attrs & PARAM_ATTRIBUTE_OUT))
5364 /* Check for null */
5365 mono_mb_emit_ldarg (mb, argnum);
5366 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
5369 mono_mb_emit_ldloc_addr (mb, conv_arg);
5370 mono_mb_emit_stloc (mb, 0);
5373 mono_mb_emit_ldarg (mb, argnum);
5374 mono_mb_emit_stloc (mb, 1);
5376 /* emit valuetype conversion code */
5377 emit_struct_conv (mb, klass, FALSE);
5379 mono_mb_patch_branch (mb, pos2);
5382 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5383 if (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype) {
5384 mono_mb_emit_stloc (mb, 3);
5389 /* load pointer to returned value type */
5390 g_assert (m->vtaddr_var);
5391 mono_mb_emit_ldloc (mb, m->vtaddr_var);
5393 /* store the address of the source into local variable 0 */
5394 mono_mb_emit_stloc (mb, 0);
5395 /* allocate space for the native struct and
5396 * store the address into dst_ptr */
5397 m->retobj_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5398 m->retobj_class = klass;
5399 g_assert (m->retobj_var);
5400 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
5401 mono_mb_emit_byte (mb, CEE_CONV_I);
5402 mono_mb_emit_icall (mb, ves_icall_marshal_alloc);
5403 mono_mb_emit_stloc (mb, 1);
5404 mono_mb_emit_ldloc (mb, 1);
5405 mono_mb_emit_stloc (mb, m->retobj_var);
5407 /* emit valuetype conversion code */
5408 emit_struct_conv (mb, klass, FALSE);
5412 g_assert_not_reached ();
5419 emit_marshal_string (EmitMarshalContext *m, int argnum, MonoType *t,
5420 MonoMarshalSpec *spec,
5421 int conv_arg, MonoType **conv_arg_type,
5422 MarshalAction action)
5424 #ifndef HAVE_ONLINE_VES
5426 case MARSHAL_ACTION_CONV_IN:
5427 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5429 case MARSHAL_ACTION_MANAGED_CONV_IN:
5430 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5434 MonoMethodBuilder *mb = m->mb;
5435 MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
5436 MonoMarshalConv conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
5440 case MARSHAL_ACTION_CONV_IN:
5441 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5442 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5445 if (t->attrs & PARAM_ATTRIBUTE_OUT)
5448 mono_mb_emit_ldarg (mb, argnum);
5449 mono_mb_emit_byte (mb, CEE_LDIND_I);
5451 mono_mb_emit_ldarg (mb, argnum);
5454 if (conv == MONO_MARSHAL_CONV_INVALID) {
5455 char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
5456 mono_mb_emit_exception_marshal_directive (mb, msg);
5458 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
5460 mono_mb_emit_stloc (mb, conv_arg);
5464 case MARSHAL_ACTION_CONV_OUT:
5465 conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
5466 if (conv == MONO_MARSHAL_CONV_INVALID) {
5467 char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
5468 mono_mb_emit_exception_marshal_directive (mb, msg);
5472 if (encoding == MONO_NATIVE_VBBYREFSTR) {
5473 static MonoMethod *m;
5476 m = mono_class_get_method_from_name_flags (mono_defaults.string_class, "get_Length", -1, 0);
5481 char *msg = g_strdup_printf ("VBByRefStr marshalling requires a ref parameter.", encoding);
5482 mono_mb_emit_exception_marshal_directive (mb, msg);
5487 * Have to allocate a new string with the same length as the original, and
5488 * copy the contents of the buffer pointed to by CONV_ARG into it.
5490 g_assert (t->byref);
5491 mono_mb_emit_ldarg (mb, argnum);
5492 mono_mb_emit_ldloc (mb, conv_arg);
5493 mono_mb_emit_ldarg (mb, argnum);
5494 mono_mb_emit_byte (mb, CEE_LDIND_I);
5495 mono_mb_emit_managed_call (mb, m, NULL);
5496 mono_mb_emit_icall (mb, mono_string_new_len_wrapper);
5497 mono_mb_emit_byte (mb, CEE_STIND_REF);
5498 } else if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT || !(t->attrs & PARAM_ATTRIBUTE_IN))) {
5500 mono_mb_emit_ldarg (mb, argnum);
5501 mono_mb_emit_ldloc (mb, conv_arg);
5502 mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
5503 mono_mb_emit_byte (mb, stind_op);
5508 mono_mb_emit_ldloc (mb, conv_arg);
5509 if (conv == MONO_MARSHAL_CONV_BSTR_STR)
5510 mono_mb_emit_icall (mb, mono_free_bstr);
5512 mono_mb_emit_icall (mb, mono_marshal_free);
5516 case MARSHAL_ACTION_PUSH:
5517 if (t->byref && encoding != MONO_NATIVE_VBBYREFSTR)
5518 mono_mb_emit_ldloc_addr (mb, conv_arg);
5520 mono_mb_emit_ldloc (mb, conv_arg);
5523 case MARSHAL_ACTION_CONV_RESULT:
5524 mono_mb_emit_stloc (mb, 0);
5526 conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
5527 if (conv == MONO_MARSHAL_CONV_INVALID) {
5528 char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
5529 mono_mb_emit_exception_marshal_directive (mb, msg);
5533 mono_mb_emit_ldloc (mb, 0);
5534 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
5535 mono_mb_emit_stloc (mb, 3);
5537 /* free the string */
5538 mono_mb_emit_ldloc (mb, 0);
5539 if (conv == MONO_MARSHAL_CONV_BSTR_STR)
5540 mono_mb_emit_icall (mb, mono_free_bstr);
5542 mono_mb_emit_icall (mb, mono_marshal_free);
5545 case MARSHAL_ACTION_MANAGED_CONV_IN:
5546 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
5548 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5551 if (t->attrs & PARAM_ATTRIBUTE_OUT)
5555 conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
5556 if (conv == MONO_MARSHAL_CONV_INVALID) {
5557 char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
5558 mono_mb_emit_exception_marshal_directive (mb, msg);
5562 mono_mb_emit_ldarg (mb, argnum);
5564 mono_mb_emit_byte (mb, CEE_LDIND_I);
5565 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
5566 mono_mb_emit_stloc (mb, conv_arg);
5569 case MARSHAL_ACTION_MANAGED_CONV_OUT:
5573 mono_mb_emit_ldarg (mb, argnum);
5574 mono_mb_emit_ldloc (mb, conv_arg);
5575 mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
5576 mono_mb_emit_byte (mb, stind_op);
5581 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5582 if (conv_to_icall (conv, NULL) == mono_marshal_string_to_utf16)
5583 /* We need to make a copy so the caller is able to free it */
5584 mono_mb_emit_icall (mb, mono_marshal_string_to_utf16_copy);
5586 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
5587 mono_mb_emit_stloc (mb, 3);
5591 g_assert_not_reached ();
5599 emit_marshal_safehandle (EmitMarshalContext *m, int argnum, MonoType *t,
5600 MonoMarshalSpec *spec, int conv_arg,
5601 MonoType **conv_arg_type, MarshalAction action)
5603 #ifndef HAVE_ONLINE_VES
5604 if (action == MARSHAL_ACTION_CONV_IN)
5605 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5607 MonoMethodBuilder *mb = m->mb;
5610 case MARSHAL_ACTION_CONV_IN: {
5611 MonoType *intptr_type;
5612 int dar_release_slot, pos;
5614 intptr_type = &mono_defaults.int_class->byval_arg;
5615 conv_arg = mono_mb_add_local (mb, intptr_type);
5616 *conv_arg_type = intptr_type;
5618 if (!sh_dangerous_add_ref)
5619 init_safe_handle ();
5621 mono_mb_emit_ldarg (mb, argnum);
5622 pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
5623 mono_mb_emit_exception (mb, "ArgumentNullException", NULL);
5625 mono_mb_patch_branch (mb, pos);
5628 * My tests in show that ref SafeHandles are not really
5629 * passed as ref objects. Instead a NULL is passed as the
5632 mono_mb_emit_icon (mb, 0);
5633 mono_mb_emit_stloc (mb, conv_arg);
5637 /* Create local to hold the ref parameter to DangerousAddRef */
5638 dar_release_slot = mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
5640 /* set release = false; */
5641 mono_mb_emit_icon (mb, 0);
5642 mono_mb_emit_stloc (mb, dar_release_slot);
5644 /* safehandle.DangerousAddRef (ref release) */
5645 mono_mb_emit_ldarg (mb, argnum);
5646 mono_mb_emit_ldloc_addr (mb, dar_release_slot);
5647 mono_mb_emit_managed_call (mb, sh_dangerous_add_ref, NULL);
5649 /* Pull the handle field from SafeHandle */
5650 mono_mb_emit_ldarg (mb, argnum);
5651 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoSafeHandle, handle));
5652 mono_mb_emit_byte (mb, CEE_LDIND_I);
5653 mono_mb_emit_stloc (mb, conv_arg);
5658 case MARSHAL_ACTION_PUSH:
5660 mono_mb_emit_ldloc_addr (mb, conv_arg);
5662 mono_mb_emit_ldloc (mb, conv_arg);
5665 case MARSHAL_ACTION_CONV_OUT: {
5666 /* The slot for the boolean is the next temporary created after conv_arg, see the CONV_IN code */
5667 int dar_release_slot = conv_arg + 1;
5670 if (!sh_dangerous_release)
5671 init_safe_handle ();
5677 * My tests indicate that ref SafeHandles parameters are not actually
5678 * passed by ref, but instead a new Handle is created regardless of
5679 * whether a change happens in the unmanaged side.
5681 * Also, the Handle is created before calling into unmanaged code,
5682 * but we do not support that mechanism (getting to the original
5683 * handle) and it makes no difference where we create this
5685 ctor = mono_class_get_method_from_name (t->data.klass, ".ctor", 0);
5687 mono_mb_emit_exception (mb, "MissingMethodException", "paramterless constructor required");
5690 /* refval = new SafeHandleDerived ()*/
5691 mono_mb_emit_ldarg (mb, argnum);
5692 mono_mb_emit_op (mb, CEE_NEWOBJ, ctor);
5693 mono_mb_emit_byte (mb, CEE_STIND_REF);
5695 /* refval.handle = returned_handle */
5696 mono_mb_emit_ldarg (mb, argnum);
5697 mono_mb_emit_byte (mb, CEE_LDIND_REF);
5698 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoSafeHandle, handle));
5699 mono_mb_emit_ldloc (mb, conv_arg);
5700 mono_mb_emit_byte (mb, CEE_STIND_I);
5702 mono_mb_emit_ldloc (mb, dar_release_slot);
5703 label_next = mono_mb_emit_branch (mb, CEE_BRFALSE);
5704 mono_mb_emit_ldarg (mb, argnum);
5705 mono_mb_emit_managed_call (mb, sh_dangerous_release, NULL);
5706 mono_mb_patch_branch (mb, label_next);
5711 case MARSHAL_ACTION_CONV_RESULT: {
5712 MonoMethod *ctor = NULL;
5713 int intptr_handle_slot;
5715 if (mono_class_is_abstract (t->data.klass)) {
5716 mono_mb_emit_byte (mb, CEE_POP);
5717 mono_mb_emit_exception_marshal_directive (mb, g_strdup ("Returned SafeHandles should not be abstract"));
5721 ctor = mono_class_get_method_from_name (t->data.klass, ".ctor", 0);
5723 mono_mb_emit_byte (mb, CEE_POP);
5724 mono_mb_emit_exception (mb, "MissingMethodException", "paramterless constructor required");
5727 /* Store the IntPtr results into a local */
5728 intptr_handle_slot = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5729 mono_mb_emit_stloc (mb, intptr_handle_slot);
5731 /* Create return value */
5732 mono_mb_emit_op (mb, CEE_NEWOBJ, ctor);
5733 mono_mb_emit_stloc (mb, 3);
5735 /* Set the return.handle to the value, am using ldflda, not sure if thats a good idea */
5736 mono_mb_emit_ldloc (mb, 3);
5737 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoSafeHandle, handle));
5738 mono_mb_emit_ldloc (mb, intptr_handle_slot);
5739 mono_mb_emit_byte (mb, CEE_STIND_I);
5743 case MARSHAL_ACTION_MANAGED_CONV_IN:
5744 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_IN\n");
5747 case MARSHAL_ACTION_MANAGED_CONV_OUT:
5748 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_OUT\n");
5751 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5752 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_RESULT\n");
5755 printf ("Unhandled case for MarshalAction: %d\n", action);
5763 emit_marshal_handleref (EmitMarshalContext *m, int argnum, MonoType *t,
5764 MonoMarshalSpec *spec, int conv_arg,
5765 MonoType **conv_arg_type, MarshalAction action)
5767 #ifndef HAVE_ONLINE_VES
5768 if (action == MARSHAL_ACTION_CONV_IN)
5769 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5771 MonoMethodBuilder *mb = m->mb;
5774 case MARSHAL_ACTION_CONV_IN: {
5775 MonoType *intptr_type;
5777 intptr_type = &mono_defaults.int_class->byval_arg;
5778 conv_arg = mono_mb_add_local (mb, intptr_type);
5779 *conv_arg_type = intptr_type;
5782 char *msg = g_strdup ("HandleRefs can not be returned from unmanaged code (or passed by ref)");
5783 mono_mb_emit_exception_marshal_directive (mb, msg);
5786 mono_mb_emit_ldarg_addr (mb, argnum);
5787 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoHandleRef, handle));
5788 mono_mb_emit_byte (mb, CEE_ADD);
5789 mono_mb_emit_byte (mb, CEE_LDIND_I);
5790 mono_mb_emit_stloc (mb, conv_arg);
5794 case MARSHAL_ACTION_PUSH:
5795 mono_mb_emit_ldloc (mb, conv_arg);
5798 case MARSHAL_ACTION_CONV_OUT: {
5799 /* no resource release required */
5803 case MARSHAL_ACTION_CONV_RESULT: {
5804 char *msg = g_strdup ("HandleRefs can not be returned from unmanaged code (or passed by ref)");
5805 mono_mb_emit_exception_marshal_directive (mb, msg);
5809 case MARSHAL_ACTION_MANAGED_CONV_IN:
5810 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_IN\n");
5813 case MARSHAL_ACTION_MANAGED_CONV_OUT:
5814 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_OUT\n");
5817 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5818 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_RESULT\n");
5821 fprintf (stderr, "Unhandled case for MarshalAction: %d\n", action);
5829 emit_marshal_object (EmitMarshalContext *m, int argnum, MonoType *t,
5830 MonoMarshalSpec *spec,
5831 int conv_arg, MonoType **conv_arg_type,
5832 MarshalAction action)
5834 #ifndef HAVE_ONLINE_VES
5835 if (action == MARSHAL_ACTION_CONV_IN)
5836 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5838 MonoMethodBuilder *mb = m->mb;
5839 MonoClass *klass = mono_class_from_mono_type (t);
5843 case MARSHAL_ACTION_CONV_IN:
5844 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5845 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5847 m->orig_conv_args [argnum] = 0;
5849 if (mono_class_from_mono_type (t) == mono_defaults.object_class) {
5850 char *msg = g_strdup_printf ("Marshalling of type object is not implemented");
5851 mono_mb_emit_exception_marshal_directive (mb, msg);
5855 if (klass->delegate) {
5857 if (!(t->attrs & PARAM_ATTRIBUTE_OUT)) {
5858 char *msg = g_strdup_printf ("Byref marshalling of delegates is not implemented.");
5859 mono_mb_emit_exception_marshal_directive (mb, msg);
5861 mono_mb_emit_byte (mb, CEE_LDNULL);
5862 mono_mb_emit_stloc (mb, conv_arg);
5864 mono_mb_emit_ldarg (mb, argnum);
5865 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_DEL_FTN, NULL));
5866 mono_mb_emit_stloc (mb, conv_arg);
5868 } else if (klass == mono_defaults.stringbuilder_class) {
5869 MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
5870 MonoMarshalConv conv = mono_marshal_get_stringbuilder_to_ptr_conv (m->piinfo, spec);
5874 if (!(t->attrs & PARAM_ATTRIBUTE_OUT)) {
5875 char *msg = g_strdup_printf ("Byref marshalling of stringbuilders is not implemented.");
5876 mono_mb_emit_exception_marshal_directive (mb, msg);
5882 if (t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && (t->attrs & PARAM_ATTRIBUTE_OUT))
5885 if (conv == MONO_MARSHAL_CONV_INVALID) {
5886 char *msg = g_strdup_printf ("stringbuilder marshalling conversion %d not implemented", encoding);
5887 mono_mb_emit_exception_marshal_directive (mb, msg);
5891 mono_mb_emit_ldarg (mb, argnum);
5893 mono_mb_emit_byte (mb, CEE_LDIND_I);
5895 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
5896 mono_mb_emit_stloc (mb, conv_arg);
5897 } else if (klass->blittable) {
5898 mono_mb_emit_byte (mb, CEE_LDNULL);
5899 mono_mb_emit_stloc (mb, conv_arg);
5901 mono_mb_emit_ldarg (mb, argnum);
5902 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5904 mono_mb_emit_ldarg (mb, argnum);
5905 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5906 mono_mb_emit_stloc (mb, conv_arg);
5908 mono_mb_patch_branch (mb, pos);
5911 mono_mb_emit_byte (mb, CEE_LDNULL);
5912 mono_mb_emit_stloc (mb, conv_arg);
5915 /* we dont need any conversions for out parameters */
5916 if (t->attrs & PARAM_ATTRIBUTE_OUT)
5919 mono_mb_emit_ldarg (mb, argnum);
5920 mono_mb_emit_byte (mb, CEE_LDIND_I);
5923 mono_mb_emit_ldarg (mb, argnum);
5924 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5925 mono_mb_emit_byte (mb, CEE_MONO_OBJADDR);
5928 /* store the address of the source into local variable 0 */
5929 mono_mb_emit_stloc (mb, 0);
5930 mono_mb_emit_ldloc (mb, 0);
5931 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5933 /* allocate space for the native struct and store the address */
5934 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
5935 mono_mb_emit_byte (mb, CEE_PREFIX1);
5936 mono_mb_emit_byte (mb, CEE_LOCALLOC);
5937 mono_mb_emit_stloc (mb, conv_arg);
5940 /* Need to store the original buffer so we can free it later */
5941 m->orig_conv_args [argnum] = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5942 mono_mb_emit_ldloc (mb, conv_arg);
5943 mono_mb_emit_stloc (mb, m->orig_conv_args [argnum]);
5946 /* set the src_ptr */
5947 mono_mb_emit_ldloc (mb, 0);
5948 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5949 mono_mb_emit_stloc (mb, 0);
5952 mono_mb_emit_ldloc (mb, conv_arg);
5953 mono_mb_emit_stloc (mb, 1);
5955 /* emit valuetype conversion code */
5956 emit_struct_conv (mb, klass, FALSE);
5958 mono_mb_patch_branch (mb, pos);
5962 case MARSHAL_ACTION_CONV_OUT:
5963 if (klass == mono_defaults.stringbuilder_class) {
5965 MonoMarshalNative encoding;
5966 MonoMarshalConv conv;
5968 encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
5969 conv = mono_marshal_get_ptr_to_stringbuilder_conv (m->piinfo, spec, &need_free);
5971 g_assert (encoding != -1);
5974 //g_assert (!(t->attrs & PARAM_ATTRIBUTE_OUT));
5978 mono_mb_emit_ldarg (mb, argnum);
5979 mono_mb_emit_ldloc (mb, conv_arg);
5982 case MONO_NATIVE_LPWSTR:
5983 mono_mb_emit_icall (mb, mono_string_utf16_to_builder2);
5985 case MONO_NATIVE_LPSTR:
5986 mono_mb_emit_icall (mb, mono_string_utf8_to_builder2);
5988 case MONO_NATIVE_UTF8STR:
5989 mono_mb_emit_icall (mb, mono_string_utf8_to_builder2);
5992 g_assert_not_reached ();
5995 mono_mb_emit_byte (mb, CEE_STIND_REF);
5997 mono_mb_emit_ldarg (mb, argnum);
5998 mono_mb_emit_ldloc (mb, conv_arg);
6000 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
6004 mono_mb_emit_ldloc (mb, conv_arg);
6005 mono_mb_emit_icall (mb, mono_marshal_free);
6010 if (klass->delegate) {
6012 mono_mb_emit_ldarg (mb, argnum);
6013 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
6014 mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
6015 mono_mb_emit_ldloc (mb, conv_arg);
6016 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL, NULL));
6017 mono_mb_emit_byte (mb, CEE_STIND_REF);
6022 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT)) {
6023 /* allocate a new object */
6024 mono_mb_emit_ldarg (mb, argnum);
6025 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
6026 mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, klass);
6027 mono_mb_emit_byte (mb, CEE_STIND_REF);
6030 /* dst = *argument */
6031 mono_mb_emit_ldarg (mb, argnum);
6034 mono_mb_emit_byte (mb, CEE_LDIND_I);
6036 mono_mb_emit_stloc (mb, 1);
6038 mono_mb_emit_ldloc (mb, 1);
6039 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
6041 if (t->byref || (t->attrs & PARAM_ATTRIBUTE_OUT)) {
6042 mono_mb_emit_ldloc (mb, 1);
6043 mono_mb_emit_icon (mb, sizeof (MonoObject));
6044 mono_mb_emit_byte (mb, CEE_ADD);
6045 mono_mb_emit_stloc (mb, 1);
6047 /* src = tmp_locals [i] */
6048 mono_mb_emit_ldloc (mb, conv_arg);
6049 mono_mb_emit_stloc (mb, 0);
6051 /* emit valuetype conversion code */
6052 emit_struct_conv (mb, klass, TRUE);
6054 /* Free the structure returned by the native code */
6055 emit_struct_free (mb, klass, conv_arg);
6057 if (m->orig_conv_args [argnum]) {
6059 * If the native function changed the pointer, then free
6060 * the original structure plus the new pointer.
6062 mono_mb_emit_ldloc (mb, m->orig_conv_args [argnum]);
6063 mono_mb_emit_ldloc (mb, conv_arg);
6064 pos2 = mono_mb_emit_branch (mb, CEE_BEQ);
6066 if (!(t->attrs & PARAM_ATTRIBUTE_OUT)) {
6067 g_assert (m->orig_conv_args [argnum]);
6069 emit_struct_free (mb, klass, m->orig_conv_args [argnum]);
6072 mono_mb_emit_ldloc (mb, conv_arg);
6073 mono_mb_emit_icall (mb, mono_marshal_free);
6075 mono_mb_patch_branch (mb, pos2);
6079 /* Free the original structure passed to native code */
6080 emit_struct_free (mb, klass, conv_arg);
6082 mono_mb_patch_branch (mb, pos);
6085 case MARSHAL_ACTION_PUSH:
6087 mono_mb_emit_ldloc_addr (mb, conv_arg);
6089 mono_mb_emit_ldloc (mb, conv_arg);
6092 case MARSHAL_ACTION_CONV_RESULT:
6093 if (klass->delegate) {
6094 g_assert (!t->byref);
6095 mono_mb_emit_stloc (mb, 0);
6096 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
6097 mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
6098 mono_mb_emit_ldloc (mb, 0);
6099 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL, NULL));
6100 mono_mb_emit_stloc (mb, 3);
6101 } else if (klass == mono_defaults.stringbuilder_class) {
6103 char *msg = g_strdup_printf ("Return marshalling of stringbuilders is not implemented.");
6104 mono_mb_emit_exception_marshal_directive (mb, msg);
6107 mono_mb_emit_stloc (mb, 0);
6109 /* Make a copy since emit_conv modifies local 0 */
6110 loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6111 mono_mb_emit_ldloc (mb, 0);
6112 mono_mb_emit_stloc (mb, loc);
6114 mono_mb_emit_byte (mb, CEE_LDNULL);
6115 mono_mb_emit_stloc (mb, 3);
6117 mono_mb_emit_ldloc (mb, 0);
6118 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
6120 /* allocate result object */
6122 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
6123 mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, klass);
6124 mono_mb_emit_stloc (mb, 3);
6128 mono_mb_emit_ldloc (mb, 3);
6129 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
6130 mono_mb_emit_stloc (mb, 1);
6132 /* emit conversion code */
6133 emit_struct_conv (mb, klass, TRUE);
6135 emit_struct_free (mb, klass, loc);
6137 /* Free the pointer allocated by unmanaged code */
6138 mono_mb_emit_ldloc (mb, loc);
6139 mono_mb_emit_icall (mb, mono_marshal_free);
6140 mono_mb_patch_branch (mb, pos);
6144 case MARSHAL_ACTION_MANAGED_CONV_IN:
6145 conv_arg = mono_mb_add_local (mb, &klass->byval_arg);
6147 if (klass->delegate) {
6148 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
6149 mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
6150 mono_mb_emit_ldarg (mb, argnum);
6152 mono_mb_emit_byte (mb, CEE_LDIND_I);
6153 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL, NULL));
6154 mono_mb_emit_stloc (mb, conv_arg);
6158 if (klass == mono_defaults.stringbuilder_class) {
6159 MonoMarshalNative encoding;
6161 encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
6164 g_assert (encoding == MONO_NATIVE_LPSTR || encoding == MONO_NATIVE_UTF8STR);
6166 g_assert (!t->byref);
6167 g_assert (encoding != -1);
6169 mono_mb_emit_ldarg (mb, argnum);
6170 mono_mb_emit_icall (mb, mono_string_utf8_to_builder2);
6171 mono_mb_emit_stloc (mb, conv_arg);
6175 /* The class can not have an automatic layout */
6176 if (mono_class_is_auto_layout (klass)) {
6177 mono_mb_emit_auto_layout_exception (mb, klass);
6181 if (t->attrs & PARAM_ATTRIBUTE_OUT) {
6182 mono_mb_emit_byte (mb, CEE_LDNULL);
6183 mono_mb_emit_stloc (mb, conv_arg);
6188 mono_mb_emit_ldarg (mb, argnum);
6192 /* Check for NULL and raise an exception */
6193 pos2 = mono_mb_emit_branch (mb, CEE_BRTRUE);
6195 mono_mb_emit_exception (mb, "ArgumentNullException", NULL);
6197 mono_mb_patch_branch (mb, pos2);
6198 mono_mb_emit_ldarg (mb, argnum);
6199 mono_mb_emit_byte (mb, CEE_LDIND_I);
6202 mono_mb_emit_stloc (mb, 0);
6204 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6205 mono_mb_emit_stloc (mb, conv_arg);
6207 mono_mb_emit_ldloc (mb, 0);
6208 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
6210 /* Create and set dst */
6211 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
6212 mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, klass);
6213 mono_mb_emit_stloc (mb, conv_arg);
6214 mono_mb_emit_ldloc (mb, conv_arg);
6215 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
6216 mono_mb_emit_stloc (mb, 1);
6218 /* emit valuetype conversion code */
6219 emit_struct_conv (mb, klass, TRUE);
6221 mono_mb_patch_branch (mb, pos);
6224 case MARSHAL_ACTION_MANAGED_CONV_OUT:
6225 if (klass->delegate) {
6228 mono_mb_emit_ldarg (mb, argnum);
6229 mono_mb_emit_ldloc (mb, conv_arg);
6230 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_DEL_FTN, &stind_op));
6231 mono_mb_emit_byte (mb, stind_op);
6237 /* Check for null */
6238 mono_mb_emit_ldloc (mb, conv_arg);
6239 pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
6240 mono_mb_emit_ldarg (mb, argnum);
6241 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6242 mono_mb_emit_byte (mb, CEE_STIND_REF);
6243 pos2 = mono_mb_emit_branch (mb, CEE_BR);
6245 mono_mb_patch_branch (mb, pos);
6248 mono_mb_emit_ldloc (mb, conv_arg);
6249 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
6250 mono_mb_emit_stloc (mb, 0);
6252 /* Allocate and set dest */
6253 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
6254 mono_mb_emit_byte (mb, CEE_CONV_I);
6255 mono_mb_emit_icall (mb, ves_icall_marshal_alloc);
6256 mono_mb_emit_stloc (mb, 1);
6258 /* Update argument pointer */
6259 mono_mb_emit_ldarg (mb, argnum);
6260 mono_mb_emit_ldloc (mb, 1);
6261 mono_mb_emit_byte (mb, CEE_STIND_I);
6263 /* emit valuetype conversion code */
6264 emit_struct_conv (mb, klass, FALSE);
6266 mono_mb_patch_branch (mb, pos2);
6267 } else if (klass == mono_defaults.stringbuilder_class) {
6268 // FIXME: What to do here ?
6270 /* byval [Out] marshalling */
6272 /* FIXME: Handle null */
6275 mono_mb_emit_ldloc (mb, conv_arg);
6276 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
6277 mono_mb_emit_stloc (mb, 0);
6280 mono_mb_emit_ldarg (mb, argnum);
6281 mono_mb_emit_stloc (mb, 1);
6283 /* emit valuetype conversion code */
6284 emit_struct_conv (mb, klass, FALSE);
6288 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
6289 if (klass->delegate) {
6290 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_DEL_FTN, NULL));
6291 mono_mb_emit_stloc (mb, 3);
6295 /* The class can not have an automatic layout */
6296 if (mono_class_is_auto_layout (klass)) {
6297 mono_mb_emit_auto_layout_exception (mb, klass);
6301 mono_mb_emit_stloc (mb, 0);
6302 /* Check for null */
6303 mono_mb_emit_ldloc (mb, 0);
6304 pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
6305 mono_mb_emit_byte (mb, CEE_LDNULL);
6306 mono_mb_emit_stloc (mb, 3);
6307 pos2 = mono_mb_emit_branch (mb, CEE_BR);
6309 mono_mb_patch_branch (mb, pos);
6312 mono_mb_emit_ldloc (mb, 0);
6313 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
6314 mono_mb_emit_stloc (mb, 0);
6316 /* Allocate and set dest */
6317 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
6318 mono_mb_emit_byte (mb, CEE_CONV_I);
6319 mono_mb_emit_icall (mb, ves_icall_marshal_alloc);
6320 mono_mb_emit_byte (mb, CEE_DUP);
6321 mono_mb_emit_stloc (mb, 1);
6322 mono_mb_emit_stloc (mb, 3);
6324 emit_struct_conv (mb, klass, FALSE);
6326 mono_mb_patch_branch (mb, pos2);
6330 g_assert_not_reached ();
6336 #ifdef HAVE_ONLINE_VES
6340 emit_marshal_variant (EmitMarshalContext *m, int argnum, MonoType *t,
6341 MonoMarshalSpec *spec,
6342 int conv_arg, MonoType **conv_arg_type,
6343 MarshalAction action)
6345 MonoMethodBuilder *mb = m->mb;
6346 static MonoMethod *get_object_for_native_variant = NULL;
6347 static MonoMethod *get_native_variant_for_object = NULL;
6349 if (!get_object_for_native_variant)
6350 get_object_for_native_variant = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetObjectForNativeVariant", 1);
6351 g_assert (get_object_for_native_variant);
6353 if (!get_native_variant_for_object)
6354 get_native_variant_for_object = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetNativeVariantForObject", 2);
6355 g_assert (get_native_variant_for_object);
6358 case MARSHAL_ACTION_CONV_IN: {
6359 conv_arg = mono_mb_add_local (mb, &mono_class_get_variant_class ()->byval_arg);
6362 *conv_arg_type = &mono_class_get_variant_class ()->this_arg;
6364 *conv_arg_type = &mono_class_get_variant_class ()->byval_arg;
6366 if (t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && t->attrs & PARAM_ATTRIBUTE_OUT)
6369 mono_mb_emit_ldarg (mb, argnum);
6371 mono_mb_emit_byte(mb, CEE_LDIND_REF);
6372 mono_mb_emit_ldloc_addr (mb, conv_arg);
6373 mono_mb_emit_managed_call (mb, get_native_variant_for_object, NULL);
6377 case MARSHAL_ACTION_CONV_OUT: {
6378 static MonoMethod *variant_clear = NULL;
6381 variant_clear = mono_class_get_method_from_name (mono_class_get_variant_class (), "Clear", 0);
6382 g_assert (variant_clear);
6385 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT || !(t->attrs & PARAM_ATTRIBUTE_IN))) {
6386 mono_mb_emit_ldarg (mb, argnum);
6387 mono_mb_emit_ldloc_addr (mb, conv_arg);
6388 mono_mb_emit_managed_call (mb, get_object_for_native_variant, NULL);
6389 mono_mb_emit_byte (mb, CEE_STIND_REF);
6392 mono_mb_emit_ldloc_addr (mb, conv_arg);
6393 mono_mb_emit_managed_call (mb, variant_clear, NULL);
6397 case MARSHAL_ACTION_PUSH:
6399 mono_mb_emit_ldloc_addr (mb, conv_arg);
6401 mono_mb_emit_ldloc (mb, conv_arg);
6404 case MARSHAL_ACTION_CONV_RESULT: {
6405 char *msg = g_strdup ("Marshalling of VARIANT not supported as a return type.");
6406 mono_mb_emit_exception_marshal_directive (mb, msg);
6410 case MARSHAL_ACTION_MANAGED_CONV_IN: {
6411 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6414 *conv_arg_type = &mono_class_get_variant_class ()->this_arg;
6416 *conv_arg_type = &mono_class_get_variant_class ()->byval_arg;
6418 if (t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && t->attrs & PARAM_ATTRIBUTE_OUT)
6422 mono_mb_emit_ldarg (mb, argnum);
6424 mono_mb_emit_ldarg_addr (mb, argnum);
6425 mono_mb_emit_managed_call (mb, get_object_for_native_variant, NULL);
6426 mono_mb_emit_stloc (mb, conv_arg);
6430 case MARSHAL_ACTION_MANAGED_CONV_OUT: {
6431 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT || !(t->attrs & PARAM_ATTRIBUTE_IN))) {
6432 mono_mb_emit_ldloc (mb, conv_arg);
6433 mono_mb_emit_ldarg (mb, argnum);
6434 mono_mb_emit_managed_call (mb, get_native_variant_for_object, NULL);
6439 case MARSHAL_ACTION_MANAGED_CONV_RESULT: {
6440 char *msg = g_strdup ("Marshalling of VARIANT not supported as a return type.");
6441 mono_mb_emit_exception_marshal_directive (mb, msg);
6446 g_assert_not_reached ();
6452 #endif /* DISABLE_COM */
6453 #endif /* HAVE_ONLINE_VES */
6456 mono_pinvoke_is_unicode (MonoMethodPInvoke *piinfo)
6458 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
6459 case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
6461 case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
6463 case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
6475 emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
6476 MonoMarshalSpec *spec,
6477 int conv_arg, MonoType **conv_arg_type,
6478 MarshalAction action)
6480 #ifndef HAVE_ONLINE_VES
6482 case MARSHAL_ACTION_CONV_IN:
6483 *conv_arg_type = &mono_defaults.object_class->byval_arg;
6485 case MARSHAL_ACTION_MANAGED_CONV_IN:
6486 *conv_arg_type = &mono_defaults.int_class->byval_arg;
6490 MonoMethodBuilder *mb = m->mb;
6491 MonoClass *klass = mono_class_from_mono_type (t);
6492 gboolean need_convert, need_free;
6493 MonoMarshalNative encoding;
6495 encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
6498 case MARSHAL_ACTION_CONV_IN:
6499 *conv_arg_type = &mono_defaults.object_class->byval_arg;
6500 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6502 if (klass->element_class->blittable) {
6503 mono_mb_emit_ldarg (mb, argnum);
6505 mono_mb_emit_byte (mb, CEE_LDIND_I);
6506 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_ARRAY_LPARRAY, NULL));
6507 mono_mb_emit_stloc (mb, conv_arg);
6510 guint32 label1, label2, label3;
6511 int index_var, src_var, dest_ptr, esize;
6512 MonoMarshalConv conv;
6513 gboolean is_string = FALSE;
6515 dest_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6517 eklass = klass->element_class;
6519 if (eklass == mono_defaults.string_class) {
6521 conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
6523 else if (eklass == mono_defaults.stringbuilder_class) {
6525 conv = mono_marshal_get_stringbuilder_to_ptr_conv (m->piinfo, spec);
6528 conv = MONO_MARSHAL_CONV_INVALID;
6530 if (is_string && conv == MONO_MARSHAL_CONV_INVALID) {
6531 char *msg = g_strdup_printf ("string/stringbuilder marshalling conversion %d not implemented", encoding);
6532 mono_mb_emit_exception_marshal_directive (mb, msg);
6536 src_var = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6537 mono_mb_emit_ldarg (mb, argnum);
6539 mono_mb_emit_byte (mb, CEE_LDIND_I);
6540 mono_mb_emit_stloc (mb, src_var);
6543 mono_mb_emit_ldloc (mb, src_var);
6544 mono_mb_emit_stloc (mb, conv_arg);
6545 mono_mb_emit_ldloc (mb, src_var);
6546 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6549 esize = sizeof (gpointer);
6550 else if (eklass == mono_defaults.char_class) /*can't call mono_marshal_type_size since it causes all sorts of asserts*/
6551 esize = mono_pinvoke_is_unicode (m->piinfo) ? 2 : 1;
6553 esize = mono_class_native_size (eklass, NULL);
6555 /* allocate space for the native struct and store the address */
6556 mono_mb_emit_icon (mb, esize);
6557 mono_mb_emit_ldloc (mb, src_var);
6558 mono_mb_emit_byte (mb, CEE_LDLEN);
6560 if (eklass == mono_defaults.string_class) {
6561 /* Make the array bigger for the terminating null */
6562 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
6563 mono_mb_emit_byte (mb, CEE_ADD);
6565 mono_mb_emit_byte (mb, CEE_MUL);
6566 mono_mb_emit_byte (mb, CEE_PREFIX1);
6567 mono_mb_emit_byte (mb, CEE_LOCALLOC);
6568 mono_mb_emit_stloc (mb, conv_arg);
6570 mono_mb_emit_ldloc (mb, conv_arg);
6571 mono_mb_emit_stloc (mb, dest_ptr);
6573 /* Emit marshalling loop */
6574 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6575 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6576 mono_mb_emit_stloc (mb, index_var);
6577 label2 = mono_mb_get_label (mb);
6578 mono_mb_emit_ldloc (mb, index_var);
6579 mono_mb_emit_ldloc (mb, src_var);
6580 mono_mb_emit_byte (mb, CEE_LDLEN);
6581 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6583 /* Emit marshalling code */
6587 mono_mb_emit_ldloc (mb, dest_ptr);
6588 mono_mb_emit_ldloc (mb, src_var);
6589 mono_mb_emit_ldloc (mb, index_var);
6590 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
6591 mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
6592 mono_mb_emit_byte (mb, stind_op);
6594 /* set the src_ptr */
6595 mono_mb_emit_ldloc (mb, src_var);
6596 mono_mb_emit_ldloc (mb, index_var);
6597 mono_mb_emit_op (mb, CEE_LDELEMA, eklass);
6598 mono_mb_emit_stloc (mb, 0);
6601 mono_mb_emit_ldloc (mb, dest_ptr);
6602 mono_mb_emit_stloc (mb, 1);
6604 /* emit valuetype conversion code */
6605 emit_struct_conv_full (mb, eklass, FALSE, 0, eklass == mono_defaults.char_class ? encoding : (MonoMarshalNative)-1);
6608 mono_mb_emit_add_to_local (mb, index_var, 1);
6609 mono_mb_emit_add_to_local (mb, dest_ptr, esize);
6611 mono_mb_emit_branch_label (mb, CEE_BR, label2);
6613 mono_mb_patch_branch (mb, label3);
6615 if (eklass == mono_defaults.string_class) {
6616 /* Null terminate */
6617 mono_mb_emit_ldloc (mb, dest_ptr);
6618 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6619 mono_mb_emit_byte (mb, CEE_STIND_REF);
6622 mono_mb_patch_branch (mb, label1);
6627 case MARSHAL_ACTION_CONV_OUT:
6628 /* Unicode character arrays are implicitly marshalled as [Out] under MS.NET */
6629 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);
6630 need_free = mono_marshal_need_free (&klass->element_class->byval_arg,
6633 if ((t->attrs & PARAM_ATTRIBUTE_OUT) && spec && spec->native == MONO_NATIVE_LPARRAY && spec->data.array_data.param_num != -1) {
6634 int param_num = spec->data.array_data.param_num;
6635 MonoType *param_type;
6637 param_type = m->sig->params [param_num];
6639 if (param_type->byref && param_type->type != MONO_TYPE_I4) {
6640 char *msg = g_strdup ("Not implemented.");
6641 mono_mb_emit_exception_marshal_directive (mb, msg);
6646 mono_mb_emit_ldarg (mb, argnum);
6648 /* Create the managed array */
6649 mono_mb_emit_ldarg (mb, param_num);
6650 if (m->sig->params [param_num]->byref)
6651 // FIXME: Support other types
6652 mono_mb_emit_byte (mb, CEE_LDIND_I4);
6653 mono_mb_emit_byte (mb, CEE_CONV_OVF_I);
6654 mono_mb_emit_op (mb, CEE_NEWARR, klass->element_class);
6655 /* Store into argument */
6656 mono_mb_emit_byte (mb, CEE_STIND_REF);
6660 if (need_convert || need_free) {
6661 /* FIXME: Optimize blittable case */
6663 guint32 label1, label2, label3;
6664 int index_var, src_ptr, loc, esize;
6666 eklass = klass->element_class;
6667 if ((eklass == mono_defaults.stringbuilder_class) || (eklass == mono_defaults.string_class))
6668 esize = sizeof (gpointer);
6669 else if (eklass == mono_defaults.char_class)
6670 esize = mono_pinvoke_is_unicode (m->piinfo) ? 2 : 1;
6672 esize = mono_class_native_size (eklass, NULL);
6673 src_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6674 loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6677 mono_mb_emit_ldarg (mb, argnum);
6679 mono_mb_emit_byte (mb, CEE_LDIND_I);
6680 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6682 mono_mb_emit_ldloc (mb, conv_arg);
6683 mono_mb_emit_stloc (mb, src_ptr);
6685 /* Emit marshalling loop */
6686 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6687 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6688 mono_mb_emit_stloc (mb, index_var);
6689 label2 = mono_mb_get_label (mb);
6690 mono_mb_emit_ldloc (mb, index_var);
6691 mono_mb_emit_ldarg (mb, argnum);
6693 mono_mb_emit_byte (mb, CEE_LDIND_REF);
6694 mono_mb_emit_byte (mb, CEE_LDLEN);
6695 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6697 /* Emit marshalling code */
6699 if (eklass == mono_defaults.stringbuilder_class) {
6700 gboolean need_free2;
6701 MonoMarshalConv conv = mono_marshal_get_ptr_to_stringbuilder_conv (m->piinfo, spec, &need_free2);
6703 g_assert (conv != MONO_MARSHAL_CONV_INVALID);
6706 mono_mb_emit_ldarg (mb, argnum);
6708 mono_mb_emit_byte (mb, CEE_LDIND_I);
6709 mono_mb_emit_ldloc (mb, index_var);
6710 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
6713 mono_mb_emit_ldloc (mb, src_ptr);
6714 mono_mb_emit_byte (mb, CEE_LDIND_I);
6716 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
6720 mono_mb_emit_ldloc (mb, src_ptr);
6721 mono_mb_emit_byte (mb, CEE_LDIND_I);
6723 mono_mb_emit_icall (mb, mono_marshal_free);
6726 else if (eklass == mono_defaults.string_class) {
6729 mono_mb_emit_ldloc (mb, src_ptr);
6730 mono_mb_emit_byte (mb, CEE_LDIND_I);
6732 mono_mb_emit_icall (mb, mono_marshal_free);
6737 /* set the src_ptr */
6738 mono_mb_emit_ldloc (mb, src_ptr);
6739 mono_mb_emit_stloc (mb, 0);
6742 mono_mb_emit_ldarg (mb, argnum);
6744 mono_mb_emit_byte (mb, CEE_LDIND_REF);
6745 mono_mb_emit_ldloc (mb, index_var);
6746 mono_mb_emit_op (mb, CEE_LDELEMA, eklass);
6747 mono_mb_emit_stloc (mb, 1);
6749 /* emit valuetype conversion code */
6750 emit_struct_conv_full (mb, eklass, TRUE, 0, eklass == mono_defaults.char_class ? encoding : (MonoMarshalNative)-1);
6754 mono_mb_emit_ldloc (mb, src_ptr);
6755 mono_mb_emit_stloc (mb, loc);
6756 mono_mb_emit_ldloc (mb, loc);
6758 emit_struct_free (mb, eklass, loc);
6762 mono_mb_emit_add_to_local (mb, index_var, 1);
6763 mono_mb_emit_add_to_local (mb, src_ptr, esize);
6765 mono_mb_emit_branch_label (mb, CEE_BR, label2);
6767 mono_mb_patch_branch (mb, label1);
6768 mono_mb_patch_branch (mb, label3);
6771 if (klass->element_class->blittable) {
6772 /* free memory allocated (if any) by MONO_MARSHAL_CONV_ARRAY_LPARRAY */
6774 mono_mb_emit_ldarg (mb, argnum);
6776 mono_mb_emit_byte (mb, CEE_LDIND_REF);
6777 mono_mb_emit_ldloc (mb, conv_arg);
6778 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_FREE_LPARRAY, NULL));
6783 case MARSHAL_ACTION_PUSH:
6785 mono_mb_emit_ldloc_addr (mb, conv_arg);
6787 mono_mb_emit_ldloc (mb, conv_arg);
6790 case MARSHAL_ACTION_CONV_RESULT:
6791 /* fixme: we need conversions here */
6792 mono_mb_emit_stloc (mb, 3);
6795 case MARSHAL_ACTION_MANAGED_CONV_IN: {
6797 guint32 label1, label2, label3;
6798 int index_var, src_ptr, esize, param_num, num_elem;
6799 MonoMarshalConv conv;
6800 gboolean is_string = FALSE;
6802 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6803 *conv_arg_type = &mono_defaults.int_class->byval_arg;
6806 char *msg = g_strdup ("Byref array marshalling to managed code is not implemented.");
6807 mono_mb_emit_exception_marshal_directive (mb, msg);
6811 char *msg = g_strdup ("[MarshalAs] attribute required to marshal arrays to managed code.");
6812 mono_mb_emit_exception_marshal_directive (mb, msg);
6815 if (spec->native != MONO_NATIVE_LPARRAY) {
6816 char *msg = g_strdup ("Non LPArray marshalling of arrays to managed code is not implemented.");
6817 mono_mb_emit_exception_marshal_directive (mb, msg);
6821 /* FIXME: t is from the method which is wrapped, not the delegate type */
6822 /* g_assert (t->attrs & PARAM_ATTRIBUTE_IN); */
6824 param_num = spec->data.array_data.param_num;
6825 num_elem = spec->data.array_data.num_elem;
6826 if (spec->data.array_data.elem_mult == 0)
6827 /* param_num is not specified */
6830 if (param_num == -1) {
6831 if (num_elem <= 0) {
6832 char *msg = g_strdup ("Either SizeConst or SizeParamIndex should be specified when marshalling arrays to managed code.");
6833 mono_mb_emit_exception_marshal_directive (mb, msg);
6838 /* FIXME: Optimize blittable case */
6840 eklass = klass->element_class;
6841 if (eklass == mono_defaults.string_class) {
6843 conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
6845 else if (eklass == mono_defaults.stringbuilder_class) {
6847 conv = mono_marshal_get_ptr_to_stringbuilder_conv (m->piinfo, spec, &need_free);
6850 conv = MONO_MARSHAL_CONV_INVALID;
6852 mono_marshal_load_type_info (eklass);
6855 esize = sizeof (gpointer);
6857 esize = mono_class_native_size (eklass, NULL);
6858 src_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6860 mono_mb_emit_byte (mb, CEE_LDNULL);
6861 mono_mb_emit_stloc (mb, conv_arg);
6863 /* Check param index */
6864 if (param_num != -1) {
6865 if (param_num >= m->sig->param_count) {
6866 char *msg = g_strdup ("Array size control parameter index is out of range.");
6867 mono_mb_emit_exception_marshal_directive (mb, msg);
6870 switch (m->sig->params [param_num]->type) {
6883 char *msg = g_strdup ("Array size control parameter must be an integral type.");
6884 mono_mb_emit_exception_marshal_directive (mb, msg);
6891 mono_mb_emit_ldarg (mb, argnum);
6892 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6894 mono_mb_emit_ldarg (mb, argnum);
6895 mono_mb_emit_stloc (mb, src_ptr);
6897 /* Create managed array */
6899 * The LPArray marshalling spec says that sometimes param_num starts
6900 * from 1, sometimes it starts from 0. But MS seems to allways start
6904 if (param_num == -1) {
6905 mono_mb_emit_icon (mb, num_elem);
6907 mono_mb_emit_ldarg (mb, param_num);
6909 mono_mb_emit_icon (mb, num_elem);
6910 mono_mb_emit_byte (mb, CEE_ADD);
6912 mono_mb_emit_byte (mb, CEE_CONV_OVF_I);
6915 mono_mb_emit_op (mb, CEE_NEWARR, eklass);
6916 mono_mb_emit_stloc (mb, conv_arg);
6918 if (eklass->blittable) {
6919 mono_mb_emit_ldloc (mb, conv_arg);
6920 mono_mb_emit_byte (mb, CEE_CONV_I);
6921 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
6922 mono_mb_emit_byte (mb, CEE_ADD);
6923 mono_mb_emit_ldarg (mb, argnum);
6924 mono_mb_emit_ldloc (mb, conv_arg);
6925 mono_mb_emit_byte (mb, CEE_LDLEN);
6926 mono_mb_emit_icon (mb, esize);
6927 mono_mb_emit_byte (mb, CEE_MUL);
6928 mono_mb_emit_byte (mb, CEE_PREFIX1);
6929 mono_mb_emit_byte (mb, CEE_CPBLK);
6930 mono_mb_patch_branch (mb, label1);
6934 /* Emit marshalling loop */
6935 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6936 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6937 mono_mb_emit_stloc (mb, index_var);
6938 label2 = mono_mb_get_label (mb);
6939 mono_mb_emit_ldloc (mb, index_var);
6940 mono_mb_emit_ldloc (mb, conv_arg);
6941 mono_mb_emit_byte (mb, CEE_LDLEN);
6942 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6944 /* Emit marshalling code */
6946 g_assert (conv != MONO_MARSHAL_CONV_INVALID);
6948 mono_mb_emit_ldloc (mb, conv_arg);
6949 mono_mb_emit_ldloc (mb, index_var);
6951 mono_mb_emit_ldloc (mb, src_ptr);
6952 mono_mb_emit_byte (mb, CEE_LDIND_I);
6954 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
6955 mono_mb_emit_byte (mb, CEE_STELEM_REF);
6958 char *msg = g_strdup ("Marshalling of non-string and non-blittable arrays to managed code is not implemented.");
6959 mono_mb_emit_exception_marshal_directive (mb, msg);
6963 mono_mb_emit_add_to_local (mb, index_var, 1);
6964 mono_mb_emit_add_to_local (mb, src_ptr, esize);
6966 mono_mb_emit_branch_label (mb, CEE_BR, label2);
6968 mono_mb_patch_branch (mb, label1);
6969 mono_mb_patch_branch (mb, label3);
6973 case MARSHAL_ACTION_MANAGED_CONV_OUT: {
6975 guint32 label1, label2, label3;
6976 int index_var, dest_ptr, esize, param_num, num_elem;
6977 MonoMarshalConv conv;
6978 gboolean is_string = FALSE;
6981 /* Already handled in CONV_IN */
6984 /* These are already checked in CONV_IN */
6985 g_assert (!t->byref);
6986 g_assert (spec->native == MONO_NATIVE_LPARRAY);
6987 g_assert (t->attrs & PARAM_ATTRIBUTE_OUT);
6989 param_num = spec->data.array_data.param_num;
6990 num_elem = spec->data.array_data.num_elem;
6992 if (spec->data.array_data.elem_mult == 0)
6993 /* param_num is not specified */
6996 if (param_num == -1) {
6997 if (num_elem <= 0) {
6998 g_assert_not_reached ();
7002 /* FIXME: Optimize blittable case */
7004 eklass = klass->element_class;
7005 if (eklass == mono_defaults.string_class) {
7007 conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
7009 else if (eklass == mono_defaults.stringbuilder_class) {
7011 conv = mono_marshal_get_stringbuilder_to_ptr_conv (m->piinfo, spec);
7014 conv = MONO_MARSHAL_CONV_INVALID;
7016 mono_marshal_load_type_info (eklass);
7019 esize = sizeof (gpointer);
7021 esize = mono_class_native_size (eklass, NULL);
7023 dest_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7026 mono_mb_emit_ldloc (mb, conv_arg);
7027 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
7029 mono_mb_emit_ldarg (mb, argnum);
7030 mono_mb_emit_stloc (mb, dest_ptr);
7032 if (eklass->blittable) {
7034 mono_mb_emit_ldarg (mb, argnum);
7036 mono_mb_emit_ldloc (mb, conv_arg);
7037 mono_mb_emit_byte (mb, CEE_CONV_I);
7038 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
7039 mono_mb_emit_byte (mb, CEE_ADD);
7041 mono_mb_emit_ldloc (mb, conv_arg);
7042 mono_mb_emit_byte (mb, CEE_LDLEN);
7043 mono_mb_emit_icon (mb, esize);
7044 mono_mb_emit_byte (mb, CEE_MUL);
7045 mono_mb_emit_byte (mb, CEE_PREFIX1);
7046 mono_mb_emit_byte (mb, CEE_CPBLK);
7050 /* Emit marshalling loop */
7051 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7052 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
7053 mono_mb_emit_stloc (mb, index_var);
7054 label2 = mono_mb_get_label (mb);
7055 mono_mb_emit_ldloc (mb, index_var);
7056 mono_mb_emit_ldloc (mb, conv_arg);
7057 mono_mb_emit_byte (mb, CEE_LDLEN);
7058 label3 = mono_mb_emit_branch (mb, CEE_BGE);
7060 /* Emit marshalling code */
7063 g_assert (conv != MONO_MARSHAL_CONV_INVALID);
7066 mono_mb_emit_ldloc (mb, dest_ptr);
7069 mono_mb_emit_ldloc (mb, conv_arg);
7070 mono_mb_emit_ldloc (mb, index_var);
7072 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
7074 mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
7075 mono_mb_emit_byte (mb, stind_op);
7078 char *msg = g_strdup ("Marshalling of non-string and non-blittable arrays to managed code is not implemented.");
7079 mono_mb_emit_exception_marshal_directive (mb, msg);
7083 mono_mb_emit_add_to_local (mb, index_var, 1);
7084 mono_mb_emit_add_to_local (mb, dest_ptr, esize);
7086 mono_mb_emit_branch_label (mb, CEE_BR, label2);
7088 mono_mb_patch_branch (mb, label1);
7089 mono_mb_patch_branch (mb, label3);
7093 case MARSHAL_ACTION_MANAGED_CONV_RESULT: {
7095 guint32 label1, label2, label3;
7096 int index_var, src, dest, esize;
7097 MonoMarshalConv conv = MONO_MARSHAL_CONV_INVALID;
7098 gboolean is_string = FALSE;
7100 g_assert (!t->byref);
7102 eklass = klass->element_class;
7104 mono_marshal_load_type_info (eklass);
7106 if (eklass == mono_defaults.string_class) {
7108 conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
7111 g_assert_not_reached ();
7115 esize = sizeof (gpointer);
7116 else if (eklass == mono_defaults.char_class)
7117 esize = mono_pinvoke_is_unicode (m->piinfo) ? 2 : 1;
7119 esize = mono_class_native_size (eklass, NULL);
7121 src = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
7122 dest = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7124 mono_mb_emit_stloc (mb, src);
7125 mono_mb_emit_ldloc (mb, src);
7126 mono_mb_emit_stloc (mb, 3);
7128 /* Check for null */
7129 mono_mb_emit_ldloc (mb, src);
7130 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
7132 /* Allocate native array */
7133 mono_mb_emit_icon (mb, esize);
7134 mono_mb_emit_ldloc (mb, src);
7135 mono_mb_emit_byte (mb, CEE_LDLEN);
7137 if (eklass == mono_defaults.string_class) {
7138 /* Make the array bigger for the terminating null */
7139 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
7140 mono_mb_emit_byte (mb, CEE_ADD);
7142 mono_mb_emit_byte (mb, CEE_MUL);
7143 mono_mb_emit_icall (mb, ves_icall_marshal_alloc);
7144 mono_mb_emit_stloc (mb, dest);
7145 mono_mb_emit_ldloc (mb, dest);
7146 mono_mb_emit_stloc (mb, 3);
7148 /* Emit marshalling loop */
7149 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7150 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
7151 mono_mb_emit_stloc (mb, index_var);
7152 label2 = mono_mb_get_label (mb);
7153 mono_mb_emit_ldloc (mb, index_var);
7154 mono_mb_emit_ldloc (mb, src);
7155 mono_mb_emit_byte (mb, CEE_LDLEN);
7156 label3 = mono_mb_emit_branch (mb, CEE_BGE);
7158 /* Emit marshalling code */
7161 g_assert (conv != MONO_MARSHAL_CONV_INVALID);
7164 mono_mb_emit_ldloc (mb, dest);
7167 mono_mb_emit_ldloc (mb, src);
7168 mono_mb_emit_ldloc (mb, index_var);
7170 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
7172 mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
7173 mono_mb_emit_byte (mb, stind_op);
7176 char *msg = g_strdup ("Marshalling of non-string arrays to managed code is not implemented.");
7177 mono_mb_emit_exception_marshal_directive (mb, msg);
7181 mono_mb_emit_add_to_local (mb, index_var, 1);
7182 mono_mb_emit_add_to_local (mb, dest, esize);
7184 mono_mb_emit_branch_label (mb, CEE_BR, label2);
7186 mono_mb_patch_branch (mb, label3);
7187 mono_mb_patch_branch (mb, label1);
7191 g_assert_not_reached ();
7198 marshal_boolean_conv_in_get_local_type (MonoMarshalSpec *spec, guint8 *ldc_op /*out*/)
7201 return &mono_defaults.int32_class->byval_arg;
7203 switch (spec->native) {
7204 case MONO_NATIVE_I1:
7205 case MONO_NATIVE_U1:
7206 return &mono_defaults.byte_class->byval_arg;
7207 case MONO_NATIVE_VARIANTBOOL:
7208 if (ldc_op) *ldc_op = CEE_LDC_I4_M1;
7209 return &mono_defaults.int16_class->byval_arg;
7210 case MONO_NATIVE_BOOLEAN:
7211 return &mono_defaults.int32_class->byval_arg;
7213 g_warning ("marshalling bool as native type %x is currently not supported", spec->native);
7214 return &mono_defaults.int32_class->byval_arg;
7220 marshal_boolean_managed_conv_in_get_conv_arg_class (MonoMarshalSpec *spec, guint8 *ldop/*out*/)
7222 MonoClass* conv_arg_class = mono_defaults.int32_class;
7224 switch (spec->native) {
7225 case MONO_NATIVE_I1:
7226 case MONO_NATIVE_U1:
7227 conv_arg_class = mono_defaults.byte_class;
7228 if (ldop) *ldop = CEE_LDIND_I1;
7230 case MONO_NATIVE_VARIANTBOOL:
7231 conv_arg_class = mono_defaults.int16_class;
7232 if (ldop) *ldop = CEE_LDIND_I2;
7234 case MONO_NATIVE_BOOLEAN:
7237 g_warning ("marshalling bool as native type %x is currently not supported", spec->native);
7240 return conv_arg_class;
7244 emit_marshal_boolean (EmitMarshalContext *m, int argnum, MonoType *t,
7245 MonoMarshalSpec *spec,
7246 int conv_arg, MonoType **conv_arg_type,
7247 MarshalAction action)
7249 #ifndef HAVE_ONLINE_VES
7251 case MARSHAL_ACTION_CONV_IN:
7253 *conv_arg_type = &mono_defaults.int_class->byval_arg;
7255 *conv_arg_type = marshal_boolean_conv_in_get_local_type (spec, NULL);
7258 case MARSHAL_ACTION_MANAGED_CONV_IN: {
7259 MonoClass* conv_arg_class = marshal_boolean_managed_conv_in_get_conv_arg_class (spec, NULL);
7261 *conv_arg_type = &conv_arg_class->this_arg;
7263 *conv_arg_type = &conv_arg_class->byval_arg;
7269 MonoMethodBuilder *mb = m->mb;
7272 case MARSHAL_ACTION_CONV_IN: {
7273 MonoType *local_type;
7275 guint8 ldc_op = CEE_LDC_I4_1;
7277 local_type = marshal_boolean_conv_in_get_local_type (spec, &ldc_op);
7279 *conv_arg_type = &mono_defaults.int_class->byval_arg;
7281 *conv_arg_type = local_type;
7282 conv_arg = mono_mb_add_local (mb, local_type);
7284 mono_mb_emit_ldarg (mb, argnum);
7286 mono_mb_emit_byte (mb, CEE_LDIND_I1);
7287 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
7288 mono_mb_emit_byte (mb, ldc_op);
7289 mono_mb_emit_stloc (mb, conv_arg);
7290 mono_mb_patch_branch (mb, label_false);
7295 case MARSHAL_ACTION_CONV_OUT:
7297 int label_false, label_end;
7301 mono_mb_emit_ldarg (mb, argnum);
7302 mono_mb_emit_ldloc (mb, conv_arg);
7304 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
7305 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
7307 label_end = mono_mb_emit_branch (mb, CEE_BR);
7308 mono_mb_patch_branch (mb, label_false);
7309 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
7310 mono_mb_patch_branch (mb, label_end);
7312 mono_mb_emit_byte (mb, CEE_STIND_I1);
7316 case MARSHAL_ACTION_PUSH:
7318 mono_mb_emit_ldloc_addr (mb, conv_arg);
7320 mono_mb_emit_ldloc (mb, conv_arg);
7322 mono_mb_emit_ldarg (mb, argnum);
7325 case MARSHAL_ACTION_CONV_RESULT:
7326 /* maybe we need to make sure that it fits within 8 bits */
7327 mono_mb_emit_stloc (mb, 3);
7330 case MARSHAL_ACTION_MANAGED_CONV_IN: {
7331 MonoClass* conv_arg_class = mono_defaults.int32_class;
7332 guint8 ldop = CEE_LDIND_I4;
7333 int label_null, label_false;
7335 conv_arg_class = marshal_boolean_managed_conv_in_get_conv_arg_class (spec, &ldop);
7336 conv_arg = mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
7339 *conv_arg_type = &conv_arg_class->this_arg;
7341 *conv_arg_type = &conv_arg_class->byval_arg;
7344 mono_mb_emit_ldarg (mb, argnum);
7348 label_null = mono_mb_emit_branch (mb, CEE_BRFALSE);
7349 mono_mb_emit_ldarg (mb, argnum);
7350 mono_mb_emit_byte (mb, ldop);
7354 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
7355 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
7356 mono_mb_emit_stloc (mb, conv_arg);
7357 mono_mb_patch_branch (mb, label_false);
7360 mono_mb_patch_branch (mb, label_null);
7364 case MARSHAL_ACTION_MANAGED_CONV_OUT: {
7365 guint8 stop = CEE_STIND_I4;
7366 guint8 ldc_op = CEE_LDC_I4_1;
7367 int label_null,label_false, label_end;;
7372 switch (spec->native) {
7373 case MONO_NATIVE_I1:
7374 case MONO_NATIVE_U1:
7375 stop = CEE_STIND_I1;
7377 case MONO_NATIVE_VARIANTBOOL:
7378 stop = CEE_STIND_I2;
7379 ldc_op = CEE_LDC_I4_M1;
7387 mono_mb_emit_ldarg (mb, argnum);
7388 label_null = mono_mb_emit_branch (mb, CEE_BRFALSE);
7390 mono_mb_emit_ldarg (mb, argnum);
7391 mono_mb_emit_ldloc (mb, conv_arg);
7393 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
7394 mono_mb_emit_byte (mb, ldc_op);
7395 label_end = mono_mb_emit_branch (mb, CEE_BR);
7397 mono_mb_patch_branch (mb, label_false);
7398 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
7399 mono_mb_patch_branch (mb, label_end);
7401 mono_mb_emit_byte (mb, stop);
7402 mono_mb_patch_branch (mb, label_null);
7407 g_assert_not_reached ();
7414 emit_marshal_ptr (EmitMarshalContext *m, int argnum, MonoType *t,
7415 MonoMarshalSpec *spec, int conv_arg,
7416 MonoType **conv_arg_type, MarshalAction action)
7418 #ifdef HAVE_ONLINE_VES
7419 MonoMethodBuilder *mb = m->mb;
7422 case MARSHAL_ACTION_CONV_IN:
7423 /* MS seems to allow this in some cases, ie. bxc #158 */
7425 if (MONO_TYPE_ISSTRUCT (t->data.type) && !mono_class_from_mono_type (t->data.type)->blittable) {
7426 char *msg = g_strdup_printf ("Can not marshal 'parameter #%d': Pointers can not reference marshaled structures. Use byref instead.", argnum + 1);
7427 mono_mb_emit_exception_marshal_directive (m->mb, msg);
7432 case MARSHAL_ACTION_PUSH:
7433 mono_mb_emit_ldarg (mb, argnum);
7436 case MARSHAL_ACTION_CONV_RESULT:
7437 /* no conversions necessary */
7438 mono_mb_emit_stloc (mb, 3);
7449 emit_marshal_char (EmitMarshalContext *m, int argnum, MonoType *t,
7450 MonoMarshalSpec *spec, int conv_arg,
7451 MonoType **conv_arg_type, MarshalAction action)
7453 #ifdef HAVE_ONLINE_VES
7454 MonoMethodBuilder *mb = m->mb;
7457 case MARSHAL_ACTION_PUSH:
7458 /* fixme: dont know how to marshal that. We cant simply
7459 * convert it to a one byte UTF8 character, because an
7460 * unicode character may need more that one byte in UTF8 */
7461 mono_mb_emit_ldarg (mb, argnum);
7464 case MARSHAL_ACTION_CONV_RESULT:
7465 /* fixme: we need conversions here */
7466 mono_mb_emit_stloc (mb, 3);
7477 emit_marshal_scalar (EmitMarshalContext *m, int argnum, MonoType *t,
7478 MonoMarshalSpec *spec, int conv_arg,
7479 MonoType **conv_arg_type, MarshalAction action)
7481 #ifdef HAVE_ONLINE_VES
7482 MonoMethodBuilder *mb = m->mb;
7485 case MARSHAL_ACTION_PUSH:
7486 mono_mb_emit_ldarg (mb, argnum);
7489 case MARSHAL_ACTION_CONV_RESULT:
7490 /* no conversions necessary */
7491 mono_mb_emit_stloc (mb, 3);
7502 emit_marshal (EmitMarshalContext *m, int argnum, MonoType *t,
7503 MonoMarshalSpec *spec, int conv_arg,
7504 MonoType **conv_arg_type, MarshalAction action)
7506 /* Ensure that we have marshalling info for this param */
7507 mono_marshal_load_type_info (mono_class_from_mono_type (t));
7509 if (spec && spec->native == MONO_NATIVE_CUSTOM)
7510 return emit_marshal_custom (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7512 if (spec && spec->native == MONO_NATIVE_ASANY)
7513 return emit_marshal_asany (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7516 case MONO_TYPE_VALUETYPE:
7517 if (t->data.klass == mono_defaults.handleref_class)
7518 return emit_marshal_handleref (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7520 return emit_marshal_vtype (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7521 case MONO_TYPE_STRING:
7522 return emit_marshal_string (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7523 case MONO_TYPE_CLASS:
7524 case MONO_TYPE_OBJECT:
7525 #if !defined(DISABLE_COM) && defined(HAVE_ONLINE_VES)
7526 if (spec && spec->native == MONO_NATIVE_STRUCT)
7527 return emit_marshal_variant (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7530 #if !defined(DISABLE_COM)
7531 if (spec && (spec->native == MONO_NATIVE_IUNKNOWN ||
7532 spec->native == MONO_NATIVE_IDISPATCH ||
7533 spec->native == MONO_NATIVE_INTERFACE))
7534 return mono_cominterop_emit_marshal_com_interface (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7535 if (spec && (spec->native == MONO_NATIVE_SAFEARRAY) &&
7536 (spec->data.safearray_data.elem_type == MONO_VARIANT_VARIANT) &&
7537 ((action == MARSHAL_ACTION_CONV_OUT) || (action == MARSHAL_ACTION_CONV_IN) || (action == MARSHAL_ACTION_PUSH)))
7538 return mono_cominterop_emit_marshal_safearray (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7541 if (mono_class_try_get_safehandle_class () != NULL && t->data.klass &&
7542 mono_class_is_subclass_of (t->data.klass, mono_class_try_get_safehandle_class (), FALSE))
7543 return emit_marshal_safehandle (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7545 return emit_marshal_object (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7546 case MONO_TYPE_ARRAY:
7547 case MONO_TYPE_SZARRAY:
7548 return emit_marshal_array (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7549 case MONO_TYPE_BOOLEAN:
7550 return emit_marshal_boolean (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7552 return emit_marshal_ptr (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7553 case MONO_TYPE_CHAR:
7554 return emit_marshal_char (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7567 case MONO_TYPE_FNPTR:
7568 return emit_marshal_scalar (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7569 case MONO_TYPE_GENERICINST:
7570 if (mono_type_generic_inst_is_valuetype (t))
7571 return emit_marshal_vtype (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7573 return emit_marshal_object (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7579 /* How the arguments of an icall should be wrapped */
7581 /* Don't wrap at all, pass the argument as is */
7582 ICALL_HANDLES_WRAP_NONE,
7583 /* Wrap the argument in an object handle, pass the handle to the icall */
7584 ICALL_HANDLES_WRAP_OBJ,
7585 /* Wrap the argument in an object handle, pass the handle to the icall,
7586 write the value out from the handle when the icall returns */
7587 ICALL_HANDLES_WRAP_OBJ_INOUT,
7588 /* Initialized an object handle to null, pass to the icalls,
7589 write the value out from the handle when the icall returns */
7590 ICALL_HANDLES_WRAP_OBJ_OUT,
7591 /* Wrap the argument (a valuetype reference) in a handle to pin its enclosing object,
7592 but pass the raw reference to the icall */
7593 ICALL_HANDLES_WRAP_VALUETYPE_REF,
7597 IcallHandlesWrap wrap;
7598 /* if wrap is NONE or OBJ or VALUETYPE_REF, this is not meaningful.
7599 if wrap is OBJ_INOUT it's the local var that holds the MonoObjectHandle.
7602 } IcallHandlesLocal;
7605 * Describes how to wrap the given parameter.
7608 static IcallHandlesWrap
7609 signature_param_uses_handles (MonoMethodSignature *sig, int param)
7611 if (MONO_TYPE_IS_REFERENCE (sig->params [param])) {
7612 if (mono_signature_param_is_out (sig, param))
7613 return ICALL_HANDLES_WRAP_OBJ_OUT;
7614 else if (mono_type_is_byref (sig->params [param]))
7615 return ICALL_HANDLES_WRAP_OBJ_INOUT;
7617 return ICALL_HANDLES_WRAP_OBJ;
7618 } else if (mono_type_is_byref (sig->params [param]))
7619 return ICALL_HANDLES_WRAP_VALUETYPE_REF;
7621 return ICALL_HANDLES_WRAP_NONE;
7625 #ifdef HAVE_ONLINE_VES
7627 * mono_marshal_emit_native_wrapper:
7628 * \param image the image to use for looking up custom marshallers
7629 * \param sig The signature of the native function
7630 * \param piinfo Marshalling information
7631 * \param mspecs Marshalling information
7632 * \param aot whenever the created method will be compiled by the AOT compiler
7633 * \param method if non-NULL, the pinvoke method to call
7634 * \param check_exceptions Whenever to check for pending exceptions after the native call
7635 * \param func_param the function to call is passed as a boxed IntPtr as the first parameter
7637 * generates IL code for the pinvoke wrapper, the generated code calls \p func .
7640 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)
7642 EmitMarshalContext m;
7643 MonoMethodSignature *csig;
7645 int i, argnum, *tmp_locals;
7646 int type, param_shift = 0;
7647 int coop_gc_stack_dummy, coop_gc_var;
7649 memset (&m, 0, sizeof (m));
7654 /* we copy the signature, so that we can set pinvoke to 0 */
7656 /* The function address is passed as the first argument */
7657 g_assert (!sig->hasthis);
7660 csig = mono_metadata_signature_dup_full (mb->method->klass->image, sig);
7668 /* we allocate local for use with emit_struct_conv() */
7669 /* allocate local 0 (pointer) src_ptr */
7670 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7671 /* allocate local 1 (pointer) dst_ptr */
7672 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7673 /* allocate local 2 (boolean) delete_old */
7674 mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
7676 /* delete_old = FALSE */
7677 mono_mb_emit_icon (mb, 0);
7678 mono_mb_emit_stloc (mb, 2);
7680 if (!MONO_TYPE_IS_VOID (sig->ret)) {
7681 /* allocate local 3 to store the return value */
7682 mono_mb_add_local (mb, sig->ret);
7685 if (mono_threads_is_coop_enabled ()) {
7686 /* local 4, dummy local used to get a stack address for suspend funcs */
7687 coop_gc_stack_dummy = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7688 /* local 5, the local to be used when calling the suspend funcs */
7689 coop_gc_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7693 * cookie = mono_threads_enter_gc_safe_region_unbalanced (ref dummy);
7695 * ret = method (...);
7697 * mono_threads_exit_gc_safe_region_unbalanced (cookie, ref dummy);
7704 if (MONO_TYPE_ISSTRUCT (sig->ret))
7705 m.vtaddr_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7707 if (mspecs [0] && mspecs [0]->native == MONO_NATIVE_CUSTOM) {
7708 /* Return type custom marshaling */
7710 * Since we can't determine the return type of the unmanaged function,
7711 * we assume it returns a pointer, and pass that pointer to
7712 * MarshalNativeToManaged.
7714 csig->ret = &mono_defaults.int_class->byval_arg;
7717 /* we first do all conversions */
7718 tmp_locals = (int *)alloca (sizeof (int) * sig->param_count);
7719 m.orig_conv_args = (int *)alloca (sizeof (int) * (sig->param_count + 1));
7721 for (i = 0; i < sig->param_count; i ++) {
7722 tmp_locals [i] = emit_marshal (&m, i + param_shift, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_CONV_IN);
7725 // In coop mode need to register blocking state during native call
7726 if (mono_threads_is_coop_enabled ()) {
7727 // Perform an extra, early lookup of the function address, so any exceptions
7728 // potentially resulting from the lookup occur before entering blocking mode.
7729 if (!func_param && !MONO_CLASS_IS_IMPORT (mb->method->klass) && aot) {
7730 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7731 mono_mb_emit_op (mb, CEE_MONO_ICALL_ADDR, &piinfo->method);
7732 mono_mb_emit_byte (mb, CEE_POP); // Result not needed yet
7735 mono_mb_emit_ldloc_addr (mb, coop_gc_stack_dummy);
7736 mono_mb_emit_icall (mb, mono_threads_enter_gc_safe_region_unbalanced);
7737 mono_mb_emit_stloc (mb, coop_gc_var);
7740 /* push all arguments */
7743 mono_mb_emit_byte (mb, CEE_LDARG_0);
7745 for (i = 0; i < sig->param_count; i++) {
7746 emit_marshal (&m, i + param_shift, sig->params [i], mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_PUSH);
7749 /* call the native method */
7751 mono_mb_emit_byte (mb, CEE_LDARG_0);
7752 mono_mb_emit_op (mb, CEE_UNBOX, mono_defaults.int_class);
7753 mono_mb_emit_byte (mb, CEE_LDIND_I);
7754 mono_mb_emit_calli (mb, csig);
7755 } else if (MONO_CLASS_IS_IMPORT (mb->method->klass)) {
7757 mono_mb_emit_cominterop_call (mb, csig, &piinfo->method);
7759 g_assert_not_reached ();
7763 /* Reuse the ICALL_ADDR opcode for pinvokes too */
7764 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7765 mono_mb_emit_op (mb, CEE_MONO_ICALL_ADDR, &piinfo->method);
7766 mono_mb_emit_calli (mb, csig);
7768 mono_mb_emit_native_call (mb, csig, func);
7772 /* Set LastError if needed */
7773 if (piinfo->piflags & PINVOKE_ATTRIBUTE_SUPPORTS_LAST_ERROR) {
7776 static MonoMethodSignature *get_last_error_sig = NULL;
7777 if (!get_last_error_sig) {
7778 get_last_error_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
7779 get_last_error_sig->ret = &mono_defaults.int_class->byval_arg;
7780 get_last_error_sig->pinvoke = 1;
7784 * Have to call GetLastError () early and without a wrapper, since various runtime components could
7785 * clobber its value.
7787 mono_mb_emit_native_call (mb, get_last_error_sig, GetLastError);
7788 mono_mb_emit_icall (mb, mono_marshal_set_last_error_windows);
7790 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7791 mono_mb_emit_byte (mb, CEE_MONO_GET_LAST_ERROR);
7792 mono_mb_emit_icall (mb, mono_marshal_set_last_error_windows);
7795 mono_mb_emit_icall (mb, mono_marshal_set_last_error);
7799 if (MONO_TYPE_ISSTRUCT (sig->ret)) {
7800 MonoClass *klass = mono_class_from_mono_type (sig->ret);
7801 mono_class_init (klass);
7802 if (!(mono_class_is_explicit_layout (klass) || klass->blittable)) {
7803 /* This is used by emit_marshal_vtype (), but it needs to go right before the call */
7804 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7805 mono_mb_emit_byte (mb, CEE_MONO_VTADDR);
7806 mono_mb_emit_stloc (mb, m.vtaddr_var);
7810 /* Unblock before converting the result, since that can involve calls into the runtime */
7811 if (mono_threads_is_coop_enabled ()) {
7812 mono_mb_emit_ldloc (mb, coop_gc_var);
7813 mono_mb_emit_ldloc_addr (mb, coop_gc_stack_dummy);
7814 mono_mb_emit_icall (mb, mono_threads_exit_gc_safe_region_unbalanced);
7817 /* convert the result */
7818 if (!sig->ret->byref) {
7819 MonoMarshalSpec *spec = mspecs [0];
7820 type = sig->ret->type;
7822 if (spec && spec->native == MONO_NATIVE_CUSTOM) {
7823 emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7827 case MONO_TYPE_VOID:
7829 case MONO_TYPE_VALUETYPE:
7830 klass = sig->ret->data.klass;
7831 if (klass->enumtype) {
7832 type = mono_class_enum_basetype (sig->ret->data.klass)->type;
7835 emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7849 case MONO_TYPE_FNPTR:
7850 case MONO_TYPE_STRING:
7851 case MONO_TYPE_CLASS:
7852 case MONO_TYPE_OBJECT:
7853 case MONO_TYPE_BOOLEAN:
7854 case MONO_TYPE_ARRAY:
7855 case MONO_TYPE_SZARRAY:
7856 case MONO_TYPE_CHAR:
7858 case MONO_TYPE_GENERICINST:
7859 emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7861 case MONO_TYPE_TYPEDBYREF:
7863 g_warning ("return type 0x%02x unknown", sig->ret->type);
7864 g_assert_not_reached ();
7868 mono_mb_emit_stloc (mb, 3);
7872 * Need to call this after converting the result since MONO_VTADDR needs
7873 * to be adjacent to the call instruction.
7875 if (check_exceptions)
7876 emit_thread_interrupt_checkpoint (mb);
7878 /* we need to convert byref arguments back and free string arrays */
7879 for (i = 0; i < sig->param_count; i++) {
7880 MonoType *t = sig->params [i];
7881 MonoMarshalSpec *spec = mspecs [i + 1];
7883 argnum = i + param_shift;
7885 if (spec && ((spec->native == MONO_NATIVE_CUSTOM) || (spec->native == MONO_NATIVE_ASANY))) {
7886 emit_marshal (&m, argnum, t, spec, tmp_locals [i], NULL, MARSHAL_ACTION_CONV_OUT);
7891 case MONO_TYPE_STRING:
7892 case MONO_TYPE_VALUETYPE:
7893 case MONO_TYPE_CLASS:
7894 case MONO_TYPE_OBJECT:
7895 case MONO_TYPE_SZARRAY:
7896 case MONO_TYPE_BOOLEAN:
7897 emit_marshal (&m, argnum, t, spec, tmp_locals [i], NULL, MARSHAL_ACTION_CONV_OUT);
7904 if (!MONO_TYPE_IS_VOID(sig->ret))
7905 mono_mb_emit_ldloc (mb, 3);
7907 mono_mb_emit_byte (mb, CEE_RET);
7909 #endif /* HAVE_ONLINE_VES */
7912 * mono_marshal_get_native_wrapper:
7913 * \param method The \c MonoMethod to wrap.
7914 * \param check_exceptions Whenever to check for pending exceptions
7916 * Generates IL code for the pinvoke wrapper. The generated method
7917 * calls the unmanaged code in \c piinfo->addr.
7920 mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions, gboolean aot)
7922 MonoMethodSignature *sig, *csig;
7923 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
7924 MonoMethodBuilder *mb;
7925 MonoMarshalSpec **mspecs;
7928 gboolean pinvoke = FALSE;
7931 const char *exc_class = "MissingMethodException";
7932 const char *exc_arg = NULL;
7935 g_assert (method != NULL);
7936 g_assert (mono_method_signature (method)->pinvoke);
7938 GHashTable **cache_ptr;
7941 if (check_exceptions)
7942 cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_aot_check_cache;
7944 cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_aot_cache;
7946 if (check_exceptions)
7947 cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_check_cache;
7949 cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_cache;
7952 cache = get_cache (cache_ptr, mono_aligned_addr_hash, NULL);
7954 if ((res = mono_marshal_find_in_cache (cache, method)))
7957 if (MONO_CLASS_IS_IMPORT (method->klass)) {
7958 /* The COM code is not AOT compatible, it calls mono_custom_attrs_get_attr_checked () */
7962 return mono_cominterop_get_native_wrapper (method);
7964 g_assert_not_reached ();
7968 sig = mono_method_signature (method);
7970 if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
7971 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7974 if (!piinfo->addr) {
7976 if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)
7977 exc_arg = "Method contains unsupported native code";
7979 mono_lookup_pinvoke_call (method, &exc_class, &exc_arg);
7981 piinfo->addr = mono_lookup_internal_call (method);
7985 /* hack - redirect certain string constructors to CreateString */
7986 if (piinfo->addr == ves_icall_System_String_ctor_RedirectToCreateString) {
7987 g_assert (!pinvoke);
7988 g_assert (method->string_ctor);
7989 g_assert (sig->hasthis);
7991 /* CreateString returns a value */
7992 csig = mono_metadata_signature_dup_full (method->klass->image, sig);
7993 csig->ret = &mono_defaults.string_class->byval_arg;
7997 while ((res = mono_class_get_methods (mono_defaults.string_class, &iter))) {
7998 if (!strcmp ("CreateString", res->name) &&
7999 mono_metadata_signature_equal (csig, mono_method_signature (res))) {
8002 g_assert (!(res->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL));
8003 g_assert (!(res->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL));
8005 /* create a wrapper to preserve .ctor in stack trace */
8006 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_MANAGED);
8008 #ifdef HAVE_ONLINE_VES
8009 mono_mb_emit_byte (mb, CEE_LDARG_0);
8010 for (i = 1; i <= csig->param_count; i++)
8011 mono_mb_emit_ldarg (mb, i);
8012 mono_mb_emit_managed_call (mb, res, NULL);
8013 mono_mb_emit_byte (mb, CEE_RET);
8016 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_STRING_CTOR);
8017 info->d.string_ctor.method = method;
8019 /* use native_wrapper_cache because internal calls are looked up there */
8020 res = mono_mb_create_and_cache_full (cache, method, mb, csig,
8021 csig->param_count + 1, info, NULL);
8028 /* exception will be thrown */
8029 piinfo->addr = NULL;
8030 g_warning ("cannot find CreateString for .ctor");
8033 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_NATIVE);
8035 mb->method->save_lmf = 1;
8038 * In AOT mode and embedding scenarios, it is possible that the icall is not
8039 * registered in the runtime doing the AOT compilation.
8041 if (!piinfo->addr && !aot) {
8042 #ifdef HAVE_ONLINE_VES
8043 mono_mb_emit_exception (mb, exc_class, exc_arg);
8045 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
8046 info->d.managed_to_native.method = method;
8048 csig = mono_metadata_signature_dup_full (method->klass->image, sig);
8050 res = mono_mb_create_and_cache_full (cache, method, mb, csig,
8051 csig->param_count + 16, info, NULL);
8057 /* internal calls: we simply push all arguments and call the method (no conversions) */
8058 if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
8060 csig = mono_metadata_signature_dup_add_this (method->klass->image, sig, method->klass);
8062 csig = mono_metadata_signature_dup_full (method->klass->image, sig);
8064 //printf ("%s\n", mono_method_full_name (method, 1));
8066 /* hack - string constructors returns a value */
8067 if (method->string_ctor)
8068 csig->ret = &mono_defaults.string_class->byval_arg;
8070 #ifdef HAVE_ONLINE_VES
8072 MonoClass *handle_stack_mark_class;
8073 MonoClass *error_class;
8074 int thread_info_var = -1, stack_mark_var = -1, error_var = -1;
8075 MonoMethodSignature *call_sig = csig;
8076 gboolean uses_handles = FALSE;
8077 gboolean save_handles_to_locals = FALSE;
8078 IcallHandlesLocal *handles_locals = NULL;
8080 (void) mono_lookup_internal_call_full (method, &uses_handles);
8082 /* If it uses handles and MonoError, it had better check exceptions */
8083 g_assert (!uses_handles || check_exceptions);
8086 MonoMethodSignature *ret;
8088 /* Add a MonoError argument and figure out which args need to be wrapped in handles */
8089 // FIXME: The stuff from mono_metadata_signature_dup_internal_with_padding ()
8090 ret = mono_metadata_signature_alloc (method->klass->image, csig->param_count + 1);
8092 ret->param_count = csig->param_count + 1;
8093 ret->ret = csig->ret;
8095 handles_locals = g_new0 (IcallHandlesLocal, csig->param_count);
8096 for (int i = 0; i < csig->param_count; ++i) {
8097 IcallHandlesWrap w = signature_param_uses_handles (csig, i);
8098 handles_locals [i].wrap = w;
8100 case ICALL_HANDLES_WRAP_OBJ:
8101 case ICALL_HANDLES_WRAP_OBJ_INOUT:
8102 case ICALL_HANDLES_WRAP_OBJ_OUT:
8103 ret->params [i] = mono_class_get_byref_type (mono_class_from_mono_type(csig->params[i]));
8104 if (w == ICALL_HANDLES_WRAP_OBJ_OUT || w == ICALL_HANDLES_WRAP_OBJ_INOUT)
8105 save_handles_to_locals = TRUE;
8107 case ICALL_HANDLES_WRAP_NONE:
8108 case ICALL_HANDLES_WRAP_VALUETYPE_REF:
8109 ret->params [i] = csig->params [i];
8112 g_assert_not_reached ();
8115 /* Add MonoError* param */
8116 ret->params [csig->param_count] = &mono_get_intptr_class ()->byval_arg;
8117 ret->pinvoke = csig->pinvoke;
8123 handle_stack_mark_class = mono_class_load_from_name (mono_get_corlib (), "Mono", "RuntimeStructs/HandleStackMark");
8124 error_class = mono_class_load_from_name (mono_get_corlib (), "Mono", "RuntimeStructs/MonoError");
8126 thread_info_var = mono_mb_add_local (mb, &mono_get_intptr_class ()->byval_arg);
8127 stack_mark_var = mono_mb_add_local (mb, &handle_stack_mark_class->byval_arg);
8128 error_var = mono_mb_add_local (mb, &error_class->byval_arg);
8130 if (save_handles_to_locals) {
8131 /* add a local var to hold the handles for each out arg */
8132 for (int i = 0; i < sig->param_count; ++i) {
8133 int j = i + sig->hasthis;
8134 switch (handles_locals[j].wrap) {
8135 case ICALL_HANDLES_WRAP_NONE:
8136 case ICALL_HANDLES_WRAP_OBJ:
8137 case ICALL_HANDLES_WRAP_VALUETYPE_REF:
8138 handles_locals [j].handle = -1;
8140 case ICALL_HANDLES_WRAP_OBJ_INOUT:
8141 case ICALL_HANDLES_WRAP_OBJ_OUT:
8142 handles_locals [j].handle = mono_mb_add_local (mb, sig->params [i]);
8145 g_assert_not_reached ();
8155 * Add a null check since public icalls can be called with 'call' which
8156 * does no such check.
8158 mono_mb_emit_byte (mb, CEE_LDARG_0);
8159 pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
8160 mono_mb_emit_exception (mb, "NullReferenceException", NULL);
8161 mono_mb_patch_branch (mb, pos);
8165 mono_mb_emit_ldloc_addr (mb, stack_mark_var);
8166 mono_mb_emit_ldloc_addr (mb, error_var);
8167 mono_mb_emit_icall (mb, mono_icall_start);
8168 mono_mb_emit_stloc (mb, thread_info_var);
8171 mono_mb_emit_byte (mb, CEE_LDARG_0);
8172 /* TODO support adding wrappers to non-static struct methods */
8173 g_assert (!mono_class_is_valuetype(mono_method_get_class (method)));
8174 mono_mb_emit_icall (mb, mono_icall_handle_new);
8176 for (i = 0; i < sig->param_count; i++) {
8177 /* load each argument. references into the managed heap get wrapped in handles */
8178 int j = i + sig->hasthis;
8179 switch (handles_locals[j].wrap) {
8180 case ICALL_HANDLES_WRAP_NONE:
8181 mono_mb_emit_ldarg (mb, j);
8183 case ICALL_HANDLES_WRAP_OBJ:
8184 /* argI = mono_handle_new (argI_raw) */
8185 mono_mb_emit_ldarg (mb, j);
8186 mono_mb_emit_icall (mb, mono_icall_handle_new);
8188 case ICALL_HANDLES_WRAP_OBJ_INOUT:
8189 case ICALL_HANDLES_WRAP_OBJ_OUT:
8191 * handleI = argI = mono_handle_new (*argI_raw)
8193 * handleI = argI = mono_handle_new (NULL)
8195 if (handles_locals[j].wrap == ICALL_HANDLES_WRAP_OBJ_INOUT) {
8196 mono_mb_emit_ldarg (mb, j);
8197 mono_mb_emit_byte (mb, CEE_LDIND_REF);
8199 mono_mb_emit_byte (mb, CEE_LDNULL);
8200 mono_mb_emit_icall (mb, mono_icall_handle_new);
8202 mono_mb_emit_byte (mb, CEE_DUP);
8204 mono_mb_emit_stloc (mb, handles_locals[j].handle);
8206 case ICALL_HANDLES_WRAP_VALUETYPE_REF:
8207 /* (void) mono_handle_new (argI); argI */
8208 mono_mb_emit_ldarg (mb, j);
8209 mono_mb_emit_byte (mb, CEE_DUP);
8210 mono_mb_emit_icall (mb, mono_icall_handle_new_interior);
8211 mono_mb_emit_byte (mb, CEE_POP);
8213 fprintf (stderr, " Method %s.%s.%s has byref valuetype argument %d\n", method->klass->name_space, method->klass->name, method->name, i);
8217 g_assert_not_reached ();
8220 mono_mb_emit_ldloc_addr (mb, error_var);
8223 mono_mb_emit_byte (mb, CEE_LDARG_0);
8224 for (i = 0; i < sig->param_count; i++)
8225 mono_mb_emit_ldarg (mb, i + sig->hasthis);
8229 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8230 mono_mb_emit_op (mb, CEE_MONO_ICALL_ADDR, &piinfo->method);
8231 mono_mb_emit_calli (mb, call_sig);
8233 g_assert (piinfo->addr);
8234 mono_mb_emit_native_call (mb, call_sig, piinfo->addr);
8238 if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
8239 // if (ret != NULL_HANDLE) {
8240 // ret = MONO_HANDLE_RAW(ret)
8242 mono_mb_emit_byte (mb, CEE_DUP);
8243 int pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
8244 mono_mb_emit_ldflda (mb, MONO_HANDLE_PAYLOAD_OFFSET (MonoObject));
8245 mono_mb_emit_byte (mb, CEE_LDIND_REF);
8246 mono_mb_patch_branch (mb, pos);
8248 if (save_handles_to_locals) {
8249 for (i = 0; i < sig->param_count; i++) {
8250 int j = i + sig->hasthis;
8251 switch (handles_locals [j].wrap) {
8252 case ICALL_HANDLES_WRAP_NONE:
8253 case ICALL_HANDLES_WRAP_OBJ:
8254 case ICALL_HANDLES_WRAP_VALUETYPE_REF:
8256 case ICALL_HANDLES_WRAP_OBJ_INOUT:
8257 case ICALL_HANDLES_WRAP_OBJ_OUT:
8258 /* *argI_raw = MONO_HANDLE_RAW (handleI) */
8261 mono_mb_emit_ldarg (mb, j);
8263 mono_mb_emit_ldloc (mb, handles_locals [j].handle);
8264 /* MONO_HANDLE_RAW(handleI) */
8265 mono_mb_emit_ldflda (mb, MONO_HANDLE_PAYLOAD_OFFSET (MonoObject));
8266 mono_mb_emit_byte (mb, CEE_LDIND_REF);
8267 /* *argI_raw = MONO_HANDLE_RAW(handleI) */
8268 mono_mb_emit_byte (mb, CEE_STIND_REF);
8271 g_assert_not_reached ();
8275 g_free (handles_locals);
8277 mono_mb_emit_ldloc (mb, thread_info_var);
8278 mono_mb_emit_ldloc_addr (mb, stack_mark_var);
8279 mono_mb_emit_ldloc_addr (mb, error_var);
8280 mono_mb_emit_icall (mb, mono_icall_end);
8283 if (check_exceptions)
8284 emit_thread_interrupt_checkpoint (mb);
8285 mono_mb_emit_byte (mb, CEE_RET);
8287 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
8288 info->d.managed_to_native.method = method;
8290 csig = mono_metadata_signature_dup_full (method->klass->image, csig);
8292 res = mono_mb_create_and_cache_full (cache, method, mb, csig, csig->param_count + 16,
8301 g_assert (piinfo->addr);
8303 #ifdef HAVE_ONLINE_VES
8304 mspecs = g_new (MonoMarshalSpec*, sig->param_count + 1);
8305 mono_method_get_marshal_info (method, mspecs);
8307 mono_marshal_emit_native_wrapper (mb->method->klass->image, mb, sig, piinfo, mspecs, piinfo->addr, aot, check_exceptions, FALSE);
8309 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_PINVOKE);
8310 info->d.managed_to_native.method = method;
8312 csig = mono_metadata_signature_dup_full (method->klass->image, sig);
8314 res = mono_mb_create_and_cache_full (cache, method, mb, csig, csig->param_count + 16,
8318 #ifdef HAVE_ONLINE_VES
8319 for (i = sig->param_count; i >= 0; i--)
8321 mono_metadata_free_marshal_spec (mspecs [i]);
8325 /* mono_method_print_code (res); */
8331 * mono_marshal_get_native_func_wrapper:
8332 * \param image The image to use for memory allocation and for looking up custom marshallers.
8333 * \param sig The signature of the function
8334 * \param func The native function to wrap
8336 * \returns a wrapper method around native functions, similar to the pinvoke
8340 mono_marshal_get_native_func_wrapper (MonoImage *image, MonoMethodSignature *sig,
8341 MonoMethodPInvoke *piinfo, MonoMarshalSpec **mspecs, gpointer func)
8343 MonoMethodSignature *csig;
8345 SignaturePointerPair key, *new_key;
8346 MonoMethodBuilder *mb;
8355 // Generic types are not safe to place in MonoImage caches.
8356 g_assert (!sig->is_inflated);
8358 cache = get_cache (&image->native_func_wrapper_cache, signature_pointer_pair_hash, signature_pointer_pair_equal);
8359 if ((res = mono_marshal_find_in_cache (cache, &key)))
8362 name = g_strdup_printf ("wrapper_native_%p", func);
8363 mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
8364 mb->method->save_lmf = 1;
8366 #ifdef HAVE_ONLINE_VES
8367 mono_marshal_emit_native_wrapper (image, mb, sig, piinfo, mspecs, func, FALSE, TRUE, FALSE);
8370 csig = mono_metadata_signature_dup_full (image, sig);
8373 new_key = g_new (SignaturePointerPair,1);
8374 new_key->sig = csig;
8375 new_key->pointer = func;
8377 res = mono_mb_create_and_cache_full (cache, new_key, mb, csig, csig->param_count + 16, NULL, &found);
8383 mono_marshal_set_wrapper_info (res, NULL);
8389 * The wrapper receives the native function as a boxed IntPtr as its 'this' argument. This is easier to support in
8393 mono_marshal_get_native_func_wrapper_aot (MonoClass *klass)
8395 MonoMethodSignature *sig, *csig;
8396 MonoMethodBuilder *mb;
8401 MonoMethodPInvoke mpiinfo;
8402 MonoMethodPInvoke *piinfo = &mpiinfo;
8403 MonoMarshalSpec **mspecs;
8404 MonoMethod *invoke = mono_get_delegate_invoke (klass);
8405 MonoImage *image = invoke->klass->image;
8408 // FIXME: include UnmanagedFunctionPointerAttribute info
8411 * The wrapper is associated with the delegate type, to pick up the marshalling info etc.
8413 cache = get_cache (&mono_method_get_wrapper_cache (invoke)->native_func_wrapper_aot_cache, mono_aligned_addr_hash, NULL);
8415 if ((res = mono_marshal_find_in_cache (cache, invoke)))
8418 memset (&mpiinfo, 0, sizeof (mpiinfo));
8419 parse_unmanaged_function_pointer_attr (klass, &mpiinfo);
8421 mspecs = g_new0 (MonoMarshalSpec*, mono_method_signature (invoke)->param_count + 1);
8422 mono_method_get_marshal_info (invoke, mspecs);
8423 /* Freed below so don't alloc from mempool */
8424 sig = mono_metadata_signature_dup (mono_method_signature (invoke));
8427 name = g_strdup_printf ("wrapper_aot_native");
8428 mb = mono_mb_new (invoke->klass, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
8429 mb->method->save_lmf = 1;
8431 #ifdef HAVE_ONLINE_VES
8432 mono_marshal_emit_native_wrapper (image, mb, sig, piinfo, mspecs, NULL, FALSE, TRUE, TRUE);
8435 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NATIVE_FUNC_AOT);
8436 info->d.managed_to_native.method = invoke;
8438 g_assert (!sig->hasthis);
8439 csig = mono_metadata_signature_dup_add_this (image, sig, mono_defaults.object_class);
8441 res = mono_mb_create_and_cache_full (cache, invoke,
8442 mb, csig, csig->param_count + 16,
8446 for (i = mono_method_signature (invoke)->param_count; i >= 0; i--)
8448 mono_metadata_free_marshal_spec (mspecs [i]);
8456 * mono_marshal_emit_managed_wrapper:
8458 * Emit the body of a native-to-managed wrapper. INVOKE_SIG is the signature of
8459 * the delegate which wraps the managed method to be called. For closed delegates,
8460 * it could have fewer parameters than the method it wraps.
8461 * THIS_LOC is the memory location where the target of the delegate is stored.
8464 mono_marshal_emit_managed_wrapper (MonoMethodBuilder *mb, MonoMethodSignature *invoke_sig, MonoMarshalSpec **mspecs, EmitMarshalContext* m, MonoMethod *method, uint32_t target_handle)
8466 #ifndef HAVE_ONLINE_VES
8467 MonoMethodSignature *sig, *csig;
8473 /* we first do all conversions */
8474 for (i = 0; i < sig->param_count; i ++) {
8475 MonoType *t = sig->params [i];
8478 case MONO_TYPE_OBJECT:
8479 case MONO_TYPE_CLASS:
8480 case MONO_TYPE_VALUETYPE:
8481 case MONO_TYPE_ARRAY:
8482 case MONO_TYPE_SZARRAY:
8483 case MONO_TYPE_STRING:
8484 case MONO_TYPE_BOOLEAN:
8485 emit_marshal (m, i, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_MANAGED_CONV_IN);
8489 if (!sig->ret->byref) {
8490 switch (sig->ret->type) {
8491 case MONO_TYPE_STRING:
8492 csig->ret = &mono_defaults.int_class->byval_arg;
8499 MonoMethodSignature *sig, *csig;
8500 MonoExceptionClause *clauses, *clause_finally, *clause_catch;
8501 int i, *tmp_locals, ex_local, e_local, attach_cookie_local, attach_dummy_local;
8502 int leave_try_pos, leave_catch_pos, ex_m1_pos;
8503 gboolean closed = FALSE;
8508 /* allocate local 0 (pointer) src_ptr */
8509 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8510 /* allocate local 1 (pointer) dst_ptr */
8511 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8512 /* allocate local 2 (boolean) delete_old */
8513 mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
8515 if (!sig->hasthis && sig->param_count != invoke_sig->param_count) {
8516 /* Closed delegate */
8517 g_assert (sig->param_count == invoke_sig->param_count + 1);
8519 /* Use a new signature without the first argument */
8520 sig = mono_metadata_signature_dup (sig);
8521 memmove (&sig->params [0], &sig->params [1], (sig->param_count - 1) * sizeof (MonoType*));
8522 sig->param_count --;
8525 if (!MONO_TYPE_IS_VOID(sig->ret)) {
8526 /* allocate local 3 to store the return value */
8527 mono_mb_add_local (mb, sig->ret);
8530 if (MONO_TYPE_ISSTRUCT (sig->ret))
8531 m->vtaddr_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8533 ex_local = mono_mb_add_local (mb, &mono_defaults.uint32_class->byval_arg);
8534 e_local = mono_mb_add_local (mb, &mono_defaults.exception_class->byval_arg);
8536 attach_cookie_local = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8537 attach_dummy_local = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8542 * // does (STARTING|RUNNING|BLOCKING) -> RUNNING + set/switch domain
8543 * mono_threads_attach_coop ();
8547 * ret = method (...);
8548 * } catch (Exception e) {
8549 * ex = mono_gchandle_new (e, false);
8551 * // does RUNNING -> (RUNNING|BLOCKING) + unset/switch domain
8552 * mono_threads_detach_coop ();
8555 * mono_marshal_ftnptr_eh_callback (ex);
8561 clauses = g_new0 (MonoExceptionClause, 2);
8563 clause_catch = &clauses [0];
8564 clause_catch->flags = MONO_EXCEPTION_CLAUSE_NONE;
8565 clause_catch->data.catch_class = mono_defaults.exception_class;
8567 clause_finally = &clauses [1];
8568 clause_finally->flags = MONO_EXCEPTION_CLAUSE_FINALLY;
8570 mono_mb_emit_icon (mb, 0);
8571 mono_mb_emit_stloc (mb, 2);
8573 mono_mb_emit_icon (mb, -1);
8574 mono_mb_emit_byte (mb, CEE_CONV_U4);
8575 mono_mb_emit_stloc (mb, ex_local);
8578 clause_catch->try_offset = clause_finally->try_offset = mono_mb_get_label (mb);
8580 if (!mono_threads_is_coop_enabled ()) {
8581 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8582 mono_mb_emit_byte (mb, CEE_MONO_JIT_ATTACH);
8584 /* mono_threads_attach_coop (); */
8585 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8586 mono_mb_emit_byte (mb, CEE_MONO_LDDOMAIN);
8587 mono_mb_emit_ldloc_addr (mb, attach_dummy_local);
8588 mono_mb_emit_icall (mb, mono_threads_attach_coop);
8589 mono_mb_emit_stloc (mb, attach_cookie_local);
8592 /* <interrupt check> */
8593 emit_thread_interrupt_checkpoint (mb);
8595 /* we first do all conversions */
8596 tmp_locals = (int *)alloca (sizeof (int) * sig->param_count);
8597 for (i = 0; i < sig->param_count; i ++) {
8598 MonoType *t = sig->params [i];
8601 case MONO_TYPE_OBJECT:
8602 case MONO_TYPE_CLASS:
8603 case MONO_TYPE_VALUETYPE:
8604 case MONO_TYPE_ARRAY:
8605 case MONO_TYPE_SZARRAY:
8606 case MONO_TYPE_STRING:
8607 case MONO_TYPE_BOOLEAN:
8608 tmp_locals [i] = emit_marshal (m, i, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_MANAGED_CONV_IN);
8618 if (target_handle) {
8619 mono_mb_emit_icon (mb, (gint32)target_handle);
8620 mono_mb_emit_icall (mb, mono_gchandle_get_target);
8623 g_assert_not_reached ();
8625 } else if (closed) {
8626 mono_mb_emit_icon (mb, (gint32)target_handle);
8627 mono_mb_emit_icall (mb, mono_gchandle_get_target);
8630 for (i = 0; i < sig->param_count; i++) {
8631 MonoType *t = sig->params [i];
8633 if (tmp_locals [i]) {
8635 mono_mb_emit_ldloc_addr (mb, tmp_locals [i]);
8637 mono_mb_emit_ldloc (mb, tmp_locals [i]);
8640 mono_mb_emit_ldarg (mb, i);
8643 /* ret = method (...) */
8644 mono_mb_emit_managed_call (mb, method, NULL);
8646 if (MONO_TYPE_ISSTRUCT (sig->ret)) {
8647 MonoClass *klass = mono_class_from_mono_type (sig->ret);
8648 mono_class_init (klass);
8649 if (!(mono_class_is_explicit_layout (klass) || klass->blittable)) {
8650 /* This is used by emit_marshal_vtype (), but it needs to go right before the call */
8651 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8652 mono_mb_emit_byte (mb, CEE_MONO_VTADDR);
8653 mono_mb_emit_stloc (mb, m->vtaddr_var);
8657 if (mspecs [0] && mspecs [0]->native == MONO_NATIVE_CUSTOM) {
8658 emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
8659 } else if (!sig->ret->byref) {
8660 switch (sig->ret->type) {
8661 case MONO_TYPE_VOID:
8663 case MONO_TYPE_BOOLEAN:
8666 case MONO_TYPE_CHAR:
8678 case MONO_TYPE_OBJECT:
8679 mono_mb_emit_stloc (mb, 3);
8681 case MONO_TYPE_STRING:
8682 csig->ret = &mono_defaults.int_class->byval_arg;
8683 emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
8685 case MONO_TYPE_VALUETYPE:
8686 case MONO_TYPE_CLASS:
8687 case MONO_TYPE_SZARRAY:
8688 emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
8691 g_warning ("return type 0x%02x unknown", sig->ret->type);
8692 g_assert_not_reached ();
8695 mono_mb_emit_stloc (mb, 3);
8698 /* Convert byref arguments back */
8699 for (i = 0; i < sig->param_count; i ++) {
8700 MonoType *t = sig->params [i];
8701 MonoMarshalSpec *spec = mspecs [i + 1];
8703 if (spec && spec->native == MONO_NATIVE_CUSTOM) {
8704 emit_marshal (m, i, t, mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
8706 else if (t->byref) {
8708 case MONO_TYPE_CLASS:
8709 case MONO_TYPE_VALUETYPE:
8710 case MONO_TYPE_OBJECT:
8711 case MONO_TYPE_STRING:
8712 case MONO_TYPE_BOOLEAN:
8713 emit_marshal (m, i, t, mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
8719 else if (invoke_sig->params [i]->attrs & PARAM_ATTRIBUTE_OUT) {
8720 /* The [Out] information is encoded in the delegate signature */
8722 case MONO_TYPE_SZARRAY:
8723 case MONO_TYPE_CLASS:
8724 case MONO_TYPE_VALUETYPE:
8725 emit_marshal (m, i, invoke_sig->params [i], mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
8728 g_assert_not_reached ();
8733 leave_try_pos = mono_mb_emit_branch (mb, CEE_LEAVE);
8737 /* catch (Exception e) { */
8738 clause_catch->try_len = mono_mb_get_label (mb) - clause_catch->try_offset;
8739 clause_catch->handler_offset = mono_mb_get_label (mb);
8741 mono_mb_emit_stloc (mb, e_local);
8743 /* ex = mono_gchandle_new (e, false); */
8744 mono_mb_emit_ldloc (mb, e_local);
8745 mono_mb_emit_icon (mb, 0);
8746 mono_mb_emit_icall (mb, mono_gchandle_new);
8747 mono_mb_emit_stloc (mb, ex_local);
8749 leave_catch_pos = mono_mb_emit_branch (mb, CEE_LEAVE);
8752 clause_catch->handler_len = mono_mb_get_pos (mb) - clause_catch->handler_offset;
8755 clause_finally->try_len = mono_mb_get_label (mb) - clause_finally->try_offset;
8756 clause_finally->handler_offset = mono_mb_get_label (mb);
8758 if (!mono_threads_is_coop_enabled ()) {
8759 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8760 mono_mb_emit_byte (mb, CEE_MONO_JIT_DETACH);
8762 /* mono_threads_detach_coop (); */
8763 mono_mb_emit_ldloc (mb, attach_cookie_local);
8764 mono_mb_emit_ldloc_addr (mb, attach_dummy_local);
8765 mono_mb_emit_icall (mb, mono_threads_detach_coop);
8769 mono_mb_emit_ldloc (mb, ex_local);
8770 mono_mb_emit_icon (mb, -1);
8771 mono_mb_emit_byte (mb, CEE_CONV_U4);
8772 ex_m1_pos = mono_mb_emit_branch (mb, CEE_BEQ);
8774 /* mono_marshal_ftnptr_eh_callback (ex) */
8775 mono_mb_emit_ldloc (mb, ex_local);
8776 mono_mb_emit_icall (mb, mono_marshal_ftnptr_eh_callback);
8779 mono_mb_patch_branch (mb, ex_m1_pos);
8781 mono_mb_emit_byte (mb, CEE_ENDFINALLY);
8783 /* } [endfinally] */
8784 clause_finally->handler_len = mono_mb_get_pos (mb) - clause_finally->handler_offset;
8786 mono_mb_patch_branch (mb, leave_try_pos);
8787 mono_mb_patch_branch (mb, leave_catch_pos);
8790 if (m->retobj_var) {
8791 mono_mb_emit_ldloc (mb, m->retobj_var);
8792 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8793 mono_mb_emit_op (mb, CEE_MONO_RETOBJ, m->retobj_class);
8796 if (!MONO_TYPE_IS_VOID(sig->ret))
8797 mono_mb_emit_ldloc (mb, 3);
8798 mono_mb_emit_byte (mb, CEE_RET);
8801 mono_mb_set_clauses (mb, 2, clauses);
8809 mono_marshal_set_callconv_from_modopt (MonoMethod *method, MonoMethodSignature *csig)
8811 MonoMethodSignature *sig;
8816 * Under windows, delegates passed to native code must use the STDCALL
8817 * calling convention.
8819 csig->call_convention = MONO_CALL_STDCALL;
8822 sig = mono_method_signature (method);
8824 /* Change default calling convention if needed */
8825 /* Why is this a modopt ? */
8826 if (sig->ret && sig->ret->num_mods) {
8827 for (i = 0; i < sig->ret->num_mods; ++i) {
8829 MonoClass *cmod_class = mono_class_get_checked (method->klass->image, sig->ret->modifiers [i].token, &error);
8830 g_assert (mono_error_ok (&error));
8831 if ((cmod_class->image == mono_defaults.corlib) && !strcmp (cmod_class->name_space, "System.Runtime.CompilerServices")) {
8832 if (!strcmp (cmod_class->name, "CallConvCdecl"))
8833 csig->call_convention = MONO_CALL_C;
8834 else if (!strcmp (cmod_class->name, "CallConvStdcall"))
8835 csig->call_convention = MONO_CALL_STDCALL;
8836 else if (!strcmp (cmod_class->name, "CallConvFastcall"))
8837 csig->call_convention = MONO_CALL_FASTCALL;
8838 else if (!strcmp (cmod_class->name, "CallConvThiscall"))
8839 csig->call_convention = MONO_CALL_THISCALL;
8846 * mono_marshal_get_managed_wrapper:
8847 * Generates IL code to call managed methods from unmanaged code
8848 * If \p target_handle is \c 0, the wrapper info will be a \c WrapperInfo structure.
8851 mono_marshal_get_managed_wrapper (MonoMethod *method, MonoClass *delegate_klass, uint32_t target_handle, MonoError *error)
8853 MonoMethodSignature *sig, *csig, *invoke_sig;
8854 MonoMethodBuilder *mb;
8855 MonoMethod *res, *invoke;
8856 MonoMarshalSpec **mspecs;
8857 MonoMethodPInvoke piinfo;
8860 EmitMarshalContext m;
8862 g_assert (method != NULL);
8865 if (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
8866 mono_error_set_invalid_program (error, "Failed because method (%s) marked PInvokeCallback (managed method) and extern (unmanaged) simultaneously.", mono_method_full_name (method, TRUE));
8871 * FIXME: Should cache the method+delegate type pair, since the same method
8872 * could be called with different delegates, thus different marshalling
8875 cache = get_cache (&mono_method_get_wrapper_cache (method)->managed_wrapper_cache, mono_aligned_addr_hash, NULL);
8877 if (!target_handle && (res = mono_marshal_find_in_cache (cache, method)))
8880 invoke = mono_get_delegate_invoke (delegate_klass);
8881 invoke_sig = mono_method_signature (invoke);
8883 mspecs = g_new0 (MonoMarshalSpec*, mono_method_signature (invoke)->param_count + 1);
8884 mono_method_get_marshal_info (invoke, mspecs);
8886 sig = mono_method_signature (method);
8888 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
8890 /*the target gchandle must be the first entry after size and the wrapper itself.*/
8891 mono_mb_add_data (mb, GUINT_TO_POINTER (target_handle));
8893 /* we copy the signature, so that we can modify it */
8895 /* Need to free this later */
8896 csig = mono_metadata_signature_dup (invoke_sig);
8898 csig = mono_metadata_signature_dup_full (method->klass->image, invoke_sig);
8902 memset (&m, 0, sizeof (m));
8908 m.image = method->klass->image;
8910 mono_marshal_set_callconv_from_modopt (invoke, csig);
8912 /* The attribute is only available in Net 2.0 */
8913 if (mono_class_try_get_unmanaged_function_pointer_attribute_class ()) {
8914 MonoCustomAttrInfo *cinfo;
8915 MonoCustomAttrEntry *attr;
8918 * The pinvoke attributes are stored in a real custom attribute. Obtain the
8919 * contents of the attribute without constructing it, as that might not be
8920 * possible when running in cross-compiling mode.
8922 cinfo = mono_custom_attrs_from_class_checked (delegate_klass, error);
8923 mono_error_assert_ok (error);
8926 for (i = 0; i < cinfo->num_attrs; ++i) {
8927 MonoClass *ctor_class = cinfo->attrs [i].ctor->klass;
8928 if (mono_class_has_parent (ctor_class, mono_class_try_get_unmanaged_function_pointer_attribute_class ())) {
8929 attr = &cinfo->attrs [i];
8935 MonoArray *typed_args, *named_args;
8936 CattrNamedArg *arginfo;
8940 MonoBoolean set_last_error = 0;
8943 mono_reflection_create_custom_attr_data_args (mono_defaults.corlib, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
8944 g_assert (mono_error_ok (&error));
8945 g_assert (mono_array_length (typed_args) == 1);
8948 o = mono_array_get (typed_args, MonoObject*, 0);
8949 call_conv = *(gint32*)mono_object_unbox (o);
8952 for (i = 0; i < mono_array_length (named_args); ++i) {
8953 CattrNamedArg *narg = &arginfo [i];
8955 o = mono_array_get (named_args, MonoObject*, i);
8957 g_assert (narg->field);
8958 if (!strcmp (narg->field->name, "CharSet")) {
8959 charset = *(gint32*)mono_object_unbox (o);
8960 } else if (!strcmp (narg->field->name, "SetLastError")) {
8961 set_last_error = *(MonoBoolean*)mono_object_unbox (o);
8962 } else if (!strcmp (narg->field->name, "BestFitMapping")) {
8963 // best_fit_mapping = *(MonoBoolean*)mono_object_unbox (o);
8964 } else if (!strcmp (narg->field->name, "ThrowOnUnmappableChar")) {
8965 // throw_on_unmappable = *(MonoBoolean*)mono_object_unbox (o);
8967 g_assert_not_reached ();
8973 memset (&piinfo, 0, sizeof (piinfo));
8975 piinfo.piflags = (call_conv << 8) | (charset ? (charset - 1) * 2 : 1) | set_last_error;
8977 csig->call_convention = call_conv - 1;
8980 if (cinfo && !cinfo->cached)
8981 mono_custom_attrs_free (cinfo);
8984 mono_marshal_emit_managed_wrapper (mb, invoke_sig, mspecs, &m, method, target_handle);
8986 if (!target_handle) {
8989 // FIXME: Associate it with the method+delegate_klass pair
8990 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
8991 info->d.native_to_managed.method = method;
8992 info->d.native_to_managed.klass = delegate_klass;
8994 res = mono_mb_create_and_cache_full (cache, method,
8995 mb, csig, sig->param_count + 16,
8998 #ifdef HAVE_ONLINE_VES
9001 res = mono_mb_create (mb, csig, sig->param_count + 16, NULL);
9005 for (i = mono_method_signature (invoke)->param_count; i >= 0; i--)
9007 mono_metadata_free_marshal_spec (mspecs [i]);
9010 /* mono_method_print_code (res); */
9016 mono_marshal_get_vtfixup_ftnptr (MonoImage *image, guint32 token, guint16 type)
9020 MonoMethodSignature *sig;
9021 MonoMethodBuilder *mb;
9026 method = mono_get_method_checked (image, token, NULL, NULL, &error);
9028 g_error ("Could not load vtfixup token 0x%x due to %s", token, mono_error_get_message (&error));
9031 if (type & (VTFIXUP_TYPE_FROM_UNMANAGED | VTFIXUP_TYPE_FROM_UNMANAGED_RETAIN_APPDOMAIN)) {
9032 MonoMethodSignature *csig;
9033 MonoMarshalSpec **mspecs;
9034 EmitMarshalContext m;
9036 sig = mono_method_signature (method);
9037 g_assert (!sig->hasthis);
9039 mspecs = g_new0 (MonoMarshalSpec*, sig->param_count + 1);
9040 mono_method_get_marshal_info (method, mspecs);
9042 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
9043 csig = mono_metadata_signature_dup_full (image, sig);
9047 memset (&m, 0, sizeof (m));
9055 mono_marshal_set_callconv_from_modopt (method, csig);
9057 /* FIXME: Implement VTFIXUP_TYPE_FROM_UNMANAGED_RETAIN_APPDOMAIN. */
9059 mono_marshal_emit_managed_wrapper (mb, sig, mspecs, &m, method, 0);
9061 #ifdef HAVE_ONLINE_VES
9064 method = mono_mb_create (mb, csig, sig->param_count + 16, NULL);
9067 for (i = sig->param_count; i >= 0; i--)
9069 mono_metadata_free_marshal_spec (mspecs [i]);
9072 gpointer compiled_ptr = mono_compile_method_checked (method, &error);
9073 mono_error_assert_ok (&error);
9074 return compiled_ptr;
9077 sig = mono_method_signature (method);
9078 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_MANAGED);
9080 param_count = sig->param_count + sig->hasthis;
9081 #ifdef HAVE_ONLINE_VES
9082 for (i = 0; i < param_count; i++)
9083 mono_mb_emit_ldarg (mb, i);
9085 if (type & VTFIXUP_TYPE_CALL_MOST_DERIVED)
9086 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
9088 mono_mb_emit_op (mb, CEE_CALL, method);
9089 mono_mb_emit_byte (mb, CEE_RET);
9094 method = mono_mb_create (mb, sig, param_count, NULL);
9097 gpointer compiled_ptr = mono_compile_method_checked (method, &error);
9098 mono_error_assert_ok (&error);
9099 return compiled_ptr;
9102 #ifdef HAVE_ONLINE_VES
9105 * The code directly following this is the cache hit, value positive branch
9107 * This function takes a new method builder with 0 locals and adds two locals
9108 * to create multiple out-branches and the fall through state of having the object
9109 * on the stack after a cache miss
9112 generate_check_cache (int obj_arg_position, int class_arg_position, int cache_arg_position, // In-parameters
9113 int *null_obj, int *cache_hit_neg, int *cache_hit_pos, // Out-parameters
9114 MonoMethodBuilder *mb)
9118 /* allocate local 0 (pointer) obj_vtable */
9119 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9120 /* allocate local 1 (pointer) cached_vtable */
9121 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9124 mono_mb_emit_ldarg (mb, obj_arg_position);
9125 *null_obj = mono_mb_emit_branch (mb, CEE_BRFALSE);
9127 /*obj_vtable = obj->vtable;*/
9128 mono_mb_emit_ldarg (mb, obj_arg_position);
9129 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9130 mono_mb_emit_byte (mb, CEE_LDIND_I);
9131 mono_mb_emit_stloc (mb, 0);
9133 /* cached_vtable = *cache*/
9134 mono_mb_emit_ldarg (mb, cache_arg_position);
9135 mono_mb_emit_byte (mb, CEE_LDIND_I);
9136 mono_mb_emit_stloc (mb, 1);
9138 mono_mb_emit_ldloc (mb, 1);
9139 mono_mb_emit_byte (mb, CEE_LDC_I4);
9140 mono_mb_emit_i4 (mb, ~0x1);
9141 mono_mb_emit_byte (mb, CEE_CONV_I);
9142 mono_mb_emit_byte (mb, CEE_AND);
9143 mono_mb_emit_ldloc (mb, 0);
9144 /*if ((cached_vtable & ~0x1)== obj_vtable)*/
9145 cache_miss_pos = mono_mb_emit_branch (mb, CEE_BNE_UN);
9147 /*return (cached_vtable & 0x1) ? NULL : obj;*/
9148 mono_mb_emit_ldloc (mb, 1);
9149 mono_mb_emit_byte(mb, CEE_LDC_I4_1);
9150 mono_mb_emit_byte (mb, CEE_CONV_U);
9151 mono_mb_emit_byte (mb, CEE_AND);
9152 *cache_hit_neg = mono_mb_emit_branch (mb, CEE_BRTRUE);
9153 *cache_hit_pos = mono_mb_emit_branch (mb, CEE_BR);
9156 mono_mb_patch_branch (mb, cache_miss_pos);
9159 mono_mb_emit_ldarg (mb, obj_arg_position);
9160 mono_mb_emit_ldarg (mb, class_arg_position);
9161 mono_mb_emit_ldarg (mb, cache_arg_position);
9162 mono_mb_emit_icall (mb, mono_marshal_isinst_with_cache);
9165 #endif /* HAVE_ONLINE_VES */
9168 * mono_marshal_get_castclass_with_cache:
9169 * This does the equivalent of \c mono_object_castclass_with_cache.
9172 mono_marshal_get_castclass_with_cache (void)
9174 static MonoMethod *cached;
9176 MonoMethodBuilder *mb;
9177 MonoMethodSignature *sig;
9178 int return_null_pos, positive_cache_hit_pos, negative_cache_hit_pos, invalid_cast_pos;
9181 const int obj_arg_position = 0;
9182 const int class_arg_position = 1;
9183 const int cache_arg_position = 2;
9188 mb = mono_mb_new (mono_defaults.object_class, "__castclass_with_cache", MONO_WRAPPER_CASTCLASS);
9189 sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
9190 sig->params [obj_arg_position] = &mono_defaults.object_class->byval_arg;
9191 sig->params [class_arg_position] = &mono_defaults.int_class->byval_arg;
9192 sig->params [cache_arg_position] = &mono_defaults.int_class->byval_arg;
9193 sig->ret = &mono_defaults.object_class->byval_arg;
9196 #ifdef HAVE_ONLINE_VES
9197 generate_check_cache (obj_arg_position, class_arg_position, cache_arg_position,
9198 &return_null_pos, &negative_cache_hit_pos, &positive_cache_hit_pos, mb);
9199 invalid_cast_pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
9202 mono_mb_patch_branch (mb, positive_cache_hit_pos);
9203 mono_mb_emit_ldarg (mb, obj_arg_position);
9204 mono_mb_emit_byte (mb, CEE_RET);
9207 mono_mb_patch_branch (mb, negative_cache_hit_pos);
9208 mono_mb_patch_branch (mb, invalid_cast_pos);
9209 mono_mb_emit_exception (mb, "InvalidCastException", NULL);
9212 mono_mb_patch_branch (mb, return_null_pos);
9213 mono_mb_emit_byte (mb, CEE_LDNULL);
9214 mono_mb_emit_byte (mb, CEE_RET);
9215 #endif /* HAVE_ONLINE_VES */
9217 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE);
9218 res = mono_mb_create (mb, sig, 8, info);
9221 if (InterlockedCompareExchangePointer ((volatile gpointer *)&cached, res, NULL)) {
9222 mono_free_method (res);
9223 mono_metadata_free_method_signature (sig);
9230 /* this is an icall */
9232 mono_marshal_isinst_with_cache (MonoObject *obj, MonoClass *klass, uintptr_t *cache)
9235 MonoObject *isinst = mono_object_isinst_checked (obj, klass, &error);
9236 if (mono_error_set_pending_exception (&error))
9239 if (mono_object_is_transparent_proxy (obj))
9242 uintptr_t cache_update = (uintptr_t)obj->vtable;
9244 cache_update = cache_update | 0x1;
9246 *cache = cache_update;
9252 * mono_marshal_get_isinst_with_cache:
9253 * This does the equivalent of \c mono_marshal_isinst_with_cache.
9256 mono_marshal_get_isinst_with_cache (void)
9258 static MonoMethod *cached;
9260 MonoMethodBuilder *mb;
9261 MonoMethodSignature *sig;
9262 int return_null_pos, positive_cache_hit_pos, negative_cache_hit_pos;
9265 const int obj_arg_position = 0;
9266 const int class_arg_position = 1;
9267 const int cache_arg_position = 2;
9272 mb = mono_mb_new (mono_defaults.object_class, "__isinst_with_cache", MONO_WRAPPER_CASTCLASS);
9273 sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
9275 sig->params [obj_arg_position] = &mono_defaults.object_class->byval_arg;
9277 sig->params [class_arg_position] = &mono_defaults.int_class->byval_arg;
9279 sig->params [cache_arg_position] = &mono_defaults.int_class->byval_arg;
9280 sig->ret = &mono_defaults.object_class->byval_arg;
9283 #ifdef HAVE_ONLINE_VES
9284 generate_check_cache (obj_arg_position, class_arg_position, cache_arg_position,
9285 &return_null_pos, &negative_cache_hit_pos, &positive_cache_hit_pos, mb);
9286 // Return the object gotten via the slow path.
9287 mono_mb_emit_byte (mb, CEE_RET);
9290 mono_mb_patch_branch (mb, negative_cache_hit_pos);
9291 mono_mb_patch_branch (mb, return_null_pos);
9292 mono_mb_emit_byte (mb, CEE_LDNULL);
9293 mono_mb_emit_byte (mb, CEE_RET);
9296 mono_mb_patch_branch (mb, positive_cache_hit_pos);
9297 mono_mb_emit_ldarg (mb, obj_arg_position);
9298 mono_mb_emit_byte (mb, CEE_RET);
9301 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ISINST_WITH_CACHE);
9302 res = mono_mb_create (mb, sig, 8, info);
9305 if (InterlockedCompareExchangePointer ((volatile gpointer *)&cached, res, NULL)) {
9306 mono_free_method (res);
9307 mono_metadata_free_method_signature (sig);
9315 * mono_marshal_get_struct_to_ptr:
9316 * \param klass \c MonoClass
9318 * Generates IL code for <code>StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld)</code>
9321 mono_marshal_get_struct_to_ptr (MonoClass *klass)
9323 MonoMethodBuilder *mb;
9324 static MonoMethod *stoptr = NULL;
9328 g_assert (klass != NULL);
9330 mono_marshal_load_type_info (klass);
9332 MonoMarshalType *marshal_info = mono_class_get_marshal_info (klass);
9333 if (marshal_info->str_to_ptr)
9334 return marshal_info->str_to_ptr;
9337 stoptr = mono_class_get_method_from_name (mono_defaults.marshal_class, "StructureToPtr", 3);
9340 mb = mono_mb_new (klass, stoptr->name, MONO_WRAPPER_UNKNOWN);
9342 #ifdef HAVE_ONLINE_VES
9343 if (klass->blittable) {
9344 mono_mb_emit_byte (mb, CEE_LDARG_1);
9345 mono_mb_emit_byte (mb, CEE_LDARG_0);
9346 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
9347 mono_mb_emit_icon (mb, mono_class_value_size (klass, NULL));
9348 mono_mb_emit_byte (mb, CEE_PREFIX1);
9349 mono_mb_emit_byte (mb, CEE_CPBLK);
9352 /* allocate local 0 (pointer) src_ptr */
9353 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9354 /* allocate local 1 (pointer) dst_ptr */
9355 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9356 /* allocate local 2 (boolean) delete_old */
9357 mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
9358 mono_mb_emit_byte (mb, CEE_LDARG_2);
9359 mono_mb_emit_stloc (mb, 2);
9361 /* initialize src_ptr to point to the start of object data */
9362 mono_mb_emit_byte (mb, CEE_LDARG_0);
9363 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
9364 mono_mb_emit_stloc (mb, 0);
9366 /* initialize dst_ptr */
9367 mono_mb_emit_byte (mb, CEE_LDARG_1);
9368 mono_mb_emit_stloc (mb, 1);
9370 emit_struct_conv (mb, klass, FALSE);
9373 mono_mb_emit_byte (mb, CEE_RET);
9375 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_STRUCTURE_TO_PTR);
9376 res = mono_mb_create (mb, mono_signature_no_pinvoke (stoptr), 0, info);
9379 mono_marshal_lock ();
9380 if (!marshal_info->str_to_ptr)
9381 marshal_info->str_to_ptr = res;
9383 res = marshal_info->str_to_ptr;
9384 mono_marshal_unlock ();
9389 * mono_marshal_get_ptr_to_struct:
9390 * \param klass \c MonoClass
9391 * Generates IL code for <code>PtrToStructure (IntPtr src, object structure)</code>
9394 mono_marshal_get_ptr_to_struct (MonoClass *klass)
9396 MonoMethodBuilder *mb;
9397 static MonoMethodSignature *ptostr = NULL;
9401 g_assert (klass != NULL);
9403 mono_marshal_load_type_info (klass);
9405 MonoMarshalType *marshal_info = mono_class_get_marshal_info (klass);
9406 if (marshal_info->ptr_to_str)
9407 return marshal_info->ptr_to_str;
9410 MonoMethodSignature *sig;
9412 /* Create the signature corresponding to
9413 static void PtrToStructure (IntPtr ptr, object structure);
9414 defined in class/corlib/System.Runtime.InteropServices/Marshal.cs */
9415 sig = mono_create_icall_signature ("void ptr object");
9416 sig = mono_metadata_signature_dup_full (mono_defaults.corlib, sig);
9418 mono_memory_barrier ();
9422 mb = mono_mb_new (klass, "PtrToStructure", MONO_WRAPPER_UNKNOWN);
9424 #ifdef HAVE_ONLINE_VES
9425 if (klass->blittable) {
9426 mono_mb_emit_byte (mb, CEE_LDARG_1);
9427 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
9428 mono_mb_emit_byte (mb, CEE_LDARG_0);
9429 mono_mb_emit_icon (mb, mono_class_value_size (klass, NULL));
9430 mono_mb_emit_byte (mb, CEE_PREFIX1);
9431 mono_mb_emit_byte (mb, CEE_CPBLK);
9434 /* allocate local 0 (pointer) src_ptr */
9435 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9436 /* allocate local 1 (pointer) dst_ptr */
9437 mono_mb_add_local (mb, &klass->this_arg);
9439 /* initialize src_ptr to point to the start of object data */
9440 mono_mb_emit_byte (mb, CEE_LDARG_0);
9441 mono_mb_emit_stloc (mb, 0);
9443 /* initialize dst_ptr */
9444 mono_mb_emit_byte (mb, CEE_LDARG_1);
9445 mono_mb_emit_op (mb, CEE_UNBOX, klass);
9446 mono_mb_emit_stloc (mb, 1);
9448 emit_struct_conv (mb, klass, TRUE);
9451 mono_mb_emit_byte (mb, CEE_RET);
9453 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_PTR_TO_STRUCTURE);
9454 res = mono_mb_create (mb, ptostr, 0, info);
9457 mono_marshal_lock ();
9458 if (!marshal_info->ptr_to_str)
9459 marshal_info->ptr_to_str = res;
9461 res = marshal_info->ptr_to_str;
9462 mono_marshal_unlock ();
9467 * Return a dummy wrapper for METHOD which is called by synchronized wrappers.
9468 * This is used to avoid infinite recursion since it is hard to determine where to
9469 * replace a method with its synchronized wrapper, and where not.
9470 * The runtime should execute METHOD instead of the wrapper.
9473 mono_marshal_get_synchronized_inner_wrapper (MonoMethod *method)
9475 MonoMethodBuilder *mb;
9477 MonoMethodSignature *sig;
9479 MonoGenericContext *ctx = NULL;
9480 MonoGenericContainer *container = NULL;
9482 if (method->is_inflated && !mono_method_get_context (method)->method_inst) {
9483 ctx = &((MonoMethodInflated*)method)->context;
9484 method = ((MonoMethodInflated*)method)->declaring;
9485 container = mono_method_get_generic_container (method);
9487 container = mono_class_try_get_generic_container (method->klass); //FIXME is this a case of a try?
9488 g_assert (container);
9491 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNKNOWN);
9492 #ifdef HAVE_ONLINE_VES
9493 mono_mb_emit_exception_full (mb, "System", "ExecutionEngineException", "Shouldn't be called.");
9494 mono_mb_emit_byte (mb, CEE_RET);
9496 sig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
9498 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_SYNCHRONIZED_INNER);
9499 info->d.synchronized_inner.method = method;
9500 res = mono_mb_create (mb, sig, 0, info);
9504 res = mono_class_inflate_generic_method_checked (res, ctx, &error);
9505 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9511 * mono_marshal_get_synchronized_wrapper:
9512 * Generates IL code for the synchronized wrapper: the generated method
9513 * calls \p method while locking \c this or the parent type.
9516 mono_marshal_get_synchronized_wrapper (MonoMethod *method)
9518 static MonoMethod *enter_method, *exit_method, *gettypefromhandle_method;
9519 MonoMethodSignature *sig;
9520 MonoExceptionClause *clause;
9521 MonoMethodBuilder *mb;
9525 int i, pos, pos2, this_local, taken_local, ret_local = 0;
9526 MonoGenericContext *ctx = NULL;
9527 MonoMethod *orig_method = NULL;
9528 MonoGenericContainer *container = NULL;
9532 if (method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED)
9535 /* FIXME: Support generic methods too */
9536 if (method->is_inflated && !mono_method_get_context (method)->method_inst) {
9537 orig_method = method;
9538 ctx = &((MonoMethodInflated*)method)->context;
9539 method = ((MonoMethodInflated*)method)->declaring;
9540 container = mono_method_get_generic_container (method);
9542 container = mono_class_try_get_generic_container (method->klass); //FIXME is this a case of a try?
9543 g_assert (container);
9550 cache = get_cache (&((MonoMethodInflated*)orig_method)->owner->wrapper_caches.synchronized_cache, mono_aligned_addr_hash, NULL);
9551 res = check_generic_wrapper_cache (cache, orig_method, orig_method, method);
9555 cache = get_cache (&method->klass->image->wrapper_caches.synchronized_cache, mono_aligned_addr_hash, NULL);
9556 if ((res = mono_marshal_find_in_cache (cache, method)))
9560 sig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
9563 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_SYNCHRONIZED);
9565 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
9566 info->d.synchronized.method = method;
9568 #ifdef HAVE_ONLINE_VES
9569 mb->skip_visibility = 1;
9571 if (!MONO_TYPE_IS_VOID (sig->ret))
9572 ret_local = mono_mb_add_local (mb, sig->ret);
9575 if (method->klass->valuetype && !(method->flags & MONO_METHOD_ATTR_STATIC)) {
9576 /* FIXME Is this really the best way to signal an error here? Isn't this called much later after class setup? -AK */
9577 mono_class_set_type_load_failure (method->klass, "");
9578 #ifdef HAVE_ONLINE_VES
9579 /* This will throw the type load exception when the wrapper is compiled */
9580 mono_mb_emit_byte (mb, CEE_LDNULL);
9581 mono_mb_emit_op (mb, CEE_ISINST, method->klass);
9582 mono_mb_emit_byte (mb, CEE_POP);
9584 if (!MONO_TYPE_IS_VOID (sig->ret))
9585 mono_mb_emit_ldloc (mb, ret_local);
9586 mono_mb_emit_byte (mb, CEE_RET);
9589 res = mono_mb_create_and_cache_full (cache, method,
9590 mb, sig, sig->param_count + 16, info, NULL);
9596 #ifdef HAVE_ONLINE_VES
9598 this_local = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
9599 taken_local = mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
9601 clause = (MonoExceptionClause *)mono_image_alloc0 (method->klass->image, sizeof (MonoExceptionClause));
9602 clause->flags = MONO_EXCEPTION_CLAUSE_FINALLY;
9605 mono_marshal_lock ();
9607 if (!enter_method) {
9608 MonoMethodDesc *desc;
9610 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
9611 enter_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
9612 g_assert (enter_method);
9613 mono_method_desc_free (desc);
9615 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
9616 exit_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
9617 g_assert (exit_method);
9618 mono_method_desc_free (desc);
9620 desc = mono_method_desc_new ("Type:GetTypeFromHandle", FALSE);
9621 gettypefromhandle_method = mono_method_desc_search_in_class (desc, mono_defaults.systemtype_class);
9622 g_assert (gettypefromhandle_method);
9623 mono_method_desc_free (desc);
9626 mono_marshal_unlock ();
9628 #ifdef HAVE_ONLINE_VES
9629 /* Push this or the type object */
9630 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
9631 /* We have special handling for this in the JIT */
9632 int index = mono_mb_add_data (mb, method->klass);
9633 mono_mb_add_data (mb, mono_defaults.typehandle_class);
9634 mono_mb_emit_byte (mb, CEE_LDTOKEN);
9635 mono_mb_emit_i4 (mb, index);
9637 mono_mb_emit_managed_call (mb, gettypefromhandle_method, NULL);
9640 mono_mb_emit_ldarg (mb, 0);
9641 mono_mb_emit_stloc (mb, this_local);
9643 /* Call Monitor::Enter() */
9644 mono_mb_emit_ldloc (mb, this_local);
9645 mono_mb_emit_ldloc_addr (mb, taken_local);
9646 mono_mb_emit_managed_call (mb, enter_method, NULL);
9648 clause->try_offset = mono_mb_get_label (mb);
9650 /* Call the method */
9652 mono_mb_emit_ldarg (mb, 0);
9653 for (i = 0; i < sig->param_count; i++)
9654 mono_mb_emit_ldarg (mb, i + (sig->hasthis == TRUE));
9658 mono_mb_emit_managed_call (mb, mono_class_inflate_generic_method_checked (method, &container->context, &error), NULL);
9659 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9661 mono_mb_emit_managed_call (mb, method, NULL);
9664 if (!MONO_TYPE_IS_VOID (sig->ret))
9665 mono_mb_emit_stloc (mb, ret_local);
9667 pos = mono_mb_emit_branch (mb, CEE_LEAVE);
9669 clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
9670 clause->handler_offset = mono_mb_get_label (mb);
9672 /* Call Monitor::Exit() if needed */
9673 mono_mb_emit_ldloc (mb, taken_local);
9674 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9675 mono_mb_emit_ldloc (mb, this_local);
9676 mono_mb_emit_managed_call (mb, exit_method, NULL);
9677 mono_mb_patch_branch (mb, pos2);
9678 mono_mb_emit_byte (mb, CEE_ENDFINALLY);
9680 clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
9682 mono_mb_patch_branch (mb, pos);
9683 if (!MONO_TYPE_IS_VOID (sig->ret))
9684 mono_mb_emit_ldloc (mb, ret_local);
9685 mono_mb_emit_byte (mb, CEE_RET);
9687 mono_mb_set_clauses (mb, 1, clause);
9692 def = mono_mb_create_and_cache_full (cache, method, mb, sig, sig->param_count + 16, info, NULL);
9693 res = cache_generic_wrapper (cache, orig_method, def, ctx, orig_method);
9695 res = mono_mb_create_and_cache_full (cache, method,
9696 mb, sig, sig->param_count + 16, info, NULL);
9705 * mono_marshal_get_unbox_wrapper:
9706 * The returned method calls \p method unboxing the \c this argument.
9709 mono_marshal_get_unbox_wrapper (MonoMethod *method)
9711 MonoMethodSignature *sig = mono_method_signature (method);
9713 MonoMethodBuilder *mb;
9718 cache = get_cache (&mono_method_get_wrapper_cache (method)->unbox_wrapper_cache, mono_aligned_addr_hash, NULL);
9720 if ((res = mono_marshal_find_in_cache (cache, method)))
9723 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNBOX);
9725 g_assert (sig->hasthis);
9727 #ifdef HAVE_ONLINE_VES
9728 mono_mb_emit_ldarg (mb, 0);
9729 mono_mb_emit_icon (mb, sizeof (MonoObject));
9730 mono_mb_emit_byte (mb, CEE_ADD);
9731 for (i = 0; i < sig->param_count; ++i)
9732 mono_mb_emit_ldarg (mb, i + 1);
9733 mono_mb_emit_managed_call (mb, method, NULL);
9734 mono_mb_emit_byte (mb, CEE_RET);
9737 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
9738 info->d.unbox.method = method;
9740 res = mono_mb_create_and_cache_full (cache, method,
9741 mb, sig, sig->param_count + 16, info, NULL);
9744 /* mono_method_print_code (res); */
9750 STELEMREF_OBJECT, /*no check at all*/
9751 STELEMREF_SEALED_CLASS, /*check vtable->klass->element_type */
9752 STELEMREF_CLASS, /*only the klass->parents check*/
9753 STELEMREF_CLASS_SMALL_IDEPTH, /* like STELEMREF_CLASS bit without the idepth check */
9754 STELEMREF_INTERFACE, /*interfaces without variant generic arguments. */
9755 STELEMREF_COMPLEX, /*arrays, MBR or types with variant generic args - go straight to icalls*/
9756 STELEMREF_KIND_COUNT
9759 static const char *strelemref_wrapper_name[] = {
9760 "object", "sealed_class", "class", "class_small_idepth", "interface", "complex"
9764 is_monomorphic_array (MonoClass *klass)
9766 MonoClass *element_class;
9767 if (klass->rank != 1)
9770 element_class = klass->element_class;
9771 return mono_class_is_sealed (element_class) || element_class->valuetype;
9775 get_virtual_stelemref_kind (MonoClass *element_class)
9777 if (element_class == mono_defaults.object_class)
9778 return STELEMREF_OBJECT;
9779 if (is_monomorphic_array (element_class))
9780 return STELEMREF_SEALED_CLASS;
9781 /* Compressed interface bitmaps require code that is quite complex, so don't optimize for it. */
9782 if (MONO_CLASS_IS_INTERFACE (element_class) && !mono_class_has_variant_generic_params (element_class))
9783 #ifdef COMPRESSED_INTERFACE_BITMAP
9784 return STELEMREF_COMPLEX;
9786 return STELEMREF_INTERFACE;
9788 /*Arrays are sealed but are covariant on their element type, We can't use any of the fast paths.*/
9789 if (mono_class_is_marshalbyref (element_class) || element_class->rank || mono_class_has_variant_generic_params (element_class))
9790 return STELEMREF_COMPLEX;
9791 if (mono_class_is_sealed (element_class))
9792 return STELEMREF_SEALED_CLASS;
9793 if (element_class->idepth <= MONO_DEFAULT_SUPERTABLE_SIZE)
9794 return STELEMREF_CLASS_SMALL_IDEPTH;
9796 return STELEMREF_CLASS;
9799 #ifdef HAVE_ONLINE_VES
9802 load_array_element_address (MonoMethodBuilder *mb)
9804 mono_mb_emit_ldarg (mb, 0);
9805 mono_mb_emit_ldarg (mb, 1);
9806 mono_mb_emit_op (mb, CEE_LDELEMA, mono_defaults.object_class);
9810 load_array_class (MonoMethodBuilder *mb, int aklass)
9812 mono_mb_emit_ldarg (mb, 0);
9813 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9814 mono_mb_emit_byte (mb, CEE_LDIND_I);
9815 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
9816 mono_mb_emit_byte (mb, CEE_LDIND_I);
9817 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, element_class));
9818 mono_mb_emit_byte (mb, CEE_LDIND_I);
9819 mono_mb_emit_stloc (mb, aklass);
9823 load_value_class (MonoMethodBuilder *mb, int vklass)
9825 mono_mb_emit_ldarg (mb, 2);
9826 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9827 mono_mb_emit_byte (mb, CEE_LDIND_I);
9828 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
9829 mono_mb_emit_byte (mb, CEE_LDIND_I);
9830 mono_mb_emit_stloc (mb, vklass);
9836 record_slot_vstore (MonoObject *array, size_t index, MonoObject *value)
9838 char *name = mono_type_get_full_name (array->vtable->klass->element_class);
9839 printf ("slow vstore of %s\n", name);
9846 * - Separate simple interfaces from variant interfaces or mbr types. This way we can avoid the icall for them.
9847 * - Emit a (new) mono bytecode that produces OP_COND_EXC_NE_UN to raise ArrayTypeMismatch
9848 * - Maybe mve some MonoClass field into the vtable to reduce the number of loads
9849 * - Add a case for arrays of arrays.
9852 get_virtual_stelemref_wrapper (int kind)
9854 static MonoMethod *cached_methods [STELEMREF_KIND_COUNT] = { NULL }; /*object iface sealed regular*/
9855 static MonoMethodSignature *signature;
9856 MonoMethodBuilder *mb;
9859 const char *param_names [16];
9860 guint32 b1, b2, b3, b4;
9861 int aklass, vklass, vtable, uiid;
9862 int array_slot_addr;
9865 if (cached_methods [kind])
9866 return cached_methods [kind];
9868 name = g_strdup_printf ("virt_stelemref_%s", strelemref_wrapper_name [kind]);
9869 mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_STELEMREF);
9873 MonoMethodSignature *sig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
9875 /* void this::stelemref (size_t idx, void* value) */
9876 sig->ret = &mono_defaults.void_class->byval_arg;
9877 sig->hasthis = TRUE;
9878 sig->params [0] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
9879 sig->params [1] = &mono_defaults.object_class->byval_arg;
9883 #ifdef HAVE_ONLINE_VES
9884 param_names [0] = "index";
9885 param_names [1] = "value";
9886 mono_mb_set_param_names (mb, param_names);
9888 /*For now simply call plain old stelemref*/
9890 case STELEMREF_OBJECT:
9891 /* ldelema (implicit bound check) */
9892 load_array_element_address (mb);
9894 mono_mb_emit_ldarg (mb, 2);
9895 mono_mb_emit_byte (mb, CEE_STIND_REF);
9896 mono_mb_emit_byte (mb, CEE_RET);
9899 case STELEMREF_COMPLEX: {
9902 <ldelema (bound check)>
9905 if (!mono_object_isinst (value, aklass))
9909 *array_slot_addr = value;
9912 throw new ArrayTypeMismatchException ();
9915 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9916 vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9917 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9921 /*Use this to debug/record stores that are going thru the slow path*/
9922 MonoMethodSignature *csig;
9923 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
9924 csig->ret = &mono_defaults.void_class->byval_arg;
9925 csig->params [0] = &mono_defaults.object_class->byval_arg;
9926 csig->params [1] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
9927 csig->params [2] = &mono_defaults.object_class->byval_arg;
9928 mono_mb_emit_ldarg (mb, 0);
9929 mono_mb_emit_ldarg (mb, 1);
9930 mono_mb_emit_ldarg (mb, 2);
9931 mono_mb_emit_native_call (mb, csig, record_slot_vstore);
9935 /* ldelema (implicit bound check) */
9936 load_array_element_address (mb);
9937 mono_mb_emit_stloc (mb, array_slot_addr);
9939 /* if (!value) goto do_store */
9940 mono_mb_emit_ldarg (mb, 2);
9941 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9943 /* aklass = array->vtable->klass->element_class */
9944 load_array_class (mb, aklass);
9945 /* vklass = value->vtable->klass */
9946 load_value_class (mb, vklass);
9949 mono_mb_emit_ldloc (mb, vklass);
9950 mono_mb_emit_ldloc (mb, aklass);
9951 b_fast = mono_mb_emit_branch (mb, CEE_BEQ);
9953 /*if (mono_object_isinst (value, aklass)) */
9954 mono_mb_emit_ldarg (mb, 2);
9955 mono_mb_emit_ldloc (mb, aklass);
9956 mono_mb_emit_icall (mb, mono_object_isinst_icall);
9957 b2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9960 mono_mb_patch_branch (mb, b1);
9961 mono_mb_patch_branch (mb, b_fast);
9962 mono_mb_emit_ldloc (mb, array_slot_addr);
9963 mono_mb_emit_ldarg (mb, 2);
9964 mono_mb_emit_byte (mb, CEE_STIND_REF);
9965 mono_mb_emit_byte (mb, CEE_RET);
9968 mono_mb_patch_branch (mb, b2);
9970 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9973 case STELEMREF_SEALED_CLASS:
9975 <ldelema (bound check)>
9979 aklass = array->vtable->klass->element_class;
9980 vklass = value->vtable->klass;
9982 if (vklass != aklass)
9986 *array_slot_addr = value;
9989 throw new ArrayTypeMismatchException ();
9991 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9992 vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9993 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9995 /* ldelema (implicit bound check) */
9996 load_array_element_address (mb);
9997 mono_mb_emit_stloc (mb, array_slot_addr);
9999 /* if (!value) goto do_store */
10000 mono_mb_emit_ldarg (mb, 2);
10001 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
10003 /* aklass = array->vtable->klass->element_class */
10004 load_array_class (mb, aklass);
10006 /* vklass = value->vtable->klass */
10007 load_value_class (mb, vklass);
10009 /*if (vklass != aklass) goto do_exception; */
10010 mono_mb_emit_ldloc (mb, aklass);
10011 mono_mb_emit_ldloc (mb, vklass);
10012 b2 = mono_mb_emit_branch (mb, CEE_BNE_UN);
10015 mono_mb_patch_branch (mb, b1);
10016 mono_mb_emit_ldloc (mb, array_slot_addr);
10017 mono_mb_emit_ldarg (mb, 2);
10018 mono_mb_emit_byte (mb, CEE_STIND_REF);
10019 mono_mb_emit_byte (mb, CEE_RET);
10021 /* do_exception: */
10022 mono_mb_patch_branch (mb, b2);
10023 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
10026 case STELEMREF_CLASS: {
10029 <ldelema (bound check)>
10033 aklass = array->vtable->klass->element_class;
10034 vklass = value->vtable->klass;
10036 if (vklass->idepth < aklass->idepth)
10039 if (vklass->supertypes [aklass->idepth - 1] != aklass)
10043 *array_slot_addr = value;
10047 throw new ArrayTypeMismatchException ();
10049 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10050 vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10051 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
10053 /* ldelema (implicit bound check) */
10054 load_array_element_address (mb);
10055 mono_mb_emit_stloc (mb, array_slot_addr);
10057 /* if (!value) goto do_store */
10058 mono_mb_emit_ldarg (mb, 2);
10059 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
10061 /* aklass = array->vtable->klass->element_class */
10062 load_array_class (mb, aklass);
10064 /* vklass = value->vtable->klass */
10065 load_value_class (mb, vklass);
10067 /* if (vklass->idepth < aklass->idepth) goto failue */
10068 mono_mb_emit_ldloc (mb, vklass);
10069 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
10070 mono_mb_emit_byte (mb, CEE_LDIND_U2);
10072 mono_mb_emit_ldloc (mb, aklass);
10073 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
10074 mono_mb_emit_byte (mb, CEE_LDIND_U2);
10076 b3 = mono_mb_emit_branch (mb, CEE_BLT_UN);
10078 /* if (vklass->supertypes [aklass->idepth - 1] != aklass) goto failure */
10079 mono_mb_emit_ldloc (mb, vklass);
10080 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, supertypes));
10081 mono_mb_emit_byte (mb, CEE_LDIND_I);
10083 mono_mb_emit_ldloc (mb, aklass);
10084 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
10085 mono_mb_emit_byte (mb, CEE_LDIND_U2);
10086 mono_mb_emit_icon (mb, 1);
10087 mono_mb_emit_byte (mb, CEE_SUB);
10088 mono_mb_emit_icon (mb, sizeof (void*));
10089 mono_mb_emit_byte (mb, CEE_MUL);
10090 mono_mb_emit_byte (mb, CEE_ADD);
10091 mono_mb_emit_byte (mb, CEE_LDIND_I);
10093 mono_mb_emit_ldloc (mb, aklass);
10094 b4 = mono_mb_emit_branch (mb, CEE_BNE_UN);
10097 mono_mb_patch_branch (mb, b1);
10098 mono_mb_emit_ldloc (mb, array_slot_addr);
10099 mono_mb_emit_ldarg (mb, 2);
10100 mono_mb_emit_byte (mb, CEE_STIND_REF);
10101 mono_mb_emit_byte (mb, CEE_RET);
10103 /* do_exception: */
10104 mono_mb_patch_branch (mb, b3);
10105 mono_mb_patch_branch (mb, b4);
10107 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
10111 case STELEMREF_CLASS_SMALL_IDEPTH:
10114 <ldelema (bound check)>
10118 aklass = array->vtable->klass->element_class;
10119 vklass = value->vtable->klass;
10121 if (vklass->supertypes [aklass->idepth - 1] != aklass)
10125 *array_slot_addr = value;
10129 throw new ArrayTypeMismatchException ();
10131 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10132 vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10133 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
10135 /* ldelema (implicit bound check) */
10136 load_array_element_address (mb);
10137 mono_mb_emit_stloc (mb, array_slot_addr);
10139 /* if (!value) goto do_store */
10140 mono_mb_emit_ldarg (mb, 2);
10141 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
10143 /* aklass = array->vtable->klass->element_class */
10144 load_array_class (mb, aklass);
10146 /* vklass = value->vtable->klass */
10147 load_value_class (mb, vklass);
10149 /* if (vklass->supertypes [aklass->idepth - 1] != aklass) goto failure */
10150 mono_mb_emit_ldloc (mb, vklass);
10151 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, supertypes));
10152 mono_mb_emit_byte (mb, CEE_LDIND_I);
10154 mono_mb_emit_ldloc (mb, aklass);
10155 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
10156 mono_mb_emit_byte (mb, CEE_LDIND_U2);
10157 mono_mb_emit_icon (mb, 1);
10158 mono_mb_emit_byte (mb, CEE_SUB);
10159 mono_mb_emit_icon (mb, sizeof (void*));
10160 mono_mb_emit_byte (mb, CEE_MUL);
10161 mono_mb_emit_byte (mb, CEE_ADD);
10162 mono_mb_emit_byte (mb, CEE_LDIND_I);
10164 mono_mb_emit_ldloc (mb, aklass);
10165 b4 = mono_mb_emit_branch (mb, CEE_BNE_UN);
10168 mono_mb_patch_branch (mb, b1);
10169 mono_mb_emit_ldloc (mb, array_slot_addr);
10170 mono_mb_emit_ldarg (mb, 2);
10171 mono_mb_emit_byte (mb, CEE_STIND_REF);
10172 mono_mb_emit_byte (mb, CEE_RET);
10174 /* do_exception: */
10175 mono_mb_patch_branch (mb, b4);
10177 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
10180 case STELEMREF_INTERFACE:
10187 klass = array->obj.vtable->klass->element_class;
10188 vt = value->vtable;
10189 uiid = klass->interface_id;
10190 if (uiid > vt->max_interface_id)
10192 if (!(vt->interface_bitmap [(uiid) >> 3] & (1 << ((uiid)&7))))
10195 mono_array_setref (array, index, value);
10198 mono_raise_exception (mono_get_exception_array_type_mismatch ());*/
10200 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
10201 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10202 vtable = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10203 uiid = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
10205 /* ldelema (implicit bound check) */
10206 load_array_element_address (mb);
10207 mono_mb_emit_stloc (mb, array_slot_addr);
10209 /* if (!value) goto do_store */
10210 mono_mb_emit_ldarg (mb, 2);
10211 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
10213 /* klass = array->vtable->klass->element_class */
10214 load_array_class (mb, aklass);
10216 /* vt = value->vtable */
10217 mono_mb_emit_ldarg (mb, 2);
10218 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
10219 mono_mb_emit_byte (mb, CEE_LDIND_I);
10220 mono_mb_emit_stloc (mb, vtable);
10222 /* uiid = klass->interface_id; */
10223 mono_mb_emit_ldloc (mb, aklass);
10224 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, interface_id));
10225 mono_mb_emit_byte (mb, CEE_LDIND_U4);
10226 mono_mb_emit_stloc (mb, uiid);
10228 /*if (uiid > vt->max_interface_id)*/
10229 mono_mb_emit_ldloc (mb, uiid);
10230 mono_mb_emit_ldloc (mb, vtable);
10231 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, max_interface_id));
10232 mono_mb_emit_byte (mb, CEE_LDIND_U4);
10233 b2 = mono_mb_emit_branch (mb, CEE_BGT_UN);
10235 /* if (!(vt->interface_bitmap [(uiid) >> 3] & (1 << ((uiid)&7)))) */
10237 /*vt->interface_bitmap*/
10238 mono_mb_emit_ldloc (mb, vtable);
10239 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, interface_bitmap));
10240 mono_mb_emit_byte (mb, CEE_LDIND_I);
10243 mono_mb_emit_ldloc (mb, uiid);
10244 mono_mb_emit_icon (mb, 3);
10245 mono_mb_emit_byte (mb, CEE_SHR_UN);
10247 /*vt->interface_bitmap [(uiid) >> 3]*/
10248 mono_mb_emit_byte (mb, CEE_ADD); /*interface_bitmap is a guint8 array*/
10249 mono_mb_emit_byte (mb, CEE_LDIND_U1);
10251 /*(1 << ((uiid)&7)))*/
10252 mono_mb_emit_icon (mb, 1);
10253 mono_mb_emit_ldloc (mb, uiid);
10254 mono_mb_emit_icon (mb, 7);
10255 mono_mb_emit_byte (mb, CEE_AND);
10256 mono_mb_emit_byte (mb, CEE_SHL);
10258 /*bitwise and the whole thing*/
10259 mono_mb_emit_byte (mb, CEE_AND);
10260 b3 = mono_mb_emit_branch (mb, CEE_BRFALSE);
10263 mono_mb_patch_branch (mb, b1);
10264 mono_mb_emit_ldloc (mb, array_slot_addr);
10265 mono_mb_emit_ldarg (mb, 2);
10266 mono_mb_emit_byte (mb, CEE_STIND_REF);
10267 mono_mb_emit_byte (mb, CEE_RET);
10269 /* do_exception: */
10270 mono_mb_patch_branch (mb, b2);
10271 mono_mb_patch_branch (mb, b3);
10272 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
10276 mono_mb_emit_ldarg (mb, 0);
10277 mono_mb_emit_ldarg (mb, 1);
10278 mono_mb_emit_ldarg (mb, 2);
10279 mono_mb_emit_managed_call (mb, mono_marshal_get_stelemref (), NULL);
10280 mono_mb_emit_byte (mb, CEE_RET);
10283 #endif /* HAVE_ONLINE_VES */
10284 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_VIRTUAL_STELEMREF);
10285 info->d.virtual_stelemref.kind = kind;
10286 res = mono_mb_create (mb, signature, 4, info);
10287 res->flags |= METHOD_ATTRIBUTE_VIRTUAL;
10289 mono_marshal_lock ();
10290 if (!cached_methods [kind]) {
10291 cached_methods [kind] = res;
10292 mono_marshal_unlock ();
10294 mono_marshal_unlock ();
10295 mono_free_method (res);
10299 return cached_methods [kind];
10303 mono_marshal_get_virtual_stelemref (MonoClass *array_class)
10307 g_assert (array_class->rank == 1);
10308 kind = get_virtual_stelemref_kind (array_class->element_class);
10310 return get_virtual_stelemref_wrapper (kind);
10314 mono_marshal_get_virtual_stelemref_wrappers (int *nwrappers)
10319 *nwrappers = STELEMREF_KIND_COUNT;
10320 res = (MonoMethod **)g_malloc0 (STELEMREF_KIND_COUNT * sizeof (MonoMethod*));
10321 for (i = 0; i < STELEMREF_KIND_COUNT; ++i)
10322 res [i] = get_virtual_stelemref_wrapper (i);
10327 * mono_marshal_get_stelemref:
10330 mono_marshal_get_stelemref (void)
10332 static MonoMethod* ret = NULL;
10333 MonoMethodSignature *sig;
10334 MonoMethodBuilder *mb;
10337 guint32 b1, b2, b3, b4;
10339 int aklass, vklass;
10340 int array_slot_addr;
10345 mb = mono_mb_new (mono_defaults.object_class, "stelemref", MONO_WRAPPER_STELEMREF);
10348 sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
10350 /* void stelemref (void* array, int idx, void* value) */
10351 sig->ret = &mono_defaults.void_class->byval_arg;
10352 sig->params [0] = &mono_defaults.object_class->byval_arg;
10353 sig->params [1] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
10354 sig->params [2] = &mono_defaults.object_class->byval_arg;
10356 #ifdef HAVE_ONLINE_VES
10357 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10358 vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10359 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
10363 <ldelema (bound check)>
10367 aklass = array->vtable->klass->element_class;
10368 vklass = value->vtable->klass;
10370 if (vklass->idepth < aklass->idepth)
10373 if (vklass->supertypes [aklass->idepth - 1] != aklass)
10377 *array_slot_addr = value;
10381 if (mono_object_isinst (value, aklass))
10384 throw new ArrayTypeMismatchException ();
10387 /* ldelema (implicit bound check) */
10388 mono_mb_emit_ldarg (mb, 0);
10389 mono_mb_emit_ldarg (mb, 1);
10390 mono_mb_emit_op (mb, CEE_LDELEMA, mono_defaults.object_class);
10391 mono_mb_emit_stloc (mb, array_slot_addr);
10393 /* if (!value) goto do_store */
10394 mono_mb_emit_ldarg (mb, 2);
10395 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
10397 /* aklass = array->vtable->klass->element_class */
10398 mono_mb_emit_ldarg (mb, 0);
10399 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
10400 mono_mb_emit_byte (mb, CEE_LDIND_I);
10401 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
10402 mono_mb_emit_byte (mb, CEE_LDIND_I);
10403 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, element_class));
10404 mono_mb_emit_byte (mb, CEE_LDIND_I);
10405 mono_mb_emit_stloc (mb, aklass);
10407 /* vklass = value->vtable->klass */
10408 mono_mb_emit_ldarg (mb, 2);
10409 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
10410 mono_mb_emit_byte (mb, CEE_LDIND_I);
10411 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
10412 mono_mb_emit_byte (mb, CEE_LDIND_I);
10413 mono_mb_emit_stloc (mb, vklass);
10415 /* if (vklass->idepth < aklass->idepth) goto failue */
10416 mono_mb_emit_ldloc (mb, vklass);
10417 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
10418 mono_mb_emit_byte (mb, CEE_LDIND_U2);
10420 mono_mb_emit_ldloc (mb, aklass);
10421 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
10422 mono_mb_emit_byte (mb, CEE_LDIND_U2);
10424 b2 = mono_mb_emit_branch (mb, CEE_BLT_UN);
10426 /* if (vklass->supertypes [aklass->idepth - 1] != aklass) goto failure */
10427 mono_mb_emit_ldloc (mb, vklass);
10428 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, supertypes));
10429 mono_mb_emit_byte (mb, CEE_LDIND_I);
10431 mono_mb_emit_ldloc (mb, aklass);
10432 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
10433 mono_mb_emit_byte (mb, CEE_LDIND_U2);
10434 mono_mb_emit_icon (mb, 1);
10435 mono_mb_emit_byte (mb, CEE_SUB);
10436 mono_mb_emit_icon (mb, sizeof (void*));
10437 mono_mb_emit_byte (mb, CEE_MUL);
10438 mono_mb_emit_byte (mb, CEE_ADD);
10439 mono_mb_emit_byte (mb, CEE_LDIND_I);
10441 mono_mb_emit_ldloc (mb, aklass);
10443 b3 = mono_mb_emit_branch (mb, CEE_BNE_UN);
10445 copy_pos = mono_mb_get_label (mb);
10447 mono_mb_patch_branch (mb, b1);
10448 mono_mb_emit_ldloc (mb, array_slot_addr);
10449 mono_mb_emit_ldarg (mb, 2);
10450 mono_mb_emit_byte (mb, CEE_STIND_REF);
10452 mono_mb_emit_byte (mb, CEE_RET);
10455 mono_mb_patch_branch (mb, b2);
10456 mono_mb_patch_branch (mb, b3);
10458 mono_mb_emit_ldarg (mb, 2);
10459 mono_mb_emit_ldloc (mb, aklass);
10460 mono_mb_emit_icall (mb, mono_object_isinst_icall);
10462 b4 = mono_mb_emit_branch (mb, CEE_BRTRUE);
10463 mono_mb_patch_addr (mb, b4, copy_pos - (b4 + 4));
10464 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
10466 mono_mb_emit_byte (mb, CEE_RET);
10468 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
10469 ret = mono_mb_create (mb, sig, 4, info);
10476 * mono_marshal_get_gsharedvt_in_wrapper:
10478 * This wrapper handles calls from normal code to gsharedvt code.
10481 mono_marshal_get_gsharedvt_in_wrapper (void)
10483 static MonoMethod* ret = NULL;
10484 MonoMethodSignature *sig;
10485 MonoMethodBuilder *mb;
10491 mb = mono_mb_new (mono_defaults.object_class, "gsharedvt_in", MONO_WRAPPER_UNKNOWN);
10493 sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
10494 sig->ret = &mono_defaults.void_class->byval_arg;
10496 #ifdef HAVE_ONLINE_VES
10498 * The body is generated by the JIT, we use a wrapper instead of a trampoline so EH works.
10500 mono_mb_emit_byte (mb, CEE_RET);
10502 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_GSHAREDVT_IN);
10503 ret = mono_mb_create (mb, sig, 4, info);
10510 * mono_marshal_get_gsharedvt_out_wrapper:
10512 * This wrapper handles calls from gsharedvt code to normal code.
10515 mono_marshal_get_gsharedvt_out_wrapper (void)
10517 static MonoMethod* ret = NULL;
10518 MonoMethodSignature *sig;
10519 MonoMethodBuilder *mb;
10525 mb = mono_mb_new (mono_defaults.object_class, "gsharedvt_out", MONO_WRAPPER_UNKNOWN);
10527 sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
10528 sig->ret = &mono_defaults.void_class->byval_arg;
10530 #ifdef HAVE_ONLINE_VES
10532 * The body is generated by the JIT, we use a wrapper instead of a trampoline so EH works.
10534 mono_mb_emit_byte (mb, CEE_RET);
10536 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_GSHAREDVT_OUT);
10537 ret = mono_mb_create (mb, sig, 4, info);
10546 MonoMethod *method;
10549 /* LOCKING: vars accessed under the marshal lock */
10550 static ArrayElemAddr *elem_addr_cache = NULL;
10551 static int elem_addr_cache_size = 0;
10552 static int elem_addr_cache_next = 0;
10555 * mono_marshal_get_array_address:
10556 * \param rank rank of the array type
10557 * \param elem_size size in bytes of an element of an array.
10559 * Returns a MonoMethod that implements the code to get the address
10560 * of an element in a multi-dimenasional array of \p rank dimensions.
10561 * The returned method takes an array as the first argument and then
10562 * \p rank indexes for the \p rank dimensions.
10563 * If ELEM_SIZE is 0, read the array size from the array object.
10566 mono_marshal_get_array_address (int rank, int elem_size)
10569 MonoMethodBuilder *mb;
10570 MonoMethodSignature *sig;
10573 int i, bounds, ind, realidx;
10574 int branch_pos, *branch_positions;
10578 mono_marshal_lock ();
10579 for (i = 0; i < elem_addr_cache_next; ++i) {
10580 if (elem_addr_cache [i].rank == rank && elem_addr_cache [i].elem_size == elem_size) {
10581 ret = elem_addr_cache [i].method;
10585 mono_marshal_unlock ();
10589 branch_positions = g_new0 (int, rank);
10591 sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1 + rank);
10593 /* void* address (void* array, int idx0, int idx1, int idx2, ...) */
10594 sig->ret = &mono_defaults.int_class->byval_arg;
10595 sig->params [0] = &mono_defaults.object_class->byval_arg;
10596 for (i = 0; i < rank; ++i) {
10597 sig->params [i + 1] = &mono_defaults.int32_class->byval_arg;
10600 name = g_strdup_printf ("ElementAddr_%d", elem_size);
10601 mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_MANAGED);
10604 #ifdef HAVE_ONLINE_VES
10605 bounds = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10606 ind = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
10607 realidx = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
10609 /* bounds = array->bounds; */
10610 mono_mb_emit_ldarg (mb, 0);
10611 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoArray, bounds));
10612 mono_mb_emit_byte (mb, CEE_LDIND_I);
10613 mono_mb_emit_stloc (mb, bounds);
10615 /* ind is the overall element index, realidx is the partial index in a single dimension */
10616 /* ind = idx0 - bounds [0].lower_bound */
10617 mono_mb_emit_ldarg (mb, 1);
10618 mono_mb_emit_ldloc (mb, bounds);
10619 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
10620 mono_mb_emit_byte (mb, CEE_ADD);
10621 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10622 mono_mb_emit_byte (mb, CEE_SUB);
10623 mono_mb_emit_stloc (mb, ind);
10624 /* if (ind >= bounds [0].length) goto exeception; */
10625 mono_mb_emit_ldloc (mb, ind);
10626 mono_mb_emit_ldloc (mb, bounds);
10627 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArrayBounds, length));
10628 mono_mb_emit_byte (mb, CEE_ADD);
10629 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10630 /* note that we use unsigned comparison */
10631 branch_pos = mono_mb_emit_branch (mb, CEE_BGE_UN);
10633 /* For large ranks (> 4?) use a loop n IL later to reduce code size.
10634 * We could also decide to ignore the passed elem_size and get it
10635 * from the array object, to reduce the number of methods we generate:
10636 * the additional cost is 3 memory loads and a non-immediate mul.
10638 for (i = 1; i < rank; ++i) {
10639 /* realidx = idxi - bounds [i].lower_bound */
10640 mono_mb_emit_ldarg (mb, 1 + i);
10641 mono_mb_emit_ldloc (mb, bounds);
10642 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
10643 mono_mb_emit_byte (mb, CEE_ADD);
10644 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10645 mono_mb_emit_byte (mb, CEE_SUB);
10646 mono_mb_emit_stloc (mb, realidx);
10647 /* if (realidx >= bounds [i].length) goto exeception; */
10648 mono_mb_emit_ldloc (mb, realidx);
10649 mono_mb_emit_ldloc (mb, bounds);
10650 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + MONO_STRUCT_OFFSET (MonoArrayBounds, length));
10651 mono_mb_emit_byte (mb, CEE_ADD);
10652 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10653 branch_positions [i] = mono_mb_emit_branch (mb, CEE_BGE_UN);
10654 /* ind = ind * bounds [i].length + realidx */
10655 mono_mb_emit_ldloc (mb, ind);
10656 mono_mb_emit_ldloc (mb, bounds);
10657 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + MONO_STRUCT_OFFSET (MonoArrayBounds, length));
10658 mono_mb_emit_byte (mb, CEE_ADD);
10659 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10660 mono_mb_emit_byte (mb, CEE_MUL);
10661 mono_mb_emit_ldloc (mb, realidx);
10662 mono_mb_emit_byte (mb, CEE_ADD);
10663 mono_mb_emit_stloc (mb, ind);
10666 /* return array->vector + ind * element_size */
10667 mono_mb_emit_ldarg (mb, 0);
10668 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
10669 mono_mb_emit_ldloc (mb, ind);
10671 mono_mb_emit_icon (mb, elem_size);
10673 /* Load arr->vtable->klass->sizes.element_class */
10674 mono_mb_emit_ldarg (mb, 0);
10675 mono_mb_emit_byte (mb, CEE_CONV_I);
10676 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
10677 mono_mb_emit_byte (mb, CEE_ADD);
10678 mono_mb_emit_byte (mb, CEE_LDIND_I);
10679 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
10680 mono_mb_emit_byte (mb, CEE_ADD);
10681 mono_mb_emit_byte (mb, CEE_LDIND_I);
10682 /* sizes is an union, so this reads sizes.element_size */
10683 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoClass, sizes));
10684 mono_mb_emit_byte (mb, CEE_ADD);
10685 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10687 mono_mb_emit_byte (mb, CEE_MUL);
10688 mono_mb_emit_byte (mb, CEE_ADD);
10689 mono_mb_emit_byte (mb, CEE_RET);
10691 /* patch the branches to get here and throw */
10692 for (i = 1; i < rank; ++i) {
10693 mono_mb_patch_branch (mb, branch_positions [i]);
10695 mono_mb_patch_branch (mb, branch_pos);
10696 /* throw exception */
10697 mono_mb_emit_exception (mb, "IndexOutOfRangeException", NULL);
10699 g_free (branch_positions);
10700 #endif /* HAVE_ONLINE_VES */
10702 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ELEMENT_ADDR);
10703 info->d.element_addr.rank = rank;
10704 info->d.element_addr.elem_size = elem_size;
10705 ret = mono_mb_create (mb, sig, 4, info);
10708 /* cache the result */
10710 mono_marshal_lock ();
10711 for (i = 0; i < elem_addr_cache_next; ++i) {
10712 if (elem_addr_cache [i].rank == rank && elem_addr_cache [i].elem_size == elem_size) {
10713 /* FIXME: free ret */
10714 ret = elem_addr_cache [i].method;
10720 if (elem_addr_cache_next >= elem_addr_cache_size) {
10721 int new_size = elem_addr_cache_size + 4;
10722 ArrayElemAddr *new_array = g_new0 (ArrayElemAddr, new_size);
10723 memcpy (new_array, elem_addr_cache, elem_addr_cache_size * sizeof (ArrayElemAddr));
10724 g_free (elem_addr_cache);
10725 elem_addr_cache = new_array;
10726 elem_addr_cache_size = new_size;
10728 elem_addr_cache [elem_addr_cache_next].rank = rank;
10729 elem_addr_cache [elem_addr_cache_next].elem_size = elem_size;
10730 elem_addr_cache [elem_addr_cache_next].method = ret;
10731 elem_addr_cache_next ++;
10733 mono_marshal_unlock ();
10738 * mono_marshal_get_array_accessor_wrapper:
10740 * Return a wrapper which just calls METHOD, which should be an Array Get/Set/Address method.
10743 mono_marshal_get_array_accessor_wrapper (MonoMethod *method)
10745 MonoMethodSignature *sig;
10746 MonoMethodBuilder *mb;
10750 MonoGenericContext *ctx = NULL;
10751 MonoMethod *orig_method = NULL;
10752 MonoGenericContainer *container = NULL;
10756 * These wrappers are needed to avoid the JIT replacing the calls to these methods with intrinsics
10757 * inside runtime invoke wrappers, thereby making the wrappers not unshareable.
10758 * FIXME: Use generic methods.
10765 g_assert_not_reached ();
10767 cache = get_cache (&method->klass->image->array_accessor_cache, mono_aligned_addr_hash, NULL);
10768 if ((res = mono_marshal_find_in_cache (cache, method)))
10772 sig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
10775 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNKNOWN);
10777 #ifdef HAVE_ONLINE_VES
10778 /* Call the method */
10780 mono_mb_emit_ldarg (mb, 0);
10781 for (i = 0; i < sig->param_count; i++)
10782 mono_mb_emit_ldarg (mb, i + (sig->hasthis == TRUE));
10786 mono_mb_emit_managed_call (mb, mono_class_inflate_generic_method_checked (method, &container->context, &error), NULL);
10787 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
10789 mono_mb_emit_managed_call (mb, method, NULL);
10791 mono_mb_emit_byte (mb, CEE_RET);
10794 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ARRAY_ACCESSOR);
10795 info->d.array_accessor.method = method;
10799 def = mono_mb_create_and_cache_full (cache, method, mb, sig, sig->param_count + 16, info, NULL);
10800 res = cache_generic_wrapper (cache, orig_method, def, ctx, orig_method);
10802 res = mono_mb_create_and_cache_full (cache, method,
10803 mb, sig, sig->param_count + 16,
10812 static inline void*
10813 mono_marshal_alloc_co_task_mem (size_t size)
10815 if ((gulong)size == 0)
10816 /* This returns a valid pointer for size 0 on MS.NET */
10819 return g_try_malloc ((gulong)size);
10824 * mono_marshal_alloc:
10827 mono_marshal_alloc (gsize size, MonoError *error)
10831 error_init (error);
10833 res = mono_marshal_alloc_co_task_mem (size);
10835 mono_error_set_out_of_memory (error, "Could not allocate %lu bytes", size);
10840 /* This is a JIT icall, it sets the pending exception and returns NULL on error. */
10842 ves_icall_marshal_alloc (gsize size)
10845 void *ret = mono_marshal_alloc (size, &error);
10846 if (!mono_error_ok (&error)) {
10847 mono_error_set_pending_exception (&error);
10856 mono_marshal_free_co_task_mem (void *ptr)
10864 * mono_marshal_free:
10867 mono_marshal_free (gpointer ptr)
10869 mono_marshal_free_co_task_mem (ptr);
10873 * mono_marshal_free_array:
10876 mono_marshal_free_array (gpointer *ptr, int size)
10883 for (i = 0; i < size; i++)
10889 mono_marshal_string_to_utf16 (MonoString *s)
10891 return s ? mono_string_chars (s) : NULL;
10894 /* This is a JIT icall, it sets the pending exception and returns NULL on error. */
10896 mono_marshal_string_to_utf16_copy (MonoString *s)
10902 gunichar2 *res = (gunichar2 *)mono_marshal_alloc ((mono_string_length (s) * 2) + 2, &error);
10903 if (!mono_error_ok (&error)) {
10904 mono_error_set_pending_exception (&error);
10907 memcpy (res, mono_string_chars (s), mono_string_length (s) * 2);
10908 res [mono_string_length (s)] = 0;
10914 * mono_marshal_set_last_error:
10916 * This function is invoked to set the last error value from a P/Invoke call
10917 * which has \c SetLastError set.
10920 mono_marshal_set_last_error (void)
10923 mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (GetLastError ()));
10925 mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (errno));
10930 mono_marshal_set_last_error_windows (int error)
10933 mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (error));
10938 ves_icall_System_Runtime_InteropServices_Marshal_copy_to_unmanaged (MonoArray *src, gint32 start_index,
10939 gpointer dest, gint32 length)
10944 MONO_CHECK_ARG_NULL (src,);
10945 MONO_CHECK_ARG_NULL (dest,);
10947 if (src->obj.vtable->klass->rank != 1) {
10948 mono_set_pending_exception (mono_get_exception_argument ("array", "array is multi-dimensional"));
10951 if (start_index < 0) {
10952 mono_set_pending_exception (mono_get_exception_argument ("startIndex", "Must be >= 0"));
10956 mono_set_pending_exception (mono_get_exception_argument ("length", "Must be >= 0"));
10959 if (start_index + length > mono_array_length (src)) {
10960 mono_set_pending_exception (mono_get_exception_argument ("length", "start_index + length > array length"));
10964 element_size = mono_array_element_size (src->obj.vtable->klass);
10966 /* no references should be involved */
10967 source_addr = mono_array_addr_with_size_fast (src, element_size, start_index);
10969 memcpy (dest, source_addr, length * element_size);
10973 ves_icall_System_Runtime_InteropServices_Marshal_copy_from_unmanaged (gpointer src, gint32 start_index,
10974 MonoArray *dest, gint32 length)
10979 MONO_CHECK_ARG_NULL (src,);
10980 MONO_CHECK_ARG_NULL (dest,);
10982 if (dest->obj.vtable->klass->rank != 1) {
10983 mono_set_pending_exception (mono_get_exception_argument ("array", "array is multi-dimensional"));
10986 if (start_index < 0) {
10987 mono_set_pending_exception (mono_get_exception_argument ("startIndex", "Must be >= 0"));
10991 mono_set_pending_exception (mono_get_exception_argument ("length", "Must be >= 0"));
10994 if (start_index + length > mono_array_length (dest)) {
10995 mono_set_pending_exception (mono_get_exception_argument ("length", "start_index + length > array length"));
10998 element_size = mono_array_element_size (dest->obj.vtable->klass);
11000 /* no references should be involved */
11001 dest_addr = mono_array_addr_with_size_fast (dest, element_size, start_index);
11003 memcpy (dest_addr, src, length * element_size);
11007 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi (char *ptr, MonoError *error)
11009 error_init (error);
11011 return MONO_HANDLE_CAST (MonoString, NULL_HANDLE);
11013 return mono_string_new_handle (mono_domain_get (), ptr, error);
11017 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi_len (char *ptr, gint32 len)
11020 MonoString *result = NULL;
11021 error_init (&error);
11023 mono_error_set_argument_null (&error, "ptr", "");
11025 result = mono_string_new_len_checked (mono_domain_get (), ptr, len, &error);
11026 mono_error_set_pending_exception (&error);
11031 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni (guint16 *ptr)
11034 MonoString *res = NULL;
11035 MonoDomain *domain = mono_domain_get ();
11045 res = mono_string_new_utf16_checked (domain, ptr, len, &error);
11046 if (!mono_error_ok (&error)) {
11047 mono_error_set_pending_exception (&error);
11054 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni_len (guint16 *ptr, gint32 len)
11057 MonoString *res = NULL;
11058 MonoDomain *domain = mono_domain_get ();
11060 error_init (&error);
11064 mono_error_set_argument_null (&error, "ptr", "");
11066 res = mono_string_new_utf16_checked (domain, ptr, len, &error);
11069 if (!mono_error_ok (&error))
11070 mono_error_set_pending_exception (&error);
11075 ves_icall_System_Runtime_InteropServices_Marshal_GetLastWin32Error (void)
11077 return (GPOINTER_TO_INT (mono_native_tls_get_value (last_error_tls_id)));
11081 ves_icall_System_Runtime_InteropServices_Marshal_SizeOf (MonoReflectionTypeHandle rtype, MonoError *error)
11087 error_init (error);
11089 if (MONO_HANDLE_IS_NULL (rtype)) {
11090 mono_error_set_argument_null (error, "type", "");
11094 type = MONO_HANDLE_GETVAL (rtype, type);
11095 klass = mono_class_from_mono_type (type);
11096 if (!mono_class_init (klass)) {
11097 mono_error_set_for_class_failure (error, klass);
11101 layout = (mono_class_get_flags (klass) & TYPE_ATTRIBUTE_LAYOUT_MASK);
11103 if (type->type == MONO_TYPE_PTR || type->type == MONO_TYPE_FNPTR) {
11104 return sizeof (gpointer);
11105 } else if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
11106 mono_error_set_argument (error, "t", "Type %s cannot be marshaled as an unmanaged structure.", klass->name);
11110 return mono_class_native_size (klass, NULL);
11114 ves_icall_System_Runtime_InteropServices_Marshal_StructureToPtr (MonoObject *obj, gpointer dst, MonoBoolean delete_old)
11117 MonoMethod *method;
11120 MONO_CHECK_ARG_NULL (obj,);
11121 MONO_CHECK_ARG_NULL (dst,);
11123 method = mono_marshal_get_struct_to_ptr (obj->vtable->klass);
11127 pa [2] = &delete_old;
11129 mono_runtime_invoke_checked (method, NULL, pa, &error);
11130 if (!mono_error_ok (&error))
11131 mono_error_set_pending_exception (&error);
11135 ptr_to_structure (gpointer src, MonoObject *dst, MonoError *error)
11137 MonoMethod *method;
11140 error_init (error);
11142 method = mono_marshal_get_ptr_to_struct (dst->vtable->klass);
11147 mono_runtime_invoke_checked (method, NULL, pa, error);
11151 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure (gpointer src, MonoObject *dst)
11156 MONO_CHECK_ARG_NULL (src,);
11157 MONO_CHECK_ARG_NULL (dst,);
11159 t = mono_type_get_underlying_type (mono_class_get_type (dst->vtable->klass));
11161 if (t->type == MONO_TYPE_VALUETYPE) {
11162 MonoException *exc;
11165 tmp = g_strdup_printf ("Destination is a boxed value type.");
11166 exc = mono_get_exception_argument ("dst", tmp);
11169 mono_set_pending_exception (exc);
11173 ptr_to_structure (src, dst, &error);
11174 if (!mono_error_ok (&error))
11175 mono_error_set_pending_exception (&error);
11179 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure_type (gpointer src, MonoReflectionType *type)
11183 MonoDomain *domain = mono_domain_get ();
11188 MONO_CHECK_ARG_NULL (type, NULL);
11190 klass = mono_class_from_mono_type (type->type);
11191 if (!mono_class_init (klass)) {
11192 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
11196 res = mono_object_new_checked (domain, klass, &error);
11197 if (!mono_error_ok (&error)) {
11198 mono_error_set_pending_exception (&error);
11202 ptr_to_structure (src, res, &error);
11203 if (!mono_error_ok (&error)) {
11204 mono_error_set_pending_exception (&error);
11212 ves_icall_System_Runtime_InteropServices_Marshal_OffsetOf (MonoReflectionTypeHandle ref_type, MonoStringHandle field_name, MonoError *error)
11214 error_init (error);
11215 if (MONO_HANDLE_IS_NULL (ref_type)) {
11216 mono_error_set_argument_null (error, "type", "");
11219 if (MONO_HANDLE_IS_NULL (field_name)) {
11220 mono_error_set_argument_null (error, "fieldName", "");
11224 char *fname = mono_string_handle_to_utf8 (field_name, error);
11225 return_val_if_nok (error, 0);
11227 MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
11228 MonoClass *klass = mono_class_from_mono_type (type);
11229 if (!mono_class_init (klass)) {
11230 mono_error_set_for_class_failure (error, klass);
11234 int match_index = -1;
11235 while (klass && match_index == -1) {
11236 MonoClassField* field;
11238 gpointer iter = NULL;
11239 while ((field = mono_class_get_fields (klass, &iter))) {
11240 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
11242 if (!strcmp (fname, mono_field_get_name (field))) {
11249 if (match_index == -1)
11250 klass = klass->parent;
11255 if(match_index == -1) {
11256 /* Get back original class instance */
11257 klass = mono_class_from_mono_type (type);
11259 mono_error_set_argument (error, "fieldName", "Field passed in is not a marshaled member of the type %s", klass->name);
11263 MonoMarshalType *info = mono_marshal_load_type_info (klass);
11264 return info->fields [match_index].offset;
11269 ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalAnsi (MonoString *string)
11272 char *ret = mono_string_to_utf8_checked (string, &error);
11273 mono_error_set_pending_exception (&error);
11278 ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalUni (MonoString *string)
11280 if (string == NULL)
11283 gunichar2 *res = (gunichar2 *)g_malloc ((mono_string_length (string) + 1) * 2);
11285 memcpy (res, mono_string_chars (string), mono_string_length (string) * 2);
11286 res [mono_string_length (string)] = 0;
11290 #endif /* !HOST_WIN32 */
11293 mono_struct_delete_old (MonoClass *klass, char *ptr)
11295 MonoMarshalType *info;
11298 info = mono_marshal_load_type_info (klass);
11300 for (i = 0; i < info->num_fields; i++) {
11301 MonoMarshalConv conv;
11302 MonoType *ftype = info->fields [i].field->type;
11305 if (ftype->attrs & FIELD_ATTRIBUTE_STATIC)
11308 mono_type_to_unmanaged (ftype, info->fields [i].mspec, TRUE,
11309 klass->unicode, &conv);
11311 cpos = ptr + info->fields [i].offset;
11314 case MONO_MARSHAL_CONV_NONE:
11315 if (MONO_TYPE_ISSTRUCT (ftype)) {
11316 mono_struct_delete_old (ftype->data.klass, cpos);
11320 case MONO_MARSHAL_CONV_STR_LPWSTR:
11321 /* We assume this field points inside a MonoString */
11323 case MONO_MARSHAL_CONV_STR_LPTSTR:
11324 #ifdef TARGET_WIN32
11325 /* We assume this field points inside a MonoString
11329 case MONO_MARSHAL_CONV_STR_LPSTR:
11330 case MONO_MARSHAL_CONV_STR_BSTR:
11331 case MONO_MARSHAL_CONV_STR_ANSIBSTR:
11332 case MONO_MARSHAL_CONV_STR_TBSTR:
11333 case MONO_MARSHAL_CONV_STR_UTF8STR:
11334 mono_marshal_free (*(gpointer *)cpos);
11344 ves_icall_System_Runtime_InteropServices_Marshal_DestroyStructure (gpointer src, MonoReflectionType *type)
11348 MONO_CHECK_ARG_NULL (src,);
11349 MONO_CHECK_ARG_NULL (type,);
11351 klass = mono_class_from_mono_type (type->type);
11352 if (!mono_class_init (klass)) {
11353 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
11357 mono_struct_delete_old (klass, (char *)src);
11361 static inline void *
11362 mono_marshal_alloc_hglobal (size_t size)
11364 return g_try_malloc (size);
11369 ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (gpointer size)
11372 size_t s = (size_t)size;
11375 /* This returns a valid pointer for size 0 on MS.NET */
11378 res = mono_marshal_alloc_hglobal (s);
11381 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11389 static inline gpointer
11390 mono_marshal_realloc_hglobal (gpointer ptr, size_t size)
11392 return g_try_realloc (ptr, size);
11397 ves_icall_System_Runtime_InteropServices_Marshal_ReAllocHGlobal (gpointer ptr, gpointer size)
11400 size_t s = (size_t)size;
11403 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11407 res = mono_marshal_realloc_hglobal (ptr, s);
11410 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11419 mono_marshal_free_hglobal (gpointer ptr)
11427 ves_icall_System_Runtime_InteropServices_Marshal_FreeHGlobal (void *ptr)
11429 mono_marshal_free_hglobal (ptr);
11433 ves_icall_System_Runtime_InteropServices_Marshal_AllocCoTaskMem (int size)
11435 void *res = mono_marshal_alloc_co_task_mem (size);
11438 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11445 ves_icall_System_Runtime_InteropServices_Marshal_AllocCoTaskMemSize (gulong size)
11447 void *res = mono_marshal_alloc_co_task_mem (size);
11450 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11457 ves_icall_System_Runtime_InteropServices_Marshal_FreeCoTaskMem (void *ptr)
11459 mono_marshal_free_co_task_mem (ptr);
11464 static inline gpointer
11465 mono_marshal_realloc_co_task_mem (gpointer ptr, size_t size)
11467 return g_try_realloc (ptr, (gulong)size);
11472 ves_icall_System_Runtime_InteropServices_Marshal_ReAllocCoTaskMem (gpointer ptr, int size)
11474 void *res = mono_marshal_realloc_co_task_mem (ptr, size);
11477 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11484 ves_icall_System_Runtime_InteropServices_Marshal_UnsafeAddrOfPinnedArrayElement (MonoArray *arrayobj, int index)
11486 return mono_array_addr_with_size_fast (arrayobj, mono_array_element_size (arrayobj->obj.vtable->klass), index);
11490 ves_icall_System_Runtime_InteropServices_Marshal_GetDelegateForFunctionPointerInternal (void *ftn, MonoReflectionTypeHandle type, MonoError *error)
11492 error_init (error);
11493 MonoClass *klass = mono_type_get_class (MONO_HANDLE_GETVAL (type, type));
11494 if (!mono_class_init (klass)) {
11495 mono_error_set_for_class_failure (error, klass);
11499 return mono_ftnptr_to_delegate_handle (klass, ftn, error);
11503 ves_icall_System_Runtime_InteropServices_Marshal_GetFunctionPointerForDelegateInternal (MonoDelegateHandle delegate, MonoError *error)
11505 error_init (error);
11506 return mono_delegate_handle_to_ftnptr (delegate, error);
11510 * mono_marshal_is_loading_type_info:
11512 * Return whenever mono_marshal_load_type_info () is being executed for KLASS by this
11516 mono_marshal_is_loading_type_info (MonoClass *klass)
11518 GSList *loads_list = (GSList *)mono_native_tls_get_value (load_type_info_tls_id);
11520 return g_slist_find (loads_list, klass) != NULL;
11524 * mono_marshal_load_type_info:
11526 * Initialize \c klass::marshal_info using information from metadata. This function can
11527 * recursively call itself, and the caller is responsible to avoid that by calling
11528 * \c mono_marshal_is_loading_type_info beforehand.
11530 * LOCKING: Acquires the loader lock.
11533 mono_marshal_load_type_info (MonoClass* klass)
11536 guint32 native_size = 0, min_align = 1, packing;
11537 MonoMarshalType *info;
11538 MonoClassField* field;
11541 GSList *loads_list;
11543 g_assert (klass != NULL);
11545 info = mono_class_get_marshal_info (klass);
11549 if (!klass->inited)
11550 mono_class_init (klass);
11552 info = mono_class_get_marshal_info (klass);
11557 * This function can recursively call itself, so we keep the list of classes which are
11558 * under initialization in a TLS list.
11560 g_assert (!mono_marshal_is_loading_type_info (klass));
11561 loads_list = (GSList *)mono_native_tls_get_value (load_type_info_tls_id);
11562 loads_list = g_slist_prepend (loads_list, klass);
11563 mono_native_tls_set_value (load_type_info_tls_id, loads_list);
11566 while ((field = mono_class_get_fields (klass, &iter))) {
11567 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
11569 if (mono_field_is_deleted (field))
11574 layout = mono_class_get_flags (klass) & TYPE_ATTRIBUTE_LAYOUT_MASK;
11576 /* The mempool is protected by the loader lock */
11577 info = (MonoMarshalType *)mono_image_alloc0 (klass->image, MONO_SIZEOF_MARSHAL_TYPE + sizeof (MonoMarshalField) * count);
11578 info->num_fields = count;
11580 /* Try to find a size for this type in metadata */
11581 mono_metadata_packing_from_typedef (klass->image, klass->type_token, NULL, &native_size);
11583 if (klass->parent) {
11584 int parent_size = mono_class_native_size (klass->parent, NULL);
11586 /* Add parent size to real size */
11587 native_size += parent_size;
11588 info->native_size = parent_size;
11591 packing = klass->packing_size ? klass->packing_size : 8;
11594 while ((field = mono_class_get_fields (klass, &iter))) {
11598 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
11601 if (mono_field_is_deleted (field))
11603 if (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL)
11604 mono_metadata_field_info_with_mempool (klass->image, mono_metadata_token_index (mono_class_get_field_token (field)) - 1,
11605 NULL, NULL, &info->fields [j].mspec);
11607 info->fields [j].field = field;
11609 if ((mono_class_num_fields (klass) == 1) && (klass->instance_size == sizeof (MonoObject)) &&
11610 (strcmp (mono_field_get_name (field), "$PRIVATE$") == 0)) {
11611 /* This field is a hack inserted by MCS to empty structures */
11616 case TYPE_ATTRIBUTE_AUTO_LAYOUT:
11617 case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
11618 size = mono_marshal_type_size (field->type, info->fields [j].mspec,
11619 &align, TRUE, klass->unicode);
11620 align = klass->packing_size ? MIN (klass->packing_size, align): align;
11621 min_align = MAX (align, min_align);
11622 info->fields [j].offset = info->native_size;
11623 info->fields [j].offset += align - 1;
11624 info->fields [j].offset &= ~(align - 1);
11625 info->native_size = info->fields [j].offset + size;
11627 case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
11628 size = mono_marshal_type_size (field->type, info->fields [j].mspec,
11629 &align, TRUE, klass->unicode);
11630 min_align = MAX (align, min_align);
11631 info->fields [j].offset = field->offset - sizeof (MonoObject);
11632 info->native_size = MAX (info->native_size, info->fields [j].offset + size);
11638 if (klass->byval_arg.type == MONO_TYPE_PTR)
11639 info->native_size = sizeof (gpointer);
11641 if (layout != TYPE_ATTRIBUTE_AUTO_LAYOUT) {
11642 info->native_size = MAX (native_size, info->native_size);
11644 * If the provided Size is equal or larger than the calculated size, and there
11645 * was no Pack attribute, we set min_align to 1 to avoid native_size being increased
11647 if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
11648 if (native_size && native_size == info->native_size && klass->packing_size == 0)
11651 min_align = MIN (min_align, packing);
11655 if (info->native_size & (min_align - 1)) {
11656 info->native_size += min_align - 1;
11657 info->native_size &= ~(min_align - 1);
11660 info->min_align = min_align;
11662 /* Update the class's blittable info, if the layouts don't match */
11663 if (info->native_size != mono_class_value_size (klass, NULL))
11664 klass->blittable = FALSE;
11666 /* If this is an array type, ensure that we have element info */
11667 if (klass->rank && !mono_marshal_is_loading_type_info (klass->element_class)) {
11668 mono_marshal_load_type_info (klass->element_class);
11671 loads_list = (GSList *)mono_native_tls_get_value (load_type_info_tls_id);
11672 loads_list = g_slist_remove (loads_list, klass);
11673 mono_native_tls_set_value (load_type_info_tls_id, loads_list);
11675 mono_marshal_lock ();
11676 MonoMarshalType *info2 = mono_class_get_marshal_info (klass);
11678 /*We do double-checking locking on marshal_info */
11679 mono_memory_barrier ();
11680 mono_class_set_marshal_info (klass, info);
11681 ++class_marshal_info_count;
11684 mono_marshal_unlock ();
11690 * mono_class_native_size:
11691 * \param klass a class
11692 * \returns the native size of an object instance (when marshaled
11693 * to unmanaged code)
11696 mono_class_native_size (MonoClass *klass, guint32 *align)
11698 MonoMarshalType *info = mono_class_get_marshal_info (klass);
11700 if (mono_marshal_is_loading_type_info (klass)) {
11705 mono_marshal_load_type_info (klass);
11707 info = mono_class_get_marshal_info (klass);
11711 *align = info->min_align;
11713 return info->native_size;
11717 * mono_type_native_stack_size:
11718 * @t: the type to return the size it uses on the stack
11720 * Returns: the number of bytes required to hold an instance of this
11721 * type on the native stack
11724 mono_type_native_stack_size (MonoType *t, guint32 *align)
11728 g_assert (t != NULL);
11734 *align = sizeof (gpointer);
11735 return sizeof (gpointer);
11739 case MONO_TYPE_BOOLEAN:
11740 case MONO_TYPE_CHAR:
11751 case MONO_TYPE_STRING:
11752 case MONO_TYPE_OBJECT:
11753 case MONO_TYPE_CLASS:
11754 case MONO_TYPE_SZARRAY:
11755 case MONO_TYPE_PTR:
11756 case MONO_TYPE_FNPTR:
11757 case MONO_TYPE_ARRAY:
11758 *align = sizeof (gpointer);
11759 return sizeof (gpointer);
11764 *align = MONO_ABI_ALIGNOF (double);
11768 *align = MONO_ABI_ALIGNOF (gint64);
11770 case MONO_TYPE_GENERICINST:
11771 if (!mono_type_generic_inst_is_valuetype (t)) {
11772 *align = sizeof (gpointer);
11773 return sizeof (gpointer);
11776 case MONO_TYPE_TYPEDBYREF:
11777 case MONO_TYPE_VALUETYPE: {
11779 MonoClass *klass = mono_class_from_mono_type (t);
11781 if (klass->enumtype)
11782 return mono_type_native_stack_size (mono_class_enum_basetype (klass), align);
11784 size = mono_class_native_size (klass, align);
11785 *align = *align + 3;
11795 g_error ("type 0x%02x unknown", t->type);
11801 * mono_marshal_type_size:
11804 mono_marshal_type_size (MonoType *type, MonoMarshalSpec *mspec, guint32 *align,
11805 gboolean as_field, gboolean unicode)
11807 MonoMarshalNative native_type = mono_type_to_unmanaged (type, mspec, as_field, unicode, NULL);
11810 switch (native_type) {
11811 case MONO_NATIVE_BOOLEAN:
11814 case MONO_NATIVE_I1:
11815 case MONO_NATIVE_U1:
11818 case MONO_NATIVE_I2:
11819 case MONO_NATIVE_U2:
11820 case MONO_NATIVE_VARIANTBOOL:
11823 case MONO_NATIVE_I4:
11824 case MONO_NATIVE_U4:
11825 case MONO_NATIVE_ERROR:
11828 case MONO_NATIVE_I8:
11829 case MONO_NATIVE_U8:
11830 *align = MONO_ABI_ALIGNOF (gint64);
11832 case MONO_NATIVE_R4:
11835 case MONO_NATIVE_R8:
11836 *align = MONO_ABI_ALIGNOF (double);
11838 case MONO_NATIVE_INT:
11839 case MONO_NATIVE_UINT:
11840 case MONO_NATIVE_LPSTR:
11841 case MONO_NATIVE_LPWSTR:
11842 case MONO_NATIVE_LPTSTR:
11843 case MONO_NATIVE_BSTR:
11844 case MONO_NATIVE_ANSIBSTR:
11845 case MONO_NATIVE_TBSTR:
11846 case MONO_NATIVE_UTF8STR:
11847 case MONO_NATIVE_LPARRAY:
11848 case MONO_NATIVE_SAFEARRAY:
11849 case MONO_NATIVE_IUNKNOWN:
11850 case MONO_NATIVE_IDISPATCH:
11851 case MONO_NATIVE_INTERFACE:
11852 case MONO_NATIVE_ASANY:
11853 case MONO_NATIVE_FUNC:
11854 case MONO_NATIVE_LPSTRUCT:
11855 *align = MONO_ABI_ALIGNOF (gpointer);
11856 return sizeof (gpointer);
11857 case MONO_NATIVE_STRUCT:
11858 klass = mono_class_from_mono_type (type);
11859 if (klass == mono_defaults.object_class &&
11860 (mspec && mspec->native == MONO_NATIVE_STRUCT)) {
11864 return mono_class_native_size (klass, align);
11865 case MONO_NATIVE_BYVALTSTR: {
11866 int esize = unicode ? 2: 1;
11869 return mspec->data.array_data.num_elem * esize;
11871 case MONO_NATIVE_BYVALARRAY: {
11872 // FIXME: Have to consider ArraySubType
11874 klass = mono_class_from_mono_type (type);
11875 if (klass->element_class == mono_defaults.char_class) {
11876 esize = unicode ? 2 : 1;
11879 esize = mono_class_native_size (klass->element_class, align);
11882 return mspec->data.array_data.num_elem * esize;
11884 case MONO_NATIVE_CUSTOM:
11885 *align = sizeof (gpointer);
11886 return sizeof (gpointer);
11888 case MONO_NATIVE_CURRENCY:
11889 case MONO_NATIVE_VBBYREFSTR:
11891 g_error ("native type %02x not implemented", native_type);
11894 g_assert_not_reached ();
11899 * mono_marshal_asany:
11900 * This is a JIT icall, it sets the pending exception and returns NULL on error.
11903 mono_marshal_asany (MonoObject *o, MonoMarshalNative string_encoding, int param_attrs)
11912 t = &o->vtable->klass->byval_arg;
11916 case MONO_TYPE_PTR:
11919 case MONO_TYPE_BOOLEAN:
11922 case MONO_TYPE_CHAR:
11927 return mono_object_unbox (o);
11929 case MONO_TYPE_STRING:
11930 switch (string_encoding) {
11931 case MONO_NATIVE_LPWSTR:
11932 return mono_marshal_string_to_utf16_copy ((MonoString*)o);
11933 case MONO_NATIVE_LPSTR:
11934 case MONO_NATIVE_UTF8STR:
11935 // Same code path, because in Mono, we treated strings as Utf8
11936 return mono_string_to_utf8str ((MonoString*)o);
11938 g_warning ("marshaling conversion %d not implemented", string_encoding);
11939 g_assert_not_reached ();
11942 case MONO_TYPE_CLASS:
11943 case MONO_TYPE_VALUETYPE: {
11944 MonoMethod *method;
11947 MonoBoolean delete_old = FALSE;
11949 klass = t->data.klass;
11951 if (mono_class_is_auto_layout (klass))
11954 if (klass->valuetype && (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype))
11955 return mono_object_unbox (o);
11957 res = mono_marshal_alloc (mono_class_native_size (klass, NULL), &error);
11958 if (!mono_error_ok (&error)) {
11959 mono_error_set_pending_exception (&error);
11963 if (!((param_attrs & PARAM_ATTRIBUTE_OUT) && !(param_attrs & PARAM_ATTRIBUTE_IN))) {
11964 method = mono_marshal_get_struct_to_ptr (o->vtable->klass);
11968 pa [2] = &delete_old;
11970 mono_runtime_invoke_checked (method, NULL, pa, &error);
11971 if (!mono_error_ok (&error)) {
11972 mono_error_set_pending_exception (&error);
11982 mono_set_pending_exception (mono_get_exception_argument ("", "No PInvoke conversion exists for value passed to Object-typed parameter."));
11987 * mono_marshal_free_asany:
11988 * This is a JIT icall, it sets the pending exception
11991 mono_marshal_free_asany (MonoObject *o, gpointer ptr, MonoMarshalNative string_encoding, int param_attrs)
12000 t = &o->vtable->klass->byval_arg;
12002 case MONO_TYPE_STRING:
12003 switch (string_encoding) {
12004 case MONO_NATIVE_LPWSTR:
12005 case MONO_NATIVE_LPSTR:
12006 case MONO_NATIVE_UTF8STR:
12007 mono_marshal_free (ptr);
12010 g_warning ("marshaling conversion %d not implemented", string_encoding);
12011 g_assert_not_reached ();
12014 case MONO_TYPE_CLASS:
12015 case MONO_TYPE_VALUETYPE: {
12016 klass = t->data.klass;
12018 if (klass->valuetype && (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype))
12021 if (param_attrs & PARAM_ATTRIBUTE_OUT) {
12022 MonoMethod *method = mono_marshal_get_ptr_to_struct (o->vtable->klass);
12028 mono_runtime_invoke_checked (method, NULL, pa, &error);
12029 if (!mono_error_ok (&error)) {
12030 mono_error_set_pending_exception (&error);
12035 if (!((param_attrs & PARAM_ATTRIBUTE_OUT) && !(param_attrs & PARAM_ATTRIBUTE_IN))) {
12036 mono_struct_delete_old (klass, (char *)ptr);
12039 mono_marshal_free (ptr);
12048 * mono_marshal_get_generic_array_helper:
12050 * Return a wrapper which is used to implement the implicit interfaces on arrays.
12051 * The wrapper routes calls to METHOD, which is one of the InternalArray_ methods in Array.
12054 mono_marshal_get_generic_array_helper (MonoClass *klass, gchar *name, MonoMethod *method)
12056 MonoMethodSignature *sig, *csig;
12057 MonoMethodBuilder *mb;
12062 mb = mono_mb_new_no_dup_name (klass, name, MONO_WRAPPER_MANAGED_TO_MANAGED);
12063 mb->method->slot = -1;
12065 mb->method->flags = METHOD_ATTRIBUTE_PRIVATE | METHOD_ATTRIBUTE_VIRTUAL |
12066 METHOD_ATTRIBUTE_NEW_SLOT | METHOD_ATTRIBUTE_HIDE_BY_SIG | METHOD_ATTRIBUTE_FINAL;
12068 sig = mono_method_signature (method);
12069 csig = mono_metadata_signature_dup_full (method->klass->image, sig);
12070 csig->generic_param_count = 0;
12072 #ifdef HAVE_ONLINE_VES
12073 mono_mb_emit_ldarg (mb, 0);
12074 for (i = 0; i < csig->param_count; i++)
12075 mono_mb_emit_ldarg (mb, i + 1);
12076 mono_mb_emit_managed_call (mb, method, NULL);
12077 mono_mb_emit_byte (mb, CEE_RET);
12079 /* We can corlib internal methods */
12080 mb->skip_visibility = TRUE;
12082 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER);
12083 info->d.generic_array_helper.method = method;
12084 res = mono_mb_create (mb, csig, csig->param_count + 16, info);
12092 * The mono_win32_compat_* functions are implementations of inline
12093 * Windows kernel32 APIs, which are DllImport-able under MS.NET,
12094 * although not exported by kernel32.
12096 * We map the appropiate kernel32 entries to these functions using
12097 * dllmaps declared in the global etc/mono/config.
12101 mono_win32_compat_CopyMemory (gpointer dest, gconstpointer source, gsize length)
12103 if (!dest || !source)
12106 memcpy (dest, source, length);
12110 mono_win32_compat_FillMemory (gpointer dest, gsize length, guchar fill)
12112 memset (dest, fill, length);
12116 mono_win32_compat_MoveMemory (gpointer dest, gconstpointer source, gsize length)
12118 if (!dest || !source)
12121 memmove (dest, source, length);
12125 mono_win32_compat_ZeroMemory (gpointer dest, gsize length)
12127 memset (dest, 0, length);
12131 mono_marshal_find_nonzero_bit_offset (guint8 *buf, int len, int *byte_offset, guint8 *bitmask)
12136 for (i = 0; i < len; ++i)
12140 g_assert (i < len);
12143 while (byte && !(byte & 1))
12145 g_assert (byte == 1);
12148 *bitmask = buf [i];
12152 mono_marshal_get_thunk_invoke_wrapper (MonoMethod *method)
12154 MonoMethodBuilder *mb;
12155 MonoMethodSignature *sig, *csig;
12156 MonoExceptionClause *clause;
12161 int i, param_count, sig_size, pos_leave;
12165 // FIXME: we need to store the exception into a MonoHandle
12166 g_assert (!mono_threads_is_coop_enabled ());
12168 klass = method->klass;
12169 image = method->klass->image;
12171 cache = get_cache (&mono_method_get_wrapper_cache (method)->thunk_invoke_cache, mono_aligned_addr_hash, NULL);
12173 if ((res = mono_marshal_find_in_cache (cache, method)))
12176 sig = mono_method_signature (method);
12177 mb = mono_mb_new (klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
12179 /* add "this" and exception param */
12180 param_count = sig->param_count + sig->hasthis + 1;
12182 /* dup & extend signature */
12183 csig = mono_metadata_signature_alloc (image, param_count);
12184 sig_size = MONO_SIZEOF_METHOD_SIGNATURE + sig->param_count * sizeof (MonoType *);
12185 memcpy (csig, sig, sig_size);
12186 csig->param_count = param_count;
12189 csig->call_convention = MONO_CALL_DEFAULT;
12191 if (sig->hasthis) {
12193 csig->params [0] = &klass->byval_arg;
12194 /* move params up by one */
12195 for (i = 0; i < sig->param_count; i++)
12196 csig->params [i + 1] = sig->params [i];
12199 /* setup exception param as byref+[out] */
12200 csig->params [param_count - 1] = mono_metadata_type_dup (image,
12201 &mono_defaults.exception_class->byval_arg);
12202 csig->params [param_count - 1]->byref = 1;
12203 csig->params [param_count - 1]->attrs = PARAM_ATTRIBUTE_OUT;
12205 /* convert struct return to object */
12206 if (MONO_TYPE_ISSTRUCT (sig->ret))
12207 csig->ret = &mono_defaults.object_class->byval_arg;
12209 #ifdef HAVE_ONLINE_VES
12210 /* local 0 (temp for exception object) */
12211 mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
12213 /* local 1 (temp for result) */
12214 if (!MONO_TYPE_IS_VOID (sig->ret))
12215 mono_mb_add_local (mb, sig->ret);
12217 /* clear exception arg */
12218 mono_mb_emit_ldarg (mb, param_count - 1);
12219 mono_mb_emit_byte (mb, CEE_LDNULL);
12220 mono_mb_emit_byte (mb, CEE_STIND_REF);
12223 clause = (MonoExceptionClause *)mono_image_alloc0 (image, sizeof (MonoExceptionClause));
12224 clause->try_offset = mono_mb_get_label (mb);
12226 /* push method's args */
12227 for (i = 0; i < param_count - 1; i++) {
12231 mono_mb_emit_ldarg (mb, i);
12233 /* get the byval type of the param */
12234 klass = mono_class_from_mono_type (csig->params [i]);
12235 type = &klass->byval_arg;
12237 /* unbox struct args */
12238 if (MONO_TYPE_ISSTRUCT (type)) {
12239 mono_mb_emit_op (mb, CEE_UNBOX, klass);
12241 /* byref args & and the "this" arg must remain a ptr.
12242 Otherwise make a copy of the value type */
12243 if (!(csig->params [i]->byref || (i == 0 && sig->hasthis)))
12244 mono_mb_emit_op (mb, CEE_LDOBJ, klass);
12246 csig->params [i] = &mono_defaults.object_class->byval_arg;
12251 if (method->flags & METHOD_ATTRIBUTE_VIRTUAL)
12252 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
12254 mono_mb_emit_op (mb, CEE_CALL, method);
12256 /* save result at local 1 */
12257 if (!MONO_TYPE_IS_VOID (sig->ret))
12258 mono_mb_emit_stloc (mb, 1);
12260 pos_leave = mono_mb_emit_branch (mb, CEE_LEAVE);
12263 clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
12264 clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
12265 clause->data.catch_class = mono_defaults.object_class;
12267 clause->handler_offset = mono_mb_get_label (mb);
12269 /* store exception at local 0 */
12270 mono_mb_emit_stloc (mb, 0);
12271 mono_mb_emit_ldarg (mb, param_count - 1);
12272 mono_mb_emit_ldloc (mb, 0);
12273 mono_mb_emit_byte (mb, CEE_STIND_REF);
12274 mono_mb_emit_branch (mb, CEE_LEAVE);
12276 clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
12278 mono_mb_set_clauses (mb, 1, clause);
12280 mono_mb_patch_branch (mb, pos_leave);
12283 if (!MONO_TYPE_IS_VOID (sig->ret)) {
12284 mono_mb_emit_ldloc (mb, 1);
12286 /* box the return value */
12287 if (MONO_TYPE_ISSTRUCT (sig->ret))
12288 mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (sig->ret));
12291 mono_mb_emit_byte (mb, CEE_RET);
12294 res = mono_mb_create_and_cache (cache, method, mb, csig, param_count + 16);
12301 * mono_marshal_free_dynamic_wrappers:
12303 * Free wrappers of the dynamic method METHOD.
12306 mono_marshal_free_dynamic_wrappers (MonoMethod *method)
12308 MonoImage *image = method->klass->image;
12310 g_assert (method_is_dynamic (method));
12312 /* This could be called during shutdown */
12313 if (marshal_mutex_initialized)
12314 mono_marshal_lock ();
12316 * FIXME: We currently leak the wrappers. Freeing them would be tricky as
12317 * they could be shared with other methods ?
12319 if (image->wrapper_caches.runtime_invoke_direct_cache)
12320 g_hash_table_remove (image->wrapper_caches.runtime_invoke_direct_cache, method);
12321 if (image->wrapper_caches.delegate_abstract_invoke_cache)
12322 g_hash_table_foreach_remove (image->wrapper_caches.delegate_abstract_invoke_cache, signature_pointer_pair_matches_pointer, method);
12323 // FIXME: Need to clear the caches in other images as well
12324 if (image->delegate_bound_static_invoke_cache)
12325 g_hash_table_remove (image->delegate_bound_static_invoke_cache, mono_method_signature (method));
12327 if (marshal_mutex_initialized)
12328 mono_marshal_unlock ();
12332 mono_marshal_ftnptr_eh_callback (guint32 gchandle)
12334 g_assert (ftnptr_eh_callback);
12335 ftnptr_eh_callback (gchandle);
12339 ftnptr_eh_callback_default (guint32 gchandle)
12341 MonoException *exc;
12342 gpointer stackdata;
12344 mono_threads_enter_gc_unsafe_region_unbalanced (&stackdata);
12346 exc = (MonoException*) mono_gchandle_get_target (gchandle);
12348 mono_gchandle_free (gchandle);
12350 mono_raise_exception (exc);
12354 * mono_install_ftnptr_eh_callback:
12356 * Install a callback that should be called when there is a managed exception
12357 * in a native-to-managed wrapper. This is mainly used by iOS to convert a
12358 * managed exception to a native exception, to properly unwind the native
12359 * stack; this native exception will then be converted back to a managed
12360 * exception in their managed-to-native wrapper.
12363 mono_install_ftnptr_eh_callback (MonoFtnPtrEHCallback callback)
12365 ftnptr_eh_callback = callback;
12368 static MonoThreadInfo*
12369 mono_icall_start (HandleStackMark *stackmark, MonoError *error)
12371 MonoThreadInfo *info = mono_thread_info_current ();
12373 mono_stack_mark_init (info, stackmark);
12374 error_init (error);
12379 mono_icall_end (MonoThreadInfo *info, HandleStackMark *stackmark, MonoError *error)
12381 mono_stack_mark_pop (info, stackmark);
12382 if (G_UNLIKELY (!is_ok (error)))
12383 mono_error_set_pending_exception (error);
12386 static MonoObjectHandle
12387 mono_icall_handle_new (gpointer rawobj)
12389 #ifdef MONO_HANDLE_TRACK_OWNER
12390 return mono_handle_new (rawobj, "<marshal args>");
12392 return mono_handle_new (rawobj);
12396 static MonoObjectHandle
12397 mono_icall_handle_new_interior (gpointer rawobj)
12399 #ifdef MONO_HANDLE_TRACK_OWNER
12400 return mono_handle_new_interior (rawobj, "<marshal args>");
12402 return mono_handle_new_interior (rawobj);