2 * marshal.c: Routines for marshaling complex types in P/Invoke methods.
5 * Paolo Molaro (lupus@ximian.com)
7 * Copyright 2002-2003 Ximian, Inc (http://www.ximian.com)
8 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
20 #include "metadata/marshal.h"
21 #include "metadata/method-builder.h"
22 #include "metadata/tabledefs.h"
23 #include "metadata/exception.h"
24 #include "metadata/appdomain.h"
25 #include "mono/metadata/debug-helpers.h"
26 #include "mono/metadata/threadpool.h"
27 #include "mono/metadata/threads.h"
28 #include "mono/metadata/monitor.h"
29 #include "mono/metadata/metadata-internals.h"
30 #include "mono/metadata/domain-internals.h"
31 #include "mono/metadata/gc-internal.h"
32 #include "mono/metadata/threads-types.h"
33 #include "mono/metadata/string-icalls.h"
34 #include "mono/metadata/attrdefs.h"
35 #include "mono/metadata/gc-internal.h"
36 #include "mono/metadata/cominterop.h"
37 #include "mono/utils/mono-counters.h"
41 /* #define DEBUG_RUNTIME_CODE */
43 #define OPDEF(a,b,c,d,e,f,g,h,i,j) \
47 MONO_MARSHAL_NONE, /* No marshalling needed */
48 MONO_MARSHAL_COPY, /* Can be copied by value to the new domain */
49 MONO_MARSHAL_COPY_OUT, /* out parameter that needs to be copied back to the original instance */
50 MONO_MARSHAL_SERIALIZE /* Value needs to be serialized into the new domain */
51 } MonoXDomainMarshalType;
54 #include "mono/cil/opcode.def"
59 struct _MonoRemotingMethods {
61 MonoMethod *invoke_with_check;
62 MonoMethod *xdomain_invoke;
63 MonoMethod *xdomain_dispatch;
66 typedef struct _MonoRemotingMethods MonoRemotingMethods;
69 * This mutex protects the various marshalling related caches in MonoImage
70 * and a few other data structures static to this file.
71 * Note that when this lock is held it is not possible to take other runtime
72 * locks like the loader lock.
74 #define mono_marshal_lock() EnterCriticalSection (&marshal_mutex)
75 #define mono_marshal_unlock() LeaveCriticalSection (&marshal_mutex)
76 static CRITICAL_SECTION marshal_mutex;
78 static guint32 last_error_tls_id;
80 static guint32 load_type_info_tls_id;
83 delegate_hash_table_add (MonoDelegate *d);
86 emit_struct_conv (MonoMethodBuilder *mb, MonoClass *klass, gboolean to_object);
89 mono_struct_delete_old (MonoClass *klass, char *ptr);
92 mono_marshal_string_to_utf16 (MonoString *s);
95 mono_marshal_string_to_utf16_copy (MonoString *s);
98 mono_string_to_lpstr (MonoString *string_obj);
100 static MonoStringBuilder *
101 mono_string_utf8_to_builder2 (char *text);
104 mono_byvalarray_to_array (MonoArray *arr, gpointer native_arr, MonoClass *eltype, guint32 elnum);
107 mono_array_to_byvalarray (gpointer native_arr, MonoArray *arr, MonoClass *eltype, guint32 elnum);
110 mono_remoting_wrapper (MonoMethod *method, gpointer *params);
112 static MonoAsyncResult *
113 mono_delegate_begin_invoke (MonoDelegate *delegate, gpointer *params);
116 mono_delegate_end_invoke (MonoDelegate *delegate, gpointer *params);
119 mono_marshal_xdomain_copy_value (MonoObject *val);
122 mono_marshal_xdomain_copy_out_value (MonoObject *src, MonoObject *dst);
125 mono_marshal_set_domain_by_id (gint32 id, MonoBoolean push);
128 mono_marshal_check_domain_image (gint32 domain_id, MonoImage *image);
131 mono_upgrade_remote_class_wrapper (MonoReflectionType *rtype, MonoTransparentProxy *tproxy);
133 static MonoReflectionType *
134 type_from_handle (MonoType *handle);
137 mono_marshal_set_last_error_windows (int error);
139 static void init_safe_handle (void);
141 /* MonoMethod pointers to SafeHandle::DangerousAddRef and ::DangerousRelease */
142 static MonoMethod *sh_dangerous_add_ref;
143 static MonoMethod *sh_dangerous_release;
149 sh_dangerous_add_ref = mono_class_get_method_from_name (
150 mono_defaults.safehandle_class, "DangerousAddRef", 1);
151 sh_dangerous_release = mono_class_get_method_from_name (
152 mono_defaults.safehandle_class, "DangerousRelease", 0);
156 register_icall (gpointer func, const char *name, const char *sigstr, gboolean save)
158 MonoMethodSignature *sig = mono_create_icall_signature (sigstr);
160 mono_register_jit_icall (func, name, sig, save);
163 static MonoMethodSignature*
164 signature_dup (MonoImage *image, MonoMethodSignature *sig)
166 MonoMethodSignature *res;
169 res = mono_metadata_signature_alloc (image, sig->param_count);
170 sigsize = sizeof (MonoMethodSignature) + ((sig->param_count - MONO_ZERO_LEN_ARRAY) * sizeof (MonoType *));
171 memcpy (res, sig, sigsize);
177 mono_signature_no_pinvoke (MonoMethod *method)
179 MonoMethodSignature *sig = mono_method_signature (method);
181 sig = signature_dup (method->klass->image, sig);
182 sig->pinvoke = FALSE;
189 mono_marshal_init (void)
191 static gboolean module_initialized = FALSE;
193 if (!module_initialized) {
194 module_initialized = TRUE;
195 InitializeCriticalSection (&marshal_mutex);
196 last_error_tls_id = TlsAlloc ();
197 load_type_info_tls_id = TlsAlloc ();
199 register_icall (ves_icall_System_Threading_Thread_ResetAbort, "ves_icall_System_Threading_Thread_ResetAbort", "void", TRUE);
200 register_icall (mono_marshal_string_to_utf16, "mono_marshal_string_to_utf16", "ptr obj", FALSE);
201 register_icall (mono_marshal_string_to_utf16_copy, "mono_marshal_string_to_utf16_copy", "ptr obj", FALSE);
202 register_icall (mono_string_to_utf16, "mono_string_to_utf16", "ptr obj", FALSE);
203 register_icall (mono_string_from_utf16, "mono_string_from_utf16", "obj ptr", FALSE);
204 register_icall (mono_string_new_wrapper, "mono_string_new_wrapper", "obj ptr", FALSE);
205 register_icall (mono_string_to_utf8, "mono_string_to_utf8", "ptr obj", FALSE);
206 register_icall (mono_string_to_lpstr, "mono_string_to_lpstr", "ptr obj", FALSE);
207 register_icall (mono_string_to_ansibstr, "mono_string_to_ansibstr", "ptr object", FALSE);
208 register_icall (mono_string_builder_to_utf8, "mono_string_builder_to_utf8", "ptr object", FALSE);
209 register_icall (mono_string_builder_to_utf16, "mono_string_builder_to_utf16", "ptr object", FALSE);
210 register_icall (mono_array_to_savearray, "mono_array_to_savearray", "ptr object", FALSE);
211 register_icall (mono_array_to_lparray, "mono_array_to_lparray", "ptr object", FALSE);
212 register_icall (mono_byvalarray_to_array, "mono_byvalarray_to_array", "void object ptr ptr int32", FALSE);
213 register_icall (mono_array_to_byvalarray, "mono_array_to_byvalarray", "void ptr object ptr int32", FALSE);
214 register_icall (mono_delegate_to_ftnptr, "mono_delegate_to_ftnptr", "ptr object", FALSE);
215 register_icall (mono_ftnptr_to_delegate, "mono_ftnptr_to_delegate", "object ptr ptr", FALSE);
216 register_icall (mono_marshal_asany, "mono_marshal_asany", "ptr object int32 int32", FALSE);
217 register_icall (mono_marshal_free_asany, "mono_marshal_free_asany", "void object ptr int32 int32", FALSE);
218 register_icall (mono_marshal_alloc, "mono_marshal_alloc", "ptr int32", FALSE);
219 register_icall (mono_marshal_free, "mono_marshal_free", "void ptr", FALSE);
220 register_icall (mono_marshal_set_last_error, "mono_marshal_set_last_error", "void", FALSE);
221 register_icall (mono_marshal_set_last_error_windows, "mono_marshal_set_last_error_windows", "void int32", FALSE);
222 register_icall (mono_string_utf8_to_builder, "mono_string_utf8_to_builder", "void ptr ptr", FALSE);
223 register_icall (mono_string_utf8_to_builder2, "mono_string_utf8_to_builder2", "object ptr", FALSE);
224 register_icall (mono_string_utf16_to_builder, "mono_string_utf16_to_builder", "void ptr ptr", FALSE);
225 register_icall (mono_marshal_free_array, "mono_marshal_free_array", "void ptr int32", FALSE);
226 register_icall (mono_string_to_byvalstr, "mono_string_to_byvalstr", "void ptr ptr int32", FALSE);
227 register_icall (mono_string_to_byvalwstr, "mono_string_to_byvalwstr", "void ptr ptr int32", FALSE);
228 register_icall (g_free, "g_free", "void ptr", FALSE);
229 register_icall (mono_object_isinst, "mono_object_isinst", "object object ptr", FALSE);
230 register_icall (mono_struct_delete_old, "mono_struct_delete_old", "void ptr ptr", FALSE);
231 register_icall (mono_remoting_wrapper, "mono_remoting_wrapper", "object ptr ptr", FALSE);
232 register_icall (mono_delegate_begin_invoke, "mono_delegate_begin_invoke", "object object ptr", FALSE);
233 register_icall (mono_delegate_end_invoke, "mono_delegate_end_invoke", "object object ptr", FALSE);
234 register_icall (mono_marshal_xdomain_copy_value, "mono_marshal_xdomain_copy_value", "object object", FALSE);
235 register_icall (mono_marshal_xdomain_copy_out_value, "mono_marshal_xdomain_copy_out_value", "void object object", FALSE);
236 register_icall (mono_marshal_set_domain_by_id, "mono_marshal_set_domain_by_id", "int32 int32 int32", FALSE);
237 register_icall (mono_marshal_check_domain_image, "mono_marshal_check_domain_image", "int32 int32 ptr", FALSE);
238 register_icall (mono_compile_method, "mono_compile_method", "ptr ptr", FALSE);
239 register_icall (mono_context_get, "mono_context_get", "object", FALSE);
240 register_icall (mono_context_set, "mono_context_set", "void object", FALSE);
241 register_icall (mono_upgrade_remote_class_wrapper, "mono_upgrade_remote_class_wrapper", "void object object", FALSE);
242 register_icall (type_from_handle, "type_from_handle", "object ptr", FALSE);
243 register_icall (mono_gc_wbarrier_generic_store, "wb_generic", "void ptr object", FALSE);
245 mono_cominterop_init ();
250 mono_marshal_cleanup (void)
252 mono_cominterop_cleanup ();
254 TlsFree (load_type_info_tls_id);
255 TlsFree (last_error_tls_id);
256 DeleteCriticalSection (&marshal_mutex);
259 MonoClass *byte_array_class;
260 static MonoMethod *method_rs_serialize, *method_rs_deserialize, *method_exc_fixexc, *method_rs_appdomain_target;
261 static MonoMethod *method_set_context, *method_get_context;
262 static MonoMethod *method_set_call_context, *method_needs_context_sink, *method_rs_serialize_exc;
265 mono_remoting_marshal_init (void)
269 static gboolean module_initialized = FALSE;
271 if (!module_initialized) {
272 klass = mono_class_from_name (mono_defaults.corlib, "System.Runtime.Remoting", "RemotingServices");
273 method_rs_serialize = mono_class_get_method_from_name (klass, "SerializeCallData", -1);
274 method_rs_deserialize = mono_class_get_method_from_name (klass, "DeserializeCallData", -1);
275 method_rs_serialize_exc = mono_class_get_method_from_name (klass, "SerializeExceptionData", -1);
277 klass = mono_defaults.real_proxy_class;
278 method_rs_appdomain_target = mono_class_get_method_from_name (klass, "GetAppDomainTarget", -1);
280 klass = mono_defaults.exception_class;
281 method_exc_fixexc = mono_class_get_method_from_name (klass, "FixRemotingException", -1);
283 klass = mono_defaults.thread_class;
284 method_get_context = mono_class_get_method_from_name (klass, "get_CurrentContext", -1);
286 klass = mono_defaults.appdomain_class;
287 method_set_context = mono_class_get_method_from_name (klass, "InternalSetContext", -1);
288 byte_array_class = mono_array_class_get (mono_defaults.byte_class, 1);
290 klass = mono_class_from_name (mono_defaults.corlib, "System.Runtime.Remoting.Messaging", "CallContext");
291 method_set_call_context = mono_class_get_method_from_name (klass, "SetCurrentCallContext", -1);
293 klass = mono_class_from_name (mono_defaults.corlib, "System.Runtime.Remoting.Contexts", "Context");
294 method_needs_context_sink = mono_class_get_method_from_name (klass, "get_NeedsContextSink", -1);
296 module_initialized = TRUE;
301 mono_delegate_to_ftnptr (MonoDelegate *delegate)
303 MonoMethod *method, *wrapper;
309 if (delegate->delegate_trampoline)
310 return delegate->delegate_trampoline;
312 klass = ((MonoObject *)delegate)->vtable->klass;
313 g_assert (klass->delegate);
315 method = delegate->method;
317 wrapper = mono_marshal_get_managed_wrapper (method, klass, delegate->target);
319 delegate->delegate_trampoline = mono_compile_method (wrapper);
321 // Add the delegate to the delegate hash table
322 delegate_hash_table_add (delegate);
324 /* when the object is collected, collect the dynamic method, too */
325 mono_object_register_finalizer ((MonoObject*)delegate);
327 return delegate->delegate_trampoline;
331 * this hash table maps from a delegate trampoline object to a weak reference
332 * of the delegate. As an optimizations with a non-moving GC we store the
333 * object pointer itself, otherwise we use a GC handle.
335 static GHashTable *delegate_hash_table;
338 delegate_hash_table_new (void) {
339 return g_hash_table_new (NULL, NULL);
343 delegate_hash_table_remove (MonoDelegate *d)
345 #ifdef HAVE_MOVING_COLLECTOR
348 mono_marshal_lock ();
349 if (delegate_hash_table == NULL)
350 delegate_hash_table = delegate_hash_table_new ();
351 #ifdef HAVE_MOVING_COLLECTOR
352 gchandle = GPOINTER_TO_UINT (g_hash_table_lookup (delegate_hash_table, d->delegate_trampoline));
354 g_hash_table_remove (delegate_hash_table, d->delegate_trampoline);
355 mono_marshal_unlock ();
356 #ifdef HAVE_MOVING_COLLECTOR
357 mono_gchandle_free (gchandle);
362 delegate_hash_table_add (MonoDelegate *d)
364 #ifdef HAVE_MOVING_COLLECTOR
365 guint32 gchandle = mono_gchandle_new_weakref ((MonoObject*)d, FALSE);
367 mono_marshal_lock ();
368 if (delegate_hash_table == NULL)
369 delegate_hash_table = delegate_hash_table_new ();
370 #ifdef HAVE_MOVING_COLLECTOR
371 g_hash_table_insert (delegate_hash_table, d->delegate_trampoline, GUINT_TO_POINTER (gchandle));
373 g_hash_table_insert (delegate_hash_table, d->delegate_trampoline, d);
375 mono_marshal_unlock ();
379 mono_ftnptr_to_delegate (MonoClass *klass, gpointer ftn)
381 #ifdef HAVE_MOVING_COLLECTOR
389 mono_marshal_lock ();
390 if (delegate_hash_table == NULL)
391 delegate_hash_table = delegate_hash_table_new ();
393 #ifdef HAVE_MOVING_COLLECTOR
394 gchandle = GPOINTER_TO_UINT (g_hash_table_lookup (delegate_hash_table, ftn));
395 mono_marshal_unlock ();
397 d = (MonoDelegate*)mono_gchandle_get_target (gchandle);
401 d = g_hash_table_lookup (delegate_hash_table, ftn);
402 mono_marshal_unlock ();
405 /* This is a native function, so construct a delegate for it */
406 static MonoClass *UnmanagedFunctionPointerAttribute;
407 MonoMethodSignature *sig;
409 MonoMarshalSpec **mspecs;
410 MonoCustomAttrInfo *cinfo;
411 MonoReflectionUnmanagedFunctionPointerAttribute *attr;
412 MonoMethod *invoke = mono_get_delegate_invoke (klass);
413 MonoMethodPInvoke piinfo;
416 memset (&piinfo, 0, sizeof (piinfo));
417 if (!UnmanagedFunctionPointerAttribute)
418 UnmanagedFunctionPointerAttribute = mono_class_from_name (mono_defaults.corlib, "System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute");
420 /* The attribute is only available in Net 2.0 */
421 if (UnmanagedFunctionPointerAttribute) {
423 * The pinvoke attributes are stored in a real custom attribute so we have to
426 cinfo = mono_custom_attrs_from_class (klass);
428 attr = (MonoReflectionUnmanagedFunctionPointerAttribute*)mono_custom_attrs_get_attr (cinfo, UnmanagedFunctionPointerAttribute);
430 piinfo.piflags = (attr->call_conv << 8) | (attr->charset ? (attr->charset - 1) * 2 : 1) | attr->set_last_error;
433 mono_custom_attrs_free (cinfo);
437 mspecs = g_new0 (MonoMarshalSpec*, mono_method_signature (invoke)->param_count + 1);
438 mono_method_get_marshal_info (invoke, mspecs);
439 /* Freed below so don't alloc from mempool */
440 sig = mono_metadata_signature_dup (mono_method_signature (invoke));
443 wrapper = mono_marshal_get_native_func_wrapper (klass->image, sig, &piinfo, mspecs, ftn);
445 for (i = mono_method_signature (invoke)->param_count; i >= 0; i--)
447 mono_metadata_free_marshal_spec (mspecs [i]);
451 d = (MonoDelegate*)mono_object_new (mono_domain_get (), klass);
452 mono_delegate_ctor_with_method ((MonoObject*)d, NULL, mono_compile_method (wrapper), wrapper);
455 if (d->object.vtable->domain != mono_domain_get ())
456 mono_raise_exception (mono_get_exception_not_supported ("Delegates cannot be marshalled from native code into a domain other than their home domain"));
462 mono_delegate_free_ftnptr (MonoDelegate *delegate)
467 delegate_hash_table_remove (delegate);
469 ptr = (gpointer)InterlockedExchangePointer (&delegate->delegate_trampoline, NULL);
471 if (!delegate->target) {
472 /* The wrapper method is shared between delegates -> no need to free it */
477 ji = mono_jit_info_table_find (mono_domain_get (), mono_get_addr_from_ftnptr (ptr));
480 mono_runtime_free_method (mono_object_domain (delegate), ji->method);
485 mono_array_to_savearray (MonoArray *array)
490 g_assert_not_reached ();
495 mono_array_to_lparray (MonoArray *array)
500 /* fixme: maybe we need to make a copy */
501 return array->vector;
505 mono_byvalarray_to_array (MonoArray *arr, gpointer native_arr, MonoClass *elclass, guint32 elnum)
507 g_assert (arr->obj.vtable->klass->element_class == mono_defaults.char_class);
509 if (elclass == mono_defaults.byte_class) {
510 GError *error = NULL;
514 ut = g_utf8_to_utf16 (native_arr, elnum, NULL, &items_written, &error);
517 memcpy (mono_array_addr (arr, guint16, 0), ut, items_written * sizeof (guint16));
521 g_error_free (error);
524 g_assert_not_reached ();
528 mono_array_to_byvalarray (gpointer native_arr, MonoArray *arr, MonoClass *elclass, guint32 elnum)
530 g_assert (arr->obj.vtable->klass->element_class == mono_defaults.char_class);
532 if (elclass == mono_defaults.byte_class) {
534 GError *error = NULL;
536 as = g_utf16_to_utf8 (mono_array_addr (arr, gunichar2, 0), mono_array_length (arr), NULL, NULL, &error);
538 MonoException *exc = mono_get_exception_argument ("string", error->message);
539 g_error_free (error);
540 mono_raise_exception (exc);
543 memcpy (native_arr, as, MIN (strlen (as), elnum));
546 g_assert_not_reached ();
551 mono_string_utf8_to_builder (MonoStringBuilder *sb, char *text)
553 GError *error = NULL;
563 ut = g_utf8_to_utf16 (text, l, NULL, &items_written, &error);
565 if (items_written > mono_stringbuilder_capacity (sb))
566 items_written = mono_stringbuilder_capacity (sb);
569 if (! sb->str || sb->str == sb->cached_str) {
570 MONO_OBJECT_SETREF (sb, str, mono_string_new_size (mono_domain_get (), items_written));
571 sb->cached_str = NULL;
574 memcpy (mono_string_chars (sb->str), ut, items_written * 2);
575 sb->length = items_written;
577 g_error_free (error);
583 mono_string_utf8_to_builder2 (char *text)
586 MonoStringBuilder *sb;
587 static MonoClass *string_builder_class;
588 static MonoMethod *sb_ctor;
595 if (!string_builder_class) {
596 MonoMethodDesc *desc;
598 string_builder_class = mono_class_from_name (mono_defaults.corlib, "System.Text", "StringBuilder");
599 g_assert (string_builder_class);
600 desc = mono_method_desc_new (":.ctor(int)", FALSE);
601 sb_ctor = mono_method_desc_search_in_class (desc, string_builder_class);
603 mono_method_desc_free (desc);
608 sb = (MonoStringBuilder*)mono_object_new (mono_domain_get (), string_builder_class);
611 mono_runtime_invoke (sb_ctor, sb, args, &exc);
614 mono_string_utf8_to_builder (sb, text);
620 * FIXME: This routine does not seem to do what it seems to do
621 * the @text is never copied into the string builder
624 mono_string_utf16_to_builder (MonoStringBuilder *sb, gunichar2 *text)
631 g_assert (mono_string_chars (sb->str) == text);
633 for (len = 0; text [len] != 0; ++len)
640 * mono_string_builder_to_utf8:
641 * @sb: the string builder
643 * Converts to utf8 the contents of the MonoStringBuilder.
645 * Returns: a utf8 string with the contents of the StringBuilder.
647 * The return value must be released with g_free.
650 mono_string_builder_to_utf8 (MonoStringBuilder *sb)
652 GError *error = NULL;
653 gchar *tmp, *res = NULL;
658 if ((sb->str == sb->cached_str) && (sb->str->length == 0)) {
660 * The sb could have been allocated with the default capacity and be empty.
661 * we need to alloc a buffer of the default capacity in this case.
663 MONO_OBJECT_SETREF (sb, str, mono_string_new_size (mono_domain_get (), 16));
664 sb->cached_str = NULL;
667 tmp = g_utf16_to_utf8 (mono_string_chars (sb->str), sb->length, NULL, NULL, &error);
669 g_error_free (error);
670 mono_raise_exception (mono_get_exception_execution_engine ("Failed to convert StringBuilder from utf16 to utf8"));
672 res = mono_marshal_alloc (mono_stringbuilder_capacity (sb) + 1);
673 memcpy (res, tmp, sb->length + 1);
681 * mono_string_builder_to_utf16:
682 * @sb: the string builder
684 * Converts to utf16 the contents of the MonoStringBuilder.
686 * Returns: a utf16 string with the contents of the StringBuilder.
688 * The return value must not be freed.
691 mono_string_builder_to_utf16 (MonoStringBuilder *sb)
699 * The stringbuilder might not have ownership of this string. If this is
700 * the case, we must duplicate the string, so that we don't munge immutable
703 if (sb->str == sb->cached_str) {
705 * The sb could have been allocated with the default capacity and be empty.
706 * we need to alloc a buffer of the default capacity in this case.
708 if (sb->str->length == 0)
709 MONO_OBJECT_SETREF (sb, str, mono_string_new_size (mono_domain_get (), 16));
711 MONO_OBJECT_SETREF (sb, str, mono_string_new_utf16 (mono_domain_get (), mono_string_chars (sb->str), mono_stringbuilder_capacity (sb)));
712 sb->cached_str = NULL;
715 return mono_string_chars (sb->str);
719 mono_string_to_lpstr (MonoString *s)
721 #ifdef PLATFORM_WIN32
724 GError *error = NULL;
730 as = CoTaskMemAlloc (1);
735 tmp = g_utf16_to_utf8 (mono_string_chars (s), s->length, NULL, &len, &error);
737 MonoException *exc = mono_get_exception_argument ("string", error->message);
738 g_error_free (error);
739 mono_raise_exception(exc);
742 as = CoTaskMemAlloc (len + 1);
743 memcpy (as, tmp, len + 1);
748 return mono_string_to_utf8 (s);
753 mono_string_to_ansibstr (MonoString *string_obj)
755 g_error ("UnmanagedMarshal.BStr is not implemented.");
760 * mono_string_to_byvalstr:
761 * @dst: Where to store the null-terminated utf8 decoded string.
762 * @src: the MonoString to copy.
763 * @size: the maximum number of bytes to copy.
765 * Copies the MonoString pointed to by @src as a utf8 string
766 * into @dst, it copies at most @size bytes into the destination.
769 mono_string_to_byvalstr (gpointer dst, MonoString *src, int size)
774 g_assert (dst != NULL);
777 memset (dst, 0, size);
781 s = mono_string_to_utf8 (src);
782 len = MIN (size, strlen (s));
785 memcpy (dst, s, len);
790 * mono_string_to_byvalwstr:
791 * @dst: Where to store the null-terminated utf16 decoded string.
792 * @src: the MonoString to copy.
793 * @size: the maximum number of bytes to copy.
795 * Copies the MonoString pointed to by @src as a utf16 string into
796 * @dst, it copies at most @size bytes into the destination (including
797 * a terminating 16-bit zero terminator).
800 mono_string_to_byvalwstr (gpointer dst, MonoString *src, int size)
804 g_assert (dst != NULL);
808 memset (dst, 0, size * 2);
812 len = MIN (size, (mono_string_length (src)));
813 memcpy (dst, mono_string_chars (src), size * 2);
814 if (size <= mono_string_length (src))
816 *((gunichar2 *) dst + len) = 0;
820 mono_mb_emit_proxy_check (MonoMethodBuilder *mb, int branch_code)
823 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoObject, vtable));
824 mono_mb_emit_byte (mb, CEE_LDIND_I);
825 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoVTable, klass));
826 mono_mb_emit_byte (mb, CEE_ADD);
827 mono_mb_emit_byte (mb, CEE_LDIND_I);
828 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
829 mono_mb_emit_byte (mb, CEE_MONO_CLASSCONST);
830 mono_mb_emit_i4 (mb, mono_mb_add_data (mb, mono_defaults.transparent_proxy_class));
831 pos = mono_mb_emit_branch (mb, branch_code);
836 mono_mb_emit_xdomain_check (MonoMethodBuilder *mb, int branch_code)
839 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoTransparentProxy, rp));
840 mono_mb_emit_byte (mb, CEE_LDIND_REF);
841 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoRealProxy, target_domain_id));
842 mono_mb_emit_byte (mb, CEE_LDIND_I4);
843 mono_mb_emit_icon (mb, -1);
844 pos = mono_mb_emit_branch (mb, branch_code);
849 mono_mb_emit_contextbound_check (MonoMethodBuilder *mb, int branch_code)
851 static int offset = -1;
855 mono_marshal_find_bitfield_offset (MonoClass, contextbound, &offset, &mask);
857 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoTransparentProxy, remote_class));
858 mono_mb_emit_byte (mb, CEE_LDIND_REF);
859 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoRemoteClass, proxy_class));
860 mono_mb_emit_byte (mb, CEE_LDIND_REF);
861 mono_mb_emit_ldflda (mb, offset);
862 mono_mb_emit_byte (mb, CEE_LDIND_U1);
863 mono_mb_emit_icon (mb, mask);
864 mono_mb_emit_byte (mb, CEE_AND);
865 mono_mb_emit_icon (mb, 0);
866 return mono_mb_emit_branch (mb, branch_code);
870 mono_mb_emit_exception_marshal_directive (MonoMethodBuilder *mb, const char *msg)
872 mono_mb_emit_exception_full (mb, "System.Runtime.InteropServices", "MarshalDirectiveException", msg);
876 mono_type_to_ldind (MonoType *type)
882 switch (type->type) {
886 case MONO_TYPE_BOOLEAN:
900 case MONO_TYPE_FNPTR:
902 case MONO_TYPE_CLASS:
903 case MONO_TYPE_STRING:
904 case MONO_TYPE_OBJECT:
905 case MONO_TYPE_SZARRAY:
906 case MONO_TYPE_ARRAY:
907 return CEE_LDIND_REF;
915 case MONO_TYPE_VALUETYPE:
916 if (type->data.klass->enumtype) {
917 type = mono_class_enum_basetype (type->data.klass);
921 case MONO_TYPE_TYPEDBYREF:
923 case MONO_TYPE_GENERICINST:
924 type = &type->data.generic_class->container_class->byval_arg;
927 g_error ("unknown type 0x%02x in type_to_ldind", type->type);
933 mono_type_to_stind (MonoType *type)
939 switch (type->type) {
942 case MONO_TYPE_BOOLEAN:
954 case MONO_TYPE_FNPTR:
956 case MONO_TYPE_CLASS:
957 case MONO_TYPE_STRING:
958 case MONO_TYPE_OBJECT:
959 case MONO_TYPE_SZARRAY:
960 case MONO_TYPE_ARRAY:
961 return CEE_STIND_REF;
969 case MONO_TYPE_VALUETYPE:
970 if (type->data.klass->enumtype) {
971 type = mono_class_enum_basetype (type->data.klass);
975 case MONO_TYPE_TYPEDBYREF:
977 case MONO_TYPE_GENERICINST:
978 type = &type->data.generic_class->container_class->byval_arg;
981 g_error ("unknown type 0x%02x in type_to_stind", type->type);
987 emit_ptr_to_object_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv conv, MonoMarshalSpec *mspec)
990 case MONO_MARSHAL_CONV_BOOL_I4:
991 mono_mb_emit_ldloc (mb, 1);
992 mono_mb_emit_ldloc (mb, 0);
993 mono_mb_emit_byte (mb, CEE_LDIND_I4);
994 mono_mb_emit_byte (mb, CEE_BRFALSE_S);
995 mono_mb_emit_byte (mb, 3);
996 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
997 mono_mb_emit_byte (mb, CEE_BR_S);
998 mono_mb_emit_byte (mb, 1);
999 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
1000 mono_mb_emit_byte (mb, CEE_STIND_I1);
1002 case MONO_MARSHAL_CONV_BOOL_VARIANTBOOL:
1003 mono_mb_emit_ldloc (mb, 1);
1004 mono_mb_emit_ldloc (mb, 0);
1005 mono_mb_emit_byte (mb, CEE_LDIND_I2);
1006 mono_mb_emit_byte (mb, CEE_BRFALSE_S);
1007 mono_mb_emit_byte (mb, 3);
1008 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
1009 mono_mb_emit_byte (mb, CEE_BR_S);
1010 mono_mb_emit_byte (mb, 1);
1011 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
1012 mono_mb_emit_byte (mb, CEE_STIND_I1);
1014 case MONO_MARSHAL_CONV_ARRAY_BYVALARRAY: {
1015 MonoClass *eklass = NULL;
1018 if (type->type == MONO_TYPE_SZARRAY) {
1019 eklass = type->data.klass;
1021 g_assert_not_reached ();
1024 esize = mono_class_native_size (eklass, NULL);
1026 /* create a new array */
1027 mono_mb_emit_ldloc (mb, 1);
1028 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1029 mono_mb_emit_op (mb, CEE_NEWARR, eklass);
1030 mono_mb_emit_byte (mb, CEE_STIND_I);
1032 if (eklass->blittable) {
1033 /* copy the elements */
1034 mono_mb_emit_ldloc (mb, 1);
1035 mono_mb_emit_byte (mb, CEE_LDIND_I);
1036 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoArray, vector));
1037 mono_mb_emit_byte (mb, CEE_ADD);
1038 mono_mb_emit_ldloc (mb, 0);
1039 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem * esize);
1040 mono_mb_emit_byte (mb, CEE_PREFIX1);
1041 mono_mb_emit_byte (mb, CEE_CPBLK);
1044 int array_var, src_var, dst_var, index_var;
1045 guint32 label2, label3;
1047 array_var = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
1048 src_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1049 dst_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1052 mono_mb_emit_ldloc (mb, 1);
1053 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1054 mono_mb_emit_stloc (mb, array_var);
1056 /* save the old src pointer */
1057 mono_mb_emit_ldloc (mb, 0);
1058 mono_mb_emit_stloc (mb, src_var);
1059 /* save the old dst pointer */
1060 mono_mb_emit_ldloc (mb, 1);
1061 mono_mb_emit_stloc (mb, dst_var);
1063 /* Emit marshalling loop */
1064 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1065 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
1066 mono_mb_emit_stloc (mb, index_var);
1069 label2 = mono_mb_get_label (mb);
1070 mono_mb_emit_ldloc (mb, index_var);
1071 mono_mb_emit_ldloc (mb, array_var);
1072 mono_mb_emit_byte (mb, CEE_LDLEN);
1073 label3 = mono_mb_emit_branch (mb, CEE_BGE);
1075 /* src is already set */
1078 mono_mb_emit_ldloc (mb, array_var);
1079 mono_mb_emit_ldloc (mb, index_var);
1080 mono_mb_emit_op (mb, CEE_LDELEMA, eklass);
1081 mono_mb_emit_stloc (mb, 1);
1083 /* Do the conversion */
1084 emit_struct_conv (mb, eklass, TRUE);
1087 mono_mb_emit_add_to_local (mb, index_var, 1);
1089 mono_mb_emit_branch_label (mb, CEE_BR, label2);
1091 mono_mb_patch_branch (mb, label3);
1093 /* restore the old src pointer */
1094 mono_mb_emit_ldloc (mb, src_var);
1095 mono_mb_emit_stloc (mb, 0);
1096 /* restore the old dst pointer */
1097 mono_mb_emit_ldloc (mb, dst_var);
1098 mono_mb_emit_stloc (mb, 1);
1102 case MONO_MARSHAL_CONV_ARRAY_BYVALCHARARRAY: {
1103 MonoClass *eclass = mono_defaults.char_class;
1105 /* create a new array */
1106 mono_mb_emit_ldloc (mb, 1);
1107 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1108 mono_mb_emit_op (mb, CEE_NEWARR, eclass);
1109 mono_mb_emit_byte (mb, CEE_STIND_REF);
1111 mono_mb_emit_ldloc (mb, 1);
1112 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1113 mono_mb_emit_ldloc (mb, 0);
1114 mono_mb_emit_ptr (mb, mono_defaults.byte_class);
1115 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1116 mono_mb_emit_icall (mb, mono_byvalarray_to_array);
1119 case MONO_MARSHAL_CONV_STR_BYVALSTR:
1120 mono_mb_emit_ldloc (mb, 1);
1121 mono_mb_emit_ldloc (mb, 0);
1122 mono_mb_emit_icall (mb, mono_string_new_wrapper);
1123 mono_mb_emit_byte (mb, CEE_STIND_REF);
1125 case MONO_MARSHAL_CONV_STR_BYVALWSTR:
1126 mono_mb_emit_ldloc (mb, 1);
1127 mono_mb_emit_ldloc (mb, 0);
1128 mono_mb_emit_icall (mb, mono_string_from_utf16);
1129 mono_mb_emit_byte (mb, CEE_STIND_REF);
1131 case MONO_MARSHAL_CONV_STR_LPTSTR:
1132 mono_mb_emit_ldloc (mb, 1);
1133 mono_mb_emit_ldloc (mb, 0);
1134 mono_mb_emit_byte (mb, CEE_LDIND_I);
1135 #ifdef PLATFORM_WIN32
1136 mono_mb_emit_icall (mb, mono_string_from_utf16);
1138 mono_mb_emit_icall (mb, mono_string_new_wrapper);
1140 mono_mb_emit_byte (mb, CEE_STIND_REF);
1142 case MONO_MARSHAL_CONV_STR_LPSTR:
1143 mono_mb_emit_ldloc (mb, 1);
1144 mono_mb_emit_ldloc (mb, 0);
1145 mono_mb_emit_byte (mb, CEE_LDIND_I);
1146 mono_mb_emit_icall (mb, mono_string_new_wrapper);
1147 mono_mb_emit_byte (mb, CEE_STIND_REF);
1149 case MONO_MARSHAL_CONV_STR_LPWSTR:
1150 mono_mb_emit_ldloc (mb, 1);
1151 mono_mb_emit_ldloc (mb, 0);
1152 mono_mb_emit_byte (mb, CEE_LDIND_I);
1153 mono_mb_emit_icall (mb, mono_string_from_utf16);
1154 mono_mb_emit_byte (mb, CEE_STIND_REF);
1156 case MONO_MARSHAL_CONV_OBJECT_STRUCT: {
1157 MonoClass *klass = mono_class_from_mono_type (type);
1158 int src_var, dst_var;
1160 src_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1161 dst_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1163 /* *dst = new object */
1164 mono_mb_emit_ldloc (mb, 1);
1165 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
1166 mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, klass);
1167 mono_mb_emit_byte (mb, CEE_STIND_REF);
1169 /* save the old src pointer */
1170 mono_mb_emit_ldloc (mb, 0);
1171 mono_mb_emit_stloc (mb, src_var);
1172 /* save the old dst pointer */
1173 mono_mb_emit_ldloc (mb, 1);
1174 mono_mb_emit_stloc (mb, dst_var);
1176 /* dst = pointer to newly created object data */
1177 mono_mb_emit_ldloc (mb, 1);
1178 mono_mb_emit_byte (mb, CEE_LDIND_I);
1179 mono_mb_emit_icon (mb, sizeof (MonoObject));
1180 mono_mb_emit_byte (mb, CEE_ADD);
1181 mono_mb_emit_stloc (mb, 1);
1183 emit_struct_conv (mb, klass, TRUE);
1185 /* restore the old src pointer */
1186 mono_mb_emit_ldloc (mb, src_var);
1187 mono_mb_emit_stloc (mb, 0);
1188 /* restore the old dst pointer */
1189 mono_mb_emit_ldloc (mb, dst_var);
1190 mono_mb_emit_stloc (mb, 1);
1193 case MONO_MARSHAL_CONV_DEL_FTN: {
1194 MonoClass *klass = mono_class_from_mono_type (type);
1196 mono_mb_emit_ldloc (mb, 1);
1197 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
1198 mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
1199 mono_mb_emit_ldloc (mb, 0);
1200 mono_mb_emit_byte (mb, CEE_LDIND_I);
1201 mono_mb_emit_icall (mb, mono_ftnptr_to_delegate);
1202 mono_mb_emit_byte (mb, CEE_STIND_REF);
1205 case MONO_MARSHAL_CONV_ARRAY_LPARRAY:
1206 g_error ("Structure field of type %s can't be marshalled as LPArray", mono_class_from_mono_type (type)->name);
1210 case MONO_MARSHAL_CONV_OBJECT_INTERFACE:
1211 case MONO_MARSHAL_CONV_OBJECT_IUNKNOWN:
1212 case MONO_MARSHAL_CONV_OBJECT_IDISPATCH:
1213 mono_cominterop_emit_ptr_to_object_conv (mb, type, conv, mspec);
1215 #endif /* DISABLE_COM */
1217 case MONO_MARSHAL_CONV_SAFEHANDLE: {
1219 * Passing SafeHandles as ref does not allow the unmanaged code
1220 * to change the SafeHandle value. If the value is changed,
1221 * we should issue a diagnostic exception (NotSupportedException)
1222 * that informs the user that changes to handles in unmanaged code
1225 * Since we currently have no access to the original
1226 * SafeHandle that was used during the marshalling,
1227 * for now we just ignore this, and ignore/discard any
1228 * changes that might have happened to the handle.
1233 case MONO_MARSHAL_CONV_HANDLEREF: {
1235 * Passing HandleRefs in a struct that is ref()ed does not
1236 * copy the values back to the HandleRef
1241 case MONO_MARSHAL_CONV_STR_BSTR:
1242 case MONO_MARSHAL_CONV_STR_ANSIBSTR:
1243 case MONO_MARSHAL_CONV_STR_TBSTR:
1244 case MONO_MARSHAL_CONV_ARRAY_SAVEARRAY:
1246 g_warning ("marshaling conversion %d not implemented", conv);
1247 g_assert_not_reached ();
1252 conv_to_icall (MonoMarshalConv conv)
1255 case MONO_MARSHAL_CONV_STR_LPWSTR:
1256 return mono_marshal_string_to_utf16;
1257 case MONO_MARSHAL_CONV_LPWSTR_STR:
1258 return mono_string_from_utf16;
1259 case MONO_MARSHAL_CONV_LPSTR_STR:
1260 return mono_string_new_wrapper;
1261 case MONO_MARSHAL_CONV_STR_LPTSTR:
1262 #ifdef PLATFORM_WIN32
1263 return mono_marshal_string_to_utf16;
1265 return mono_string_to_lpstr;
1267 case MONO_MARSHAL_CONV_STR_LPSTR:
1268 return mono_string_to_lpstr;
1269 case MONO_MARSHAL_CONV_STR_BSTR:
1270 return mono_string_to_bstr;
1271 case MONO_MARSHAL_CONV_BSTR_STR:
1272 return mono_string_from_bstr;
1273 case MONO_MARSHAL_CONV_STR_TBSTR:
1274 case MONO_MARSHAL_CONV_STR_ANSIBSTR:
1275 return mono_string_to_ansibstr;
1276 case MONO_MARSHAL_CONV_SB_LPSTR:
1277 return mono_string_builder_to_utf8;
1278 case MONO_MARSHAL_CONV_SB_LPTSTR:
1279 #ifdef PLATFORM_WIN32
1280 return mono_string_builder_to_utf16;
1282 return mono_string_builder_to_utf8;
1284 case MONO_MARSHAL_CONV_SB_LPWSTR:
1285 return mono_string_builder_to_utf16;
1286 case MONO_MARSHAL_CONV_ARRAY_SAVEARRAY:
1287 return mono_array_to_savearray;
1288 case MONO_MARSHAL_CONV_ARRAY_LPARRAY:
1289 return mono_array_to_lparray;
1290 case MONO_MARSHAL_CONV_DEL_FTN:
1291 return mono_delegate_to_ftnptr;
1292 case MONO_MARSHAL_CONV_FTN_DEL:
1293 return mono_ftnptr_to_delegate;
1294 case MONO_MARSHAL_CONV_LPSTR_SB:
1295 return mono_string_utf8_to_builder;
1296 case MONO_MARSHAL_CONV_LPTSTR_SB:
1297 #ifdef PLATFORM_WIN32
1298 return mono_string_utf16_to_builder;
1300 return mono_string_utf8_to_builder;
1302 case MONO_MARSHAL_CONV_LPWSTR_SB:
1303 return mono_string_utf16_to_builder;
1304 case MONO_MARSHAL_FREE_ARRAY:
1305 return mono_marshal_free_array;
1306 case MONO_MARSHAL_CONV_STR_BYVALSTR:
1307 return mono_string_to_byvalstr;
1308 case MONO_MARSHAL_CONV_STR_BYVALWSTR:
1309 return mono_string_to_byvalwstr;
1311 g_assert_not_reached ();
1318 emit_object_to_ptr_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv conv, MonoMarshalSpec *mspec)
1323 case MONO_MARSHAL_CONV_BOOL_I4:
1324 mono_mb_emit_ldloc (mb, 1);
1325 mono_mb_emit_ldloc (mb, 0);
1326 mono_mb_emit_byte (mb, CEE_LDIND_U1);
1327 mono_mb_emit_byte (mb, CEE_STIND_I4);
1329 case MONO_MARSHAL_CONV_BOOL_VARIANTBOOL:
1330 mono_mb_emit_ldloc (mb, 1);
1331 mono_mb_emit_ldloc (mb, 0);
1332 mono_mb_emit_byte (mb, CEE_LDIND_U1);
1333 mono_mb_emit_byte (mb, CEE_NEG);
1334 mono_mb_emit_byte (mb, CEE_STIND_I2);
1336 case MONO_MARSHAL_CONV_STR_LPWSTR:
1337 case MONO_MARSHAL_CONV_STR_LPSTR:
1338 case MONO_MARSHAL_CONV_STR_LPTSTR:
1339 case MONO_MARSHAL_CONV_STR_BSTR:
1340 case MONO_MARSHAL_CONV_STR_ANSIBSTR:
1341 case MONO_MARSHAL_CONV_STR_TBSTR: {
1344 /* free space if free == true */
1345 mono_mb_emit_ldloc (mb, 2);
1346 pos = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
1347 mono_mb_emit_ldloc (mb, 1);
1348 mono_mb_emit_byte (mb, CEE_LDIND_I);
1349 mono_mb_emit_icall (mb, g_free);
1350 mono_mb_patch_short_branch (mb, pos);
1352 mono_mb_emit_ldloc (mb, 1);
1353 mono_mb_emit_ldloc (mb, 0);
1354 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1355 mono_mb_emit_icall (mb, conv_to_icall (conv));
1356 mono_mb_emit_byte (mb, CEE_STIND_I);
1359 case MONO_MARSHAL_CONV_ARRAY_SAVEARRAY:
1360 case MONO_MARSHAL_CONV_ARRAY_LPARRAY:
1361 case MONO_MARSHAL_CONV_DEL_FTN:
1362 mono_mb_emit_ldloc (mb, 1);
1363 mono_mb_emit_ldloc (mb, 0);
1364 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1365 mono_mb_emit_icall (mb, conv_to_icall (conv));
1366 mono_mb_emit_byte (mb, CEE_STIND_I);
1368 case MONO_MARSHAL_CONV_STR_BYVALSTR:
1369 case MONO_MARSHAL_CONV_STR_BYVALWSTR: {
1372 mono_mb_emit_ldloc (mb, 1); /* dst */
1373 mono_mb_emit_ldloc (mb, 0);
1374 mono_mb_emit_byte (mb, CEE_LDIND_REF); /* src String */
1375 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1376 mono_mb_emit_icall (mb, conv_to_icall (conv));
1379 case MONO_MARSHAL_CONV_ARRAY_BYVALARRAY: {
1380 MonoClass *eklass = NULL;
1383 if (type->type == MONO_TYPE_SZARRAY) {
1384 eklass = type->data.klass;
1386 g_assert_not_reached ();
1389 if (eklass->valuetype)
1390 esize = mono_class_native_size (eklass, NULL);
1392 esize = sizeof (gpointer);
1394 mono_mb_emit_ldloc (mb, 0);
1395 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1396 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
1398 if (eklass->blittable) {
1399 mono_mb_emit_ldloc (mb, 1);
1400 mono_mb_emit_ldloc (mb, 0);
1401 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1402 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoArray, vector));
1403 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem * esize);
1404 mono_mb_emit_byte (mb, CEE_PREFIX1);
1405 mono_mb_emit_byte (mb, CEE_CPBLK);
1407 int array_var, src_var, dst_var, index_var;
1408 guint32 label2, label3;
1410 array_var = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
1411 src_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1412 dst_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1415 mono_mb_emit_ldloc (mb, 0);
1416 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1417 mono_mb_emit_stloc (mb, array_var);
1419 /* save the old src pointer */
1420 mono_mb_emit_ldloc (mb, 0);
1421 mono_mb_emit_stloc (mb, src_var);
1422 /* save the old dst pointer */
1423 mono_mb_emit_ldloc (mb, 1);
1424 mono_mb_emit_stloc (mb, dst_var);
1426 /* Emit marshalling loop */
1427 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1428 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
1429 mono_mb_emit_stloc (mb, index_var);
1432 label2 = mono_mb_get_label (mb);
1433 mono_mb_emit_ldloc (mb, index_var);
1434 mono_mb_emit_ldloc (mb, array_var);
1435 mono_mb_emit_byte (mb, CEE_LDLEN);
1436 label3 = mono_mb_emit_branch (mb, CEE_BGE);
1439 mono_mb_emit_ldloc (mb, array_var);
1440 mono_mb_emit_ldloc (mb, index_var);
1441 mono_mb_emit_op (mb, CEE_LDELEMA, eklass);
1442 mono_mb_emit_stloc (mb, 0);
1444 /* dst is already set */
1446 /* Do the conversion */
1447 emit_struct_conv (mb, eklass, FALSE);
1450 mono_mb_emit_add_to_local (mb, index_var, 1);
1452 mono_mb_emit_branch_label (mb, CEE_BR, label2);
1454 mono_mb_patch_branch (mb, label3);
1456 /* restore the old src pointer */
1457 mono_mb_emit_ldloc (mb, src_var);
1458 mono_mb_emit_stloc (mb, 0);
1459 /* restore the old dst pointer */
1460 mono_mb_emit_ldloc (mb, dst_var);
1461 mono_mb_emit_stloc (mb, 1);
1464 mono_mb_patch_branch (mb, pos);
1467 case MONO_MARSHAL_CONV_ARRAY_BYVALCHARARRAY: {
1468 mono_mb_emit_ldloc (mb, 0);
1469 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1470 pos = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
1472 mono_mb_emit_ldloc (mb, 1);
1473 mono_mb_emit_ldloc (mb, 0);
1474 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1475 mono_mb_emit_ptr (mb, mono_defaults.byte_class);
1476 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1477 mono_mb_emit_icall (mb, mono_array_to_byvalarray);
1478 mono_mb_patch_short_branch (mb, pos);
1481 case MONO_MARSHAL_CONV_OBJECT_STRUCT: {
1482 int src_var, dst_var;
1484 src_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1485 dst_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1487 mono_mb_emit_ldloc (mb, 0);
1488 mono_mb_emit_byte (mb, CEE_LDIND_I);
1489 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
1491 /* save the old src pointer */
1492 mono_mb_emit_ldloc (mb, 0);
1493 mono_mb_emit_stloc (mb, src_var);
1494 /* save the old dst pointer */
1495 mono_mb_emit_ldloc (mb, 1);
1496 mono_mb_emit_stloc (mb, dst_var);
1498 /* src = pointer to object data */
1499 mono_mb_emit_ldloc (mb, 0);
1500 mono_mb_emit_byte (mb, CEE_LDIND_I);
1501 mono_mb_emit_icon (mb, sizeof (MonoObject));
1502 mono_mb_emit_byte (mb, CEE_ADD);
1503 mono_mb_emit_stloc (mb, 0);
1505 emit_struct_conv (mb, mono_class_from_mono_type (type), FALSE);
1507 /* restore the old src pointer */
1508 mono_mb_emit_ldloc (mb, src_var);
1509 mono_mb_emit_stloc (mb, 0);
1510 /* restore the old dst pointer */
1511 mono_mb_emit_ldloc (mb, dst_var);
1512 mono_mb_emit_stloc (mb, 1);
1514 mono_mb_patch_branch (mb, pos);
1519 case MONO_MARSHAL_CONV_OBJECT_INTERFACE:
1520 case MONO_MARSHAL_CONV_OBJECT_IDISPATCH:
1521 case MONO_MARSHAL_CONV_OBJECT_IUNKNOWN:
1522 mono_cominterop_emit_object_to_ptr_conv (mb, type, conv, mspec);
1524 #endif /* DISABLE_COM */
1526 case MONO_MARSHAL_CONV_SAFEHANDLE: {
1527 int dar_release_slot, pos;
1529 dar_release_slot = mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
1532 * The following is ifdefed-out, because I have no way of doing the
1533 * DangerousRelease when destroying the structure
1536 /* set release = false */
1537 mono_mb_emit_icon (mb, 0);
1538 mono_mb_emit_stloc (mb, dar_release_slot);
1539 if (!sh_dangerous_add_ref)
1540 init_safe_handle ();
1542 /* safehandle.DangerousAddRef (ref release) */
1543 mono_mb_emit_ldloc (mb, 0); /* the source */
1544 mono_mb_emit_byte (mb, CEE_LDIND_I);
1545 mono_mb_emit_ldloc_addr (mb, dar_release_slot);
1546 mono_mb_emit_managed_call (mb, sh_dangerous_add_ref, NULL);
1548 mono_mb_emit_ldloc (mb, 0);
1549 mono_mb_emit_byte (mb, CEE_LDIND_I);
1550 pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
1551 mono_mb_emit_exception (mb, "ArgumentNullException", NULL);
1552 mono_mb_patch_branch (mb, pos);
1554 /* Pull the handle field from SafeHandle */
1555 mono_mb_emit_ldloc (mb, 1);
1556 mono_mb_emit_ldloc (mb, 0);
1557 mono_mb_emit_byte (mb, CEE_LDIND_I);
1558 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoSafeHandle, handle));
1559 mono_mb_emit_byte (mb, CEE_LDIND_I);
1560 mono_mb_emit_byte (mb, CEE_STIND_I);
1564 case MONO_MARSHAL_CONV_HANDLEREF: {
1565 mono_mb_emit_ldloc (mb, 1);
1566 mono_mb_emit_ldloc (mb, 0);
1567 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoHandleRef, handle));
1568 mono_mb_emit_byte (mb, CEE_ADD);
1569 mono_mb_emit_byte (mb, CEE_LDIND_I);
1570 mono_mb_emit_byte (mb, CEE_STIND_I);
1575 char *msg = g_strdup_printf ("marshalling conversion %d not implemented", conv);
1576 MonoException *exc = mono_get_exception_not_implemented (msg);
1579 mono_raise_exception (exc);
1585 emit_struct_conv (MonoMethodBuilder *mb, MonoClass *klass, gboolean to_object)
1587 MonoMarshalType *info;
1591 emit_struct_conv(mb, klass->parent, to_object);
1593 info = mono_marshal_load_type_info (klass);
1595 if (info->native_size == 0)
1598 if (klass->blittable) {
1599 int msize = mono_class_value_size (klass, NULL);
1600 g_assert (msize == info->native_size);
1601 mono_mb_emit_ldloc (mb, 1);
1602 mono_mb_emit_ldloc (mb, 0);
1603 mono_mb_emit_icon (mb, msize);
1604 mono_mb_emit_byte (mb, CEE_PREFIX1);
1605 mono_mb_emit_byte (mb, CEE_CPBLK);
1607 mono_mb_emit_add_to_local (mb, 0, msize);
1608 mono_mb_emit_add_to_local (mb, 1, msize);
1612 for (i = 0; i < info->num_fields; i++) {
1613 MonoMarshalNative ntype;
1614 MonoMarshalConv conv;
1615 MonoType *ftype = info->fields [i].field->type;
1618 gboolean last_field = i < (info->num_fields -1) ? 0 : 1;
1620 if (ftype->attrs & FIELD_ATTRIBUTE_STATIC)
1623 ntype = mono_type_to_unmanaged (ftype, info->fields [i].mspec, TRUE, klass->unicode, &conv);
1626 msize = klass->instance_size - info->fields [i].field->offset;
1627 usize = info->native_size - info->fields [i].offset;
1629 msize = info->fields [i + 1].field->offset - info->fields [i].field->offset;
1630 usize = info->fields [i + 1].offset - info->fields [i].offset;
1633 if (klass != mono_defaults.safehandle_class){
1635 * FIXME: Should really check for usize==0 and msize>0, but we apply
1636 * the layout to the managed structure as well.
1639 if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) && (usize == 0)) {
1640 if (MONO_TYPE_IS_REFERENCE (info->fields [i].field->type) ||
1641 ((!last_field && MONO_TYPE_IS_REFERENCE (info->fields [i + 1].field->type))))
1642 g_error ("Type %s which has an [ExplicitLayout] attribute cannot have a "
1643 "reference field at the same offset as another field.",
1644 mono_type_full_name (&klass->byval_arg));
1647 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
1648 g_error ("Type %s which is passed to unmanaged code must have a StructLayout attribute",
1649 mono_type_full_name (&klass->byval_arg));
1654 case MONO_MARSHAL_CONV_NONE: {
1657 if (ftype->byref || ftype->type == MONO_TYPE_I ||
1658 ftype->type == MONO_TYPE_U) {
1659 mono_mb_emit_ldloc (mb, 1);
1660 mono_mb_emit_ldloc (mb, 0);
1661 mono_mb_emit_byte (mb, CEE_LDIND_I);
1662 mono_mb_emit_byte (mb, CEE_STIND_I);
1673 case MONO_TYPE_BOOLEAN:
1676 case MONO_TYPE_CHAR:
1682 mono_mb_emit_ldloc (mb, 1);
1683 mono_mb_emit_ldloc (mb, 0);
1684 mono_mb_emit_byte (mb, mono_type_to_ldind (ftype));
1685 mono_mb_emit_byte (mb, mono_type_to_stind (ftype));
1687 case MONO_TYPE_VALUETYPE: {
1688 int src_var, dst_var;
1690 if (ftype->data.klass->enumtype) {
1691 ftype = mono_class_enum_basetype (ftype->data.klass);
1695 src_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1696 dst_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1698 /* save the old src pointer */
1699 mono_mb_emit_ldloc (mb, 0);
1700 mono_mb_emit_stloc (mb, src_var);
1701 /* save the old dst pointer */
1702 mono_mb_emit_ldloc (mb, 1);
1703 mono_mb_emit_stloc (mb, dst_var);
1705 emit_struct_conv (mb, ftype->data.klass, to_object);
1707 /* restore the old src pointer */
1708 mono_mb_emit_ldloc (mb, src_var);
1709 mono_mb_emit_stloc (mb, 0);
1710 /* restore the old dst pointer */
1711 mono_mb_emit_ldloc (mb, dst_var);
1712 mono_mb_emit_stloc (mb, 1);
1715 case MONO_TYPE_OBJECT: {
1716 mono_init_com_types ();
1718 static MonoMethod *variant_clear = NULL;
1719 static MonoMethod *get_object_for_native_variant = NULL;
1722 variant_clear = mono_class_get_method_from_name (mono_defaults.variant_class, "Clear", 0);
1723 if (!get_object_for_native_variant)
1724 get_object_for_native_variant = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetObjectForNativeVariant", 1);
1725 mono_mb_emit_ldloc (mb, 1);
1726 mono_mb_emit_ldloc (mb, 0);
1727 mono_mb_emit_managed_call (mb, get_object_for_native_variant, NULL);
1728 mono_mb_emit_byte (mb, CEE_STIND_REF);
1730 mono_mb_emit_ldloc (mb, 0);
1731 mono_mb_emit_managed_call (mb, variant_clear, NULL);
1734 static MonoMethod *get_native_variant_for_object = NULL;
1736 if (!get_native_variant_for_object)
1737 get_native_variant_for_object = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetNativeVariantForObject", 2);
1739 mono_mb_emit_ldloc (mb, 0);
1740 mono_mb_emit_byte(mb, CEE_LDIND_REF);
1741 mono_mb_emit_ldloc (mb, 1);
1742 mono_mb_emit_managed_call (mb, get_native_variant_for_object, NULL);
1748 g_warning ("marshaling type %02x not implemented", ftype->type);
1749 g_assert_not_reached ();
1754 int src_var, dst_var;
1756 src_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1757 dst_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1759 /* save the old src pointer */
1760 mono_mb_emit_ldloc (mb, 0);
1761 mono_mb_emit_stloc (mb, src_var);
1762 /* save the old dst pointer */
1763 mono_mb_emit_ldloc (mb, 1);
1764 mono_mb_emit_stloc (mb, dst_var);
1767 emit_ptr_to_object_conv (mb, ftype, conv, info->fields [i].mspec);
1769 emit_object_to_ptr_conv (mb, ftype, conv, info->fields [i].mspec);
1771 /* restore the old src pointer */
1772 mono_mb_emit_ldloc (mb, src_var);
1773 mono_mb_emit_stloc (mb, 0);
1774 /* restore the old dst pointer */
1775 mono_mb_emit_ldloc (mb, dst_var);
1776 mono_mb_emit_stloc (mb, 1);
1781 mono_mb_emit_add_to_local (mb, 0, usize);
1782 mono_mb_emit_add_to_local (mb, 1, msize);
1784 mono_mb_emit_add_to_local (mb, 0, msize);
1785 mono_mb_emit_add_to_local (mb, 1, usize);
1791 emit_struct_free (MonoMethodBuilder *mb, MonoClass *klass, int struct_var)
1793 /* Call DestroyStructure */
1794 /* FIXME: Only do this if needed */
1795 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
1796 mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
1797 mono_mb_emit_ldloc (mb, struct_var);
1798 mono_mb_emit_icall (mb, mono_struct_delete_old);
1802 emit_thread_interrupt_checkpoint_call (MonoMethodBuilder *mb, gpointer checkpoint_func)
1806 mono_mb_emit_ptr (mb, (gpointer) mono_thread_interruption_request_flag ());
1807 mono_mb_emit_byte (mb, CEE_LDIND_U4);
1808 pos_noabort = mono_mb_emit_branch (mb, CEE_BRFALSE);
1810 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
1811 mono_mb_emit_byte (mb, CEE_MONO_NOT_TAKEN);
1813 mono_mb_emit_icall (mb, checkpoint_func);
1815 mono_mb_patch_branch (mb, pos_noabort);
1819 emit_thread_interrupt_checkpoint (MonoMethodBuilder *mb)
1821 if (strstr (mb->name, "mono_thread_interruption_checkpoint"))
1824 emit_thread_interrupt_checkpoint_call (mb, mono_thread_interruption_checkpoint);
1828 emit_thread_force_interrupt_checkpoint (MonoMethodBuilder *mb)
1830 emit_thread_interrupt_checkpoint_call (mb, mono_thread_force_interruption_checkpoint);
1834 mono_marshal_emit_thread_interrupt_checkpoint (MonoMethodBuilder *mb)
1836 emit_thread_interrupt_checkpoint (mb);
1839 static MonoAsyncResult *
1840 mono_delegate_begin_invoke (MonoDelegate *delegate, gpointer *params)
1842 MonoMethodMessage *msg;
1843 MonoDelegate *async_callback;
1847 MonoMethod *method = NULL, *method2 = NULL;
1849 g_assert (delegate);
1851 if (delegate->target && mono_object_class (delegate->target) == mono_defaults.transparent_proxy_class) {
1853 MonoTransparentProxy* tp = (MonoTransparentProxy *)delegate->target;
1854 if (!tp->remote_class->proxy_class->contextbound || tp->rp->context != (MonoObject *) mono_context_get ()) {
1856 /* If the target is a proxy, make a direct call. Is proxy's work
1857 // to make the call asynchronous.
1859 MonoAsyncResult *ares;
1861 MonoArray *out_args;
1863 method = delegate->method;
1865 msg = mono_method_call_message_new (mono_marshal_method_from_wrapper (method), params, NULL, &async_callback, &state);
1866 handle = CreateEvent (NULL, TRUE, FALSE, NULL);
1867 g_assert(handle != NULL);
1868 ares = mono_async_result_new (mono_domain_get (), handle, state, handle, NULL);
1869 MONO_OBJECT_SETREF (ares, async_delegate, (MonoObject *)delegate);
1870 MONO_OBJECT_SETREF (ares, async_callback, (MonoObject *)async_callback);
1871 MONO_OBJECT_SETREF (msg, async_result, ares);
1872 msg->call_type = CallType_BeginInvoke;
1874 mono_remoting_invoke ((MonoObject *)tp->rp, msg, &exc, &out_args);
1879 klass = delegate->object.vtable->klass;
1881 method = mono_get_delegate_invoke (klass);
1882 method2 = mono_class_get_method_from_name (klass, "BeginInvoke", -1);
1885 g_assert (method != NULL);
1887 im = mono_get_delegate_invoke (method->klass);
1888 msg = mono_method_call_message_new (method, params, im, &async_callback, &state);
1890 return mono_thread_pool_add ((MonoObject *)delegate, msg, async_callback, state);
1894 mono_mb_emit_save_args (MonoMethodBuilder *mb, MonoMethodSignature *sig, gboolean save_this)
1896 int i, params_var, tmp_var;
1898 /* allocate local (pointer) *params[] */
1899 params_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1900 /* allocate local (pointer) tmp */
1901 tmp_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1903 /* alloate space on stack to store an array of pointers to the arguments */
1904 mono_mb_emit_icon (mb, sizeof (gpointer) * (sig->param_count + 1));
1905 mono_mb_emit_byte (mb, CEE_PREFIX1);
1906 mono_mb_emit_byte (mb, CEE_LOCALLOC);
1907 mono_mb_emit_stloc (mb, params_var);
1910 mono_mb_emit_ldloc (mb, params_var);
1911 mono_mb_emit_stloc (mb, tmp_var);
1913 if (save_this && sig->hasthis) {
1914 mono_mb_emit_ldloc (mb, tmp_var);
1915 mono_mb_emit_ldarg_addr (mb, 0);
1916 mono_mb_emit_byte (mb, CEE_STIND_I);
1917 /* tmp = tmp + sizeof (gpointer) */
1918 if (sig->param_count)
1919 mono_mb_emit_add_to_local (mb, tmp_var, sizeof (gpointer));
1923 for (i = 0; i < sig->param_count; i++) {
1924 mono_mb_emit_ldloc (mb, tmp_var);
1925 mono_mb_emit_ldarg_addr (mb, i + sig->hasthis);
1926 mono_mb_emit_byte (mb, CEE_STIND_I);
1927 /* tmp = tmp + sizeof (gpointer) */
1928 if (i < (sig->param_count - 1))
1929 mono_mb_emit_add_to_local (mb, tmp_var, sizeof (gpointer));
1936 mono_signature_to_name (MonoMethodSignature *sig, const char *prefix)
1940 GString *res = g_string_new ("");
1943 g_string_append (res, prefix);
1944 g_string_append_c (res, '_');
1947 mono_type_get_desc (res, sig->ret, FALSE);
1950 g_string_append (res, "__this__");
1952 for (i = 0; i < sig->param_count; ++i) {
1953 g_string_append_c (res, '_');
1954 mono_type_get_desc (res, sig->params [i], FALSE);
1957 g_string_free (res, FALSE);
1962 * mono_marshal_get_string_encoding:
1964 * Return the string encoding which should be used for a given parameter.
1966 static MonoMarshalNative
1967 mono_marshal_get_string_encoding (MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec)
1969 /* First try the parameter marshal info */
1971 if (spec->native == MONO_NATIVE_LPARRAY) {
1972 if ((spec->data.array_data.elem_type != 0) && (spec->data.array_data.elem_type != MONO_NATIVE_MAX))
1973 return spec->data.array_data.elem_type;
1976 return spec->native;
1980 return MONO_NATIVE_LPSTR;
1982 /* Then try the method level marshal info */
1983 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
1984 case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
1985 return MONO_NATIVE_LPSTR;
1986 case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
1987 return MONO_NATIVE_LPWSTR;
1988 case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
1989 #ifdef PLATFORM_WIN32
1990 return MONO_NATIVE_LPWSTR;
1992 return MONO_NATIVE_LPSTR;
1995 return MONO_NATIVE_LPSTR;
1999 static MonoMarshalConv
2000 mono_marshal_get_string_to_ptr_conv (MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec)
2002 MonoMarshalNative encoding = mono_marshal_get_string_encoding (piinfo, spec);
2005 case MONO_NATIVE_LPWSTR:
2006 return MONO_MARSHAL_CONV_STR_LPWSTR;
2007 case MONO_NATIVE_LPSTR:
2008 return MONO_MARSHAL_CONV_STR_LPSTR;
2009 case MONO_NATIVE_LPTSTR:
2010 return MONO_MARSHAL_CONV_STR_LPTSTR;
2011 case MONO_NATIVE_BSTR:
2012 return MONO_MARSHAL_CONV_STR_BSTR;
2018 static MonoMarshalConv
2019 mono_marshal_get_stringbuilder_to_ptr_conv (MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec)
2021 MonoMarshalNative encoding = mono_marshal_get_string_encoding (piinfo, spec);
2024 case MONO_NATIVE_LPWSTR:
2025 return MONO_MARSHAL_CONV_SB_LPWSTR;
2027 case MONO_NATIVE_LPSTR:
2028 return MONO_MARSHAL_CONV_SB_LPSTR;
2030 case MONO_NATIVE_LPTSTR:
2031 return MONO_MARSHAL_CONV_SB_LPTSTR;
2038 static MonoMarshalConv
2039 mono_marshal_get_ptr_to_string_conv (MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec, gboolean *need_free)
2041 MonoMarshalNative encoding = mono_marshal_get_string_encoding (piinfo, spec);
2046 case MONO_NATIVE_LPWSTR:
2048 return MONO_MARSHAL_CONV_LPWSTR_STR;
2049 case MONO_NATIVE_LPSTR:
2050 return MONO_MARSHAL_CONV_LPSTR_STR;
2051 case MONO_NATIVE_LPTSTR:
2052 return MONO_MARSHAL_CONV_LPTSTR_STR;
2053 case MONO_NATIVE_BSTR:
2054 return MONO_MARSHAL_CONV_BSTR_STR;
2060 static MonoMarshalConv
2061 mono_marshal_get_ptr_to_stringbuilder_conv (MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec, gboolean *need_free)
2063 MonoMarshalNative encoding = mono_marshal_get_string_encoding (piinfo, spec);
2068 case MONO_NATIVE_LPWSTR:
2070 * mono_string_builder_to_utf16 does not allocate a
2071 * new buffer, so no need to free it.
2074 return MONO_MARSHAL_CONV_LPWSTR_SB;
2075 case MONO_NATIVE_LPSTR:
2076 return MONO_MARSHAL_CONV_LPSTR_SB;
2078 case MONO_NATIVE_LPTSTR:
2079 return MONO_MARSHAL_CONV_LPTSTR_SB;
2087 * Return whenever a field of a native structure or an array member needs to
2091 mono_marshal_need_free (MonoType *t, MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec)
2093 MonoMarshalNative encoding;
2094 MonoMarshalConv conv;
2097 case MONO_TYPE_VALUETYPE:
2098 /* FIXME: Optimize this */
2100 case MONO_TYPE_OBJECT:
2101 case MONO_TYPE_CLASS:
2102 if (t->data.klass == mono_defaults.stringbuilder_class) {
2104 conv = mono_marshal_get_ptr_to_stringbuilder_conv (piinfo, spec, &need_free);
2108 case MONO_TYPE_STRING:
2109 encoding = mono_marshal_get_string_encoding (piinfo, spec);
2110 return (encoding == MONO_NATIVE_LPWSTR) ? FALSE : TRUE;
2117 * Return the hash table pointed to by VAR, lazily creating it if neccesary.
2120 get_cache (GHashTable **var, GHashFunc hash_func, GCompareFunc equal_func)
2123 mono_marshal_lock ();
2126 g_hash_table_new (hash_func, equal_func);
2127 mono_memory_barrier ();
2130 mono_marshal_unlock ();
2136 mono_marshal_get_cache (GHashTable **var, GHashFunc hash_func, GCompareFunc equal_func)
2138 return get_cache (var, hash_func, equal_func);
2142 mono_marshal_find_in_cache (GHashTable *cache, gpointer key)
2146 mono_marshal_lock ();
2147 res = g_hash_table_lookup (cache, key);
2148 mono_marshal_unlock ();
2153 mono_marshal_method_set_wrapper_data (MonoMethod *method, gpointer data)
2157 if (method->wrapper_type == MONO_WRAPPER_NONE || method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
2160 datav = ((MonoMethodWrapper *)method)->method_data;
2164 /* Create the method from the builder and place it in the cache */
2166 mono_mb_create_and_cache (GHashTable *cache, gpointer key,
2167 MonoMethodBuilder *mb, MonoMethodSignature *sig,
2172 mono_marshal_lock ();
2173 res = g_hash_table_lookup (cache, key);
2174 mono_marshal_unlock ();
2177 newm = mono_mb_create_method (mb, sig, max_stack);
2178 mono_marshal_lock ();
2179 res = g_hash_table_lookup (cache, key);
2182 g_hash_table_insert (cache, key, res);
2183 mono_marshal_method_set_wrapper_data (res, key);
2184 mono_marshal_unlock ();
2186 mono_marshal_unlock ();
2187 mono_free_method (newm);
2195 static inline MonoMethod*
2196 mono_marshal_remoting_find_in_cache (MonoMethod *method, int wrapper_type)
2198 MonoMethod *res = NULL;
2199 MonoRemotingMethods *wrps;
2201 mono_marshal_lock ();
2202 if (method->klass->image->remoting_invoke_cache)
2203 wrps = g_hash_table_lookup (method->klass->image->remoting_invoke_cache, method);
2208 switch (wrapper_type) {
2209 case MONO_WRAPPER_REMOTING_INVOKE: res = wrps->invoke; break;
2210 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK: res = wrps->invoke_with_check; break;
2211 case MONO_WRAPPER_XDOMAIN_INVOKE: res = wrps->xdomain_invoke; break;
2212 case MONO_WRAPPER_XDOMAIN_DISPATCH: res = wrps->xdomain_dispatch; break;
2216 /* it is important to do the unlock after the load from wrps, since in
2217 * mono_remoting_mb_create_and_cache () we drop the marshal lock to be able
2218 * to take the loader lock and some other thread may set the fields.
2220 mono_marshal_unlock ();
2224 /* Create the method from the builder and place it in the cache */
2225 static inline MonoMethod*
2226 mono_remoting_mb_create_and_cache (MonoMethod *key, MonoMethodBuilder *mb,
2227 MonoMethodSignature *sig, int max_stack)
2229 MonoMethod **res = NULL;
2230 MonoRemotingMethods *wrps;
2231 GHashTable *cache = get_cache (&key->klass->image->remoting_invoke_cache, mono_aligned_addr_hash, NULL);
2233 mono_marshal_lock ();
2234 wrps = g_hash_table_lookup (cache, key);
2236 wrps = g_new0 (MonoRemotingMethods, 1);
2237 g_hash_table_insert (cache, key, wrps);
2240 switch (mb->method->wrapper_type) {
2241 case MONO_WRAPPER_REMOTING_INVOKE: res = &wrps->invoke; break;
2242 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK: res = &wrps->invoke_with_check; break;
2243 case MONO_WRAPPER_XDOMAIN_INVOKE: res = &wrps->xdomain_invoke; break;
2244 case MONO_WRAPPER_XDOMAIN_DISPATCH: res = &wrps->xdomain_dispatch; break;
2245 default: g_assert_not_reached (); break;
2247 mono_marshal_unlock ();
2251 newm = mono_mb_create_method (mb, sig, max_stack);
2253 mono_marshal_lock ();
2256 mono_marshal_method_set_wrapper_data (*res, key);
2257 mono_marshal_unlock ();
2259 mono_marshal_unlock ();
2260 mono_free_method (newm);
2268 mono_marshal_method_from_wrapper (MonoMethod *wrapper)
2272 if (wrapper->wrapper_type == MONO_WRAPPER_NONE || wrapper->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
2275 res = mono_method_get_wrapper_data (wrapper, 1);
2282 mono_marshal_get_delegate_begin_invoke (MonoMethod *method)
2284 MonoMethodSignature *sig;
2285 MonoMethodBuilder *mb;
2291 g_assert (method && method->klass->parent == mono_defaults.multicastdelegate_class &&
2292 !strcmp (method->name, "BeginInvoke"));
2294 sig = mono_signature_no_pinvoke (method);
2296 cache = get_cache (&method->klass->image->delegate_begin_invoke_cache,
2297 (GHashFunc)mono_signature_hash,
2298 (GCompareFunc)mono_metadata_signature_equal);
2299 if ((res = mono_marshal_find_in_cache (cache, sig)))
2302 g_assert (sig->hasthis);
2304 name = mono_signature_to_name (sig, "begin_invoke");
2305 mb = mono_mb_new (method->klass, name, MONO_WRAPPER_DELEGATE_BEGIN_INVOKE);
2308 params_var = mono_mb_emit_save_args (mb, sig, FALSE);
2310 mono_mb_emit_ldarg (mb, 0);
2311 mono_mb_emit_ldloc (mb, params_var);
2312 mono_mb_emit_icall (mb, mono_delegate_begin_invoke);
2313 mono_mb_emit_byte (mb, CEE_RET);
2315 res = mono_mb_create_and_cache (cache, sig, mb, sig, sig->param_count + 16);
2321 mono_delegate_end_invoke (MonoDelegate *delegate, gpointer *params)
2323 MonoDomain *domain = mono_domain_get ();
2324 MonoAsyncResult *ares;
2325 MonoMethod *method = NULL;
2326 MonoMethodSignature *sig;
2327 MonoMethodMessage *msg;
2328 MonoObject *res, *exc;
2329 MonoArray *out_args;
2332 g_assert (delegate);
2334 if (!delegate->method_info) {
2335 g_assert (delegate->method);
2336 MONO_OBJECT_SETREF (delegate, method_info, mono_method_get_object (domain, delegate->method, NULL));
2339 if (!delegate->method_info || !delegate->method_info->method)
2340 g_assert_not_reached ();
2342 klass = delegate->object.vtable->klass;
2344 method = mono_class_get_method_from_name (klass, "EndInvoke", -1);
2345 g_assert (method != NULL);
2347 sig = mono_signature_no_pinvoke (method);
2349 msg = mono_method_call_message_new (method, params, NULL, NULL, NULL);
2351 ares = mono_array_get (msg->args, gpointer, sig->param_count - 1);
2353 mono_raise_exception (mono_exception_from_name_msg (mono_defaults.corlib, "System.Runtime.Remoting", "RemotingException", "The async result object is null or of an unexpected type."));
2355 if (ares->async_delegate != (MonoObject*)delegate && mono_framework_version () >= 2) {
2356 mono_raise_exception (mono_get_exception_invalid_operation (
2357 "The IAsyncResult object provided does not match this delegate."));
2361 if (delegate->target && mono_object_class (delegate->target) == mono_defaults.transparent_proxy_class) {
2362 MonoTransparentProxy* tp = (MonoTransparentProxy *)delegate->target;
2363 msg = (MonoMethodMessage *)mono_object_new (domain, mono_defaults.mono_method_message_class);
2364 mono_message_init (domain, msg, delegate->method_info, NULL);
2365 msg->call_type = CallType_EndInvoke;
2366 MONO_OBJECT_SETREF (msg, async_result, ares);
2367 res = mono_remoting_invoke ((MonoObject *)tp->rp, msg, &exc, &out_args);
2369 res = mono_thread_pool_finish (ares, &out_args, &exc);
2373 if (((MonoException*)exc)->stack_trace) {
2374 char *strace = mono_string_to_utf8 (((MonoException*)exc)->stack_trace);
2376 tmp = g_strdup_printf ("%s\nException Rethrown at:\n", strace);
2378 MONO_OBJECT_SETREF (((MonoException*)exc), stack_trace, mono_string_new (domain, tmp));
2381 mono_raise_exception ((MonoException*)exc);
2384 mono_method_return_message_restore (method, params, out_args);
2389 mono_mb_emit_restore_result (MonoMethodBuilder *mb, MonoType *return_type)
2391 MonoType *t = mono_type_get_underlying_type (return_type);
2393 if (return_type->byref)
2394 return_type = &mono_defaults.int_class->byval_arg;
2397 case MONO_TYPE_VOID:
2398 g_assert_not_reached ();
2401 case MONO_TYPE_STRING:
2402 case MONO_TYPE_CLASS:
2403 case MONO_TYPE_OBJECT:
2404 case MONO_TYPE_ARRAY:
2405 case MONO_TYPE_SZARRAY:
2409 case MONO_TYPE_BOOLEAN:
2412 case MONO_TYPE_CHAR:
2422 mono_mb_emit_op (mb, CEE_UNBOX, mono_class_from_mono_type (return_type));
2423 mono_mb_emit_byte (mb, mono_type_to_ldind (return_type));
2425 case MONO_TYPE_GENERICINST:
2426 if (!mono_type_generic_inst_is_valuetype (return_type))
2429 case MONO_TYPE_VALUETYPE: {
2430 MonoClass *klass = mono_class_from_mono_type (return_type);
2431 mono_mb_emit_op (mb, CEE_UNBOX, klass);
2432 mono_mb_emit_op (mb, CEE_LDOBJ, klass);
2436 g_warning ("type 0x%x not handled", return_type->type);
2437 g_assert_not_reached ();
2440 mono_mb_emit_byte (mb, CEE_RET);
2444 mono_marshal_get_delegate_end_invoke (MonoMethod *method)
2446 MonoMethodSignature *sig;
2447 MonoMethodBuilder *mb;
2453 g_assert (method && method->klass->parent == mono_defaults.multicastdelegate_class &&
2454 !strcmp (method->name, "EndInvoke"));
2456 sig = mono_signature_no_pinvoke (method);
2458 cache = get_cache (&method->klass->image->delegate_end_invoke_cache,
2459 (GHashFunc)mono_signature_hash,
2460 (GCompareFunc)mono_metadata_signature_equal);
2461 if ((res = mono_marshal_find_in_cache (cache, sig)))
2464 g_assert (sig->hasthis);
2466 name = mono_signature_to_name (sig, "end_invoke");
2467 mb = mono_mb_new (method->klass, name, MONO_WRAPPER_DELEGATE_END_INVOKE);
2470 params_var = mono_mb_emit_save_args (mb, sig, FALSE);
2472 mono_mb_emit_ldarg (mb, 0);
2473 mono_mb_emit_ldloc (mb, params_var);
2474 mono_mb_emit_icall (mb, mono_delegate_end_invoke);
2476 if (sig->ret->type == MONO_TYPE_VOID) {
2477 mono_mb_emit_byte (mb, CEE_POP);
2478 mono_mb_emit_byte (mb, CEE_RET);
2480 mono_mb_emit_restore_result (mb, sig->ret);
2482 res = mono_mb_create_and_cache (cache, sig,
2483 mb, sig, sig->param_count + 16);
2490 mono_remoting_wrapper (MonoMethod *method, gpointer *params)
2492 MonoMethodMessage *msg;
2493 MonoTransparentProxy *this;
2494 MonoObject *res, *exc;
2495 MonoArray *out_args;
2497 this = *((MonoTransparentProxy **)params [0]);
2500 g_assert (((MonoObject *)this)->vtable->klass == mono_defaults.transparent_proxy_class);
2502 /* skip the this pointer */
2505 if (this->remote_class->proxy_class->contextbound && this->rp->context == (MonoObject *) mono_context_get ())
2508 MonoMethodSignature *sig = mono_method_signature (method);
2509 int count = sig->param_count;
2510 gpointer* mparams = (gpointer*) alloca(count*sizeof(gpointer));
2512 for (i=0; i<count; i++) {
2513 MonoClass *class = mono_class_from_mono_type (sig->params [i]);
2514 if (class->valuetype) {
2515 if (sig->params [i]->byref) {
2516 mparams[i] = *((gpointer *)params [i]);
2518 /* runtime_invoke expects a boxed instance */
2519 if (mono_class_is_nullable (mono_class_from_mono_type (sig->params [i])))
2520 mparams[i] = mono_nullable_box (params [i], class);
2522 mparams[i] = params [i];
2525 mparams[i] = *((gpointer**)params [i]);
2529 return mono_runtime_invoke (method, method->klass->valuetype? mono_object_unbox ((MonoObject*)this): this, mparams, NULL);
2532 msg = mono_method_call_message_new (method, params, NULL, NULL, NULL);
2534 res = mono_remoting_invoke ((MonoObject *)this->rp, msg, &exc, &out_args);
2537 mono_raise_exception ((MonoException *)exc);
2539 mono_method_return_message_restore (method, params, out_args);
2545 mono_marshal_get_remoting_invoke (MonoMethod *method)
2547 MonoMethodSignature *sig;
2548 MonoMethodBuilder *mb;
2554 if (method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE || method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE)
2557 /* this seems to be the best plase to put this, as all remoting invokes seem to get filtered through here */
2558 if ((method->klass->is_com_object || method->klass == mono_defaults.com_object_class) && !mono_class_vtable (mono_domain_get (), method->klass)->remote) {
2560 return mono_cominterop_get_invoke (method);
2562 g_assert_not_reached ();
2566 sig = mono_signature_no_pinvoke (method);
2568 /* we cant remote methods without this pointer */
2572 if ((res = mono_marshal_remoting_find_in_cache (method, MONO_WRAPPER_REMOTING_INVOKE)))
2575 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_REMOTING_INVOKE);
2576 mb->method->save_lmf = 1;
2578 params_var = mono_mb_emit_save_args (mb, sig, TRUE);
2580 mono_mb_emit_ptr (mb, method);
2581 mono_mb_emit_ldloc (mb, params_var);
2582 mono_mb_emit_icall (mb, mono_remoting_wrapper);
2583 emit_thread_interrupt_checkpoint (mb);
2585 if (sig->ret->type == MONO_TYPE_VOID) {
2586 mono_mb_emit_byte (mb, CEE_POP);
2587 mono_mb_emit_byte (mb, CEE_RET);
2589 mono_mb_emit_restore_result (mb, sig->ret);
2592 res = mono_remoting_mb_create_and_cache (method, mb, sig, sig->param_count + 16);
2598 /* mono_get_xdomain_marshal_type()
2599 * Returns the kind of marshalling that a type needs for cross domain calls.
2601 static MonoXDomainMarshalType
2602 mono_get_xdomain_marshal_type (MonoType *t)
2605 case MONO_TYPE_VOID:
2606 g_assert_not_reached ();
2610 case MONO_TYPE_BOOLEAN:
2613 case MONO_TYPE_CHAR:
2620 return MONO_MARSHAL_NONE;
2621 case MONO_TYPE_STRING:
2622 return MONO_MARSHAL_COPY;
2623 case MONO_TYPE_ARRAY:
2624 case MONO_TYPE_SZARRAY: {
2625 MonoClass *elem_class = mono_class_from_mono_type (t)->element_class;
2626 if (mono_get_xdomain_marshal_type (&(elem_class->byval_arg)) != MONO_MARSHAL_SERIALIZE)
2627 return MONO_MARSHAL_COPY;
2632 return MONO_MARSHAL_SERIALIZE;
2636 /* mono_marshal_xdomain_copy_value
2637 * Makes a copy of "val" suitable for the current domain.
2640 mono_marshal_xdomain_copy_value (MonoObject *val)
2643 if (val == NULL) return NULL;
2645 domain = mono_domain_get ();
2647 switch (mono_object_class (val)->byval_arg.type) {
2648 case MONO_TYPE_VOID:
2649 g_assert_not_reached ();
2653 case MONO_TYPE_BOOLEAN:
2656 case MONO_TYPE_CHAR:
2662 case MONO_TYPE_R8: {
2663 return mono_value_box (domain, mono_object_class (val), ((char*)val) + sizeof(MonoObject));
2665 case MONO_TYPE_STRING: {
2666 MonoString *str = (MonoString *) val;
2667 return (MonoObject *) mono_string_new_utf16 (domain, mono_string_chars (str), mono_string_length (str));
2669 case MONO_TYPE_ARRAY:
2670 case MONO_TYPE_SZARRAY: {
2672 MonoXDomainMarshalType mt = mono_get_xdomain_marshal_type (&(mono_object_class (val)->element_class->byval_arg));
2673 if (mt == MONO_MARSHAL_SERIALIZE) return NULL;
2674 acopy = mono_array_clone_in_domain (domain, (MonoArray *) val);
2675 if (mt == MONO_MARSHAL_COPY) {
2676 int i, len = mono_array_length (acopy);
2677 for (i = 0; i < len; i++) {
2678 MonoObject *item = mono_array_get (acopy, gpointer, i);
2679 mono_array_setref (acopy, i, mono_marshal_xdomain_copy_value (item));
2682 return (MonoObject *) acopy;
2686 if (mono_object_class (val) == mono_defaults.stringbuilder_class) {
2687 MonoStringBuilder *oldsb = (MonoStringBuilder *) val;
2688 MonoStringBuilder *newsb = (MonoStringBuilder *) mono_object_new (domain, mono_defaults.stringbuilder_class);
2689 MONO_OBJECT_SETREF (newsb, str, mono_string_new_utf16 (domain, mono_string_chars (oldsb->str), mono_string_length (oldsb->str)));
2690 newsb->length = oldsb->length;
2691 newsb->max_capacity = (gint32)0x7fffffff;
2692 return (MonoObject *) newsb;
2697 /* mono_marshal_xdomain_copy_out_value()
2698 * Copies the contents of the src instance into the dst instance. src and dst
2699 * must have the same type, and if they are arrays, the same size.
2702 mono_marshal_xdomain_copy_out_value (MonoObject *src, MonoObject *dst)
2704 if (src == NULL || dst == NULL) return;
2706 g_assert (mono_object_class (src) == mono_object_class (dst));
2708 switch (mono_object_class (src)->byval_arg.type) {
2709 case MONO_TYPE_ARRAY:
2710 case MONO_TYPE_SZARRAY: {
2711 int mt = mono_get_xdomain_marshal_type (&(mono_object_class (src)->element_class->byval_arg));
2712 if (mt == MONO_MARSHAL_SERIALIZE) return;
2713 if (mt == MONO_MARSHAL_COPY) {
2714 int i, len = mono_array_length ((MonoArray *)dst);
2715 for (i = 0; i < len; i++) {
2716 MonoObject *item = mono_array_get ((MonoArray *)src, gpointer, i);
2717 mono_array_setref ((MonoArray *)dst, i, mono_marshal_xdomain_copy_value (item));
2720 mono_array_full_copy ((MonoArray *)src, (MonoArray *)dst);
2726 if (mono_object_class (src) == mono_defaults.stringbuilder_class) {
2727 MonoStringBuilder *src_sb = (MonoStringBuilder *) src;
2728 MonoStringBuilder *dst_sb = (MonoStringBuilder *) dst;
2730 MONO_OBJECT_SETREF (dst_sb, str, mono_string_new_utf16 (mono_object_domain (dst), mono_string_chars (src_sb->str), mono_string_length (src_sb->str)));
2731 dst_sb->cached_str = NULL;
2732 dst_sb->length = src_sb->length;
2737 mono_marshal_emit_xdomain_copy_value (MonoMethodBuilder *mb, MonoClass *pclass)
2739 mono_mb_emit_icall (mb, mono_marshal_xdomain_copy_value);
2740 mono_mb_emit_op (mb, CEE_CASTCLASS, pclass);
2744 mono_marshal_emit_xdomain_copy_out_value (MonoMethodBuilder *mb, MonoClass *pclass)
2746 mono_mb_emit_icall (mb, mono_marshal_xdomain_copy_out_value);
2749 /* mono_marshal_supports_fast_xdomain()
2750 * Returns TRUE if the method can use the fast xdomain wrapper.
2753 mono_marshal_supports_fast_xdomain (MonoMethod *method)
2755 return !method->klass->contextbound &&
2756 !((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) && (strcmp (".ctor", method->name) == 0));
2760 mono_marshal_set_domain_by_id (gint32 id, MonoBoolean push)
2762 MonoDomain *current_domain = mono_domain_get ();
2763 MonoDomain *domain = mono_domain_get_by_id (id);
2765 if (!domain || !mono_domain_set (domain, FALSE))
2766 mono_raise_exception (mono_get_exception_appdomain_unloaded ());
2769 mono_thread_push_appdomain_ref (domain);
2771 mono_thread_pop_appdomain_ref ();
2773 return current_domain->domain_id;
2777 mono_marshal_emit_switch_domain (MonoMethodBuilder *mb)
2779 mono_mb_emit_icall (mb, mono_marshal_set_domain_by_id);
2782 /* mono_marshal_emit_load_domain_method ()
2783 * Loads into the stack a pointer to the code of the provided method for
2784 * the current domain.
2787 mono_marshal_emit_load_domain_method (MonoMethodBuilder *mb, MonoMethod *method)
2789 /* We need a pointer to the method for the running domain (not the domain
2790 * that compiles the method).
2792 mono_mb_emit_ptr (mb, method);
2793 mono_mb_emit_icall (mb, mono_compile_method);
2796 /* mono_marshal_check_domain_image ()
2797 * Returns TRUE if the image is loaded in the specified
2798 * application domain.
2801 mono_marshal_check_domain_image (gint32 domain_id, MonoImage *image)
2806 MonoDomain *domain = mono_domain_get_by_id (domain_id);
2810 mono_domain_assemblies_lock (domain);
2811 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
2813 if (ass->image == image)
2816 mono_domain_assemblies_unlock (domain);
2821 /* mono_marshal_get_xappdomain_dispatch ()
2822 * Generates a method that dispatches a method call from another domain into
2823 * the current domain.
2826 mono_marshal_get_xappdomain_dispatch (MonoMethod *method, int *marshal_types, int complex_count, int complex_out_count, int ret_marshal_type)
2828 MonoMethodSignature *sig, *csig;
2829 MonoMethodBuilder *mb;
2831 int i, j, param_index, copy_locals_base;
2832 MonoClass *ret_class = NULL;
2833 int loc_array=0, loc_return=0, loc_serialized_exc=0;
2834 MonoExceptionClause *main_clause;
2836 gboolean copy_return;
2838 if ((res = mono_marshal_remoting_find_in_cache (method, MONO_WRAPPER_XDOMAIN_DISPATCH)))
2841 sig = mono_method_signature (method);
2842 copy_return = (sig->ret->type != MONO_TYPE_VOID && ret_marshal_type != MONO_MARSHAL_SERIALIZE);
2845 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3 + sig->param_count - complex_count);
2846 csig->params [j++] = &mono_defaults.object_class->byval_arg;
2847 csig->params [j++] = &byte_array_class->this_arg;
2848 csig->params [j++] = &byte_array_class->this_arg;
2849 for (i = 0; i < sig->param_count; i++) {
2850 if (marshal_types [i] != MONO_MARSHAL_SERIALIZE)
2851 csig->params [j++] = sig->params [i];
2854 csig->ret = sig->ret;
2856 csig->ret = &mono_defaults.void_class->byval_arg;
2858 csig->hasthis = FALSE;
2860 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_XDOMAIN_DISPATCH);
2861 mb->method->save_lmf = 1;
2865 loc_serialized_exc = mono_mb_add_local (mb, &byte_array_class->byval_arg);
2866 if (complex_count > 0)
2867 loc_array = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
2868 if (sig->ret->type != MONO_TYPE_VOID) {
2869 loc_return = mono_mb_add_local (mb, sig->ret);
2870 ret_class = mono_class_from_mono_type (sig->ret);
2875 main_clause = mono_image_alloc0 (method->klass->image, sizeof (MonoExceptionClause));
2876 main_clause->try_offset = mono_mb_get_label (mb);
2878 /* Clean the call context */
2880 mono_mb_emit_byte (mb, CEE_LDNULL);
2881 mono_mb_emit_managed_call (mb, method_set_call_context, NULL);
2882 mono_mb_emit_byte (mb, CEE_POP);
2884 /* Deserialize call data */
2886 mono_mb_emit_ldarg (mb, 1);
2887 mono_mb_emit_byte (mb, CEE_LDIND_REF);
2888 mono_mb_emit_byte (mb, CEE_DUP);
2889 pos = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
2891 mono_marshal_emit_xdomain_copy_value (mb, byte_array_class);
2892 mono_mb_emit_managed_call (mb, method_rs_deserialize, NULL);
2894 if (complex_count > 0)
2895 mono_mb_emit_stloc (mb, loc_array);
2897 mono_mb_emit_byte (mb, CEE_POP);
2899 mono_mb_patch_short_branch (mb, pos);
2901 /* Get the target object */
2903 mono_mb_emit_ldarg (mb, 0);
2904 mono_mb_emit_managed_call (mb, method_rs_appdomain_target, NULL);
2906 /* Load the arguments */
2908 copy_locals_base = mb->locals;
2909 param_index = 3; // Index of the first non-serialized parameter of this wrapper
2911 for (i = 0; i < sig->param_count; i++) {
2912 MonoType *pt = sig->params [i];
2913 MonoClass *pclass = mono_class_from_mono_type (pt);
2914 switch (marshal_types [i]) {
2915 case MONO_MARSHAL_SERIALIZE: {
2916 /* take the value from the serialized array */
2917 mono_mb_emit_ldloc (mb, loc_array);
2918 mono_mb_emit_icon (mb, j++);
2920 if (pclass->valuetype) {
2921 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
2922 mono_mb_emit_op (mb, CEE_UNBOX, pclass);
2924 mono_mb_emit_op (mb, CEE_LDELEMA, pclass);
2927 if (pclass->valuetype) {
2928 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
2929 mono_mb_emit_op (mb, CEE_UNBOX, pclass);
2930 mono_mb_emit_op (mb, CEE_LDOBJ, pclass);
2932 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
2933 if (pclass != mono_defaults.object_class) {
2934 mono_mb_emit_op (mb, CEE_CASTCLASS, pclass);
2940 case MONO_MARSHAL_COPY_OUT: {
2941 /* Keep a local copy of the value since we need to copy it back after the call */
2942 int copy_local = mono_mb_add_local (mb, &(pclass->byval_arg));
2943 mono_mb_emit_ldarg (mb, param_index++);
2944 mono_marshal_emit_xdomain_copy_value (mb, pclass);
2945 mono_mb_emit_byte (mb, CEE_DUP);
2946 mono_mb_emit_stloc (mb, copy_local);
2949 case MONO_MARSHAL_COPY: {
2950 mono_mb_emit_ldarg (mb, param_index);
2952 mono_mb_emit_byte (mb, CEE_DUP);
2953 mono_mb_emit_byte (mb, CEE_DUP);
2954 mono_mb_emit_byte (mb, CEE_LDIND_REF);
2955 mono_marshal_emit_xdomain_copy_value (mb, pclass);
2956 mono_mb_emit_byte (mb, CEE_STIND_REF);
2958 mono_marshal_emit_xdomain_copy_value (mb, pclass);
2963 case MONO_MARSHAL_NONE:
2964 mono_mb_emit_ldarg (mb, param_index++);
2969 /* Make the call to the real object */
2971 emit_thread_force_interrupt_checkpoint (mb);
2973 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
2975 if (sig->ret->type != MONO_TYPE_VOID)
2976 mono_mb_emit_stloc (mb, loc_return);
2978 /* copy back MONO_MARSHAL_COPY_OUT parameters */
2982 for (i = 0; i < sig->param_count; i++) {
2983 if (marshal_types [i] == MONO_MARSHAL_SERIALIZE) continue;
2984 if (marshal_types [i] == MONO_MARSHAL_COPY_OUT) {
2985 mono_mb_emit_ldloc (mb, copy_locals_base + (j++));
2986 mono_mb_emit_ldarg (mb, param_index);
2987 mono_marshal_emit_xdomain_copy_out_value (mb, mono_class_from_mono_type (sig->params [i]));
2992 /* Serialize the return values */
2994 if (complex_out_count > 0) {
2995 /* Reset parameters in the array that don't need to be serialized back */
2997 for (i = 0; i < sig->param_count; i++) {
2998 if (marshal_types[i] != MONO_MARSHAL_SERIALIZE) continue;
2999 if (!sig->params [i]->byref) {
3000 mono_mb_emit_ldloc (mb, loc_array);
3001 mono_mb_emit_icon (mb, j);
3002 mono_mb_emit_byte (mb, CEE_LDNULL);
3003 mono_mb_emit_byte (mb, CEE_STELEM_REF);
3008 /* Add the return value to the array */
3010 if (ret_marshal_type == MONO_MARSHAL_SERIALIZE) {
3011 mono_mb_emit_ldloc (mb, loc_array);
3012 mono_mb_emit_icon (mb, complex_count); /* The array has an additional slot to hold the ret value */
3013 mono_mb_emit_ldloc (mb, loc_return);
3014 if (ret_class->valuetype) {
3015 mono_mb_emit_op (mb, CEE_BOX, ret_class);
3017 mono_mb_emit_byte (mb, CEE_STELEM_REF);
3022 mono_mb_emit_ldarg (mb, 1);
3023 mono_mb_emit_ldloc (mb, loc_array);
3024 mono_mb_emit_managed_call (mb, method_rs_serialize, NULL);
3025 mono_mb_emit_byte (mb, CEE_STIND_REF);
3026 } else if (ret_marshal_type == MONO_MARSHAL_SERIALIZE) {
3027 mono_mb_emit_ldarg (mb, 1);
3028 mono_mb_emit_ldloc (mb, loc_return);
3029 if (ret_class->valuetype) {
3030 mono_mb_emit_op (mb, CEE_BOX, ret_class);
3032 mono_mb_emit_managed_call (mb, method_rs_serialize, NULL);
3033 mono_mb_emit_byte (mb, CEE_STIND_REF);
3035 mono_mb_emit_ldarg (mb, 1);
3036 mono_mb_emit_byte (mb, CEE_LDNULL);
3037 mono_mb_emit_managed_call (mb, method_rs_serialize, NULL);
3038 mono_mb_emit_byte (mb, CEE_STIND_REF);
3041 mono_mb_emit_ldarg (mb, 2);
3042 mono_mb_emit_byte (mb, CEE_LDNULL);
3043 mono_mb_emit_byte (mb, CEE_STIND_REF);
3044 pos_leave = mono_mb_emit_branch (mb, CEE_LEAVE);
3046 /* Main exception catch */
3047 main_clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
3048 main_clause->try_len = mono_mb_get_pos (mb) - main_clause->try_offset;
3049 main_clause->data.catch_class = mono_defaults.object_class;
3052 main_clause->handler_offset = mono_mb_get_label (mb);
3053 mono_mb_emit_managed_call (mb, method_rs_serialize_exc, NULL);
3054 mono_mb_emit_stloc (mb, loc_serialized_exc);
3055 mono_mb_emit_ldarg (mb, 2);
3056 mono_mb_emit_ldloc (mb, loc_serialized_exc);
3057 mono_mb_emit_byte (mb, CEE_STIND_REF);
3058 mono_mb_emit_branch (mb, CEE_LEAVE);
3059 main_clause->handler_len = mono_mb_get_pos (mb) - main_clause->handler_offset;
3062 mono_mb_patch_branch (mb, pos_leave);
3065 mono_mb_emit_ldloc (mb, loc_return);
3067 mono_mb_emit_byte (mb, CEE_RET);
3069 mono_mb_set_clauses (mb, 1, main_clause);
3071 res = mono_remoting_mb_create_and_cache (method, mb, csig, csig->param_count + 16);
3077 /* mono_marshal_get_xappdomain_invoke ()
3078 * Generates a fast remoting wrapper for cross app domain calls.
3081 mono_marshal_get_xappdomain_invoke (MonoMethod *method)
3083 MonoMethodSignature *sig;
3084 MonoMethodBuilder *mb;
3086 int i, j, complex_count, complex_out_count, copy_locals_base;
3088 MonoClass *ret_class = NULL;
3089 MonoMethod *xdomain_method;
3090 int ret_marshal_type = MONO_MARSHAL_NONE;
3091 int loc_array=0, loc_serialized_data=-1, loc_real_proxy;
3092 int loc_old_domainid, loc_domainid, loc_return=0, loc_serialized_exc=0, loc_context;
3093 int pos, pos_dispatch, pos_noex;
3094 gboolean copy_return = FALSE;
3098 if (method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE || method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE)
3101 /* we cant remote methods without this pointer */
3102 if (!mono_method_signature (method)->hasthis)
3105 if (!mono_marshal_supports_fast_xdomain (method))
3106 return mono_marshal_get_remoting_invoke (method);
3108 mono_remoting_marshal_init ();
3110 if ((res = mono_marshal_remoting_find_in_cache (method, MONO_WRAPPER_XDOMAIN_INVOKE)))
3113 sig = mono_signature_no_pinvoke (method);
3115 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_XDOMAIN_INVOKE);
3116 mb->method->save_lmf = 1;
3118 /* Count the number of parameters that need to be serialized */
3120 marshal_types = alloca (sizeof (int) * sig->param_count);
3121 complex_count = complex_out_count = 0;
3122 for (i = 0; i < sig->param_count; i++) {
3123 MonoType *ptype = sig->params[i];
3124 int mt = mono_get_xdomain_marshal_type (ptype);
3126 /* If the [Out] attribute is applied to a parameter that can be internally copied,
3127 * the copy will be made by reusing the original object instance
3129 if ((ptype->attrs & PARAM_ATTRIBUTE_OUT) != 0 && mt == MONO_MARSHAL_COPY && !ptype->byref)
3130 mt = MONO_MARSHAL_COPY_OUT;
3131 else if (mt == MONO_MARSHAL_SERIALIZE) {
3133 if (ptype->byref) complex_out_count++;
3135 marshal_types [i] = mt;
3138 if (sig->ret->type != MONO_TYPE_VOID) {
3139 ret_marshal_type = mono_get_xdomain_marshal_type (sig->ret);
3140 ret_class = mono_class_from_mono_type (sig->ret);
3141 copy_return = ret_marshal_type != MONO_MARSHAL_SERIALIZE;
3146 if (complex_count > 0)
3147 loc_array = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
3148 loc_serialized_data = mono_mb_add_local (mb, &byte_array_class->byval_arg);
3149 loc_real_proxy = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
3151 loc_return = mono_mb_add_local (mb, sig->ret);
3152 loc_old_domainid = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
3153 loc_domainid = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
3154 loc_serialized_exc = mono_mb_add_local (mb, &byte_array_class->byval_arg);
3155 loc_context = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
3157 /* Save thread domain data */
3159 mono_mb_emit_icall (mb, mono_context_get);
3160 mono_mb_emit_byte (mb, CEE_DUP);
3161 mono_mb_emit_stloc (mb, loc_context);
3163 /* If the thread is not running in the default context, it needs to go
3164 * through the whole remoting sink, since the context is going to change
3166 mono_mb_emit_managed_call (mb, method_needs_context_sink, NULL);
3167 pos = mono_mb_emit_short_branch (mb, CEE_BRTRUE_S);
3169 /* Another case in which the fast path can't be used: when the target domain
3170 * has a different image for the same assembly.
3173 /* Get the target domain id */
3175 mono_mb_emit_ldarg (mb, 0);
3176 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoTransparentProxy, rp));
3177 mono_mb_emit_byte (mb, CEE_LDIND_REF);
3178 mono_mb_emit_byte (mb, CEE_DUP);
3179 mono_mb_emit_stloc (mb, loc_real_proxy);
3181 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoRealProxy, target_domain_id));
3182 mono_mb_emit_byte (mb, CEE_LDIND_I4);
3183 mono_mb_emit_stloc (mb, loc_domainid);
3185 /* Check if the target domain has the same image for the required assembly */
3187 mono_mb_emit_ldloc (mb, loc_domainid);
3188 mono_mb_emit_ptr (mb, method->klass->image);
3189 mono_mb_emit_icall (mb, mono_marshal_check_domain_image);
3190 pos_dispatch = mono_mb_emit_short_branch (mb, CEE_BRTRUE_S);
3192 /* Use the whole remoting sink to dispatch this message */
3194 mono_mb_patch_short_branch (mb, pos);
3196 mono_mb_emit_ldarg (mb, 0);
3197 for (i = 0; i < sig->param_count; i++)
3198 mono_mb_emit_ldarg (mb, i + 1);
3200 mono_mb_emit_managed_call (mb, mono_marshal_get_remoting_invoke (method), NULL);
3201 mono_mb_emit_byte (mb, CEE_RET);
3202 mono_mb_patch_short_branch (mb, pos_dispatch);
3204 /* Create the array that will hold the parameters to be serialized */
3206 if (complex_count > 0) {
3207 mono_mb_emit_icon (mb, (ret_marshal_type == MONO_MARSHAL_SERIALIZE && complex_out_count > 0) ? complex_count + 1 : complex_count); /* +1 for the return type */
3208 mono_mb_emit_op (mb, CEE_NEWARR, mono_defaults.object_class);
3211 for (i = 0; i < sig->param_count; i++) {
3213 if (marshal_types [i] != MONO_MARSHAL_SERIALIZE) continue;
3214 pclass = mono_class_from_mono_type (sig->params[i]);
3215 mono_mb_emit_byte (mb, CEE_DUP);
3216 mono_mb_emit_icon (mb, j);
3217 mono_mb_emit_ldarg (mb, i + 1); /* 0=this */
3218 if (sig->params[i]->byref) {
3219 if (pclass->valuetype)
3220 mono_mb_emit_op (mb, CEE_LDOBJ, pclass);
3222 mono_mb_emit_byte (mb, CEE_LDIND_REF);
3224 if (pclass->valuetype)
3225 mono_mb_emit_op (mb, CEE_BOX, pclass);
3226 mono_mb_emit_byte (mb, CEE_STELEM_REF);
3229 mono_mb_emit_stloc (mb, loc_array);
3231 /* Serialize parameters */
3233 mono_mb_emit_ldloc (mb, loc_array);
3234 mono_mb_emit_managed_call (mb, method_rs_serialize, NULL);
3235 mono_mb_emit_stloc (mb, loc_serialized_data);
3237 mono_mb_emit_byte (mb, CEE_LDNULL);
3238 mono_mb_emit_managed_call (mb, method_rs_serialize, NULL);
3239 mono_mb_emit_stloc (mb, loc_serialized_data);
3244 mono_mb_emit_ldloc (mb, loc_domainid);
3245 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
3246 mono_marshal_emit_switch_domain (mb);
3247 mono_mb_emit_stloc (mb, loc_old_domainid);
3249 /* Load the arguments */
3251 mono_mb_emit_ldloc (mb, loc_real_proxy);
3252 mono_mb_emit_ldloc_addr (mb, loc_serialized_data);
3253 mono_mb_emit_ldloc_addr (mb, loc_serialized_exc);
3255 copy_locals_base = mb->locals;
3256 for (i = 0; i < sig->param_count; i++) {
3257 switch (marshal_types [i]) {
3258 case MONO_MARSHAL_SERIALIZE:
3260 case MONO_MARSHAL_COPY: {
3261 mono_mb_emit_ldarg (mb, i+1);
3262 if (sig->params [i]->byref) {
3263 /* make a local copy of the byref parameter. The real parameter
3264 * will be updated after the xdomain call
3266 MonoClass *pclass = mono_class_from_mono_type (sig->params [i]);
3267 int copy_local = mono_mb_add_local (mb, &(pclass->byval_arg));
3268 mono_mb_emit_byte (mb, CEE_LDIND_REF);
3269 mono_mb_emit_stloc (mb, copy_local);
3270 mono_mb_emit_ldloc_addr (mb, copy_local);
3274 case MONO_MARSHAL_COPY_OUT:
3275 case MONO_MARSHAL_NONE:
3276 mono_mb_emit_ldarg (mb, i+1);
3281 /* Make the call to the invoke wrapper in the target domain */
3283 xdomain_method = mono_marshal_get_xappdomain_dispatch (method, marshal_types, complex_count, complex_out_count, ret_marshal_type);
3284 mono_marshal_emit_load_domain_method (mb, xdomain_method);
3285 mono_mb_emit_calli (mb, mono_method_signature (xdomain_method));
3288 mono_mb_emit_stloc (mb, loc_return);
3292 mono_mb_emit_ldloc (mb, loc_old_domainid);
3293 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
3294 mono_marshal_emit_switch_domain (mb);
3295 mono_mb_emit_byte (mb, CEE_POP);
3297 /* Restore thread domain data */
3299 mono_mb_emit_ldloc (mb, loc_context);
3300 mono_mb_emit_icall (mb, mono_context_set);
3302 /* if (loc_serialized_exc != null) ... */
3304 mono_mb_emit_ldloc (mb, loc_serialized_exc);
3305 pos_noex = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
3307 mono_mb_emit_ldloc (mb, loc_serialized_exc);
3308 mono_marshal_emit_xdomain_copy_value (mb, byte_array_class);
3309 mono_mb_emit_managed_call (mb, method_rs_deserialize, NULL);
3310 mono_mb_emit_op (mb, CEE_CASTCLASS, mono_defaults.exception_class);
3311 mono_mb_emit_managed_call (mb, method_exc_fixexc, NULL);
3312 mono_mb_emit_byte (mb, CEE_THROW);
3313 mono_mb_patch_short_branch (mb, pos_noex);
3315 /* copy back non-serialized output parameters */
3318 for (i = 0; i < sig->param_count; i++) {
3319 if (!sig->params [i]->byref || marshal_types [i] != MONO_MARSHAL_COPY) continue;
3320 mono_mb_emit_ldarg (mb, i + 1);
3321 mono_mb_emit_ldloc (mb, copy_locals_base + (j++));
3322 mono_marshal_emit_xdomain_copy_value (mb, mono_class_from_mono_type (sig->params [i]));
3323 mono_mb_emit_byte (mb, CEE_STIND_REF);
3326 /* Deserialize out parameters */
3328 if (complex_out_count > 0) {
3329 mono_mb_emit_ldloc (mb, loc_serialized_data);
3330 mono_marshal_emit_xdomain_copy_value (mb, byte_array_class);
3331 mono_mb_emit_managed_call (mb, method_rs_deserialize, NULL);
3332 mono_mb_emit_stloc (mb, loc_array);
3334 /* Copy back output parameters and return type */
3337 for (i = 0; i < sig->param_count; i++) {
3338 if (marshal_types [i] != MONO_MARSHAL_SERIALIZE) continue;
3339 if (sig->params[i]->byref) {
3340 MonoClass *pclass = mono_class_from_mono_type (sig->params [i]);
3341 mono_mb_emit_ldarg (mb, i + 1);
3342 mono_mb_emit_ldloc (mb, loc_array);
3343 mono_mb_emit_icon (mb, j);
3344 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
3345 if (pclass->valuetype) {
3346 mono_mb_emit_op (mb, CEE_UNBOX, pclass);
3347 mono_mb_emit_op (mb, CEE_LDOBJ, pclass);
3348 mono_mb_emit_op (mb, CEE_STOBJ, pclass);
3350 if (pclass != mono_defaults.object_class)
3351 mono_mb_emit_op (mb, CEE_CASTCLASS, pclass);
3352 mono_mb_emit_byte (mb, CEE_STIND_REF);
3358 if (ret_marshal_type == MONO_MARSHAL_SERIALIZE) {
3359 mono_mb_emit_ldloc (mb, loc_array);
3360 mono_mb_emit_icon (mb, complex_count);
3361 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
3362 if (ret_class->valuetype) {
3363 mono_mb_emit_op (mb, CEE_UNBOX, ret_class);
3364 mono_mb_emit_op (mb, CEE_LDOBJ, ret_class);
3367 } else if (ret_marshal_type == MONO_MARSHAL_SERIALIZE) {
3368 mono_mb_emit_ldloc (mb, loc_serialized_data);
3369 mono_marshal_emit_xdomain_copy_value (mb, byte_array_class);
3370 mono_mb_emit_managed_call (mb, method_rs_deserialize, NULL);
3371 if (ret_class->valuetype) {
3372 mono_mb_emit_op (mb, CEE_UNBOX, ret_class);
3373 mono_mb_emit_op (mb, CEE_LDOBJ, ret_class);
3374 } else if (ret_class != mono_defaults.object_class) {
3375 mono_mb_emit_op (mb, CEE_CASTCLASS, ret_class);
3378 mono_mb_emit_ldloc (mb, loc_serialized_data);
3379 mono_mb_emit_byte (mb, CEE_DUP);
3380 pos = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
3381 mono_marshal_emit_xdomain_copy_value (mb, byte_array_class);
3383 mono_mb_patch_short_branch (mb, pos);
3384 mono_mb_emit_managed_call (mb, method_rs_deserialize, NULL);
3385 mono_mb_emit_byte (mb, CEE_POP);
3389 mono_mb_emit_ldloc (mb, loc_return);
3390 if (ret_marshal_type == MONO_MARSHAL_COPY)
3391 mono_marshal_emit_xdomain_copy_value (mb, ret_class);
3394 mono_mb_emit_byte (mb, CEE_RET);
3396 res = mono_remoting_mb_create_and_cache (method, mb, sig, sig->param_count + 16);
3403 mono_marshal_get_remoting_invoke_for_target (MonoMethod *method, MonoRemotingTarget target_type)
3405 if (target_type == MONO_REMOTING_TARGET_APPDOMAIN) {
3406 return mono_marshal_get_xappdomain_invoke (method);
3407 } else if (target_type == MONO_REMOTING_TARGET_COMINTEROP) {
3409 return mono_cominterop_get_invoke (method);
3411 g_assert_not_reached ();
3414 return mono_marshal_get_remoting_invoke (method);
3418 G_GNUC_UNUSED static gpointer
3419 mono_marshal_load_remoting_wrapper (MonoRealProxy *rp, MonoMethod *method)
3421 if (rp->target_domain_id != -1)
3422 return mono_compile_method (mono_marshal_get_xappdomain_invoke (method));
3424 return mono_compile_method (mono_marshal_get_remoting_invoke (method));
3428 mono_marshal_get_remoting_invoke_with_check (MonoMethod *method)
3430 MonoMethodSignature *sig;
3431 MonoMethodBuilder *mb;
3432 MonoMethod *res, *native;
3433 int i, pos, pos_rem;
3437 if (method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
3440 /* we cant remote methods without this pointer */
3441 g_assert (mono_method_signature (method)->hasthis);
3443 if ((res = mono_marshal_remoting_find_in_cache (method, MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)))
3446 sig = mono_signature_no_pinvoke (method);
3448 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK);
3450 for (i = 0; i <= sig->param_count; i++)
3451 mono_mb_emit_ldarg (mb, i);
3453 mono_mb_emit_ldarg (mb, 0);
3454 pos = mono_mb_emit_proxy_check (mb, CEE_BNE_UN);
3456 if (mono_marshal_supports_fast_xdomain (method)) {
3457 mono_mb_emit_ldarg (mb, 0);
3458 pos_rem = mono_mb_emit_xdomain_check (mb, CEE_BEQ);
3460 /* wrapper for cross app domain calls */
3461 native = mono_marshal_get_xappdomain_invoke (method);
3462 mono_mb_emit_managed_call (mb, native, mono_method_signature (native));
3463 mono_mb_emit_byte (mb, CEE_RET);
3465 mono_mb_patch_branch (mb, pos_rem);
3467 /* wrapper for normal remote calls */
3468 native = mono_marshal_get_remoting_invoke (method);
3469 mono_mb_emit_managed_call (mb, native, mono_method_signature (native));
3470 mono_mb_emit_byte (mb, CEE_RET);
3473 mono_mb_patch_branch (mb, pos);
3474 mono_mb_emit_managed_call (mb, method, mono_method_signature (method));
3475 mono_mb_emit_byte (mb, CEE_RET);
3477 res = mono_remoting_mb_create_and_cache (method, mb, sig, sig->param_count + 16);
3485 MonoMethodSignature *sig;
3487 } SignatureMethodPair;
3490 signature_method_pair_hash (gconstpointer data)
3492 SignatureMethodPair *pair = (SignatureMethodPair*)data;
3494 return mono_signature_hash (pair->sig) ^ mono_aligned_addr_hash (pair->method);
3498 signature_method_pair_equal (SignatureMethodPair *pair1, SignatureMethodPair *pair2)
3500 return mono_metadata_signature_equal (pair1->sig, pair2->sig) && (pair1->method == pair2->method);
3504 free_signature_method_pair (SignatureMethodPair *pair)
3510 * the returned method invokes all methods in a multicast delegate.
3513 mono_marshal_get_delegate_invoke (MonoMethod *method, MonoDelegate *del)
3515 MonoMethodSignature *sig, *static_sig;
3517 MonoMethodBuilder *mb;
3518 MonoMethod *res, *newm;
3520 SignatureMethodPair key;
3521 SignatureMethodPair *new_key;
3522 int local_prev, local_target;
3525 MonoMethod *target_method = NULL;
3526 MonoClass *target_class = NULL;
3527 gboolean callvirt = FALSE;
3530 * If the delegate target is null, and the target method is not static, a virtual
3531 * call is made to that method with the first delegate argument as this. This is
3532 * a non-documented .NET feature.
3534 if (del && !del->target && del->method && mono_method_signature (del->method)->hasthis) {
3536 target_method = del->method;
3537 if (target_method->is_inflated) {
3538 MonoType *target_type;
3540 g_assert (method->signature->hasthis);
3541 target_type = mono_class_inflate_generic_type (method->signature->params [0],
3542 mono_method_get_context (method));
3543 target_class = mono_class_from_mono_type (target_type);
3545 target_class = del->method->klass;
3549 g_assert (method && method->klass->parent == mono_defaults.multicastdelegate_class &&
3550 !strcmp (method->name, "Invoke"));
3552 sig = mono_signature_no_pinvoke (method);
3555 /* We need to cache the signature+method pair */
3556 mono_marshal_lock ();
3557 if (!method->klass->image->delegate_abstract_invoke_cache)
3558 method->klass->image->delegate_abstract_invoke_cache = g_hash_table_new_full (signature_method_pair_hash, (GEqualFunc)signature_method_pair_equal, (GDestroyNotify)free_signature_method_pair, NULL);
3559 cache = method->klass->image->delegate_abstract_invoke_cache;
3561 key.method = target_method;
3562 res = g_hash_table_lookup (cache, &key);
3563 mono_marshal_unlock ();
3567 cache = get_cache (&method->klass->image->delegate_invoke_cache,
3568 (GHashFunc)mono_signature_hash,
3569 (GCompareFunc)mono_metadata_signature_equal);
3570 if ((res = mono_marshal_find_in_cache (cache, sig)))
3574 static_sig = signature_dup (method->klass->image, sig);
3575 static_sig->hasthis = 0;
3577 name = mono_signature_to_name (sig, "invoke");
3578 mb = mono_mb_new (method->klass, name, MONO_WRAPPER_DELEGATE_INVOKE);
3581 /* allocate local 0 (object) */
3582 local_target = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
3583 local_prev = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
3585 g_assert (sig->hasthis);
3589 * prev.Invoke( args .. );
3590 * return this.<target>( args .. );
3593 /* this wrapper can be used in unmanaged-managed transitions */
3594 emit_thread_interrupt_checkpoint (mb);
3596 /* get this->prev */
3597 mono_mb_emit_ldarg (mb, 0);
3598 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoMulticastDelegate, prev));
3599 mono_mb_emit_byte (mb, CEE_LDIND_REF);
3600 mono_mb_emit_stloc (mb, local_prev);
3601 mono_mb_emit_ldloc (mb, local_prev);
3603 /* if prev != null */
3604 pos0 = mono_mb_emit_branch (mb, CEE_BRFALSE);
3608 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
3609 mono_mb_emit_byte (mb, CEE_MONO_NOT_TAKEN);
3611 mono_mb_emit_ldloc (mb, local_prev);
3612 for (i = 0; i < sig->param_count; i++)
3613 mono_mb_emit_ldarg (mb, i + 1);
3614 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
3615 if (sig->ret->type != MONO_TYPE_VOID)
3616 mono_mb_emit_byte (mb, CEE_POP);
3618 /* continued or prev == null */
3619 mono_mb_patch_branch (mb, pos0);
3621 /* get this->target */
3622 mono_mb_emit_ldarg (mb, 0);
3623 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoDelegate, target));
3624 mono_mb_emit_byte (mb, CEE_LDIND_REF);
3625 mono_mb_emit_stloc (mb, local_target);
3627 /* if target != null */
3628 mono_mb_emit_ldloc (mb, local_target);
3629 pos0 = mono_mb_emit_branch (mb, CEE_BRFALSE);
3631 /* then call this->method_ptr nonstatic */
3634 mono_mb_emit_exception_full (mb, "System", "NotImplementedException", "");
3636 mono_mb_emit_ldloc (mb, local_target);
3637 for (i = 0; i < sig->param_count; ++i)
3638 mono_mb_emit_ldarg (mb, i + 1);
3639 mono_mb_emit_ldarg (mb, 0);
3640 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoDelegate, method_ptr));
3641 mono_mb_emit_byte (mb, CEE_LDIND_I );
3642 mono_mb_emit_op (mb, CEE_CALLI, sig);
3644 mono_mb_emit_byte (mb, CEE_RET);
3647 /* else [target == null] call this->method_ptr static */
3648 mono_mb_patch_branch (mb, pos0);
3651 mono_mb_emit_ldarg (mb, 1);
3652 mono_mb_emit_op (mb, CEE_CASTCLASS, target_class);
3653 for (i = 1; i < sig->param_count; ++i)
3654 mono_mb_emit_ldarg (mb, i + 1);
3655 mono_mb_emit_op (mb, CEE_CALLVIRT, target_method);
3657 for (i = 0; i < sig->param_count; ++i)
3658 mono_mb_emit_ldarg (mb, i + 1);
3659 mono_mb_emit_ldarg (mb, 0);
3660 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoDelegate, method_ptr));
3661 mono_mb_emit_byte (mb, CEE_LDIND_I );
3662 mono_mb_emit_op (mb, CEE_CALLI, static_sig);
3665 mono_mb_emit_byte (mb, CEE_RET);
3668 // From mono_mb_create_and_cache
3669 mb->skip_visibility = 1;
3670 newm = mono_mb_create_method (mb, sig, sig->param_count + 16);
3671 /*We perform double checked locking, so must fence before publishing*/
3672 mono_memory_barrier ();
3673 mono_marshal_lock ();
3674 res = g_hash_table_lookup (cache, &key);
3677 new_key = g_new0 (SignatureMethodPair, 1);
3679 new_key->method = target_method;
3680 g_hash_table_insert (cache, new_key, res);
3681 mono_marshal_method_set_wrapper_data (res, new_key);
3682 mono_marshal_unlock ();
3684 mono_marshal_unlock ();
3685 mono_free_method (newm);
3688 mb->skip_visibility = 1;
3689 res = mono_mb_create_and_cache (cache, sig, mb, sig, sig->param_count + 16);
3697 * signature_dup_add_this:
3699 * Make a copy of @sig, adding an explicit this argument.
3701 static MonoMethodSignature*
3702 signature_dup_add_this (MonoMethodSignature *sig, MonoClass *klass)
3704 MonoMethodSignature *res;
3707 res = mono_metadata_signature_alloc (klass->image, sig->param_count + 1);
3708 memcpy (res, sig, sizeof (MonoMethodSignature));
3709 res->param_count = sig->param_count + 1;
3710 res->hasthis = FALSE;
3711 for (i = sig->param_count - 1; i >= 0; i --)
3712 res->params [i + 1] = sig->params [i];
3713 res->params [0] = &mono_ptr_class_get (&klass->byval_arg)->byval_arg;
3719 MonoMethodSignature *ctor_sig;
3720 MonoMethodSignature *sig;
3723 /* protected by the marshal lock, contains CtorSigPair pointers */
3724 static GSList *strsig_list = NULL;
3726 static MonoMethodSignature *
3727 lookup_string_ctor_signature (MonoMethodSignature *sig)
3729 MonoMethodSignature *callsig;
3733 mono_marshal_lock ();
3735 for (item = strsig_list; item; item = item->next) {
3737 /* mono_metadata_signature_equal () is safe to call with the marshal lock
3738 * because it is lock-free.
3740 if (mono_metadata_signature_equal (sig, cs->ctor_sig)) {
3745 mono_marshal_unlock ();
3749 static MonoMethodSignature *
3750 add_string_ctor_signature (MonoMethod *method)
3752 MonoMethodSignature *callsig;
3755 callsig = signature_dup (method->klass->image, mono_method_signature (method));
3756 callsig->ret = &mono_defaults.string_class->byval_arg;
3757 cs = g_new (CtorSigPair, 1);
3759 cs->ctor_sig = mono_method_signature (method);
3761 mono_marshal_lock ();
3762 strsig_list = g_slist_prepend (strsig_list, cs);
3763 mono_marshal_unlock ();
3768 get_runtime_invoke_type (MonoType *t)
3771 return &mono_defaults.int_class->byval_arg;
3775 return &mono_defaults.sbyte_class->byval_arg;
3777 return &mono_defaults.int16_class->byval_arg;
3779 return &mono_defaults.int32_class->byval_arg;
3781 return &mono_defaults.int64_class->byval_arg;
3782 case MONO_TYPE_BOOLEAN:
3783 return &mono_defaults.byte_class->byval_arg;
3784 case MONO_TYPE_CHAR:
3785 return &mono_defaults.int16_class->byval_arg;
3787 return &mono_defaults.int_class->byval_arg;
3788 case MONO_TYPE_VALUETYPE:
3791 if (MONO_TYPE_IS_REFERENCE (t))
3792 return &mono_defaults.object_class->byval_arg;
3798 * mono_marshal_get_runtime_invoke_sig:
3800 * Return a common signature used for sharing runtime invoke wrappers.
3802 static MonoMethodSignature*
3803 mono_marshal_get_runtime_invoke_sig (MonoMethodSignature *sig)
3805 MonoMethodSignature *res = mono_metadata_signature_dup (sig);
3808 res->ret = get_runtime_invoke_type (sig->ret);
3809 for (i = 0; i < res->param_count; ++i)
3810 res->params [i] = get_runtime_invoke_type (sig->params [i]);
3816 runtime_invoke_signature_equal (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
3818 /* Can't share wrappers which return a vtype since it needs to be boxed */
3819 if (sig1->ret != sig2->ret && !(MONO_TYPE_IS_REFERENCE (sig1->ret) && MONO_TYPE_IS_REFERENCE (sig2->ret)))
3822 return mono_metadata_signature_equal (sig1, sig2);
3826 * generates IL code for the runtime invoke function
3827 * MonoObject *runtime_invoke (MonoObject *this, void **params, MonoObject **exc, void* method)
3829 * we also catch exceptions if exc != null
3832 mono_marshal_get_runtime_invoke (MonoMethod *method)
3834 MonoMethodSignature *sig, *csig, *callsig;
3835 MonoExceptionClause *clause;
3836 MonoMethodBuilder *mb;
3837 GHashTable *cache = NULL;
3838 MonoClass *target_klass;
3839 MonoMethod *res = NULL;
3840 static MonoString *string_dummy = NULL;
3841 static MonoMethodSignature *cctor_signature = NULL;
3842 static MonoMethodSignature *finalize_signature = NULL;
3845 gboolean need_direct_wrapper = FALSE;
3846 int *tmp_nullable_locals;
3850 if (!cctor_signature) {
3851 cctor_signature = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3852 cctor_signature->ret = &mono_defaults.void_class->byval_arg;
3854 if (!finalize_signature) {
3855 finalize_signature = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3856 finalize_signature->ret = &mono_defaults.void_class->byval_arg;
3857 finalize_signature->hasthis = 1;
3861 * Use a separate cache indexed by methods to speed things up and to avoid the
3862 * boundless mempool growth caused by the signature_dup stuff below.
3864 cache = get_cache (&method->klass->image->runtime_invoke_direct_cache, mono_aligned_addr_hash, NULL);
3865 res = mono_marshal_find_in_cache (cache, method);
3869 if (method->klass->rank && (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
3870 (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
3872 * Array Get/Set/Address methods. The JIT implements them using inline code
3873 * so we need to create an invoke wrapper which calls the method directly.
3875 need_direct_wrapper = TRUE;
3878 if (method->string_ctor) {
3879 callsig = lookup_string_ctor_signature (mono_method_signature (method));
3881 callsig = add_string_ctor_signature (method);
3883 if (method->klass->valuetype && mono_method_signature (method)->hasthis) {
3885 * Valuetype methods receive a managed pointer as the this argument.
3886 * Create a new signature to reflect this.
3888 callsig = signature_dup_add_this (mono_method_signature (method), method->klass);
3890 if (method->dynamic)
3891 callsig = signature_dup (method->klass->image, mono_method_signature (method));
3893 callsig = mono_method_signature (method);
3897 /* Vtypes/nullables/Byrefs cause too many problems */
3898 for (i = 0; i < callsig->param_count; ++i) {
3899 if (MONO_TYPE_ISSTRUCT (callsig->params [i]) || callsig->params [i]->byref)
3900 need_direct_wrapper = TRUE;
3904 * We try to share runtime invoke wrappers between different methods but have to
3905 * be careful about methods whose klass has a type cctor, since putting the wrapper
3906 * into that klass would mean that calling a method of klass A might invoke the
3907 * type initializer of class B, or throw an exception if the type initializer
3908 * was called before and failed. See #349621 for an example.
3909 * We avoid that for mscorlib methods by putting every wrapper into the object class.
3911 if (method->klass->image == mono_defaults.corlib)
3912 target_klass = mono_defaults.object_class;
3914 /* Try to share wrappers for non-corlib methods with simple signatures */
3915 if (mono_metadata_signature_equal (callsig, cctor_signature)) {
3916 callsig = cctor_signature;
3917 target_klass = mono_defaults.object_class;
3918 } else if (mono_metadata_signature_equal (callsig, finalize_signature)) {
3919 callsig = finalize_signature;
3920 target_klass = mono_defaults.object_class;
3922 // FIXME: This breaks too many things
3924 if (mono_class_get_cctor (method->klass))
3925 need_direct_wrapper = TRUE;
3929 * Can't put these wrappers into object, since they reference non-corlib
3930 * metadata (callsig).
3932 target_klass = method->klass;
3936 if (need_direct_wrapper) {
3937 /* Already searched at the start */
3939 callsig = mono_marshal_get_runtime_invoke_sig (callsig);
3941 cache = get_cache (&target_klass->image->runtime_invoke_cache,
3942 (GHashFunc)mono_signature_hash,
3943 (GCompareFunc)runtime_invoke_signature_equal);
3945 /* from mono_marshal_find_in_cache */
3946 mono_marshal_lock ();
3947 res = g_hash_table_lookup (cache, callsig);
3948 mono_marshal_unlock ();
3955 // FIXME: When to free callsig ?
3958 /* to make it work with our special string constructors */
3959 if (!string_dummy) {
3960 MONO_GC_REGISTER_ROOT (string_dummy);
3961 string_dummy = mono_string_new_wrapper ("dummy");
3964 sig = mono_method_signature (method);
3966 csig = mono_metadata_signature_alloc (target_klass->image, 4);
3968 csig->ret = &mono_defaults.object_class->byval_arg;
3969 if (method->klass->valuetype && mono_method_signature (method)->hasthis)
3970 csig->params [0] = callsig->params [0];
3972 csig->params [0] = &mono_defaults.object_class->byval_arg;
3973 csig->params [1] = &mono_defaults.int_class->byval_arg;
3974 csig->params [2] = &mono_defaults.int_class->byval_arg;
3975 csig->params [3] = &mono_defaults.int_class->byval_arg;
3977 name = mono_signature_to_name (callsig, "runtime_invoke");
3978 mb = mono_mb_new (target_klass, name, MONO_WRAPPER_RUNTIME_INVOKE);
3981 /* allocate local 0 (object) tmp */
3982 mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
3983 /* allocate local 1 (object) exc */
3984 mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
3986 /* cond set *exc to null */
3987 mono_mb_emit_byte (mb, CEE_LDARG_2);
3988 mono_mb_emit_byte (mb, CEE_BRFALSE_S);
3989 mono_mb_emit_byte (mb, 3);
3990 mono_mb_emit_byte (mb, CEE_LDARG_2);
3991 mono_mb_emit_byte (mb, CEE_LDNULL);
3992 mono_mb_emit_byte (mb, CEE_STIND_REF);
3994 emit_thread_force_interrupt_checkpoint (mb);
3997 if (method->string_ctor) {
3998 mono_mb_emit_ptr (mb, string_dummy);
4000 mono_mb_emit_ldarg (mb, 0);
4004 tmp_nullable_locals = g_new0 (int, sig->param_count);
4006 for (i = 0; i < sig->param_count; i++) {
4007 MonoType *t = sig->params [i];
4010 mono_mb_emit_ldarg (mb, 1);
4012 mono_mb_emit_icon (mb, sizeof (gpointer) * i);
4013 mono_mb_emit_byte (mb, CEE_ADD);
4017 mono_mb_emit_byte (mb, CEE_LDIND_I);
4018 /* A Nullable<T> type don't have a boxed form, it's either null or a boxed T.
4019 * So to make this work we unbox it to a local variablee and push a reference to that.
4021 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
4022 tmp_nullable_locals [i] = mono_mb_add_local (mb, &mono_class_from_mono_type (t)->byval_arg);
4024 mono_mb_emit_op (mb, CEE_UNBOX_ANY, mono_class_from_mono_type (t));
4025 mono_mb_emit_stloc (mb, tmp_nullable_locals [i]);
4026 mono_mb_emit_ldloc_addr (mb, tmp_nullable_locals [i]);
4031 type = sig->params [i]->type;
4035 case MONO_TYPE_BOOLEAN:
4039 case MONO_TYPE_CHAR:
4048 mono_mb_emit_byte (mb, CEE_LDIND_I);
4049 mono_mb_emit_byte (mb, mono_type_to_ldind (sig->params [i]));
4051 case MONO_TYPE_STRING:
4052 case MONO_TYPE_CLASS:
4053 case MONO_TYPE_ARRAY:
4055 case MONO_TYPE_SZARRAY:
4056 case MONO_TYPE_OBJECT:
4057 mono_mb_emit_byte (mb, mono_type_to_ldind (sig->params [i]));
4059 case MONO_TYPE_GENERICINST:
4060 if (!mono_type_generic_inst_is_valuetype (sig->params [i])) {
4061 mono_mb_emit_byte (mb, CEE_LDIND_I);
4066 case MONO_TYPE_VALUETYPE:
4067 if (type == MONO_TYPE_VALUETYPE && t->data.klass->enumtype) {
4068 type = mono_class_enum_basetype (t->data.klass)->type;
4071 mono_mb_emit_byte (mb, CEE_LDIND_I);
4072 if (mono_class_is_nullable (mono_class_from_mono_type (sig->params [i]))) {
4073 /* Need to convert a boxed vtype to an mp to a Nullable struct */
4074 mono_mb_emit_op (mb, CEE_UNBOX, mono_class_from_mono_type (sig->params [i]));
4075 mono_mb_emit_op (mb, CEE_LDOBJ, mono_class_from_mono_type (sig->params [i]));
4077 mono_mb_emit_op (mb, CEE_LDOBJ, mono_class_from_mono_type (sig->params [i]));
4081 g_assert_not_reached ();
4085 if (need_direct_wrapper) {
4086 mono_mb_emit_op (mb, CEE_CALL, method);
4088 mono_mb_emit_ldarg (mb, 3);
4089 mono_mb_emit_calli (mb, callsig);
4092 if (sig->ret->byref) {
4094 g_assert_not_reached ();
4098 switch (sig->ret->type) {
4099 case MONO_TYPE_VOID:
4100 if (!method->string_ctor)
4101 mono_mb_emit_byte (mb, CEE_LDNULL);
4103 case MONO_TYPE_BOOLEAN:
4104 case MONO_TYPE_CHAR:
4117 case MONO_TYPE_VALUETYPE:
4118 case MONO_TYPE_TYPEDBYREF:
4119 case MONO_TYPE_GENERICINST:
4120 /* box value types */
4121 mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (sig->ret));
4123 case MONO_TYPE_STRING:
4124 case MONO_TYPE_CLASS:
4125 case MONO_TYPE_ARRAY:
4126 case MONO_TYPE_SZARRAY:
4127 case MONO_TYPE_OBJECT:
4132 g_assert_not_reached ();
4135 mono_mb_emit_stloc (mb, 0);
4137 /* Convert back nullable-byref arguments */
4138 for (i = 0; i < sig->param_count; i++) {
4139 MonoType *t = sig->params [i];
4142 * Box the result and put it back into the array, the caller will have
4143 * to obtain it from there.
4145 if (t->byref && t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
4146 mono_mb_emit_ldarg (mb, 1);
4147 mono_mb_emit_icon (mb, sizeof (gpointer) * i);
4148 mono_mb_emit_byte (mb, CEE_ADD);
4150 mono_mb_emit_ldloc (mb, tmp_nullable_locals [i]);
4151 mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (t));
4153 mono_mb_emit_byte (mb, CEE_STIND_REF);
4157 pos = mono_mb_emit_branch (mb, CEE_LEAVE);
4159 clause = mono_image_alloc0 (target_klass->image, sizeof (MonoExceptionClause));
4160 clause->flags = MONO_EXCEPTION_CLAUSE_FILTER;
4161 clause->try_len = mono_mb_get_label (mb);
4164 clause->data.filter_offset = mono_mb_get_label (mb);
4166 mono_mb_emit_byte (mb, CEE_POP);
4167 mono_mb_emit_byte (mb, CEE_LDARG_2);
4168 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
4169 mono_mb_emit_byte (mb, CEE_PREFIX1);
4170 mono_mb_emit_byte (mb, CEE_CGT_UN);
4171 mono_mb_emit_byte (mb, CEE_PREFIX1);
4172 mono_mb_emit_byte (mb, CEE_ENDFILTER);
4174 clause->handler_offset = mono_mb_get_label (mb);
4177 /* store exception */
4178 mono_mb_emit_stloc (mb, 1);
4180 mono_mb_emit_byte (mb, CEE_LDARG_2);
4181 mono_mb_emit_ldloc (mb, 1);
4182 mono_mb_emit_byte (mb, CEE_STIND_REF);
4184 mono_mb_emit_byte (mb, CEE_LDNULL);
4185 mono_mb_emit_stloc (mb, 0);
4187 /* Check for the abort exception */
4188 mono_mb_emit_ldloc (mb, 1);
4189 mono_mb_emit_op (mb, CEE_ISINST, mono_defaults.threadabortexception_class);
4190 posna = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
4192 /* Delay the abort exception */
4193 mono_mb_emit_icall (mb, ves_icall_System_Threading_Thread_ResetAbort);
4195 mono_mb_patch_short_branch (mb, posna);
4196 mono_mb_emit_branch (mb, CEE_LEAVE);
4198 clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
4200 mono_mb_set_clauses (mb, 1, clause);
4203 mono_mb_patch_branch (mb, pos);
4204 mono_mb_emit_ldloc (mb, 0);
4205 mono_mb_emit_byte (mb, CEE_RET);
4207 if (need_direct_wrapper) {
4208 mb->skip_visibility = 1;
4209 res = mono_mb_create_and_cache (cache, method, mb, csig, sig->param_count + 16);
4211 /* taken from mono_mb_create_and_cache */
4212 mono_marshal_lock ();
4213 res = g_hash_table_lookup (cache, callsig);
4214 mono_marshal_unlock ();
4216 /* Somebody may have created it before us */
4219 newm = mono_mb_create_method (mb, csig, sig->param_count + 16);
4221 mono_marshal_lock ();
4222 res = g_hash_table_lookup (cache, callsig);
4225 g_hash_table_insert (cache, callsig, res);
4226 /* Can't insert it into wrapper_hash since the key is a signature */
4227 g_hash_table_insert (method->klass->image->runtime_invoke_direct_cache, method, res);
4229 mono_free_method (newm);
4231 mono_marshal_unlock ();
4234 /* end mono_mb_create_and_cache */
4243 * mono_marshal_get_static_rgctx_invoke:
4246 * Generates a wrapper for calling a generic shared method, either
4247 * static or generic. We need this for virtual generic method lookup
4248 * and ldftn when we do generic code sharing. Instead of producing
4249 * the address of the method we produce the address of a wrapper for
4250 * the method because the wrapper passes the (method) runtime generic
4251 * context argument which calli cannot do.
4254 mono_marshal_get_static_rgctx_invoke (MonoMethod *method)
4256 static gboolean inited = FALSE;
4257 static int num_wrappers = 0;
4259 MonoMethodBuilder *mb;
4261 MonoClass *target_klass = method->klass;
4262 MonoMethodSignature *sig = mono_method_signature (method);
4266 MonoImage *image = method->klass->image;
4268 cache = get_cache (&image->static_rgctx_invoke_cache, mono_aligned_addr_hash, NULL);
4269 if ((res = mono_marshal_find_in_cache (cache, method)))
4273 mono_counters_register ("Static rgctx invoke wrappers",
4274 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &num_wrappers);
4279 name = mono_signature_to_name (mono_method_signature (method), "static_rgctx_invoke");
4280 mb = mono_mb_new (target_klass, name, MONO_WRAPPER_STATIC_RGCTX_INVOKE);
4283 for (i = 0; i < sig->param_count + sig->hasthis; i++)
4284 mono_mb_emit_ldarg (mb, i);
4285 mono_mb_emit_op (mb, CEE_CALL, method);
4286 mono_mb_emit_byte (mb, CEE_RET);
4288 mb->skip_visibility = TRUE;
4289 res = mono_mb_create_and_cache (cache, method, mb, mono_method_signature (method),
4290 sig->param_count + sig->hasthis + 4);
4291 res->flags = method->flags;
4299 mono_mb_emit_auto_layout_exception (MonoMethodBuilder *mb, MonoClass *klass)
4301 char *msg = g_strdup_printf ("The type `%s.%s' layout needs to be Sequential or Explicit",
4302 klass->name_space, klass->name);
4304 mono_mb_emit_exception_marshal_directive (mb, msg);
4308 * mono_marshal_get_ldfld_remote_wrapper:
4309 * @klass: The return type
4311 * This method generates a wrapper for calling mono_load_remote_field_new.
4312 * The return type is ignored for now, as mono_load_remote_field_new () always
4313 * returns an object. In the future, to optimize some codepaths, we might
4314 * call a different function that takes a pointer to a valuetype, instead.
4317 mono_marshal_get_ldfld_remote_wrapper (MonoClass *klass)
4319 MonoMethodSignature *sig, *csig;
4320 MonoMethodBuilder *mb;
4322 static MonoMethod* cached = NULL;
4324 mono_marshal_lock ();
4326 mono_marshal_unlock ();
4329 mono_marshal_unlock ();
4331 mb = mono_mb_new_no_dup_name (mono_defaults.object_class, "__mono_load_remote_field_new_wrapper", MONO_WRAPPER_LDFLD_REMOTE);
4333 mb->method->save_lmf = 1;
4335 sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4336 sig->params [0] = &mono_defaults.object_class->byval_arg;
4337 sig->params [1] = &mono_defaults.int_class->byval_arg;
4338 sig->params [2] = &mono_defaults.int_class->byval_arg;
4339 sig->ret = &mono_defaults.object_class->byval_arg;
4341 mono_mb_emit_ldarg (mb, 0);
4342 mono_mb_emit_ldarg (mb, 1);
4343 mono_mb_emit_ldarg (mb, 2);
4345 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4346 csig->params [0] = &mono_defaults.object_class->byval_arg;
4347 csig->params [1] = &mono_defaults.int_class->byval_arg;
4348 csig->params [2] = &mono_defaults.int_class->byval_arg;
4349 csig->ret = &mono_defaults.object_class->byval_arg;
4352 mono_mb_emit_native_call (mb, csig, mono_load_remote_field_new);
4353 emit_thread_interrupt_checkpoint (mb);
4355 mono_mb_emit_byte (mb, CEE_RET);
4357 mono_marshal_lock ();
4359 mono_marshal_unlock ();
4362 newm = mono_mb_create_method (mb, sig, 4);
4363 mono_marshal_lock ();
4368 mono_marshal_unlock ();
4370 mono_marshal_unlock ();
4371 mono_free_method (newm);
4380 * mono_marshal_get_ldfld_wrapper:
4381 * @type: the type of the field
4383 * This method generates a function which can be use to load a field with type
4384 * @type from an object. The generated function has the following signature:
4385 * <@type> ldfld_wrapper (MonoObject *this, MonoClass *class, MonoClassField *field, int offset)
4388 mono_marshal_get_ldfld_wrapper (MonoType *type)
4390 MonoMethodSignature *sig;
4391 MonoMethodBuilder *mb;
4396 int t, pos0, pos1 = 0;
4398 type = mono_type_get_underlying_type (type);
4403 if (type->type == MONO_TYPE_SZARRAY) {
4404 klass = mono_defaults.array_class;
4405 } else if (type->type == MONO_TYPE_VALUETYPE) {
4406 klass = type->data.klass;
4407 } else if (t == MONO_TYPE_OBJECT || t == MONO_TYPE_CLASS || t == MONO_TYPE_STRING) {
4408 klass = mono_defaults.object_class;
4409 } else if (t == MONO_TYPE_PTR || t == MONO_TYPE_FNPTR) {
4410 klass = mono_defaults.int_class;
4411 } else if (t == MONO_TYPE_GENERICINST) {
4412 if (mono_type_generic_inst_is_valuetype (type))
4413 klass = mono_class_from_mono_type (type);
4415 klass = mono_defaults.object_class;
4417 klass = mono_class_from_mono_type (type);
4420 klass = mono_defaults.int_class;
4423 cache = get_cache (&klass->image->ldfld_wrapper_cache, mono_aligned_addr_hash, NULL);
4424 if ((res = mono_marshal_find_in_cache (cache, klass)))
4427 /* we add the %p pointer value of klass because class names are not unique */
4428 name = g_strdup_printf ("__ldfld_wrapper_%p_%s.%s", klass, klass->name_space, klass->name);
4429 mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_LDFLD);
4432 sig = mono_metadata_signature_alloc (mono_defaults.corlib, 4);
4433 sig->params [0] = &mono_defaults.object_class->byval_arg;
4434 sig->params [1] = &mono_defaults.int_class->byval_arg;
4435 sig->params [2] = &mono_defaults.int_class->byval_arg;
4436 sig->params [3] = &mono_defaults.int_class->byval_arg;
4437 sig->ret = &klass->byval_arg;
4439 mono_mb_emit_ldarg (mb, 0);
4440 pos0 = mono_mb_emit_proxy_check (mb, CEE_BNE_UN);
4442 mono_mb_emit_ldarg (mb, 0);
4443 mono_mb_emit_ldarg (mb, 1);
4444 mono_mb_emit_ldarg (mb, 2);
4446 mono_mb_emit_managed_call (mb, mono_marshal_get_ldfld_remote_wrapper (klass), NULL);
4449 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4450 csig->params [0] = &mono_defaults.object_class->byval_arg;
4451 csig->params [1] = &mono_defaults.int_class->byval_arg;
4452 csig->params [2] = &mono_defaults.int_class->byval_arg;
4453 csig->ret = &klass->this_arg;
4456 mono_mb_emit_native_call (mb, csig, mono_load_remote_field_new);
4457 emit_thread_interrupt_checkpoint (mb);
4460 if (klass->valuetype) {
4461 mono_mb_emit_op (mb, CEE_UNBOX, klass);
4462 pos1 = mono_mb_emit_branch (mb, CEE_BR);
4464 mono_mb_emit_byte (mb, CEE_RET);
4468 mono_mb_patch_branch (mb, pos0);
4470 mono_mb_emit_ldarg (mb, 0);
4471 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
4472 mono_mb_emit_byte (mb, CEE_MONO_OBJADDR);
4473 mono_mb_emit_ldarg (mb, 3);
4474 mono_mb_emit_byte (mb, CEE_ADD);
4476 if (klass->valuetype)
4477 mono_mb_patch_branch (mb, pos1);
4482 case MONO_TYPE_BOOLEAN:
4483 case MONO_TYPE_CHAR:
4492 case MONO_TYPE_ARRAY:
4493 case MONO_TYPE_SZARRAY:
4494 case MONO_TYPE_OBJECT:
4495 case MONO_TYPE_CLASS:
4496 case MONO_TYPE_STRING:
4500 case MONO_TYPE_FNPTR:
4501 mono_mb_emit_byte (mb, mono_type_to_ldind (type));
4503 case MONO_TYPE_VALUETYPE:
4504 g_assert (!klass->enumtype);
4505 mono_mb_emit_op (mb, CEE_LDOBJ, klass);
4507 case MONO_TYPE_GENERICINST:
4508 if (mono_type_generic_inst_is_valuetype (type)) {
4509 mono_mb_emit_op (mb, CEE_LDOBJ, klass);
4511 mono_mb_emit_byte (mb, CEE_LDIND_REF);
4515 g_warning ("type %x not implemented", type->type);
4516 g_assert_not_reached ();
4519 mono_mb_emit_byte (mb, CEE_RET);
4521 res = mono_mb_create_and_cache (cache, klass,
4522 mb, sig, sig->param_count + 16);
4529 * mono_marshal_get_ldflda_wrapper:
4530 * @type: the type of the field
4532 * This method generates a function which can be used to load a field address
4533 * from an object. The generated function has the following signature:
4534 * gpointer ldflda_wrapper (MonoObject *this, MonoClass *class, MonoClassField *field, int offset);
4537 mono_marshal_get_ldflda_wrapper (MonoType *type)
4539 MonoMethodSignature *sig;
4540 MonoMethodBuilder *mb;
4545 int t, pos0, pos1, pos2, pos3;
4547 type = mono_type_get_underlying_type (type);
4551 if (type->type == MONO_TYPE_SZARRAY) {
4552 klass = mono_defaults.array_class;
4553 } else if (type->type == MONO_TYPE_VALUETYPE) {
4554 klass = type->data.klass;
4555 } else if (t == MONO_TYPE_OBJECT || t == MONO_TYPE_CLASS || t == MONO_TYPE_STRING ||
4556 t == MONO_TYPE_CLASS) {
4557 klass = mono_defaults.object_class;
4558 } else if (t == MONO_TYPE_PTR || t == MONO_TYPE_FNPTR) {
4559 klass = mono_defaults.int_class;
4560 } else if (t == MONO_TYPE_GENERICINST) {
4561 if (mono_type_generic_inst_is_valuetype (type))
4562 klass = mono_class_from_mono_type (type);
4564 klass = mono_defaults.object_class;
4566 klass = mono_class_from_mono_type (type);
4569 klass = mono_defaults.int_class;
4572 cache = get_cache (&klass->image->ldflda_wrapper_cache, mono_aligned_addr_hash, NULL);
4573 if ((res = mono_marshal_find_in_cache (cache, klass)))
4576 /* we add the %p pointer value of klass because class names are not unique */
4577 name = g_strdup_printf ("__ldflda_wrapper_%p_%s.%s", klass, klass->name_space, klass->name);
4578 mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_LDFLDA);
4581 sig = mono_metadata_signature_alloc (mono_defaults.corlib, 4);
4582 sig->params [0] = &mono_defaults.object_class->byval_arg;
4583 sig->params [1] = &mono_defaults.int_class->byval_arg;
4584 sig->params [2] = &mono_defaults.int_class->byval_arg;
4585 sig->params [3] = &mono_defaults.int_class->byval_arg;
4586 sig->ret = &mono_defaults.int_class->byval_arg;
4588 /* if typeof (this) != transparent_proxy goto pos0 */
4589 mono_mb_emit_ldarg (mb, 0);
4590 pos0 = mono_mb_emit_proxy_check (mb, CEE_BNE_UN);
4592 /* if same_appdomain goto pos1 */
4593 mono_mb_emit_ldarg (mb, 0);
4594 pos1 = mono_mb_emit_xdomain_check (mb, CEE_BEQ);
4596 mono_mb_emit_exception_full (mb, "System", "InvalidOperationException", "Attempt to load field address from object in another appdomain.");
4598 /* same app domain */
4599 mono_mb_patch_branch (mb, pos1);
4601 /* if typeof (this) != contextbound goto pos2 */
4602 mono_mb_emit_ldarg (mb, 0);
4603 pos2 = mono_mb_emit_contextbound_check (mb, CEE_BEQ);
4605 /* if this->rp->context == mono_context_get goto pos3 */
4606 mono_mb_emit_ldarg (mb, 0);
4607 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoTransparentProxy, rp));
4608 mono_mb_emit_byte (mb, CEE_LDIND_REF);
4609 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoRealProxy, context));
4610 mono_mb_emit_byte (mb, CEE_LDIND_REF);
4611 mono_mb_emit_icall (mb, mono_context_get);
4612 pos3 = mono_mb_emit_branch (mb, CEE_BEQ);
4614 mono_mb_emit_exception_full (mb, "System", "InvalidOperationException", "Attempt to load field address from object in another context.");
4616 mono_mb_patch_branch (mb, pos2);
4617 mono_mb_patch_branch (mb, pos3);
4619 /* return the address of the field from this->rp->unwrapped_server */
4620 mono_mb_emit_ldarg (mb, 0);
4621 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoTransparentProxy, rp));
4622 mono_mb_emit_byte (mb, CEE_LDIND_REF);
4623 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoRealProxy, unwrapped_server));
4624 mono_mb_emit_byte (mb, CEE_LDIND_REF);
4625 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
4626 mono_mb_emit_byte (mb, CEE_MONO_OBJADDR);
4627 mono_mb_emit_ldarg (mb, 3);
4628 mono_mb_emit_byte (mb, CEE_ADD);
4629 mono_mb_emit_byte (mb, CEE_RET);
4631 /* not a proxy: return the address of the field directly */
4632 mono_mb_patch_branch (mb, pos0);
4634 mono_mb_emit_ldarg (mb, 0);
4635 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
4636 mono_mb_emit_byte (mb, CEE_MONO_OBJADDR);
4637 mono_mb_emit_ldarg (mb, 3);
4638 mono_mb_emit_byte (mb, CEE_ADD);
4640 mono_mb_emit_byte (mb, CEE_RET);
4642 res = mono_mb_create_and_cache (cache, klass,
4643 mb, sig, sig->param_count + 16);
4650 * mono_marshal_get_stfld_remote_wrapper:
4651 * klass: The type of the field
4653 * This function generates a wrapper for calling mono_store_remote_field_new
4654 * with the appropriate signature.
4655 * Similarly to mono_marshal_get_ldfld_remote_wrapper () this doesn't depend on the
4656 * klass argument anymore.
4659 mono_marshal_get_stfld_remote_wrapper (MonoClass *klass)
4661 MonoMethodSignature *sig, *csig;
4662 MonoMethodBuilder *mb;
4664 static MonoMethod *cached = NULL;
4666 mono_marshal_lock ();
4668 mono_marshal_unlock ();
4671 mono_marshal_unlock ();
4673 mb = mono_mb_new_no_dup_name (mono_defaults.object_class, "__mono_store_remote_field_new_wrapper", MONO_WRAPPER_STFLD_REMOTE);
4675 mb->method->save_lmf = 1;
4677 sig = mono_metadata_signature_alloc (mono_defaults.corlib, 4);
4678 sig->params [0] = &mono_defaults.object_class->byval_arg;
4679 sig->params [1] = &mono_defaults.int_class->byval_arg;
4680 sig->params [2] = &mono_defaults.int_class->byval_arg;
4681 sig->params [3] = &mono_defaults.object_class->byval_arg;
4682 sig->ret = &mono_defaults.void_class->byval_arg;
4684 mono_mb_emit_ldarg (mb, 0);
4685 mono_mb_emit_ldarg (mb, 1);
4686 mono_mb_emit_ldarg (mb, 2);
4687 mono_mb_emit_ldarg (mb, 3);
4689 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 4);
4690 csig->params [0] = &mono_defaults.object_class->byval_arg;
4691 csig->params [1] = &mono_defaults.int_class->byval_arg;
4692 csig->params [2] = &mono_defaults.int_class->byval_arg;
4693 csig->params [3] = &mono_defaults.object_class->byval_arg;
4694 csig->ret = &mono_defaults.void_class->byval_arg;
4697 mono_mb_emit_native_call (mb, csig, mono_store_remote_field_new);
4698 emit_thread_interrupt_checkpoint (mb);
4700 mono_mb_emit_byte (mb, CEE_RET);
4702 mono_marshal_lock ();
4704 mono_marshal_unlock ();
4707 newm = mono_mb_create_method (mb, sig, 6);
4708 mono_marshal_lock ();
4713 mono_marshal_unlock ();
4715 mono_marshal_unlock ();
4716 mono_free_method (newm);
4725 * mono_marshal_get_stfld_wrapper:
4726 * @type: the type of the field
4728 * This method generates a function which can be use to store a field with type
4729 * @type. The generated function has the following signature:
4730 * void stfld_wrapper (MonoObject *this, MonoClass *class, MonoClassField *field, int offset, <@type> val)
4733 mono_marshal_get_stfld_wrapper (MonoType *type)
4735 MonoMethodSignature *sig;
4736 MonoMethodBuilder *mb;
4743 type = mono_type_get_underlying_type (type);
4747 if (type->type == MONO_TYPE_SZARRAY) {
4748 klass = mono_defaults.array_class;
4749 } else if (type->type == MONO_TYPE_VALUETYPE) {
4750 klass = type->data.klass;
4751 } else if (t == MONO_TYPE_OBJECT || t == MONO_TYPE_CLASS || t == MONO_TYPE_STRING) {
4752 klass = mono_defaults.object_class;
4753 } else if (t == MONO_TYPE_PTR || t == MONO_TYPE_FNPTR) {
4754 klass = mono_defaults.int_class;
4755 } else if (t == MONO_TYPE_GENERICINST) {
4756 if (mono_type_generic_inst_is_valuetype (type))
4757 klass = mono_class_from_mono_type (type);
4759 klass = mono_defaults.object_class;
4761 klass = mono_class_from_mono_type (type);
4764 klass = mono_defaults.int_class;
4767 cache = get_cache (&klass->image->stfld_wrapper_cache, mono_aligned_addr_hash, NULL);
4768 if ((res = mono_marshal_find_in_cache (cache, klass)))
4771 /* we add the %p pointer value of klass because class names are not unique */
4772 name = g_strdup_printf ("__stfld_wrapper_%p_%s.%s", klass, klass->name_space, klass->name);
4773 mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_STFLD);
4776 sig = mono_metadata_signature_alloc (mono_defaults.corlib, 5);
4777 sig->params [0] = &mono_defaults.object_class->byval_arg;
4778 sig->params [1] = &mono_defaults.int_class->byval_arg;
4779 sig->params [2] = &mono_defaults.int_class->byval_arg;
4780 sig->params [3] = &mono_defaults.int_class->byval_arg;
4781 sig->params [4] = &klass->byval_arg;
4782 sig->ret = &mono_defaults.void_class->byval_arg;
4784 mono_mb_emit_ldarg (mb, 0);
4785 pos = mono_mb_emit_proxy_check (mb, CEE_BNE_UN);
4787 mono_mb_emit_ldarg (mb, 0);
4788 mono_mb_emit_ldarg (mb, 1);
4789 mono_mb_emit_ldarg (mb, 2);
4790 mono_mb_emit_ldarg (mb, 4);
4791 if (klass->valuetype)
4792 mono_mb_emit_op (mb, CEE_BOX, klass);
4794 mono_mb_emit_managed_call (mb, mono_marshal_get_stfld_remote_wrapper (klass), NULL);
4796 mono_mb_emit_byte (mb, CEE_RET);
4798 mono_mb_patch_branch (mb, pos);
4800 mono_mb_emit_ldarg (mb, 0);
4801 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
4802 mono_mb_emit_byte (mb, CEE_MONO_OBJADDR);
4803 mono_mb_emit_ldarg (mb, 3);
4804 mono_mb_emit_byte (mb, CEE_ADD);
4805 mono_mb_emit_ldarg (mb, 4);
4810 case MONO_TYPE_BOOLEAN:
4811 case MONO_TYPE_CHAR:
4820 case MONO_TYPE_ARRAY:
4821 case MONO_TYPE_SZARRAY:
4822 case MONO_TYPE_OBJECT:
4823 case MONO_TYPE_CLASS:
4824 case MONO_TYPE_STRING:
4828 case MONO_TYPE_FNPTR:
4829 mono_mb_emit_byte (mb, mono_type_to_stind (type));
4831 case MONO_TYPE_VALUETYPE:
4832 g_assert (!klass->enumtype);
4833 mono_mb_emit_op (mb, CEE_STOBJ, klass);
4835 case MONO_TYPE_GENERICINST:
4836 mono_mb_emit_op (mb, CEE_STOBJ, klass);
4839 g_warning ("type %x not implemented", type->type);
4840 g_assert_not_reached ();
4843 mono_mb_emit_byte (mb, CEE_RET);
4845 res = mono_mb_create_and_cache (cache, klass,
4846 mb, sig, sig->param_count + 16);
4853 * generates IL code for the icall wrapper (the generated method
4854 * calls the unmanaged code in func)
4857 mono_marshal_get_icall_wrapper (MonoMethodSignature *sig, const char *name, gconstpointer func, gboolean check_exceptions)
4859 MonoMethodSignature *csig;
4860 MonoMethodBuilder *mb;
4864 g_assert (sig->pinvoke);
4866 mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
4868 mb->method->save_lmf = 1;
4870 /* we copy the signature, so that we can modify it */
4873 mono_mb_emit_byte (mb, CEE_LDARG_0);
4875 for (i = 0; i < sig->param_count; i++)
4876 mono_mb_emit_ldarg (mb, i + sig->hasthis);
4878 mono_mb_emit_native_call (mb, sig, (gpointer) func);
4879 if (check_exceptions)
4880 emit_thread_interrupt_checkpoint (mb);
4881 mono_mb_emit_byte (mb, CEE_RET);
4883 csig = signature_dup (mono_defaults.corlib, sig);
4885 if (csig->call_convention == MONO_CALL_VARARG)
4886 csig->call_convention = 0;
4888 res = mono_mb_create_method (mb, csig, csig->param_count + 16);
4895 emit_marshal_custom (EmitMarshalContext *m, int argnum, MonoType *t,
4896 MonoMarshalSpec *spec,
4897 int conv_arg, MonoType **conv_arg_type,
4898 MarshalAction action)
4902 static MonoClass *ICustomMarshaler = NULL;
4903 static MonoMethod *cleanup_native, *cleanup_managed;
4904 static MonoMethod *marshal_managed_to_native, *marshal_native_to_managed;
4905 MonoMethod *get_instance;
4906 MonoMethodBuilder *mb = m->mb;
4907 char *exception_msg = NULL;
4911 if (!ICustomMarshaler) {
4912 ICustomMarshaler = mono_class_from_name (mono_defaults.corlib, "System.Runtime.InteropServices", "ICustomMarshaler");
4913 g_assert (ICustomMarshaler);
4915 cleanup_native = mono_class_get_method_from_name (ICustomMarshaler, "CleanUpNativeData", 1);
4916 g_assert (cleanup_native);
4917 cleanup_managed = mono_class_get_method_from_name (ICustomMarshaler, "CleanUpManagedData", 1);
4918 g_assert (cleanup_managed);
4919 marshal_managed_to_native = mono_class_get_method_from_name (ICustomMarshaler, "MarshalManagedToNative", 1);
4920 g_assert (marshal_managed_to_native);
4921 marshal_native_to_managed = mono_class_get_method_from_name (ICustomMarshaler, "MarshalNativeToManaged", 1);
4922 g_assert (marshal_native_to_managed);
4925 mtype = mono_reflection_type_from_name (spec->data.custom_data.custom_name, m->image);
4926 g_assert (mtype != NULL);
4927 mklass = mono_class_from_mono_type (mtype);
4928 g_assert (mklass != NULL);
4930 if (!mono_class_is_assignable_from (ICustomMarshaler, mklass))
4931 exception_msg = g_strdup_printf ("Custom marshaler '%s' does not implement the ICustomMarshaler interface.", mklass->name);
4933 get_instance = mono_class_get_method_from_name_flags (mklass, "GetInstance", 1, METHOD_ATTRIBUTE_STATIC);
4935 MonoMethodSignature *get_sig = mono_method_signature (get_instance);
4936 if ((get_sig->ret->type != MONO_TYPE_CLASS) ||
4937 (mono_class_from_mono_type (get_sig->ret) != ICustomMarshaler) ||
4938 (get_sig->params [0]->type != MONO_TYPE_STRING))
4939 get_instance = NULL;
4943 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);
4945 /* Throw exception and emit compensation code if neccesary */
4946 if (exception_msg) {
4948 case MARSHAL_ACTION_CONV_IN:
4949 case MARSHAL_ACTION_CONV_RESULT:
4950 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
4951 if ((action == MARSHAL_ACTION_CONV_RESULT) || (action == MARSHAL_ACTION_MANAGED_CONV_RESULT))
4952 mono_mb_emit_byte (mb, CEE_POP);
4954 mono_mb_emit_exception_full (mb, "System", "ApplicationException", exception_msg);
4955 g_free (exception_msg);
4958 case MARSHAL_ACTION_PUSH:
4959 mono_mb_emit_byte (mb, CEE_LDNULL);
4967 /* FIXME: MS.NET seems to create one instance for each klass + cookie pair */
4968 /* FIXME: MS.NET throws an exception if GetInstance returns null */
4971 case MARSHAL_ACTION_CONV_IN:
4973 case MONO_TYPE_CLASS:
4974 case MONO_TYPE_OBJECT:
4975 case MONO_TYPE_STRING:
4976 case MONO_TYPE_ARRAY:
4977 case MONO_TYPE_SZARRAY:
4978 case MONO_TYPE_VALUETYPE:
4982 g_warning ("custom marshalling of type %x is currently not supported", t->type);
4983 g_assert_not_reached ();
4987 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
4989 mono_mb_emit_byte (mb, CEE_LDNULL);
4990 mono_mb_emit_stloc (mb, conv_arg);
4992 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT))
4995 /* Minic MS.NET behavior */
4996 if (!t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT) && !(t->attrs & PARAM_ATTRIBUTE_IN))
4999 /* Check for null */
5000 mono_mb_emit_ldarg (mb, argnum);
5002 mono_mb_emit_byte (mb, CEE_LDIND_I);
5003 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
5005 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
5007 mono_mb_emit_op (mb, CEE_CALL, get_instance);
5009 mono_mb_emit_ldarg (mb, argnum);
5011 mono_mb_emit_byte (mb, CEE_LDIND_REF);
5013 if (t->type == MONO_TYPE_VALUETYPE) {
5015 * Since we can't determine the type of the argument, we
5016 * will assume the unmanaged function takes a pointer.
5018 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5020 mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (t));
5023 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_managed_to_native);
5024 mono_mb_emit_stloc (mb, conv_arg);
5026 mono_mb_patch_branch (mb, pos2);
5029 case MARSHAL_ACTION_CONV_OUT:
5030 /* Check for null */
5031 mono_mb_emit_ldloc (mb, conv_arg);
5032 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
5035 mono_mb_emit_ldarg (mb, argnum);
5037 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
5039 mono_mb_emit_op (mb, CEE_CALL, get_instance);
5041 mono_mb_emit_ldloc (mb, conv_arg);
5042 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
5043 mono_mb_emit_byte (mb, CEE_STIND_REF);
5044 } else if (t->attrs & PARAM_ATTRIBUTE_OUT) {
5045 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
5047 mono_mb_emit_op (mb, CEE_CALL, get_instance);
5049 mono_mb_emit_ldloc (mb, conv_arg);
5050 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
5052 /* We have nowhere to store the result */
5053 mono_mb_emit_byte (mb, CEE_POP);
5056 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
5058 mono_mb_emit_op (mb, CEE_CALL, get_instance);
5060 mono_mb_emit_ldloc (mb, conv_arg);
5062 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_native);
5064 mono_mb_patch_branch (mb, pos2);
5067 case MARSHAL_ACTION_PUSH:
5069 mono_mb_emit_ldloc_addr (mb, conv_arg);
5071 mono_mb_emit_ldloc (mb, conv_arg);
5074 case MARSHAL_ACTION_CONV_RESULT:
5075 loc1 = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5077 mono_mb_emit_stloc (mb, 3);
5079 mono_mb_emit_ldloc (mb, 3);
5080 mono_mb_emit_stloc (mb, loc1);
5082 /* Check for null */
5083 mono_mb_emit_ldloc (mb, 3);
5084 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
5086 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
5088 mono_mb_emit_op (mb, CEE_CALL, get_instance);
5089 mono_mb_emit_byte (mb, CEE_DUP);
5091 mono_mb_emit_ldloc (mb, 3);
5092 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
5093 mono_mb_emit_stloc (mb, 3);
5095 mono_mb_emit_ldloc (mb, loc1);
5096 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_native);
5098 mono_mb_patch_branch (mb, pos2);
5101 case MARSHAL_ACTION_MANAGED_CONV_IN:
5102 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
5104 mono_mb_emit_byte (mb, CEE_LDNULL);
5105 mono_mb_emit_stloc (mb, conv_arg);
5107 if (t->byref && t->attrs & PARAM_ATTRIBUTE_OUT)
5110 /* Check for null */
5111 mono_mb_emit_ldarg (mb, argnum);
5113 mono_mb_emit_byte (mb, CEE_LDIND_I);
5114 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
5116 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
5117 mono_mb_emit_op (mb, CEE_CALL, get_instance);
5119 mono_mb_emit_ldarg (mb, argnum);
5121 mono_mb_emit_byte (mb, CEE_LDIND_I);
5123 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
5124 mono_mb_emit_stloc (mb, conv_arg);
5126 mono_mb_patch_branch (mb, pos2);
5129 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5130 g_assert (!t->byref);
5132 loc1 = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
5134 mono_mb_emit_stloc (mb, 3);
5136 mono_mb_emit_ldloc (mb, 3);
5137 mono_mb_emit_stloc (mb, loc1);
5139 /* Check for null */
5140 mono_mb_emit_ldloc (mb, 3);
5141 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
5143 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
5144 mono_mb_emit_op (mb, CEE_CALL, get_instance);
5145 mono_mb_emit_byte (mb, CEE_DUP);
5147 mono_mb_emit_ldloc (mb, 3);
5148 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_managed_to_native);
5149 mono_mb_emit_stloc (mb, 3);
5151 mono_mb_emit_ldloc (mb, loc1);
5152 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_managed);
5154 mono_mb_patch_branch (mb, pos2);
5157 case MARSHAL_ACTION_MANAGED_CONV_OUT:
5159 /* Check for null */
5160 mono_mb_emit_ldloc (mb, conv_arg);
5161 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
5164 mono_mb_emit_ldarg (mb, argnum);
5166 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
5168 mono_mb_emit_op (mb, CEE_CALL, get_instance);
5170 mono_mb_emit_ldloc (mb, conv_arg);
5171 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_managed_to_native);
5172 mono_mb_emit_byte (mb, CEE_STIND_I);
5175 /* Call CleanUpManagedData */
5176 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
5178 mono_mb_emit_op (mb, CEE_CALL, get_instance);
5180 mono_mb_emit_ldloc (mb, conv_arg);
5181 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_managed);
5183 mono_mb_patch_branch (mb, pos2);
5187 g_assert_not_reached ();
5194 emit_marshal_asany (EmitMarshalContext *m, int argnum, MonoType *t,
5195 MonoMarshalSpec *spec,
5196 int conv_arg, MonoType **conv_arg_type,
5197 MarshalAction action)
5199 MonoMethodBuilder *mb = m->mb;
5202 case MARSHAL_ACTION_CONV_IN: {
5203 MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, NULL);
5205 g_assert (t->type == MONO_TYPE_OBJECT);
5206 g_assert (!t->byref);
5208 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5209 mono_mb_emit_ldarg (mb, argnum);
5210 mono_mb_emit_icon (mb, encoding);
5211 mono_mb_emit_icon (mb, t->attrs);
5212 mono_mb_emit_icall (mb, mono_marshal_asany);
5213 mono_mb_emit_stloc (mb, conv_arg);
5217 case MARSHAL_ACTION_PUSH:
5218 mono_mb_emit_ldloc (mb, conv_arg);
5221 case MARSHAL_ACTION_CONV_OUT: {
5222 MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, NULL);
5224 mono_mb_emit_ldarg (mb, argnum);
5225 mono_mb_emit_ldloc (mb, conv_arg);
5226 mono_mb_emit_icon (mb, encoding);
5227 mono_mb_emit_icon (mb, t->attrs);
5228 mono_mb_emit_icall (mb, mono_marshal_free_asany);
5233 g_assert_not_reached ();
5240 emit_marshal_vtype (EmitMarshalContext *m, int argnum, MonoType *t,
5241 MonoMarshalSpec *spec,
5242 int conv_arg, MonoType **conv_arg_type,
5243 MarshalAction action)
5245 MonoMethodBuilder *mb = m->mb;
5249 klass = mono_class_from_mono_type (t);
5252 case MARSHAL_ACTION_CONV_IN:
5253 if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
5254 klass->blittable || klass->enumtype)
5257 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5259 /* store the address of the source into local variable 0 */
5261 mono_mb_emit_ldarg (mb, argnum);
5263 mono_mb_emit_ldarg_addr (mb, argnum);
5265 mono_mb_emit_stloc (mb, 0);
5267 /* allocate space for the native struct and
5268 * store the address into local variable 1 (dest) */
5269 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
5270 mono_mb_emit_byte (mb, CEE_PREFIX1);
5271 mono_mb_emit_byte (mb, CEE_LOCALLOC);
5272 mono_mb_emit_stloc (mb, conv_arg);
5275 mono_mb_emit_ldloc (mb, 0);
5276 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5279 if (!(t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && (t->attrs & PARAM_ATTRIBUTE_OUT))) {
5281 mono_mb_emit_ldloc (mb, conv_arg);
5282 mono_mb_emit_stloc (mb, 1);
5284 /* emit valuetype conversion code */
5285 emit_struct_conv (mb, klass, FALSE);
5289 mono_mb_patch_branch (mb, pos);
5292 case MARSHAL_ACTION_PUSH:
5293 if (spec && spec->native == MONO_NATIVE_LPSTRUCT) {
5295 g_assert (!t->byref);
5297 /* Have to change the signature since the vtype is passed byref */
5298 m->csig->params [argnum - m->csig->hasthis] = &mono_defaults.int_class->byval_arg;
5300 if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
5301 klass->blittable || klass->enumtype)
5302 mono_mb_emit_ldarg_addr (mb, argnum);
5304 mono_mb_emit_ldloc (mb, conv_arg);
5308 if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
5309 klass->blittable || klass->enumtype) {
5310 mono_mb_emit_ldarg (mb, argnum);
5313 mono_mb_emit_ldloc (mb, conv_arg);
5315 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5316 mono_mb_emit_op (mb, CEE_MONO_LDNATIVEOBJ, klass);
5320 case MARSHAL_ACTION_CONV_OUT:
5321 if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
5322 klass->blittable || klass->enumtype)
5326 /* dst = argument */
5327 mono_mb_emit_ldarg (mb, argnum);
5328 mono_mb_emit_stloc (mb, 1);
5330 mono_mb_emit_ldloc (mb, 1);
5331 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5333 if (!((t->attrs & PARAM_ATTRIBUTE_IN) && !(t->attrs & PARAM_ATTRIBUTE_OUT))) {
5334 /* src = tmp_locals [i] */
5335 mono_mb_emit_ldloc (mb, conv_arg);
5336 mono_mb_emit_stloc (mb, 0);
5338 /* emit valuetype conversion code */
5339 emit_struct_conv (mb, klass, TRUE);
5343 emit_struct_free (mb, klass, conv_arg);
5346 mono_mb_patch_branch (mb, pos);
5349 case MARSHAL_ACTION_CONV_RESULT:
5350 if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
5352 mono_mb_emit_stloc (mb, 3);
5355 /* load pointer to returned value type */
5356 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5357 mono_mb_emit_byte (mb, CEE_MONO_VTADDR);
5358 /* store the address of the source into local variable 0 */
5359 mono_mb_emit_stloc (mb, 0);
5361 mono_mb_emit_ldloc_addr (mb, 3);
5362 mono_mb_emit_stloc (mb, 1);
5364 /* emit valuetype conversion code */
5365 emit_struct_conv (mb, klass, TRUE);
5368 case MARSHAL_ACTION_MANAGED_CONV_IN:
5369 if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
5370 klass->blittable || klass->enumtype) {
5375 conv_arg = mono_mb_add_local (mb, &klass->byval_arg);
5377 if (t->attrs & PARAM_ATTRIBUTE_OUT)
5381 mono_mb_emit_ldarg (mb, argnum);
5383 mono_mb_emit_ldarg_addr (mb, argnum);
5384 mono_mb_emit_stloc (mb, 0);
5387 mono_mb_emit_ldloc (mb, 0);
5388 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5391 mono_mb_emit_ldloc_addr (mb, conv_arg);
5392 mono_mb_emit_stloc (mb, 1);
5394 /* emit valuetype conversion code */
5395 emit_struct_conv (mb, klass, TRUE);
5398 mono_mb_patch_branch (mb, pos);
5401 case MARSHAL_ACTION_MANAGED_CONV_OUT:
5402 if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
5403 klass->blittable || klass->enumtype) {
5407 /* Check for null */
5408 mono_mb_emit_ldarg (mb, argnum);
5409 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
5412 mono_mb_emit_ldloc_addr (mb, conv_arg);
5413 mono_mb_emit_stloc (mb, 0);
5416 mono_mb_emit_ldarg (mb, argnum);
5417 mono_mb_emit_stloc (mb, 1);
5419 /* emit valuetype conversion code */
5420 emit_struct_conv (mb, klass, FALSE);
5422 mono_mb_patch_branch (mb, pos2);
5425 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5426 if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
5427 klass->blittable || klass->enumtype) {
5428 mono_mb_emit_stloc (mb, 3);
5433 /* load pointer to returned value type */
5434 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5435 mono_mb_emit_byte (mb, CEE_MONO_VTADDR);
5437 /* store the address of the source into local variable 0 */
5438 mono_mb_emit_stloc (mb, 0);
5439 /* allocate space for the native struct and
5440 * store the address into dst_ptr */
5441 m->retobj_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5442 m->retobj_class = klass;
5443 g_assert (m->retobj_var);
5444 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
5445 mono_mb_emit_byte (mb, CEE_CONV_I);
5446 mono_mb_emit_icall (mb, mono_marshal_alloc);
5447 mono_mb_emit_stloc (mb, 1);
5448 mono_mb_emit_ldloc (mb, 1);
5449 mono_mb_emit_stloc (mb, m->retobj_var);
5451 /* emit valuetype conversion code */
5452 emit_struct_conv (mb, klass, FALSE);
5456 g_assert_not_reached ();
5463 emit_marshal_string (EmitMarshalContext *m, int argnum, MonoType *t,
5464 MonoMarshalSpec *spec,
5465 int conv_arg, MonoType **conv_arg_type,
5466 MarshalAction action)
5468 MonoMethodBuilder *mb = m->mb;
5469 MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
5470 MonoMarshalConv conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
5474 case MARSHAL_ACTION_CONV_IN:
5475 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5476 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5479 if (t->attrs & PARAM_ATTRIBUTE_OUT)
5482 mono_mb_emit_ldarg (mb, argnum);
5483 mono_mb_emit_byte (mb, CEE_LDIND_I);
5485 mono_mb_emit_ldarg (mb, argnum);
5489 char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
5490 MonoException *exc = mono_get_exception_not_implemented (msg);
5493 mono_raise_exception (exc);
5496 mono_mb_emit_icall (mb, conv_to_icall (conv));
5498 mono_mb_emit_stloc (mb, conv_arg);
5501 case MARSHAL_ACTION_CONV_OUT:
5502 conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
5504 char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
5505 mono_mb_emit_exception_marshal_directive (mb, msg);
5509 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT)) {
5510 mono_mb_emit_ldarg (mb, argnum);
5511 mono_mb_emit_ldloc (mb, conv_arg);
5512 mono_mb_emit_icall (mb, conv_to_icall (conv));
5513 mono_mb_emit_byte (mb, CEE_STIND_REF);
5516 if (need_free || (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT))) {
5517 mono_mb_emit_ldloc (mb, conv_arg);
5518 if (conv == MONO_MARSHAL_CONV_BSTR_STR)
5519 mono_mb_emit_icall (mb, mono_free_bstr);
5521 mono_mb_emit_icall (mb, mono_marshal_free);
5525 case MARSHAL_ACTION_PUSH:
5527 mono_mb_emit_ldloc_addr (mb, conv_arg);
5529 mono_mb_emit_ldloc (mb, conv_arg);
5532 case MARSHAL_ACTION_CONV_RESULT:
5533 mono_mb_emit_stloc (mb, 0);
5535 conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
5537 char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
5538 mono_mb_emit_exception_marshal_directive (mb, msg);
5542 mono_mb_emit_ldloc (mb, 0);
5543 mono_mb_emit_icall (mb, conv_to_icall (conv));
5544 mono_mb_emit_stloc (mb, 3);
5546 /* free the string */
5547 mono_mb_emit_ldloc (mb, 0);
5548 if (conv == MONO_MARSHAL_CONV_BSTR_STR)
5549 mono_mb_emit_icall (mb, mono_free_bstr);
5551 mono_mb_emit_icall (mb, mono_marshal_free);
5554 case MARSHAL_ACTION_MANAGED_CONV_IN:
5555 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
5557 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5559 conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
5561 char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
5562 mono_mb_emit_exception_marshal_directive (mb, msg);
5566 mono_mb_emit_ldarg (mb, argnum);
5568 mono_mb_emit_byte (mb, CEE_LDIND_I);
5569 mono_mb_emit_icall (mb, conv_to_icall (conv));
5570 mono_mb_emit_stloc (mb, conv_arg);
5573 case MARSHAL_ACTION_MANAGED_CONV_OUT:
5576 mono_mb_emit_ldarg (mb, argnum);
5577 mono_mb_emit_ldloc (mb, conv_arg);
5578 mono_mb_emit_icall (mb, conv_to_icall (conv));
5579 mono_mb_emit_byte (mb, CEE_STIND_I);
5584 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5585 if (conv_to_icall (conv) == mono_marshal_string_to_utf16)
5586 /* We need to make a copy so the caller is able to free it */
5587 mono_mb_emit_icall (mb, mono_marshal_string_to_utf16_copy);
5589 mono_mb_emit_icall (mb, conv_to_icall (conv));
5590 mono_mb_emit_stloc (mb, 3);
5594 g_assert_not_reached ();
5601 emit_marshal_safehandle (EmitMarshalContext *m, int argnum, MonoType *t,
5602 MonoMarshalSpec *spec, int conv_arg,
5603 MonoType **conv_arg_type, MarshalAction action)
5605 MonoMethodBuilder *mb = m->mb;
5608 case MARSHAL_ACTION_CONV_IN: {
5609 MonoType *intptr_type;
5610 int dar_release_slot, pos;
5612 intptr_type = &mono_defaults.int_class->byval_arg;
5613 conv_arg = mono_mb_add_local (mb, intptr_type);
5614 *conv_arg_type = intptr_type;
5616 if (!sh_dangerous_add_ref)
5617 init_safe_handle ();
5619 mono_mb_emit_ldarg (mb, argnum);
5620 pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
5621 mono_mb_emit_exception (mb, "ArgumentNullException", NULL);
5623 mono_mb_patch_branch (mb, pos);
5626 * My tests in show that ref SafeHandles are not really
5627 * passed as ref objects. Instead a NULL is passed as the
5630 mono_mb_emit_icon (mb, 0);
5631 mono_mb_emit_stloc (mb, conv_arg);
5635 /* Create local to hold the ref parameter to DangerousAddRef */
5636 dar_release_slot = mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
5638 /* set release = false; */
5639 mono_mb_emit_icon (mb, 0);
5640 mono_mb_emit_stloc (mb, dar_release_slot);
5642 /* safehandle.DangerousAddRef (ref release) */
5643 mono_mb_emit_ldarg (mb, argnum);
5644 mono_mb_emit_ldloc_addr (mb, dar_release_slot);
5645 mono_mb_emit_managed_call (mb, sh_dangerous_add_ref, NULL);
5647 /* Pull the handle field from SafeHandle */
5648 mono_mb_emit_ldarg (mb, argnum);
5649 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoSafeHandle, handle));
5650 mono_mb_emit_byte (mb, CEE_LDIND_I);
5651 mono_mb_emit_stloc (mb, conv_arg);
5656 case MARSHAL_ACTION_PUSH:
5658 mono_mb_emit_ldloc_addr (mb, conv_arg);
5660 mono_mb_emit_ldloc (mb, conv_arg);
5663 case MARSHAL_ACTION_CONV_OUT: {
5664 /* The slot for the boolean is the next temporary created after conv_arg, see the CONV_IN code */
5665 int dar_release_slot = conv_arg + 1;
5668 if (!sh_dangerous_release)
5669 init_safe_handle ();
5675 * My tests indicate that ref SafeHandles parameters are not actually
5676 * passed by ref, but instead a new Handle is created regardless of
5677 * whether a change happens in the unmanaged side.
5679 * Also, the Handle is created before calling into unmanaged code,
5680 * but we do not support that mechanism (getting to the original
5681 * handle) and it makes no difference where we create this
5683 ctor = mono_class_get_method_from_name (t->data.klass, ".ctor", 0);
5685 mono_mb_emit_exception (mb, "MissingMethodException", "paramterless constructor required");
5688 /* refval = new SafeHandleDerived ()*/
5689 mono_mb_emit_ldarg (mb, argnum);
5690 mono_mb_emit_op (mb, CEE_NEWOBJ, ctor);
5691 mono_mb_emit_byte (mb, CEE_STIND_REF);
5693 /* refval.handle = returned_handle */
5694 mono_mb_emit_ldarg (mb, argnum);
5695 mono_mb_emit_byte (mb, CEE_LDIND_REF);
5696 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoSafeHandle, handle));
5697 mono_mb_emit_ldloc (mb, conv_arg);
5698 mono_mb_emit_byte (mb, CEE_STIND_I);
5700 mono_mb_emit_ldloc (mb, dar_release_slot);
5701 label_next = mono_mb_emit_branch (mb, CEE_BRFALSE);
5702 mono_mb_emit_ldarg (mb, argnum);
5703 mono_mb_emit_managed_call (mb, sh_dangerous_release, NULL);
5704 mono_mb_patch_branch (mb, label_next);
5709 case MARSHAL_ACTION_CONV_RESULT: {
5710 MonoMethod *ctor = NULL;
5711 int intptr_handle_slot;
5713 if (t->data.klass->flags & TYPE_ATTRIBUTE_ABSTRACT){
5714 mono_mb_emit_byte (mb, CEE_POP);
5715 mono_mb_emit_exception_marshal_directive (mb, "Returned SafeHandles should not be abstract");
5719 ctor = mono_class_get_method_from_name (t->data.klass, ".ctor", 0);
5721 mono_mb_emit_byte (mb, CEE_POP);
5722 mono_mb_emit_exception (mb, "MissingMethodException", "paramterless constructor required");
5725 /* Store the IntPtr results into a local */
5726 intptr_handle_slot = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5727 mono_mb_emit_stloc (mb, intptr_handle_slot);
5729 /* Create return value */
5730 mono_mb_emit_op (mb, CEE_NEWOBJ, ctor);
5731 mono_mb_emit_stloc (mb, 3);
5733 /* Set the return.handle to the value, am using ldflda, not sure if thats a good idea */
5734 mono_mb_emit_ldloc (mb, 3);
5735 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoSafeHandle, handle));
5736 mono_mb_emit_ldloc (mb, intptr_handle_slot);
5737 mono_mb_emit_byte (mb, CEE_STIND_I);
5741 case MARSHAL_ACTION_MANAGED_CONV_IN:
5742 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_IN\n");
5745 case MARSHAL_ACTION_MANAGED_CONV_OUT:
5746 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_OUT\n");
5749 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5750 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_RESULT\n");
5753 printf ("Unhandled case for MarshalAction: %d\n", action);
5760 emit_marshal_handleref (EmitMarshalContext *m, int argnum, MonoType *t,
5761 MonoMarshalSpec *spec, int conv_arg,
5762 MonoType **conv_arg_type, MarshalAction action)
5764 MonoMethodBuilder *mb = m->mb;
5767 case MARSHAL_ACTION_CONV_IN: {
5768 MonoType *intptr_type;
5770 intptr_type = &mono_defaults.int_class->byval_arg;
5771 conv_arg = mono_mb_add_local (mb, intptr_type);
5772 *conv_arg_type = intptr_type;
5775 mono_mb_emit_exception_marshal_directive (mb,
5776 "HandleRefs can not be returned from unmanaged code (or passed by ref)");
5779 mono_mb_emit_ldarg_addr (mb, argnum);
5780 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoHandleRef, handle));
5781 mono_mb_emit_byte (mb, CEE_ADD);
5782 mono_mb_emit_byte (mb, CEE_LDIND_I);
5783 mono_mb_emit_stloc (mb, conv_arg);
5787 case MARSHAL_ACTION_PUSH:
5788 mono_mb_emit_ldloc (mb, conv_arg);
5791 case MARSHAL_ACTION_CONV_OUT: {
5792 /* no resource release required */
5796 case MARSHAL_ACTION_CONV_RESULT: {
5797 mono_mb_emit_exception_marshal_directive (mb,
5798 "HandleRefs can not be returned from unmanaged code (or passed by ref)");
5802 case MARSHAL_ACTION_MANAGED_CONV_IN:
5803 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_IN\n");
5806 case MARSHAL_ACTION_MANAGED_CONV_OUT:
5807 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_OUT\n");
5810 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5811 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_RESULT\n");
5814 fprintf (stderr, "Unhandled case for MarshalAction: %d\n", action);
5821 emit_marshal_object (EmitMarshalContext *m, int argnum, MonoType *t,
5822 MonoMarshalSpec *spec,
5823 int conv_arg, MonoType **conv_arg_type,
5824 MarshalAction action)
5826 MonoMethodBuilder *mb = m->mb;
5827 MonoClass *klass = mono_class_from_mono_type (t);
5830 if (mono_class_from_mono_type (t) == mono_defaults.object_class) {
5831 mono_raise_exception (mono_get_exception_not_implemented ("Marshalling of type object is not implemented"));
5835 case MARSHAL_ACTION_CONV_IN:
5836 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5837 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5839 m->orig_conv_args [argnum] = 0;
5841 if (klass->delegate) {
5843 if (!(t->attrs & PARAM_ATTRIBUTE_OUT)) {
5844 char *msg = g_strdup_printf ("Byref marshalling of delegates is not implemented.");
5845 mono_mb_emit_exception_marshal_directive (mb, msg);
5847 mono_mb_emit_byte (mb, CEE_LDNULL);
5848 mono_mb_emit_stloc (mb, conv_arg);
5850 mono_mb_emit_ldarg (mb, argnum);
5851 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_DEL_FTN));
5852 mono_mb_emit_stloc (mb, conv_arg);
5854 } else if (klass == mono_defaults.stringbuilder_class) {
5855 MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
5856 MonoMarshalConv conv = mono_marshal_get_stringbuilder_to_ptr_conv (m->piinfo, spec);
5858 g_assert (!t->byref);
5859 mono_mb_emit_ldarg (mb, argnum);
5862 mono_mb_emit_icall (mb, conv_to_icall (conv));
5864 char *msg = g_strdup_printf ("stringbuilder marshalling conversion %d not implemented", encoding);
5865 MonoException *exc = mono_get_exception_not_implemented (msg);
5868 mono_raise_exception (exc);
5871 mono_mb_emit_stloc (mb, conv_arg);
5872 } else if (klass->blittable) {
5873 mono_mb_emit_byte (mb, CEE_LDNULL);
5874 mono_mb_emit_stloc (mb, conv_arg);
5876 mono_mb_emit_ldarg (mb, argnum);
5877 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5879 mono_mb_emit_ldarg (mb, argnum);
5880 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5881 mono_mb_emit_stloc (mb, conv_arg);
5883 mono_mb_patch_branch (mb, pos);
5886 mono_mb_emit_byte (mb, CEE_LDNULL);
5887 mono_mb_emit_stloc (mb, conv_arg);
5890 /* we dont need any conversions for out parameters */
5891 if (t->attrs & PARAM_ATTRIBUTE_OUT)
5894 mono_mb_emit_ldarg (mb, argnum);
5895 mono_mb_emit_byte (mb, CEE_LDIND_I);
5898 mono_mb_emit_ldarg (mb, argnum);
5899 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5900 mono_mb_emit_byte (mb, CEE_MONO_OBJADDR);
5903 /* store the address of the source into local variable 0 */
5904 mono_mb_emit_stloc (mb, 0);
5905 mono_mb_emit_ldloc (mb, 0);
5906 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5908 /* allocate space for the native struct and store the address */
5909 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
5910 mono_mb_emit_byte (mb, CEE_PREFIX1);
5911 mono_mb_emit_byte (mb, CEE_LOCALLOC);
5912 mono_mb_emit_stloc (mb, conv_arg);
5915 /* Need to store the original buffer so we can free it later */
5916 m->orig_conv_args [argnum] = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5917 mono_mb_emit_ldloc (mb, conv_arg);
5918 mono_mb_emit_stloc (mb, m->orig_conv_args [argnum]);
5921 /* set the src_ptr */
5922 mono_mb_emit_ldloc (mb, 0);
5923 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5924 mono_mb_emit_stloc (mb, 0);
5927 mono_mb_emit_ldloc (mb, conv_arg);
5928 mono_mb_emit_stloc (mb, 1);
5930 /* emit valuetype conversion code */
5931 emit_struct_conv (mb, klass, FALSE);
5933 mono_mb_patch_branch (mb, pos);
5937 case MARSHAL_ACTION_CONV_OUT:
5938 if (klass == mono_defaults.stringbuilder_class) {
5940 MonoMarshalNative encoding;
5941 MonoMarshalConv conv;
5943 encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
5944 conv = mono_marshal_get_ptr_to_stringbuilder_conv (m->piinfo, spec, &need_free);
5946 g_assert (!t->byref);
5947 g_assert (encoding != -1);
5949 mono_mb_emit_ldarg (mb, argnum);
5950 mono_mb_emit_ldloc (mb, conv_arg);
5952 mono_mb_emit_icall (mb, conv_to_icall (conv));
5955 mono_mb_emit_ldloc (mb, conv_arg);
5956 mono_mb_emit_icall (mb, mono_marshal_free);
5961 if (klass->delegate) {
5963 mono_mb_emit_ldarg (mb, argnum);
5964 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5965 mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
5966 mono_mb_emit_ldloc (mb, conv_arg);
5967 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL));
5968 mono_mb_emit_byte (mb, CEE_STIND_REF);
5973 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT)) {
5974 /* allocate a new object */
5975 mono_mb_emit_ldarg (mb, argnum);
5976 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5977 mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, klass);
5978 mono_mb_emit_byte (mb, CEE_STIND_REF);
5981 /* dst = *argument */
5982 mono_mb_emit_ldarg (mb, argnum);
5985 mono_mb_emit_byte (mb, CEE_LDIND_I);
5987 mono_mb_emit_stloc (mb, 1);
5989 mono_mb_emit_ldloc (mb, 1);
5990 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5992 if (t->byref || (t->attrs & PARAM_ATTRIBUTE_OUT)) {
5993 mono_mb_emit_ldloc (mb, 1);
5994 mono_mb_emit_icon (mb, sizeof (MonoObject));
5995 mono_mb_emit_byte (mb, CEE_ADD);
5996 mono_mb_emit_stloc (mb, 1);
5998 /* src = tmp_locals [i] */
5999 mono_mb_emit_ldloc (mb, conv_arg);
6000 mono_mb_emit_stloc (mb, 0);
6002 /* emit valuetype conversion code */
6003 emit_struct_conv (mb, klass, TRUE);
6005 /* Free the structure returned by the native code */
6006 emit_struct_free (mb, klass, conv_arg);
6008 if (m->orig_conv_args [argnum]) {
6010 * If the native function changed the pointer, then free
6011 * the original structure plus the new pointer.
6013 mono_mb_emit_ldloc (mb, m->orig_conv_args [argnum]);
6014 mono_mb_emit_ldloc (mb, conv_arg);
6015 pos2 = mono_mb_emit_branch (mb, CEE_BEQ);
6017 if (!(t->attrs & PARAM_ATTRIBUTE_OUT)) {
6018 g_assert (m->orig_conv_args [argnum]);
6020 emit_struct_free (mb, klass, m->orig_conv_args [argnum]);
6023 mono_mb_emit_ldloc (mb, conv_arg);
6024 mono_mb_emit_icall (mb, g_free);
6026 mono_mb_patch_branch (mb, pos2);
6030 /* Free the original structure passed to native code */
6031 emit_struct_free (mb, klass, conv_arg);
6033 mono_mb_patch_branch (mb, pos);
6036 case MARSHAL_ACTION_PUSH:
6038 mono_mb_emit_ldloc_addr (mb, conv_arg);
6040 mono_mb_emit_ldloc (mb, conv_arg);
6043 case MARSHAL_ACTION_CONV_RESULT:
6044 if (klass->delegate) {
6045 g_assert (!t->byref);
6046 mono_mb_emit_stloc (mb, 0);
6047 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
6048 mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
6049 mono_mb_emit_ldloc (mb, 0);
6050 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL));
6051 mono_mb_emit_stloc (mb, 3);
6054 mono_mb_emit_stloc (mb, 0);
6056 /* Make a copy since emit_conv modifies local 0 */
6057 loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6058 mono_mb_emit_ldloc (mb, 0);
6059 mono_mb_emit_stloc (mb, loc);
6061 mono_mb_emit_byte (mb, CEE_LDNULL);
6062 mono_mb_emit_stloc (mb, 3);
6064 mono_mb_emit_ldloc (mb, 0);
6065 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
6067 /* allocate result object */
6069 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
6070 mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, klass);
6071 mono_mb_emit_stloc (mb, 3);
6075 mono_mb_emit_ldloc (mb, 3);
6076 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
6077 mono_mb_emit_stloc (mb, 1);
6079 /* emit conversion code */
6080 emit_struct_conv (mb, klass, TRUE);
6082 emit_struct_free (mb, klass, loc);
6084 /* Free the pointer allocated by unmanaged code */
6085 mono_mb_emit_ldloc (mb, loc);
6086 mono_mb_emit_icall (mb, g_free);
6087 mono_mb_patch_branch (mb, pos);
6091 case MARSHAL_ACTION_MANAGED_CONV_IN:
6092 conv_arg = mono_mb_add_local (mb, &klass->byval_arg);
6094 if (klass->delegate) {
6095 g_assert (!t->byref);
6096 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
6097 mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
6098 mono_mb_emit_ldarg (mb, argnum);
6099 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL));
6100 mono_mb_emit_stloc (mb, conv_arg);
6104 if (klass == mono_defaults.stringbuilder_class) {
6105 MonoMarshalNative encoding;
6107 encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
6110 g_assert (encoding == MONO_NATIVE_LPSTR);
6112 g_assert (!t->byref);
6113 g_assert (encoding != -1);
6115 mono_mb_emit_ldarg (mb, argnum);
6116 mono_mb_emit_icall (mb, mono_string_utf8_to_builder2);
6117 mono_mb_emit_stloc (mb, conv_arg);
6121 /* The class can not have an automatic layout */
6122 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
6123 mono_mb_emit_auto_layout_exception (mb, klass);
6127 if (t->attrs & PARAM_ATTRIBUTE_OUT) {
6128 mono_mb_emit_byte (mb, CEE_LDNULL);
6129 mono_mb_emit_stloc (mb, conv_arg);
6134 mono_mb_emit_ldarg (mb, argnum);
6138 /* Check for NULL and raise an exception */
6139 pos2 = mono_mb_emit_branch (mb, CEE_BRTRUE);
6141 mono_mb_emit_exception (mb, "ArgumentNullException", NULL);
6143 mono_mb_patch_branch (mb, pos2);
6144 mono_mb_emit_ldarg (mb, argnum);
6145 mono_mb_emit_byte (mb, CEE_LDIND_I);
6148 mono_mb_emit_stloc (mb, 0);
6150 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6151 mono_mb_emit_stloc (mb, conv_arg);
6153 mono_mb_emit_ldloc (mb, 0);
6154 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
6156 /* Create and set dst */
6157 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
6158 mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, klass);
6159 mono_mb_emit_stloc (mb, conv_arg);
6160 mono_mb_emit_ldloc (mb, conv_arg);
6161 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
6162 mono_mb_emit_stloc (mb, 1);
6164 /* emit valuetype conversion code */
6165 emit_struct_conv (mb, klass, TRUE);
6167 mono_mb_patch_branch (mb, pos);
6170 case MARSHAL_ACTION_MANAGED_CONV_OUT:
6172 /* Check for null */
6173 mono_mb_emit_ldloc (mb, conv_arg);
6174 pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
6175 mono_mb_emit_ldarg (mb, argnum);
6176 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6177 mono_mb_emit_byte (mb, CEE_STIND_REF);
6178 pos2 = mono_mb_emit_branch (mb, CEE_BR);
6180 mono_mb_patch_branch (mb, pos);
6183 mono_mb_emit_ldloc (mb, conv_arg);
6184 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
6185 mono_mb_emit_stloc (mb, 0);
6187 /* Allocate and set dest */
6188 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
6189 mono_mb_emit_byte (mb, CEE_CONV_I);
6190 mono_mb_emit_icall (mb, mono_marshal_alloc);
6191 mono_mb_emit_stloc (mb, 1);
6193 /* Update argument pointer */
6194 mono_mb_emit_ldarg (mb, argnum);
6195 mono_mb_emit_ldloc (mb, 1);
6196 mono_mb_emit_byte (mb, CEE_STIND_I);
6198 /* emit valuetype conversion code */
6199 emit_struct_conv (mb, klass, FALSE);
6201 mono_mb_patch_branch (mb, pos2);
6203 /* byval [Out] marshalling */
6205 /* FIXME: Handle null */
6208 mono_mb_emit_ldloc (mb, conv_arg);
6209 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
6210 mono_mb_emit_stloc (mb, 0);
6213 mono_mb_emit_ldarg (mb, argnum);
6214 mono_mb_emit_stloc (mb, 1);
6216 /* emit valuetype conversion code */
6217 emit_struct_conv (mb, klass, FALSE);
6221 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
6222 if (klass->delegate) {
6223 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_DEL_FTN));
6224 mono_mb_emit_stloc (mb, 3);
6228 /* The class can not have an automatic layout */
6229 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
6230 mono_mb_emit_auto_layout_exception (mb, klass);
6234 mono_mb_emit_stloc (mb, 0);
6235 /* Check for null */
6236 mono_mb_emit_ldloc (mb, 0);
6237 pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
6238 mono_mb_emit_byte (mb, CEE_LDNULL);
6239 mono_mb_emit_stloc (mb, 3);
6240 pos2 = mono_mb_emit_branch (mb, CEE_BR);
6242 mono_mb_patch_branch (mb, pos);
6245 mono_mb_emit_ldloc (mb, 0);
6246 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
6247 mono_mb_emit_stloc (mb, 0);
6249 /* Allocate and set dest */
6250 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
6251 mono_mb_emit_byte (mb, CEE_CONV_I);
6252 mono_mb_emit_icall (mb, mono_marshal_alloc);
6253 mono_mb_emit_byte (mb, CEE_DUP);
6254 mono_mb_emit_stloc (mb, 1);
6255 mono_mb_emit_stloc (mb, 3);
6257 emit_struct_conv (mb, klass, FALSE);
6259 mono_mb_patch_branch (mb, pos2);
6263 g_assert_not_reached ();
6270 emit_marshal_variant (EmitMarshalContext *m, int argnum, MonoType *t,
6271 MonoMarshalSpec *spec,
6272 int conv_arg, MonoType **conv_arg_type,
6273 MarshalAction action)
6275 MonoMethodBuilder *mb = m->mb;
6276 static MonoMethod *get_object_for_native_variant = NULL;
6277 static MonoMethod *get_native_variant_for_object = NULL;
6279 mono_init_com_types ();
6281 if (!get_object_for_native_variant)
6282 get_object_for_native_variant = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetObjectForNativeVariant", 1);
6283 g_assert (get_object_for_native_variant);
6285 if (!get_native_variant_for_object)
6286 get_native_variant_for_object = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetNativeVariantForObject", 2);
6287 g_assert (get_native_variant_for_object);
6290 case MARSHAL_ACTION_CONV_IN: {
6291 conv_arg = mono_mb_add_local (mb, &mono_defaults.variant_class->byval_arg);
6294 *conv_arg_type = &mono_defaults.variant_class->this_arg;
6296 *conv_arg_type = &mono_defaults.variant_class->byval_arg;
6298 if (t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && t->attrs & PARAM_ATTRIBUTE_OUT)
6301 mono_mb_emit_ldarg (mb, argnum);
6303 mono_mb_emit_byte(mb, CEE_LDIND_REF);
6304 mono_mb_emit_ldloc_addr (mb, conv_arg);
6305 mono_mb_emit_managed_call (mb, get_native_variant_for_object, NULL);
6309 case MARSHAL_ACTION_CONV_OUT: {
6310 static MonoMethod *variant_clear = NULL;
6313 variant_clear = mono_class_get_method_from_name (mono_defaults.variant_class, "Clear", 0);
6314 g_assert (variant_clear);
6317 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT || !(t->attrs & PARAM_ATTRIBUTE_IN))) {
6318 mono_mb_emit_ldarg (mb, argnum);
6319 mono_mb_emit_ldloc_addr (mb, conv_arg);
6320 mono_mb_emit_managed_call (mb, get_object_for_native_variant, NULL);
6321 mono_mb_emit_byte (mb, CEE_STIND_REF);
6324 mono_mb_emit_ldloc_addr (mb, conv_arg);
6325 mono_mb_emit_managed_call (mb, variant_clear, NULL);
6329 case MARSHAL_ACTION_PUSH:
6331 mono_mb_emit_ldloc_addr (mb, conv_arg);
6333 mono_mb_emit_ldloc (mb, conv_arg);
6336 case MARSHAL_ACTION_CONV_RESULT: {
6337 char *msg = g_strdup ("Marshalling of VARIANT not supported as a return type.");
6338 mono_mb_emit_exception_marshal_directive (mb, msg);
6342 case MARSHAL_ACTION_MANAGED_CONV_IN: {
6343 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6346 *conv_arg_type = &mono_defaults.variant_class->this_arg;
6348 *conv_arg_type = &mono_defaults.variant_class->byval_arg;
6350 if (t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && t->attrs & PARAM_ATTRIBUTE_OUT)
6354 mono_mb_emit_ldarg (mb, argnum);
6356 mono_mb_emit_ldarg_addr (mb, argnum);
6357 mono_mb_emit_managed_call (mb, get_object_for_native_variant, NULL);
6358 mono_mb_emit_stloc (mb, conv_arg);
6362 case MARSHAL_ACTION_MANAGED_CONV_OUT: {
6363 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT || !(t->attrs & PARAM_ATTRIBUTE_IN))) {
6364 mono_mb_emit_ldloc (mb, conv_arg);
6365 mono_mb_emit_ldarg (mb, argnum);
6366 mono_mb_emit_managed_call (mb, get_native_variant_for_object, NULL);
6371 case MARSHAL_ACTION_MANAGED_CONV_RESULT: {
6372 char *msg = g_strdup ("Marshalling of VARIANT not supported as a return type.");
6373 mono_mb_emit_exception_marshal_directive (mb, msg);
6378 g_assert_not_reached ();
6385 emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
6386 MonoMarshalSpec *spec,
6387 int conv_arg, MonoType **conv_arg_type,
6388 MarshalAction action)
6390 MonoMethodBuilder *mb = m->mb;
6391 MonoClass *klass = mono_class_from_mono_type (t);
6392 gboolean need_convert, need_free;
6393 MonoMarshalNative encoding;
6395 encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
6398 case MARSHAL_ACTION_CONV_IN:
6399 *conv_arg_type = &mono_defaults.object_class->byval_arg;
6400 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6402 if (klass->element_class->blittable) {
6403 mono_mb_emit_ldarg (mb, argnum);
6405 mono_mb_emit_byte (mb, CEE_LDIND_I);
6406 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_ARRAY_LPARRAY));
6407 mono_mb_emit_stloc (mb, conv_arg);
6410 guint32 label1, label2, label3;
6411 int index_var, src_var, dest_ptr, esize;
6412 MonoMarshalConv conv;
6413 gboolean is_string = FALSE;
6415 dest_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6417 eklass = klass->element_class;
6419 if (eklass == mono_defaults.string_class) {
6421 conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
6423 else if (eklass == mono_defaults.stringbuilder_class) {
6425 conv = mono_marshal_get_stringbuilder_to_ptr_conv (m->piinfo, spec);
6430 src_var = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6431 mono_mb_emit_ldarg (mb, argnum);
6433 mono_mb_emit_byte (mb, CEE_LDIND_I);
6434 mono_mb_emit_stloc (mb, src_var);
6437 mono_mb_emit_ldloc (mb, src_var);
6438 mono_mb_emit_stloc (mb, conv_arg);
6439 mono_mb_emit_ldloc (mb, src_var);
6440 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6444 char *msg = g_strdup_printf ("string/stringbuilder marshalling conversion %d not implemented", encoding);
6445 MonoException *exc = mono_get_exception_not_implemented (msg);
6448 mono_raise_exception (exc);
6453 esize = sizeof (gpointer);
6455 esize = mono_class_native_size (eklass, NULL);
6457 /* allocate space for the native struct and store the address */
6458 mono_mb_emit_icon (mb, esize);
6459 mono_mb_emit_ldloc (mb, src_var);
6460 mono_mb_emit_byte (mb, CEE_LDLEN);
6462 if (eklass == mono_defaults.string_class) {
6463 /* Make the array bigger for the terminating null */
6464 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
6465 mono_mb_emit_byte (mb, CEE_ADD);
6467 mono_mb_emit_byte (mb, CEE_MUL);
6468 mono_mb_emit_byte (mb, CEE_PREFIX1);
6469 mono_mb_emit_byte (mb, CEE_LOCALLOC);
6470 mono_mb_emit_stloc (mb, conv_arg);
6472 mono_mb_emit_ldloc (mb, conv_arg);
6473 mono_mb_emit_stloc (mb, dest_ptr);
6475 /* Emit marshalling loop */
6476 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6477 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6478 mono_mb_emit_stloc (mb, index_var);
6479 label2 = mono_mb_get_label (mb);
6480 mono_mb_emit_ldloc (mb, index_var);
6481 mono_mb_emit_ldloc (mb, src_var);
6482 mono_mb_emit_byte (mb, CEE_LDLEN);
6483 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6485 /* Emit marshalling code */
6488 mono_mb_emit_ldloc (mb, dest_ptr);
6489 mono_mb_emit_ldloc (mb, src_var);
6490 mono_mb_emit_ldloc (mb, index_var);
6491 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
6492 mono_mb_emit_icall (mb, conv_to_icall (conv));
6493 mono_mb_emit_byte (mb, CEE_STIND_I);
6495 /* set the src_ptr */
6496 mono_mb_emit_ldloc (mb, src_var);
6497 mono_mb_emit_ldloc (mb, index_var);
6498 mono_mb_emit_op (mb, CEE_LDELEMA, eklass);
6499 mono_mb_emit_stloc (mb, 0);
6502 mono_mb_emit_ldloc (mb, dest_ptr);
6503 mono_mb_emit_stloc (mb, 1);
6505 /* emit valuetype conversion code */
6506 emit_struct_conv (mb, eklass, FALSE);
6509 mono_mb_emit_add_to_local (mb, index_var, 1);
6510 mono_mb_emit_add_to_local (mb, dest_ptr, esize);
6512 mono_mb_emit_branch_label (mb, CEE_BR, label2);
6514 mono_mb_patch_branch (mb, label3);
6516 if (eklass == mono_defaults.string_class) {
6517 /* Null terminate */
6518 mono_mb_emit_ldloc (mb, dest_ptr);
6519 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6520 mono_mb_emit_byte (mb, CEE_STIND_REF);
6523 mono_mb_patch_branch (mb, label1);
6528 case MARSHAL_ACTION_CONV_OUT:
6529 /* Unicode character arrays are implicitly marshalled as [Out] under MS.NET */
6530 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);
6531 need_free = mono_marshal_need_free (&klass->element_class->byval_arg,
6534 if (need_convert || need_free) {
6535 /* FIXME: Optimize blittable case */
6537 guint32 label1, label2, label3;
6538 int index_var, src_ptr, loc, esize;
6540 eklass = klass->element_class;
6541 if ((eklass == mono_defaults.stringbuilder_class) || (eklass == mono_defaults.string_class))
6542 esize = sizeof (gpointer);
6544 esize = mono_class_native_size (eklass, NULL);
6545 src_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6546 loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6549 mono_mb_emit_ldarg (mb, argnum);
6551 mono_mb_emit_byte (mb, CEE_LDIND_I);
6552 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6554 mono_mb_emit_ldloc (mb, conv_arg);
6555 mono_mb_emit_stloc (mb, src_ptr);
6557 /* Emit marshalling loop */
6558 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6559 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6560 mono_mb_emit_stloc (mb, index_var);
6561 label2 = mono_mb_get_label (mb);
6562 mono_mb_emit_ldloc (mb, index_var);
6563 mono_mb_emit_ldarg (mb, argnum);
6565 mono_mb_emit_byte (mb, CEE_LDIND_REF);
6566 mono_mb_emit_byte (mb, CEE_LDLEN);
6567 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6569 /* Emit marshalling code */
6571 if (eklass == mono_defaults.stringbuilder_class) {
6572 gboolean need_free2;
6573 MonoMarshalConv conv = mono_marshal_get_ptr_to_stringbuilder_conv (m->piinfo, spec, &need_free2);
6575 g_assert (conv != -1);
6578 mono_mb_emit_ldarg (mb, argnum);
6580 mono_mb_emit_byte (mb, CEE_LDIND_I);
6581 mono_mb_emit_ldloc (mb, index_var);
6582 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
6585 mono_mb_emit_ldloc (mb, src_ptr);
6586 mono_mb_emit_byte (mb, CEE_LDIND_I);
6588 mono_mb_emit_icall (mb, conv_to_icall (conv));
6592 mono_mb_emit_ldloc (mb, src_ptr);
6593 mono_mb_emit_byte (mb, CEE_LDIND_I);
6595 mono_mb_emit_icall (mb, mono_marshal_free);
6598 else if (eklass == mono_defaults.string_class) {
6601 mono_mb_emit_ldloc (mb, src_ptr);
6602 mono_mb_emit_byte (mb, CEE_LDIND_I);
6604 mono_mb_emit_icall (mb, mono_marshal_free);
6609 /* set the src_ptr */
6610 mono_mb_emit_ldloc (mb, src_ptr);
6611 mono_mb_emit_stloc (mb, 0);
6614 mono_mb_emit_ldarg (mb, argnum);
6616 mono_mb_emit_byte (mb, CEE_LDIND_REF);
6617 mono_mb_emit_ldloc (mb, index_var);
6618 mono_mb_emit_op (mb, CEE_LDELEMA, eklass);
6619 mono_mb_emit_stloc (mb, 1);
6621 /* emit valuetype conversion code */
6622 emit_struct_conv (mb, eklass, TRUE);
6626 mono_mb_emit_ldloc (mb, src_ptr);
6627 mono_mb_emit_stloc (mb, loc);
6628 mono_mb_emit_ldloc (mb, loc);
6630 emit_struct_free (mb, eklass, loc);
6634 mono_mb_emit_add_to_local (mb, index_var, 1);
6635 mono_mb_emit_add_to_local (mb, src_ptr, esize);
6637 mono_mb_emit_branch_label (mb, CEE_BR, label2);
6639 mono_mb_patch_branch (mb, label1);
6640 mono_mb_patch_branch (mb, label3);
6644 case MARSHAL_ACTION_PUSH:
6646 mono_mb_emit_ldloc_addr (mb, conv_arg);
6648 mono_mb_emit_ldloc (mb, conv_arg);
6651 case MARSHAL_ACTION_CONV_RESULT:
6652 /* fixme: we need conversions here */
6653 mono_mb_emit_stloc (mb, 3);
6656 case MARSHAL_ACTION_MANAGED_CONV_IN: {
6658 guint32 label1, label2, label3;
6659 int index_var, src_ptr, loc, esize, param_num, num_elem;
6660 MonoMarshalConv conv;
6661 gboolean is_string = FALSE;
6663 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6664 *conv_arg_type = &mono_defaults.int_class->byval_arg;
6667 char *msg = g_strdup ("Byref array marshalling to managed code is not implemented.");
6668 mono_mb_emit_exception_marshal_directive (mb, msg);
6672 char *msg = g_strdup ("[MarshalAs] attribute required to marshal arrays to managed code.");
6673 mono_mb_emit_exception_marshal_directive (mb, msg);
6676 if (spec->native != MONO_NATIVE_LPARRAY) {
6677 char *msg = g_strdup ("Non LPArray marshalling of arrays to managed code is not implemented.");
6678 mono_mb_emit_exception_marshal_directive (mb, msg);
6682 /* FIXME: t is from the method which is wrapped, not the delegate type */
6683 /* g_assert (t->attrs & PARAM_ATTRIBUTE_IN); */
6685 param_num = spec->data.array_data.param_num;
6686 num_elem = spec->data.array_data.num_elem;
6687 if (spec->data.array_data.elem_mult == 0)
6688 /* param_num is not specified */
6691 if (param_num == -1) {
6692 if (num_elem <= 0) {
6693 char *msg = g_strdup ("Either SizeConst or SizeParamIndex should be specified when marshalling arrays to managed code.");
6694 mono_mb_emit_exception_marshal_directive (mb, msg);
6699 /* FIXME: Optimize blittable case */
6701 eklass = klass->element_class;
6702 if (eklass == mono_defaults.string_class) {
6704 conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
6706 else if (eklass == mono_defaults.stringbuilder_class) {
6708 conv = mono_marshal_get_ptr_to_stringbuilder_conv (m->piinfo, spec, &need_free);
6713 mono_marshal_load_type_info (eklass);
6716 esize = sizeof (gpointer);
6718 esize = mono_class_native_size (eklass, NULL);
6719 src_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6720 loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6722 mono_mb_emit_byte (mb, CEE_LDNULL);
6723 mono_mb_emit_stloc (mb, conv_arg);
6725 /* Check param index */
6726 if (param_num != -1) {
6727 if (param_num >= m->sig->param_count) {
6728 char *msg = g_strdup ("Array size control parameter index is out of range.");
6729 mono_mb_emit_exception_marshal_directive (mb, msg);
6732 switch (m->sig->params [param_num]->type) {
6745 char *msg = g_strdup ("Array size control parameter must be an integral type.");
6746 mono_mb_emit_exception_marshal_directive (mb, msg);
6753 mono_mb_emit_ldarg (mb, argnum);
6754 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6756 mono_mb_emit_ldarg (mb, argnum);
6757 mono_mb_emit_stloc (mb, src_ptr);
6759 /* Create managed array */
6761 * The LPArray marshalling spec says that sometimes param_num starts
6762 * from 1, sometimes it starts from 0. But MS seems to allways start
6766 if (param_num == -1)
6767 mono_mb_emit_icon (mb, num_elem);
6769 /* FIXME: Add the two together */
6770 mono_mb_emit_ldarg (mb, param_num);
6772 mono_mb_emit_icon (mb, num_elem);
6773 mono_mb_emit_byte (mb, CEE_ADD);
6777 mono_mb_emit_op (mb, CEE_NEWARR, eklass);
6778 mono_mb_emit_stloc (mb, conv_arg);
6780 if (eklass->blittable) {
6781 mono_mb_emit_ldloc (mb, conv_arg);
6782 mono_mb_emit_byte (mb, CEE_CONV_I);
6783 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoArray, vector));
6784 mono_mb_emit_byte (mb, CEE_ADD);
6785 mono_mb_emit_ldarg (mb, argnum);
6786 mono_mb_emit_ldloc (mb, conv_arg);
6787 mono_mb_emit_byte (mb, CEE_LDLEN);
6788 mono_mb_emit_icon (mb, esize);
6789 mono_mb_emit_byte (mb, CEE_MUL);
6790 mono_mb_emit_byte (mb, CEE_PREFIX1);
6791 mono_mb_emit_byte (mb, CEE_CPBLK);
6795 /* Emit marshalling loop */
6796 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6797 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6798 mono_mb_emit_stloc (mb, index_var);
6799 label2 = mono_mb_get_label (mb);
6800 mono_mb_emit_ldloc (mb, index_var);
6801 mono_mb_emit_ldloc (mb, conv_arg);
6802 mono_mb_emit_byte (mb, CEE_LDLEN);
6803 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6805 /* Emit marshalling code */
6807 g_assert (conv != -1);
6809 mono_mb_emit_ldloc (mb, conv_arg);
6810 mono_mb_emit_ldloc (mb, index_var);
6812 mono_mb_emit_ldloc (mb, src_ptr);
6813 mono_mb_emit_byte (mb, CEE_LDIND_I);
6815 mono_mb_emit_icall (mb, conv_to_icall (conv));
6816 mono_mb_emit_byte (mb, CEE_STELEM_REF);
6819 char *msg = g_strdup ("Marshalling of non-string and non-blittable arrays to managed code is not implemented.");
6820 mono_mb_emit_exception_marshal_directive (mb, msg);
6824 mono_mb_emit_add_to_local (mb, index_var, 1);
6825 mono_mb_emit_add_to_local (mb, src_ptr, esize);
6827 mono_mb_emit_branch_label (mb, CEE_BR, label2);
6829 mono_mb_patch_branch (mb, label1);
6830 mono_mb_patch_branch (mb, label3);
6834 case MARSHAL_ACTION_MANAGED_CONV_OUT: {
6836 guint32 label1, label2, label3;
6837 int index_var, dest_ptr, loc, esize, param_num, num_elem;
6838 MonoMarshalConv conv;
6839 gboolean is_string = FALSE;
6842 /* Already handled in CONV_IN */
6845 /* These are already checked in CONV_IN */
6846 g_assert (!t->byref);
6847 g_assert (spec->native == MONO_NATIVE_LPARRAY);
6848 g_assert (t->attrs & PARAM_ATTRIBUTE_OUT);
6850 param_num = spec->data.array_data.param_num;
6851 num_elem = spec->data.array_data.num_elem;
6853 if (spec->data.array_data.elem_mult == 0)
6854 /* param_num is not specified */
6857 if (param_num == -1) {
6858 if (num_elem <= 0) {
6859 g_assert_not_reached ();
6863 /* FIXME: Optimize blittable case */
6865 eklass = klass->element_class;
6866 if (eklass == mono_defaults.string_class) {
6868 conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
6870 else if (eklass == mono_defaults.stringbuilder_class) {
6872 conv = mono_marshal_get_stringbuilder_to_ptr_conv (m->piinfo, spec);
6877 mono_marshal_load_type_info (eklass);
6880 esize = sizeof (gpointer);
6882 esize = mono_class_native_size (eklass, NULL);
6884 dest_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6885 loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6888 mono_mb_emit_ldloc (mb, conv_arg);
6889 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6891 mono_mb_emit_ldarg (mb, argnum);
6892 mono_mb_emit_stloc (mb, dest_ptr);
6894 if (eklass->blittable) {
6896 mono_mb_emit_ldarg (mb, argnum);
6898 mono_mb_emit_ldloc (mb, conv_arg);
6899 mono_mb_emit_byte (mb, CEE_CONV_I);
6900 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoArray, vector));
6901 mono_mb_emit_byte (mb, CEE_ADD);
6903 mono_mb_emit_ldloc (mb, conv_arg);
6904 mono_mb_emit_byte (mb, CEE_LDLEN);
6905 mono_mb_emit_icon (mb, esize);
6906 mono_mb_emit_byte (mb, CEE_MUL);
6907 mono_mb_emit_byte (mb, CEE_PREFIX1);
6908 mono_mb_emit_byte (mb, CEE_CPBLK);
6912 /* Emit marshalling loop */
6913 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6914 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6915 mono_mb_emit_stloc (mb, index_var);
6916 label2 = mono_mb_get_label (mb);
6917 mono_mb_emit_ldloc (mb, index_var);
6918 mono_mb_emit_ldloc (mb, conv_arg);
6919 mono_mb_emit_byte (mb, CEE_LDLEN);
6920 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6922 /* Emit marshalling code */
6924 g_assert (conv != -1);
6927 mono_mb_emit_ldloc (mb, dest_ptr);
6930 mono_mb_emit_ldloc (mb, conv_arg);
6931 mono_mb_emit_ldloc (mb, index_var);
6933 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
6935 mono_mb_emit_icall (mb, conv_to_icall (conv));
6936 mono_mb_emit_byte (mb, CEE_STIND_I);
6939 char *msg = g_strdup ("Marshalling of non-string and non-blittable arrays to managed code is not implemented.");
6940 mono_mb_emit_exception_marshal_directive (mb, msg);
6944 mono_mb_emit_add_to_local (mb, index_var, 1);
6945 mono_mb_emit_add_to_local (mb, dest_ptr, esize);
6947 mono_mb_emit_branch_label (mb, CEE_BR, label2);
6949 mono_mb_patch_branch (mb, label1);
6950 mono_mb_patch_branch (mb, label3);
6954 case MARSHAL_ACTION_MANAGED_CONV_RESULT: {
6956 guint32 label1, label2, label3;
6957 int index_var, src, dest, esize;
6958 MonoMarshalConv conv = -1;
6959 gboolean is_string = FALSE;
6961 g_assert (!t->byref);
6963 eklass = klass->element_class;
6965 mono_marshal_load_type_info (eklass);
6967 if (eklass == mono_defaults.string_class) {
6969 conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
6972 g_assert_not_reached ();
6976 esize = sizeof (gpointer);
6978 esize = mono_class_native_size (eklass, NULL);
6980 src = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6981 dest = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6983 mono_mb_emit_stloc (mb, src);
6984 mono_mb_emit_ldloc (mb, src);
6985 mono_mb_emit_stloc (mb, 3);
6987 /* Check for null */
6988 mono_mb_emit_ldloc (mb, src);
6989 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6991 /* Allocate native array */
6992 mono_mb_emit_icon (mb, esize);
6993 mono_mb_emit_ldloc (mb, src);
6994 mono_mb_emit_byte (mb, CEE_LDLEN);
6996 if (eklass == mono_defaults.string_class) {
6997 /* Make the array bigger for the terminating null */
6998 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
6999 mono_mb_emit_byte (mb, CEE_ADD);
7001 mono_mb_emit_byte (mb, CEE_MUL);
7002 mono_mb_emit_icall (mb, mono_marshal_alloc);
7003 mono_mb_emit_stloc (mb, dest);
7004 mono_mb_emit_ldloc (mb, dest);
7005 mono_mb_emit_stloc (mb, 3);
7007 /* Emit marshalling loop */
7008 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7009 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
7010 mono_mb_emit_stloc (mb, index_var);
7011 label2 = mono_mb_get_label (mb);
7012 mono_mb_emit_ldloc (mb, index_var);
7013 mono_mb_emit_ldloc (mb, src);
7014 mono_mb_emit_byte (mb, CEE_LDLEN);
7015 label3 = mono_mb_emit_branch (mb, CEE_BGE);
7017 /* Emit marshalling code */
7019 g_assert (conv != -1);
7022 mono_mb_emit_ldloc (mb, dest);
7025 mono_mb_emit_ldloc (mb, src);
7026 mono_mb_emit_ldloc (mb, index_var);
7028 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
7030 mono_mb_emit_icall (mb, conv_to_icall (conv));
7031 mono_mb_emit_byte (mb, CEE_STIND_I);
7034 char *msg = g_strdup ("Marshalling of non-string arrays to managed code is not implemented.");
7035 mono_mb_emit_exception_marshal_directive (mb, msg);
7039 mono_mb_emit_add_to_local (mb, index_var, 1);
7040 mono_mb_emit_add_to_local (mb, dest, esize);
7042 mono_mb_emit_branch_label (mb, CEE_BR, label2);
7044 mono_mb_patch_branch (mb, label3);
7045 mono_mb_patch_branch (mb, label1);
7049 g_assert_not_reached ();
7056 emit_marshal_boolean (EmitMarshalContext *m, int argnum, MonoType *t,
7057 MonoMarshalSpec *spec,
7058 int conv_arg, MonoType **conv_arg_type,
7059 MarshalAction action)
7061 MonoMethodBuilder *mb = m->mb;
7064 case MARSHAL_ACTION_CONV_IN: {
7065 MonoType *local_type;
7066 int variant_bool = 0;
7070 local_type = &mono_defaults.int32_class->byval_arg;
7072 switch (spec->native) {
7073 case MONO_NATIVE_I1:
7074 case MONO_NATIVE_U1:
7075 local_type = &mono_defaults.byte_class->byval_arg;
7077 case MONO_NATIVE_VARIANTBOOL:
7078 local_type = &mono_defaults.int16_class->byval_arg;
7082 g_warning ("marshalling bool as native type %x is currently not supported", spec->native);
7083 local_type = &mono_defaults.int32_class->byval_arg;
7087 *conv_arg_type = &mono_defaults.int_class->byval_arg;
7088 conv_arg = mono_mb_add_local (mb, local_type);
7089 mono_mb_emit_ldarg (mb, argnum);
7090 mono_mb_emit_byte (mb, CEE_LDIND_I1);
7092 mono_mb_emit_byte (mb, CEE_NEG);
7093 mono_mb_emit_stloc (mb, conv_arg);
7097 case MARSHAL_ACTION_CONV_OUT:
7100 mono_mb_emit_ldarg (mb, argnum);
7101 mono_mb_emit_ldloc (mb, conv_arg);
7102 if (spec != NULL && spec->native == MONO_NATIVE_VARIANTBOOL)
7103 mono_mb_emit_byte (mb, CEE_NEG);
7104 mono_mb_emit_byte (mb, CEE_STIND_I1);
7107 case MARSHAL_ACTION_PUSH:
7109 mono_mb_emit_ldloc_addr (mb, conv_arg);
7111 mono_mb_emit_ldarg (mb, argnum);
7114 case MARSHAL_ACTION_CONV_RESULT:
7115 /* maybe we need to make sure that it fits within 8 bits */
7116 mono_mb_emit_stloc (mb, 3);
7119 case MARSHAL_ACTION_MANAGED_CONV_IN: {
7120 gint variant_bool = 0;
7121 guint8 ldop = CEE_LDIND_I4;
7127 conv_arg = mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
7129 *conv_arg_type = &mono_defaults.int32_class->byval_arg;
7132 switch (spec->native) {
7133 case MONO_NATIVE_I1:
7134 case MONO_NATIVE_U1:
7135 *conv_arg_type = &mono_defaults.byte_class->this_arg;
7136 ldop = CEE_LDIND_I1;
7138 case MONO_NATIVE_VARIANTBOOL:
7139 *conv_arg_type = &mono_defaults.int16_class->this_arg;
7141 ldop = CEE_LDIND_I2;
7143 case MONO_NATIVE_BOOLEAN:
7146 g_warning ("marshalling bool as native type %x is currently not supported", spec->native);
7151 mono_mb_emit_ldarg (mb, argnum);
7152 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
7154 mono_mb_emit_ldarg (mb, argnum);
7155 mono_mb_emit_byte (mb, ldop);
7158 mono_mb_emit_byte (mb, CEE_NEG);
7159 mono_mb_emit_stloc (mb, conv_arg);
7161 mono_mb_patch_branch (mb, label1);
7165 case MARSHAL_ACTION_MANAGED_CONV_OUT: {
7166 guint8 stop = CEE_STIND_I4;
7172 switch (spec->native) {
7173 case MONO_NATIVE_I1:
7174 case MONO_NATIVE_U1:
7175 stop = CEE_STIND_I1;
7177 case MONO_NATIVE_VARIANTBOOL:
7178 stop = CEE_STIND_I2;
7186 mono_mb_emit_ldarg (mb, argnum);
7187 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
7189 mono_mb_emit_ldarg (mb, argnum);
7190 mono_mb_emit_ldloc (mb, conv_arg);
7191 if (spec != NULL && spec->native == MONO_NATIVE_VARIANTBOOL)
7192 mono_mb_emit_byte (mb, CEE_NEG);
7193 mono_mb_emit_byte (mb, stop);
7195 mono_mb_patch_branch (mb, label1);
7200 g_assert_not_reached ();
7207 emit_marshal_ptr (EmitMarshalContext *m, int argnum, MonoType *t,
7208 MonoMarshalSpec *spec, int conv_arg,
7209 MonoType **conv_arg_type, MarshalAction action)
7211 MonoMethodBuilder *mb = m->mb;
7214 case MARSHAL_ACTION_CONV_IN:
7215 if (MONO_TYPE_ISSTRUCT (t->data.type) && !mono_class_from_mono_type (t->data.type)->blittable) {
7216 char *msg = g_strdup_printf ("Can not marshal 'parameter #%d': Pointers can not reference marshaled structures. Use byref instead.", argnum + 1);
7217 mono_mb_emit_exception_marshal_directive (m->mb, msg);
7221 case MARSHAL_ACTION_PUSH:
7222 mono_mb_emit_ldarg (mb, argnum);
7225 case MARSHAL_ACTION_CONV_RESULT:
7226 /* no conversions necessary */
7227 mono_mb_emit_stloc (mb, 3);
7238 emit_marshal_char (EmitMarshalContext *m, int argnum, MonoType *t,
7239 MonoMarshalSpec *spec, int conv_arg,
7240 MonoType **conv_arg_type, MarshalAction action)
7242 MonoMethodBuilder *mb = m->mb;
7245 case MARSHAL_ACTION_PUSH:
7246 /* fixme: dont know how to marshal that. We cant simply
7247 * convert it to a one byte UTF8 character, because an
7248 * unicode character may need more that one byte in UTF8 */
7249 mono_mb_emit_ldarg (mb, argnum);
7252 case MARSHAL_ACTION_CONV_RESULT:
7253 /* fixme: we need conversions here */
7254 mono_mb_emit_stloc (mb, 3);
7265 emit_marshal_scalar (EmitMarshalContext *m, int argnum, MonoType *t,
7266 MonoMarshalSpec *spec, int conv_arg,
7267 MonoType **conv_arg_type, MarshalAction action)
7269 MonoMethodBuilder *mb = m->mb;
7272 case MARSHAL_ACTION_PUSH:
7273 mono_mb_emit_ldarg (mb, argnum);
7276 case MARSHAL_ACTION_CONV_RESULT:
7277 /* no conversions necessary */
7278 mono_mb_emit_stloc (mb, 3);
7289 emit_marshal (EmitMarshalContext *m, int argnum, MonoType *t,
7290 MonoMarshalSpec *spec, int conv_arg,
7291 MonoType **conv_arg_type, MarshalAction action)
7293 /* Ensure that we have marshalling info for this param */
7294 mono_marshal_load_type_info (mono_class_from_mono_type (t));
7296 if (spec && spec->native == MONO_NATIVE_CUSTOM)
7297 return emit_marshal_custom (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7299 if (spec && spec->native == MONO_NATIVE_ASANY)
7300 return emit_marshal_asany (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7303 case MONO_TYPE_VALUETYPE:
7304 if (t->data.klass == mono_defaults.handleref_class)
7305 return emit_marshal_handleref (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7307 return emit_marshal_vtype (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7308 case MONO_TYPE_STRING:
7309 return emit_marshal_string (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7310 case MONO_TYPE_CLASS:
7311 case MONO_TYPE_OBJECT:
7312 if (spec && spec->native == MONO_NATIVE_STRUCT)
7313 return emit_marshal_variant (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7316 if (spec && (spec->native == MONO_NATIVE_IUNKNOWN ||
7317 spec->native == MONO_NATIVE_IDISPATCH ||
7318 spec->native == MONO_NATIVE_INTERFACE))
7319 return mono_cominterop_emit_marshal_com_interface (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7322 if (mono_defaults.safehandle_class != NULL &&
7323 mono_class_is_subclass_of (t->data.klass, mono_defaults.safehandle_class, FALSE))
7324 return emit_marshal_safehandle (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7326 return emit_marshal_object (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7327 case MONO_TYPE_ARRAY:
7328 case MONO_TYPE_SZARRAY:
7329 return emit_marshal_array (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7330 case MONO_TYPE_BOOLEAN:
7331 return emit_marshal_boolean (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7333 return emit_marshal_ptr (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7334 case MONO_TYPE_CHAR:
7335 return emit_marshal_char (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7348 case MONO_TYPE_FNPTR:
7349 return emit_marshal_scalar (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7350 case MONO_TYPE_GENERICINST:
7351 if (mono_type_generic_inst_is_valuetype (t))
7352 return emit_marshal_vtype (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7354 return emit_marshal_object (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7361 * mono_marshal_emit_native_wrapper:
7362 * @image: the image to use for looking up custom marshallers
7363 * @sig: The signature of the native function
7364 * @piinfo: Marshalling information
7365 * @mspecs: Marshalling information
7366 * @aot: whenever the created method will be compiled by the AOT compiler
7367 * @method: if non-NULL, the pinvoke method to call
7368 * @check_exceptions: Whenever to check for pending exceptions after the native call
7370 * generates IL code for the pinvoke wrapper, the generated code calls @func.
7373 mono_marshal_emit_native_wrapper (MonoImage *image, MonoMethodBuilder *mb, MonoMethodSignature *sig, MonoMethodPInvoke *piinfo, MonoMarshalSpec **mspecs, gpointer func, gboolean aot, gboolean check_exceptions)
7375 EmitMarshalContext m;
7376 MonoMethodSignature *csig;
7378 int i, argnum, *tmp_locals;
7380 static MonoMethodSignature *get_last_error_sig = NULL;
7385 /* we copy the signature, so that we can set pinvoke to 0 */
7386 csig = signature_dup (mb->method->klass->image, sig);
7391 /* we allocate local for use with emit_struct_conv() */
7392 /* allocate local 0 (pointer) src_ptr */
7393 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7394 /* allocate local 1 (pointer) dst_ptr */
7395 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7396 /* allocate local 2 (boolean) delete_old */
7397 mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
7399 /* delete_old = FALSE */
7400 mono_mb_emit_icon (mb, 0);
7401 mono_mb_emit_stloc (mb, 2);
7403 if (!MONO_TYPE_IS_VOID(sig->ret)) {
7404 /* allocate local 3 to store the return value */
7405 mono_mb_add_local (mb, sig->ret);
7408 if (mspecs [0] && mspecs [0]->native == MONO_NATIVE_CUSTOM) {
7409 /* Return type custom marshaling */
7411 * Since we can't determine the return type of the unmanaged function,
7412 * we assume it returns a pointer, and pass that pointer to
7413 * MarshalNativeToManaged.
7415 csig->ret = &mono_defaults.int_class->byval_arg;
7418 /* we first do all conversions */
7419 tmp_locals = alloca (sizeof (int) * sig->param_count);
7420 m.orig_conv_args = alloca (sizeof (int) * (sig->param_count + 1));
7422 for (i = 0; i < sig->param_count; i ++) {
7423 tmp_locals [i] = emit_marshal (&m, i + sig->hasthis, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_CONV_IN);
7426 /* push all arguments */
7429 mono_mb_emit_byte (mb, CEE_LDARG_0);
7431 for (i = 0; i < sig->param_count; i++) {
7432 emit_marshal (&m, i + sig->hasthis, sig->params [i], mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_PUSH);
7435 /* call the native method */
7436 if (MONO_CLASS_IS_IMPORT (mb->method->klass)) {
7438 mono_mb_emit_cominterop_call (mb, csig, &piinfo->method);
7440 g_assert_not_reached ();
7445 /* Reuse the ICALL_ADDR opcode for pinvokes too */
7446 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7447 mono_mb_emit_op (mb, CEE_MONO_ICALL_ADDR, &piinfo->method);
7448 mono_mb_emit_calli (mb, csig);
7450 mono_mb_emit_native_call (mb, csig, func);
7454 /* Set LastError if needed */
7455 if (piinfo->piflags & PINVOKE_ATTRIBUTE_SUPPORTS_LAST_ERROR) {
7456 if (!get_last_error_sig) {
7457 get_last_error_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
7458 get_last_error_sig->ret = &mono_defaults.int_class->byval_arg;
7459 get_last_error_sig->pinvoke = 1;
7462 #ifdef PLATFORM_WIN32
7464 * Have to call GetLastError () early and without a wrapper, since various runtime components could
7465 * clobber its value.
7467 mono_mb_emit_native_call (mb, get_last_error_sig, GetLastError);
7468 mono_mb_emit_icall (mb, mono_marshal_set_last_error_windows);
7470 mono_mb_emit_icall (mb, mono_marshal_set_last_error);
7474 /* convert the result */
7475 if (!sig->ret->byref) {
7476 MonoMarshalSpec *spec = mspecs [0];
7477 type = sig->ret->type;
7479 if (spec && spec->native == MONO_NATIVE_CUSTOM) {
7480 emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7485 case MONO_TYPE_VOID:
7487 case MONO_TYPE_VALUETYPE:
7488 klass = sig->ret->data.klass;
7489 if (klass->enumtype) {
7490 type = mono_class_enum_basetype (sig->ret->data.klass)->type;
7493 emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7507 case MONO_TYPE_FNPTR:
7508 case MONO_TYPE_STRING:
7509 case MONO_TYPE_CLASS:
7510 case MONO_TYPE_OBJECT:
7511 case MONO_TYPE_BOOLEAN:
7512 case MONO_TYPE_ARRAY:
7513 case MONO_TYPE_SZARRAY:
7514 case MONO_TYPE_CHAR:
7516 case MONO_TYPE_GENERICINST:
7517 emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7519 case MONO_TYPE_TYPEDBYREF:
7521 g_warning ("return type 0x%02x unknown", sig->ret->type);
7522 g_assert_not_reached ();
7526 mono_mb_emit_stloc (mb, 3);
7530 * Need to call this after converting the result since MONO_VTADDR needs
7531 * to be adjacent to the call instruction.
7533 if (check_exceptions)
7534 emit_thread_interrupt_checkpoint (mb);
7536 /* we need to convert byref arguments back and free string arrays */
7537 for (i = 0; i < sig->param_count; i++) {
7538 MonoType *t = sig->params [i];
7539 MonoMarshalSpec *spec = mspecs [i + 1];
7541 argnum = i + sig->hasthis;
7543 if (spec && ((spec->native == MONO_NATIVE_CUSTOM) || (spec->native == MONO_NATIVE_ASANY))) {
7544 emit_marshal (&m, argnum, t, spec, tmp_locals [i], NULL, MARSHAL_ACTION_CONV_OUT);
7549 case MONO_TYPE_STRING:
7550 case MONO_TYPE_VALUETYPE:
7551 case MONO_TYPE_CLASS:
7552 case MONO_TYPE_OBJECT:
7553 case MONO_TYPE_SZARRAY:
7554 case MONO_TYPE_BOOLEAN:
7555 emit_marshal (&m, argnum, t, spec, tmp_locals [i], NULL, MARSHAL_ACTION_CONV_OUT);
7560 if (!MONO_TYPE_IS_VOID(sig->ret))
7561 mono_mb_emit_ldloc (mb, 3);
7563 mono_mb_emit_byte (mb, CEE_RET);
7567 * mono_marshal_get_native_wrapper:
7568 * @method: The MonoMethod to wrap.
7569 * @check_exceptions: Whenever to check for pending exceptions
7571 * generates IL code for the pinvoke wrapper (the generated method
7572 * calls the unmanaged code in piinfo->addr)
7575 mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions, gboolean aot)
7577 MonoMethodSignature *sig, *csig;
7578 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
7579 MonoMethodBuilder *mb;
7580 MonoMarshalSpec **mspecs;
7583 gboolean pinvoke = FALSE;
7586 const char *exc_class = "MissingMethodException";
7587 const char *exc_arg = NULL;
7589 g_assert (method != NULL);
7590 g_assert (mono_method_signature (method)->pinvoke);
7593 cache = get_cache (&method->klass->image->native_wrapper_aot_cache, mono_aligned_addr_hash, NULL);
7595 cache = get_cache (&method->klass->image->native_wrapper_cache, mono_aligned_addr_hash, NULL);
7596 if ((res = mono_marshal_find_in_cache (cache, method)))
7599 if (MONO_CLASS_IS_IMPORT (method->klass)) {
7601 return mono_cominterop_get_native_wrapper (method);
7603 g_assert_not_reached ();
7607 sig = mono_method_signature (method);
7609 if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
7610 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7613 if (!piinfo->addr) {
7615 if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)
7616 exc_arg = "Method contains unsupported native code";
7618 mono_lookup_pinvoke_call (method, &exc_class, &exc_arg);
7620 piinfo->addr = mono_lookup_internal_call (method);
7623 /* hack - redirect certain string constructors to CreateString */
7624 if (piinfo->addr == ves_icall_System_String_ctor_RedirectToCreateString) {
7625 g_assert (!pinvoke);
7626 g_assert (method->string_ctor);
7627 g_assert (sig->hasthis);
7629 /* CreateString returns a value */
7630 csig = signature_dup (method->klass->image, sig);
7631 csig->ret = &mono_defaults.string_class->byval_arg;
7635 while ((res = mono_class_get_methods (mono_defaults.string_class, &iter))) {
7636 if (!strcmp ("CreateString", res->name) &&
7637 mono_metadata_signature_equal (csig, mono_method_signature (res))) {
7639 g_assert (!(res->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL));
7640 g_assert (!(res->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL));
7642 /* create a wrapper to preserve .ctor in stack trace */
7643 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_MANAGED);
7645 mono_mb_emit_byte (mb, CEE_LDARG_0);
7646 for (i = 1; i <= csig->param_count; i++)
7647 mono_mb_emit_ldarg (mb, i);
7648 mono_mb_emit_managed_call (mb, res, NULL);
7649 mono_mb_emit_byte (mb, CEE_RET);
7651 /* use native_wrapper_cache because internal calls are looked up there */
7652 res = mono_mb_create_and_cache (cache, method,
7653 mb, csig, csig->param_count + 1);
7661 /* exception will be thrown */
7662 piinfo->addr = NULL;
7663 g_warning ("cannot find CreateString for .ctor");
7666 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_NATIVE);
7668 mb->method->save_lmf = 1;
7671 * In AOT mode and embedding scenarios, it is possible that the icall is not
7672 * registered in the runtime doing the AOT compilation.
7674 if (!piinfo->addr && !aot) {
7675 mono_mb_emit_exception (mb, exc_class, exc_arg);
7676 csig = signature_dup (method->klass->image, sig);
7678 res = mono_mb_create_and_cache (cache, method,
7679 mb, csig, csig->param_count + 16);
7684 /* internal calls: we simply push all arguments and call the method (no conversions) */
7685 if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
7687 /* hack - string constructors returns a value */
7688 if (method->string_ctor) {
7689 csig = signature_dup (method->klass->image, sig);
7690 csig->ret = &mono_defaults.string_class->byval_arg;
7695 mono_mb_emit_byte (mb, CEE_LDARG_0);
7697 for (i = 0; i < sig->param_count; i++)
7698 mono_mb_emit_ldarg (mb, i + sig->hasthis);
7701 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7702 mono_mb_emit_op (mb, CEE_MONO_ICALL_ADDR, &piinfo->method);
7703 mono_mb_emit_calli (mb, csig);
7705 g_assert (piinfo->addr);
7706 mono_mb_emit_native_call (mb, csig, piinfo->addr);
7708 if (check_exceptions)
7709 emit_thread_interrupt_checkpoint (mb);
7710 mono_mb_emit_byte (mb, CEE_RET);
7712 csig = signature_dup (method->klass->image, csig);
7714 res = mono_mb_create_and_cache (cache, method,
7715 mb, csig, csig->param_count + 16);
7722 g_assert (piinfo->addr);
7724 mspecs = g_new (MonoMarshalSpec*, sig->param_count + 1);
7725 mono_method_get_marshal_info (method, mspecs);
7727 mono_marshal_emit_native_wrapper (mb->method->klass->image, mb, sig, piinfo, mspecs, piinfo->addr, aot, check_exceptions);
7729 csig = signature_dup (method->klass->image, sig);
7731 res = mono_mb_create_and_cache (cache, method,
7732 mb, csig, csig->param_count + 16);
7735 for (i = sig->param_count; i >= 0; i--)
7737 mono_metadata_free_marshal_spec (mspecs [i]);
7740 /* printf ("CODE FOR %s: \n%s.\n", mono_method_full_name (res, TRUE), mono_disasm_code (0, res, ((MonoMethodNormal*)res)->header->code, ((MonoMethodNormal*)res)->header->code + ((MonoMethodNormal*)res)->header->code_size)); */
7746 * mono_marshal_get_native_func_wrapper:
7747 * @image: The image to use for memory allocation and for looking up custom marshallers.
7748 * @sig: The signature of the function
7749 * @func: The native function to wrap
7751 * Returns a wrapper method around native functions, similar to the pinvoke
7755 mono_marshal_get_native_func_wrapper (MonoImage *image, MonoMethodSignature *sig,
7756 MonoMethodPInvoke *piinfo, MonoMarshalSpec **mspecs, gpointer func)
7758 MonoMethodSignature *csig;
7760 MonoMethodBuilder *mb;
7765 cache = get_cache (&image->native_wrapper_cache, mono_aligned_addr_hash, NULL);
7766 if ((res = mono_marshal_find_in_cache (cache, func)))
7769 name = g_strdup_printf ("wrapper_native_%p", func);
7770 mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
7771 mb->method->save_lmf = 1;
7773 mono_marshal_emit_native_wrapper (image, mb, sig, piinfo, mspecs, func, FALSE, TRUE);
7775 csig = signature_dup (image, sig);
7777 res = mono_mb_create_and_cache (cache, func,
7778 mb, csig, csig->param_count + 16);
7781 /* printf ("CODE FOR %s: \n%s.\n", mono_method_full_name (res, TRUE), mono_disasm_code (0, res, ((MonoMethodNormal*)res)->header->code, ((MonoMethodNormal*)res)->header->code + ((MonoMethodNormal*)res)->header->code_size)); */
7786 /* FIXME: moving GC */
7788 mono_marshal_emit_managed_wrapper (MonoMethodBuilder *mb, MonoMethodSignature *invoke_sig, MonoMarshalSpec **mspecs, EmitMarshalContext* m, MonoMethod *method, MonoObject* this)
7790 MonoMethodSignature *sig, *csig;
7796 /* allocate local 0 (pointer) src_ptr */
7797 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7798 /* allocate local 1 (pointer) dst_ptr */
7799 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7800 /* allocate local 2 (boolean) delete_old */
7801 mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
7803 if (!MONO_TYPE_IS_VOID(sig->ret)) {
7804 /* allocate local 3 to store the return value */
7805 mono_mb_add_local (mb, sig->ret);
7808 mono_mb_emit_icon (mb, 0);
7809 mono_mb_emit_stloc (mb, 2);
7811 /* we first do all conversions */
7812 tmp_locals = alloca (sizeof (int) * sig->param_count);
7813 for (i = 0; i < sig->param_count; i ++) {
7814 MonoType *t = sig->params [i];
7817 case MONO_TYPE_OBJECT:
7818 case MONO_TYPE_CLASS:
7819 case MONO_TYPE_VALUETYPE:
7820 case MONO_TYPE_ARRAY:
7821 case MONO_TYPE_SZARRAY:
7822 case MONO_TYPE_STRING:
7823 case MONO_TYPE_BOOLEAN:
7824 tmp_locals [i] = emit_marshal (m, i, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_MANAGED_CONV_IN);
7833 emit_thread_interrupt_checkpoint (mb);
7835 /* fixme: howto handle this ? */
7838 /* FIXME: need a solution for the moving GC here */
7839 mono_mb_emit_ptr (mb, this);
7842 g_assert_not_reached ();
7846 for (i = 0; i < sig->param_count; i++) {
7847 MonoType *t = sig->params [i];
7849 if (tmp_locals [i]) {
7851 mono_mb_emit_ldloc_addr (mb, tmp_locals [i]);
7853 mono_mb_emit_ldloc (mb, tmp_locals [i]);
7856 mono_mb_emit_ldarg (mb, i);
7859 mono_mb_emit_managed_call (mb, method, NULL);
7861 if (mspecs [0] && mspecs [0]->native == MONO_NATIVE_CUSTOM) {
7862 emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
7865 if (!sig->ret->byref) {
7866 switch (sig->ret->type) {
7867 case MONO_TYPE_VOID:
7869 case MONO_TYPE_BOOLEAN:
7872 case MONO_TYPE_CHAR:
7884 case MONO_TYPE_OBJECT:
7885 mono_mb_emit_stloc (mb, 3);
7887 case MONO_TYPE_STRING:
7888 csig->ret = &mono_defaults.int_class->byval_arg;
7889 emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
7891 case MONO_TYPE_VALUETYPE:
7892 case MONO_TYPE_CLASS:
7893 case MONO_TYPE_SZARRAY:
7894 emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
7897 g_warning ("return type 0x%02x unknown", sig->ret->type);
7898 g_assert_not_reached ();
7901 mono_mb_emit_stloc (mb, 3);
7904 /* Convert byref arguments back */
7905 for (i = 0; i < sig->param_count; i ++) {
7906 MonoType *t = sig->params [i];
7907 MonoMarshalSpec *spec = mspecs [i + 1];
7909 if (spec && spec->native == MONO_NATIVE_CUSTOM) {
7910 emit_marshal (m, i, t, mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
7912 else if (t->byref) {
7914 case MONO_TYPE_CLASS:
7915 case MONO_TYPE_VALUETYPE:
7916 case MONO_TYPE_OBJECT:
7917 case MONO_TYPE_STRING:
7918 case MONO_TYPE_BOOLEAN:
7919 emit_marshal (m, i, t, mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
7923 else if (invoke_sig->params [i]->attrs & PARAM_ATTRIBUTE_OUT) {
7924 /* The [Out] information is encoded in the delegate signature */
7926 case MONO_TYPE_SZARRAY:
7927 case MONO_TYPE_CLASS:
7928 case MONO_TYPE_VALUETYPE:
7929 emit_marshal (m, i, invoke_sig->params [i], mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
7932 g_assert_not_reached ();
7937 if (m->retobj_var) {
7938 mono_mb_emit_ldloc (mb, m->retobj_var);
7939 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7940 mono_mb_emit_op (mb, CEE_MONO_RETOBJ, m->retobj_class);
7943 if (!MONO_TYPE_IS_VOID(sig->ret))
7944 mono_mb_emit_ldloc (mb, 3);
7945 mono_mb_emit_byte (mb, CEE_RET);
7951 mono_marshal_set_callconv_from_modopt (MonoMethod *method, MonoMethodSignature *csig)
7953 MonoMethodSignature *sig;
7956 #ifdef PLATFORM_WIN32
7958 * Under windows, delegates passed to native code must use the STDCALL
7959 * calling convention.
7961 csig->call_convention = MONO_CALL_STDCALL;
7964 sig = mono_method_signature (method);
7966 /* Change default calling convention if needed */
7967 /* Why is this a modopt ? */
7968 if (sig->ret && sig->ret->num_mods) {
7969 for (i = 0; i < sig->ret->num_mods; ++i) {
7970 MonoClass *cmod_class = mono_class_get (method->klass->image, sig->ret->modifiers [i].token);
7971 g_assert (cmod_class);
7972 if ((cmod_class->image == mono_defaults.corlib) && !strcmp (cmod_class->name_space, "System.Runtime.CompilerServices")) {
7973 if (!strcmp (cmod_class->name, "CallConvCdecl"))
7974 csig->call_convention = MONO_CALL_C;
7975 else if (!strcmp (cmod_class->name, "CallConvStdcall"))
7976 csig->call_convention = MONO_CALL_STDCALL;
7977 else if (!strcmp (cmod_class->name, "CallConvFastcall"))
7978 csig->call_convention = MONO_CALL_FASTCALL;
7979 else if (!strcmp (cmod_class->name, "CallConvThiscall"))
7980 csig->call_convention = MONO_CALL_THISCALL;
7987 * generates IL code to call managed methods from unmanaged code
7990 mono_marshal_get_managed_wrapper (MonoMethod *method, MonoClass *delegate_klass, MonoObject *this)
7992 static MonoClass *UnmanagedFunctionPointerAttribute;
7993 MonoMethodSignature *sig, *csig, *invoke_sig;
7994 MonoMethodBuilder *mb;
7995 MonoMethod *res, *invoke;
7996 MonoMarshalSpec **mspecs;
7997 MonoMethodPInvoke piinfo;
8000 EmitMarshalContext m;
8002 g_assert (method != NULL);
8003 g_assert (!mono_method_signature (method)->pinvoke);
8006 * FIXME: Should cache the method+delegate type pair, since the same method
8007 * could be called with different delegates, thus different marshalling
8010 cache = get_cache (&method->klass->image->managed_wrapper_cache, mono_aligned_addr_hash, NULL);
8011 if (!this && (res = mono_marshal_find_in_cache (cache, method)))
8014 invoke = mono_class_get_method_from_name (delegate_klass, "Invoke", mono_method_signature (method)->param_count);
8015 invoke_sig = mono_method_signature (invoke);
8017 mspecs = g_new0 (MonoMarshalSpec*, mono_method_signature (invoke)->param_count + 1);
8018 mono_method_get_marshal_info (invoke, mspecs);
8020 sig = mono_method_signature (method);
8022 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
8025 /* we copy the signature, so that we can modify it */
8027 /* Need to free this later */
8028 csig = mono_metadata_signature_dup (sig);
8030 csig = signature_dup (method->klass->image, sig);
8039 m.image = method->klass->image;
8041 mono_marshal_set_callconv_from_modopt (invoke, csig);
8043 /* Handle the UnmanagedFunctionPointerAttribute */
8044 if (!UnmanagedFunctionPointerAttribute)
8045 UnmanagedFunctionPointerAttribute = mono_class_from_name (mono_defaults.corlib, "System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute");
8047 /* The attribute is only available in Net 2.0 */
8048 if (UnmanagedFunctionPointerAttribute) {
8049 MonoReflectionUnmanagedFunctionPointerAttribute *attr;
8050 MonoCustomAttrInfo *cinfo;
8053 * The pinvoke attributes are stored in a real custom attribute so we have to
8056 cinfo = mono_custom_attrs_from_class (delegate_klass);
8058 attr = (MonoReflectionUnmanagedFunctionPointerAttribute*)mono_custom_attrs_get_attr (cinfo, UnmanagedFunctionPointerAttribute);
8060 memset (&piinfo, 0, sizeof (piinfo));
8062 piinfo.piflags = (attr->call_conv << 8) | (attr->charset ? (attr->charset - 1) * 2 : 1) | attr->set_last_error;
8064 csig->call_convention = attr->call_conv - 1;
8067 mono_custom_attrs_free (cinfo);
8071 mono_marshal_emit_managed_wrapper (mb, invoke_sig, mspecs, &m, method, this);
8074 res = mono_mb_create_and_cache (cache, method,
8075 mb, csig, sig->param_count + 16);
8078 res = mono_mb_create_method (mb, csig, sig->param_count + 16);
8082 for (i = mono_method_signature (invoke)->param_count; i >= 0; i--)
8084 mono_metadata_free_marshal_spec (mspecs [i]);
8087 /* printf ("CODE FOR %s: \n%s.\n", mono_method_full_name (res, TRUE), mono_disasm_code (0, res, ((MonoMethodNormal*)res)->header->code, ((MonoMethodNormal*)res)->header->code + ((MonoMethodNormal*)res)->header->code_size)); */
8093 mono_marshal_get_vtfixup_ftnptr (MonoImage *image, guint32 token, guint16 type)
8096 MonoMethodSignature *sig;
8097 MonoMethodBuilder *mb;
8102 method = mono_get_method (image, token, NULL);
8105 if (type & (VTFIXUP_TYPE_FROM_UNMANAGED | VTFIXUP_TYPE_FROM_UNMANAGED_RETAIN_APPDOMAIN)) {
8106 MonoMethodSignature *csig;
8107 MonoMarshalSpec **mspecs;
8108 EmitMarshalContext m;
8110 sig = mono_method_signature (method);
8111 g_assert (!sig->hasthis);
8113 mspecs = g_new0 (MonoMarshalSpec*, sig->param_count + 1);
8114 mono_method_get_marshal_info (method, mspecs);
8116 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
8117 csig = signature_dup (image, sig);
8128 mono_marshal_set_callconv_from_modopt (method, csig);
8130 /* FIXME: Implement VTFIXUP_TYPE_FROM_UNMANAGED_RETAIN_APPDOMAIN. */
8132 mono_marshal_emit_managed_wrapper (mb, sig, mspecs, &m, method, NULL);
8135 method = mono_mb_create_method (mb, csig, sig->param_count + 16);
8138 for (i = sig->param_count; i >= 0; i--)
8140 mono_metadata_free_marshal_spec (mspecs [i]);
8143 return mono_compile_method (method);
8146 sig = mono_method_signature (method);
8147 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_MANAGED);
8149 param_count = sig->param_count + sig->hasthis;
8150 for (i = 0; i < param_count; i++)
8151 mono_mb_emit_ldarg (mb, i);
8153 if (type & VTFIXUP_TYPE_CALL_MOST_DERIVED)
8154 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
8156 mono_mb_emit_op (mb, CEE_CALL, method);
8157 mono_mb_emit_byte (mb, CEE_RET);
8160 method = mono_mb_create_method (mb, sig, param_count);
8163 return mono_compile_method (method);
8166 static MonoReflectionType *
8167 type_from_handle (MonoType *handle)
8169 MonoDomain *domain = mono_domain_get ();
8170 MonoClass *klass = mono_class_from_mono_type (handle);
8172 MONO_ARCH_SAVE_REGS;
8174 mono_class_init (klass);
8175 return mono_type_get_object (domain, handle);
8179 * mono_marshal_get_isinst:
8180 * @klass: the type of the field
8182 * This method generates a function which can be used to check if an object is
8183 * an instance of the given type, icluding the case where the object is a proxy.
8184 * The generated function has the following signature:
8185 * MonoObject* __isinst_wrapper_ (MonoObject *obj)
8188 mono_marshal_get_isinst (MonoClass *klass)
8190 static MonoMethodSignature *isint_sig = NULL;
8193 int pos_was_ok, pos_failed, pos_end, pos_end2;
8195 MonoMethodBuilder *mb;
8197 cache = get_cache (&klass->image->isinst_cache, mono_aligned_addr_hash, NULL);
8198 if ((res = mono_marshal_find_in_cache (cache, klass)))
8202 isint_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
8203 isint_sig->params [0] = &mono_defaults.object_class->byval_arg;
8204 isint_sig->ret = &mono_defaults.object_class->byval_arg;
8205 isint_sig->pinvoke = 0;
8208 name = g_strdup_printf ("__isinst_wrapper_%s", klass->name);
8209 mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_ISINST);
8212 mb->method->save_lmf = 1;
8214 /* check if the object is a proxy that needs special cast */
8215 mono_mb_emit_ldarg (mb, 0);
8216 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8217 mono_mb_emit_op (mb, CEE_MONO_CISINST, klass);
8219 /* The result of MONO_ISINST can be:
8220 0) the type check succeeded
8221 1) the type check did not succeed
8222 2) a CanCastTo call is needed */
8224 mono_mb_emit_byte (mb, CEE_DUP);
8225 pos_was_ok = mono_mb_emit_branch (mb, CEE_BRFALSE);
8227 mono_mb_emit_byte (mb, CEE_LDC_I4_2);
8228 pos_failed = mono_mb_emit_branch (mb, CEE_BNE_UN);
8230 /* get the real proxy from the transparent proxy*/
8232 mono_mb_emit_ldarg (mb, 0);
8233 mono_mb_emit_managed_call (mb, mono_marshal_get_proxy_cancast (klass), NULL);
8234 pos_end = mono_mb_emit_branch (mb, CEE_BR);
8238 mono_mb_patch_branch (mb, pos_failed);
8239 mono_mb_emit_byte (mb, CEE_LDNULL);
8240 pos_end2 = mono_mb_emit_branch (mb, CEE_BR);
8244 mono_mb_patch_branch (mb, pos_was_ok);
8245 mono_mb_emit_byte (mb, CEE_POP);
8246 mono_mb_emit_ldarg (mb, 0);
8250 mono_mb_patch_branch (mb, pos_end);
8251 mono_mb_patch_branch (mb, pos_end2);
8252 mono_mb_emit_byte (mb, CEE_RET);
8254 res = mono_mb_create_and_cache (cache, klass, mb, isint_sig, isint_sig->param_count + 16);
8261 * mono_marshal_get_castclass:
8262 * @klass: the type of the field
8264 * This method generates a function which can be used to cast an object to
8265 * an instance of the given type, icluding the case where the object is a proxy.
8266 * The generated function has the following signature:
8267 * MonoObject* __castclass_wrapper_ (MonoObject *obj)
8270 mono_marshal_get_castclass (MonoClass *klass)
8272 static MonoMethodSignature *castclass_sig = NULL;
8275 int pos_was_ok, pos_was_ok2;
8277 MonoMethodBuilder *mb;
8279 cache = get_cache (&klass->image->castclass_cache, mono_aligned_addr_hash, NULL);
8280 if ((res = mono_marshal_find_in_cache (cache, klass)))
8283 if (!castclass_sig) {
8284 castclass_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
8285 castclass_sig->params [0] = &mono_defaults.object_class->byval_arg;
8286 castclass_sig->ret = &mono_defaults.object_class->byval_arg;
8287 castclass_sig->pinvoke = 0;
8290 name = g_strdup_printf ("__castclass_wrapper_%s", klass->name);
8291 mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_CASTCLASS);
8294 mb->method->save_lmf = 1;
8296 /* check if the object is a proxy that needs special cast */
8297 mono_mb_emit_ldarg (mb, 0);
8298 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8299 mono_mb_emit_op (mb, CEE_MONO_CCASTCLASS, klass);
8301 /* The result of MONO_ISINST can be:
8302 0) the cast is valid
8303 1) cast of unknown proxy type
8304 or an exception if the cast is is invalid
8307 pos_was_ok = mono_mb_emit_branch (mb, CEE_BRFALSE);
8309 /* get the real proxy from the transparent proxy*/
8311 mono_mb_emit_ldarg (mb, 0);
8312 mono_mb_emit_managed_call (mb, mono_marshal_get_proxy_cancast (klass), NULL);
8313 pos_was_ok2 = mono_mb_emit_branch (mb, CEE_BRTRUE);
8316 mono_mb_emit_exception (mb, "InvalidCastException", NULL);
8319 mono_mb_patch_branch (mb, pos_was_ok);
8320 mono_mb_patch_branch (mb, pos_was_ok2);
8321 mono_mb_emit_ldarg (mb, 0);
8324 mono_mb_emit_byte (mb, CEE_RET);
8326 res = mono_mb_create_and_cache (cache, klass, mb, castclass_sig, castclass_sig->param_count + 16);
8333 mono_marshal_get_proxy_cancast (MonoClass *klass)
8335 static MonoMethodSignature *isint_sig = NULL;
8338 int pos_failed, pos_end;
8340 MonoMethod *can_cast_to;
8341 MonoMethodDesc *desc;
8342 MonoMethodBuilder *mb;
8344 cache = get_cache (&klass->image->proxy_isinst_cache, mono_aligned_addr_hash, NULL);
8345 if ((res = mono_marshal_find_in_cache (cache, klass)))
8349 isint_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
8350 isint_sig->params [0] = &mono_defaults.object_class->byval_arg;
8351 isint_sig->ret = &mono_defaults.object_class->byval_arg;
8352 isint_sig->pinvoke = 0;
8355 name = g_strdup_printf ("__proxy_isinst_wrapper_%s", klass->name);
8356 mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_PROXY_ISINST);
8359 mb->method->save_lmf = 1;
8361 /* get the real proxy from the transparent proxy*/
8362 mono_mb_emit_ldarg (mb, 0);
8363 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoTransparentProxy, rp));
8364 mono_mb_emit_byte (mb, CEE_LDIND_REF);
8366 /* get the reflection type from the type handle */
8367 mono_mb_emit_ptr (mb, &klass->byval_arg);
8368 mono_mb_emit_icall (mb, type_from_handle);
8370 mono_mb_emit_ldarg (mb, 0);
8372 /* make the call to CanCastTo (type, ob) */
8373 desc = mono_method_desc_new ("IRemotingTypeInfo:CanCastTo", FALSE);
8374 can_cast_to = mono_method_desc_search_in_class (desc, mono_defaults.iremotingtypeinfo_class);
8375 g_assert (can_cast_to);
8376 mono_method_desc_free (desc);
8377 mono_mb_emit_op (mb, CEE_CALLVIRT, can_cast_to);
8379 pos_failed = mono_mb_emit_branch (mb, CEE_BRFALSE);
8381 /* Upgrade the proxy vtable by calling: mono_upgrade_remote_class_wrapper (type, ob)*/
8382 mono_mb_emit_ptr (mb, &klass->byval_arg);
8383 mono_mb_emit_icall (mb, type_from_handle);
8384 mono_mb_emit_ldarg (mb, 0);
8386 mono_mb_emit_icall (mb, mono_upgrade_remote_class_wrapper);
8387 emit_thread_interrupt_checkpoint (mb);
8389 mono_mb_emit_ldarg (mb, 0);
8390 pos_end = mono_mb_emit_branch (mb, CEE_BR);
8394 mono_mb_patch_branch (mb, pos_failed);
8395 mono_mb_emit_byte (mb, CEE_LDNULL);
8399 mono_mb_patch_branch (mb, pos_end);
8400 mono_mb_emit_byte (mb, CEE_RET);
8402 res = mono_mb_create_and_cache (cache, klass, mb, isint_sig, isint_sig->param_count + 16);
8409 mono_upgrade_remote_class_wrapper (MonoReflectionType *rtype, MonoTransparentProxy *tproxy)
8412 MonoDomain *domain = ((MonoObject*)tproxy)->vtable->domain;
8413 klass = mono_class_from_mono_type (rtype->type);
8414 mono_upgrade_remote_class (domain, (MonoObject*)tproxy, klass);
8418 * mono_marshal_get_struct_to_ptr:
8421 * generates IL code for StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld)
8424 mono_marshal_get_struct_to_ptr (MonoClass *klass)
8426 MonoMethodBuilder *mb;
8427 static MonoMethod *stoptr = NULL;
8430 g_assert (klass != NULL);
8432 mono_marshal_load_type_info (klass);
8434 if (klass->marshal_info->str_to_ptr)
8435 return klass->marshal_info->str_to_ptr;
8438 stoptr = mono_class_get_method_from_name (mono_defaults.marshal_class, "StructureToPtr", 3);
8441 mb = mono_mb_new (klass, stoptr->name, MONO_WRAPPER_UNKNOWN);
8443 if (klass->blittable) {
8444 mono_mb_emit_byte (mb, CEE_LDARG_1);
8445 mono_mb_emit_byte (mb, CEE_LDARG_0);
8446 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
8447 mono_mb_emit_icon (mb, mono_class_value_size (klass, NULL));
8448 mono_mb_emit_byte (mb, CEE_PREFIX1);
8449 mono_mb_emit_byte (mb, CEE_CPBLK);
8452 /* allocate local 0 (pointer) src_ptr */
8453 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8454 /* allocate local 1 (pointer) dst_ptr */
8455 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8456 /* allocate local 2 (boolean) delete_old */
8457 mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
8458 mono_mb_emit_byte (mb, CEE_LDARG_2);
8459 mono_mb_emit_stloc (mb, 2);
8461 /* initialize src_ptr to point to the start of object data */
8462 mono_mb_emit_byte (mb, CEE_LDARG_0);
8463 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
8464 mono_mb_emit_stloc (mb, 0);
8466 /* initialize dst_ptr */
8467 mono_mb_emit_byte (mb, CEE_LDARG_1);
8468 mono_mb_emit_stloc (mb, 1);
8470 emit_struct_conv (mb, klass, FALSE);
8473 mono_mb_emit_byte (mb, CEE_RET);
8475 res = mono_mb_create_method (mb, mono_signature_no_pinvoke (stoptr), 0);
8478 klass->marshal_info->str_to_ptr = res;
8483 * mono_marshal_get_ptr_to_struct:
8486 * generates IL code for PtrToStructure (IntPtr src, object structure)
8489 mono_marshal_get_ptr_to_struct (MonoClass *klass)
8491 MonoMethodBuilder *mb;
8492 static MonoMethodSignature *ptostr = NULL;
8495 g_assert (klass != NULL);
8497 mono_marshal_load_type_info (klass);
8499 if (klass->marshal_info->ptr_to_str)
8500 return klass->marshal_info->ptr_to_str;
8503 MonoMethodSignature *sig;
8505 /* Create the signature corresponding to
8506 static void PtrToStructure (IntPtr ptr, object structure);
8507 defined in class/corlib/System.Runtime.InteropServices/Marshal.cs */
8508 sig = mono_create_icall_signature ("void ptr object");
8509 sig = signature_dup (mono_defaults.corlib, sig);
8511 mono_memory_barrier ();
8515 mb = mono_mb_new (klass, "PtrToStructure", MONO_WRAPPER_UNKNOWN);
8517 if (klass->blittable) {
8518 mono_mb_emit_byte (mb, CEE_LDARG_1);
8519 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
8520 mono_mb_emit_byte (mb, CEE_LDARG_0);
8521 mono_mb_emit_icon (mb, mono_class_value_size (klass, NULL));
8522 mono_mb_emit_byte (mb, CEE_PREFIX1);
8523 mono_mb_emit_byte (mb, CEE_CPBLK);
8526 /* allocate local 0 (pointer) src_ptr */
8527 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8528 /* allocate local 1 (pointer) dst_ptr */
8529 mono_mb_add_local (mb, &klass->this_arg);
8531 /* initialize src_ptr to point to the start of object data */
8532 mono_mb_emit_byte (mb, CEE_LDARG_0);
8533 mono_mb_emit_stloc (mb, 0);
8535 /* initialize dst_ptr */
8536 mono_mb_emit_byte (mb, CEE_LDARG_1);
8537 mono_mb_emit_op (mb, CEE_UNBOX, klass);
8538 mono_mb_emit_stloc (mb, 1);
8540 emit_struct_conv (mb, klass, TRUE);
8543 mono_mb_emit_byte (mb, CEE_RET);
8545 res = mono_mb_create_method (mb, ptostr, 0);
8548 klass->marshal_info->ptr_to_str = res;
8553 * generates IL code for the synchronized wrapper: the generated method
8554 * calls METHOD while locking 'this' or the parent type.
8557 mono_marshal_get_synchronized_wrapper (MonoMethod *method)
8559 static MonoMethod *enter_method, *exit_method, *gettypefromhandle_method;
8560 MonoMethodSignature *sig;
8561 MonoExceptionClause *clause;
8562 MonoMethodBuilder *mb;
8565 int i, pos, this_local, ret_local = 0;
8569 if (method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED)
8572 cache = get_cache (&method->klass->image->synchronized_cache, mono_aligned_addr_hash, NULL);
8573 if ((res = mono_marshal_find_in_cache (cache, method)))
8576 sig = signature_dup (method->klass->image, mono_method_signature (method));
8579 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_SYNCHRONIZED);
8582 if (!MONO_TYPE_IS_VOID (sig->ret))
8583 ret_local = mono_mb_add_local (mb, sig->ret);
8585 if (method->klass->valuetype && !(method->flags & MONO_METHOD_ATTR_STATIC)) {
8586 mono_class_set_failure (method->klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
8587 /* This will throw the type load exception when the wrapper is compiled */
8588 mono_mb_emit_byte (mb, CEE_LDNULL);
8589 mono_mb_emit_op (mb, CEE_ISINST, method->klass);
8590 mono_mb_emit_byte (mb, CEE_POP);
8592 if (!MONO_TYPE_IS_VOID (sig->ret))
8593 mono_mb_emit_ldloc (mb, ret_local);
8594 mono_mb_emit_byte (mb, CEE_RET);
8596 res = mono_mb_create_and_cache (cache, method,
8597 mb, sig, sig->param_count + 16);
8604 this_local = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
8606 clause = mono_image_alloc0 (method->klass->image, sizeof (MonoExceptionClause));
8607 clause->flags = MONO_EXCEPTION_CLAUSE_FINALLY;
8609 mono_loader_lock ();
8611 if (!enter_method) {
8612 MonoMethodDesc *desc;
8614 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
8615 enter_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
8616 g_assert (enter_method);
8617 mono_method_desc_free (desc);
8619 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
8620 exit_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
8621 g_assert (exit_method);
8622 mono_method_desc_free (desc);
8624 desc = mono_method_desc_new ("Type:GetTypeFromHandle", FALSE);
8625 gettypefromhandle_method = mono_method_desc_search_in_class (desc, mono_defaults.monotype_class->parent);
8626 g_assert (gettypefromhandle_method);
8627 mono_method_desc_free (desc);
8630 mono_loader_unlock ();
8632 /* Push this or the type object */
8633 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
8634 /* We have special handling for this in the JIT */
8635 int index = mono_mb_add_data (mb, method->klass);
8636 mono_mb_add_data (mb, mono_defaults.typehandle_class);
8637 mono_mb_emit_byte (mb, CEE_LDTOKEN);
8638 mono_mb_emit_i4 (mb, index);
8640 mono_mb_emit_managed_call (mb, gettypefromhandle_method, NULL);
8643 mono_mb_emit_ldarg (mb, 0);
8644 mono_mb_emit_stloc (mb, this_local);
8646 /* Call Monitor::Enter() */
8647 mono_mb_emit_ldloc (mb, this_local);
8648 mono_mb_emit_managed_call (mb, enter_method, NULL);
8650 clause->try_offset = mono_mb_get_label (mb);
8652 /* Call the method */
8654 mono_mb_emit_ldarg (mb, 0);
8655 for (i = 0; i < sig->param_count; i++)
8656 mono_mb_emit_ldarg (mb, i + (sig->hasthis == TRUE));
8658 mono_mb_emit_managed_call (mb, method, NULL);
8660 if (!MONO_TYPE_IS_VOID (sig->ret))
8661 mono_mb_emit_stloc (mb, ret_local);
8663 pos = mono_mb_emit_branch (mb, CEE_LEAVE);
8665 clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
8666 clause->handler_offset = mono_mb_get_label (mb);
8668 /* Call Monitor::Exit() */
8669 mono_mb_emit_ldloc (mb, this_local);
8670 mono_mb_emit_managed_call (mb, exit_method, NULL);
8671 mono_mb_emit_byte (mb, CEE_ENDFINALLY);
8673 clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
8675 mono_mb_patch_branch (mb, pos);
8676 if (!MONO_TYPE_IS_VOID (sig->ret))
8677 mono_mb_emit_ldloc (mb, ret_local);
8678 mono_mb_emit_byte (mb, CEE_RET);
8680 mono_mb_set_clauses (mb, 1, clause);
8682 res = mono_mb_create_and_cache (cache, method,
8683 mb, sig, sig->param_count + 16);
8691 * the returned method calls 'method' unboxing the this argument
8694 mono_marshal_get_unbox_wrapper (MonoMethod *method)
8696 MonoMethodSignature *sig = mono_method_signature (method);
8698 MonoMethodBuilder *mb;
8702 cache = get_cache (&method->klass->image->unbox_wrapper_cache, mono_aligned_addr_hash, NULL);
8703 if ((res = mono_marshal_find_in_cache (cache, method)))
8706 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNBOX);
8708 g_assert (sig->hasthis);
8710 mono_mb_emit_ldarg (mb, 0);
8711 mono_mb_emit_icon (mb, sizeof (MonoObject));
8712 mono_mb_emit_byte (mb, CEE_ADD);
8713 for (i = 0; i < sig->param_count; ++i)
8714 mono_mb_emit_ldarg (mb, i + 1);
8715 mono_mb_emit_managed_call (mb, method, NULL);
8716 mono_mb_emit_byte (mb, CEE_RET);
8718 res = mono_mb_create_and_cache (cache, method,
8719 mb, sig, sig->param_count + 16);
8722 /* printf ("CODE FOR %s: \n%s.\n", mono_method_full_name (res, TRUE), mono_disasm_code (0, res, ((MonoMethodNormal*)res)->header->code, ((MonoMethodNormal*)res)->header->code + ((MonoMethodNormal*)res)->header->code_size)); */
8728 mono_marshal_get_stelemref ()
8730 static MonoMethod* ret = NULL;
8731 MonoMethodSignature *sig;
8732 MonoMethodBuilder *mb;
8734 guint32 b1, b2, b3, b4;
8737 int array_slot_addr;
8742 mb = mono_mb_new (mono_defaults.object_class, "stelemref", MONO_WRAPPER_STELEMREF);
8745 sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
8747 /* void stelemref (void* array, int idx, void* value) */
8748 sig->ret = &mono_defaults.void_class->byval_arg;
8749 sig->params [0] = &mono_defaults.object_class->byval_arg;
8750 sig->params [1] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
8751 sig->params [2] = &mono_defaults.object_class->byval_arg;
8753 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8754 vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8755 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
8759 <ldelema (bound check)>
8763 aklass = array->vtable->klass->element_class;
8764 vklass = value->vtable->klass;
8766 if (vklass->idepth < aklass->idepth)
8769 if (vklass->supertypes [aklass->idepth - 1] != aklass)
8773 *array_slot_addr = value;
8777 if (mono_object_isinst (value, aklass))
8780 throw new ArrayTypeMismatchException ();
8783 /* ldelema (implicit bound check) */
8784 mono_mb_emit_ldarg (mb, 0);
8785 mono_mb_emit_ldarg (mb, 1);
8786 mono_mb_emit_op (mb, CEE_LDELEMA, mono_defaults.object_class);
8787 mono_mb_emit_stloc (mb, array_slot_addr);
8789 /* if (!value) goto do_store */
8790 mono_mb_emit_ldarg (mb, 2);
8791 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
8793 /* aklass = array->vtable->klass->element_class */
8794 mono_mb_emit_ldarg (mb, 0);
8795 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoObject, vtable));
8796 mono_mb_emit_byte (mb, CEE_LDIND_I);
8797 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoVTable, klass));
8798 mono_mb_emit_byte (mb, CEE_LDIND_I);
8799 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoClass, element_class));
8800 mono_mb_emit_byte (mb, CEE_LDIND_I);
8801 mono_mb_emit_stloc (mb, aklass);
8803 /* vklass = value->vtable->klass */
8804 mono_mb_emit_ldarg (mb, 2);
8805 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoObject, vtable));
8806 mono_mb_emit_byte (mb, CEE_LDIND_I);
8807 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoVTable, klass));
8808 mono_mb_emit_byte (mb, CEE_LDIND_I);
8809 mono_mb_emit_stloc (mb, vklass);
8811 /* if (vklass->idepth < aklass->idepth) goto failue */
8812 mono_mb_emit_ldloc (mb, vklass);
8813 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoClass, idepth));
8814 mono_mb_emit_byte (mb, CEE_LDIND_U2);
8816 mono_mb_emit_ldloc (mb, aklass);
8817 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoClass, idepth));
8818 mono_mb_emit_byte (mb, CEE_LDIND_U2);
8820 b2 = mono_mb_emit_branch (mb, CEE_BLT_UN);
8822 /* if (vklass->supertypes [aklass->idepth - 1] != aklass) goto failure */
8823 mono_mb_emit_ldloc (mb, vklass);
8824 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoClass, supertypes));
8825 mono_mb_emit_byte (mb, CEE_LDIND_I);
8827 mono_mb_emit_ldloc (mb, aklass);
8828 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoClass, idepth));
8829 mono_mb_emit_byte (mb, CEE_LDIND_U2);
8830 mono_mb_emit_icon (mb, 1);
8831 mono_mb_emit_byte (mb, CEE_SUB);
8832 mono_mb_emit_icon (mb, sizeof (void*));
8833 mono_mb_emit_byte (mb, CEE_MUL);
8834 mono_mb_emit_byte (mb, CEE_ADD);
8835 mono_mb_emit_byte (mb, CEE_LDIND_I);
8837 mono_mb_emit_ldloc (mb, aklass);
8839 b3 = mono_mb_emit_branch (mb, CEE_BNE_UN);
8841 copy_pos = mono_mb_get_label (mb);
8843 mono_mb_patch_branch (mb, b1);
8844 mono_mb_emit_ldloc (mb, array_slot_addr);
8845 mono_mb_emit_ldarg (mb, 2);
8846 mono_mb_emit_byte (mb, CEE_STIND_REF);
8848 mono_mb_emit_byte (mb, CEE_RET);
8851 mono_mb_patch_branch (mb, b2);
8852 mono_mb_patch_branch (mb, b3);
8854 mono_mb_emit_ldarg (mb, 2);
8855 mono_mb_emit_ldloc (mb, aklass);
8856 mono_mb_emit_icall (mb, mono_object_isinst);
8858 b4 = mono_mb_emit_branch (mb, CEE_BRTRUE);
8859 mono_mb_patch_addr (mb, b4, copy_pos - (b4 + 4));
8860 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
8862 mono_mb_emit_byte (mb, CEE_RET);
8863 ret = mono_mb_create_method (mb, sig, 4);
8874 /* LOCKING: vars accessed under the marshal lock */
8875 static ArrayElemAddr *elem_addr_cache = NULL;
8876 static int elem_addr_cache_size = 0;
8877 static int elem_addr_cache_next = 0;
8880 * mono_marshal_get_array_address:
8881 * @rank: rank of the array type
8882 * @elem_size: size in bytes of an element of an array.
8884 * Returns a MonoMethd that implements the code to get the address
8885 * of an element in a multi-dimenasional array of @rank dimensions.
8886 * The returned method takes an array as the first argument and then
8887 * @rank indexes for the @rank dimensions.
8890 mono_marshal_get_array_address (int rank, int elem_size)
8893 MonoMethodBuilder *mb;
8894 MonoMethodSignature *sig;
8895 int i, bounds, ind, realidx;
8896 int branch_pos, *branch_positions;
8900 mono_marshal_lock ();
8901 for (i = 0; i < elem_addr_cache_next; ++i) {
8902 if (elem_addr_cache [i].rank == rank && elem_addr_cache [i].elem_size == elem_size) {
8903 ret = elem_addr_cache [i].method;
8907 mono_marshal_unlock ();
8911 branch_positions = g_new0 (int, rank);
8913 sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1 + rank);
8915 /* void* address (void* array, int idx0, int idx1, int idx2, ...) */
8916 sig->ret = &mono_defaults.int_class->byval_arg;
8917 sig->params [0] = &mono_defaults.object_class->byval_arg;
8918 for (i = 0; i < rank; ++i) {
8919 sig->params [i + 1] = &mono_defaults.int32_class->byval_arg;
8922 mb = mono_mb_new (mono_defaults.object_class, "ElementAddr", MONO_WRAPPER_MANAGED_TO_MANAGED);
8924 bounds = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8925 ind = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
8926 realidx = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
8928 /* bounds = array->bounds; */
8929 mono_mb_emit_ldarg (mb, 0);
8930 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoArray, bounds));
8931 mono_mb_emit_byte (mb, CEE_LDIND_I);
8932 mono_mb_emit_stloc (mb, bounds);
8934 /* ind is the overall element index, realidx is the partial index in a single dimension */
8935 /* ind = idx0 - bounds [0].lower_bound */
8936 mono_mb_emit_ldarg (mb, 1);
8937 mono_mb_emit_ldloc (mb, bounds);
8938 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
8939 mono_mb_emit_byte (mb, CEE_ADD);
8940 mono_mb_emit_byte (mb, CEE_LDIND_I4);
8941 mono_mb_emit_byte (mb, CEE_SUB);
8942 mono_mb_emit_stloc (mb, ind);
8943 /* if (ind >= bounds [0].length) goto exeception; */
8944 mono_mb_emit_ldloc (mb, ind);
8945 mono_mb_emit_ldloc (mb, bounds);
8946 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoArrayBounds, length));
8947 mono_mb_emit_byte (mb, CEE_ADD);
8948 mono_mb_emit_byte (mb, CEE_LDIND_I4);
8949 /* note that we use unsigned comparison */
8950 branch_pos = mono_mb_emit_branch (mb, CEE_BGE_UN);
8952 /* For large ranks (> 4?) use a loop n IL later to reduce code size.
8953 * We could also decide to ignore the passed elem_size and get it
8954 * from the array object, to reduce the number of methods we generate:
8955 * the additional cost is 3 memory loads and a non-immediate mul.
8957 for (i = 1; i < rank; ++i) {
8958 /* realidx = idxi - bounds [i].lower_bound */
8959 mono_mb_emit_ldarg (mb, 1 + i);
8960 mono_mb_emit_ldloc (mb, bounds);
8961 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + G_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
8962 mono_mb_emit_byte (mb, CEE_ADD);
8963 mono_mb_emit_byte (mb, CEE_LDIND_I4);
8964 mono_mb_emit_byte (mb, CEE_SUB);
8965 mono_mb_emit_stloc (mb, realidx);
8966 /* if (realidx >= bounds [i].length) goto exeception; */
8967 mono_mb_emit_ldloc (mb, realidx);
8968 mono_mb_emit_ldloc (mb, bounds);
8969 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + G_STRUCT_OFFSET (MonoArrayBounds, length));
8970 mono_mb_emit_byte (mb, CEE_ADD);
8971 mono_mb_emit_byte (mb, CEE_LDIND_I4);
8972 branch_positions [i] = mono_mb_emit_branch (mb, CEE_BGE_UN);
8973 /* ind = ind * bounds [i].length + realidx */
8974 mono_mb_emit_ldloc (mb, ind);
8975 mono_mb_emit_ldloc (mb, bounds);
8976 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + G_STRUCT_OFFSET (MonoArrayBounds, length));
8977 mono_mb_emit_byte (mb, CEE_ADD);
8978 mono_mb_emit_byte (mb, CEE_LDIND_I4);
8979 mono_mb_emit_byte (mb, CEE_MUL);
8980 mono_mb_emit_ldloc (mb, realidx);
8981 mono_mb_emit_byte (mb, CEE_ADD);
8982 mono_mb_emit_stloc (mb, ind);
8985 /* return array->vector + ind * element_size */
8986 mono_mb_emit_ldarg (mb, 0);
8987 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoArray, vector));
8988 mono_mb_emit_ldloc (mb, ind);
8989 mono_mb_emit_icon (mb, elem_size);
8990 mono_mb_emit_byte (mb, CEE_MUL);
8991 mono_mb_emit_byte (mb, CEE_ADD);
8992 mono_mb_emit_byte (mb, CEE_RET);
8994 /* patch the branches to get here and throw */
8995 for (i = 1; i < rank; ++i) {
8996 mono_mb_patch_branch (mb, branch_positions [i]);
8998 mono_mb_patch_branch (mb, branch_pos);
8999 /* throw exception */
9000 mono_mb_emit_exception (mb, "IndexOutOfRangeException", NULL);
9002 g_free (branch_positions);
9003 ret = mono_mb_create_method (mb, sig, 4);
9006 /* cache the result */
9008 mono_marshal_lock ();
9009 for (i = 0; i < elem_addr_cache_next; ++i) {
9010 if (elem_addr_cache [i].rank == rank && elem_addr_cache [i].elem_size == elem_size) {
9011 /* FIXME: free ret */
9012 ret = elem_addr_cache [i].method;
9018 if (elem_addr_cache_next >= elem_addr_cache_size) {
9019 int new_size = elem_addr_cache_size + 4;
9020 ArrayElemAddr *new_array = g_new0 (ArrayElemAddr, new_size);
9021 memcpy (new_array, elem_addr_cache, elem_addr_cache_size * sizeof (ArrayElemAddr));
9022 g_free (elem_addr_cache);
9023 elem_addr_cache = new_array;
9024 elem_addr_cache_size = new_size;
9026 elem_addr_cache [elem_addr_cache_next].rank = rank;
9027 elem_addr_cache [elem_addr_cache_next].elem_size = elem_size;
9028 elem_addr_cache [elem_addr_cache_next].method = ret;
9030 mono_marshal_unlock ();
9035 mono_marshal_alloc (gulong size)
9039 #ifdef PLATFORM_WIN32
9040 res = CoTaskMemAlloc (size);
9042 res = g_try_malloc ((gulong)size);
9044 mono_gc_out_of_memory ((gulong)size);
9050 mono_marshal_free (gpointer ptr)
9052 #ifdef PLATFORM_WIN32
9053 CoTaskMemFree (ptr);
9060 mono_marshal_free_array (gpointer *ptr, int size)
9067 for (i = 0; i < size; i++)
9073 mono_marshal_string_to_utf16 (MonoString *s)
9075 return s ? mono_string_chars (s) : NULL;
9079 mono_marshal_string_to_utf16_copy (MonoString *s)
9084 gunichar2 *res = mono_marshal_alloc ((mono_string_length (s) * 2) + 2);
9085 memcpy (res, mono_string_chars (s), mono_string_length (s) * 2);
9086 res [mono_string_length (s)] = 0;
9092 * mono_marshal_set_last_error:
9094 * This function is invoked to set the last error value from a P/Invoke call
9095 * which has SetLastError set.
9098 mono_marshal_set_last_error (void)
9101 TlsSetValue (last_error_tls_id, GINT_TO_POINTER (GetLastError ()));
9103 TlsSetValue (last_error_tls_id, GINT_TO_POINTER (errno));
9108 mono_marshal_set_last_error_windows (int error)
9111 TlsSetValue (last_error_tls_id, GINT_TO_POINTER (error));
9116 ves_icall_System_Runtime_InteropServices_Marshal_copy_to_unmanaged (MonoArray *src, gint32 start_index,
9117 gpointer dest, gint32 length)
9122 MONO_ARCH_SAVE_REGS;
9124 MONO_CHECK_ARG_NULL (src);
9125 MONO_CHECK_ARG_NULL (dest);
9127 if (src->obj.vtable->klass->rank != 1)
9128 mono_raise_exception (mono_get_exception_argument ("array", "array is multi-dimensional"));
9129 if (start_index < 0)
9130 mono_raise_exception (mono_get_exception_argument ("startIndex", "Must be >= 0"));
9132 mono_raise_exception (mono_get_exception_argument ("length", "Must be >= 0"));
9133 if (start_index + length > mono_array_length (src))
9134 mono_raise_exception (mono_get_exception_argument ("length", "start_index + length > array length"));
9136 element_size = mono_array_element_size (src->obj.vtable->klass);
9138 /* no references should be involved */
9139 source_addr = mono_array_addr_with_size (src, element_size, start_index);
9141 memcpy (dest, source_addr, length * element_size);
9145 ves_icall_System_Runtime_InteropServices_Marshal_copy_from_unmanaged (gpointer src, gint32 start_index,
9146 MonoArray *dest, gint32 length)
9151 MONO_ARCH_SAVE_REGS;
9153 MONO_CHECK_ARG_NULL (src);
9154 MONO_CHECK_ARG_NULL (dest);
9156 if (dest->obj.vtable->klass->rank != 1)
9157 mono_raise_exception (mono_get_exception_argument ("array", "array is multi-dimensional"));
9158 if (start_index < 0)
9159 mono_raise_exception (mono_get_exception_argument ("startIndex", "Must be >= 0"));
9161 mono_raise_exception (mono_get_exception_argument ("length", "Must be >= 0"));
9162 if (start_index + length > mono_array_length (dest))
9163 mono_raise_exception (mono_get_exception_argument ("length", "start_index + length > array length"));
9165 element_size = mono_array_element_size (dest->obj.vtable->klass);
9167 /* no references should be involved */
9168 dest_addr = mono_array_addr_with_size (dest, element_size, start_index);
9170 memcpy (dest_addr, src, length * element_size);
9173 #if NO_UNALIGNED_ACCESS
9174 #define RETURN_UNALIGNED(type, addr) \
9177 memcpy(&val, p + offset, sizeof(val)); \
9180 #define WRITE_UNALIGNED(type, addr, val) \
9181 memcpy(addr, &val, sizeof(type))
9183 #define RETURN_UNALIGNED(type, addr) \
9184 return *(type*)(p + offset);
9185 #define WRITE_UNALIGNED(type, addr, val) \
9186 (*(type *)(addr) = (val))
9190 ves_icall_System_Runtime_InteropServices_Marshal_ReadIntPtr (gpointer ptr, gint32 offset)
9194 MONO_ARCH_SAVE_REGS;
9196 RETURN_UNALIGNED(gpointer, p + offset);
9200 ves_icall_System_Runtime_InteropServices_Marshal_ReadByte (gpointer ptr, gint32 offset)
9204 MONO_ARCH_SAVE_REGS;
9206 return *(unsigned char*)(p + offset);
9210 ves_icall_System_Runtime_InteropServices_Marshal_ReadInt16 (gpointer ptr, gint32 offset)
9214 MONO_ARCH_SAVE_REGS;
9216 RETURN_UNALIGNED(gint16, p + offset);
9220 ves_icall_System_Runtime_InteropServices_Marshal_ReadInt32 (gpointer ptr, gint32 offset)
9224 MONO_ARCH_SAVE_REGS;
9226 RETURN_UNALIGNED(gint32, p + offset);
9230 ves_icall_System_Runtime_InteropServices_Marshal_ReadInt64 (gpointer ptr, gint32 offset)
9234 MONO_ARCH_SAVE_REGS;
9236 RETURN_UNALIGNED(gint64, p + offset);
9240 ves_icall_System_Runtime_InteropServices_Marshal_WriteByte (gpointer ptr, gint32 offset, unsigned char val)
9244 MONO_ARCH_SAVE_REGS;
9246 *(unsigned char*)(p + offset) = val;
9250 ves_icall_System_Runtime_InteropServices_Marshal_WriteIntPtr (gpointer ptr, gint32 offset, gpointer val)
9254 MONO_ARCH_SAVE_REGS;
9256 WRITE_UNALIGNED(gpointer, p + offset, val);
9260 ves_icall_System_Runtime_InteropServices_Marshal_WriteInt16 (gpointer ptr, gint32 offset, gint16 val)
9264 MONO_ARCH_SAVE_REGS;
9266 WRITE_UNALIGNED(gint16, p + offset, val);
9270 ves_icall_System_Runtime_InteropServices_Marshal_WriteInt32 (gpointer ptr, gint32 offset, gint32 val)
9274 MONO_ARCH_SAVE_REGS;
9276 WRITE_UNALIGNED(gint32, p + offset, val);
9280 ves_icall_System_Runtime_InteropServices_Marshal_WriteInt64 (gpointer ptr, gint32 offset, gint64 val)
9284 MONO_ARCH_SAVE_REGS;
9286 WRITE_UNALIGNED(gint64, p + offset, val);
9290 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi (char *ptr)
9292 MONO_ARCH_SAVE_REGS;
9297 return mono_string_new (mono_domain_get (), ptr);
9301 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi_len (char *ptr, gint32 len)
9303 MONO_ARCH_SAVE_REGS;
9306 mono_raise_exception (mono_get_exception_argument_null ("ptr"));
9307 g_assert_not_reached ();
9310 return mono_string_new_len (mono_domain_get (), ptr, len);
9315 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni (guint16 *ptr)
9317 MonoDomain *domain = mono_domain_get ();
9321 MONO_ARCH_SAVE_REGS;
9329 return mono_string_new_utf16 (domain, ptr, len);
9333 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni_len (guint16 *ptr, gint32 len)
9335 MonoDomain *domain = mono_domain_get ();
9337 MONO_ARCH_SAVE_REGS;
9340 mono_raise_exception (mono_get_exception_argument_null ("ptr"));
9341 g_assert_not_reached ();
9344 return mono_string_new_utf16 (domain, ptr, len);
9349 ves_icall_System_Runtime_InteropServices_Marshal_GetLastWin32Error (void)
9351 MONO_ARCH_SAVE_REGS;
9353 return (GPOINTER_TO_INT (TlsGetValue (last_error_tls_id)));
9357 ves_icall_System_Runtime_InteropServices_Marshal_SizeOf (MonoReflectionType *rtype)
9363 MONO_ARCH_SAVE_REGS;
9365 MONO_CHECK_ARG_NULL (rtype);
9368 klass = mono_class_from_mono_type (type);
9369 layout = (klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK);
9371 if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
9375 msg = g_strdup_printf ("Type %s cannot be marshaled as an unmanaged structure.", klass->name);
9376 exc = mono_get_exception_argument ("t", msg);
9378 mono_raise_exception (exc);
9382 return mono_class_native_size (klass, NULL);
9386 ves_icall_System_Runtime_InteropServices_Marshal_StructureToPtr (MonoObject *obj, gpointer dst, MonoBoolean delete_old)
9391 MONO_ARCH_SAVE_REGS;
9393 MONO_CHECK_ARG_NULL (obj);
9394 MONO_CHECK_ARG_NULL (dst);
9396 method = mono_marshal_get_struct_to_ptr (obj->vtable->klass);
9400 pa [2] = &delete_old;
9402 mono_runtime_invoke (method, NULL, pa, NULL);
9406 ptr_to_structure (gpointer src, MonoObject *dst)
9411 method = mono_marshal_get_ptr_to_struct (dst->vtable->klass);
9416 mono_runtime_invoke (method, NULL, pa, NULL);
9420 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure (gpointer src, MonoObject *dst)
9424 MONO_ARCH_SAVE_REGS;
9426 MONO_CHECK_ARG_NULL (src);
9427 MONO_CHECK_ARG_NULL (dst);
9429 t = mono_type_get_underlying_type (mono_class_get_type (dst->vtable->klass));
9431 if (t->type == MONO_TYPE_VALUETYPE) {
9435 tmp = g_strdup_printf ("Destination is a boxed value type.");
9436 exc = mono_get_exception_argument ("dst", tmp);
9439 mono_raise_exception (exc);
9443 ptr_to_structure (src, dst);
9447 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure_type (gpointer src, MonoReflectionType *type)
9449 MonoDomain *domain = mono_domain_get ();
9452 MONO_ARCH_SAVE_REGS;
9454 MONO_CHECK_ARG_NULL (src);
9455 MONO_CHECK_ARG_NULL (type);
9457 res = mono_object_new (domain, mono_class_from_mono_type (type->type));
9459 ptr_to_structure (src, res);
9465 ves_icall_System_Runtime_InteropServices_Marshal_OffsetOf (MonoReflectionType *type, MonoString *field_name)
9467 MonoMarshalType *info;
9470 int match_index = -1;
9472 MONO_ARCH_SAVE_REGS;
9474 MONO_CHECK_ARG_NULL (type);
9475 MONO_CHECK_ARG_NULL (field_name);
9477 fname = mono_string_to_utf8 (field_name);
9478 klass = mono_class_from_mono_type (type->type);
9480 while (klass && match_index == -1) {
9481 MonoClassField* field;
9483 gpointer iter = NULL;
9484 while ((field = mono_class_get_fields (klass, &iter))) {
9485 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
9487 if (!strcmp (fname, mono_field_get_name (field))) {
9494 if (match_index == -1)
9495 klass = klass->parent;
9500 if(match_index == -1) {
9504 /* Get back original class instance */
9505 klass = mono_class_from_mono_type (type->type);
9507 tmp = g_strdup_printf ("Field passed in is not a marshaled member of the type %s", klass->name);
9508 exc = mono_get_exception_argument ("fieldName", tmp);
9511 mono_raise_exception ((MonoException*)exc);
9514 info = mono_marshal_load_type_info (klass);
9515 return info->fields [match_index].offset;
9519 ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalAnsi (MonoString *string)
9521 #ifdef PLATFORM_WIN32
9524 tres = mono_string_to_utf8 (string);
9528 len = strlen (tres) + 1;
9529 ret = ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (len);
9530 memcpy (ret, tres, len);
9535 return mono_string_to_utf8 (string);
9540 ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalUni (MonoString *string)
9542 MONO_ARCH_SAVE_REGS;
9547 #ifdef PLATFORM_WIN32
9548 gunichar2 *res = ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal
9549 ((mono_string_length (string) + 1) * 2);
9551 gunichar2 *res = g_malloc ((mono_string_length (string) + 1) * 2);
9553 memcpy (res, mono_string_chars (string), mono_string_length (string) * 2);
9554 res [mono_string_length (string)] = 0;
9560 mono_struct_delete_old (MonoClass *klass, char *ptr)
9562 MonoMarshalType *info;
9565 info = mono_marshal_load_type_info (klass);
9567 for (i = 0; i < info->num_fields; i++) {
9568 MonoMarshalNative ntype;
9569 MonoMarshalConv conv;
9570 MonoType *ftype = info->fields [i].field->type;
9573 if (ftype->attrs & FIELD_ATTRIBUTE_STATIC)
9576 ntype = mono_type_to_unmanaged (ftype, info->fields [i].mspec, TRUE,
9577 klass->unicode, &conv);
9579 cpos = ptr + info->fields [i].offset;
9582 case MONO_MARSHAL_CONV_NONE:
9583 if (MONO_TYPE_ISSTRUCT (ftype)) {
9584 mono_struct_delete_old (ftype->data.klass, cpos);
9588 case MONO_MARSHAL_CONV_STR_LPWSTR:
9589 /* We assume this field points inside a MonoString */
9591 case MONO_MARSHAL_CONV_STR_LPTSTR:
9592 #ifdef PLATFORM_WIN32
9593 /* We assume this field points inside a MonoString
9597 case MONO_MARSHAL_CONV_STR_LPSTR:
9598 case MONO_MARSHAL_CONV_STR_BSTR:
9599 case MONO_MARSHAL_CONV_STR_ANSIBSTR:
9600 case MONO_MARSHAL_CONV_STR_TBSTR:
9601 mono_marshal_free (*(gpointer *)cpos);
9611 ves_icall_System_Runtime_InteropServices_Marshal_DestroyStructure (gpointer src, MonoReflectionType *type)
9615 MONO_ARCH_SAVE_REGS;
9617 MONO_CHECK_ARG_NULL (src);
9618 MONO_CHECK_ARG_NULL (type);
9620 klass = mono_class_from_mono_type (type->type);
9622 mono_struct_delete_old (klass, (char *)src);
9626 ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (int size)
9630 MONO_ARCH_SAVE_REGS;
9632 if ((gulong)size == 0)
9633 /* This returns a valid pointer for size 0 on MS.NET */
9636 #ifdef PLATFORM_WIN32
9637 res = GlobalAlloc (GMEM_FIXED, (gulong)size);
9639 res = g_try_malloc ((gulong)size);
9642 mono_gc_out_of_memory ((gulong)size);
9648 ves_icall_System_Runtime_InteropServices_Marshal_ReAllocHGlobal (gpointer ptr, int size)
9653 mono_gc_out_of_memory ((gulong)size);
9657 #ifdef PLATFORM_WIN32
9658 res = GlobalReAlloc (ptr, (gulong)size, GMEM_MOVEABLE);
9660 res = g_try_realloc (ptr, (gulong)size);
9663 mono_gc_out_of_memory ((gulong)size);
9669 ves_icall_System_Runtime_InteropServices_Marshal_FreeHGlobal (void *ptr)
9671 MONO_ARCH_SAVE_REGS;
9673 #ifdef PLATFORM_WIN32
9681 ves_icall_System_Runtime_InteropServices_Marshal_AllocCoTaskMem (int size)
9683 MONO_ARCH_SAVE_REGS;
9685 #ifdef PLATFORM_WIN32
9686 return CoTaskMemAlloc (size);
9688 return g_try_malloc ((gulong)size);
9693 ves_icall_System_Runtime_InteropServices_Marshal_FreeCoTaskMem (void *ptr)
9695 MONO_ARCH_SAVE_REGS;
9697 #ifdef PLATFORM_WIN32
9698 CoTaskMemFree (ptr);
9705 ves_icall_System_Runtime_InteropServices_Marshal_ReAllocCoTaskMem (gpointer ptr, int size)
9707 MONO_ARCH_SAVE_REGS;
9709 #ifdef PLATFORM_WIN32
9710 return CoTaskMemRealloc (ptr, size);
9712 return g_try_realloc (ptr, (gulong)size);
9717 ves_icall_System_Runtime_InteropServices_Marshal_UnsafeAddrOfPinnedArrayElement (MonoArray *arrayobj, int index)
9719 return mono_array_addr_with_size (arrayobj, mono_array_element_size (arrayobj->obj.vtable->klass), index);
9723 ves_icall_System_Runtime_InteropServices_Marshal_GetDelegateForFunctionPointerInternal (void *ftn, MonoReflectionType *type)
9725 return mono_ftnptr_to_delegate (mono_type_get_class (type->type), ftn);
9729 * mono_marshal_is_loading_type_info:
9731 * Return whenever mono_marshal_load_type_info () is being executed for KLASS by this
9735 mono_marshal_is_loading_type_info (MonoClass *klass)
9737 GSList *loads_list = TlsGetValue (load_type_info_tls_id);
9739 return g_slist_find (loads_list, klass) != NULL;
9743 * mono_marshal_load_type_info:
9745 * Initialize klass->marshal_info using information from metadata. This function can
9746 * recursively call itself, and the caller is responsible to avoid that by calling
9747 * mono_marshal_is_loading_type_info () beforehand.
9749 * LOCKING: Acquires the loader lock.
9752 mono_marshal_load_type_info (MonoClass* klass)
9755 guint32 native_size = 0, min_align = 1;
9756 MonoMarshalType *info;
9757 MonoClassField* field;
9762 g_assert (klass != NULL);
9764 if (klass->marshal_info)
9765 return klass->marshal_info;
9768 mono_class_init (klass);
9770 mono_loader_lock ();
9772 if (klass->marshal_info) {
9773 mono_loader_unlock ();
9774 return klass->marshal_info;
9778 * This function can recursively call itself, so we keep the list of classes which are
9779 * under initialization in a TLS list.
9781 g_assert (!mono_marshal_is_loading_type_info (klass));
9782 loads_list = TlsGetValue (load_type_info_tls_id);
9783 loads_list = g_slist_prepend (loads_list, klass);
9784 TlsSetValue (load_type_info_tls_id, loads_list);
9787 while ((field = mono_class_get_fields (klass, &iter))) {
9788 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
9790 if (mono_field_is_deleted (field))
9795 layout = klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
9797 /* The mempool is protected by the loader lock */
9798 info = mono_image_alloc0 (klass->image, sizeof (MonoMarshalType) + sizeof (MonoMarshalField) * count);
9799 info->num_fields = count;
9801 /* Try to find a size for this type in metadata */
9802 mono_metadata_packing_from_typedef (klass->image, klass->type_token, NULL, &native_size);
9804 if (klass->parent) {
9805 int parent_size = mono_class_native_size (klass->parent, NULL);
9807 /* Add parent size to real size */
9808 native_size += parent_size;
9809 info->native_size = parent_size;
9814 while ((field = mono_class_get_fields (klass, &iter))) {
9818 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
9821 if (mono_field_is_deleted (field))
9823 if (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL)
9824 mono_metadata_field_info_with_mempool (klass->image, mono_metadata_token_index (mono_class_get_field_token (field)) - 1,
9825 NULL, NULL, &info->fields [j].mspec);
9827 info->fields [j].field = field;
9829 if ((mono_class_num_fields (klass) == 1) && (klass->instance_size == sizeof (MonoObject)) &&
9830 (strcmp (mono_field_get_name (field), "$PRIVATE$") == 0)) {
9831 /* This field is a hack inserted by MCS to empty structures */
9836 case TYPE_ATTRIBUTE_AUTO_LAYOUT:
9837 case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
9838 size = mono_marshal_type_size (field->type, info->fields [j].mspec,
9839 &align, TRUE, klass->unicode);
9840 align = klass->packing_size ? MIN (klass->packing_size, align): align;
9841 min_align = MAX (align, min_align);
9842 info->fields [j].offset = info->native_size;
9843 info->fields [j].offset += align - 1;
9844 info->fields [j].offset &= ~(align - 1);
9845 info->native_size = info->fields [j].offset + size;
9847 case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
9848 size = mono_marshal_type_size (field->type, info->fields [j].mspec,
9849 &align, TRUE, klass->unicode);
9850 align = klass->packing_size ? MIN (klass->packing_size, align): align;
9851 min_align = MAX (align, min_align);
9852 info->fields [j].offset = field->offset - sizeof (MonoObject);
9853 info->native_size = MAX (info->native_size, info->fields [j].offset + size);
9859 if(layout != TYPE_ATTRIBUTE_AUTO_LAYOUT) {
9860 info->native_size = MAX (native_size, info->native_size);
9863 if (info->native_size & (min_align - 1)) {
9864 info->native_size += min_align - 1;
9865 info->native_size &= ~(min_align - 1);
9868 info->min_align = min_align;
9870 /* Update the class's blittable info, if the layouts don't match */
9871 if (info->native_size != mono_class_value_size (klass, NULL))
9872 klass->blittable = FALSE;
9874 /* If this is an array type, ensure that we have element info */
9875 if (klass->element_class && !mono_marshal_is_loading_type_info (klass->element_class)) {
9876 mono_marshal_load_type_info (klass->element_class);
9879 loads_list = TlsGetValue (load_type_info_tls_id);
9880 loads_list = g_slist_remove (loads_list, klass);
9881 TlsSetValue (load_type_info_tls_id, loads_list);
9883 /*We do double-checking locking on marshal_info */
9884 mono_memory_barrier ();
9886 klass->marshal_info = info;
9888 mono_loader_unlock ();
9890 return klass->marshal_info;
9894 * mono_class_native_size:
9897 * Returns: the native size of an object instance (when marshaled
9898 * to unmanaged code)
9901 mono_class_native_size (MonoClass *klass, guint32 *align)
9903 if (!klass->marshal_info) {
9904 if (mono_marshal_is_loading_type_info (klass)) {
9909 mono_marshal_load_type_info (klass);
9914 *align = klass->marshal_info->min_align;
9916 return klass->marshal_info->native_size;
9919 /* __alignof__ returns the preferred alignment of values not the actual alignment used by
9920 the compiler so is wrong e.g. for Linux where doubles are aligned on a 4 byte boundary
9921 but __alignof__ returns 8 - using G_STRUCT_OFFSET works better */
9922 #define ALIGNMENT(type) G_STRUCT_OFFSET(struct { char c; type x; }, x)
9925 * mono_type_native_stack_size:
9926 * @t: the type to return the size it uses on the stack
9928 * Returns: the number of bytes required to hold an instance of this
9929 * type on the native stack
9932 mono_type_native_stack_size (MonoType *t, guint32 *align)
9936 g_assert (t != NULL);
9942 *align = sizeof (gpointer);
9943 return sizeof (gpointer);
9947 case MONO_TYPE_BOOLEAN:
9948 case MONO_TYPE_CHAR:
9959 case MONO_TYPE_STRING:
9960 case MONO_TYPE_OBJECT:
9961 case MONO_TYPE_CLASS:
9962 case MONO_TYPE_SZARRAY:
9964 case MONO_TYPE_FNPTR:
9965 case MONO_TYPE_ARRAY:
9966 *align = sizeof (gpointer);
9967 return sizeof (gpointer);
9972 *align = ALIGNMENT (gdouble);
9976 *align = ALIGNMENT (glong);
9978 case MONO_TYPE_GENERICINST:
9979 if (!mono_type_generic_inst_is_valuetype (t)) {
9980 *align = sizeof (gpointer);
9981 return sizeof (gpointer);
9984 case MONO_TYPE_TYPEDBYREF:
9985 case MONO_TYPE_VALUETYPE: {
9987 MonoClass *klass = mono_class_from_mono_type (t);
9989 if (klass->enumtype)
9990 return mono_type_native_stack_size (mono_class_enum_basetype (klass), align);
9992 size = mono_class_native_size (klass, align);
9993 *align = *align + 3;
10003 g_error ("type 0x%02x unknown", t->type);
10009 mono_marshal_type_size (MonoType *type, MonoMarshalSpec *mspec, guint32 *align,
10010 gboolean as_field, gboolean unicode)
10012 MonoMarshalNative native_type = mono_type_to_unmanaged (type, mspec, as_field, unicode, NULL);
10015 switch (native_type) {
10016 case MONO_NATIVE_BOOLEAN:
10019 case MONO_NATIVE_I1:
10020 case MONO_NATIVE_U1:
10023 case MONO_NATIVE_I2:
10024 case MONO_NATIVE_U2:
10025 case MONO_NATIVE_VARIANTBOOL:
10028 case MONO_NATIVE_I4:
10029 case MONO_NATIVE_U4:
10030 case MONO_NATIVE_ERROR:
10033 case MONO_NATIVE_I8:
10034 case MONO_NATIVE_U8:
10035 *align = ALIGNMENT(guint64);
10037 case MONO_NATIVE_R4:
10040 case MONO_NATIVE_R8:
10041 *align = ALIGNMENT(double);
10043 case MONO_NATIVE_INT:
10044 case MONO_NATIVE_UINT:
10045 case MONO_NATIVE_LPSTR:
10046 case MONO_NATIVE_LPWSTR:
10047 case MONO_NATIVE_LPTSTR:
10048 case MONO_NATIVE_BSTR:
10049 case MONO_NATIVE_ANSIBSTR:
10050 case MONO_NATIVE_TBSTR:
10051 case MONO_NATIVE_LPARRAY:
10052 case MONO_NATIVE_SAFEARRAY:
10053 case MONO_NATIVE_IUNKNOWN:
10054 case MONO_NATIVE_IDISPATCH:
10055 case MONO_NATIVE_INTERFACE:
10056 case MONO_NATIVE_ASANY:
10057 case MONO_NATIVE_FUNC:
10058 case MONO_NATIVE_LPSTRUCT:
10059 *align = ALIGNMENT(gpointer);
10060 return sizeof (gpointer);
10061 case MONO_NATIVE_STRUCT:
10062 klass = mono_class_from_mono_type (type);
10063 if (klass == mono_defaults.object_class &&
10064 (mspec && mspec->native == MONO_NATIVE_STRUCT)) {
10068 return mono_class_native_size (klass, align);
10069 case MONO_NATIVE_BYVALTSTR: {
10070 int esize = unicode ? 2: 1;
10073 return mspec->data.array_data.num_elem * esize;
10075 case MONO_NATIVE_BYVALARRAY: {
10076 // FIXME: Have to consider ArraySubType
10078 klass = mono_class_from_mono_type (type);
10079 if (klass->element_class == mono_defaults.char_class) {
10080 esize = unicode ? 2 : 1;
10083 esize = mono_class_native_size (klass->element_class, align);
10086 return mspec->data.array_data.num_elem * esize;
10088 case MONO_NATIVE_CUSTOM:
10089 *align = sizeof (gpointer);
10090 return sizeof (gpointer);
10092 case MONO_NATIVE_CURRENCY:
10093 case MONO_NATIVE_VBBYREFSTR:
10095 g_error ("native type %02x not implemented", native_type);
10098 g_assert_not_reached ();
10103 mono_marshal_asany (MonoObject *o, MonoMarshalNative string_encoding, int param_attrs)
10111 t = &o->vtable->klass->byval_arg;
10115 case MONO_TYPE_PTR:
10118 case MONO_TYPE_BOOLEAN:
10121 case MONO_TYPE_CHAR:
10126 return mono_object_unbox (o);
10128 case MONO_TYPE_STRING:
10129 switch (string_encoding) {
10130 case MONO_NATIVE_LPWSTR:
10131 return mono_string_to_utf16 ((MonoString*)o);
10133 case MONO_NATIVE_LPSTR:
10134 return mono_string_to_lpstr ((MonoString*)o);
10137 g_warning ("marshaling conversion %d not implemented", string_encoding);
10138 g_assert_not_reached ();
10141 case MONO_TYPE_CLASS:
10142 case MONO_TYPE_VALUETYPE: {
10143 MonoMethod *method;
10146 MonoBoolean delete_old = FALSE;
10148 klass = t->data.klass;
10150 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
10153 if (klass->valuetype && (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
10154 klass->blittable || klass->enumtype))
10155 return mono_object_unbox (o);
10157 res = mono_marshal_alloc (mono_class_native_size (klass, NULL));
10159 if (!((param_attrs & PARAM_ATTRIBUTE_OUT) && !(param_attrs & PARAM_ATTRIBUTE_IN))) {
10160 method = mono_marshal_get_struct_to_ptr (o->vtable->klass);
10164 pa [2] = &delete_old;
10166 mono_runtime_invoke (method, NULL, pa, NULL);
10173 mono_raise_exception (mono_get_exception_argument ("", "No PInvoke conversion exists for value passed to Object-typed parameter."));
10179 mono_marshal_free_asany (MonoObject *o, gpointer ptr, MonoMarshalNative string_encoding, int param_attrs)
10187 t = &o->vtable->klass->byval_arg;
10189 case MONO_TYPE_STRING:
10190 switch (string_encoding) {
10191 case MONO_NATIVE_LPWSTR:
10192 case MONO_NATIVE_LPSTR:
10193 mono_marshal_free (ptr);
10196 g_warning ("marshaling conversion %d not implemented", string_encoding);
10197 g_assert_not_reached ();
10200 case MONO_TYPE_CLASS:
10201 case MONO_TYPE_VALUETYPE: {
10202 klass = t->data.klass;
10204 if (klass->valuetype && (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
10205 klass->blittable || klass->enumtype))
10208 if (param_attrs & PARAM_ATTRIBUTE_OUT) {
10209 MonoMethod *method = mono_marshal_get_ptr_to_struct (o->vtable->klass);
10215 mono_runtime_invoke (method, NULL, pa, NULL);
10218 if (!((param_attrs & PARAM_ATTRIBUTE_OUT) && !(param_attrs & PARAM_ATTRIBUTE_IN))) {
10219 mono_struct_delete_old (klass, ptr);
10222 mono_marshal_free (ptr);
10231 mono_marshal_get_generic_array_helper (MonoClass *class, MonoClass *iface, gchar *name, MonoMethod *method)
10233 MonoMethodSignature *sig, *csig;
10234 MonoMethodBuilder *mb;
10238 mb = mono_mb_new_no_dup_name (class, name, MONO_WRAPPER_MANAGED_TO_MANAGED);
10239 mb->method->slot = -1;
10241 mb->method->flags = METHOD_ATTRIBUTE_PRIVATE | METHOD_ATTRIBUTE_VIRTUAL |
10242 METHOD_ATTRIBUTE_NEW_SLOT | METHOD_ATTRIBUTE_HIDE_BY_SIG | METHOD_ATTRIBUTE_FINAL;
10244 sig = mono_method_signature (method);
10245 csig = signature_dup (method->klass->image, sig);
10246 csig->generic_param_count = 0;
10248 mono_mb_emit_ldarg (mb, 0);
10249 for (i = 0; i < csig->param_count; i++)
10250 mono_mb_emit_ldarg (mb, i + 1);
10251 mono_mb_emit_managed_call (mb, method, NULL);
10252 mono_mb_emit_byte (mb, CEE_RET);
10254 /* We can corlib internal methods */
10255 mb->skip_visibility = TRUE;
10257 res = mono_mb_create_method (mb, csig, csig->param_count + 16);
10265 * The mono_win32_compat_* functions are implementations of inline
10266 * Windows kernel32 APIs, which are DllImport-able under MS.NET,
10267 * although not exported by kernel32.
10269 * We map the appropiate kernel32 entries to these functions using
10270 * dllmaps declared in the global etc/mono/config.
10274 mono_win32_compat_CopyMemory (gpointer dest, gconstpointer source, gsize length)
10276 if (!dest || !source)
10279 memcpy (dest, source, length);
10283 mono_win32_compat_FillMemory (gpointer dest, gsize length, guchar fill)
10285 memset (dest, fill, length);
10289 mono_win32_compat_MoveMemory (gpointer dest, gconstpointer source, gsize length)
10291 if (!dest || !source)
10294 memmove (dest, source, length);
10298 mono_win32_compat_ZeroMemory (gpointer dest, gsize length)
10300 memset (dest, 0, length);
10304 mono_marshal_find_nonzero_bit_offset (guint8 *buf, int len, int *byte_offset, guint8 *bitmask)
10309 for (i = 0; i < len; ++i)
10313 g_assert (i < len);
10316 while (byte && !(byte & 1))
10318 g_assert (byte == 1);
10321 *bitmask = buf [i];
10325 mono_marshal_get_thunk_invoke_wrapper (MonoMethod *method)
10327 MonoMethodBuilder *mb;
10328 MonoMethodSignature *sig, *csig;
10329 MonoExceptionClause *clause;
10334 int i, param_count, sig_size, pos_leave;
10338 klass = method->klass;
10339 image = method->klass->image;
10340 cache = get_cache (&image->thunk_invoke_cache, mono_aligned_addr_hash, NULL);
10342 if ((res = mono_marshal_find_in_cache (cache, method)))
10345 sig = mono_method_signature (method);
10346 mb = mono_mb_new (klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
10348 /* add "this" and exception param */
10349 param_count = sig->param_count + sig->hasthis + 1;
10351 /* dup & extend signature */
10352 csig = mono_metadata_signature_alloc (image, param_count);
10353 sig_size = sizeof (MonoMethodSignature) + ((sig->param_count - MONO_ZERO_LEN_ARRAY) * sizeof (MonoType *));
10354 memcpy (csig, sig, sig_size);
10355 csig->param_count = param_count;
10358 csig->call_convention = MONO_CALL_DEFAULT;
10360 if (sig->hasthis) {
10362 csig->params [0] = &klass->byval_arg;
10363 /* move params up by one */
10364 for (i = 0; i < sig->param_count; i++)
10365 csig->params [i + 1] = sig->params [i];
10368 /* setup exception param as byref+[out] */
10369 csig->params [param_count - 1] = mono_metadata_type_dup (image,
10370 &mono_defaults.exception_class->byval_arg);
10371 csig->params [param_count - 1]->byref = 1;
10372 csig->params [param_count - 1]->attrs = PARAM_ATTRIBUTE_OUT;
10374 /* convert struct return to object */
10375 if (MONO_TYPE_ISSTRUCT (sig->ret))
10376 csig->ret = &mono_defaults.object_class->byval_arg;
10378 /* local 0 (temp for exception object) */
10379 mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
10381 /* local 1 (temp for result) */
10382 if (!MONO_TYPE_IS_VOID (sig->ret))
10383 mono_mb_add_local (mb, sig->ret);
10385 /* clear exception arg */
10386 mono_mb_emit_ldarg (mb, param_count - 1);
10387 mono_mb_emit_byte (mb, CEE_LDNULL);
10388 mono_mb_emit_byte (mb, CEE_STIND_REF);
10391 clause = mono_image_alloc0 (image, sizeof (MonoExceptionClause));
10392 clause->try_offset = mono_mb_get_label (mb);
10394 /* push method's args */
10395 for (i = 0; i < param_count - 1; i++) {
10399 mono_mb_emit_ldarg (mb, i);
10401 /* get the byval type of the param */
10402 klass = mono_class_from_mono_type (csig->params [i]);
10403 type = &klass->byval_arg;
10405 /* unbox struct args */
10406 if (MONO_TYPE_ISSTRUCT (type)) {
10407 mono_mb_emit_op (mb, CEE_UNBOX, klass);
10409 /* byref args & and the "this" arg must remain a ptr.
10410 Otherwise make a copy of the value type */
10411 if (!(csig->params [i]->byref || (i == 0 && sig->hasthis)))
10412 mono_mb_emit_op (mb, CEE_LDOBJ, klass);
10414 csig->params [i] = &mono_defaults.object_class->byval_arg;
10419 if (method->flags & METHOD_ATTRIBUTE_VIRTUAL)
10420 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
10422 mono_mb_emit_op (mb, CEE_CALL, method);
10424 /* save result at local 1 */
10425 if (!MONO_TYPE_IS_VOID (sig->ret))
10426 mono_mb_emit_stloc (mb, 1);
10428 pos_leave = mono_mb_emit_branch (mb, CEE_LEAVE);
10431 clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
10432 clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
10433 clause->data.catch_class = mono_defaults.object_class;
10435 clause->handler_offset = mono_mb_get_label (mb);
10437 /* store exception at local 0 */
10438 mono_mb_emit_stloc (mb, 0);
10439 mono_mb_emit_ldarg (mb, param_count - 1);
10440 mono_mb_emit_ldloc (mb, 0);
10441 mono_mb_emit_byte (mb, CEE_STIND_REF);
10442 mono_mb_emit_branch (mb, CEE_LEAVE);
10444 clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
10446 mono_mb_set_clauses (mb, 1, clause);
10448 mono_mb_patch_branch (mb, pos_leave);
10451 if (!MONO_TYPE_IS_VOID (sig->ret)) {
10452 mono_mb_emit_ldloc (mb, 1);
10454 /* box the return value */
10455 if (MONO_TYPE_ISSTRUCT (sig->ret))
10456 mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (sig->ret));
10459 mono_mb_emit_byte (mb, CEE_RET);
10461 res = mono_mb_create_and_cache (cache, method, mb, csig, param_count + 16);
10468 * mono_marshal_free_dynamic_wrappers:
10470 * Free wrappers of the dynamic method METHOD.
10473 mono_marshal_free_dynamic_wrappers (MonoMethod *method)
10475 g_assert (method->dynamic);
10477 mono_marshal_lock ();
10479 * FIXME: We currently leak the wrappers. Freeing them would be tricky as
10480 * they could be shared with other methods ?
10482 if (method->klass->image->runtime_invoke_direct_cache)
10483 g_hash_table_remove (method->klass->image->runtime_invoke_direct_cache, method);
10484 mono_marshal_unlock ();