Merge pull request #3936 from kumpera/monoclass_reorg2
[mono-project.git] / mono / metadata / marshal.c
blob148f5bc251743e9d26bf104a8fc70b9c9c41d7cb
1 /*
2 * marshal.c: Routines for marshaling complex types in P/Invoke methods.
3 *
4 * Author:
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)
9 * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
11 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
14 #include "config.h"
15 #ifdef HAVE_ALLOCA_H
16 #include <alloca.h>
17 #endif
19 #include "object.h"
20 #include "loader.h"
21 #include "cil-coff.h"
22 #include "metadata/marshal.h"
23 #include "metadata/marshal-internals.h"
24 #include "metadata/method-builder.h"
25 #include "metadata/tabledefs.h"
26 #include "metadata/exception.h"
27 #include "metadata/appdomain.h"
28 #include "mono/metadata/abi-details.h"
29 #include "mono/metadata/debug-helpers.h"
30 #include "mono/metadata/threads.h"
31 #include "mono/metadata/monitor.h"
32 #include "mono/metadata/class-internals.h"
33 #include "mono/metadata/metadata-internals.h"
34 #include "mono/metadata/domain-internals.h"
35 #include "mono/metadata/gc-internals.h"
36 #include "mono/metadata/threads-types.h"
37 #include "mono/metadata/string-icalls.h"
38 #include "mono/metadata/attrdefs.h"
39 #include "mono/metadata/gc-internals.h"
40 #include "mono/metadata/cominterop.h"
41 #include "mono/metadata/remoting.h"
42 #include "mono/metadata/reflection-internals.h"
43 #include "mono/metadata/threadpool-ms.h"
44 #include "mono/metadata/handle.h"
45 #include "mono/utils/mono-counters.h"
46 #include "mono/utils/mono-tls.h"
47 #include "mono/utils/mono-memory-model.h"
48 #include "mono/utils/atomic.h"
49 #include <mono/utils/mono-threads.h>
50 #include <mono/utils/mono-threads-coop.h>
51 #include <mono/utils/mono-error-internals.h>
53 #include <string.h>
54 #include <errno.h>
56 /* #define DEBUG_RUNTIME_CODE */
58 #define OPDEF(a,b,c,d,e,f,g,h,i,j) \
59 a = i,
61 enum {
62 #include "mono/cil/opcode.def"
63 LAST = 0xff
65 #undef OPDEF
67 /*
68 * This mutex protects the various marshalling related caches in MonoImage
69 * and a few other data structures static to this file.
71 * The marshal lock is a non-recursive complex lock that sits below the domain lock in the
72 * runtime locking latice. Which means it can take simple locks suck as the image lock.
74 #define mono_marshal_lock() mono_locks_os_acquire (&marshal_mutex, MarshalLock)
75 #define mono_marshal_unlock() mono_locks_os_release (&marshal_mutex, MarshalLock)
76 static mono_mutex_t marshal_mutex;
77 static gboolean marshal_mutex_initialized;
79 static MonoNativeTlsKey last_error_tls_id;
81 static MonoNativeTlsKey load_type_info_tls_id;
83 static gboolean use_aot_wrappers;
85 static int class_marshal_info_count;
87 static void ftnptr_eh_callback_default (guint32 gchandle);
89 static MonoFtnPtrEHCallback ftnptr_eh_callback = ftnptr_eh_callback_default;
91 static void
92 delegate_hash_table_add (MonoDelegate *d);
94 static void
95 delegate_hash_table_remove (MonoDelegate *d);
97 static void
98 emit_struct_conv (MonoMethodBuilder *mb, MonoClass *klass, gboolean to_object);
100 static void
101 emit_struct_conv_full (MonoMethodBuilder *mb, MonoClass *klass, gboolean to_object, int offset_of_first_child_field, MonoMarshalNative string_encoding);
103 static void
104 mono_struct_delete_old (MonoClass *klass, char *ptr);
106 MONO_API void *
107 mono_marshal_string_to_utf16 (MonoString *s);
109 static void *
110 mono_marshal_string_to_utf16_copy (MonoString *s);
112 #ifndef HOST_WIN32
113 static gpointer
114 mono_string_to_utf8str (MonoString *string_obj);
115 #endif
117 static MonoStringBuilder *
118 mono_string_utf8_to_builder2 (char *text);
120 static MonoStringBuilder *
121 mono_string_utf16_to_builder2 (gunichar2 *text);
123 static MonoString*
124 mono_string_new_len_wrapper (const char *text, guint length);
126 static MonoString *
127 mono_string_from_byvalstr (const char *data, int len);
129 static MonoString *
130 mono_string_from_byvalwstr (gunichar2 *data, int len);
132 static void
133 mono_byvalarray_to_array (MonoArray *arr, gpointer native_arr, MonoClass *eltype, guint32 elnum);
135 static void
136 mono_byvalarray_to_byte_array (MonoArray *arr, gpointer native_arr, guint32 elnum);
138 static void
139 mono_array_to_byvalarray (gpointer native_arr, MonoArray *arr, MonoClass *eltype, guint32 elnum);
141 static void
142 mono_array_to_byte_byvalarray (gpointer native_arr, MonoArray *arr, guint32 elnum);
144 static MonoAsyncResult *
145 mono_delegate_begin_invoke (MonoDelegate *delegate, gpointer *params);
147 static MonoObject *
148 mono_delegate_end_invoke (MonoDelegate *delegate, gpointer *params);
150 static void
151 mono_marshal_set_last_error_windows (int error);
153 static MonoObject *
154 mono_marshal_isinst_with_cache (MonoObject *obj, MonoClass *klass, uintptr_t *cache);
156 static void init_safe_handle (void);
158 static void*
159 ves_icall_marshal_alloc (gulong size);
161 void
162 mono_string_utf8_to_builder (MonoStringBuilder *sb, char *text);
164 void
165 mono_string_utf16_to_builder (MonoStringBuilder *sb, gunichar2 *text);
167 gchar*
168 mono_string_builder_to_utf8 (MonoStringBuilder *sb);
170 gunichar2*
171 mono_string_builder_to_utf16 (MonoStringBuilder *sb);
173 void
174 mono_string_to_byvalstr (gpointer dst, MonoString *src, int size);
176 void
177 mono_string_to_byvalwstr (gpointer dst, MonoString *src, int size);
179 gpointer
180 mono_delegate_to_ftnptr (MonoDelegate *delegate);
182 MonoDelegate*
183 mono_ftnptr_to_delegate (MonoClass *klass, gpointer ftn);
185 gpointer
186 mono_array_to_savearray (MonoArray *array);
188 gpointer
189 mono_array_to_lparray (MonoArray *array);
191 void
192 mono_free_lparray (MonoArray *array, gpointer* nativeArray);
194 gpointer
195 mono_marshal_asany (MonoObject *obj, MonoMarshalNative string_encoding, int param_attrs);
197 void
198 mono_marshal_free_asany (MonoObject *o, gpointer ptr, MonoMarshalNative string_encoding, int param_attrs);
200 gpointer
201 mono_array_to_savearray (MonoArray *array);
203 gpointer
204 mono_array_to_lparray (MonoArray *array);
206 void
207 mono_free_lparray (MonoArray *array, gpointer* nativeArray);
209 static void
210 mono_marshal_ftnptr_eh_callback (guint32 gchandle);
212 static MonoThreadInfo*
213 mono_icall_start (HandleStackMark *stackmark, MonoError *error);
215 static void
216 mono_icall_end (MonoThreadInfo *info, HandleStackMark *stackmark, MonoError *error);
218 /* Lazy class loading functions */
219 static GENERATE_GET_CLASS_WITH_CACHE (string_builder, System.Text, StringBuilder)
220 static GENERATE_GET_CLASS_WITH_CACHE (date_time, System, DateTime)
221 static GENERATE_TRY_GET_CLASS_WITH_CACHE (unmanaged_function_pointer_attribute, System.Runtime.InteropServices, UnmanagedFunctionPointerAttribute)
222 static GENERATE_TRY_GET_CLASS_WITH_CACHE (icustom_marshaler, System.Runtime.InteropServices, ICustomMarshaler)
224 /* MonoMethod pointers to SafeHandle::DangerousAddRef and ::DangerousRelease */
225 static MonoMethod *sh_dangerous_add_ref;
226 static MonoMethod *sh_dangerous_release;
228 static void
229 init_safe_handle ()
231 sh_dangerous_add_ref = mono_class_get_method_from_name (
232 mono_class_try_get_safehandle_class (), "DangerousAddRef", 1);
233 sh_dangerous_release = mono_class_get_method_from_name (
234 mono_class_try_get_safehandle_class (), "DangerousRelease", 0);
237 static void
238 register_icall (gpointer func, const char *name, const char *sigstr, gboolean no_wrapper)
240 MonoMethodSignature *sig = mono_create_icall_signature (sigstr);
242 mono_register_jit_icall (func, name, sig, no_wrapper);
245 MonoMethodSignature*
246 mono_signature_no_pinvoke (MonoMethod *method)
248 MonoMethodSignature *sig = mono_method_signature (method);
249 if (sig->pinvoke) {
250 sig = mono_metadata_signature_dup_full (method->klass->image, sig);
251 sig->pinvoke = FALSE;
254 return sig;
257 void
258 mono_marshal_init_tls (void)
260 mono_native_tls_alloc (&last_error_tls_id, NULL);
261 mono_native_tls_alloc (&load_type_info_tls_id, NULL);
264 static MonoObject*
265 mono_object_isinst_icall (MonoObject *obj, MonoClass *klass)
267 MonoError error;
268 MonoObject *result = mono_object_isinst_checked (obj, klass, &error);
269 mono_error_set_pending_exception (&error);
270 return result;
273 static MonoString*
274 ves_icall_mono_string_from_utf16 (gunichar2 *data)
276 MonoError error;
277 MonoString *result = mono_string_from_utf16_checked (data, &error);
278 mono_error_set_pending_exception (&error);
279 return result;
282 static char*
283 ves_icall_mono_string_to_utf8 (MonoString *str)
285 MonoError error;
286 char *result = mono_string_to_utf8_checked (str, &error);
287 mono_error_set_pending_exception (&error);
288 return result;
291 void
292 mono_marshal_init (void)
294 static gboolean module_initialized = FALSE;
296 if (!module_initialized) {
297 module_initialized = TRUE;
298 mono_os_mutex_init_recursive (&marshal_mutex);
299 marshal_mutex_initialized = TRUE;
301 register_icall (ves_icall_System_Threading_Thread_ResetAbort, "ves_icall_System_Threading_Thread_ResetAbort", "void", TRUE);
302 register_icall (mono_marshal_string_to_utf16, "mono_marshal_string_to_utf16", "ptr obj", FALSE);
303 register_icall (mono_marshal_string_to_utf16_copy, "mono_marshal_string_to_utf16_copy", "ptr obj", FALSE);
304 register_icall (mono_string_to_utf16, "mono_string_to_utf16", "ptr obj", FALSE);
305 register_icall (ves_icall_mono_string_from_utf16, "ves_icall_mono_string_from_utf16", "obj ptr", FALSE);
306 register_icall (mono_string_from_byvalstr, "mono_string_from_byvalstr", "obj ptr int", FALSE);
307 register_icall (mono_string_from_byvalwstr, "mono_string_from_byvalwstr", "obj ptr int", FALSE);
308 register_icall (mono_string_new_wrapper, "mono_string_new_wrapper", "obj ptr", FALSE);
309 register_icall (mono_string_new_len_wrapper, "mono_string_new_len_wrapper", "obj ptr int", FALSE);
310 register_icall (ves_icall_mono_string_to_utf8, "ves_icall_mono_string_to_utf8", "ptr obj", FALSE);
311 register_icall (mono_string_to_utf8str, "mono_string_to_utf8str", "ptr obj", FALSE);
312 register_icall (mono_string_to_ansibstr, "mono_string_to_ansibstr", "ptr object", FALSE);
313 register_icall (mono_string_builder_to_utf8, "mono_string_builder_to_utf8", "ptr object", FALSE);
314 register_icall (mono_string_builder_to_utf16, "mono_string_builder_to_utf16", "ptr object", FALSE);
315 register_icall (mono_array_to_savearray, "mono_array_to_savearray", "ptr object", FALSE);
316 register_icall (mono_array_to_lparray, "mono_array_to_lparray", "ptr object", FALSE);
317 register_icall (mono_free_lparray, "mono_free_lparray", "void object ptr", FALSE);
318 register_icall (mono_byvalarray_to_array, "mono_byvalarray_to_array", "void object ptr ptr int32", FALSE);
319 register_icall (mono_byvalarray_to_byte_array, "mono_byvalarray_to_byte_array", "void object ptr int32", FALSE);
320 register_icall (mono_array_to_byvalarray, "mono_array_to_byvalarray", "void ptr object ptr int32", FALSE);
321 register_icall (mono_array_to_byte_byvalarray, "mono_array_to_byte_byvalarray", "void ptr object int32", FALSE);
322 register_icall (mono_delegate_to_ftnptr, "mono_delegate_to_ftnptr", "ptr object", FALSE);
323 register_icall (mono_ftnptr_to_delegate, "mono_ftnptr_to_delegate", "object ptr ptr", FALSE);
324 register_icall (mono_marshal_asany, "mono_marshal_asany", "ptr object int32 int32", FALSE);
325 register_icall (mono_marshal_free_asany, "mono_marshal_free_asany", "void object ptr int32 int32", FALSE);
326 register_icall (ves_icall_marshal_alloc, "ves_icall_marshal_alloc", "ptr int32", FALSE);
327 register_icall (mono_marshal_free, "mono_marshal_free", "void ptr", FALSE);
328 register_icall (mono_marshal_set_last_error, "mono_marshal_set_last_error", "void", FALSE);
329 register_icall (mono_marshal_set_last_error_windows, "mono_marshal_set_last_error_windows", "void int32", FALSE);
330 register_icall (mono_string_utf8_to_builder, "mono_string_utf8_to_builder", "void ptr ptr", FALSE);
331 register_icall (mono_string_utf8_to_builder2, "mono_string_utf8_to_builder2", "object ptr", FALSE);
332 register_icall (mono_string_utf16_to_builder, "mono_string_utf16_to_builder", "void ptr ptr", FALSE);
333 register_icall (mono_string_utf16_to_builder2, "mono_string_utf16_to_builder2", "object ptr", FALSE);
334 register_icall (mono_marshal_free_array, "mono_marshal_free_array", "void ptr int32", FALSE);
335 register_icall (mono_string_to_byvalstr, "mono_string_to_byvalstr", "void ptr ptr int32", FALSE);
336 register_icall (mono_string_to_byvalwstr, "mono_string_to_byvalwstr", "void ptr ptr int32", FALSE);
337 register_icall (g_free, "g_free", "void ptr", FALSE);
338 register_icall (mono_object_isinst_icall, "mono_object_isinst_icall", "object object ptr", FALSE);
339 register_icall (mono_struct_delete_old, "mono_struct_delete_old", "void ptr ptr", FALSE);
340 register_icall (mono_delegate_begin_invoke, "mono_delegate_begin_invoke", "object object ptr", FALSE);
341 register_icall (mono_delegate_end_invoke, "mono_delegate_end_invoke", "object object ptr", FALSE);
342 register_icall (mono_context_get, "mono_context_get", "object", FALSE);
343 register_icall (mono_context_set, "mono_context_set", "void object", FALSE);
344 register_icall (mono_gc_wbarrier_generic_nostore, "wb_generic", "void ptr", FALSE);
345 register_icall (mono_gchandle_get_target, "mono_gchandle_get_target", "object int32", TRUE);
346 register_icall (mono_gchandle_new, "mono_gchandle_new", "uint32 object bool", TRUE);
347 register_icall (mono_marshal_isinst_with_cache, "mono_marshal_isinst_with_cache", "object object ptr ptr", FALSE);
348 register_icall (mono_marshal_ftnptr_eh_callback, "mono_marshal_ftnptr_eh_callback", "void uint32", TRUE);
349 register_icall (mono_threads_enter_gc_safe_region_unbalanced, "mono_threads_enter_gc_safe_region_unbalanced", "ptr ptr", TRUE);
350 register_icall (mono_threads_exit_gc_safe_region_unbalanced, "mono_threads_exit_gc_safe_region_unbalanced", "void ptr ptr", TRUE);
351 register_icall (mono_threads_attach_coop, "mono_threads_attach_coop", "ptr ptr ptr", TRUE);
352 register_icall (mono_threads_detach_coop, "mono_threads_detach_coop", "void ptr ptr", TRUE);
353 register_icall (mono_icall_start, "mono_icall_start", "ptr ptr ptr", TRUE);
354 register_icall (mono_icall_end, "mono_icall_end", "void ptr ptr ptr", TRUE);
355 register_icall (mono_handle_new, "mono_handle_new", "ptr ptr", TRUE);
357 mono_cominterop_init ();
358 mono_remoting_init ();
360 mono_counters_register ("MonoClass::class_marshal_info_count count",
361 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &class_marshal_info_count);
366 void
367 mono_marshal_cleanup (void)
369 mono_cominterop_cleanup ();
371 mono_native_tls_free (load_type_info_tls_id);
372 mono_native_tls_free (last_error_tls_id);
373 mono_os_mutex_destroy (&marshal_mutex);
374 marshal_mutex_initialized = FALSE;
377 void
378 mono_marshal_lock_internal (void)
380 mono_marshal_lock ();
383 void
384 mono_marshal_unlock_internal (void)
386 mono_marshal_unlock ();
389 /* This is a JIT icall, it sets the pending exception and return NULL on error */
390 gpointer
391 mono_delegate_to_ftnptr (MonoDelegate *delegate)
393 MonoError error;
394 MonoMethod *method, *wrapper;
395 MonoClass *klass;
396 uint32_t target_handle = 0;
398 if (!delegate)
399 return NULL;
401 if (delegate->delegate_trampoline)
402 return delegate->delegate_trampoline;
404 klass = ((MonoObject *)delegate)->vtable->klass;
405 g_assert (klass->delegate);
407 method = delegate->method;
408 if (delegate->method_is_virtual)
409 method = mono_object_get_virtual_method (delegate->target, method);
411 if (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
412 const char *exc_class, *exc_arg;
413 gpointer ftnptr;
415 ftnptr = mono_lookup_pinvoke_call (method, &exc_class, &exc_arg);
416 if (!ftnptr) {
417 g_assert (exc_class);
418 mono_set_pending_exception (mono_exception_from_name_msg (mono_defaults.corlib, "System", exc_class, exc_arg));
419 return NULL;
421 return ftnptr;
424 if (delegate->target) {
425 /* Produce a location which can be embedded in JITted code */
426 target_handle = mono_gchandle_new_weakref (delegate->target, FALSE);
429 wrapper = mono_marshal_get_managed_wrapper (method, klass, target_handle);
431 delegate->delegate_trampoline = mono_compile_method_checked (wrapper, &error);
432 if (!is_ok (&error))
433 goto fail;
435 // Add the delegate to the delegate hash table
436 delegate_hash_table_add (delegate);
438 /* when the object is collected, collect the dynamic method, too */
439 mono_object_register_finalizer ((MonoObject*)delegate);
441 return delegate->delegate_trampoline;
443 fail:
444 if (target_handle != 0)
445 mono_gchandle_free (target_handle);
446 mono_error_set_pending_exception (&error);
447 return NULL;
451 * this hash table maps from a delegate trampoline object to a weak reference
452 * of the delegate. As an optimizations with a non-moving GC we store the
453 * object pointer itself, otherwise we use a GC handle.
455 static GHashTable *delegate_hash_table;
457 static GHashTable *
458 delegate_hash_table_new (void) {
459 return g_hash_table_new (NULL, NULL);
462 static void
463 delegate_hash_table_remove (MonoDelegate *d)
465 guint32 gchandle = 0;
467 mono_marshal_lock ();
468 if (delegate_hash_table == NULL)
469 delegate_hash_table = delegate_hash_table_new ();
470 if (mono_gc_is_moving ())
471 gchandle = GPOINTER_TO_UINT (g_hash_table_lookup (delegate_hash_table, d->delegate_trampoline));
472 g_hash_table_remove (delegate_hash_table, d->delegate_trampoline);
473 mono_marshal_unlock ();
474 if (gchandle && mono_gc_is_moving ())
475 mono_gchandle_free (gchandle);
478 static void
479 delegate_hash_table_add (MonoDelegate *d)
481 guint32 gchandle;
482 guint32 old_gchandle;
484 mono_marshal_lock ();
485 if (delegate_hash_table == NULL)
486 delegate_hash_table = delegate_hash_table_new ();
487 if (mono_gc_is_moving ()) {
488 gchandle = mono_gchandle_new_weakref ((MonoObject*)d, FALSE);
489 old_gchandle = GPOINTER_TO_UINT (g_hash_table_lookup (delegate_hash_table, d->delegate_trampoline));
490 g_hash_table_insert (delegate_hash_table, d->delegate_trampoline, GUINT_TO_POINTER (gchandle));
491 if (old_gchandle)
492 mono_gchandle_free (old_gchandle);
493 } else {
494 g_hash_table_insert (delegate_hash_table, d->delegate_trampoline, d);
496 mono_marshal_unlock ();
500 * mono_marshal_use_aot_wrappers:
502 * Instructs this module to use AOT compatible wrappers.
504 void
505 mono_marshal_use_aot_wrappers (gboolean use)
507 use_aot_wrappers = use;
510 static void
511 parse_unmanaged_function_pointer_attr (MonoClass *klass, MonoMethodPInvoke *piinfo)
513 MonoError error;
514 MonoCustomAttrInfo *cinfo;
515 MonoReflectionUnmanagedFunctionPointerAttribute *attr;
517 /* The attribute is only available in Net 2.0 */
518 if (mono_class_try_get_unmanaged_function_pointer_attribute_class ()) {
520 * The pinvoke attributes are stored in a real custom attribute so we have to
521 * construct it.
523 cinfo = mono_custom_attrs_from_class_checked (klass, &error);
524 if (!mono_error_ok (&error)) {
525 g_warning ("Could not load UnmanagedFunctionPointerAttribute due to %s", mono_error_get_message (&error));
526 mono_error_cleanup (&error);
528 if (cinfo && !mono_runtime_get_no_exec ()) {
529 attr = (MonoReflectionUnmanagedFunctionPointerAttribute*)mono_custom_attrs_get_attr_checked (cinfo, mono_class_try_get_unmanaged_function_pointer_attribute_class (), &error);
530 if (attr) {
531 piinfo->piflags = (attr->call_conv << 8) | (attr->charset ? (attr->charset - 1) * 2 : 1) | attr->set_last_error;
532 } else {
533 if (!mono_error_ok (&error)) {
534 g_warning ("Could not load UnmanagedFunctionPointerAttribute due to %s", mono_error_get_message (&error));
535 mono_error_cleanup (&error);
538 if (!cinfo->cached)
539 mono_custom_attrs_free (cinfo);
544 /* This is a JIT icall, it sets the pending exception and returns NULL on error */
545 MonoDelegate*
546 mono_ftnptr_to_delegate (MonoClass *klass, gpointer ftn)
548 MonoError error;
549 guint32 gchandle;
550 MonoDelegate *d;
552 if (ftn == NULL)
553 return NULL;
555 mono_marshal_lock ();
556 if (delegate_hash_table == NULL)
557 delegate_hash_table = delegate_hash_table_new ();
559 if (mono_gc_is_moving ()) {
560 gchandle = GPOINTER_TO_UINT (g_hash_table_lookup (delegate_hash_table, ftn));
561 mono_marshal_unlock ();
562 if (gchandle)
563 d = (MonoDelegate*)mono_gchandle_get_target (gchandle);
564 else
565 d = NULL;
566 } else {
567 d = (MonoDelegate *)g_hash_table_lookup (delegate_hash_table, ftn);
568 mono_marshal_unlock ();
570 if (d == NULL) {
571 /* This is a native function, so construct a delegate for it */
572 MonoMethodSignature *sig;
573 MonoMethod *wrapper;
574 MonoMarshalSpec **mspecs;
575 MonoMethod *invoke = mono_get_delegate_invoke (klass);
576 MonoMethodPInvoke piinfo;
577 MonoObject *this_obj;
578 int i;
580 if (use_aot_wrappers) {
581 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
582 this_obj = mono_value_box_checked (mono_domain_get (), mono_defaults.int_class, &ftn, &error);
583 if (!is_ok (&error)) {
584 mono_error_set_pending_exception (&error);
585 return NULL;
587 } else {
588 memset (&piinfo, 0, sizeof (piinfo));
589 parse_unmanaged_function_pointer_attr (klass, &piinfo);
591 mspecs = g_new0 (MonoMarshalSpec*, mono_method_signature (invoke)->param_count + 1);
592 mono_method_get_marshal_info (invoke, mspecs);
593 /* Freed below so don't alloc from mempool */
594 sig = mono_metadata_signature_dup (mono_method_signature (invoke));
595 sig->hasthis = 0;
597 wrapper = mono_marshal_get_native_func_wrapper (klass->image, sig, &piinfo, mspecs, ftn);
598 this_obj = NULL;
600 for (i = mono_method_signature (invoke)->param_count; i >= 0; i--)
601 if (mspecs [i])
602 mono_metadata_free_marshal_spec (mspecs [i]);
603 g_free (mspecs);
604 g_free (sig);
607 d = (MonoDelegate*)mono_object_new_checked (mono_domain_get (), klass, &error);
608 if (!mono_error_ok (&error)) {
609 mono_error_set_pending_exception (&error);
610 return NULL;
612 gpointer compiled_ptr = mono_compile_method_checked (wrapper, &error);
613 if (mono_error_set_pending_exception (&error))
614 return NULL;
615 mono_delegate_ctor_with_method ((MonoObject*)d, this_obj, compiled_ptr, wrapper, &error);
616 if (mono_error_set_pending_exception (&error))
617 return NULL;
620 if (d->object.vtable->domain != mono_domain_get ()) {
621 mono_set_pending_exception (mono_get_exception_not_supported ("Delegates cannot be marshalled from native code into a domain other than their home domain"));
622 return NULL;
625 return d;
628 void
629 mono_delegate_free_ftnptr (MonoDelegate *delegate)
631 MonoJitInfo *ji;
632 void *ptr;
634 delegate_hash_table_remove (delegate);
636 ptr = (gpointer)InterlockedExchangePointer (&delegate->delegate_trampoline, NULL);
638 if (!delegate->target) {
639 /* The wrapper method is shared between delegates -> no need to free it */
640 return;
643 if (ptr) {
644 uint32_t gchandle;
645 void **method_data;
646 MonoMethod *method;
648 ji = mono_jit_info_table_find (mono_domain_get (), (char *)mono_get_addr_from_ftnptr (ptr));
649 g_assert (ji);
651 method = mono_jit_info_get_method (ji);
652 method_data = (void **)((MonoMethodWrapper*)method)->method_data;
654 /*the target gchandle is the first entry after size and the wrapper itself.*/
655 gchandle = GPOINTER_TO_UINT (method_data [2]);
657 if (gchandle)
658 mono_gchandle_free (gchandle);
660 mono_runtime_free_method (mono_object_domain (delegate), method);
664 /* This is a JIT icall, it sets the pending exception and returns NULL on error */
665 static MonoString *
666 mono_string_from_byvalstr (const char *data, int max_len)
668 MonoError error;
669 MonoDomain *domain = mono_domain_get ();
670 int len = 0;
672 if (!data)
673 return NULL;
675 while (len < max_len - 1 && data [len])
676 len++;
678 MonoString *result = mono_string_new_len_checked (domain, data, len, &error);
679 mono_error_set_pending_exception (&error);
680 return result;
683 /* This is a JIT icall, it sets the pending exception and return NULL on error */
684 static MonoString *
685 mono_string_from_byvalwstr (gunichar2 *data, int max_len)
687 MonoError error;
688 MonoString *res = NULL;
689 MonoDomain *domain = mono_domain_get ();
690 int len = 0;
692 if (!data)
693 return NULL;
695 while (data [len]) len++;
697 res = mono_string_new_utf16_checked (domain, data, MIN (len, max_len), &error);
698 if (!mono_error_ok (&error)) {
699 mono_error_set_pending_exception (&error);
700 return NULL;
702 return res;
705 gpointer
706 mono_array_to_savearray (MonoArray *array)
708 if (!array)
709 return NULL;
711 g_assert_not_reached ();
712 return NULL;
715 gpointer
716 mono_array_to_lparray (MonoArray *array)
718 #ifndef DISABLE_COM
719 gpointer *nativeArray = NULL;
720 int nativeArraySize = 0;
722 int i = 0;
723 MonoClass *klass;
724 #endif
726 if (!array)
727 return NULL;
728 #ifndef DISABLE_COM
730 klass = array->obj.vtable->klass;
732 switch (klass->element_class->byval_arg.type) {
733 case MONO_TYPE_VOID:
734 g_assert_not_reached ();
735 break;
736 case MONO_TYPE_CLASS:
737 nativeArraySize = array->max_length;
738 nativeArray = (void **)malloc(sizeof(gpointer) * nativeArraySize);
739 for(i = 0; i < nativeArraySize; ++i)
740 nativeArray[i] = ves_icall_System_Runtime_InteropServices_Marshal_GetIUnknownForObjectInternal(((MonoObject **)array->vector)[i]);
741 return nativeArray;
742 case MONO_TYPE_U1:
743 case MONO_TYPE_BOOLEAN:
744 case MONO_TYPE_I1:
745 case MONO_TYPE_U2:
746 case MONO_TYPE_CHAR:
747 case MONO_TYPE_I2:
748 case MONO_TYPE_I:
749 case MONO_TYPE_U:
750 case MONO_TYPE_I4:
751 case MONO_TYPE_U4:
752 case MONO_TYPE_U8:
753 case MONO_TYPE_I8:
754 case MONO_TYPE_R4:
755 case MONO_TYPE_R8:
756 case MONO_TYPE_VALUETYPE:
757 case MONO_TYPE_PTR:
758 /* nothing to do */
759 break;
760 case MONO_TYPE_GENERICINST:
761 case MONO_TYPE_OBJECT:
762 case MONO_TYPE_ARRAY:
763 case MONO_TYPE_SZARRAY:
764 case MONO_TYPE_STRING:
765 default:
766 g_warning ("type 0x%x not handled", klass->element_class->byval_arg.type);
767 g_assert_not_reached ();
769 #endif
770 return array->vector;
773 void
774 mono_free_lparray (MonoArray *array, gpointer* nativeArray)
776 #ifndef DISABLE_COM
777 MonoClass *klass;
778 int i = 0;
780 if (!array)
781 return;
783 if (!nativeArray)
784 return;
785 klass = array->obj.vtable->klass;
787 if (klass->element_class->byval_arg.type == MONO_TYPE_CLASS) {
788 for(i = 0; i < array->max_length; ++i)
789 mono_marshal_free_ccw (mono_array_get (array, MonoObject*, i));
790 g_free (nativeArray);
792 #endif
795 static void
796 mono_byvalarray_to_array (MonoArray *arr, gpointer native_arr, MonoClass *elclass, guint32 elnum)
798 g_assert (arr->obj.vtable->klass->element_class == mono_defaults.char_class);
800 if (elclass == mono_defaults.byte_class) {
801 GError *error = NULL;
802 guint16 *ut;
803 glong items_written;
805 ut = g_utf8_to_utf16 ((const gchar *)native_arr, elnum, NULL, &items_written, &error);
807 if (!error) {
808 memcpy (mono_array_addr (arr, guint16, 0), ut, items_written * sizeof (guint16));
809 g_free (ut);
811 else
812 g_error_free (error);
814 else
815 g_assert_not_reached ();
818 static void
819 mono_byvalarray_to_byte_array (MonoArray *arr, gpointer native_arr, guint32 elnum)
821 mono_byvalarray_to_array (arr, native_arr, mono_defaults.byte_class, elnum);
824 /* This is a JIT icall, it sets the pending exception and returns on error */
825 static void
826 mono_array_to_byvalarray (gpointer native_arr, MonoArray *arr, MonoClass *elclass, guint32 elnum)
828 g_assert (arr->obj.vtable->klass->element_class == mono_defaults.char_class);
830 if (elclass == mono_defaults.byte_class) {
831 char *as;
832 GError *error = NULL;
834 as = g_utf16_to_utf8 (mono_array_addr (arr, gunichar2, 0), mono_array_length (arr), NULL, NULL, &error);
835 if (error) {
836 mono_set_pending_exception (mono_get_exception_argument ("string", error->message));
837 g_error_free (error);
838 return;
841 memcpy (native_arr, as, MIN (strlen (as), elnum));
842 g_free (as);
843 } else {
844 g_assert_not_reached ();
848 static void
849 mono_array_to_byte_byvalarray (gpointer native_arr, MonoArray *arr, guint32 elnum)
851 mono_array_to_byvalarray (native_arr, arr, mono_defaults.byte_class, elnum);
854 static MonoStringBuilder *
855 mono_string_builder_new (int starting_string_length)
857 static MonoClass *string_builder_class;
858 static MonoMethod *sb_ctor;
859 static void *args [1];
861 MonoError error;
862 int initial_len = starting_string_length;
864 if (initial_len < 0)
865 initial_len = 0;
867 if (!sb_ctor) {
868 MonoMethodDesc *desc;
869 MonoMethod *m;
871 string_builder_class = mono_class_get_string_builder_class ();
872 g_assert (string_builder_class);
873 desc = mono_method_desc_new (":.ctor(int)", FALSE);
874 m = mono_method_desc_search_in_class (desc, string_builder_class);
875 g_assert (m);
876 mono_method_desc_free (desc);
877 mono_memory_barrier ();
878 sb_ctor = m;
881 // We make a new array in the _to_builder function, so this
882 // array will always be garbage collected.
883 args [0] = &initial_len;
885 MonoStringBuilder *sb = (MonoStringBuilder*)mono_object_new_checked (mono_domain_get (), string_builder_class, &error);
886 mono_error_assert_ok (&error);
888 MonoObject *exc;
889 mono_runtime_try_invoke (sb_ctor, sb, args, &exc, &error);
890 g_assert (exc == NULL);
891 mono_error_assert_ok (&error);
893 g_assert (sb->chunkChars->max_length >= initial_len);
895 return sb;
898 static void
899 mono_string_utf16_to_builder_copy (MonoStringBuilder *sb, gunichar2 *text, size_t string_len)
901 gunichar2 *charDst = (gunichar2 *)sb->chunkChars->vector;
902 gunichar2 *charSrc = (gunichar2 *)text;
903 memcpy (charDst, charSrc, sizeof (gunichar2) * string_len);
905 sb->chunkLength = string_len;
907 return;
910 MonoStringBuilder *
911 mono_string_utf16_to_builder2 (gunichar2 *text)
913 if (!text)
914 return NULL;
916 int len;
917 for (len = 0; text [len] != 0; ++len);
919 MonoStringBuilder *sb = mono_string_builder_new (len);
920 mono_string_utf16_to_builder (sb, text);
922 return sb;
925 void
926 mono_string_utf8_to_builder (MonoStringBuilder *sb, char *text)
928 if (!sb || !text)
929 return;
931 GError *error = NULL;
932 glong copied;
933 gunichar2* ut = g_utf8_to_utf16 (text, strlen (text), NULL, &copied, &error);
934 int capacity = mono_string_builder_capacity (sb);
936 if (copied > capacity)
937 copied = capacity;
939 if (!error) {
940 MONO_OBJECT_SETREF (sb, chunkPrevious, NULL);
941 mono_string_utf16_to_builder_copy (sb, ut, copied);
942 } else
943 g_error_free (error);
945 g_free (ut);
948 MonoStringBuilder *
949 mono_string_utf8_to_builder2 (char *text)
951 if (!text)
952 return NULL;
954 int len = strlen (text);
955 MonoStringBuilder *sb = mono_string_builder_new (len);
956 mono_string_utf8_to_builder (sb, text);
958 return sb;
961 void
962 mono_string_utf16_to_builder (MonoStringBuilder *sb, gunichar2 *text)
964 if (!sb || !text)
965 return;
967 guint32 len;
968 for (len = 0; text [len] != 0; ++len);
970 if (len > mono_string_builder_capacity (sb))
971 len = mono_string_builder_capacity (sb);
973 mono_string_utf16_to_builder_copy (sb, text, len);
977 * mono_string_builder_to_utf8:
978 * @sb: the string builder
980 * Converts to utf8 the contents of the MonoStringBuilder.
982 * Returns: a utf8 string with the contents of the StringBuilder.
984 * The return value must be released with mono_marshal_free.
986 * This is a JIT icall, it sets the pending exception and returns NULL on error.
988 gchar*
989 mono_string_builder_to_utf8 (MonoStringBuilder *sb)
991 MonoError error;
992 GError *gerror = NULL;
993 glong byte_count;
994 if (!sb)
995 return NULL;
997 gunichar2 *str_utf16 = mono_string_builder_to_utf16 (sb);
999 guint str_len = mono_string_builder_string_length (sb);
1001 gchar *tmp = g_utf16_to_utf8 (str_utf16, str_len, NULL, &byte_count, &gerror);
1003 if (gerror) {
1004 g_error_free (gerror);
1005 mono_marshal_free (str_utf16);
1006 mono_set_pending_exception (mono_get_exception_execution_engine ("Failed to convert StringBuilder from utf16 to utf8"));
1007 return NULL;
1008 } else {
1009 guint len = mono_string_builder_capacity (sb) + 1;
1010 gchar *res = (gchar *)mono_marshal_alloc (MAX (byte_count+1, len * sizeof (gchar)), &error);
1011 if (!mono_error_ok (&error)) {
1012 mono_marshal_free (str_utf16);
1013 g_free (tmp);
1014 mono_error_set_pending_exception (&error);
1015 return NULL;
1018 memcpy (res, tmp, byte_count);
1019 res[byte_count] = '\0';
1021 mono_marshal_free (str_utf16);
1022 g_free (tmp);
1023 return res;
1028 * mono_string_builder_to_utf16:
1029 * @sb: the string builder
1031 * Converts to utf16 the contents of the MonoStringBuilder.
1033 * Returns: a utf16 string with the contents of the StringBuilder.
1035 * The return value must be released with mono_marshal_free.
1037 * This is a JIT icall, it sets the pending exception and returns NULL on error.
1039 gunichar2*
1040 mono_string_builder_to_utf16 (MonoStringBuilder *sb)
1042 MonoError error;
1044 if (!sb)
1045 return NULL;
1047 g_assert (sb->chunkChars);
1049 guint len = mono_string_builder_capacity (sb);
1051 if (len == 0)
1052 len = 1;
1054 gunichar2 *str = (gunichar2 *)mono_marshal_alloc ((len + 1) * sizeof (gunichar2), &error);
1055 if (!mono_error_ok (&error)) {
1056 mono_error_set_pending_exception (&error);
1057 return NULL;
1060 str[len] = '\0';
1062 if (len == 0)
1063 return str;
1065 MonoStringBuilder* chunk = sb;
1066 do {
1067 if (chunk->chunkLength > 0) {
1068 // Check that we will not overrun our boundaries.
1069 gunichar2 *source = (gunichar2 *)chunk->chunkChars->vector;
1071 if (chunk->chunkLength <= len) {
1072 memcpy (str + chunk->chunkOffset, source, chunk->chunkLength * sizeof(gunichar2));
1073 } else {
1074 g_error ("A chunk in the StringBuilder had a length longer than expected from the offset.");
1077 len -= chunk->chunkLength;
1079 chunk = chunk->chunkPrevious;
1080 } while (chunk != NULL);
1082 return str;
1085 #ifndef HOST_WIN32
1086 /* This is a JIT icall, it sets the pending exception and returns NULL on error. */
1087 static gpointer
1088 mono_string_to_utf8str (MonoString *s)
1090 MonoError error;
1091 char *result = mono_string_to_utf8_checked (s, &error);
1092 mono_error_set_pending_exception (&error);
1093 return result;
1095 #endif
1097 gpointer
1098 mono_string_to_ansibstr (MonoString *string_obj)
1100 g_error ("UnmanagedMarshal.BStr is not implemented.");
1101 return NULL;
1105 * mono_string_to_byvalstr:
1106 * @dst: Where to store the null-terminated utf8 decoded string.
1107 * @src: the MonoString to copy.
1108 * @size: the maximum number of bytes to copy.
1110 * Copies the MonoString pointed to by @src as a utf8 string
1111 * into @dst, it copies at most @size bytes into the destination.
1113 void
1114 mono_string_to_byvalstr (gpointer dst, MonoString *src, int size)
1116 MonoError error;
1117 char *s;
1118 int len;
1120 g_assert (dst != NULL);
1121 g_assert (size > 0);
1123 memset (dst, 0, size);
1124 if (!src)
1125 return;
1127 s = mono_string_to_utf8_checked (src, &error);
1128 if (mono_error_set_pending_exception (&error))
1129 return;
1130 len = MIN (size, strlen (s));
1131 if (len >= size)
1132 len--;
1133 memcpy (dst, s, len);
1134 g_free (s);
1138 * mono_string_to_byvalwstr:
1139 * @dst: Where to store the null-terminated utf16 decoded string.
1140 * @src: the MonoString to copy.
1141 * @size: the maximum number of bytes to copy.
1143 * Copies the MonoString pointed to by @src as a utf16 string into
1144 * @dst, it copies at most @size bytes into the destination (including
1145 * a terminating 16-bit zero terminator).
1147 void
1148 mono_string_to_byvalwstr (gpointer dst, MonoString *src, int size)
1150 int len;
1152 g_assert (dst != NULL);
1153 g_assert (size > 1);
1155 if (!src) {
1156 memset (dst, 0, size * 2);
1157 return;
1160 len = MIN (size, (mono_string_length (src)));
1161 memcpy (dst, mono_string_chars (src), size * 2);
1162 if (size <= mono_string_length (src))
1163 len--;
1164 *((gunichar2 *) dst + len) = 0;
1167 /* this is an icall, it sets the pending exception and returns NULL on error */
1168 static MonoString*
1169 mono_string_new_len_wrapper (const char *text, guint length)
1171 MonoError error;
1172 MonoString *result = mono_string_new_len_checked (mono_domain_get (), text, length, &error);
1173 mono_error_set_pending_exception (&error);
1174 return result;
1177 #ifndef DISABLE_JIT
1180 * mono_mb_emit_exception_marshal_directive:
1182 * This function assumes ownership of MSG, which should be malloc-ed.
1184 static void
1185 mono_mb_emit_exception_marshal_directive (MonoMethodBuilder *mb, char *msg)
1187 char *s;
1189 if (!mb->dynamic) {
1190 s = mono_image_strdup (mb->method->klass->image, msg);
1191 g_free (msg);
1192 } else {
1193 s = g_strdup (msg);
1195 mono_mb_emit_exception_full (mb, "System.Runtime.InteropServices", "MarshalDirectiveException", s);
1198 #endif /* !DISABLE_JIT */
1200 guint
1201 mono_type_to_ldind (MonoType *type)
1203 if (type->byref)
1204 return CEE_LDIND_I;
1206 handle_enum:
1207 switch (type->type) {
1208 case MONO_TYPE_I1:
1209 return CEE_LDIND_I1;
1210 case MONO_TYPE_U1:
1211 case MONO_TYPE_BOOLEAN:
1212 return CEE_LDIND_U1;
1213 case MONO_TYPE_I2:
1214 return CEE_LDIND_I2;
1215 case MONO_TYPE_U2:
1216 case MONO_TYPE_CHAR:
1217 return CEE_LDIND_U2;
1218 case MONO_TYPE_I4:
1219 return CEE_LDIND_I4;
1220 case MONO_TYPE_U4:
1221 return CEE_LDIND_U4;
1222 case MONO_TYPE_I:
1223 case MONO_TYPE_U:
1224 case MONO_TYPE_PTR:
1225 case MONO_TYPE_FNPTR:
1226 return CEE_LDIND_I;
1227 case MONO_TYPE_CLASS:
1228 case MONO_TYPE_STRING:
1229 case MONO_TYPE_OBJECT:
1230 case MONO_TYPE_SZARRAY:
1231 case MONO_TYPE_ARRAY:
1232 return CEE_LDIND_REF;
1233 case MONO_TYPE_I8:
1234 case MONO_TYPE_U8:
1235 return CEE_LDIND_I8;
1236 case MONO_TYPE_R4:
1237 return CEE_LDIND_R4;
1238 case MONO_TYPE_R8:
1239 return CEE_LDIND_R8;
1240 case MONO_TYPE_VALUETYPE:
1241 if (type->data.klass->enumtype) {
1242 type = mono_class_enum_basetype (type->data.klass);
1243 goto handle_enum;
1245 return CEE_LDOBJ;
1246 case MONO_TYPE_TYPEDBYREF:
1247 return CEE_LDOBJ;
1248 case MONO_TYPE_GENERICINST:
1249 type = &type->data.generic_class->container_class->byval_arg;
1250 goto handle_enum;
1251 default:
1252 g_error ("unknown type 0x%02x in type_to_ldind", type->type);
1254 return -1;
1257 guint
1258 mono_type_to_stind (MonoType *type)
1260 if (type->byref)
1261 return MONO_TYPE_IS_REFERENCE (type) ? CEE_STIND_REF : CEE_STIND_I;
1264 handle_enum:
1265 switch (type->type) {
1266 case MONO_TYPE_I1:
1267 case MONO_TYPE_U1:
1268 case MONO_TYPE_BOOLEAN:
1269 return CEE_STIND_I1;
1270 case MONO_TYPE_I2:
1271 case MONO_TYPE_U2:
1272 case MONO_TYPE_CHAR:
1273 return CEE_STIND_I2;
1274 case MONO_TYPE_I4:
1275 case MONO_TYPE_U4:
1276 return CEE_STIND_I4;
1277 case MONO_TYPE_I:
1278 case MONO_TYPE_U:
1279 case MONO_TYPE_PTR:
1280 case MONO_TYPE_FNPTR:
1281 return CEE_STIND_I;
1282 case MONO_TYPE_CLASS:
1283 case MONO_TYPE_STRING:
1284 case MONO_TYPE_OBJECT:
1285 case MONO_TYPE_SZARRAY:
1286 case MONO_TYPE_ARRAY:
1287 return CEE_STIND_REF;
1288 case MONO_TYPE_I8:
1289 case MONO_TYPE_U8:
1290 return CEE_STIND_I8;
1291 case MONO_TYPE_R4:
1292 return CEE_STIND_R4;
1293 case MONO_TYPE_R8:
1294 return CEE_STIND_R8;
1295 case MONO_TYPE_VALUETYPE:
1296 if (type->data.klass->enumtype) {
1297 type = mono_class_enum_basetype (type->data.klass);
1298 goto handle_enum;
1300 return CEE_STOBJ;
1301 case MONO_TYPE_TYPEDBYREF:
1302 return CEE_STOBJ;
1303 case MONO_TYPE_GENERICINST:
1304 type = &type->data.generic_class->container_class->byval_arg;
1305 goto handle_enum;
1306 default:
1307 g_error ("unknown type 0x%02x in type_to_stind", type->type);
1309 return -1;
1312 #ifndef DISABLE_JIT
1314 static void
1315 emit_ptr_to_object_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv conv, MonoMarshalSpec *mspec)
1317 switch (conv) {
1318 case MONO_MARSHAL_CONV_BOOL_I4:
1319 mono_mb_emit_ldloc (mb, 1);
1320 mono_mb_emit_ldloc (mb, 0);
1321 mono_mb_emit_byte (mb, CEE_LDIND_I4);
1322 mono_mb_emit_byte (mb, CEE_BRFALSE_S);
1323 mono_mb_emit_byte (mb, 3);
1324 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
1325 mono_mb_emit_byte (mb, CEE_BR_S);
1326 mono_mb_emit_byte (mb, 1);
1327 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
1328 mono_mb_emit_byte (mb, CEE_STIND_I1);
1329 break;
1330 case MONO_MARSHAL_CONV_BOOL_VARIANTBOOL:
1331 mono_mb_emit_ldloc (mb, 1);
1332 mono_mb_emit_ldloc (mb, 0);
1333 mono_mb_emit_byte (mb, CEE_LDIND_I2);
1334 mono_mb_emit_byte (mb, CEE_BRFALSE_S);
1335 mono_mb_emit_byte (mb, 3);
1336 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
1337 mono_mb_emit_byte (mb, CEE_BR_S);
1338 mono_mb_emit_byte (mb, 1);
1339 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
1340 mono_mb_emit_byte (mb, CEE_STIND_I1);
1341 break;
1342 case MONO_MARSHAL_CONV_ARRAY_BYVALARRAY: {
1343 MonoClass *eklass = NULL;
1344 int esize;
1346 if (type->type == MONO_TYPE_SZARRAY) {
1347 eklass = type->data.klass;
1348 } else {
1349 g_assert_not_reached ();
1352 esize = mono_class_native_size (eklass, NULL);
1354 /* create a new array */
1355 mono_mb_emit_ldloc (mb, 1);
1356 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1357 mono_mb_emit_op (mb, CEE_NEWARR, eklass);
1358 mono_mb_emit_byte (mb, CEE_STIND_REF);
1360 if (eklass->blittable) {
1361 /* copy the elements */
1362 mono_mb_emit_ldloc (mb, 1);
1363 mono_mb_emit_byte (mb, CEE_LDIND_I);
1364 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
1365 mono_mb_emit_byte (mb, CEE_ADD);
1366 mono_mb_emit_ldloc (mb, 0);
1367 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem * esize);
1368 mono_mb_emit_byte (mb, CEE_PREFIX1);
1369 mono_mb_emit_byte (mb, CEE_CPBLK);
1371 else {
1372 int array_var, src_var, dst_var, index_var;
1373 guint32 label2, label3;
1375 array_var = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
1376 src_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1377 dst_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1379 /* set array_var */
1380 mono_mb_emit_ldloc (mb, 1);
1381 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1382 mono_mb_emit_stloc (mb, array_var);
1384 /* save the old src pointer */
1385 mono_mb_emit_ldloc (mb, 0);
1386 mono_mb_emit_stloc (mb, src_var);
1387 /* save the old dst pointer */
1388 mono_mb_emit_ldloc (mb, 1);
1389 mono_mb_emit_stloc (mb, dst_var);
1391 /* Emit marshalling loop */
1392 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1393 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
1394 mono_mb_emit_stloc (mb, index_var);
1396 /* Loop header */
1397 label2 = mono_mb_get_label (mb);
1398 mono_mb_emit_ldloc (mb, index_var);
1399 mono_mb_emit_ldloc (mb, array_var);
1400 mono_mb_emit_byte (mb, CEE_LDLEN);
1401 label3 = mono_mb_emit_branch (mb, CEE_BGE);
1403 /* src is already set */
1405 /* Set dst */
1406 mono_mb_emit_ldloc (mb, array_var);
1407 mono_mb_emit_ldloc (mb, index_var);
1408 mono_mb_emit_op (mb, CEE_LDELEMA, eklass);
1409 mono_mb_emit_stloc (mb, 1);
1411 /* Do the conversion */
1412 emit_struct_conv (mb, eklass, TRUE);
1414 /* Loop footer */
1415 mono_mb_emit_add_to_local (mb, index_var, 1);
1417 mono_mb_emit_branch_label (mb, CEE_BR, label2);
1419 mono_mb_patch_branch (mb, label3);
1421 /* restore the old src pointer */
1422 mono_mb_emit_ldloc (mb, src_var);
1423 mono_mb_emit_stloc (mb, 0);
1424 /* restore the old dst pointer */
1425 mono_mb_emit_ldloc (mb, dst_var);
1426 mono_mb_emit_stloc (mb, 1);
1428 break;
1430 case MONO_MARSHAL_CONV_ARRAY_BYVALCHARARRAY: {
1431 MonoClass *eclass = mono_defaults.char_class;
1433 /* create a new array */
1434 mono_mb_emit_ldloc (mb, 1);
1435 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1436 mono_mb_emit_op (mb, CEE_NEWARR, eclass);
1437 mono_mb_emit_byte (mb, CEE_STIND_REF);
1439 mono_mb_emit_ldloc (mb, 1);
1440 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1441 mono_mb_emit_ldloc (mb, 0);
1442 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1443 mono_mb_emit_icall (mb, mono_byvalarray_to_byte_array);
1444 break;
1446 case MONO_MARSHAL_CONV_STR_BYVALSTR:
1447 if (mspec && mspec->native == MONO_NATIVE_BYVALTSTR && mspec->data.array_data.num_elem) {
1448 mono_mb_emit_ldloc (mb, 1);
1449 mono_mb_emit_ldloc (mb, 0);
1450 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1451 mono_mb_emit_icall (mb, mono_string_from_byvalstr);
1452 } else {
1453 mono_mb_emit_ldloc (mb, 1);
1454 mono_mb_emit_ldloc (mb, 0);
1455 mono_mb_emit_icall (mb, mono_string_new_wrapper);
1457 mono_mb_emit_byte (mb, CEE_STIND_REF);
1458 break;
1459 case MONO_MARSHAL_CONV_STR_BYVALWSTR:
1460 if (mspec && mspec->native == MONO_NATIVE_BYVALTSTR && mspec->data.array_data.num_elem) {
1461 mono_mb_emit_ldloc (mb, 1);
1462 mono_mb_emit_ldloc (mb, 0);
1463 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1464 mono_mb_emit_icall (mb, mono_string_from_byvalwstr);
1465 } else {
1466 mono_mb_emit_ldloc (mb, 1);
1467 mono_mb_emit_ldloc (mb, 0);
1468 mono_mb_emit_icall (mb, ves_icall_mono_string_from_utf16);
1470 mono_mb_emit_byte (mb, CEE_STIND_REF);
1471 break;
1472 case MONO_MARSHAL_CONV_STR_LPTSTR:
1473 mono_mb_emit_ldloc (mb, 1);
1474 mono_mb_emit_ldloc (mb, 0);
1475 mono_mb_emit_byte (mb, CEE_LDIND_I);
1476 #ifdef TARGET_WIN32
1477 mono_mb_emit_icall (mb, ves_icall_mono_string_from_utf16);
1478 #else
1479 mono_mb_emit_icall (mb, mono_string_new_wrapper);
1480 #endif
1481 mono_mb_emit_byte (mb, CEE_STIND_REF);
1482 break;
1484 // In Mono historically LPSTR was treated as a UTF8STR
1485 case MONO_MARSHAL_CONV_STR_LPSTR:
1486 case MONO_MARSHAL_CONV_STR_UTF8STR:
1487 mono_mb_emit_ldloc (mb, 1);
1488 mono_mb_emit_ldloc (mb, 0);
1489 mono_mb_emit_byte (mb, CEE_LDIND_I);
1490 mono_mb_emit_icall (mb, mono_string_new_wrapper);
1491 mono_mb_emit_byte (mb, CEE_STIND_REF);
1492 break;
1493 case MONO_MARSHAL_CONV_STR_LPWSTR:
1494 mono_mb_emit_ldloc (mb, 1);
1495 mono_mb_emit_ldloc (mb, 0);
1496 mono_mb_emit_byte (mb, CEE_LDIND_I);
1497 mono_mb_emit_icall (mb, ves_icall_mono_string_from_utf16);
1498 mono_mb_emit_byte (mb, CEE_STIND_REF);
1499 break;
1500 case MONO_MARSHAL_CONV_OBJECT_STRUCT: {
1501 MonoClass *klass = mono_class_from_mono_type (type);
1502 int src_var, dst_var;
1504 src_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1505 dst_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1507 /* *dst = new object */
1508 mono_mb_emit_ldloc (mb, 1);
1509 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
1510 mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, klass);
1511 mono_mb_emit_byte (mb, CEE_STIND_REF);
1513 /* save the old src pointer */
1514 mono_mb_emit_ldloc (mb, 0);
1515 mono_mb_emit_stloc (mb, src_var);
1516 /* save the old dst pointer */
1517 mono_mb_emit_ldloc (mb, 1);
1518 mono_mb_emit_stloc (mb, dst_var);
1520 /* dst = pointer to newly created object data */
1521 mono_mb_emit_ldloc (mb, 1);
1522 mono_mb_emit_byte (mb, CEE_LDIND_I);
1523 mono_mb_emit_icon (mb, sizeof (MonoObject));
1524 mono_mb_emit_byte (mb, CEE_ADD);
1525 mono_mb_emit_stloc (mb, 1);
1527 emit_struct_conv (mb, klass, TRUE);
1529 /* restore the old src pointer */
1530 mono_mb_emit_ldloc (mb, src_var);
1531 mono_mb_emit_stloc (mb, 0);
1532 /* restore the old dst pointer */
1533 mono_mb_emit_ldloc (mb, dst_var);
1534 mono_mb_emit_stloc (mb, 1);
1535 break;
1537 case MONO_MARSHAL_CONV_DEL_FTN: {
1538 MonoClass *klass = mono_class_from_mono_type (type);
1540 mono_mb_emit_ldloc (mb, 1);
1541 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
1542 mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
1543 mono_mb_emit_ldloc (mb, 0);
1544 mono_mb_emit_byte (mb, CEE_LDIND_I);
1545 mono_mb_emit_icall (mb, mono_ftnptr_to_delegate);
1546 mono_mb_emit_byte (mb, CEE_STIND_REF);
1547 break;
1549 case MONO_MARSHAL_CONV_ARRAY_LPARRAY:
1550 g_error ("Structure field of type %s can't be marshalled as LPArray", mono_class_from_mono_type (type)->name);
1551 break;
1553 #ifndef DISABLE_COM
1554 case MONO_MARSHAL_CONV_OBJECT_INTERFACE:
1555 case MONO_MARSHAL_CONV_OBJECT_IUNKNOWN:
1556 case MONO_MARSHAL_CONV_OBJECT_IDISPATCH:
1557 mono_cominterop_emit_ptr_to_object_conv (mb, type, conv, mspec);
1558 break;
1559 #endif /* DISABLE_COM */
1561 case MONO_MARSHAL_CONV_SAFEHANDLE: {
1563 * Passing SafeHandles as ref does not allow the unmanaged code
1564 * to change the SafeHandle value. If the value is changed,
1565 * we should issue a diagnostic exception (NotSupportedException)
1566 * that informs the user that changes to handles in unmanaged code
1567 * is not supported.
1569 * Since we currently have no access to the original
1570 * SafeHandle that was used during the marshalling,
1571 * for now we just ignore this, and ignore/discard any
1572 * changes that might have happened to the handle.
1574 break;
1577 case MONO_MARSHAL_CONV_HANDLEREF: {
1579 * Passing HandleRefs in a struct that is ref()ed does not
1580 * copy the values back to the HandleRef
1582 break;
1585 case MONO_MARSHAL_CONV_STR_BSTR:
1586 case MONO_MARSHAL_CONV_STR_ANSIBSTR:
1587 case MONO_MARSHAL_CONV_STR_TBSTR:
1588 case MONO_MARSHAL_CONV_ARRAY_SAVEARRAY:
1589 default: {
1590 char *msg = g_strdup_printf ("marshaling conversion %d not implemented", conv);
1592 mono_mb_emit_exception_marshal_directive (mb, msg);
1593 break;
1598 static gpointer
1599 conv_to_icall (MonoMarshalConv conv, int *ind_store_type)
1601 int dummy;
1602 if (!ind_store_type)
1603 ind_store_type = &dummy;
1604 *ind_store_type = CEE_STIND_I;
1605 switch (conv) {
1606 case MONO_MARSHAL_CONV_STR_LPWSTR:
1607 return mono_marshal_string_to_utf16;
1608 case MONO_MARSHAL_CONV_LPWSTR_STR:
1609 *ind_store_type = CEE_STIND_REF;
1610 return ves_icall_mono_string_from_utf16;
1611 case MONO_MARSHAL_CONV_LPTSTR_STR:
1612 *ind_store_type = CEE_STIND_REF;
1613 return mono_string_new_wrapper;
1614 case MONO_MARSHAL_CONV_UTF8STR_STR:
1615 case MONO_MARSHAL_CONV_LPSTR_STR:
1616 *ind_store_type = CEE_STIND_REF;
1617 return mono_string_new_wrapper;
1618 case MONO_MARSHAL_CONV_STR_LPTSTR:
1619 #ifdef TARGET_WIN32
1620 return mono_marshal_string_to_utf16;
1621 #else
1622 return mono_string_to_utf8str;
1623 #endif
1624 // In Mono historically LPSTR was treated as a UTF8STR
1625 case MONO_MARSHAL_CONV_STR_UTF8STR:
1626 case MONO_MARSHAL_CONV_STR_LPSTR:
1627 return mono_string_to_utf8str;
1628 case MONO_MARSHAL_CONV_STR_BSTR:
1629 return mono_string_to_bstr;
1630 case MONO_MARSHAL_CONV_BSTR_STR:
1631 *ind_store_type = CEE_STIND_REF;
1632 return mono_string_from_bstr_icall;
1633 case MONO_MARSHAL_CONV_STR_TBSTR:
1634 case MONO_MARSHAL_CONV_STR_ANSIBSTR:
1635 return mono_string_to_ansibstr;
1636 case MONO_MARSHAL_CONV_SB_UTF8STR:
1637 case MONO_MARSHAL_CONV_SB_LPSTR:
1638 return mono_string_builder_to_utf8;
1639 case MONO_MARSHAL_CONV_SB_LPTSTR:
1640 #ifdef TARGET_WIN32
1641 return mono_string_builder_to_utf16;
1642 #else
1643 return mono_string_builder_to_utf8;
1644 #endif
1645 case MONO_MARSHAL_CONV_SB_LPWSTR:
1646 return mono_string_builder_to_utf16;
1647 case MONO_MARSHAL_CONV_ARRAY_SAVEARRAY:
1648 return mono_array_to_savearray;
1649 case MONO_MARSHAL_CONV_ARRAY_LPARRAY:
1650 return mono_array_to_lparray;
1651 case MONO_MARSHAL_FREE_LPARRAY:
1652 return mono_free_lparray;
1653 case MONO_MARSHAL_CONV_DEL_FTN:
1654 return mono_delegate_to_ftnptr;
1655 case MONO_MARSHAL_CONV_FTN_DEL:
1656 *ind_store_type = CEE_STIND_REF;
1657 return mono_ftnptr_to_delegate;
1658 case MONO_MARSHAL_CONV_UTF8STR_SB:
1659 case MONO_MARSHAL_CONV_LPSTR_SB:
1660 *ind_store_type = CEE_STIND_REF;
1661 return mono_string_utf8_to_builder;
1662 case MONO_MARSHAL_CONV_LPTSTR_SB:
1663 *ind_store_type = CEE_STIND_REF;
1664 #ifdef TARGET_WIN32
1665 return mono_string_utf16_to_builder;
1666 #else
1667 return mono_string_utf8_to_builder;
1668 #endif
1669 case MONO_MARSHAL_CONV_LPWSTR_SB:
1670 *ind_store_type = CEE_STIND_REF;
1671 return mono_string_utf16_to_builder;
1672 case MONO_MARSHAL_FREE_ARRAY:
1673 return mono_marshal_free_array;
1674 case MONO_MARSHAL_CONV_STR_BYVALSTR:
1675 return mono_string_to_byvalstr;
1676 case MONO_MARSHAL_CONV_STR_BYVALWSTR:
1677 return mono_string_to_byvalwstr;
1678 default:
1679 g_assert_not_reached ();
1682 return NULL;
1685 static void
1686 emit_object_to_ptr_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv conv, MonoMarshalSpec *mspec)
1688 int pos;
1689 int stind_op;
1691 switch (conv) {
1692 case MONO_MARSHAL_CONV_BOOL_I4:
1693 mono_mb_emit_ldloc (mb, 1);
1694 mono_mb_emit_ldloc (mb, 0);
1695 mono_mb_emit_byte (mb, CEE_LDIND_U1);
1696 mono_mb_emit_byte (mb, CEE_STIND_I4);
1697 break;
1698 case MONO_MARSHAL_CONV_BOOL_VARIANTBOOL:
1699 mono_mb_emit_ldloc (mb, 1);
1700 mono_mb_emit_ldloc (mb, 0);
1701 mono_mb_emit_byte (mb, CEE_LDIND_U1);
1702 mono_mb_emit_byte (mb, CEE_NEG);
1703 mono_mb_emit_byte (mb, CEE_STIND_I2);
1704 break;
1705 // In Mono historically LPSTR was treated as a UTF8STR
1706 case MONO_MARSHAL_CONV_STR_UTF8STR:
1707 case MONO_MARSHAL_CONV_STR_LPWSTR:
1708 case MONO_MARSHAL_CONV_STR_LPSTR:
1709 case MONO_MARSHAL_CONV_STR_LPTSTR:
1710 case MONO_MARSHAL_CONV_STR_BSTR:
1711 case MONO_MARSHAL_CONV_STR_ANSIBSTR:
1712 case MONO_MARSHAL_CONV_STR_TBSTR: {
1713 int pos;
1715 /* free space if free == true */
1716 mono_mb_emit_ldloc (mb, 2);
1717 pos = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
1718 mono_mb_emit_ldloc (mb, 1);
1719 mono_mb_emit_byte (mb, CEE_LDIND_I);
1720 mono_mb_emit_icall (mb, g_free);
1721 mono_mb_patch_short_branch (mb, pos);
1723 mono_mb_emit_ldloc (mb, 1);
1724 mono_mb_emit_ldloc (mb, 0);
1725 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1726 mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
1727 mono_mb_emit_byte (mb, stind_op);
1728 break;
1730 case MONO_MARSHAL_CONV_ARRAY_SAVEARRAY:
1731 case MONO_MARSHAL_CONV_ARRAY_LPARRAY:
1732 case MONO_MARSHAL_CONV_DEL_FTN:
1733 mono_mb_emit_ldloc (mb, 1);
1734 mono_mb_emit_ldloc (mb, 0);
1735 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1736 mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
1737 mono_mb_emit_byte (mb, stind_op);
1738 break;
1739 case MONO_MARSHAL_CONV_STR_BYVALSTR:
1740 case MONO_MARSHAL_CONV_STR_BYVALWSTR: {
1741 g_assert (mspec);
1743 mono_mb_emit_ldloc (mb, 1); /* dst */
1744 mono_mb_emit_ldloc (mb, 0);
1745 mono_mb_emit_byte (mb, CEE_LDIND_REF); /* src String */
1746 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1747 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
1748 break;
1750 case MONO_MARSHAL_CONV_ARRAY_BYVALARRAY: {
1751 MonoClass *eklass = NULL;
1752 int esize;
1754 if (type->type == MONO_TYPE_SZARRAY) {
1755 eklass = type->data.klass;
1756 } else {
1757 g_assert_not_reached ();
1760 if (eklass->valuetype)
1761 esize = mono_class_native_size (eklass, NULL);
1762 else
1763 esize = sizeof (gpointer);
1765 mono_mb_emit_ldloc (mb, 0);
1766 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1767 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
1769 if (eklass->blittable) {
1770 mono_mb_emit_ldloc (mb, 1);
1771 mono_mb_emit_ldloc (mb, 0);
1772 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1773 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
1774 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem * esize);
1775 mono_mb_emit_byte (mb, CEE_PREFIX1);
1776 mono_mb_emit_byte (mb, CEE_CPBLK);
1777 } else {
1778 int array_var, src_var, dst_var, index_var;
1779 guint32 label2, label3;
1781 array_var = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
1782 src_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1783 dst_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1785 /* set array_var */
1786 mono_mb_emit_ldloc (mb, 0);
1787 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1788 mono_mb_emit_stloc (mb, array_var);
1790 /* save the old src pointer */
1791 mono_mb_emit_ldloc (mb, 0);
1792 mono_mb_emit_stloc (mb, src_var);
1793 /* save the old dst pointer */
1794 mono_mb_emit_ldloc (mb, 1);
1795 mono_mb_emit_stloc (mb, dst_var);
1797 /* Emit marshalling loop */
1798 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1799 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
1800 mono_mb_emit_stloc (mb, index_var);
1802 /* Loop header */
1803 label2 = mono_mb_get_label (mb);
1804 mono_mb_emit_ldloc (mb, index_var);
1805 mono_mb_emit_ldloc (mb, array_var);
1806 mono_mb_emit_byte (mb, CEE_LDLEN);
1807 label3 = mono_mb_emit_branch (mb, CEE_BGE);
1809 /* Set src */
1810 mono_mb_emit_ldloc (mb, array_var);
1811 mono_mb_emit_ldloc (mb, index_var);
1812 mono_mb_emit_op (mb, CEE_LDELEMA, eklass);
1813 mono_mb_emit_stloc (mb, 0);
1815 /* dst is already set */
1817 /* Do the conversion */
1818 emit_struct_conv (mb, eklass, FALSE);
1820 /* Loop footer */
1821 mono_mb_emit_add_to_local (mb, index_var, 1);
1823 mono_mb_emit_branch_label (mb, CEE_BR, label2);
1825 mono_mb_patch_branch (mb, label3);
1827 /* restore the old src pointer */
1828 mono_mb_emit_ldloc (mb, src_var);
1829 mono_mb_emit_stloc (mb, 0);
1830 /* restore the old dst pointer */
1831 mono_mb_emit_ldloc (mb, dst_var);
1832 mono_mb_emit_stloc (mb, 1);
1835 mono_mb_patch_branch (mb, pos);
1836 break;
1838 case MONO_MARSHAL_CONV_ARRAY_BYVALCHARARRAY: {
1839 mono_mb_emit_ldloc (mb, 0);
1840 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1841 pos = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
1843 mono_mb_emit_ldloc (mb, 1);
1844 mono_mb_emit_ldloc (mb, 0);
1845 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1846 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1847 mono_mb_emit_icall (mb, mono_array_to_byte_byvalarray);
1848 mono_mb_patch_short_branch (mb, pos);
1849 break;
1851 case MONO_MARSHAL_CONV_OBJECT_STRUCT: {
1852 int src_var, dst_var;
1854 src_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1855 dst_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1857 mono_mb_emit_ldloc (mb, 0);
1858 mono_mb_emit_byte (mb, CEE_LDIND_I);
1859 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
1861 /* save the old src pointer */
1862 mono_mb_emit_ldloc (mb, 0);
1863 mono_mb_emit_stloc (mb, src_var);
1864 /* save the old dst pointer */
1865 mono_mb_emit_ldloc (mb, 1);
1866 mono_mb_emit_stloc (mb, dst_var);
1868 /* src = pointer to object data */
1869 mono_mb_emit_ldloc (mb, 0);
1870 mono_mb_emit_byte (mb, CEE_LDIND_I);
1871 mono_mb_emit_icon (mb, sizeof (MonoObject));
1872 mono_mb_emit_byte (mb, CEE_ADD);
1873 mono_mb_emit_stloc (mb, 0);
1875 emit_struct_conv (mb, mono_class_from_mono_type (type), FALSE);
1877 /* restore the old src pointer */
1878 mono_mb_emit_ldloc (mb, src_var);
1879 mono_mb_emit_stloc (mb, 0);
1880 /* restore the old dst pointer */
1881 mono_mb_emit_ldloc (mb, dst_var);
1882 mono_mb_emit_stloc (mb, 1);
1884 mono_mb_patch_branch (mb, pos);
1885 break;
1888 #ifndef DISABLE_COM
1889 case MONO_MARSHAL_CONV_OBJECT_INTERFACE:
1890 case MONO_MARSHAL_CONV_OBJECT_IDISPATCH:
1891 case MONO_MARSHAL_CONV_OBJECT_IUNKNOWN:
1892 mono_cominterop_emit_object_to_ptr_conv (mb, type, conv, mspec);
1893 break;
1894 #endif /* DISABLE_COM */
1896 case MONO_MARSHAL_CONV_SAFEHANDLE: {
1897 int pos;
1899 mono_mb_emit_ldloc (mb, 0);
1900 mono_mb_emit_byte (mb, CEE_LDIND_I);
1901 pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
1902 mono_mb_emit_exception (mb, "ArgumentNullException", NULL);
1903 mono_mb_patch_branch (mb, pos);
1905 /* Pull the handle field from SafeHandle */
1906 mono_mb_emit_ldloc (mb, 1);
1907 mono_mb_emit_ldloc (mb, 0);
1908 mono_mb_emit_byte (mb, CEE_LDIND_I);
1909 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoSafeHandle, handle));
1910 mono_mb_emit_byte (mb, CEE_LDIND_I);
1911 mono_mb_emit_byte (mb, CEE_STIND_I);
1912 break;
1915 case MONO_MARSHAL_CONV_HANDLEREF: {
1916 mono_mb_emit_ldloc (mb, 1);
1917 mono_mb_emit_ldloc (mb, 0);
1918 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoHandleRef, handle));
1919 mono_mb_emit_byte (mb, CEE_ADD);
1920 mono_mb_emit_byte (mb, CEE_LDIND_I);
1921 mono_mb_emit_byte (mb, CEE_STIND_I);
1922 break;
1925 default: {
1926 g_error ("marshalling conversion %d not implemented", conv);
1931 static int
1932 offset_of_first_nonstatic_field (MonoClass *klass)
1934 int i;
1935 int fcount = mono_class_get_field_count (klass);
1936 for (i = 0; i < fcount; i++) {
1937 if (!(klass->fields[i].type->attrs & FIELD_ATTRIBUTE_STATIC) && !mono_field_is_deleted (&klass->fields[i]))
1938 return klass->fields[i].offset - sizeof (MonoObject);
1941 return 0;
1944 static void
1945 emit_struct_conv_full (MonoMethodBuilder *mb, MonoClass *klass, gboolean to_object,
1946 int offset_of_first_child_field, MonoMarshalNative string_encoding)
1948 MonoMarshalType *info;
1949 int i;
1951 if (klass->parent)
1952 emit_struct_conv_full (mb, klass->parent, to_object, offset_of_first_nonstatic_field (klass), string_encoding);
1954 info = mono_marshal_load_type_info (klass);
1956 if (info->native_size == 0)
1957 return;
1959 if (klass->blittable) {
1960 int usize = mono_class_value_size (klass, NULL);
1961 g_assert (usize == info->native_size);
1962 mono_mb_emit_ldloc (mb, 1);
1963 mono_mb_emit_ldloc (mb, 0);
1964 mono_mb_emit_icon (mb, usize);
1965 mono_mb_emit_byte (mb, CEE_PREFIX1);
1966 mono_mb_emit_byte (mb, CEE_CPBLK);
1968 if (to_object) {
1969 mono_mb_emit_add_to_local (mb, 0, usize);
1970 mono_mb_emit_add_to_local (mb, 1, offset_of_first_child_field);
1971 } else {
1972 mono_mb_emit_add_to_local (mb, 0, offset_of_first_child_field);
1973 mono_mb_emit_add_to_local (mb, 1, usize);
1975 return;
1978 if (klass != mono_class_try_get_safehandle_class ()) {
1979 if (mono_class_is_auto_layout (klass)) {
1980 char *msg = g_strdup_printf ("Type %s which is passed to unmanaged code must have a StructLayout attribute.",
1981 mono_type_full_name (&klass->byval_arg));
1982 mono_mb_emit_exception_marshal_directive (mb, msg);
1983 return;
1987 for (i = 0; i < info->num_fields; i++) {
1988 MonoMarshalNative ntype;
1989 MonoMarshalConv conv;
1990 MonoType *ftype = info->fields [i].field->type;
1991 int msize = 0;
1992 int usize = 0;
1993 gboolean last_field = i < (info->num_fields -1) ? 0 : 1;
1995 if (ftype->attrs & FIELD_ATTRIBUTE_STATIC)
1996 continue;
1998 ntype = (MonoMarshalNative)mono_type_to_unmanaged (ftype, info->fields [i].mspec, TRUE, klass->unicode, &conv);
2000 if (last_field) {
2001 msize = klass->instance_size - info->fields [i].field->offset;
2002 usize = info->native_size - info->fields [i].offset;
2003 } else {
2004 msize = info->fields [i + 1].field->offset - info->fields [i].field->offset;
2005 usize = info->fields [i + 1].offset - info->fields [i].offset;
2008 if (klass != mono_class_try_get_safehandle_class ()){
2010 * FIXME: Should really check for usize==0 and msize>0, but we apply
2011 * the layout to the managed structure as well.
2014 if (mono_class_is_explicit_layout (klass) && (usize == 0)) {
2015 if (MONO_TYPE_IS_REFERENCE (info->fields [i].field->type) ||
2016 ((!last_field && MONO_TYPE_IS_REFERENCE (info->fields [i + 1].field->type))))
2017 g_error ("Type %s which has an [ExplicitLayout] attribute cannot have a "
2018 "reference field at the same offset as another field.",
2019 mono_type_full_name (&klass->byval_arg));
2023 switch (conv) {
2024 case MONO_MARSHAL_CONV_NONE: {
2025 int t;
2027 //XXX a byref field!?!? that's not allowed! and worse, it might miss a WB
2028 g_assert (!ftype->byref);
2029 if (ftype->type == MONO_TYPE_I || ftype->type == MONO_TYPE_U) {
2030 mono_mb_emit_ldloc (mb, 1);
2031 mono_mb_emit_ldloc (mb, 0);
2032 mono_mb_emit_byte (mb, CEE_LDIND_I);
2033 mono_mb_emit_byte (mb, CEE_STIND_I);
2034 break;
2037 handle_enum:
2038 t = ftype->type;
2039 switch (t) {
2040 case MONO_TYPE_I4:
2041 case MONO_TYPE_U4:
2042 case MONO_TYPE_I1:
2043 case MONO_TYPE_U1:
2044 case MONO_TYPE_BOOLEAN:
2045 case MONO_TYPE_I2:
2046 case MONO_TYPE_U2:
2047 case MONO_TYPE_CHAR:
2048 case MONO_TYPE_I8:
2049 case MONO_TYPE_U8:
2050 case MONO_TYPE_PTR:
2051 case MONO_TYPE_R4:
2052 case MONO_TYPE_R8:
2053 mono_mb_emit_ldloc (mb, 1);
2054 mono_mb_emit_ldloc (mb, 0);
2055 if (t == MONO_TYPE_CHAR && ntype == MONO_NATIVE_U1 && string_encoding != MONO_NATIVE_LPWSTR) {
2056 if (to_object) {
2057 mono_mb_emit_byte (mb, CEE_LDIND_U1);
2058 mono_mb_emit_byte (mb, CEE_STIND_I2);
2059 } else {
2060 mono_mb_emit_byte (mb, CEE_LDIND_U2);
2061 mono_mb_emit_byte (mb, CEE_STIND_I1);
2063 } else {
2064 mono_mb_emit_byte (mb, mono_type_to_ldind (ftype));
2065 mono_mb_emit_byte (mb, mono_type_to_stind (ftype));
2067 break;
2068 case MONO_TYPE_VALUETYPE: {
2069 int src_var, dst_var;
2071 if (ftype->data.klass->enumtype) {
2072 ftype = mono_class_enum_basetype (ftype->data.klass);
2073 goto handle_enum;
2076 src_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
2077 dst_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
2079 /* save the old src pointer */
2080 mono_mb_emit_ldloc (mb, 0);
2081 mono_mb_emit_stloc (mb, src_var);
2082 /* save the old dst pointer */
2083 mono_mb_emit_ldloc (mb, 1);
2084 mono_mb_emit_stloc (mb, dst_var);
2086 emit_struct_conv (mb, ftype->data.klass, to_object);
2088 /* restore the old src pointer */
2089 mono_mb_emit_ldloc (mb, src_var);
2090 mono_mb_emit_stloc (mb, 0);
2091 /* restore the old dst pointer */
2092 mono_mb_emit_ldloc (mb, dst_var);
2093 mono_mb_emit_stloc (mb, 1);
2094 break;
2096 case MONO_TYPE_OBJECT: {
2097 #ifndef DISABLE_COM
2098 if (to_object) {
2099 static MonoMethod *variant_clear = NULL;
2100 static MonoMethod *get_object_for_native_variant = NULL;
2102 if (!variant_clear)
2103 variant_clear = mono_class_get_method_from_name (mono_class_get_variant_class (), "Clear", 0);
2104 if (!get_object_for_native_variant)
2105 get_object_for_native_variant = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetObjectForNativeVariant", 1);
2106 mono_mb_emit_ldloc (mb, 1);
2107 mono_mb_emit_ldloc (mb, 0);
2108 mono_mb_emit_managed_call (mb, get_object_for_native_variant, NULL);
2109 mono_mb_emit_byte (mb, CEE_STIND_REF);
2111 mono_mb_emit_ldloc (mb, 0);
2112 mono_mb_emit_managed_call (mb, variant_clear, NULL);
2114 else {
2115 static MonoMethod *get_native_variant_for_object = NULL;
2117 if (!get_native_variant_for_object)
2118 get_native_variant_for_object = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetNativeVariantForObject", 2);
2120 mono_mb_emit_ldloc (mb, 0);
2121 mono_mb_emit_byte(mb, CEE_LDIND_REF);
2122 mono_mb_emit_ldloc (mb, 1);
2123 mono_mb_emit_managed_call (mb, get_native_variant_for_object, NULL);
2125 #else
2126 char *msg = g_strdup_printf ("COM support was disabled at compilation time.");
2127 mono_mb_emit_exception_marshal_directive (mb, msg);
2128 #endif
2129 break;
2132 default:
2133 g_warning ("marshaling type %02x not implemented", ftype->type);
2134 g_assert_not_reached ();
2136 break;
2138 default: {
2139 int src_var, dst_var;
2141 src_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
2142 dst_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
2144 /* save the old src pointer */
2145 mono_mb_emit_ldloc (mb, 0);
2146 mono_mb_emit_stloc (mb, src_var);
2147 /* save the old dst pointer */
2148 mono_mb_emit_ldloc (mb, 1);
2149 mono_mb_emit_stloc (mb, dst_var);
2151 if (to_object)
2152 emit_ptr_to_object_conv (mb, ftype, conv, info->fields [i].mspec);
2153 else
2154 emit_object_to_ptr_conv (mb, ftype, conv, info->fields [i].mspec);
2156 /* restore the old src pointer */
2157 mono_mb_emit_ldloc (mb, src_var);
2158 mono_mb_emit_stloc (mb, 0);
2159 /* restore the old dst pointer */
2160 mono_mb_emit_ldloc (mb, dst_var);
2161 mono_mb_emit_stloc (mb, 1);
2165 if (to_object) {
2166 mono_mb_emit_add_to_local (mb, 0, usize);
2167 mono_mb_emit_add_to_local (mb, 1, msize);
2168 } else {
2169 mono_mb_emit_add_to_local (mb, 0, msize);
2170 mono_mb_emit_add_to_local (mb, 1, usize);
2175 static void
2176 emit_struct_conv (MonoMethodBuilder *mb, MonoClass *klass, gboolean to_object)
2178 emit_struct_conv_full (mb, klass, to_object, 0, (MonoMarshalNative)-1);
2181 static void
2182 emit_struct_free (MonoMethodBuilder *mb, MonoClass *klass, int struct_var)
2184 /* Call DestroyStructure */
2185 /* FIXME: Only do this if needed */
2186 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
2187 mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
2188 mono_mb_emit_ldloc (mb, struct_var);
2189 mono_mb_emit_icall (mb, mono_struct_delete_old);
2192 static void
2193 emit_thread_interrupt_checkpoint_call (MonoMethodBuilder *mb, gpointer checkpoint_func)
2195 int pos_noabort, pos_noex;
2197 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
2198 mono_mb_emit_byte (mb, CEE_MONO_LDPTR_INT_REQ_FLAG);
2199 mono_mb_emit_byte (mb, CEE_LDIND_U4);
2200 pos_noabort = mono_mb_emit_branch (mb, CEE_BRFALSE);
2202 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
2203 mono_mb_emit_byte (mb, CEE_MONO_NOT_TAKEN);
2205 mono_mb_emit_icall (mb, checkpoint_func);
2206 /* Throw the exception returned by the checkpoint function, if any */
2207 mono_mb_emit_byte (mb, CEE_DUP);
2208 pos_noex = mono_mb_emit_branch (mb, CEE_BRFALSE);
2209 mono_mb_emit_byte (mb, CEE_THROW);
2210 mono_mb_patch_branch (mb, pos_noex);
2211 mono_mb_emit_byte (mb, CEE_POP);
2213 mono_mb_patch_branch (mb, pos_noabort);
2216 static void
2217 emit_thread_interrupt_checkpoint (MonoMethodBuilder *mb)
2219 if (strstr (mb->name, "mono_thread_interruption_checkpoint"))
2220 return;
2222 emit_thread_interrupt_checkpoint_call (mb, mono_thread_interruption_checkpoint);
2225 static void
2226 emit_thread_force_interrupt_checkpoint (MonoMethodBuilder *mb)
2228 emit_thread_interrupt_checkpoint_call (mb, mono_thread_force_interruption_checkpoint_noraise);
2231 void
2232 mono_marshal_emit_thread_interrupt_checkpoint (MonoMethodBuilder *mb)
2234 emit_thread_interrupt_checkpoint (mb);
2237 void
2238 mono_marshal_emit_thread_force_interrupt_checkpoint (MonoMethodBuilder *mb)
2240 emit_thread_force_interrupt_checkpoint (mb);
2243 #endif /* DISABLE_JIT */
2245 /* This is a JIT icall, it sets the pending exception and returns NULL on error. */
2246 static MonoAsyncResult *
2247 mono_delegate_begin_invoke (MonoDelegate *delegate, gpointer *params)
2249 MonoError error;
2250 MonoMulticastDelegate *mcast_delegate;
2251 MonoClass *klass;
2252 MonoMethod *method;
2254 g_assert (delegate);
2255 mcast_delegate = (MonoMulticastDelegate *) delegate;
2256 if (mcast_delegate->delegates != NULL) {
2257 mono_set_pending_exception (mono_get_exception_argument (NULL, "The delegate must have only one target"));
2258 return NULL;
2261 #ifndef DISABLE_REMOTING
2262 if (delegate->target && mono_object_class (delegate->target) == mono_defaults.transparent_proxy_class) {
2263 MonoTransparentProxy* tp = (MonoTransparentProxy *)delegate->target;
2264 if (!mono_class_is_contextbound (tp->remote_class->proxy_class) || tp->rp->context != (MonoObject *) mono_context_get ()) {
2265 /* If the target is a proxy, make a direct call. Is proxy's work
2266 // to make the call asynchronous.
2268 MonoMethodMessage *msg;
2269 MonoDelegate *async_callback;
2270 MonoObject *state;
2271 MonoAsyncResult *ares;
2272 MonoObject *exc;
2273 MonoArray *out_args;
2274 method = delegate->method;
2276 msg = mono_method_call_message_new (mono_marshal_method_from_wrapper (method), params, NULL, &async_callback, &state, &error);
2277 if (mono_error_set_pending_exception (&error))
2278 return NULL;
2279 ares = mono_async_result_new (mono_domain_get (), NULL, state, NULL, NULL, &error);
2280 if (mono_error_set_pending_exception (&error))
2281 return NULL;
2282 MONO_OBJECT_SETREF (ares, async_delegate, (MonoObject *)delegate);
2283 MONO_OBJECT_SETREF (ares, async_callback, (MonoObject *)async_callback);
2284 MONO_OBJECT_SETREF (msg, async_result, ares);
2285 msg->call_type = CallType_BeginInvoke;
2287 exc = NULL;
2288 mono_remoting_invoke ((MonoObject *)tp->rp, msg, &exc, &out_args, &error);
2289 if (!mono_error_ok (&error)) {
2290 mono_error_set_pending_exception (&error);
2291 return NULL;
2293 if (exc)
2294 mono_set_pending_exception ((MonoException *) exc);
2295 return ares;
2298 #endif
2300 klass = delegate->object.vtable->klass;
2302 method = mono_class_get_method_from_name (klass, "BeginInvoke", -1);
2303 if (!method)
2304 method = mono_get_delegate_invoke (klass);
2305 g_assert (method);
2307 MonoAsyncResult *result = mono_threadpool_ms_begin_invoke (mono_domain_get (), (MonoObject*) delegate, method, params, &error);
2308 mono_error_set_pending_exception (&error);
2309 return result;
2312 #ifndef DISABLE_JIT
2315 mono_mb_emit_save_args (MonoMethodBuilder *mb, MonoMethodSignature *sig, gboolean save_this)
2317 int i, params_var, tmp_var;
2319 /* allocate local (pointer) *params[] */
2320 params_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
2321 /* allocate local (pointer) tmp */
2322 tmp_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
2324 /* alloate space on stack to store an array of pointers to the arguments */
2325 mono_mb_emit_icon (mb, sizeof (gpointer) * (sig->param_count + 1));
2326 mono_mb_emit_byte (mb, CEE_PREFIX1);
2327 mono_mb_emit_byte (mb, CEE_LOCALLOC);
2328 mono_mb_emit_stloc (mb, params_var);
2330 /* tmp = params */
2331 mono_mb_emit_ldloc (mb, params_var);
2332 mono_mb_emit_stloc (mb, tmp_var);
2334 if (save_this && sig->hasthis) {
2335 mono_mb_emit_ldloc (mb, tmp_var);
2336 mono_mb_emit_ldarg_addr (mb, 0);
2337 mono_mb_emit_byte (mb, CEE_STIND_I);
2338 /* tmp = tmp + sizeof (gpointer) */
2339 if (sig->param_count)
2340 mono_mb_emit_add_to_local (mb, tmp_var, sizeof (gpointer));
2344 for (i = 0; i < sig->param_count; i++) {
2345 mono_mb_emit_ldloc (mb, tmp_var);
2346 mono_mb_emit_ldarg_addr (mb, i + sig->hasthis);
2347 mono_mb_emit_byte (mb, CEE_STIND_I);
2348 /* tmp = tmp + sizeof (gpointer) */
2349 if (i < (sig->param_count - 1))
2350 mono_mb_emit_add_to_local (mb, tmp_var, sizeof (gpointer));
2353 return params_var;
2356 #endif /* DISABLE_JIT */
2358 static char*
2359 mono_signature_to_name (MonoMethodSignature *sig, const char *prefix)
2361 int i;
2362 char *result;
2363 GString *res = g_string_new ("");
2365 if (prefix) {
2366 g_string_append (res, prefix);
2367 g_string_append_c (res, '_');
2370 mono_type_get_desc (res, sig->ret, FALSE);
2372 if (sig->hasthis)
2373 g_string_append (res, "__this__");
2375 for (i = 0; i < sig->param_count; ++i) {
2376 g_string_append_c (res, '_');
2377 mono_type_get_desc (res, sig->params [i], FALSE);
2379 result = res->str;
2380 g_string_free (res, FALSE);
2381 return result;
2385 * mono_marshal_get_string_encoding:
2387 * Return the string encoding which should be used for a given parameter.
2389 static MonoMarshalNative
2390 mono_marshal_get_string_encoding (MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec)
2392 /* First try the parameter marshal info */
2393 if (spec) {
2394 if (spec->native == MONO_NATIVE_LPARRAY) {
2395 if ((spec->data.array_data.elem_type != 0) && (spec->data.array_data.elem_type != MONO_NATIVE_MAX))
2396 return spec->data.array_data.elem_type;
2398 else
2399 return spec->native;
2402 if (!piinfo)
2403 return MONO_NATIVE_LPSTR;
2405 /* Then try the method level marshal info */
2406 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
2407 case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
2408 return MONO_NATIVE_LPSTR;
2409 case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
2410 return MONO_NATIVE_LPWSTR;
2411 case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
2412 #ifdef TARGET_WIN32
2413 return MONO_NATIVE_LPWSTR;
2414 #else
2415 return MONO_NATIVE_LPSTR;
2416 #endif
2417 default:
2418 return MONO_NATIVE_LPSTR;
2422 static MonoMarshalConv
2423 mono_marshal_get_string_to_ptr_conv (MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec)
2425 MonoMarshalNative encoding = mono_marshal_get_string_encoding (piinfo, spec);
2427 switch (encoding) {
2428 case MONO_NATIVE_LPWSTR:
2429 return MONO_MARSHAL_CONV_STR_LPWSTR;
2430 case MONO_NATIVE_LPSTR:
2431 case MONO_NATIVE_VBBYREFSTR:
2432 return MONO_MARSHAL_CONV_STR_LPSTR;
2433 case MONO_NATIVE_LPTSTR:
2434 return MONO_MARSHAL_CONV_STR_LPTSTR;
2435 case MONO_NATIVE_BSTR:
2436 return MONO_MARSHAL_CONV_STR_BSTR;
2437 case MONO_NATIVE_UTF8STR:
2438 return MONO_MARSHAL_CONV_STR_UTF8STR;
2439 default:
2440 return MONO_MARSHAL_CONV_INVALID;
2444 static MonoMarshalConv
2445 mono_marshal_get_stringbuilder_to_ptr_conv (MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec)
2447 MonoMarshalNative encoding = mono_marshal_get_string_encoding (piinfo, spec);
2449 switch (encoding) {
2450 case MONO_NATIVE_LPWSTR:
2451 return MONO_MARSHAL_CONV_SB_LPWSTR;
2452 case MONO_NATIVE_LPSTR:
2453 return MONO_MARSHAL_CONV_SB_LPSTR;
2454 case MONO_NATIVE_UTF8STR:
2455 return MONO_MARSHAL_CONV_SB_UTF8STR;
2456 case MONO_NATIVE_LPTSTR:
2457 return MONO_MARSHAL_CONV_SB_LPTSTR;
2458 default:
2459 return MONO_MARSHAL_CONV_INVALID;
2463 static MonoMarshalConv
2464 mono_marshal_get_ptr_to_string_conv (MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec, gboolean *need_free)
2466 MonoMarshalNative encoding = mono_marshal_get_string_encoding (piinfo, spec);
2468 *need_free = TRUE;
2470 switch (encoding) {
2471 case MONO_NATIVE_LPWSTR:
2472 *need_free = FALSE;
2473 return MONO_MARSHAL_CONV_LPWSTR_STR;
2474 case MONO_NATIVE_UTF8STR:
2475 return MONO_MARSHAL_CONV_UTF8STR_STR;
2476 case MONO_NATIVE_LPSTR:
2477 case MONO_NATIVE_VBBYREFSTR:
2478 return MONO_MARSHAL_CONV_LPSTR_STR;
2479 case MONO_NATIVE_LPTSTR:
2480 return MONO_MARSHAL_CONV_LPTSTR_STR;
2481 case MONO_NATIVE_BSTR:
2482 return MONO_MARSHAL_CONV_BSTR_STR;
2483 default:
2484 return MONO_MARSHAL_CONV_INVALID;
2488 static MonoMarshalConv
2489 mono_marshal_get_ptr_to_stringbuilder_conv (MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec, gboolean *need_free)
2491 MonoMarshalNative encoding = mono_marshal_get_string_encoding (piinfo, spec);
2493 *need_free = TRUE;
2495 switch (encoding) {
2496 case MONO_NATIVE_LPWSTR:
2498 * mono_string_builder_to_utf16 does not allocate a
2499 * new buffer, so no need to free it.
2501 *need_free = FALSE;
2502 return MONO_MARSHAL_CONV_LPWSTR_SB;
2503 case MONO_NATIVE_UTF8STR:
2504 return MONO_MARSHAL_CONV_UTF8STR_SB;
2505 case MONO_NATIVE_LPSTR:
2506 return MONO_MARSHAL_CONV_LPSTR_SB;
2507 break;
2508 case MONO_NATIVE_LPTSTR:
2509 return MONO_MARSHAL_CONV_LPTSTR_SB;
2510 break;
2511 default:
2512 return MONO_MARSHAL_CONV_INVALID;
2517 * Return whenever a field of a native structure or an array member needs to
2518 * be freed.
2520 static gboolean
2521 mono_marshal_need_free (MonoType *t, MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec)
2523 MonoMarshalNative encoding;
2525 switch (t->type) {
2526 case MONO_TYPE_VALUETYPE:
2527 /* FIXME: Optimize this */
2528 return TRUE;
2529 case MONO_TYPE_OBJECT:
2530 case MONO_TYPE_CLASS:
2531 if (t->data.klass == mono_defaults.stringbuilder_class) {
2532 gboolean need_free;
2533 mono_marshal_get_ptr_to_stringbuilder_conv (piinfo, spec, &need_free);
2534 return need_free;
2536 return FALSE;
2537 case MONO_TYPE_STRING:
2538 encoding = mono_marshal_get_string_encoding (piinfo, spec);
2539 return (encoding == MONO_NATIVE_LPWSTR) ? FALSE : TRUE;
2540 default:
2541 return FALSE;
2546 * Return the hash table pointed to by VAR, lazily creating it if neccesary.
2548 static GHashTable*
2549 get_cache (GHashTable **var, GHashFunc hash_func, GCompareFunc equal_func)
2551 if (!(*var)) {
2552 mono_marshal_lock ();
2553 if (!(*var)) {
2554 GHashTable *cache =
2555 g_hash_table_new (hash_func, equal_func);
2556 mono_memory_barrier ();
2557 *var = cache;
2559 mono_marshal_unlock ();
2561 return *var;
2564 GHashTable*
2565 mono_marshal_get_cache (GHashTable **var, GHashFunc hash_func, GCompareFunc equal_func)
2567 return get_cache (var, hash_func, equal_func);
2570 MonoMethod*
2571 mono_marshal_find_in_cache (GHashTable *cache, gpointer key)
2573 MonoMethod *res;
2575 mono_marshal_lock ();
2576 res = (MonoMethod *)g_hash_table_lookup (cache, key);
2577 mono_marshal_unlock ();
2578 return res;
2582 * mono_mb_create:
2584 * Create a MonoMethod from MB, set INFO as wrapper info.
2586 MonoMethod*
2587 mono_mb_create (MonoMethodBuilder *mb, MonoMethodSignature *sig,
2588 int max_stack, WrapperInfo *info)
2590 MonoMethod *res;
2592 res = mono_mb_create_method (mb, sig, max_stack);
2593 if (info)
2594 mono_marshal_set_wrapper_info (res, info);
2595 return res;
2598 /* Create the method from the builder and place it in the cache */
2599 MonoMethod*
2600 mono_mb_create_and_cache_full (GHashTable *cache, gpointer key,
2601 MonoMethodBuilder *mb, MonoMethodSignature *sig,
2602 int max_stack, WrapperInfo *info, gboolean *out_found)
2604 MonoMethod *res;
2606 if (out_found)
2607 *out_found = FALSE;
2609 mono_marshal_lock ();
2610 res = (MonoMethod *)g_hash_table_lookup (cache, key);
2611 mono_marshal_unlock ();
2612 if (!res) {
2613 MonoMethod *newm;
2614 newm = mono_mb_create_method (mb, sig, max_stack);
2615 mono_marshal_lock ();
2616 res = (MonoMethod *)g_hash_table_lookup (cache, key);
2617 if (!res) {
2618 res = newm;
2619 g_hash_table_insert (cache, key, res);
2620 mono_marshal_set_wrapper_info (res, info);
2621 mono_marshal_unlock ();
2622 } else {
2623 if (out_found)
2624 *out_found = TRUE;
2625 mono_marshal_unlock ();
2626 mono_free_method (newm);
2630 return res;
2633 MonoMethod*
2634 mono_mb_create_and_cache (GHashTable *cache, gpointer key,
2635 MonoMethodBuilder *mb, MonoMethodSignature *sig,
2636 int max_stack)
2638 return mono_mb_create_and_cache_full (cache, key, mb, sig, max_stack, NULL, NULL);
2641 MonoMethod *
2642 mono_marshal_method_from_wrapper (MonoMethod *wrapper)
2644 MonoMethod *m;
2645 int wrapper_type = wrapper->wrapper_type;
2646 WrapperInfo *info;
2648 if (wrapper_type == MONO_WRAPPER_NONE || wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
2649 return wrapper;
2651 info = mono_marshal_get_wrapper_info (wrapper);
2653 switch (wrapper_type) {
2654 case MONO_WRAPPER_REMOTING_INVOKE:
2655 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2656 case MONO_WRAPPER_XDOMAIN_INVOKE:
2657 m = info->d.remoting.method;
2658 if (wrapper->is_inflated) {
2659 MonoError error;
2660 MonoMethod *result;
2662 * A method cannot be inflated and a wrapper at the same time, so the wrapper info
2663 * contains an uninflated method.
2665 result = mono_class_inflate_generic_method_checked (m, mono_method_get_context (wrapper), &error);
2666 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
2667 return result;
2669 return m;
2670 case MONO_WRAPPER_SYNCHRONIZED:
2671 m = info->d.synchronized.method;
2672 if (wrapper->is_inflated) {
2673 MonoError error;
2674 MonoMethod *result;
2675 result = mono_class_inflate_generic_method_checked (m, mono_method_get_context (wrapper), &error);
2676 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
2677 return result;
2679 return m;
2680 case MONO_WRAPPER_UNBOX:
2681 return info->d.unbox.method;
2682 case MONO_WRAPPER_MANAGED_TO_NATIVE:
2683 if (info && (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT || info->subtype == WRAPPER_SUBTYPE_PINVOKE))
2684 return info->d.managed_to_native.method;
2685 else
2686 return NULL;
2687 case MONO_WRAPPER_RUNTIME_INVOKE:
2688 if (info && (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL))
2689 return info->d.runtime_invoke.method;
2690 else
2691 return NULL;
2692 case MONO_WRAPPER_DELEGATE_INVOKE:
2693 if (info)
2694 return info->d.delegate_invoke.method;
2695 else
2696 return NULL;
2697 default:
2698 return NULL;
2703 * mono_marshal_get_wrapper_info:
2705 * Retrieve the WrapperInfo structure associated with WRAPPER.
2707 WrapperInfo*
2708 mono_marshal_get_wrapper_info (MonoMethod *wrapper)
2710 g_assert (wrapper->wrapper_type);
2712 return (WrapperInfo *)mono_method_get_wrapper_data (wrapper, 1);
2716 * mono_marshal_set_wrapper_info:
2718 * Set the WrapperInfo structure associated with the wrapper
2719 * method METHOD to INFO.
2721 void
2722 mono_marshal_set_wrapper_info (MonoMethod *method, WrapperInfo *info)
2724 void **datav;
2725 /* assert */
2726 if (method->wrapper_type == MONO_WRAPPER_NONE || method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
2727 return;
2729 datav = (void **)((MonoMethodWrapper *)method)->method_data;
2730 datav [1] = info;
2733 WrapperInfo*
2734 mono_wrapper_info_create (MonoMethodBuilder *mb, WrapperSubtype subtype)
2736 WrapperInfo *info;
2738 info = (WrapperInfo *)mono_image_alloc0 (mb->method->klass->image, sizeof (WrapperInfo));
2739 info->subtype = subtype;
2740 return info;
2744 * get_wrapper_target_class:
2746 * Return the class where a wrapper method should be placed.
2748 static MonoClass*
2749 get_wrapper_target_class (MonoImage *image)
2751 MonoError error;
2752 MonoClass *klass;
2755 * Notes:
2756 * - can't put all wrappers into an mscorlib class, because they reference
2757 * metadata (signature) so they should be put into the same image as the
2758 * method they wrap, so they are unloaded together.
2759 * - putting them into a class with a type initalizer could cause the
2760 * initializer to be executed which can be a problem if the wrappers are
2761 * shared.
2762 * - putting them into an inflated class can cause problems if the the
2763 * class is deleted because it references an image which is unloaded.
2764 * To avoid these problems, we put the wrappers into the <Module> class of
2765 * the image.
2767 if (image_is_dynamic (image)) {
2768 klass = ((MonoDynamicImage*)image)->wrappers_type;
2769 } else {
2770 klass = mono_class_get_checked (image, mono_metadata_make_token (MONO_TABLE_TYPEDEF, 1), &error);
2771 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
2773 g_assert (klass);
2775 return klass;
2779 * Wrappers for generic methods should be instances of generic wrapper methods, i.e .the wrapper for Sort<int> should be
2780 * an instance of the wrapper for Sort<T>. This is required for full-aot to work.
2784 * check_generic_wrapper_cache:
2786 * Check CACHE for the wrapper of the generic instance ORIG_METHOD, and return it if it is found.
2787 * KEY should be the key for ORIG_METHOD in the cache, while DEF_KEY should be the key of its
2788 * generic method definition.
2790 static MonoMethod*
2791 check_generic_wrapper_cache (GHashTable *cache, MonoMethod *orig_method, gpointer key, gpointer def_key)
2793 MonoMethod *res;
2794 MonoMethod *inst, *def;
2795 MonoGenericContext *ctx;
2797 g_assert (orig_method->is_inflated);
2798 ctx = mono_method_get_context (orig_method);
2801 * Look for the instance
2803 res = mono_marshal_find_in_cache (cache, key);
2804 if (res)
2805 return res;
2808 * Look for the definition
2810 def = mono_marshal_find_in_cache (cache, def_key);
2811 if (def) {
2812 MonoError error;
2813 inst = mono_class_inflate_generic_method_checked (def, ctx, &error);
2814 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
2815 /* Cache it */
2816 mono_memory_barrier ();
2817 mono_marshal_lock ();
2818 res = (MonoMethod *)g_hash_table_lookup (cache, key);
2819 if (!res) {
2820 g_hash_table_insert (cache, key, inst);
2821 res = inst;
2823 mono_marshal_unlock ();
2824 return res;
2826 return NULL;
2829 static MonoMethod*
2830 cache_generic_wrapper (GHashTable *cache, MonoMethod *orig_method, MonoMethod *def, MonoGenericContext *ctx, gpointer key)
2832 MonoError error;
2833 MonoMethod *inst, *res;
2836 * We use the same cache for the generic definition and the instances.
2838 inst = mono_class_inflate_generic_method_checked (def, ctx, &error);
2839 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
2840 mono_memory_barrier ();
2841 mono_marshal_lock ();
2842 res = (MonoMethod *)g_hash_table_lookup (cache, key);
2843 if (!res) {
2844 g_hash_table_insert (cache, key, inst);
2845 res = inst;
2847 mono_marshal_unlock ();
2848 return res;
2851 static MonoMethod*
2852 check_generic_delegate_wrapper_cache (GHashTable *cache, MonoMethod *orig_method, MonoMethod *def_method, MonoGenericContext *ctx)
2854 MonoError error;
2855 MonoMethod *res;
2856 MonoMethod *inst, *def;
2859 * Look for the instance
2861 res = mono_marshal_find_in_cache (cache, orig_method->klass);
2862 if (res)
2863 return res;
2866 * Look for the definition
2868 def = mono_marshal_find_in_cache (cache, def_method->klass);
2869 if (def) {
2870 inst = mono_class_inflate_generic_method_checked (def, ctx, &error);
2871 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
2873 /* Cache it */
2874 mono_memory_barrier ();
2875 mono_marshal_lock ();
2876 res = (MonoMethod *)g_hash_table_lookup (cache, orig_method->klass);
2877 if (!res) {
2878 g_hash_table_insert (cache, orig_method->klass, inst);
2879 res = inst;
2881 mono_marshal_unlock ();
2882 return res;
2884 return NULL;
2887 static MonoMethod*
2888 cache_generic_delegate_wrapper (GHashTable *cache, MonoMethod *orig_method, MonoMethod *def, MonoGenericContext *ctx)
2890 MonoError error;
2891 MonoMethod *inst, *res;
2892 WrapperInfo *ginfo, *info;
2895 * We use the same cache for the generic definition and the instances.
2897 inst = mono_class_inflate_generic_method_checked (def, ctx, &error);
2898 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
2900 ginfo = mono_marshal_get_wrapper_info (def);
2901 if (ginfo) {
2902 info = (WrapperInfo *)mono_image_alloc0 (def->klass->image, sizeof (WrapperInfo));
2903 info->subtype = ginfo->subtype;
2904 if (info->subtype == WRAPPER_SUBTYPE_NONE) {
2905 info->d.delegate_invoke.method = mono_class_inflate_generic_method_checked (ginfo->d.delegate_invoke.method, ctx, &error);
2906 mono_error_assert_ok (&error);
2910 mono_memory_barrier ();
2911 mono_marshal_lock ();
2912 res = (MonoMethod *)g_hash_table_lookup (cache, orig_method->klass);
2913 if (!res) {
2914 g_hash_table_insert (cache, orig_method->klass, inst);
2915 res = inst;
2917 mono_marshal_unlock ();
2918 return res;
2921 MonoMethod *
2922 mono_marshal_get_delegate_begin_invoke (MonoMethod *method)
2924 MonoMethodSignature *sig;
2925 MonoMethodBuilder *mb;
2926 MonoMethod *res;
2927 GHashTable *cache;
2928 int params_var;
2929 char *name;
2930 MonoGenericContext *ctx = NULL;
2931 MonoMethod *orig_method = NULL;
2933 g_assert (method && method->klass->parent == mono_defaults.multicastdelegate_class &&
2934 !strcmp (method->name, "BeginInvoke"));
2937 * For generic delegates, create a generic wrapper, and returns an instance to help AOT.
2939 if (method->is_inflated) {
2940 orig_method = method;
2941 ctx = &((MonoMethodInflated*)method)->context;
2942 method = ((MonoMethodInflated*)method)->declaring;
2945 sig = mono_signature_no_pinvoke (method);
2948 * Check cache
2950 if (ctx) {
2951 cache = get_cache (&((MonoMethodInflated*)orig_method)->owner->wrapper_caches.delegate_begin_invoke_cache, mono_aligned_addr_hash, NULL);
2952 res = check_generic_delegate_wrapper_cache (cache, orig_method, method, ctx);
2953 if (res)
2954 return res;
2955 } else {
2956 cache = get_cache (&method->klass->image->wrapper_caches.delegate_begin_invoke_cache,
2957 (GHashFunc)mono_signature_hash,
2958 (GCompareFunc)mono_metadata_signature_equal);
2959 if ((res = mono_marshal_find_in_cache (cache, sig)))
2960 return res;
2963 g_assert (sig->hasthis);
2965 name = mono_signature_to_name (sig, "begin_invoke");
2966 if (ctx)
2967 mb = mono_mb_new (method->klass, name, MONO_WRAPPER_DELEGATE_BEGIN_INVOKE);
2968 else
2969 mb = mono_mb_new (get_wrapper_target_class (method->klass->image), name, MONO_WRAPPER_DELEGATE_BEGIN_INVOKE);
2970 g_free (name);
2972 #ifndef DISABLE_JIT
2973 params_var = mono_mb_emit_save_args (mb, sig, FALSE);
2975 mono_mb_emit_ldarg (mb, 0);
2976 mono_mb_emit_ldloc (mb, params_var);
2977 mono_mb_emit_icall (mb, mono_delegate_begin_invoke);
2978 mono_mb_emit_byte (mb, CEE_RET);
2979 #endif
2981 if (ctx) {
2982 MonoMethod *def;
2983 def = mono_mb_create_and_cache (cache, method->klass, mb, sig, sig->param_count + 16);
2984 res = cache_generic_delegate_wrapper (cache, orig_method, def, ctx);
2985 } else {
2986 res = mono_mb_create_and_cache (cache, sig, mb, sig, sig->param_count + 16);
2989 mono_mb_free (mb);
2990 return res;
2993 /* This is a JIT icall, it sets the pending exception and returns NULL on error. */
2994 static MonoObject *
2995 mono_delegate_end_invoke (MonoDelegate *delegate, gpointer *params)
2997 MonoError error;
2998 MonoDomain *domain = mono_domain_get ();
2999 MonoAsyncResult *ares;
3000 MonoMethod *method = NULL;
3001 MonoMethodSignature *sig;
3002 MonoMethodMessage *msg;
3003 MonoObject *res, *exc;
3004 MonoArray *out_args;
3005 MonoClass *klass;
3007 g_assert (delegate);
3009 if (!delegate->method_info) {
3010 g_assert (delegate->method);
3011 MonoReflectionMethod *rm = mono_method_get_object_checked (domain, delegate->method, NULL, &error);
3012 if (!mono_error_ok (&error)) {
3013 mono_error_set_pending_exception (&error);
3014 return NULL;
3016 MONO_OBJECT_SETREF (delegate, method_info, rm);
3019 if (!delegate->method_info || !delegate->method_info->method)
3020 g_assert_not_reached ();
3022 klass = delegate->object.vtable->klass;
3024 method = mono_class_get_method_from_name (klass, "EndInvoke", -1);
3025 g_assert (method != NULL);
3027 sig = mono_signature_no_pinvoke (method);
3029 msg = mono_method_call_message_new (method, params, NULL, NULL, NULL, &error);
3030 if (mono_error_set_pending_exception (&error))
3031 return NULL;
3033 ares = (MonoAsyncResult *)mono_array_get (msg->args, gpointer, sig->param_count - 1);
3034 if (ares == NULL) {
3035 mono_set_pending_exception (mono_exception_from_name_msg (mono_defaults.corlib, "System.Runtime.Remoting", "RemotingException", "The async result object is null or of an unexpected type."));
3036 return NULL;
3039 if (ares->async_delegate != (MonoObject*)delegate) {
3040 mono_set_pending_exception (mono_get_exception_invalid_operation (
3041 "The IAsyncResult object provided does not match this delegate."));
3042 return NULL;
3045 #ifndef DISABLE_REMOTING
3046 if (delegate->target && mono_object_is_transparent_proxy (delegate->target)) {
3047 MonoTransparentProxy* tp = (MonoTransparentProxy *)delegate->target;
3048 msg = (MonoMethodMessage *)mono_object_new_checked (domain, mono_defaults.mono_method_message_class, &error);
3049 if (!mono_error_ok (&error)) {
3050 mono_error_set_pending_exception (&error);
3051 return NULL;
3053 mono_message_init (domain, msg, delegate->method_info, NULL, &error);
3054 if (mono_error_set_pending_exception (&error))
3055 return NULL;
3056 msg->call_type = CallType_EndInvoke;
3057 MONO_OBJECT_SETREF (msg, async_result, ares);
3058 res = mono_remoting_invoke ((MonoObject *)tp->rp, msg, &exc, &out_args, &error);
3059 if (!mono_error_ok (&error)) {
3060 mono_error_set_pending_exception (&error);
3061 return NULL;
3063 } else
3064 #endif
3066 res = mono_threadpool_ms_end_invoke (ares, &out_args, &exc, &error);
3067 if (mono_error_set_pending_exception (&error))
3068 return NULL;
3071 if (exc) {
3072 if (((MonoException*)exc)->stack_trace) {
3073 MonoError inner_error;
3074 char *strace = mono_string_to_utf8_checked (((MonoException*)exc)->stack_trace, &inner_error);
3075 if (is_ok (&inner_error)) {
3076 char *tmp;
3077 tmp = g_strdup_printf ("%s\nException Rethrown at:\n", strace);
3078 g_free (strace);
3079 MONO_OBJECT_SETREF (((MonoException*)exc), stack_trace, mono_string_new (domain, tmp));
3080 g_free (tmp);
3081 } else
3082 mono_error_cleanup (&inner_error); /* no stack trace, but at least throw the original exception */
3084 mono_set_pending_exception ((MonoException*)exc);
3087 mono_method_return_message_restore (method, params, out_args, &error);
3088 mono_error_set_pending_exception (&error);
3089 return res;
3092 #ifndef DISABLE_JIT
3094 void
3095 mono_mb_emit_restore_result (MonoMethodBuilder *mb, MonoType *return_type)
3097 MonoType *t = mono_type_get_underlying_type (return_type);
3099 if (return_type->byref)
3100 return_type = &mono_defaults.int_class->byval_arg;
3102 switch (t->type) {
3103 case MONO_TYPE_VOID:
3104 g_assert_not_reached ();
3105 break;
3106 case MONO_TYPE_PTR:
3107 case MONO_TYPE_STRING:
3108 case MONO_TYPE_CLASS:
3109 case MONO_TYPE_OBJECT:
3110 case MONO_TYPE_ARRAY:
3111 case MONO_TYPE_SZARRAY:
3112 /* nothing to do */
3113 break;
3114 case MONO_TYPE_U1:
3115 case MONO_TYPE_BOOLEAN:
3116 case MONO_TYPE_I1:
3117 case MONO_TYPE_U2:
3118 case MONO_TYPE_CHAR:
3119 case MONO_TYPE_I2:
3120 case MONO_TYPE_I:
3121 case MONO_TYPE_U:
3122 case MONO_TYPE_I4:
3123 case MONO_TYPE_U4:
3124 case MONO_TYPE_U8:
3125 case MONO_TYPE_I8:
3126 case MONO_TYPE_R4:
3127 case MONO_TYPE_R8:
3128 mono_mb_emit_op (mb, CEE_UNBOX, mono_class_from_mono_type (return_type));
3129 mono_mb_emit_byte (mb, mono_type_to_ldind (return_type));
3130 break;
3131 case MONO_TYPE_GENERICINST:
3132 if (!mono_type_generic_inst_is_valuetype (t))
3133 break;
3134 /* fall through */
3135 case MONO_TYPE_VALUETYPE: {
3136 MonoClass *klass = mono_class_from_mono_type (return_type);
3137 mono_mb_emit_op (mb, CEE_UNBOX, klass);
3138 mono_mb_emit_op (mb, CEE_LDOBJ, klass);
3139 break;
3141 case MONO_TYPE_VAR:
3142 case MONO_TYPE_MVAR: {
3143 MonoClass *klass = mono_class_from_mono_type (return_type);
3144 mono_mb_emit_op (mb, CEE_UNBOX_ANY, klass);
3145 break;
3147 default:
3148 g_warning ("type 0x%x not handled", return_type->type);
3149 g_assert_not_reached ();
3152 mono_mb_emit_byte (mb, CEE_RET);
3155 #endif /* DISABLE_JIT */
3157 MonoMethod *
3158 mono_marshal_get_delegate_end_invoke (MonoMethod *method)
3160 MonoMethodSignature *sig;
3161 MonoMethodBuilder *mb;
3162 MonoMethod *res;
3163 GHashTable *cache;
3164 int params_var;
3165 char *name;
3166 MonoGenericContext *ctx = NULL;
3167 MonoMethod *orig_method = NULL;
3169 g_assert (method && method->klass->parent == mono_defaults.multicastdelegate_class &&
3170 !strcmp (method->name, "EndInvoke"));
3173 * For generic delegates, create a generic wrapper, and returns an instance to help AOT.
3175 if (method->is_inflated) {
3176 orig_method = method;
3177 ctx = &((MonoMethodInflated*)method)->context;
3178 method = ((MonoMethodInflated*)method)->declaring;
3181 sig = mono_signature_no_pinvoke (method);
3184 * Check cache
3186 if (ctx) {
3187 cache = get_cache (&((MonoMethodInflated*)orig_method)->owner->wrapper_caches.delegate_end_invoke_cache, mono_aligned_addr_hash, NULL);
3188 res = check_generic_delegate_wrapper_cache (cache, orig_method, method, ctx);
3189 if (res)
3190 return res;
3191 } else {
3192 cache = get_cache (&method->klass->image->wrapper_caches.delegate_end_invoke_cache,
3193 (GHashFunc)mono_signature_hash,
3194 (GCompareFunc)mono_metadata_signature_equal);
3195 if ((res = mono_marshal_find_in_cache (cache, sig)))
3196 return res;
3199 g_assert (sig->hasthis);
3201 name = mono_signature_to_name (sig, "end_invoke");
3202 if (ctx)
3203 mb = mono_mb_new (method->klass, name, MONO_WRAPPER_DELEGATE_END_INVOKE);
3204 else
3205 mb = mono_mb_new (get_wrapper_target_class (method->klass->image), name, MONO_WRAPPER_DELEGATE_END_INVOKE);
3206 g_free (name);
3208 #ifndef DISABLE_JIT
3209 params_var = mono_mb_emit_save_args (mb, sig, FALSE);
3211 mono_mb_emit_ldarg (mb, 0);
3212 mono_mb_emit_ldloc (mb, params_var);
3213 mono_mb_emit_icall (mb, mono_delegate_end_invoke);
3215 if (sig->ret->type == MONO_TYPE_VOID) {
3216 mono_mb_emit_byte (mb, CEE_POP);
3217 mono_mb_emit_byte (mb, CEE_RET);
3218 } else
3219 mono_mb_emit_restore_result (mb, sig->ret);
3220 #endif
3222 if (ctx) {
3223 MonoMethod *def;
3224 def = mono_mb_create_and_cache (cache, method->klass, mb, sig, sig->param_count + 16);
3225 res = cache_generic_delegate_wrapper (cache, orig_method, def, ctx);
3226 } else {
3227 res = mono_mb_create_and_cache (cache, sig,
3228 mb, sig, sig->param_count + 16);
3230 mono_mb_free (mb);
3232 return res;
3235 typedef struct
3237 MonoMethodSignature *sig;
3238 gpointer pointer;
3239 } SignaturePointerPair;
3241 static guint
3242 signature_pointer_pair_hash (gconstpointer data)
3244 SignaturePointerPair *pair = (SignaturePointerPair*)data;
3246 return mono_signature_hash (pair->sig) ^ mono_aligned_addr_hash (pair->pointer);
3249 static gboolean
3250 signature_pointer_pair_equal (gconstpointer data1, gconstpointer data2)
3252 SignaturePointerPair *pair1 = (SignaturePointerPair*) data1, *pair2 = (SignaturePointerPair*) data2;
3253 return mono_metadata_signature_equal (pair1->sig, pair2->sig) && (pair1->pointer == pair2->pointer);
3256 static gboolean
3257 signature_pointer_pair_matches_pointer (gpointer key, gpointer value, gpointer user_data)
3259 SignaturePointerPair *pair = (SignaturePointerPair*)key;
3261 return pair->pointer == user_data;
3264 static void
3265 free_signature_pointer_pair (SignaturePointerPair *pair)
3267 g_free (pair);
3270 MonoMethod *
3271 mono_marshal_get_delegate_invoke_internal (MonoMethod *method, gboolean callvirt, gboolean static_method_with_first_arg_bound, MonoMethod *target_method)
3273 MonoMethodSignature *sig, *static_sig, *invoke_sig;
3274 int i;
3275 MonoMethodBuilder *mb;
3276 MonoMethod *res;
3277 GHashTable *cache;
3278 gpointer cache_key = NULL;
3279 SignaturePointerPair key = { NULL, NULL };
3280 SignaturePointerPair *new_key;
3281 int local_i, local_len, local_delegates, local_d, local_target, local_res;
3282 int pos0, pos1, pos2;
3283 char *name;
3284 MonoClass *target_class = NULL;
3285 gboolean closed_over_null = FALSE;
3286 MonoGenericContext *ctx = NULL;
3287 MonoGenericContainer *container = NULL;
3288 MonoMethod *orig_method = method;
3289 WrapperInfo *info;
3290 WrapperSubtype subtype = WRAPPER_SUBTYPE_NONE;
3291 gboolean found;
3292 gboolean void_ret;
3294 g_assert (method && method->klass->parent == mono_defaults.multicastdelegate_class &&
3295 !strcmp (method->name, "Invoke"));
3297 invoke_sig = sig = mono_signature_no_pinvoke (method);
3300 * If the delegate target is null, and the target method is not static, a virtual
3301 * call is made to that method with the first delegate argument as this. This is
3302 * a non-documented .NET feature.
3304 if (callvirt) {
3305 subtype = WRAPPER_SUBTYPE_DELEGATE_INVOKE_VIRTUAL;
3306 if (target_method->is_inflated) {
3307 MonoError error;
3308 MonoType *target_type;
3310 g_assert (method->signature->hasthis);
3311 target_type = mono_class_inflate_generic_type_checked (method->signature->params [0],
3312 mono_method_get_context (method), &error);
3313 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
3314 target_class = mono_class_from_mono_type (target_type);
3315 } else {
3316 target_class = target_method->klass;
3319 closed_over_null = sig->param_count == mono_method_signature (target_method)->param_count;
3322 if (static_method_with_first_arg_bound) {
3323 subtype = WRAPPER_SUBTYPE_DELEGATE_INVOKE_BOUND;
3324 g_assert (!callvirt);
3325 invoke_sig = mono_method_signature (target_method);
3329 * For generic delegates, create a generic wrapper, and return an instance to help AOT.
3331 if (method->is_inflated && subtype == WRAPPER_SUBTYPE_NONE) {
3332 ctx = &((MonoMethodInflated*)method)->context;
3333 method = ((MonoMethodInflated*)method)->declaring;
3335 container = mono_method_get_generic_container (method);
3336 if (!container)
3337 container = mono_class_try_get_generic_container (method->klass); //FIXME is this a case of a try?
3338 g_assert (container);
3340 invoke_sig = sig = mono_signature_no_pinvoke (method);
3344 * Check cache
3346 if (ctx) {
3347 cache = get_cache (&((MonoMethodInflated*)orig_method)->owner->wrapper_caches.delegate_invoke_cache, mono_aligned_addr_hash, NULL);
3348 res = check_generic_delegate_wrapper_cache (cache, orig_method, method, ctx);
3349 if (res)
3350 return res;
3351 cache_key = method->klass;
3352 } else if (static_method_with_first_arg_bound) {
3353 cache = get_cache (&method->klass->image->delegate_bound_static_invoke_cache,
3354 (GHashFunc)mono_signature_hash,
3355 (GCompareFunc)mono_metadata_signature_equal);
3357 * The wrapper is based on sig+invoke_sig, but sig can be derived from invoke_sig.
3359 res = mono_marshal_find_in_cache (cache, invoke_sig);
3360 if (res)
3361 return res;
3362 cache_key = invoke_sig;
3363 } else if (callvirt) {
3364 GHashTable **cache_ptr;
3366 cache_ptr = &mono_method_get_wrapper_cache (method)->delegate_abstract_invoke_cache;
3368 /* We need to cache the signature+method pair */
3369 mono_marshal_lock ();
3370 if (!*cache_ptr)
3371 *cache_ptr = g_hash_table_new_full (signature_pointer_pair_hash, (GEqualFunc)signature_pointer_pair_equal, (GDestroyNotify)free_signature_pointer_pair, NULL);
3372 cache = *cache_ptr;
3373 key.sig = invoke_sig;
3374 key.pointer = target_method;
3375 res = (MonoMethod *)g_hash_table_lookup (cache, &key);
3376 mono_marshal_unlock ();
3377 if (res)
3378 return res;
3379 } else {
3380 // Inflated methods should not be in this cache because it's not stored on the imageset.
3381 g_assert (!method->is_inflated);
3382 cache = get_cache (&method->klass->image->wrapper_caches.delegate_invoke_cache,
3383 (GHashFunc)mono_signature_hash,
3384 (GCompareFunc)mono_metadata_signature_equal);
3385 res = mono_marshal_find_in_cache (cache, sig);
3386 if (res)
3387 return res;
3388 cache_key = sig;
3391 static_sig = mono_metadata_signature_dup_full (method->klass->image, sig);
3392 static_sig->hasthis = 0;
3393 if (!static_method_with_first_arg_bound)
3394 invoke_sig = static_sig;
3396 if (static_method_with_first_arg_bound)
3397 name = mono_signature_to_name (invoke_sig, "invoke_bound");
3398 else if (closed_over_null)
3399 name = mono_signature_to_name (invoke_sig, "invoke_closed_over_null");
3400 else if (callvirt)
3401 name = mono_signature_to_name (invoke_sig, "invoke_callvirt");
3402 else
3403 name = mono_signature_to_name (invoke_sig, "invoke");
3404 if (ctx)
3405 mb = mono_mb_new (method->klass, name, MONO_WRAPPER_DELEGATE_INVOKE);
3406 else
3407 mb = mono_mb_new (get_wrapper_target_class (method->klass->image), name, MONO_WRAPPER_DELEGATE_INVOKE);
3408 g_free (name);
3410 #ifndef DISABLE_JIT
3411 void_ret = sig->ret->type == MONO_TYPE_VOID && !method->string_ctor;
3413 /* allocate local 0 (object) */
3414 local_i = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
3415 local_len = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
3416 local_delegates = mono_mb_add_local (mb, &mono_defaults.array_class->byval_arg);
3417 local_d = mono_mb_add_local (mb, &mono_defaults.multicastdelegate_class->byval_arg);
3418 local_target = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
3420 if (!void_ret)
3421 local_res = mono_mb_add_local (mb, &mono_class_from_mono_type (sig->ret)->byval_arg);
3423 g_assert (sig->hasthis);
3426 * {type: sig->ret} res;
3427 * if (delegates == null) {
3428 * return this.<target> ( args .. );
3429 * } else {
3430 * int i = 0, len = this.delegates.Length;
3431 * do {
3432 * res = this.delegates [i].Invoke ( args .. );
3433 * } while (++i < len);
3434 * return res;
3438 /* this wrapper can be used in unmanaged-managed transitions */
3439 emit_thread_interrupt_checkpoint (mb);
3441 /* delegates = this.delegates */
3442 mono_mb_emit_ldarg (mb, 0);
3443 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoMulticastDelegate, delegates));
3444 mono_mb_emit_byte (mb, CEE_LDIND_REF);
3445 mono_mb_emit_stloc (mb, local_delegates);
3447 /* if (delegates == null) */
3448 mono_mb_emit_ldloc (mb, local_delegates);
3449 pos2 = mono_mb_emit_branch (mb, CEE_BRTRUE);
3451 /* return target.<target_method|method_ptr> ( args .. ); */
3453 /* target = d.target; */
3454 mono_mb_emit_ldarg (mb, 0);
3455 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoDelegate, target));
3456 mono_mb_emit_byte (mb, CEE_LDIND_REF);
3457 mono_mb_emit_stloc (mb, local_target);
3459 /*static methods with bound first arg can have null target and still be bound*/
3460 if (!static_method_with_first_arg_bound) {
3461 /* if target != null */
3462 mono_mb_emit_ldloc (mb, local_target);
3463 pos0 = mono_mb_emit_branch (mb, CEE_BRFALSE);
3465 /* then call this->method_ptr nonstatic */
3466 if (callvirt) {
3467 // FIXME:
3468 mono_mb_emit_exception_full (mb, "System", "NotImplementedException", "");
3469 } else {
3470 mono_mb_emit_ldloc (mb, local_target);
3471 for (i = 0; i < sig->param_count; ++i)
3472 mono_mb_emit_ldarg (mb, i + 1);
3473 mono_mb_emit_ldarg (mb, 0);
3474 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoDelegate, extra_arg));
3475 mono_mb_emit_byte (mb, CEE_LDIND_I);
3476 mono_mb_emit_ldarg (mb, 0);
3477 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoDelegate, method_ptr));
3478 mono_mb_emit_byte (mb, CEE_LDIND_I);
3479 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
3480 mono_mb_emit_op (mb, CEE_MONO_CALLI_EXTRA_ARG, sig);
3481 mono_mb_emit_byte (mb, CEE_RET);
3484 /* else [target == null] call this->method_ptr static */
3485 mono_mb_patch_branch (mb, pos0);
3488 if (callvirt) {
3489 if (!closed_over_null) {
3490 if (target_class->valuetype) {
3491 mono_mb_emit_ldarg (mb, 1);
3492 for (i = 1; i < sig->param_count; ++i)
3493 mono_mb_emit_ldarg (mb, i + 1);
3494 mono_mb_emit_op (mb, CEE_CALL, target_method);
3495 } else {
3496 mono_mb_emit_ldarg (mb, 1);
3497 mono_mb_emit_op (mb, CEE_CASTCLASS, target_class);
3498 for (i = 1; i < sig->param_count; ++i)
3499 mono_mb_emit_ldarg (mb, i + 1);
3500 mono_mb_emit_op (mb, CEE_CALLVIRT, target_method);
3502 } else {
3503 mono_mb_emit_byte (mb, CEE_LDNULL);
3504 for (i = 0; i < sig->param_count; ++i)
3505 mono_mb_emit_ldarg (mb, i + 1);
3506 mono_mb_emit_op (mb, CEE_CALL, target_method);
3508 } else {
3509 if (static_method_with_first_arg_bound) {
3510 mono_mb_emit_ldloc (mb, local_target);
3511 if (!MONO_TYPE_IS_REFERENCE (invoke_sig->params[0]))
3512 mono_mb_emit_op (mb, CEE_UNBOX_ANY, mono_class_from_mono_type (invoke_sig->params[0]));
3514 for (i = 0; i < sig->param_count; ++i)
3515 mono_mb_emit_ldarg (mb, i + 1);
3516 mono_mb_emit_ldarg (mb, 0);
3517 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoDelegate, extra_arg));
3518 mono_mb_emit_byte (mb, CEE_LDIND_I);
3519 mono_mb_emit_ldarg (mb, 0);
3520 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoDelegate, method_ptr));
3521 mono_mb_emit_byte (mb, CEE_LDIND_I);
3522 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
3523 mono_mb_emit_op (mb, CEE_MONO_CALLI_EXTRA_ARG, invoke_sig);
3526 mono_mb_emit_byte (mb, CEE_RET);
3528 /* else [delegates != null] */
3529 mono_mb_patch_branch (mb, pos2);
3531 /* len = delegates.Length; */
3532 mono_mb_emit_ldloc (mb, local_delegates);
3533 mono_mb_emit_byte (mb, CEE_LDLEN);
3534 mono_mb_emit_byte (mb, CEE_CONV_I4);
3535 mono_mb_emit_stloc (mb, local_len);
3537 /* i = 0; */
3538 mono_mb_emit_icon (mb, 0);
3539 mono_mb_emit_stloc (mb, local_i);
3541 pos1 = mono_mb_get_label (mb);
3543 /* d = delegates [i]; */
3544 mono_mb_emit_ldloc (mb, local_delegates);
3545 mono_mb_emit_ldloc (mb, local_i);
3546 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
3547 mono_mb_emit_stloc (mb, local_d);
3549 /* res = d.Invoke ( args .. ); */
3550 mono_mb_emit_ldloc (mb, local_d);
3551 for (i = 0; i < sig->param_count; i++)
3552 mono_mb_emit_ldarg (mb, i + 1);
3553 if (!ctx) {
3554 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
3555 } else {
3556 MonoError error;
3557 mono_mb_emit_op (mb, CEE_CALLVIRT, mono_class_inflate_generic_method_checked (method, &container->context, &error));
3558 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3560 if (!void_ret)
3561 mono_mb_emit_stloc (mb, local_res);
3563 /* i += 1 */
3564 mono_mb_emit_add_to_local (mb, local_i, 1);
3566 /* i < l */
3567 mono_mb_emit_ldloc (mb, local_i);
3568 mono_mb_emit_ldloc (mb, local_len);
3569 mono_mb_emit_branch_label (mb, CEE_BLT, pos1);
3571 /* return res */
3572 if (!void_ret)
3573 mono_mb_emit_ldloc (mb, local_res);
3574 mono_mb_emit_byte (mb, CEE_RET);
3576 mb->skip_visibility = 1;
3577 #endif /* DISABLE_JIT */
3579 info = mono_wrapper_info_create (mb, subtype);
3580 info->d.delegate_invoke.method = method;
3582 if (ctx) {
3583 MonoMethod *def;
3585 def = mono_mb_create_and_cache_full (cache, cache_key, mb, sig, sig->param_count + 16, info, NULL);
3586 res = cache_generic_delegate_wrapper (cache, orig_method, def, ctx);
3587 } else if (callvirt) {
3588 new_key = g_new0 (SignaturePointerPair, 1);
3589 *new_key = key;
3591 res = mono_mb_create_and_cache_full (cache, new_key, mb, sig, sig->param_count + 16, info, &found);
3592 if (found)
3593 g_free (new_key);
3594 } else {
3595 res = mono_mb_create_and_cache_full (cache, cache_key, mb, sig, sig->param_count + 16, info, NULL);
3597 mono_mb_free (mb);
3599 /* mono_method_print_code (res); */
3601 return res;
3605 * the returned method invokes all methods in a multicast delegate.
3607 MonoMethod *
3608 mono_marshal_get_delegate_invoke (MonoMethod *method, MonoDelegate *del)
3610 gboolean callvirt = FALSE;
3611 gboolean static_method_with_first_arg_bound = FALSE;
3612 MonoMethod *target_method = NULL;
3613 MonoMethodSignature *sig;
3615 sig = mono_signature_no_pinvoke (method);
3617 if (del && !del->target && del->method && mono_method_signature (del->method)->hasthis) {
3618 callvirt = TRUE;
3619 target_method = del->method;
3622 if (del && del->method && mono_method_signature (del->method)->param_count == sig->param_count + 1 && (del->method->flags & METHOD_ATTRIBUTE_STATIC)) {
3623 static_method_with_first_arg_bound = TRUE;
3624 target_method = del->method;
3627 return mono_marshal_get_delegate_invoke_internal (method, callvirt, static_method_with_first_arg_bound, target_method);
3630 typedef struct {
3631 MonoMethodSignature *ctor_sig;
3632 MonoMethodSignature *sig;
3633 } CtorSigPair;
3635 /* protected by the marshal lock, contains CtorSigPair pointers */
3636 static GSList *strsig_list = NULL;
3638 static MonoMethodSignature *
3639 lookup_string_ctor_signature (MonoMethodSignature *sig)
3641 MonoMethodSignature *callsig;
3642 CtorSigPair *cs;
3643 GSList *item;
3645 mono_marshal_lock ();
3646 callsig = NULL;
3647 for (item = strsig_list; item; item = item->next) {
3648 cs = (CtorSigPair *)item->data;
3649 /* mono_metadata_signature_equal () is safe to call with the marshal lock
3650 * because it is lock-free.
3652 if (mono_metadata_signature_equal (sig, cs->ctor_sig)) {
3653 callsig = cs->sig;
3654 break;
3657 mono_marshal_unlock ();
3658 return callsig;
3661 static MonoMethodSignature *
3662 add_string_ctor_signature (MonoMethod *method)
3664 MonoMethodSignature *callsig;
3665 CtorSigPair *cs;
3667 callsig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
3668 callsig->ret = &mono_defaults.string_class->byval_arg;
3669 cs = g_new (CtorSigPair, 1);
3670 cs->sig = callsig;
3671 cs->ctor_sig = mono_method_signature (method);
3673 mono_marshal_lock ();
3674 strsig_list = g_slist_prepend (strsig_list, cs);
3675 mono_marshal_unlock ();
3676 return callsig;
3680 * mono_marshal_get_string_ctor_signature:
3682 * Return the modified signature used by string ctors (they return the newly created
3683 * string).
3685 MonoMethodSignature*
3686 mono_marshal_get_string_ctor_signature (MonoMethod *method)
3688 MonoMethodSignature *sig = lookup_string_ctor_signature (mono_method_signature (method));
3689 if (!sig)
3690 sig = add_string_ctor_signature (method);
3692 return sig;
3695 static MonoType*
3696 get_runtime_invoke_type (MonoType *t, gboolean ret)
3698 if (t->byref) {
3699 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t)))
3700 return t;
3701 /* Can't share this with 'I' as that needs another indirection */
3702 return &mono_defaults.int_class->this_arg;
3705 if (MONO_TYPE_IS_REFERENCE (t))
3706 return &mono_defaults.object_class->byval_arg;
3708 if (ret)
3709 /* The result needs to be boxed */
3710 return t;
3712 handle_enum:
3713 switch (t->type) {
3714 /* Can't share these as the argument needs to be loaded using sign/zero extension */
3716 case MONO_TYPE_U1:
3717 return &mono_defaults.sbyte_class->byval_arg;
3718 case MONO_TYPE_U2:
3719 return &mono_defaults.int16_class->byval_arg;
3720 case MONO_TYPE_U4:
3721 return &mono_defaults.int32_class->byval_arg;
3723 case MONO_TYPE_U8:
3724 return &mono_defaults.int64_class->byval_arg;
3725 case MONO_TYPE_BOOLEAN:
3726 return &mono_defaults.byte_class->byval_arg;
3727 case MONO_TYPE_CHAR:
3728 return &mono_defaults.uint16_class->byval_arg;
3729 case MONO_TYPE_U:
3730 return &mono_defaults.int_class->byval_arg;
3731 case MONO_TYPE_VALUETYPE:
3732 if (t->data.klass->enumtype) {
3733 t = mono_class_enum_basetype (t->data.klass);
3734 goto handle_enum;
3736 return t;
3737 default:
3738 return t;
3743 * mono_marshal_get_runtime_invoke_sig:
3745 * Return a common signature used for sharing runtime invoke wrappers.
3747 static MonoMethodSignature*
3748 mono_marshal_get_runtime_invoke_sig (MonoMethodSignature *sig)
3750 MonoMethodSignature *res = mono_metadata_signature_dup (sig);
3751 int i;
3753 res->generic_param_count = 0;
3754 res->ret = get_runtime_invoke_type (sig->ret, TRUE);
3755 for (i = 0; i < res->param_count; ++i)
3756 res->params [i] = get_runtime_invoke_type (sig->params [i], FALSE);
3758 return res;
3761 static gboolean
3762 runtime_invoke_signature_equal (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
3764 /* Can't share wrappers which return a vtype since it needs to be boxed */
3765 if (sig1->ret != sig2->ret && !(MONO_TYPE_IS_REFERENCE (sig1->ret) && MONO_TYPE_IS_REFERENCE (sig2->ret)) && !mono_metadata_type_equal (sig1->ret, sig2->ret))
3766 return FALSE;
3767 else
3768 return mono_metadata_signature_equal (sig1, sig2);
3771 #ifndef DISABLE_JIT
3774 * emit_invoke_call:
3776 * Emit the call to the wrapper method from a runtime invoke wrapper.
3778 static void
3779 emit_invoke_call (MonoMethodBuilder *mb, MonoMethod *method,
3780 MonoMethodSignature *sig, MonoMethodSignature *callsig,
3781 int loc_res,
3782 gboolean virtual_, gboolean need_direct_wrapper)
3784 static MonoString *string_dummy = NULL;
3785 int i;
3786 int *tmp_nullable_locals;
3787 gboolean void_ret = FALSE;
3788 gboolean string_ctor = method && method->string_ctor;
3790 /* to make it work with our special string constructors */
3791 if (!string_dummy) {
3792 MONO_GC_REGISTER_ROOT_SINGLE (string_dummy, MONO_ROOT_SOURCE_MARSHAL, "dummy marshal string");
3793 string_dummy = mono_string_new_wrapper ("dummy");
3796 if (virtual_) {
3797 g_assert (sig->hasthis);
3798 g_assert (method->flags & METHOD_ATTRIBUTE_VIRTUAL);
3801 if (sig->hasthis) {
3802 if (string_ctor) {
3803 if (mono_gc_is_moving ()) {
3804 mono_mb_emit_ptr (mb, &string_dummy);
3805 mono_mb_emit_byte (mb, CEE_LDIND_REF);
3806 } else {
3807 mono_mb_emit_ptr (mb, string_dummy);
3809 } else {
3810 mono_mb_emit_ldarg (mb, 0);
3814 tmp_nullable_locals = g_new0 (int, sig->param_count);
3816 for (i = 0; i < sig->param_count; i++) {
3817 MonoType *t = sig->params [i];
3818 int type;
3820 mono_mb_emit_ldarg (mb, 1);
3821 if (i) {
3822 mono_mb_emit_icon (mb, sizeof (gpointer) * i);
3823 mono_mb_emit_byte (mb, CEE_ADD);
3826 if (t->byref) {
3827 mono_mb_emit_byte (mb, CEE_LDIND_I);
3828 /* A Nullable<T> type don't have a boxed form, it's either null or a boxed T.
3829 * So to make this work we unbox it to a local variablee and push a reference to that.
3831 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
3832 tmp_nullable_locals [i] = mono_mb_add_local (mb, &mono_class_from_mono_type (t)->byval_arg);
3834 mono_mb_emit_op (mb, CEE_UNBOX_ANY, mono_class_from_mono_type (t));
3835 mono_mb_emit_stloc (mb, tmp_nullable_locals [i]);
3836 mono_mb_emit_ldloc_addr (mb, tmp_nullable_locals [i]);
3838 continue;
3841 /*FIXME 'this doesn't handle generic enums. Shouldn't we?*/
3842 type = sig->params [i]->type;
3843 handle_enum:
3844 switch (type) {
3845 case MONO_TYPE_I1:
3846 case MONO_TYPE_BOOLEAN:
3847 case MONO_TYPE_U1:
3848 case MONO_TYPE_I2:
3849 case MONO_TYPE_U2:
3850 case MONO_TYPE_CHAR:
3851 case MONO_TYPE_I:
3852 case MONO_TYPE_U:
3853 case MONO_TYPE_I4:
3854 case MONO_TYPE_U4:
3855 case MONO_TYPE_R4:
3856 case MONO_TYPE_R8:
3857 case MONO_TYPE_I8:
3858 case MONO_TYPE_U8:
3859 mono_mb_emit_byte (mb, CEE_LDIND_I);
3860 mono_mb_emit_byte (mb, mono_type_to_ldind (sig->params [i]));
3861 break;
3862 case MONO_TYPE_STRING:
3863 case MONO_TYPE_CLASS:
3864 case MONO_TYPE_ARRAY:
3865 case MONO_TYPE_PTR:
3866 case MONO_TYPE_SZARRAY:
3867 case MONO_TYPE_OBJECT:
3868 mono_mb_emit_byte (mb, mono_type_to_ldind (sig->params [i]));
3869 break;
3870 case MONO_TYPE_GENERICINST:
3871 if (!mono_type_generic_inst_is_valuetype (sig->params [i])) {
3872 mono_mb_emit_byte (mb, mono_type_to_ldind (sig->params [i]));
3873 break;
3876 /* fall through */
3877 case MONO_TYPE_VALUETYPE:
3878 if (type == MONO_TYPE_VALUETYPE && t->data.klass->enumtype) {
3879 type = mono_class_enum_basetype (t->data.klass)->type;
3880 goto handle_enum;
3882 mono_mb_emit_byte (mb, CEE_LDIND_I);
3883 if (mono_class_is_nullable (mono_class_from_mono_type (sig->params [i]))) {
3884 /* Need to convert a boxed vtype to an mp to a Nullable struct */
3885 mono_mb_emit_op (mb, CEE_UNBOX, mono_class_from_mono_type (sig->params [i]));
3886 mono_mb_emit_op (mb, CEE_LDOBJ, mono_class_from_mono_type (sig->params [i]));
3887 } else {
3888 mono_mb_emit_op (mb, CEE_LDOBJ, mono_class_from_mono_type (sig->params [i]));
3890 break;
3891 default:
3892 g_assert_not_reached ();
3896 if (virtual_) {
3897 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
3898 } else if (need_direct_wrapper) {
3899 mono_mb_emit_op (mb, CEE_CALL, method);
3900 } else {
3901 mono_mb_emit_ldarg (mb, 3);
3902 mono_mb_emit_calli (mb, callsig);
3905 if (sig->ret->byref) {
3906 /* fixme: */
3907 g_assert_not_reached ();
3910 switch (sig->ret->type) {
3911 case MONO_TYPE_VOID:
3912 if (!string_ctor)
3913 void_ret = TRUE;
3914 break;
3915 case MONO_TYPE_BOOLEAN:
3916 case MONO_TYPE_CHAR:
3917 case MONO_TYPE_I1:
3918 case MONO_TYPE_U1:
3919 case MONO_TYPE_I2:
3920 case MONO_TYPE_U2:
3921 case MONO_TYPE_I4:
3922 case MONO_TYPE_U4:
3923 case MONO_TYPE_I:
3924 case MONO_TYPE_U:
3925 case MONO_TYPE_R4:
3926 case MONO_TYPE_R8:
3927 case MONO_TYPE_I8:
3928 case MONO_TYPE_U8:
3929 case MONO_TYPE_VALUETYPE:
3930 case MONO_TYPE_TYPEDBYREF:
3931 case MONO_TYPE_GENERICINST:
3932 /* box value types */
3933 mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (sig->ret));
3934 break;
3935 case MONO_TYPE_STRING:
3936 case MONO_TYPE_CLASS:
3937 case MONO_TYPE_ARRAY:
3938 case MONO_TYPE_SZARRAY:
3939 case MONO_TYPE_OBJECT:
3940 /* nothing to do */
3941 break;
3942 case MONO_TYPE_PTR:
3943 /* The result is an IntPtr */
3944 mono_mb_emit_op (mb, CEE_BOX, mono_defaults.int_class);
3945 break;
3946 default:
3947 g_assert_not_reached ();
3950 if (!void_ret)
3951 mono_mb_emit_stloc (mb, loc_res);
3953 /* Convert back nullable-byref arguments */
3954 for (i = 0; i < sig->param_count; i++) {
3955 MonoType *t = sig->params [i];
3958 * Box the result and put it back into the array, the caller will have
3959 * to obtain it from there.
3961 if (t->byref && t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
3962 mono_mb_emit_ldarg (mb, 1);
3963 mono_mb_emit_icon (mb, sizeof (gpointer) * i);
3964 mono_mb_emit_byte (mb, CEE_ADD);
3966 mono_mb_emit_ldloc (mb, tmp_nullable_locals [i]);
3967 mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (t));
3969 mono_mb_emit_byte (mb, CEE_STIND_REF);
3973 g_free (tmp_nullable_locals);
3976 static void
3977 emit_runtime_invoke_body (MonoMethodBuilder *mb, MonoImage *image, MonoMethod *method,
3978 MonoMethodSignature *sig, MonoMethodSignature *callsig,
3979 gboolean virtual_, gboolean need_direct_wrapper)
3981 gint32 labels [16];
3982 MonoExceptionClause *clause;
3983 int loc_res, loc_exc;
3985 /* The wrapper looks like this:
3987 * <interrupt check>
3988 * if (exc) {
3989 * try {
3990 * return <call>
3991 * } catch (Exception e) {
3992 * *exc = e;
3994 * } else {
3995 * return <call>
3999 /* allocate local 0 (object) tmp */
4000 loc_res = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
4001 /* allocate local 1 (object) exc */
4002 loc_exc = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
4004 /* *exc is assumed to be initialized to NULL by the caller */
4006 mono_mb_emit_byte (mb, CEE_LDARG_2);
4007 labels [0] = mono_mb_emit_branch (mb, CEE_BRFALSE);
4010 * if (exc) case
4012 labels [1] = mono_mb_get_label (mb);
4013 emit_thread_force_interrupt_checkpoint (mb);
4014 emit_invoke_call (mb, method, sig, callsig, loc_res, virtual_, need_direct_wrapper);
4016 labels [2] = mono_mb_emit_branch (mb, CEE_LEAVE);
4018 /* Add a try clause around the call */
4019 clause = (MonoExceptionClause *)mono_image_alloc0 (image, sizeof (MonoExceptionClause));
4020 clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
4021 clause->data.catch_class = mono_defaults.exception_class;
4022 clause->try_offset = labels [1];
4023 clause->try_len = mono_mb_get_label (mb) - labels [1];
4025 clause->handler_offset = mono_mb_get_label (mb);
4027 /* handler code */
4028 mono_mb_emit_stloc (mb, loc_exc);
4029 mono_mb_emit_byte (mb, CEE_LDARG_2);
4030 mono_mb_emit_ldloc (mb, loc_exc);
4031 mono_mb_emit_byte (mb, CEE_STIND_REF);
4033 mono_mb_emit_branch (mb, CEE_LEAVE);
4035 clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
4037 mono_mb_set_clauses (mb, 1, clause);
4039 mono_mb_patch_branch (mb, labels [2]);
4040 mono_mb_emit_ldloc (mb, loc_res);
4041 mono_mb_emit_byte (mb, CEE_RET);
4044 * if (!exc) case
4046 mono_mb_patch_branch (mb, labels [0]);
4047 emit_thread_force_interrupt_checkpoint (mb);
4048 emit_invoke_call (mb, method, sig, callsig, loc_res, virtual_, need_direct_wrapper);
4050 mono_mb_emit_ldloc (mb, 0);
4051 mono_mb_emit_byte (mb, CEE_RET);
4053 #endif
4056 * generates IL code for the runtime invoke function
4057 * MonoObject *runtime_invoke (MonoObject *this_obj, void **params, MonoObject **exc, void* method)
4059 * we also catch exceptions if exc != null
4060 * If VIRTUAL is TRUE, then METHOD is invoked virtually on THIS. This is useful since
4061 * it means that the compiled code for METHOD does not have to be looked up
4062 * before calling the runtime invoke wrapper. In this case, the wrapper ignores
4063 * its METHOD argument.
4065 MonoMethod *
4066 mono_marshal_get_runtime_invoke (MonoMethod *method, gboolean virtual_)
4068 MonoMethodSignature *sig, *csig, *callsig;
4069 MonoMethodBuilder *mb;
4070 GHashTable *cache = NULL;
4071 MonoClass *target_klass;
4072 MonoMethod *res = NULL;
4073 static MonoMethodSignature *cctor_signature = NULL;
4074 static MonoMethodSignature *finalize_signature = NULL;
4075 char *name;
4076 const char *param_names [16];
4077 gboolean need_direct_wrapper = FALSE;
4078 WrapperInfo *info;
4080 g_assert (method);
4082 if (!cctor_signature) {
4083 cctor_signature = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4084 cctor_signature->ret = &mono_defaults.void_class->byval_arg;
4086 if (!finalize_signature) {
4087 finalize_signature = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4088 finalize_signature->ret = &mono_defaults.void_class->byval_arg;
4089 finalize_signature->hasthis = 1;
4092 if (virtual_)
4093 need_direct_wrapper = TRUE;
4096 * Use a separate cache indexed by methods to speed things up and to avoid the
4097 * boundless mempool growth caused by the signature_dup stuff below.
4099 if (virtual_)
4100 cache = get_cache (&method->klass->image->runtime_invoke_vcall_cache, mono_aligned_addr_hash, NULL);
4101 else
4102 cache = get_cache (&mono_method_get_wrapper_cache (method)->runtime_invoke_direct_cache, mono_aligned_addr_hash, NULL);
4104 res = mono_marshal_find_in_cache (cache, method);
4105 if (res)
4106 return res;
4108 if (method->klass->rank && (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
4109 (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
4111 * Array Get/Set/Address methods. The JIT implements them using inline code
4112 * so we need to create an invoke wrapper which calls the method directly.
4114 need_direct_wrapper = TRUE;
4117 if (method->string_ctor) {
4118 callsig = lookup_string_ctor_signature (mono_method_signature (method));
4119 if (!callsig)
4120 callsig = add_string_ctor_signature (method);
4121 /* Can't share this as we push a string as this */
4122 need_direct_wrapper = TRUE;
4123 } else {
4124 if (method_is_dynamic (method))
4125 callsig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
4126 else
4127 callsig = mono_method_signature (method);
4130 sig = mono_method_signature (method);
4132 target_klass = get_wrapper_target_class (method->klass->image);
4134 /* Try to share wrappers for non-corlib methods with simple signatures */
4135 if (mono_metadata_signature_equal (callsig, cctor_signature)) {
4136 callsig = cctor_signature;
4137 target_klass = mono_defaults.object_class;
4138 } else if (mono_metadata_signature_equal (callsig, finalize_signature)) {
4139 callsig = finalize_signature;
4140 target_klass = mono_defaults.object_class;
4143 if (need_direct_wrapper) {
4144 /* Already searched at the start */
4145 } else {
4146 MonoMethodSignature *tmp_sig;
4148 callsig = mono_marshal_get_runtime_invoke_sig (callsig);
4149 GHashTable **cache_table = NULL;
4151 if (method->klass->valuetype && mono_method_signature (method)->hasthis)
4152 cache_table = &mono_method_get_wrapper_cache (method)->runtime_invoke_vtype_cache;
4153 else
4154 cache_table = &mono_method_get_wrapper_cache (method)->runtime_invoke_cache;
4156 cache = get_cache (cache_table, (GHashFunc)mono_signature_hash,
4157 (GCompareFunc)runtime_invoke_signature_equal);
4159 /* from mono_marshal_find_in_cache */
4160 mono_marshal_lock ();
4161 res = (MonoMethod *)g_hash_table_lookup (cache, callsig);
4162 mono_marshal_unlock ();
4164 if (res) {
4165 g_free (callsig);
4166 return res;
4169 /* Make a copy of the signature from the image mempool */
4170 tmp_sig = callsig;
4171 callsig = mono_metadata_signature_dup_full (target_klass->image, callsig);
4172 g_free (tmp_sig);
4175 csig = mono_metadata_signature_alloc (target_klass->image, 4);
4177 csig->ret = &mono_defaults.object_class->byval_arg;
4178 if (method->klass->valuetype && mono_method_signature (method)->hasthis)
4179 csig->params [0] = get_runtime_invoke_type (&method->klass->this_arg, FALSE);
4180 else
4181 csig->params [0] = &mono_defaults.object_class->byval_arg;
4182 csig->params [1] = &mono_defaults.int_class->byval_arg;
4183 csig->params [2] = &mono_defaults.int_class->byval_arg;
4184 csig->params [3] = &mono_defaults.int_class->byval_arg;
4185 csig->pinvoke = 1;
4186 #if TARGET_WIN32
4187 /* This is called from runtime code so it has to be cdecl */
4188 csig->call_convention = MONO_CALL_C;
4189 #endif
4191 name = mono_signature_to_name (callsig, virtual_ ? "runtime_invoke_virtual" : "runtime_invoke");
4192 mb = mono_mb_new (target_klass, name, MONO_WRAPPER_RUNTIME_INVOKE);
4193 g_free (name);
4195 #ifndef DISABLE_JIT
4196 param_names [0] = "this";
4197 param_names [1] = "params";
4198 param_names [2] = "exc";
4199 param_names [3] = "method";
4200 mono_mb_set_param_names (mb, param_names);
4202 emit_runtime_invoke_body (mb, target_klass->image, method, sig, callsig, virtual_, need_direct_wrapper);
4203 #endif
4205 if (need_direct_wrapper) {
4206 #ifndef DISABLE_JIT
4207 mb->skip_visibility = 1;
4208 #endif
4209 info = mono_wrapper_info_create (mb, virtual_ ? WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL : WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT);
4210 info->d.runtime_invoke.method = method;
4211 res = mono_mb_create_and_cache_full (cache, method, mb, csig, sig->param_count + 16, info, NULL);
4212 } else {
4213 /* taken from mono_mb_create_and_cache */
4214 mono_marshal_lock ();
4215 res = (MonoMethod *)g_hash_table_lookup (cache, callsig);
4216 mono_marshal_unlock ();
4218 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL);
4219 info->d.runtime_invoke.sig = callsig;
4221 /* Somebody may have created it before us */
4222 if (!res) {
4223 MonoMethod *newm;
4224 newm = mono_mb_create (mb, csig, sig->param_count + 16, info);
4226 mono_marshal_lock ();
4227 res = (MonoMethod *)g_hash_table_lookup (cache, callsig);
4228 if (!res) {
4229 GHashTable *direct_cache;
4230 res = newm;
4231 g_hash_table_insert (cache, callsig, res);
4232 /* Can't insert it into wrapper_hash since the key is a signature */
4233 direct_cache = mono_method_get_wrapper_cache (method)->runtime_invoke_direct_cache;
4235 g_hash_table_insert (direct_cache, method, res);
4236 } else {
4237 mono_free_method (newm);
4239 mono_marshal_unlock ();
4242 /* end mono_mb_create_and_cache */
4245 mono_mb_free (mb);
4247 return res;
4251 * mono_marshal_get_runtime_invoke_dynamic:
4253 * Return a method which can be used to invoke managed methods from native code
4254 * dynamically.
4255 * The signature of the returned method is given by RuntimeInvokeDynamicFunction:
4256 * void runtime_invoke (void *args, MonoObject **exc, void *compiled_method)
4257 * ARGS should point to an architecture specific structure containing
4258 * the arguments and space for the return value.
4259 * The other arguments are the same as for runtime_invoke (), except that
4260 * ARGS should contain the this argument too.
4261 * This wrapper serves the same purpose as the runtime-invoke wrappers, but there
4262 * is only one copy of it, which is useful in full-aot.
4264 MonoMethod*
4265 mono_marshal_get_runtime_invoke_dynamic (void)
4267 static MonoMethod *method;
4268 MonoMethodSignature *csig;
4269 MonoExceptionClause *clause;
4270 MonoMethodBuilder *mb;
4271 int pos, posna;
4272 char *name;
4273 WrapperInfo *info;
4275 if (method)
4276 return method;
4278 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 4);
4280 csig->ret = &mono_defaults.void_class->byval_arg;
4281 csig->params [0] = &mono_defaults.int_class->byval_arg;
4282 csig->params [1] = &mono_defaults.int_class->byval_arg;
4283 csig->params [2] = &mono_defaults.int_class->byval_arg;
4284 csig->params [3] = &mono_defaults.int_class->byval_arg;
4286 name = g_strdup ("runtime_invoke_dynamic");
4287 mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_RUNTIME_INVOKE);
4288 g_free (name);
4290 #ifndef DISABLE_JIT
4291 /* allocate local 0 (object) tmp */
4292 mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
4293 /* allocate local 1 (object) exc */
4294 mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
4296 /* cond set *exc to null */
4297 mono_mb_emit_byte (mb, CEE_LDARG_1);
4298 mono_mb_emit_byte (mb, CEE_BRFALSE_S);
4299 mono_mb_emit_byte (mb, 3);
4300 mono_mb_emit_byte (mb, CEE_LDARG_1);
4301 mono_mb_emit_byte (mb, CEE_LDNULL);
4302 mono_mb_emit_byte (mb, CEE_STIND_REF);
4304 emit_thread_force_interrupt_checkpoint (mb);
4306 mono_mb_emit_byte (mb, CEE_LDARG_0);
4307 mono_mb_emit_byte (mb, CEE_LDARG_2);
4308 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
4309 mono_mb_emit_byte (mb, CEE_MONO_DYN_CALL);
4311 pos = mono_mb_emit_branch (mb, CEE_LEAVE);
4313 clause = (MonoExceptionClause *)mono_image_alloc0 (mono_defaults.corlib, sizeof (MonoExceptionClause));
4314 clause->flags = MONO_EXCEPTION_CLAUSE_FILTER;
4315 clause->try_len = mono_mb_get_label (mb);
4317 /* filter code */
4318 clause->data.filter_offset = mono_mb_get_label (mb);
4320 mono_mb_emit_byte (mb, CEE_POP);
4321 mono_mb_emit_byte (mb, CEE_LDARG_1);
4322 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
4323 mono_mb_emit_byte (mb, CEE_PREFIX1);
4324 mono_mb_emit_byte (mb, CEE_CGT_UN);
4325 mono_mb_emit_byte (mb, CEE_PREFIX1);
4326 mono_mb_emit_byte (mb, CEE_ENDFILTER);
4328 clause->handler_offset = mono_mb_get_label (mb);
4330 /* handler code */
4331 /* store exception */
4332 mono_mb_emit_stloc (mb, 1);
4334 mono_mb_emit_byte (mb, CEE_LDARG_1);
4335 mono_mb_emit_ldloc (mb, 1);
4336 mono_mb_emit_byte (mb, CEE_STIND_REF);
4338 mono_mb_emit_byte (mb, CEE_LDNULL);
4339 mono_mb_emit_stloc (mb, 0);
4341 /* Check for the abort exception */
4342 mono_mb_emit_ldloc (mb, 1);
4343 mono_mb_emit_op (mb, CEE_ISINST, mono_defaults.threadabortexception_class);
4344 posna = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
4346 /* Delay the abort exception */
4347 mono_mb_emit_icall (mb, ves_icall_System_Threading_Thread_ResetAbort);
4349 mono_mb_patch_short_branch (mb, posna);
4350 mono_mb_emit_branch (mb, CEE_LEAVE);
4352 clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
4354 mono_mb_set_clauses (mb, 1, clause);
4356 /* return result */
4357 mono_mb_patch_branch (mb, pos);
4358 //mono_mb_emit_ldloc (mb, 0);
4359 mono_mb_emit_byte (mb, CEE_RET);
4360 #endif /* DISABLE_JIT */
4362 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC);
4364 mono_marshal_lock ();
4365 /* double-checked locking */
4366 if (!method)
4367 method = mono_mb_create (mb, csig, 16, info);
4369 mono_marshal_unlock ();
4371 mono_mb_free (mb);
4373 return method;
4377 * mono_marshal_get_runtime_invoke_for_sig:
4379 * Return a runtime invoke wrapper for a given signature.
4381 MonoMethod *
4382 mono_marshal_get_runtime_invoke_for_sig (MonoMethodSignature *sig)
4384 MonoMethodSignature *csig, *callsig;
4385 MonoMethodBuilder *mb;
4386 MonoImage *image;
4387 GHashTable *cache = NULL;
4388 GHashTable **cache_table = NULL;
4389 MonoMethod *res = NULL;
4390 char *name;
4391 const char *param_names [16];
4392 WrapperInfo *info;
4394 /* A simplified version of mono_marshal_get_runtime_invoke */
4396 image = mono_defaults.corlib;
4398 callsig = mono_marshal_get_runtime_invoke_sig (sig);
4400 cache_table = &image->wrapper_caches.runtime_invoke_sig_cache;
4402 cache = get_cache (cache_table, (GHashFunc)mono_signature_hash,
4403 (GCompareFunc)runtime_invoke_signature_equal);
4405 /* from mono_marshal_find_in_cache */
4406 mono_marshal_lock ();
4407 res = (MonoMethod *)g_hash_table_lookup (cache, callsig);
4408 mono_marshal_unlock ();
4410 if (res) {
4411 g_free (callsig);
4412 return res;
4415 /* Make a copy of the signature from the image mempool */
4416 callsig = mono_metadata_signature_dup_full (image, callsig);
4418 csig = mono_metadata_signature_alloc (image, 4);
4419 csig->ret = &mono_defaults.object_class->byval_arg;
4420 csig->params [0] = &mono_defaults.object_class->byval_arg;
4421 csig->params [1] = &mono_defaults.int_class->byval_arg;
4422 csig->params [2] = &mono_defaults.int_class->byval_arg;
4423 csig->params [3] = &mono_defaults.int_class->byval_arg;
4424 csig->pinvoke = 1;
4425 #if TARGET_WIN32
4426 /* This is called from runtime code so it has to be cdecl */
4427 csig->call_convention = MONO_CALL_C;
4428 #endif
4430 name = mono_signature_to_name (callsig, "runtime_invoke_sig");
4431 mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_RUNTIME_INVOKE);
4432 g_free (name);
4434 #ifndef DISABLE_JIT
4435 param_names [0] = "this";
4436 param_names [1] = "params";
4437 param_names [2] = "exc";
4438 param_names [3] = "method";
4439 mono_mb_set_param_names (mb, param_names);
4441 emit_runtime_invoke_body (mb, image, NULL, sig, callsig, FALSE, FALSE);
4442 #endif
4444 /* taken from mono_mb_create_and_cache */
4445 mono_marshal_lock ();
4446 res = (MonoMethod *)g_hash_table_lookup (cache, callsig);
4447 mono_marshal_unlock ();
4449 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL);
4450 info->d.runtime_invoke.sig = callsig;
4452 /* Somebody may have created it before us */
4453 if (!res) {
4454 MonoMethod *newm;
4455 newm = mono_mb_create (mb, csig, sig->param_count + 16, info);
4457 mono_marshal_lock ();
4458 res = (MonoMethod *)g_hash_table_lookup (cache, callsig);
4459 if (!res) {
4460 res = newm;
4461 g_hash_table_insert (cache, callsig, res);
4462 } else {
4463 mono_free_method (newm);
4465 mono_marshal_unlock ();
4468 /* end mono_mb_create_and_cache */
4470 mono_mb_free (mb);
4472 return res;
4475 #ifndef DISABLE_JIT
4476 static void
4477 mono_mb_emit_auto_layout_exception (MonoMethodBuilder *mb, MonoClass *klass)
4479 char *msg = g_strdup_printf ("The type `%s.%s' layout needs to be Sequential or Explicit",
4480 klass->name_space, klass->name);
4482 mono_mb_emit_exception_marshal_directive (mb, msg);
4484 #endif
4487 * generates IL code for the icall wrapper (the generated method
4488 * calls the unmanaged code in func)
4490 MonoMethod *
4491 mono_marshal_get_icall_wrapper (MonoMethodSignature *sig, const char *name, gconstpointer func, gboolean check_exceptions)
4493 MonoMethodSignature *csig, *csig2;
4494 MonoMethodBuilder *mb;
4495 MonoMethod *res;
4496 int i;
4497 WrapperInfo *info;
4499 GHashTable *cache = get_cache (&mono_defaults.object_class->image->icall_wrapper_cache, mono_aligned_addr_hash, NULL);
4500 if ((res = mono_marshal_find_in_cache (cache, (gpointer) func)))
4501 return res;
4503 g_assert (sig->pinvoke);
4505 mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
4507 mb->method->save_lmf = 1;
4509 /* Add an explicit this argument */
4510 if (sig->hasthis)
4511 csig2 = mono_metadata_signature_dup_add_this (mono_defaults.corlib, sig, mono_defaults.object_class);
4512 else
4513 csig2 = mono_metadata_signature_dup_full (mono_defaults.corlib, sig);
4515 #ifndef DISABLE_JIT
4516 if (sig->hasthis)
4517 mono_mb_emit_byte (mb, CEE_LDARG_0);
4519 for (i = 0; i < sig->param_count; i++)
4520 mono_mb_emit_ldarg (mb, i + sig->hasthis);
4522 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
4523 mono_mb_emit_op (mb, CEE_MONO_JIT_ICALL_ADDR, (gpointer)func);
4524 mono_mb_emit_calli (mb, csig2);
4525 if (check_exceptions)
4526 emit_thread_interrupt_checkpoint (mb);
4527 mono_mb_emit_byte (mb, CEE_RET);
4528 #endif
4530 csig = mono_metadata_signature_dup_full (mono_defaults.corlib, sig);
4531 csig->pinvoke = 0;
4532 if (csig->call_convention == MONO_CALL_VARARG)
4533 csig->call_convention = 0;
4535 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ICALL_WRAPPER);
4536 info->d.icall.func = (gpointer)func;
4537 res = mono_mb_create_and_cache_full (cache, (gpointer) func, mb, csig, csig->param_count + 16, info, NULL);
4538 mono_mb_free (mb);
4540 return res;
4543 static int
4544 emit_marshal_custom (EmitMarshalContext *m, int argnum, MonoType *t,
4545 MonoMarshalSpec *spec,
4546 int conv_arg, MonoType **conv_arg_type,
4547 MarshalAction action)
4549 #ifdef DISABLE_JIT
4550 if (action == MARSHAL_ACTION_CONV_IN && t->type == MONO_TYPE_VALUETYPE)
4551 *conv_arg_type = &mono_defaults.int_class->byval_arg;
4552 return conv_arg;
4553 #else
4554 MonoError error;
4555 MonoType *mtype;
4556 MonoClass *mklass;
4557 static MonoClass *ICustomMarshaler = NULL;
4558 static MonoMethod *cleanup_native, *cleanup_managed;
4559 static MonoMethod *marshal_managed_to_native, *marshal_native_to_managed;
4560 MonoMethod *get_instance = NULL;
4561 MonoMethodBuilder *mb = m->mb;
4562 char *exception_msg = NULL;
4563 guint32 loc1;
4564 int pos2;
4566 if (!ICustomMarshaler) {
4567 MonoClass *klass = mono_class_try_get_icustom_marshaler_class ();
4568 if (!klass) {
4569 exception_msg = g_strdup ("Current profile doesn't support ICustomMarshaler");
4570 goto handle_exception;
4573 cleanup_native = mono_class_get_method_from_name (klass, "CleanUpNativeData", 1);
4574 g_assert (cleanup_native);
4575 cleanup_managed = mono_class_get_method_from_name (klass, "CleanUpManagedData", 1);
4576 g_assert (cleanup_managed);
4577 marshal_managed_to_native = mono_class_get_method_from_name (klass, "MarshalManagedToNative", 1);
4578 g_assert (marshal_managed_to_native);
4579 marshal_native_to_managed = mono_class_get_method_from_name (klass, "MarshalNativeToManaged", 1);
4580 g_assert (marshal_native_to_managed);
4582 mono_memory_barrier ();
4583 ICustomMarshaler = klass;
4586 if (spec->data.custom_data.image)
4587 mtype = mono_reflection_type_from_name_checked (spec->data.custom_data.custom_name, spec->data.custom_data.image, &error);
4588 else
4589 mtype = mono_reflection_type_from_name_checked (spec->data.custom_data.custom_name, m->image, &error);
4590 g_assert (mtype != NULL);
4591 mono_error_assert_ok (&error);
4592 mklass = mono_class_from_mono_type (mtype);
4593 g_assert (mklass != NULL);
4595 if (!mono_class_is_assignable_from (ICustomMarshaler, mklass))
4596 exception_msg = g_strdup_printf ("Custom marshaler '%s' does not implement the ICustomMarshaler interface.", mklass->name);
4598 get_instance = mono_class_get_method_from_name_flags (mklass, "GetInstance", 1, METHOD_ATTRIBUTE_STATIC);
4599 if (get_instance) {
4600 MonoMethodSignature *get_sig = mono_method_signature (get_instance);
4601 if ((get_sig->ret->type != MONO_TYPE_CLASS) ||
4602 (mono_class_from_mono_type (get_sig->ret) != ICustomMarshaler) ||
4603 (get_sig->params [0]->type != MONO_TYPE_STRING))
4604 get_instance = NULL;
4607 if (!get_instance)
4608 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);
4610 handle_exception:
4611 /* Throw exception and emit compensation code if neccesary */
4612 if (exception_msg) {
4613 switch (action) {
4614 case MARSHAL_ACTION_CONV_IN:
4615 case MARSHAL_ACTION_CONV_RESULT:
4616 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
4617 if ((action == MARSHAL_ACTION_CONV_RESULT) || (action == MARSHAL_ACTION_MANAGED_CONV_RESULT))
4618 mono_mb_emit_byte (mb, CEE_POP);
4620 mono_mb_emit_exception_full (mb, "System", "ApplicationException", exception_msg);
4621 g_free (exception_msg);
4623 break;
4624 case MARSHAL_ACTION_PUSH:
4625 mono_mb_emit_byte (mb, CEE_LDNULL);
4626 break;
4627 default:
4628 break;
4630 return 0;
4633 /* FIXME: MS.NET seems to create one instance for each klass + cookie pair */
4634 /* FIXME: MS.NET throws an exception if GetInstance returns null */
4636 switch (action) {
4637 case MARSHAL_ACTION_CONV_IN:
4638 switch (t->type) {
4639 case MONO_TYPE_CLASS:
4640 case MONO_TYPE_OBJECT:
4641 case MONO_TYPE_STRING:
4642 case MONO_TYPE_ARRAY:
4643 case MONO_TYPE_SZARRAY:
4644 case MONO_TYPE_VALUETYPE:
4645 break;
4647 default:
4648 g_warning ("custom marshalling of type %x is currently not supported", t->type);
4649 g_assert_not_reached ();
4650 break;
4653 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
4655 mono_mb_emit_byte (mb, CEE_LDNULL);
4656 mono_mb_emit_stloc (mb, conv_arg);
4658 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT))
4659 break;
4661 /* Minic MS.NET behavior */
4662 if (!t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT) && !(t->attrs & PARAM_ATTRIBUTE_IN))
4663 break;
4665 /* Check for null */
4666 mono_mb_emit_ldarg (mb, argnum);
4667 if (t->byref)
4668 mono_mb_emit_byte (mb, CEE_LDIND_I);
4669 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4671 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4673 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4675 mono_mb_emit_ldarg (mb, argnum);
4676 if (t->byref)
4677 mono_mb_emit_byte (mb, CEE_LDIND_REF);
4679 if (t->type == MONO_TYPE_VALUETYPE) {
4681 * Since we can't determine the type of the argument, we
4682 * will assume the unmanaged function takes a pointer.
4684 *conv_arg_type = &mono_defaults.int_class->byval_arg;
4686 mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (t));
4689 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_managed_to_native);
4690 mono_mb_emit_stloc (mb, conv_arg);
4692 mono_mb_patch_branch (mb, pos2);
4693 break;
4695 case MARSHAL_ACTION_CONV_OUT:
4696 /* Check for null */
4697 mono_mb_emit_ldloc (mb, conv_arg);
4698 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4700 if (t->byref) {
4701 mono_mb_emit_ldarg (mb, argnum);
4703 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4705 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4707 mono_mb_emit_ldloc (mb, conv_arg);
4708 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
4709 mono_mb_emit_byte (mb, CEE_STIND_REF);
4710 } else if (t->attrs & PARAM_ATTRIBUTE_OUT) {
4711 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4713 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4715 mono_mb_emit_ldloc (mb, conv_arg);
4716 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
4718 /* We have nowhere to store the result */
4719 mono_mb_emit_byte (mb, CEE_POP);
4722 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4724 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4726 mono_mb_emit_ldloc (mb, conv_arg);
4728 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_native);
4730 mono_mb_patch_branch (mb, pos2);
4731 break;
4733 case MARSHAL_ACTION_PUSH:
4734 if (t->byref)
4735 mono_mb_emit_ldloc_addr (mb, conv_arg);
4736 else
4737 mono_mb_emit_ldloc (mb, conv_arg);
4738 break;
4740 case MARSHAL_ACTION_CONV_RESULT:
4741 loc1 = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
4743 mono_mb_emit_stloc (mb, 3);
4745 mono_mb_emit_ldloc (mb, 3);
4746 mono_mb_emit_stloc (mb, loc1);
4748 /* Check for null */
4749 mono_mb_emit_ldloc (mb, 3);
4750 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4752 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4754 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4755 mono_mb_emit_byte (mb, CEE_DUP);
4757 mono_mb_emit_ldloc (mb, 3);
4758 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
4759 mono_mb_emit_stloc (mb, 3);
4761 mono_mb_emit_ldloc (mb, loc1);
4762 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_native);
4764 mono_mb_patch_branch (mb, pos2);
4765 break;
4767 case MARSHAL_ACTION_MANAGED_CONV_IN:
4768 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
4770 mono_mb_emit_byte (mb, CEE_LDNULL);
4771 mono_mb_emit_stloc (mb, conv_arg);
4773 if (t->byref && t->attrs & PARAM_ATTRIBUTE_OUT)
4774 break;
4776 /* Check for null */
4777 mono_mb_emit_ldarg (mb, argnum);
4778 if (t->byref)
4779 mono_mb_emit_byte (mb, CEE_LDIND_I);
4780 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4782 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4783 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4785 mono_mb_emit_ldarg (mb, argnum);
4786 if (t->byref)
4787 mono_mb_emit_byte (mb, CEE_LDIND_I);
4789 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
4790 mono_mb_emit_stloc (mb, conv_arg);
4792 mono_mb_patch_branch (mb, pos2);
4793 break;
4795 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
4796 g_assert (!t->byref);
4798 loc1 = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
4800 mono_mb_emit_stloc (mb, 3);
4802 mono_mb_emit_ldloc (mb, 3);
4803 mono_mb_emit_stloc (mb, loc1);
4805 /* Check for null */
4806 mono_mb_emit_ldloc (mb, 3);
4807 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4809 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4810 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4811 mono_mb_emit_byte (mb, CEE_DUP);
4813 mono_mb_emit_ldloc (mb, 3);
4814 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_managed_to_native);
4815 mono_mb_emit_stloc (mb, 3);
4817 mono_mb_emit_ldloc (mb, loc1);
4818 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_managed);
4820 mono_mb_patch_branch (mb, pos2);
4821 break;
4823 case MARSHAL_ACTION_MANAGED_CONV_OUT:
4825 /* Check for null */
4826 mono_mb_emit_ldloc (mb, conv_arg);
4827 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4829 if (t->byref) {
4830 mono_mb_emit_ldarg (mb, argnum);
4832 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4834 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4836 mono_mb_emit_ldloc (mb, conv_arg);
4837 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_managed_to_native);
4838 mono_mb_emit_byte (mb, CEE_STIND_I);
4841 /* Call CleanUpManagedData */
4842 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4844 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4846 mono_mb_emit_ldloc (mb, conv_arg);
4847 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_managed);
4849 mono_mb_patch_branch (mb, pos2);
4850 break;
4852 default:
4853 g_assert_not_reached ();
4855 return conv_arg;
4856 #endif
4860 static int
4861 emit_marshal_asany (EmitMarshalContext *m, int argnum, MonoType *t,
4862 MonoMarshalSpec *spec,
4863 int conv_arg, MonoType **conv_arg_type,
4864 MarshalAction action)
4866 #ifndef DISABLE_JIT
4867 MonoMethodBuilder *mb = m->mb;
4869 switch (action) {
4870 case MARSHAL_ACTION_CONV_IN: {
4871 MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, NULL);
4873 g_assert (t->type == MONO_TYPE_OBJECT);
4874 g_assert (!t->byref);
4876 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
4877 mono_mb_emit_ldarg (mb, argnum);
4878 mono_mb_emit_icon (mb, encoding);
4879 mono_mb_emit_icon (mb, t->attrs);
4880 mono_mb_emit_icall (mb, mono_marshal_asany);
4881 mono_mb_emit_stloc (mb, conv_arg);
4882 break;
4885 case MARSHAL_ACTION_PUSH:
4886 mono_mb_emit_ldloc (mb, conv_arg);
4887 break;
4889 case MARSHAL_ACTION_CONV_OUT: {
4890 MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, NULL);
4892 mono_mb_emit_ldarg (mb, argnum);
4893 mono_mb_emit_ldloc (mb, conv_arg);
4894 mono_mb_emit_icon (mb, encoding);
4895 mono_mb_emit_icon (mb, t->attrs);
4896 mono_mb_emit_icall (mb, mono_marshal_free_asany);
4897 break;
4900 default:
4901 g_assert_not_reached ();
4903 #endif
4904 return conv_arg;
4907 static int
4908 emit_marshal_vtype (EmitMarshalContext *m, int argnum, MonoType *t,
4909 MonoMarshalSpec *spec,
4910 int conv_arg, MonoType **conv_arg_type,
4911 MarshalAction action)
4913 #ifndef DISABLE_JIT
4914 MonoMethodBuilder *mb = m->mb;
4915 MonoClass *klass, *date_time_class;
4916 int pos = 0, pos2;
4918 klass = mono_class_from_mono_type (t);
4920 date_time_class = mono_class_get_date_time_class ();
4922 switch (action) {
4923 case MARSHAL_ACTION_CONV_IN:
4924 if (klass == date_time_class) {
4925 /* Convert it to an OLE DATE type */
4926 static MonoMethod *to_oadate;
4928 if (!to_oadate)
4929 to_oadate = mono_class_get_method_from_name (date_time_class, "ToOADate", 0);
4930 g_assert (to_oadate);
4932 conv_arg = mono_mb_add_local (mb, &mono_defaults.double_class->byval_arg);
4934 if (t->byref) {
4935 mono_mb_emit_ldarg (mb, argnum);
4936 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
4939 if (!(t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && (t->attrs & PARAM_ATTRIBUTE_OUT))) {
4940 if (!t->byref)
4941 m->csig->params [argnum - m->csig->hasthis] = &mono_defaults.double_class->byval_arg;
4943 mono_mb_emit_ldarg_addr (mb, argnum);
4944 mono_mb_emit_managed_call (mb, to_oadate, NULL);
4945 mono_mb_emit_stloc (mb, conv_arg);
4948 if (t->byref)
4949 mono_mb_patch_branch (mb, pos);
4950 break;
4953 if (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype)
4954 break;
4956 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
4958 /* store the address of the source into local variable 0 */
4959 if (t->byref)
4960 mono_mb_emit_ldarg (mb, argnum);
4961 else
4962 mono_mb_emit_ldarg_addr (mb, argnum);
4964 mono_mb_emit_stloc (mb, 0);
4966 /* allocate space for the native struct and
4967 * store the address into local variable 1 (dest) */
4968 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
4969 mono_mb_emit_byte (mb, CEE_PREFIX1);
4970 mono_mb_emit_byte (mb, CEE_LOCALLOC);
4971 mono_mb_emit_stloc (mb, conv_arg);
4973 if (t->byref) {
4974 mono_mb_emit_ldloc (mb, 0);
4975 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
4978 if (!(t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && (t->attrs & PARAM_ATTRIBUTE_OUT))) {
4979 /* set dst_ptr */
4980 mono_mb_emit_ldloc (mb, conv_arg);
4981 mono_mb_emit_stloc (mb, 1);
4983 /* emit valuetype conversion code */
4984 emit_struct_conv (mb, klass, FALSE);
4987 if (t->byref)
4988 mono_mb_patch_branch (mb, pos);
4989 break;
4991 case MARSHAL_ACTION_PUSH:
4992 if (spec && spec->native == MONO_NATIVE_LPSTRUCT) {
4993 /* FIXME: */
4994 g_assert (!t->byref);
4996 /* Have to change the signature since the vtype is passed byref */
4997 m->csig->params [argnum - m->csig->hasthis] = &mono_defaults.int_class->byval_arg;
4999 if (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype)
5000 mono_mb_emit_ldarg_addr (mb, argnum);
5001 else
5002 mono_mb_emit_ldloc (mb, conv_arg);
5003 break;
5006 if (klass == date_time_class) {
5007 if (t->byref)
5008 mono_mb_emit_ldloc_addr (mb, conv_arg);
5009 else
5010 mono_mb_emit_ldloc (mb, conv_arg);
5011 break;
5014 if (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype) {
5015 mono_mb_emit_ldarg (mb, argnum);
5016 break;
5018 mono_mb_emit_ldloc (mb, conv_arg);
5019 if (!t->byref) {
5020 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5021 mono_mb_emit_op (mb, CEE_MONO_LDNATIVEOBJ, klass);
5023 break;
5025 case MARSHAL_ACTION_CONV_OUT:
5026 if (klass == date_time_class) {
5027 /* Convert from an OLE DATE type */
5028 static MonoMethod *from_oadate;
5030 if (!t->byref)
5031 break;
5033 if (!((t->attrs & PARAM_ATTRIBUTE_IN) && !(t->attrs & PARAM_ATTRIBUTE_OUT))) {
5034 if (!from_oadate)
5035 from_oadate = mono_class_get_method_from_name (date_time_class, "FromOADate", 1);
5036 g_assert (from_oadate);
5038 mono_mb_emit_ldarg (mb, argnum);
5039 mono_mb_emit_ldloc (mb, conv_arg);
5040 mono_mb_emit_managed_call (mb, from_oadate, NULL);
5041 mono_mb_emit_op (mb, CEE_STOBJ, date_time_class);
5043 break;
5046 if (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype)
5047 break;
5049 if (t->byref) {
5050 /* dst = argument */
5051 mono_mb_emit_ldarg (mb, argnum);
5052 mono_mb_emit_stloc (mb, 1);
5054 mono_mb_emit_ldloc (mb, 1);
5055 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5057 if (!((t->attrs & PARAM_ATTRIBUTE_IN) && !(t->attrs & PARAM_ATTRIBUTE_OUT))) {
5058 /* src = tmp_locals [i] */
5059 mono_mb_emit_ldloc (mb, conv_arg);
5060 mono_mb_emit_stloc (mb, 0);
5062 /* emit valuetype conversion code */
5063 emit_struct_conv (mb, klass, TRUE);
5067 emit_struct_free (mb, klass, conv_arg);
5069 if (t->byref)
5070 mono_mb_patch_branch (mb, pos);
5071 break;
5073 case MARSHAL_ACTION_CONV_RESULT:
5074 if (mono_class_is_explicit_layout (klass) || klass->blittable) {
5075 mono_mb_emit_stloc (mb, 3);
5076 break;
5079 /* load pointer to returned value type */
5080 g_assert (m->vtaddr_var);
5081 mono_mb_emit_ldloc (mb, m->vtaddr_var);
5082 /* store the address of the source into local variable 0 */
5083 mono_mb_emit_stloc (mb, 0);
5084 /* set dst_ptr */
5085 mono_mb_emit_ldloc_addr (mb, 3);
5086 mono_mb_emit_stloc (mb, 1);
5088 /* emit valuetype conversion code */
5089 emit_struct_conv (mb, klass, TRUE);
5090 break;
5092 case MARSHAL_ACTION_MANAGED_CONV_IN:
5093 if (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype) {
5094 conv_arg = 0;
5095 break;
5098 conv_arg = mono_mb_add_local (mb, &klass->byval_arg);
5100 if (t->attrs & PARAM_ATTRIBUTE_OUT)
5101 break;
5103 if (t->byref)
5104 mono_mb_emit_ldarg (mb, argnum);
5105 else
5106 mono_mb_emit_ldarg_addr (mb, argnum);
5107 mono_mb_emit_stloc (mb, 0);
5109 if (t->byref) {
5110 mono_mb_emit_ldloc (mb, 0);
5111 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5114 mono_mb_emit_ldloc_addr (mb, conv_arg);
5115 mono_mb_emit_stloc (mb, 1);
5117 /* emit valuetype conversion code */
5118 emit_struct_conv (mb, klass, TRUE);
5120 if (t->byref)
5121 mono_mb_patch_branch (mb, pos);
5122 break;
5124 case MARSHAL_ACTION_MANAGED_CONV_OUT:
5125 if (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype)
5126 break;
5127 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_IN) && !(t->attrs & PARAM_ATTRIBUTE_OUT))
5128 break;
5130 /* Check for null */
5131 mono_mb_emit_ldarg (mb, argnum);
5132 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
5134 /* Set src */
5135 mono_mb_emit_ldloc_addr (mb, conv_arg);
5136 mono_mb_emit_stloc (mb, 0);
5138 /* Set dest */
5139 mono_mb_emit_ldarg (mb, argnum);
5140 mono_mb_emit_stloc (mb, 1);
5142 /* emit valuetype conversion code */
5143 emit_struct_conv (mb, klass, FALSE);
5145 mono_mb_patch_branch (mb, pos2);
5146 break;
5148 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5149 if (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype) {
5150 mono_mb_emit_stloc (mb, 3);
5151 m->retobj_var = 0;
5152 break;
5155 /* load pointer to returned value type */
5156 g_assert (m->vtaddr_var);
5157 mono_mb_emit_ldloc (mb, m->vtaddr_var);
5159 /* store the address of the source into local variable 0 */
5160 mono_mb_emit_stloc (mb, 0);
5161 /* allocate space for the native struct and
5162 * store the address into dst_ptr */
5163 m->retobj_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5164 m->retobj_class = klass;
5165 g_assert (m->retobj_var);
5166 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
5167 mono_mb_emit_byte (mb, CEE_CONV_I);
5168 mono_mb_emit_icall (mb, ves_icall_marshal_alloc);
5169 mono_mb_emit_stloc (mb, 1);
5170 mono_mb_emit_ldloc (mb, 1);
5171 mono_mb_emit_stloc (mb, m->retobj_var);
5173 /* emit valuetype conversion code */
5174 emit_struct_conv (mb, klass, FALSE);
5175 break;
5177 default:
5178 g_assert_not_reached ();
5180 #endif
5181 return conv_arg;
5184 static int
5185 emit_marshal_string (EmitMarshalContext *m, int argnum, MonoType *t,
5186 MonoMarshalSpec *spec,
5187 int conv_arg, MonoType **conv_arg_type,
5188 MarshalAction action)
5190 #ifdef DISABLE_JIT
5191 switch (action) {
5192 case MARSHAL_ACTION_CONV_IN:
5193 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5194 break;
5195 case MARSHAL_ACTION_MANAGED_CONV_IN:
5196 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5197 break;
5199 #else
5200 MonoMethodBuilder *mb = m->mb;
5201 MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
5202 MonoMarshalConv conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
5203 gboolean need_free;
5205 switch (action) {
5206 case MARSHAL_ACTION_CONV_IN:
5207 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5208 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5210 if (t->byref) {
5211 if (t->attrs & PARAM_ATTRIBUTE_OUT)
5212 break;
5214 mono_mb_emit_ldarg (mb, argnum);
5215 mono_mb_emit_byte (mb, CEE_LDIND_I);
5216 } else {
5217 mono_mb_emit_ldarg (mb, argnum);
5220 if (conv == MONO_MARSHAL_CONV_INVALID) {
5221 char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
5222 mono_mb_emit_exception_marshal_directive (mb, msg);
5223 } else {
5224 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
5226 mono_mb_emit_stloc (mb, conv_arg);
5228 break;
5230 case MARSHAL_ACTION_CONV_OUT:
5231 conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
5232 if (conv == MONO_MARSHAL_CONV_INVALID) {
5233 char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
5234 mono_mb_emit_exception_marshal_directive (mb, msg);
5235 break;
5238 if (encoding == MONO_NATIVE_VBBYREFSTR) {
5239 static MonoMethod *m;
5241 if (!m) {
5242 m = mono_class_get_method_from_name_flags (mono_defaults.string_class, "get_Length", -1, 0);
5243 g_assert (m);
5246 if (!t->byref) {
5247 char *msg = g_strdup_printf ("VBByRefStr marshalling requires a ref parameter.", encoding);
5248 mono_mb_emit_exception_marshal_directive (mb, msg);
5249 break;
5253 * Have to allocate a new string with the same length as the original, and
5254 * copy the contents of the buffer pointed to by CONV_ARG into it.
5256 g_assert (t->byref);
5257 mono_mb_emit_ldarg (mb, argnum);
5258 mono_mb_emit_ldloc (mb, conv_arg);
5259 mono_mb_emit_ldarg (mb, argnum);
5260 mono_mb_emit_byte (mb, CEE_LDIND_I);
5261 mono_mb_emit_managed_call (mb, m, NULL);
5262 mono_mb_emit_icall (mb, mono_string_new_len_wrapper);
5263 mono_mb_emit_byte (mb, CEE_STIND_REF);
5264 } else if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT || !(t->attrs & PARAM_ATTRIBUTE_IN))) {
5265 int stind_op;
5266 mono_mb_emit_ldarg (mb, argnum);
5267 mono_mb_emit_ldloc (mb, conv_arg);
5268 mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
5269 mono_mb_emit_byte (mb, stind_op);
5270 need_free = TRUE;
5273 if (need_free) {
5274 mono_mb_emit_ldloc (mb, conv_arg);
5275 if (conv == MONO_MARSHAL_CONV_BSTR_STR)
5276 mono_mb_emit_icall (mb, mono_free_bstr);
5277 else
5278 mono_mb_emit_icall (mb, mono_marshal_free);
5280 break;
5282 case MARSHAL_ACTION_PUSH:
5283 if (t->byref && encoding != MONO_NATIVE_VBBYREFSTR)
5284 mono_mb_emit_ldloc_addr (mb, conv_arg);
5285 else
5286 mono_mb_emit_ldloc (mb, conv_arg);
5287 break;
5289 case MARSHAL_ACTION_CONV_RESULT:
5290 mono_mb_emit_stloc (mb, 0);
5292 conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
5293 if (conv == MONO_MARSHAL_CONV_INVALID) {
5294 char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
5295 mono_mb_emit_exception_marshal_directive (mb, msg);
5296 break;
5299 mono_mb_emit_ldloc (mb, 0);
5300 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
5301 mono_mb_emit_stloc (mb, 3);
5303 /* free the string */
5304 mono_mb_emit_ldloc (mb, 0);
5305 if (conv == MONO_MARSHAL_CONV_BSTR_STR)
5306 mono_mb_emit_icall (mb, mono_free_bstr);
5307 else
5308 mono_mb_emit_icall (mb, mono_marshal_free);
5309 break;
5311 case MARSHAL_ACTION_MANAGED_CONV_IN:
5312 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
5314 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5316 if (t->byref) {
5317 if (t->attrs & PARAM_ATTRIBUTE_OUT)
5318 break;
5321 conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
5322 if (conv == MONO_MARSHAL_CONV_INVALID) {
5323 char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
5324 mono_mb_emit_exception_marshal_directive (mb, msg);
5325 break;
5328 mono_mb_emit_ldarg (mb, argnum);
5329 if (t->byref)
5330 mono_mb_emit_byte (mb, CEE_LDIND_I);
5331 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
5332 mono_mb_emit_stloc (mb, conv_arg);
5333 break;
5335 case MARSHAL_ACTION_MANAGED_CONV_OUT:
5336 if (t->byref) {
5337 if (conv_arg) {
5338 int stind_op;
5339 mono_mb_emit_ldarg (mb, argnum);
5340 mono_mb_emit_ldloc (mb, conv_arg);
5341 mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
5342 mono_mb_emit_byte (mb, stind_op);
5345 break;
5347 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5348 if (conv_to_icall (conv, NULL) == mono_marshal_string_to_utf16)
5349 /* We need to make a copy so the caller is able to free it */
5350 mono_mb_emit_icall (mb, mono_marshal_string_to_utf16_copy);
5351 else
5352 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
5353 mono_mb_emit_stloc (mb, 3);
5354 break;
5356 default:
5357 g_assert_not_reached ();
5359 #endif
5360 return conv_arg;
5364 static int
5365 emit_marshal_safehandle (EmitMarshalContext *m, int argnum, MonoType *t,
5366 MonoMarshalSpec *spec, int conv_arg,
5367 MonoType **conv_arg_type, MarshalAction action)
5369 #ifdef DISABLE_JIT
5370 if (action == MARSHAL_ACTION_CONV_IN)
5371 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5372 #else
5373 MonoMethodBuilder *mb = m->mb;
5375 switch (action){
5376 case MARSHAL_ACTION_CONV_IN: {
5377 MonoType *intptr_type;
5378 int dar_release_slot, pos;
5380 intptr_type = &mono_defaults.int_class->byval_arg;
5381 conv_arg = mono_mb_add_local (mb, intptr_type);
5382 *conv_arg_type = intptr_type;
5384 if (!sh_dangerous_add_ref)
5385 init_safe_handle ();
5387 mono_mb_emit_ldarg (mb, argnum);
5388 pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
5389 mono_mb_emit_exception (mb, "ArgumentNullException", NULL);
5391 mono_mb_patch_branch (mb, pos);
5392 if (t->byref){
5394 * My tests in show that ref SafeHandles are not really
5395 * passed as ref objects. Instead a NULL is passed as the
5396 * value of the ref
5398 mono_mb_emit_icon (mb, 0);
5399 mono_mb_emit_stloc (mb, conv_arg);
5400 break;
5403 /* Create local to hold the ref parameter to DangerousAddRef */
5404 dar_release_slot = mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
5406 /* set release = false; */
5407 mono_mb_emit_icon (mb, 0);
5408 mono_mb_emit_stloc (mb, dar_release_slot);
5410 /* safehandle.DangerousAddRef (ref release) */
5411 mono_mb_emit_ldarg (mb, argnum);
5412 mono_mb_emit_ldloc_addr (mb, dar_release_slot);
5413 mono_mb_emit_managed_call (mb, sh_dangerous_add_ref, NULL);
5415 /* Pull the handle field from SafeHandle */
5416 mono_mb_emit_ldarg (mb, argnum);
5417 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoSafeHandle, handle));
5418 mono_mb_emit_byte (mb, CEE_LDIND_I);
5419 mono_mb_emit_stloc (mb, conv_arg);
5421 break;
5424 case MARSHAL_ACTION_PUSH:
5425 if (t->byref)
5426 mono_mb_emit_ldloc_addr (mb, conv_arg);
5427 else
5428 mono_mb_emit_ldloc (mb, conv_arg);
5429 break;
5431 case MARSHAL_ACTION_CONV_OUT: {
5432 /* The slot for the boolean is the next temporary created after conv_arg, see the CONV_IN code */
5433 int dar_release_slot = conv_arg + 1;
5434 int label_next;
5436 if (!sh_dangerous_release)
5437 init_safe_handle ();
5439 if (t->byref){
5440 MonoMethod *ctor;
5443 * My tests indicate that ref SafeHandles parameters are not actually
5444 * passed by ref, but instead a new Handle is created regardless of
5445 * whether a change happens in the unmanaged side.
5447 * Also, the Handle is created before calling into unmanaged code,
5448 * but we do not support that mechanism (getting to the original
5449 * handle) and it makes no difference where we create this
5451 ctor = mono_class_get_method_from_name (t->data.klass, ".ctor", 0);
5452 if (ctor == NULL){
5453 mono_mb_emit_exception (mb, "MissingMethodException", "paramterless constructor required");
5454 break;
5456 /* refval = new SafeHandleDerived ()*/
5457 mono_mb_emit_ldarg (mb, argnum);
5458 mono_mb_emit_op (mb, CEE_NEWOBJ, ctor);
5459 mono_mb_emit_byte (mb, CEE_STIND_REF);
5461 /* refval.handle = returned_handle */
5462 mono_mb_emit_ldarg (mb, argnum);
5463 mono_mb_emit_byte (mb, CEE_LDIND_REF);
5464 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoSafeHandle, handle));
5465 mono_mb_emit_ldloc (mb, conv_arg);
5466 mono_mb_emit_byte (mb, CEE_STIND_I);
5467 } else {
5468 mono_mb_emit_ldloc (mb, dar_release_slot);
5469 label_next = mono_mb_emit_branch (mb, CEE_BRFALSE);
5470 mono_mb_emit_ldarg (mb, argnum);
5471 mono_mb_emit_managed_call (mb, sh_dangerous_release, NULL);
5472 mono_mb_patch_branch (mb, label_next);
5474 break;
5477 case MARSHAL_ACTION_CONV_RESULT: {
5478 MonoMethod *ctor = NULL;
5479 int intptr_handle_slot;
5481 if (mono_class_is_abstract (t->data.klass)) {
5482 mono_mb_emit_byte (mb, CEE_POP);
5483 mono_mb_emit_exception_marshal_directive (mb, g_strdup ("Returned SafeHandles should not be abstract"));
5484 break;
5487 ctor = mono_class_get_method_from_name (t->data.klass, ".ctor", 0);
5488 if (ctor == NULL){
5489 mono_mb_emit_byte (mb, CEE_POP);
5490 mono_mb_emit_exception (mb, "MissingMethodException", "paramterless constructor required");
5491 break;
5493 /* Store the IntPtr results into a local */
5494 intptr_handle_slot = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5495 mono_mb_emit_stloc (mb, intptr_handle_slot);
5497 /* Create return value */
5498 mono_mb_emit_op (mb, CEE_NEWOBJ, ctor);
5499 mono_mb_emit_stloc (mb, 3);
5501 /* Set the return.handle to the value, am using ldflda, not sure if thats a good idea */
5502 mono_mb_emit_ldloc (mb, 3);
5503 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoSafeHandle, handle));
5504 mono_mb_emit_ldloc (mb, intptr_handle_slot);
5505 mono_mb_emit_byte (mb, CEE_STIND_I);
5506 break;
5509 case MARSHAL_ACTION_MANAGED_CONV_IN:
5510 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_IN\n");
5511 break;
5513 case MARSHAL_ACTION_MANAGED_CONV_OUT:
5514 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_OUT\n");
5515 break;
5517 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5518 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_RESULT\n");
5519 break;
5520 default:
5521 printf ("Unhandled case for MarshalAction: %d\n", action);
5523 #endif
5524 return conv_arg;
5528 static int
5529 emit_marshal_handleref (EmitMarshalContext *m, int argnum, MonoType *t,
5530 MonoMarshalSpec *spec, int conv_arg,
5531 MonoType **conv_arg_type, MarshalAction action)
5533 #ifdef DISABLE_JIT
5534 if (action == MARSHAL_ACTION_CONV_IN)
5535 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5536 #else
5537 MonoMethodBuilder *mb = m->mb;
5539 switch (action){
5540 case MARSHAL_ACTION_CONV_IN: {
5541 MonoType *intptr_type;
5543 intptr_type = &mono_defaults.int_class->byval_arg;
5544 conv_arg = mono_mb_add_local (mb, intptr_type);
5545 *conv_arg_type = intptr_type;
5547 if (t->byref){
5548 char *msg = g_strdup ("HandleRefs can not be returned from unmanaged code (or passed by ref)");
5549 mono_mb_emit_exception_marshal_directive (mb, msg);
5550 break;
5552 mono_mb_emit_ldarg_addr (mb, argnum);
5553 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoHandleRef, handle));
5554 mono_mb_emit_byte (mb, CEE_ADD);
5555 mono_mb_emit_byte (mb, CEE_LDIND_I);
5556 mono_mb_emit_stloc (mb, conv_arg);
5557 break;
5560 case MARSHAL_ACTION_PUSH:
5561 mono_mb_emit_ldloc (mb, conv_arg);
5562 break;
5564 case MARSHAL_ACTION_CONV_OUT: {
5565 /* no resource release required */
5566 break;
5569 case MARSHAL_ACTION_CONV_RESULT: {
5570 char *msg = g_strdup ("HandleRefs can not be returned from unmanaged code (or passed by ref)");
5571 mono_mb_emit_exception_marshal_directive (mb, msg);
5572 break;
5575 case MARSHAL_ACTION_MANAGED_CONV_IN:
5576 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_IN\n");
5577 break;
5579 case MARSHAL_ACTION_MANAGED_CONV_OUT:
5580 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_OUT\n");
5581 break;
5583 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5584 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_RESULT\n");
5585 break;
5586 default:
5587 fprintf (stderr, "Unhandled case for MarshalAction: %d\n", action);
5589 #endif
5590 return conv_arg;
5594 static int
5595 emit_marshal_object (EmitMarshalContext *m, int argnum, MonoType *t,
5596 MonoMarshalSpec *spec,
5597 int conv_arg, MonoType **conv_arg_type,
5598 MarshalAction action)
5600 #ifdef DISABLE_JIT
5601 if (action == MARSHAL_ACTION_CONV_IN)
5602 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5603 #else
5604 MonoMethodBuilder *mb = m->mb;
5605 MonoClass *klass = mono_class_from_mono_type (t);
5606 int pos, pos2, loc;
5608 switch (action) {
5609 case MARSHAL_ACTION_CONV_IN:
5610 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5611 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5613 m->orig_conv_args [argnum] = 0;
5615 if (mono_class_from_mono_type (t) == mono_defaults.object_class) {
5616 char *msg = g_strdup_printf ("Marshalling of type object is not implemented");
5617 mono_mb_emit_exception_marshal_directive (mb, msg);
5618 break;
5621 if (klass->delegate) {
5622 if (t->byref) {
5623 if (!(t->attrs & PARAM_ATTRIBUTE_OUT)) {
5624 char *msg = g_strdup_printf ("Byref marshalling of delegates is not implemented.");
5625 mono_mb_emit_exception_marshal_directive (mb, msg);
5627 mono_mb_emit_byte (mb, CEE_LDNULL);
5628 mono_mb_emit_stloc (mb, conv_arg);
5629 } else {
5630 mono_mb_emit_ldarg (mb, argnum);
5631 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_DEL_FTN, NULL));
5632 mono_mb_emit_stloc (mb, conv_arg);
5634 } else if (klass == mono_defaults.stringbuilder_class) {
5635 MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
5636 MonoMarshalConv conv = mono_marshal_get_stringbuilder_to_ptr_conv (m->piinfo, spec);
5638 #if 0
5639 if (t->byref) {
5640 if (!(t->attrs & PARAM_ATTRIBUTE_OUT)) {
5641 char *msg = g_strdup_printf ("Byref marshalling of stringbuilders is not implemented.");
5642 mono_mb_emit_exception_marshal_directive (mb, msg);
5644 break;
5646 #endif
5648 if (t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && (t->attrs & PARAM_ATTRIBUTE_OUT))
5649 break;
5651 if (conv == MONO_MARSHAL_CONV_INVALID) {
5652 char *msg = g_strdup_printf ("stringbuilder marshalling conversion %d not implemented", encoding);
5653 mono_mb_emit_exception_marshal_directive (mb, msg);
5654 break;
5657 mono_mb_emit_ldarg (mb, argnum);
5658 if (t->byref)
5659 mono_mb_emit_byte (mb, CEE_LDIND_I);
5661 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
5662 mono_mb_emit_stloc (mb, conv_arg);
5663 } else if (klass->blittable) {
5664 mono_mb_emit_byte (mb, CEE_LDNULL);
5665 mono_mb_emit_stloc (mb, conv_arg);
5667 mono_mb_emit_ldarg (mb, argnum);
5668 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5670 mono_mb_emit_ldarg (mb, argnum);
5671 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5672 mono_mb_emit_stloc (mb, conv_arg);
5674 mono_mb_patch_branch (mb, pos);
5675 break;
5676 } else {
5677 mono_mb_emit_byte (mb, CEE_LDNULL);
5678 mono_mb_emit_stloc (mb, conv_arg);
5680 if (t->byref) {
5681 /* we dont need any conversions for out parameters */
5682 if (t->attrs & PARAM_ATTRIBUTE_OUT)
5683 break;
5685 mono_mb_emit_ldarg (mb, argnum);
5686 mono_mb_emit_byte (mb, CEE_LDIND_I);
5688 } else {
5689 mono_mb_emit_ldarg (mb, argnum);
5690 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5691 mono_mb_emit_byte (mb, CEE_MONO_OBJADDR);
5694 /* store the address of the source into local variable 0 */
5695 mono_mb_emit_stloc (mb, 0);
5696 mono_mb_emit_ldloc (mb, 0);
5697 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5699 /* allocate space for the native struct and store the address */
5700 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
5701 mono_mb_emit_byte (mb, CEE_PREFIX1);
5702 mono_mb_emit_byte (mb, CEE_LOCALLOC);
5703 mono_mb_emit_stloc (mb, conv_arg);
5705 if (t->byref) {
5706 /* Need to store the original buffer so we can free it later */
5707 m->orig_conv_args [argnum] = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5708 mono_mb_emit_ldloc (mb, conv_arg);
5709 mono_mb_emit_stloc (mb, m->orig_conv_args [argnum]);
5712 /* set the src_ptr */
5713 mono_mb_emit_ldloc (mb, 0);
5714 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5715 mono_mb_emit_stloc (mb, 0);
5717 /* set dst_ptr */
5718 mono_mb_emit_ldloc (mb, conv_arg);
5719 mono_mb_emit_stloc (mb, 1);
5721 /* emit valuetype conversion code */
5722 emit_struct_conv (mb, klass, FALSE);
5724 mono_mb_patch_branch (mb, pos);
5726 break;
5728 case MARSHAL_ACTION_CONV_OUT:
5729 if (klass == mono_defaults.stringbuilder_class) {
5730 gboolean need_free;
5731 MonoMarshalNative encoding;
5732 MonoMarshalConv conv;
5734 encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
5735 conv = mono_marshal_get_ptr_to_stringbuilder_conv (m->piinfo, spec, &need_free);
5737 g_assert (encoding != -1);
5739 if (t->byref) {
5740 //g_assert (!(t->attrs & PARAM_ATTRIBUTE_OUT));
5742 need_free = TRUE;
5744 mono_mb_emit_ldarg (mb, argnum);
5745 mono_mb_emit_ldloc (mb, conv_arg);
5747 switch (encoding) {
5748 case MONO_NATIVE_LPWSTR:
5749 mono_mb_emit_icall (mb, mono_string_utf16_to_builder2);
5750 break;
5751 case MONO_NATIVE_LPSTR:
5752 mono_mb_emit_icall (mb, mono_string_utf8_to_builder2);
5753 break;
5754 case MONO_NATIVE_UTF8STR:
5755 mono_mb_emit_icall (mb, mono_string_utf8_to_builder2);
5756 break;
5757 default:
5758 g_assert_not_reached ();
5761 mono_mb_emit_byte (mb, CEE_STIND_REF);
5762 } else {
5763 mono_mb_emit_ldarg (mb, argnum);
5764 mono_mb_emit_ldloc (mb, conv_arg);
5766 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
5769 if (need_free) {
5770 mono_mb_emit_ldloc (mb, conv_arg);
5771 mono_mb_emit_icall (mb, mono_marshal_free);
5773 break;
5776 if (klass->delegate) {
5777 if (t->byref) {
5778 mono_mb_emit_ldarg (mb, argnum);
5779 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5780 mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
5781 mono_mb_emit_ldloc (mb, conv_arg);
5782 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL, NULL));
5783 mono_mb_emit_byte (mb, CEE_STIND_REF);
5785 break;
5788 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT)) {
5789 /* allocate a new object */
5790 mono_mb_emit_ldarg (mb, argnum);
5791 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5792 mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, klass);
5793 mono_mb_emit_byte (mb, CEE_STIND_REF);
5796 /* dst = *argument */
5797 mono_mb_emit_ldarg (mb, argnum);
5799 if (t->byref)
5800 mono_mb_emit_byte (mb, CEE_LDIND_I);
5802 mono_mb_emit_stloc (mb, 1);
5804 mono_mb_emit_ldloc (mb, 1);
5805 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5807 if (t->byref || (t->attrs & PARAM_ATTRIBUTE_OUT)) {
5808 mono_mb_emit_ldloc (mb, 1);
5809 mono_mb_emit_icon (mb, sizeof (MonoObject));
5810 mono_mb_emit_byte (mb, CEE_ADD);
5811 mono_mb_emit_stloc (mb, 1);
5813 /* src = tmp_locals [i] */
5814 mono_mb_emit_ldloc (mb, conv_arg);
5815 mono_mb_emit_stloc (mb, 0);
5817 /* emit valuetype conversion code */
5818 emit_struct_conv (mb, klass, TRUE);
5820 /* Free the structure returned by the native code */
5821 emit_struct_free (mb, klass, conv_arg);
5823 if (m->orig_conv_args [argnum]) {
5825 * If the native function changed the pointer, then free
5826 * the original structure plus the new pointer.
5828 mono_mb_emit_ldloc (mb, m->orig_conv_args [argnum]);
5829 mono_mb_emit_ldloc (mb, conv_arg);
5830 pos2 = mono_mb_emit_branch (mb, CEE_BEQ);
5832 if (!(t->attrs & PARAM_ATTRIBUTE_OUT)) {
5833 g_assert (m->orig_conv_args [argnum]);
5835 emit_struct_free (mb, klass, m->orig_conv_args [argnum]);
5838 mono_mb_emit_ldloc (mb, conv_arg);
5839 mono_mb_emit_icall (mb, mono_marshal_free);
5841 mono_mb_patch_branch (mb, pos2);
5844 else
5845 /* Free the original structure passed to native code */
5846 emit_struct_free (mb, klass, conv_arg);
5848 mono_mb_patch_branch (mb, pos);
5849 break;
5851 case MARSHAL_ACTION_PUSH:
5852 if (t->byref)
5853 mono_mb_emit_ldloc_addr (mb, conv_arg);
5854 else
5855 mono_mb_emit_ldloc (mb, conv_arg);
5856 break;
5858 case MARSHAL_ACTION_CONV_RESULT:
5859 if (klass->delegate) {
5860 g_assert (!t->byref);
5861 mono_mb_emit_stloc (mb, 0);
5862 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5863 mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
5864 mono_mb_emit_ldloc (mb, 0);
5865 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL, NULL));
5866 mono_mb_emit_stloc (mb, 3);
5867 } else if (klass == mono_defaults.stringbuilder_class){
5868 // FIXME: implement
5869 } else {
5870 /* set src */
5871 mono_mb_emit_stloc (mb, 0);
5873 /* Make a copy since emit_conv modifies local 0 */
5874 loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5875 mono_mb_emit_ldloc (mb, 0);
5876 mono_mb_emit_stloc (mb, loc);
5878 mono_mb_emit_byte (mb, CEE_LDNULL);
5879 mono_mb_emit_stloc (mb, 3);
5881 mono_mb_emit_ldloc (mb, 0);
5882 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5884 /* allocate result object */
5886 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5887 mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, klass);
5888 mono_mb_emit_stloc (mb, 3);
5890 /* set dst */
5892 mono_mb_emit_ldloc (mb, 3);
5893 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5894 mono_mb_emit_stloc (mb, 1);
5896 /* emit conversion code */
5897 emit_struct_conv (mb, klass, TRUE);
5899 emit_struct_free (mb, klass, loc);
5901 /* Free the pointer allocated by unmanaged code */
5902 mono_mb_emit_ldloc (mb, loc);
5903 mono_mb_emit_icall (mb, mono_marshal_free);
5904 mono_mb_patch_branch (mb, pos);
5906 break;
5908 case MARSHAL_ACTION_MANAGED_CONV_IN:
5909 conv_arg = mono_mb_add_local (mb, &klass->byval_arg);
5911 if (klass->delegate) {
5912 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5913 mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
5914 mono_mb_emit_ldarg (mb, argnum);
5915 if (t->byref)
5916 mono_mb_emit_byte (mb, CEE_LDIND_I);
5917 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL, NULL));
5918 mono_mb_emit_stloc (mb, conv_arg);
5919 break;
5922 if (klass == mono_defaults.stringbuilder_class) {
5923 MonoMarshalNative encoding;
5925 encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
5927 // FIXME:
5928 g_assert (encoding == MONO_NATIVE_LPSTR || encoding == MONO_NATIVE_UTF8STR);
5930 g_assert (!t->byref);
5931 g_assert (encoding != -1);
5933 mono_mb_emit_ldarg (mb, argnum);
5934 mono_mb_emit_icall (mb, mono_string_utf8_to_builder2);
5935 mono_mb_emit_stloc (mb, conv_arg);
5936 break;
5939 /* The class can not have an automatic layout */
5940 if (mono_class_is_auto_layout (klass)) {
5941 mono_mb_emit_auto_layout_exception (mb, klass);
5942 break;
5945 if (t->attrs & PARAM_ATTRIBUTE_OUT) {
5946 mono_mb_emit_byte (mb, CEE_LDNULL);
5947 mono_mb_emit_stloc (mb, conv_arg);
5948 break;
5951 /* Set src */
5952 mono_mb_emit_ldarg (mb, argnum);
5953 if (t->byref) {
5954 int pos2;
5956 /* Check for NULL and raise an exception */
5957 pos2 = mono_mb_emit_branch (mb, CEE_BRTRUE);
5959 mono_mb_emit_exception (mb, "ArgumentNullException", NULL);
5961 mono_mb_patch_branch (mb, pos2);
5962 mono_mb_emit_ldarg (mb, argnum);
5963 mono_mb_emit_byte (mb, CEE_LDIND_I);
5966 mono_mb_emit_stloc (mb, 0);
5968 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
5969 mono_mb_emit_stloc (mb, conv_arg);
5971 mono_mb_emit_ldloc (mb, 0);
5972 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5974 /* Create and set dst */
5975 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5976 mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, klass);
5977 mono_mb_emit_stloc (mb, conv_arg);
5978 mono_mb_emit_ldloc (mb, conv_arg);
5979 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5980 mono_mb_emit_stloc (mb, 1);
5982 /* emit valuetype conversion code */
5983 emit_struct_conv (mb, klass, TRUE);
5985 mono_mb_patch_branch (mb, pos);
5986 break;
5988 case MARSHAL_ACTION_MANAGED_CONV_OUT:
5989 if (klass->delegate) {
5990 if (t->byref) {
5991 int stind_op;
5992 mono_mb_emit_ldarg (mb, argnum);
5993 mono_mb_emit_ldloc (mb, conv_arg);
5994 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_DEL_FTN, &stind_op));
5995 mono_mb_emit_byte (mb, stind_op);
5996 break;
6000 if (t->byref) {
6001 /* Check for null */
6002 mono_mb_emit_ldloc (mb, conv_arg);
6003 pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
6004 mono_mb_emit_ldarg (mb, argnum);
6005 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6006 mono_mb_emit_byte (mb, CEE_STIND_REF);
6007 pos2 = mono_mb_emit_branch (mb, CEE_BR);
6009 mono_mb_patch_branch (mb, pos);
6011 /* Set src */
6012 mono_mb_emit_ldloc (mb, conv_arg);
6013 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
6014 mono_mb_emit_stloc (mb, 0);
6016 /* Allocate and set dest */
6017 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
6018 mono_mb_emit_byte (mb, CEE_CONV_I);
6019 mono_mb_emit_icall (mb, ves_icall_marshal_alloc);
6020 mono_mb_emit_stloc (mb, 1);
6022 /* Update argument pointer */
6023 mono_mb_emit_ldarg (mb, argnum);
6024 mono_mb_emit_ldloc (mb, 1);
6025 mono_mb_emit_byte (mb, CEE_STIND_I);
6027 /* emit valuetype conversion code */
6028 emit_struct_conv (mb, klass, FALSE);
6030 mono_mb_patch_branch (mb, pos2);
6031 } else if (klass == mono_defaults.stringbuilder_class) {
6032 // FIXME: What to do here ?
6033 } else {
6034 /* byval [Out] marshalling */
6036 /* FIXME: Handle null */
6038 /* Set src */
6039 mono_mb_emit_ldloc (mb, conv_arg);
6040 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
6041 mono_mb_emit_stloc (mb, 0);
6043 /* Set dest */
6044 mono_mb_emit_ldarg (mb, argnum);
6045 mono_mb_emit_stloc (mb, 1);
6047 /* emit valuetype conversion code */
6048 emit_struct_conv (mb, klass, FALSE);
6050 break;
6052 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
6053 if (klass->delegate) {
6054 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_DEL_FTN, NULL));
6055 mono_mb_emit_stloc (mb, 3);
6056 break;
6059 /* The class can not have an automatic layout */
6060 if (mono_class_is_auto_layout (klass)) {
6061 mono_mb_emit_auto_layout_exception (mb, klass);
6062 break;
6065 mono_mb_emit_stloc (mb, 0);
6066 /* Check for null */
6067 mono_mb_emit_ldloc (mb, 0);
6068 pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
6069 mono_mb_emit_byte (mb, CEE_LDNULL);
6070 mono_mb_emit_stloc (mb, 3);
6071 pos2 = mono_mb_emit_branch (mb, CEE_BR);
6073 mono_mb_patch_branch (mb, pos);
6075 /* Set src */
6076 mono_mb_emit_ldloc (mb, 0);
6077 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
6078 mono_mb_emit_stloc (mb, 0);
6080 /* Allocate and set dest */
6081 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
6082 mono_mb_emit_byte (mb, CEE_CONV_I);
6083 mono_mb_emit_icall (mb, ves_icall_marshal_alloc);
6084 mono_mb_emit_byte (mb, CEE_DUP);
6085 mono_mb_emit_stloc (mb, 1);
6086 mono_mb_emit_stloc (mb, 3);
6088 emit_struct_conv (mb, klass, FALSE);
6090 mono_mb_patch_branch (mb, pos2);
6091 break;
6093 default:
6094 g_assert_not_reached ();
6096 #endif
6097 return conv_arg;
6100 #ifndef DISABLE_JIT
6102 #ifndef DISABLE_COM
6104 static int
6105 emit_marshal_variant (EmitMarshalContext *m, int argnum, MonoType *t,
6106 MonoMarshalSpec *spec,
6107 int conv_arg, MonoType **conv_arg_type,
6108 MarshalAction action)
6110 MonoMethodBuilder *mb = m->mb;
6111 static MonoMethod *get_object_for_native_variant = NULL;
6112 static MonoMethod *get_native_variant_for_object = NULL;
6114 if (!get_object_for_native_variant)
6115 get_object_for_native_variant = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetObjectForNativeVariant", 1);
6116 g_assert (get_object_for_native_variant);
6118 if (!get_native_variant_for_object)
6119 get_native_variant_for_object = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetNativeVariantForObject", 2);
6120 g_assert (get_native_variant_for_object);
6122 switch (action) {
6123 case MARSHAL_ACTION_CONV_IN: {
6124 conv_arg = mono_mb_add_local (mb, &mono_class_get_variant_class ()->byval_arg);
6126 if (t->byref)
6127 *conv_arg_type = &mono_class_get_variant_class ()->this_arg;
6128 else
6129 *conv_arg_type = &mono_class_get_variant_class ()->byval_arg;
6131 if (t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && t->attrs & PARAM_ATTRIBUTE_OUT)
6132 break;
6134 mono_mb_emit_ldarg (mb, argnum);
6135 if (t->byref)
6136 mono_mb_emit_byte(mb, CEE_LDIND_REF);
6137 mono_mb_emit_ldloc_addr (mb, conv_arg);
6138 mono_mb_emit_managed_call (mb, get_native_variant_for_object, NULL);
6139 break;
6142 case MARSHAL_ACTION_CONV_OUT: {
6143 static MonoMethod *variant_clear = NULL;
6145 if (!variant_clear)
6146 variant_clear = mono_class_get_method_from_name (mono_class_get_variant_class (), "Clear", 0);
6147 g_assert (variant_clear);
6150 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT || !(t->attrs & PARAM_ATTRIBUTE_IN))) {
6151 mono_mb_emit_ldarg (mb, argnum);
6152 mono_mb_emit_ldloc_addr (mb, conv_arg);
6153 mono_mb_emit_managed_call (mb, get_object_for_native_variant, NULL);
6154 mono_mb_emit_byte (mb, CEE_STIND_REF);
6157 mono_mb_emit_ldloc_addr (mb, conv_arg);
6158 mono_mb_emit_managed_call (mb, variant_clear, NULL);
6159 break;
6162 case MARSHAL_ACTION_PUSH:
6163 if (t->byref)
6164 mono_mb_emit_ldloc_addr (mb, conv_arg);
6165 else
6166 mono_mb_emit_ldloc (mb, conv_arg);
6167 break;
6169 case MARSHAL_ACTION_CONV_RESULT: {
6170 char *msg = g_strdup ("Marshalling of VARIANT not supported as a return type.");
6171 mono_mb_emit_exception_marshal_directive (mb, msg);
6172 break;
6175 case MARSHAL_ACTION_MANAGED_CONV_IN: {
6176 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6178 if (t->byref)
6179 *conv_arg_type = &mono_class_get_variant_class ()->this_arg;
6180 else
6181 *conv_arg_type = &mono_class_get_variant_class ()->byval_arg;
6183 if (t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && t->attrs & PARAM_ATTRIBUTE_OUT)
6184 break;
6186 if (t->byref)
6187 mono_mb_emit_ldarg (mb, argnum);
6188 else
6189 mono_mb_emit_ldarg_addr (mb, argnum);
6190 mono_mb_emit_managed_call (mb, get_object_for_native_variant, NULL);
6191 mono_mb_emit_stloc (mb, conv_arg);
6192 break;
6195 case MARSHAL_ACTION_MANAGED_CONV_OUT: {
6196 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT || !(t->attrs & PARAM_ATTRIBUTE_IN))) {
6197 mono_mb_emit_ldloc (mb, conv_arg);
6198 mono_mb_emit_ldarg (mb, argnum);
6199 mono_mb_emit_managed_call (mb, get_native_variant_for_object, NULL);
6201 break;
6204 case MARSHAL_ACTION_MANAGED_CONV_RESULT: {
6205 char *msg = g_strdup ("Marshalling of VARIANT not supported as a return type.");
6206 mono_mb_emit_exception_marshal_directive (mb, msg);
6207 break;
6210 default:
6211 g_assert_not_reached ();
6214 return conv_arg;
6217 #endif /* DISABLE_COM */
6218 #endif /* DISABLE_JIT */
6220 static gboolean
6221 mono_pinvoke_is_unicode (MonoMethodPInvoke *piinfo)
6223 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
6224 case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
6225 return FALSE;
6226 case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
6227 return TRUE;
6228 case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
6229 default:
6230 #ifdef TARGET_WIN32
6231 return TRUE;
6232 #else
6233 return FALSE;
6234 #endif
6239 static int
6240 emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
6241 MonoMarshalSpec *spec,
6242 int conv_arg, MonoType **conv_arg_type,
6243 MarshalAction action)
6245 #ifdef DISABLE_JIT
6246 switch (action) {
6247 case MARSHAL_ACTION_CONV_IN:
6248 *conv_arg_type = &mono_defaults.object_class->byval_arg;
6249 break;
6250 case MARSHAL_ACTION_MANAGED_CONV_IN:
6251 *conv_arg_type = &mono_defaults.int_class->byval_arg;
6252 break;
6254 #else
6255 MonoMethodBuilder *mb = m->mb;
6256 MonoClass *klass = mono_class_from_mono_type (t);
6257 gboolean need_convert, need_free;
6258 MonoMarshalNative encoding;
6260 encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
6262 switch (action) {
6263 case MARSHAL_ACTION_CONV_IN:
6264 *conv_arg_type = &mono_defaults.object_class->byval_arg;
6265 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6267 if (klass->element_class->blittable) {
6268 mono_mb_emit_ldarg (mb, argnum);
6269 if (t->byref)
6270 mono_mb_emit_byte (mb, CEE_LDIND_I);
6271 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_ARRAY_LPARRAY, NULL));
6272 mono_mb_emit_stloc (mb, conv_arg);
6273 } else {
6274 MonoClass *eklass;
6275 guint32 label1, label2, label3;
6276 int index_var, src_var, dest_ptr, esize;
6277 MonoMarshalConv conv;
6278 gboolean is_string = FALSE;
6280 dest_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6282 eklass = klass->element_class;
6284 if (eklass == mono_defaults.string_class) {
6285 is_string = TRUE;
6286 conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
6288 else if (eklass == mono_defaults.stringbuilder_class) {
6289 is_string = TRUE;
6290 conv = mono_marshal_get_stringbuilder_to_ptr_conv (m->piinfo, spec);
6292 else
6293 conv = MONO_MARSHAL_CONV_INVALID;
6295 if (is_string && conv == MONO_MARSHAL_CONV_INVALID) {
6296 char *msg = g_strdup_printf ("string/stringbuilder marshalling conversion %d not implemented", encoding);
6297 mono_mb_emit_exception_marshal_directive (mb, msg);
6298 break;
6301 src_var = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6302 mono_mb_emit_ldarg (mb, argnum);
6303 if (t->byref)
6304 mono_mb_emit_byte (mb, CEE_LDIND_I);
6305 mono_mb_emit_stloc (mb, src_var);
6307 /* Check null */
6308 mono_mb_emit_ldloc (mb, src_var);
6309 mono_mb_emit_stloc (mb, conv_arg);
6310 mono_mb_emit_ldloc (mb, src_var);
6311 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6313 if (is_string)
6314 esize = sizeof (gpointer);
6315 else if (eklass == mono_defaults.char_class) /*can't call mono_marshal_type_size since it causes all sorts of asserts*/
6316 esize = mono_pinvoke_is_unicode (m->piinfo) ? 2 : 1;
6317 else
6318 esize = mono_class_native_size (eklass, NULL);
6320 /* allocate space for the native struct and store the address */
6321 mono_mb_emit_icon (mb, esize);
6322 mono_mb_emit_ldloc (mb, src_var);
6323 mono_mb_emit_byte (mb, CEE_LDLEN);
6325 if (eklass == mono_defaults.string_class) {
6326 /* Make the array bigger for the terminating null */
6327 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
6328 mono_mb_emit_byte (mb, CEE_ADD);
6330 mono_mb_emit_byte (mb, CEE_MUL);
6331 mono_mb_emit_byte (mb, CEE_PREFIX1);
6332 mono_mb_emit_byte (mb, CEE_LOCALLOC);
6333 mono_mb_emit_stloc (mb, conv_arg);
6335 mono_mb_emit_ldloc (mb, conv_arg);
6336 mono_mb_emit_stloc (mb, dest_ptr);
6338 /* Emit marshalling loop */
6339 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6340 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6341 mono_mb_emit_stloc (mb, index_var);
6342 label2 = mono_mb_get_label (mb);
6343 mono_mb_emit_ldloc (mb, index_var);
6344 mono_mb_emit_ldloc (mb, src_var);
6345 mono_mb_emit_byte (mb, CEE_LDLEN);
6346 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6348 /* Emit marshalling code */
6350 if (is_string) {
6351 int stind_op;
6352 mono_mb_emit_ldloc (mb, dest_ptr);
6353 mono_mb_emit_ldloc (mb, src_var);
6354 mono_mb_emit_ldloc (mb, index_var);
6355 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
6356 mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
6357 mono_mb_emit_byte (mb, stind_op);
6358 } else {
6359 /* set the src_ptr */
6360 mono_mb_emit_ldloc (mb, src_var);
6361 mono_mb_emit_ldloc (mb, index_var);
6362 mono_mb_emit_op (mb, CEE_LDELEMA, eklass);
6363 mono_mb_emit_stloc (mb, 0);
6365 /* set dst_ptr */
6366 mono_mb_emit_ldloc (mb, dest_ptr);
6367 mono_mb_emit_stloc (mb, 1);
6369 /* emit valuetype conversion code */
6370 emit_struct_conv_full (mb, eklass, FALSE, 0, eklass == mono_defaults.char_class ? encoding : (MonoMarshalNative)-1);
6373 mono_mb_emit_add_to_local (mb, index_var, 1);
6374 mono_mb_emit_add_to_local (mb, dest_ptr, esize);
6376 mono_mb_emit_branch_label (mb, CEE_BR, label2);
6378 mono_mb_patch_branch (mb, label3);
6380 if (eklass == mono_defaults.string_class) {
6381 /* Null terminate */
6382 mono_mb_emit_ldloc (mb, dest_ptr);
6383 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6384 mono_mb_emit_byte (mb, CEE_STIND_REF);
6387 mono_mb_patch_branch (mb, label1);
6390 break;
6392 case MARSHAL_ACTION_CONV_OUT:
6393 /* Unicode character arrays are implicitly marshalled as [Out] under MS.NET */
6394 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);
6395 need_free = mono_marshal_need_free (&klass->element_class->byval_arg,
6396 m->piinfo, spec);
6398 if ((t->attrs & PARAM_ATTRIBUTE_OUT) && spec && spec->native == MONO_NATIVE_LPARRAY && spec->data.array_data.param_num != -1) {
6399 int param_num = spec->data.array_data.param_num;
6400 MonoType *param_type;
6402 param_type = m->sig->params [param_num];
6404 if (param_type->byref && param_type->type != MONO_TYPE_I4) {
6405 char *msg = g_strdup ("Not implemented.");
6406 mono_mb_emit_exception_marshal_directive (mb, msg);
6407 break;
6410 if (t->byref ) {
6411 mono_mb_emit_ldarg (mb, argnum);
6413 /* Create the managed array */
6414 mono_mb_emit_ldarg (mb, param_num);
6415 if (m->sig->params [param_num]->byref)
6416 // FIXME: Support other types
6417 mono_mb_emit_byte (mb, CEE_LDIND_I4);
6418 mono_mb_emit_byte (mb, CEE_CONV_OVF_I);
6419 mono_mb_emit_op (mb, CEE_NEWARR, klass->element_class);
6420 /* Store into argument */
6421 mono_mb_emit_byte (mb, CEE_STIND_REF);
6425 if (need_convert || need_free) {
6426 /* FIXME: Optimize blittable case */
6427 MonoClass *eklass;
6428 guint32 label1, label2, label3;
6429 int index_var, src_ptr, loc, esize;
6431 eklass = klass->element_class;
6432 if ((eklass == mono_defaults.stringbuilder_class) || (eklass == mono_defaults.string_class))
6433 esize = sizeof (gpointer);
6434 else if (eklass == mono_defaults.char_class)
6435 esize = mono_pinvoke_is_unicode (m->piinfo) ? 2 : 1;
6436 else
6437 esize = mono_class_native_size (eklass, NULL);
6438 src_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6439 loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6441 /* Check null */
6442 mono_mb_emit_ldarg (mb, argnum);
6443 if (t->byref)
6444 mono_mb_emit_byte (mb, CEE_LDIND_I);
6445 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6447 mono_mb_emit_ldloc (mb, conv_arg);
6448 mono_mb_emit_stloc (mb, src_ptr);
6450 /* Emit marshalling loop */
6451 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6452 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6453 mono_mb_emit_stloc (mb, index_var);
6454 label2 = mono_mb_get_label (mb);
6455 mono_mb_emit_ldloc (mb, index_var);
6456 mono_mb_emit_ldarg (mb, argnum);
6457 if (t->byref)
6458 mono_mb_emit_byte (mb, CEE_LDIND_REF);
6459 mono_mb_emit_byte (mb, CEE_LDLEN);
6460 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6462 /* Emit marshalling code */
6464 if (eklass == mono_defaults.stringbuilder_class) {
6465 gboolean need_free2;
6466 MonoMarshalConv conv = mono_marshal_get_ptr_to_stringbuilder_conv (m->piinfo, spec, &need_free2);
6468 g_assert (conv != MONO_MARSHAL_CONV_INVALID);
6470 /* dest */
6471 mono_mb_emit_ldarg (mb, argnum);
6472 if (t->byref)
6473 mono_mb_emit_byte (mb, CEE_LDIND_I);
6474 mono_mb_emit_ldloc (mb, index_var);
6475 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
6477 /* src */
6478 mono_mb_emit_ldloc (mb, src_ptr);
6479 mono_mb_emit_byte (mb, CEE_LDIND_I);
6481 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
6483 if (need_free) {
6484 /* src */
6485 mono_mb_emit_ldloc (mb, src_ptr);
6486 mono_mb_emit_byte (mb, CEE_LDIND_I);
6488 mono_mb_emit_icall (mb, mono_marshal_free);
6491 else if (eklass == mono_defaults.string_class) {
6492 if (need_free) {
6493 /* src */
6494 mono_mb_emit_ldloc (mb, src_ptr);
6495 mono_mb_emit_byte (mb, CEE_LDIND_I);
6497 mono_mb_emit_icall (mb, mono_marshal_free);
6500 else {
6501 if (need_convert) {
6502 /* set the src_ptr */
6503 mono_mb_emit_ldloc (mb, src_ptr);
6504 mono_mb_emit_stloc (mb, 0);
6506 /* set dst_ptr */
6507 mono_mb_emit_ldarg (mb, argnum);
6508 if (t->byref)
6509 mono_mb_emit_byte (mb, CEE_LDIND_REF);
6510 mono_mb_emit_ldloc (mb, index_var);
6511 mono_mb_emit_op (mb, CEE_LDELEMA, eklass);
6512 mono_mb_emit_stloc (mb, 1);
6514 /* emit valuetype conversion code */
6515 emit_struct_conv_full (mb, eklass, TRUE, 0, eklass == mono_defaults.char_class ? encoding : (MonoMarshalNative)-1);
6518 if (need_free) {
6519 mono_mb_emit_ldloc (mb, src_ptr);
6520 mono_mb_emit_stloc (mb, loc);
6521 mono_mb_emit_ldloc (mb, loc);
6523 emit_struct_free (mb, eklass, loc);
6527 mono_mb_emit_add_to_local (mb, index_var, 1);
6528 mono_mb_emit_add_to_local (mb, src_ptr, esize);
6530 mono_mb_emit_branch_label (mb, CEE_BR, label2);
6532 mono_mb_patch_branch (mb, label1);
6533 mono_mb_patch_branch (mb, label3);
6536 if (klass->element_class->blittable) {
6537 /* free memory allocated (if any) by MONO_MARSHAL_CONV_ARRAY_LPARRAY */
6539 mono_mb_emit_ldarg (mb, argnum);
6540 if (t->byref)
6541 mono_mb_emit_byte (mb, CEE_LDIND_REF);
6542 mono_mb_emit_ldloc (mb, conv_arg);
6543 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_FREE_LPARRAY, NULL));
6546 break;
6548 case MARSHAL_ACTION_PUSH:
6549 if (t->byref)
6550 mono_mb_emit_ldloc_addr (mb, conv_arg);
6551 else
6552 mono_mb_emit_ldloc (mb, conv_arg);
6553 break;
6555 case MARSHAL_ACTION_CONV_RESULT:
6556 /* fixme: we need conversions here */
6557 mono_mb_emit_stloc (mb, 3);
6558 break;
6560 case MARSHAL_ACTION_MANAGED_CONV_IN: {
6561 MonoClass *eklass;
6562 guint32 label1, label2, label3;
6563 int index_var, src_ptr, esize, param_num, num_elem;
6564 MonoMarshalConv conv;
6565 gboolean is_string = FALSE;
6567 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6568 *conv_arg_type = &mono_defaults.int_class->byval_arg;
6570 if (t->byref) {
6571 char *msg = g_strdup ("Byref array marshalling to managed code is not implemented.");
6572 mono_mb_emit_exception_marshal_directive (mb, msg);
6573 return conv_arg;
6575 if (!spec) {
6576 char *msg = g_strdup ("[MarshalAs] attribute required to marshal arrays to managed code.");
6577 mono_mb_emit_exception_marshal_directive (mb, msg);
6578 return conv_arg;
6580 if (spec->native != MONO_NATIVE_LPARRAY) {
6581 char *msg = g_strdup ("Non LPArray marshalling of arrays to managed code is not implemented.");
6582 mono_mb_emit_exception_marshal_directive (mb, msg);
6583 return conv_arg;
6586 /* FIXME: t is from the method which is wrapped, not the delegate type */
6587 /* g_assert (t->attrs & PARAM_ATTRIBUTE_IN); */
6589 param_num = spec->data.array_data.param_num;
6590 num_elem = spec->data.array_data.num_elem;
6591 if (spec->data.array_data.elem_mult == 0)
6592 /* param_num is not specified */
6593 param_num = -1;
6595 if (param_num == -1) {
6596 if (num_elem <= 0) {
6597 char *msg = g_strdup ("Either SizeConst or SizeParamIndex should be specified when marshalling arrays to managed code.");
6598 mono_mb_emit_exception_marshal_directive (mb, msg);
6599 return conv_arg;
6603 /* FIXME: Optimize blittable case */
6605 eklass = klass->element_class;
6606 if (eklass == mono_defaults.string_class) {
6607 is_string = TRUE;
6608 conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
6610 else if (eklass == mono_defaults.stringbuilder_class) {
6611 is_string = TRUE;
6612 conv = mono_marshal_get_ptr_to_stringbuilder_conv (m->piinfo, spec, &need_free);
6614 else
6615 conv = MONO_MARSHAL_CONV_INVALID;
6617 mono_marshal_load_type_info (eklass);
6619 if (is_string)
6620 esize = sizeof (gpointer);
6621 else
6622 esize = mono_class_native_size (eklass, NULL);
6623 src_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6625 mono_mb_emit_byte (mb, CEE_LDNULL);
6626 mono_mb_emit_stloc (mb, conv_arg);
6628 /* Check param index */
6629 if (param_num != -1) {
6630 if (param_num >= m->sig->param_count) {
6631 char *msg = g_strdup ("Array size control parameter index is out of range.");
6632 mono_mb_emit_exception_marshal_directive (mb, msg);
6633 return conv_arg;
6635 switch (m->sig->params [param_num]->type) {
6636 case MONO_TYPE_I1:
6637 case MONO_TYPE_U1:
6638 case MONO_TYPE_I2:
6639 case MONO_TYPE_U2:
6640 case MONO_TYPE_I4:
6641 case MONO_TYPE_U4:
6642 case MONO_TYPE_I:
6643 case MONO_TYPE_U:
6644 case MONO_TYPE_I8:
6645 case MONO_TYPE_U8:
6646 break;
6647 default: {
6648 char *msg = g_strdup ("Array size control parameter must be an integral type.");
6649 mono_mb_emit_exception_marshal_directive (mb, msg);
6650 return conv_arg;
6655 /* Check null */
6656 mono_mb_emit_ldarg (mb, argnum);
6657 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6659 mono_mb_emit_ldarg (mb, argnum);
6660 mono_mb_emit_stloc (mb, src_ptr);
6662 /* Create managed array */
6664 * The LPArray marshalling spec says that sometimes param_num starts
6665 * from 1, sometimes it starts from 0. But MS seems to allways start
6666 * from 0.
6669 if (param_num == -1) {
6670 mono_mb_emit_icon (mb, num_elem);
6671 } else {
6672 mono_mb_emit_ldarg (mb, param_num);
6673 if (num_elem > 0) {
6674 mono_mb_emit_icon (mb, num_elem);
6675 mono_mb_emit_byte (mb, CEE_ADD);
6677 mono_mb_emit_byte (mb, CEE_CONV_OVF_I);
6680 mono_mb_emit_op (mb, CEE_NEWARR, eklass);
6681 mono_mb_emit_stloc (mb, conv_arg);
6683 if (eklass->blittable) {
6684 mono_mb_emit_ldloc (mb, conv_arg);
6685 mono_mb_emit_byte (mb, CEE_CONV_I);
6686 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
6687 mono_mb_emit_byte (mb, CEE_ADD);
6688 mono_mb_emit_ldarg (mb, argnum);
6689 mono_mb_emit_ldloc (mb, conv_arg);
6690 mono_mb_emit_byte (mb, CEE_LDLEN);
6691 mono_mb_emit_icon (mb, esize);
6692 mono_mb_emit_byte (mb, CEE_MUL);
6693 mono_mb_emit_byte (mb, CEE_PREFIX1);
6694 mono_mb_emit_byte (mb, CEE_CPBLK);
6695 mono_mb_patch_branch (mb, label1);
6696 break;
6699 /* Emit marshalling loop */
6700 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6701 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6702 mono_mb_emit_stloc (mb, index_var);
6703 label2 = mono_mb_get_label (mb);
6704 mono_mb_emit_ldloc (mb, index_var);
6705 mono_mb_emit_ldloc (mb, conv_arg);
6706 mono_mb_emit_byte (mb, CEE_LDLEN);
6707 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6709 /* Emit marshalling code */
6710 if (is_string) {
6711 g_assert (conv != MONO_MARSHAL_CONV_INVALID);
6713 mono_mb_emit_ldloc (mb, conv_arg);
6714 mono_mb_emit_ldloc (mb, index_var);
6716 mono_mb_emit_ldloc (mb, src_ptr);
6717 mono_mb_emit_byte (mb, CEE_LDIND_I);
6719 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
6720 mono_mb_emit_byte (mb, CEE_STELEM_REF);
6722 else {
6723 char *msg = g_strdup ("Marshalling of non-string and non-blittable arrays to managed code is not implemented.");
6724 mono_mb_emit_exception_marshal_directive (mb, msg);
6725 return conv_arg;
6728 mono_mb_emit_add_to_local (mb, index_var, 1);
6729 mono_mb_emit_add_to_local (mb, src_ptr, esize);
6731 mono_mb_emit_branch_label (mb, CEE_BR, label2);
6733 mono_mb_patch_branch (mb, label1);
6734 mono_mb_patch_branch (mb, label3);
6736 break;
6738 case MARSHAL_ACTION_MANAGED_CONV_OUT: {
6739 MonoClass *eklass;
6740 guint32 label1, label2, label3;
6741 int index_var, dest_ptr, esize, param_num, num_elem;
6742 MonoMarshalConv conv;
6743 gboolean is_string = FALSE;
6745 if (!spec)
6746 /* Already handled in CONV_IN */
6747 break;
6749 /* These are already checked in CONV_IN */
6750 g_assert (!t->byref);
6751 g_assert (spec->native == MONO_NATIVE_LPARRAY);
6752 g_assert (t->attrs & PARAM_ATTRIBUTE_OUT);
6754 param_num = spec->data.array_data.param_num;
6755 num_elem = spec->data.array_data.num_elem;
6757 if (spec->data.array_data.elem_mult == 0)
6758 /* param_num is not specified */
6759 param_num = -1;
6761 if (param_num == -1) {
6762 if (num_elem <= 0) {
6763 g_assert_not_reached ();
6767 /* FIXME: Optimize blittable case */
6769 eklass = klass->element_class;
6770 if (eklass == mono_defaults.string_class) {
6771 is_string = TRUE;
6772 conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
6774 else if (eklass == mono_defaults.stringbuilder_class) {
6775 is_string = TRUE;
6776 conv = mono_marshal_get_stringbuilder_to_ptr_conv (m->piinfo, spec);
6778 else
6779 conv = MONO_MARSHAL_CONV_INVALID;
6781 mono_marshal_load_type_info (eklass);
6783 if (is_string)
6784 esize = sizeof (gpointer);
6785 else
6786 esize = mono_class_native_size (eklass, NULL);
6788 dest_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6790 /* Check null */
6791 mono_mb_emit_ldloc (mb, conv_arg);
6792 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6794 mono_mb_emit_ldarg (mb, argnum);
6795 mono_mb_emit_stloc (mb, dest_ptr);
6797 if (eklass->blittable) {
6798 /* dest */
6799 mono_mb_emit_ldarg (mb, argnum);
6800 /* src */
6801 mono_mb_emit_ldloc (mb, conv_arg);
6802 mono_mb_emit_byte (mb, CEE_CONV_I);
6803 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
6804 mono_mb_emit_byte (mb, CEE_ADD);
6805 /* length */
6806 mono_mb_emit_ldloc (mb, conv_arg);
6807 mono_mb_emit_byte (mb, CEE_LDLEN);
6808 mono_mb_emit_icon (mb, esize);
6809 mono_mb_emit_byte (mb, CEE_MUL);
6810 mono_mb_emit_byte (mb, CEE_PREFIX1);
6811 mono_mb_emit_byte (mb, CEE_CPBLK);
6812 break;
6815 /* Emit marshalling loop */
6816 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6817 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6818 mono_mb_emit_stloc (mb, index_var);
6819 label2 = mono_mb_get_label (mb);
6820 mono_mb_emit_ldloc (mb, index_var);
6821 mono_mb_emit_ldloc (mb, conv_arg);
6822 mono_mb_emit_byte (mb, CEE_LDLEN);
6823 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6825 /* Emit marshalling code */
6826 if (is_string) {
6827 int stind_op;
6828 g_assert (conv != MONO_MARSHAL_CONV_INVALID);
6830 /* dest */
6831 mono_mb_emit_ldloc (mb, dest_ptr);
6833 /* src */
6834 mono_mb_emit_ldloc (mb, conv_arg);
6835 mono_mb_emit_ldloc (mb, index_var);
6837 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
6839 mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
6840 mono_mb_emit_byte (mb, stind_op);
6842 else {
6843 char *msg = g_strdup ("Marshalling of non-string and non-blittable arrays to managed code is not implemented.");
6844 mono_mb_emit_exception_marshal_directive (mb, msg);
6845 return conv_arg;
6848 mono_mb_emit_add_to_local (mb, index_var, 1);
6849 mono_mb_emit_add_to_local (mb, dest_ptr, esize);
6851 mono_mb_emit_branch_label (mb, CEE_BR, label2);
6853 mono_mb_patch_branch (mb, label1);
6854 mono_mb_patch_branch (mb, label3);
6856 break;
6858 case MARSHAL_ACTION_MANAGED_CONV_RESULT: {
6859 MonoClass *eklass;
6860 guint32 label1, label2, label3;
6861 int index_var, src, dest, esize;
6862 MonoMarshalConv conv = MONO_MARSHAL_CONV_INVALID;
6863 gboolean is_string = FALSE;
6865 g_assert (!t->byref);
6867 eklass = klass->element_class;
6869 mono_marshal_load_type_info (eklass);
6871 if (eklass == mono_defaults.string_class) {
6872 is_string = TRUE;
6873 conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
6875 else {
6876 g_assert_not_reached ();
6879 if (is_string)
6880 esize = sizeof (gpointer);
6881 else if (eklass == mono_defaults.char_class)
6882 esize = mono_pinvoke_is_unicode (m->piinfo) ? 2 : 1;
6883 else
6884 esize = mono_class_native_size (eklass, NULL);
6886 src = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6887 dest = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6889 mono_mb_emit_stloc (mb, src);
6890 mono_mb_emit_ldloc (mb, src);
6891 mono_mb_emit_stloc (mb, 3);
6893 /* Check for null */
6894 mono_mb_emit_ldloc (mb, src);
6895 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6897 /* Allocate native array */
6898 mono_mb_emit_icon (mb, esize);
6899 mono_mb_emit_ldloc (mb, src);
6900 mono_mb_emit_byte (mb, CEE_LDLEN);
6902 if (eklass == mono_defaults.string_class) {
6903 /* Make the array bigger for the terminating null */
6904 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
6905 mono_mb_emit_byte (mb, CEE_ADD);
6907 mono_mb_emit_byte (mb, CEE_MUL);
6908 mono_mb_emit_icall (mb, ves_icall_marshal_alloc);
6909 mono_mb_emit_stloc (mb, dest);
6910 mono_mb_emit_ldloc (mb, dest);
6911 mono_mb_emit_stloc (mb, 3);
6913 /* Emit marshalling loop */
6914 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6915 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6916 mono_mb_emit_stloc (mb, index_var);
6917 label2 = mono_mb_get_label (mb);
6918 mono_mb_emit_ldloc (mb, index_var);
6919 mono_mb_emit_ldloc (mb, src);
6920 mono_mb_emit_byte (mb, CEE_LDLEN);
6921 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6923 /* Emit marshalling code */
6924 if (is_string) {
6925 int stind_op;
6926 g_assert (conv != MONO_MARSHAL_CONV_INVALID);
6928 /* dest */
6929 mono_mb_emit_ldloc (mb, dest);
6931 /* src */
6932 mono_mb_emit_ldloc (mb, src);
6933 mono_mb_emit_ldloc (mb, index_var);
6935 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
6937 mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
6938 mono_mb_emit_byte (mb, stind_op);
6940 else {
6941 char *msg = g_strdup ("Marshalling of non-string arrays to managed code is not implemented.");
6942 mono_mb_emit_exception_marshal_directive (mb, msg);
6943 return conv_arg;
6946 mono_mb_emit_add_to_local (mb, index_var, 1);
6947 mono_mb_emit_add_to_local (mb, dest, esize);
6949 mono_mb_emit_branch_label (mb, CEE_BR, label2);
6951 mono_mb_patch_branch (mb, label3);
6952 mono_mb_patch_branch (mb, label1);
6953 break;
6955 default:
6956 g_assert_not_reached ();
6958 #endif
6959 return conv_arg;
6962 static MonoType*
6963 marshal_boolean_conv_in_get_local_type (MonoMarshalSpec *spec, guint8 *ldc_op /*out*/)
6965 if (spec == NULL) {
6966 return &mono_defaults.int32_class->byval_arg;
6967 } else {
6968 switch (spec->native) {
6969 case MONO_NATIVE_I1:
6970 case MONO_NATIVE_U1:
6971 return &mono_defaults.byte_class->byval_arg;
6972 case MONO_NATIVE_VARIANTBOOL:
6973 if (ldc_op) *ldc_op = CEE_LDC_I4_M1;
6974 return &mono_defaults.int16_class->byval_arg;
6975 case MONO_NATIVE_BOOLEAN:
6976 return &mono_defaults.int32_class->byval_arg;
6977 default:
6978 g_warning ("marshalling bool as native type %x is currently not supported", spec->native);
6979 return &mono_defaults.int32_class->byval_arg;
6984 static MonoClass*
6985 marshal_boolean_managed_conv_in_get_conv_arg_class (MonoMarshalSpec *spec, guint8 *ldop/*out*/)
6987 MonoClass* conv_arg_class = mono_defaults.int32_class;
6988 if (spec) {
6989 switch (spec->native) {
6990 case MONO_NATIVE_I1:
6991 case MONO_NATIVE_U1:
6992 conv_arg_class = mono_defaults.byte_class;
6993 if (ldop) *ldop = CEE_LDIND_I1;
6994 break;
6995 case MONO_NATIVE_VARIANTBOOL:
6996 conv_arg_class = mono_defaults.int16_class;
6997 if (ldop) *ldop = CEE_LDIND_I2;
6998 break;
6999 case MONO_NATIVE_BOOLEAN:
7000 break;
7001 default:
7002 g_warning ("marshalling bool as native type %x is currently not supported", spec->native);
7005 return conv_arg_class;
7008 static int
7009 emit_marshal_boolean (EmitMarshalContext *m, int argnum, MonoType *t,
7010 MonoMarshalSpec *spec,
7011 int conv_arg, MonoType **conv_arg_type,
7012 MarshalAction action)
7014 #ifdef DISABLE_JIT
7015 switch (action) {
7016 case MARSHAL_ACTION_CONV_IN:
7017 if (t->byref)
7018 *conv_arg_type = &mono_defaults.int_class->byval_arg;
7019 else
7020 *conv_arg_type = marshal_boolean_conv_in_get_local_type (spec, NULL);
7021 break;
7023 case MARSHAL_ACTION_MANAGED_CONV_IN: {
7024 MonoClass* conv_arg_class = marshal_boolean_managed_conv_in_get_conv_arg_class (spec, NULL);
7025 if (t->byref)
7026 *conv_arg_type = &conv_arg_class->this_arg;
7027 else
7028 *conv_arg_type = &conv_arg_class->byval_arg;
7029 break;
7033 #else
7034 MonoMethodBuilder *mb = m->mb;
7036 switch (action) {
7037 case MARSHAL_ACTION_CONV_IN: {
7038 MonoType *local_type;
7039 int label_false;
7040 guint8 ldc_op = CEE_LDC_I4_1;
7042 local_type = marshal_boolean_conv_in_get_local_type (spec, &ldc_op);
7043 if (t->byref)
7044 *conv_arg_type = &mono_defaults.int_class->byval_arg;
7045 else
7046 *conv_arg_type = local_type;
7047 conv_arg = mono_mb_add_local (mb, local_type);
7049 mono_mb_emit_ldarg (mb, argnum);
7050 if (t->byref)
7051 mono_mb_emit_byte (mb, CEE_LDIND_I1);
7052 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
7053 mono_mb_emit_byte (mb, ldc_op);
7054 mono_mb_emit_stloc (mb, conv_arg);
7055 mono_mb_patch_branch (mb, label_false);
7057 break;
7060 case MARSHAL_ACTION_CONV_OUT:
7062 int label_false, label_end;
7063 if (!t->byref)
7064 break;
7066 mono_mb_emit_ldarg (mb, argnum);
7067 mono_mb_emit_ldloc (mb, conv_arg);
7069 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
7070 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
7072 label_end = mono_mb_emit_branch (mb, CEE_BR);
7073 mono_mb_patch_branch (mb, label_false);
7074 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
7075 mono_mb_patch_branch (mb, label_end);
7077 mono_mb_emit_byte (mb, CEE_STIND_I1);
7078 break;
7081 case MARSHAL_ACTION_PUSH:
7082 if (t->byref)
7083 mono_mb_emit_ldloc_addr (mb, conv_arg);
7084 else if (conv_arg)
7085 mono_mb_emit_ldloc (mb, conv_arg);
7086 else
7087 mono_mb_emit_ldarg (mb, argnum);
7088 break;
7090 case MARSHAL_ACTION_CONV_RESULT:
7091 /* maybe we need to make sure that it fits within 8 bits */
7092 mono_mb_emit_stloc (mb, 3);
7093 break;
7095 case MARSHAL_ACTION_MANAGED_CONV_IN: {
7096 MonoClass* conv_arg_class = mono_defaults.int32_class;
7097 guint8 ldop = CEE_LDIND_I4;
7098 int label_null, label_false;
7100 conv_arg_class = marshal_boolean_managed_conv_in_get_conv_arg_class (spec, &ldop);
7101 conv_arg = mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
7103 if (t->byref)
7104 *conv_arg_type = &conv_arg_class->this_arg;
7105 else
7106 *conv_arg_type = &conv_arg_class->byval_arg;
7109 mono_mb_emit_ldarg (mb, argnum);
7111 /* Check null */
7112 if (t->byref) {
7113 label_null = mono_mb_emit_branch (mb, CEE_BRFALSE);
7114 mono_mb_emit_ldarg (mb, argnum);
7115 mono_mb_emit_byte (mb, ldop);
7116 } else
7117 label_null = 0;
7119 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
7120 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
7121 mono_mb_emit_stloc (mb, conv_arg);
7122 mono_mb_patch_branch (mb, label_false);
7124 if (t->byref)
7125 mono_mb_patch_branch (mb, label_null);
7126 break;
7129 case MARSHAL_ACTION_MANAGED_CONV_OUT: {
7130 guint8 stop = CEE_STIND_I4;
7131 guint8 ldc_op = CEE_LDC_I4_1;
7132 int label_null,label_false, label_end;;
7134 if (!t->byref)
7135 break;
7136 if (spec) {
7137 switch (spec->native) {
7138 case MONO_NATIVE_I1:
7139 case MONO_NATIVE_U1:
7140 stop = CEE_STIND_I1;
7141 break;
7142 case MONO_NATIVE_VARIANTBOOL:
7143 stop = CEE_STIND_I2;
7144 ldc_op = CEE_LDC_I4_M1;
7145 break;
7146 default:
7147 break;
7151 /* Check null */
7152 mono_mb_emit_ldarg (mb, argnum);
7153 label_null = mono_mb_emit_branch (mb, CEE_BRFALSE);
7155 mono_mb_emit_ldarg (mb, argnum);
7156 mono_mb_emit_ldloc (mb, conv_arg);
7158 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
7159 mono_mb_emit_byte (mb, ldc_op);
7160 label_end = mono_mb_emit_branch (mb, CEE_BR);
7162 mono_mb_patch_branch (mb, label_false);
7163 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
7164 mono_mb_patch_branch (mb, label_end);
7166 mono_mb_emit_byte (mb, stop);
7167 mono_mb_patch_branch (mb, label_null);
7168 break;
7171 default:
7172 g_assert_not_reached ();
7174 #endif
7175 return conv_arg;
7178 static int
7179 emit_marshal_ptr (EmitMarshalContext *m, int argnum, MonoType *t,
7180 MonoMarshalSpec *spec, int conv_arg,
7181 MonoType **conv_arg_type, MarshalAction action)
7183 #ifndef DISABLE_JIT
7184 MonoMethodBuilder *mb = m->mb;
7186 switch (action) {
7187 case MARSHAL_ACTION_CONV_IN:
7188 /* MS seems to allow this in some cases, ie. bxc #158 */
7190 if (MONO_TYPE_ISSTRUCT (t->data.type) && !mono_class_from_mono_type (t->data.type)->blittable) {
7191 char *msg = g_strdup_printf ("Can not marshal 'parameter #%d': Pointers can not reference marshaled structures. Use byref instead.", argnum + 1);
7192 mono_mb_emit_exception_marshal_directive (m->mb, msg);
7195 break;
7197 case MARSHAL_ACTION_PUSH:
7198 mono_mb_emit_ldarg (mb, argnum);
7199 break;
7201 case MARSHAL_ACTION_CONV_RESULT:
7202 /* no conversions necessary */
7203 mono_mb_emit_stloc (mb, 3);
7204 break;
7206 default:
7207 break;
7209 #endif
7210 return conv_arg;
7213 static int
7214 emit_marshal_char (EmitMarshalContext *m, int argnum, MonoType *t,
7215 MonoMarshalSpec *spec, int conv_arg,
7216 MonoType **conv_arg_type, MarshalAction action)
7218 #ifndef DISABLE_JIT
7219 MonoMethodBuilder *mb = m->mb;
7221 switch (action) {
7222 case MARSHAL_ACTION_PUSH:
7223 /* fixme: dont know how to marshal that. We cant simply
7224 * convert it to a one byte UTF8 character, because an
7225 * unicode character may need more that one byte in UTF8 */
7226 mono_mb_emit_ldarg (mb, argnum);
7227 break;
7229 case MARSHAL_ACTION_CONV_RESULT:
7230 /* fixme: we need conversions here */
7231 mono_mb_emit_stloc (mb, 3);
7232 break;
7234 default:
7235 break;
7237 #endif
7238 return conv_arg;
7241 static int
7242 emit_marshal_scalar (EmitMarshalContext *m, int argnum, MonoType *t,
7243 MonoMarshalSpec *spec, int conv_arg,
7244 MonoType **conv_arg_type, MarshalAction action)
7246 #ifndef DISABLE_JIT
7247 MonoMethodBuilder *mb = m->mb;
7249 switch (action) {
7250 case MARSHAL_ACTION_PUSH:
7251 mono_mb_emit_ldarg (mb, argnum);
7252 break;
7254 case MARSHAL_ACTION_CONV_RESULT:
7255 /* no conversions necessary */
7256 mono_mb_emit_stloc (mb, 3);
7257 break;
7259 default:
7260 break;
7262 #endif
7263 return conv_arg;
7266 static int
7267 emit_marshal (EmitMarshalContext *m, int argnum, MonoType *t,
7268 MonoMarshalSpec *spec, int conv_arg,
7269 MonoType **conv_arg_type, MarshalAction action)
7271 /* Ensure that we have marshalling info for this param */
7272 mono_marshal_load_type_info (mono_class_from_mono_type (t));
7274 if (spec && spec->native == MONO_NATIVE_CUSTOM)
7275 return emit_marshal_custom (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7277 if (spec && spec->native == MONO_NATIVE_ASANY)
7278 return emit_marshal_asany (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7280 switch (t->type) {
7281 case MONO_TYPE_VALUETYPE:
7282 if (t->data.klass == mono_defaults.handleref_class)
7283 return emit_marshal_handleref (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7285 return emit_marshal_vtype (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7286 case MONO_TYPE_STRING:
7287 return emit_marshal_string (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7288 case MONO_TYPE_CLASS:
7289 case MONO_TYPE_OBJECT:
7290 #if !defined(DISABLE_COM) && !defined(DISABLE_JIT)
7291 if (spec && spec->native == MONO_NATIVE_STRUCT)
7292 return emit_marshal_variant (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7293 #endif
7295 #if !defined(DISABLE_COM)
7296 if (spec && (spec->native == MONO_NATIVE_IUNKNOWN ||
7297 spec->native == MONO_NATIVE_IDISPATCH ||
7298 spec->native == MONO_NATIVE_INTERFACE))
7299 return mono_cominterop_emit_marshal_com_interface (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7300 if (spec && (spec->native == MONO_NATIVE_SAFEARRAY) &&
7301 (spec->data.safearray_data.elem_type == MONO_VARIANT_VARIANT) &&
7302 ((action == MARSHAL_ACTION_CONV_OUT) || (action == MARSHAL_ACTION_CONV_IN) || (action == MARSHAL_ACTION_PUSH)))
7303 return mono_cominterop_emit_marshal_safearray (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7304 #endif
7306 if (mono_class_try_get_safehandle_class () != NULL && t->data.klass &&
7307 mono_class_is_subclass_of (t->data.klass, mono_class_try_get_safehandle_class (), FALSE))
7308 return emit_marshal_safehandle (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7310 return emit_marshal_object (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7311 case MONO_TYPE_ARRAY:
7312 case MONO_TYPE_SZARRAY:
7313 return emit_marshal_array (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7314 case MONO_TYPE_BOOLEAN:
7315 return emit_marshal_boolean (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7316 case MONO_TYPE_PTR:
7317 return emit_marshal_ptr (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7318 case MONO_TYPE_CHAR:
7319 return emit_marshal_char (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7320 case MONO_TYPE_I1:
7321 case MONO_TYPE_U1:
7322 case MONO_TYPE_I2:
7323 case MONO_TYPE_U2:
7324 case MONO_TYPE_I4:
7325 case MONO_TYPE_U4:
7326 case MONO_TYPE_I:
7327 case MONO_TYPE_U:
7328 case MONO_TYPE_R4:
7329 case MONO_TYPE_R8:
7330 case MONO_TYPE_I8:
7331 case MONO_TYPE_U8:
7332 case MONO_TYPE_FNPTR:
7333 return emit_marshal_scalar (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7334 case MONO_TYPE_GENERICINST:
7335 if (mono_type_generic_inst_is_valuetype (t))
7336 return emit_marshal_vtype (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7337 else
7338 return emit_marshal_object (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7339 default:
7340 return conv_arg;
7344 #ifndef DISABLE_JIT
7346 * mono_marshal_emit_native_wrapper:
7347 * @image: the image to use for looking up custom marshallers
7348 * @sig: The signature of the native function
7349 * @piinfo: Marshalling information
7350 * @mspecs: Marshalling information
7351 * @aot: whenever the created method will be compiled by the AOT compiler
7352 * @method: if non-NULL, the pinvoke method to call
7353 * @check_exceptions: Whenever to check for pending exceptions after the native call
7354 * @func_param: the function to call is passed as a boxed IntPtr as the first parameter
7356 * generates IL code for the pinvoke wrapper, the generated code calls @func.
7358 void
7359 mono_marshal_emit_native_wrapper (MonoImage *image, MonoMethodBuilder *mb, MonoMethodSignature *sig, MonoMethodPInvoke *piinfo, MonoMarshalSpec **mspecs, gpointer func, gboolean aot, gboolean check_exceptions, gboolean func_param)
7361 EmitMarshalContext m;
7362 MonoMethodSignature *csig;
7363 MonoClass *klass;
7364 int i, argnum, *tmp_locals;
7365 int type, param_shift = 0;
7366 int coop_gc_stack_dummy, coop_gc_var;
7368 memset (&m, 0, sizeof (m));
7369 m.mb = mb;
7370 m.sig = sig;
7371 m.piinfo = piinfo;
7373 /* we copy the signature, so that we can set pinvoke to 0 */
7374 if (func_param) {
7375 /* The function address is passed as the first argument */
7376 g_assert (!sig->hasthis);
7377 param_shift += 1;
7379 csig = mono_metadata_signature_dup_full (mb->method->klass->image, sig);
7380 csig->pinvoke = 1;
7381 m.csig = csig;
7382 m.image = image;
7384 if (sig->hasthis)
7385 param_shift += 1;
7387 /* we allocate local for use with emit_struct_conv() */
7388 /* allocate local 0 (pointer) src_ptr */
7389 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7390 /* allocate local 1 (pointer) dst_ptr */
7391 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7392 /* allocate local 2 (boolean) delete_old */
7393 mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
7395 /* delete_old = FALSE */
7396 mono_mb_emit_icon (mb, 0);
7397 mono_mb_emit_stloc (mb, 2);
7399 if (!MONO_TYPE_IS_VOID (sig->ret)) {
7400 /* allocate local 3 to store the return value */
7401 mono_mb_add_local (mb, sig->ret);
7404 if (mono_threads_is_coop_enabled ()) {
7405 /* local 4, dummy local used to get a stack address for suspend funcs */
7406 coop_gc_stack_dummy = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7407 /* local 5, the local to be used when calling the suspend funcs */
7408 coop_gc_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7412 * cookie = mono_threads_enter_gc_safe_region_unbalanced (ref dummy);
7414 * ret = method (...);
7416 * mono_threads_exit_gc_safe_region_unbalanced (cookie, ref dummy);
7418 * <interrupt check>
7420 * return ret;
7423 if (MONO_TYPE_ISSTRUCT (sig->ret))
7424 m.vtaddr_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7426 if (mspecs [0] && mspecs [0]->native == MONO_NATIVE_CUSTOM) {
7427 /* Return type custom marshaling */
7429 * Since we can't determine the return type of the unmanaged function,
7430 * we assume it returns a pointer, and pass that pointer to
7431 * MarshalNativeToManaged.
7433 csig->ret = &mono_defaults.int_class->byval_arg;
7436 /* we first do all conversions */
7437 tmp_locals = (int *)alloca (sizeof (int) * sig->param_count);
7438 m.orig_conv_args = (int *)alloca (sizeof (int) * (sig->param_count + 1));
7440 for (i = 0; i < sig->param_count; i ++) {
7441 tmp_locals [i] = emit_marshal (&m, i + param_shift, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_CONV_IN);
7444 // In coop mode need to register blocking state during native call
7445 if (mono_threads_is_coop_enabled ()) {
7446 // Perform an extra, early lookup of the function address, so any exceptions
7447 // potentially resulting from the lookup occur before entering blocking mode.
7448 if (!func_param && !MONO_CLASS_IS_IMPORT (mb->method->klass) && aot) {
7449 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7450 mono_mb_emit_op (mb, CEE_MONO_ICALL_ADDR, &piinfo->method);
7451 mono_mb_emit_byte (mb, CEE_POP); // Result not needed yet
7454 mono_mb_emit_ldloc_addr (mb, coop_gc_stack_dummy);
7455 mono_mb_emit_icall (mb, mono_threads_enter_gc_safe_region_unbalanced);
7456 mono_mb_emit_stloc (mb, coop_gc_var);
7459 /* push all arguments */
7461 if (sig->hasthis)
7462 mono_mb_emit_byte (mb, CEE_LDARG_0);
7464 for (i = 0; i < sig->param_count; i++) {
7465 emit_marshal (&m, i + param_shift, sig->params [i], mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_PUSH);
7468 /* call the native method */
7469 if (func_param) {
7470 mono_mb_emit_byte (mb, CEE_LDARG_0);
7471 mono_mb_emit_op (mb, CEE_UNBOX, mono_defaults.int_class);
7472 mono_mb_emit_byte (mb, CEE_LDIND_I);
7473 mono_mb_emit_calli (mb, csig);
7474 } else if (MONO_CLASS_IS_IMPORT (mb->method->klass)) {
7475 #ifndef DISABLE_COM
7476 mono_mb_emit_cominterop_call (mb, csig, &piinfo->method);
7477 #else
7478 g_assert_not_reached ();
7479 #endif
7480 } else {
7481 if (aot) {
7482 /* Reuse the ICALL_ADDR opcode for pinvokes too */
7483 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7484 mono_mb_emit_op (mb, CEE_MONO_ICALL_ADDR, &piinfo->method);
7485 mono_mb_emit_calli (mb, csig);
7486 } else {
7487 mono_mb_emit_native_call (mb, csig, func);
7491 /* Set LastError if needed */
7492 if (piinfo->piflags & PINVOKE_ATTRIBUTE_SUPPORTS_LAST_ERROR) {
7493 #ifdef TARGET_WIN32
7494 if (!aot) {
7495 static MonoMethodSignature *get_last_error_sig = NULL;
7496 if (!get_last_error_sig) {
7497 get_last_error_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
7498 get_last_error_sig->ret = &mono_defaults.int_class->byval_arg;
7499 get_last_error_sig->pinvoke = 1;
7503 * Have to call GetLastError () early and without a wrapper, since various runtime components could
7504 * clobber its value.
7506 mono_mb_emit_native_call (mb, get_last_error_sig, GetLastError);
7507 mono_mb_emit_icall (mb, mono_marshal_set_last_error_windows);
7508 } else {
7509 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7510 mono_mb_emit_byte (mb, CEE_MONO_GET_LAST_ERROR);
7511 mono_mb_emit_icall (mb, mono_marshal_set_last_error_windows);
7513 #else
7514 mono_mb_emit_icall (mb, mono_marshal_set_last_error);
7515 #endif
7518 if (MONO_TYPE_ISSTRUCT (sig->ret)) {
7519 MonoClass *klass = mono_class_from_mono_type (sig->ret);
7520 mono_class_init (klass);
7521 if (!(mono_class_is_explicit_layout (klass) || klass->blittable)) {
7522 /* This is used by emit_marshal_vtype (), but it needs to go right before the call */
7523 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7524 mono_mb_emit_byte (mb, CEE_MONO_VTADDR);
7525 mono_mb_emit_stloc (mb, m.vtaddr_var);
7529 /* Unblock before converting the result, since that can involve calls into the runtime */
7530 if (mono_threads_is_coop_enabled ()) {
7531 mono_mb_emit_ldloc (mb, coop_gc_var);
7532 mono_mb_emit_ldloc_addr (mb, coop_gc_stack_dummy);
7533 mono_mb_emit_icall (mb, mono_threads_exit_gc_safe_region_unbalanced);
7536 /* convert the result */
7537 if (!sig->ret->byref) {
7538 MonoMarshalSpec *spec = mspecs [0];
7539 type = sig->ret->type;
7541 if (spec && spec->native == MONO_NATIVE_CUSTOM) {
7542 emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7543 } else {
7544 handle_enum:
7545 switch (type) {
7546 case MONO_TYPE_VOID:
7547 break;
7548 case MONO_TYPE_VALUETYPE:
7549 klass = sig->ret->data.klass;
7550 if (klass->enumtype) {
7551 type = mono_class_enum_basetype (sig->ret->data.klass)->type;
7552 goto handle_enum;
7554 emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7555 break;
7556 case MONO_TYPE_I1:
7557 case MONO_TYPE_U1:
7558 case MONO_TYPE_I2:
7559 case MONO_TYPE_U2:
7560 case MONO_TYPE_I4:
7561 case MONO_TYPE_U4:
7562 case MONO_TYPE_I:
7563 case MONO_TYPE_U:
7564 case MONO_TYPE_R4:
7565 case MONO_TYPE_R8:
7566 case MONO_TYPE_I8:
7567 case MONO_TYPE_U8:
7568 case MONO_TYPE_FNPTR:
7569 case MONO_TYPE_STRING:
7570 case MONO_TYPE_CLASS:
7571 case MONO_TYPE_OBJECT:
7572 case MONO_TYPE_BOOLEAN:
7573 case MONO_TYPE_ARRAY:
7574 case MONO_TYPE_SZARRAY:
7575 case MONO_TYPE_CHAR:
7576 case MONO_TYPE_PTR:
7577 case MONO_TYPE_GENERICINST:
7578 emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7579 break;
7580 case MONO_TYPE_TYPEDBYREF:
7581 default:
7582 g_warning ("return type 0x%02x unknown", sig->ret->type);
7583 g_assert_not_reached ();
7586 } else {
7587 mono_mb_emit_stloc (mb, 3);
7591 * Need to call this after converting the result since MONO_VTADDR needs
7592 * to be adjacent to the call instruction.
7594 if (check_exceptions)
7595 emit_thread_interrupt_checkpoint (mb);
7597 /* we need to convert byref arguments back and free string arrays */
7598 for (i = 0; i < sig->param_count; i++) {
7599 MonoType *t = sig->params [i];
7600 MonoMarshalSpec *spec = mspecs [i + 1];
7602 argnum = i + param_shift;
7604 if (spec && ((spec->native == MONO_NATIVE_CUSTOM) || (spec->native == MONO_NATIVE_ASANY))) {
7605 emit_marshal (&m, argnum, t, spec, tmp_locals [i], NULL, MARSHAL_ACTION_CONV_OUT);
7606 continue;
7609 switch (t->type) {
7610 case MONO_TYPE_STRING:
7611 case MONO_TYPE_VALUETYPE:
7612 case MONO_TYPE_CLASS:
7613 case MONO_TYPE_OBJECT:
7614 case MONO_TYPE_SZARRAY:
7615 case MONO_TYPE_BOOLEAN:
7616 emit_marshal (&m, argnum, t, spec, tmp_locals [i], NULL, MARSHAL_ACTION_CONV_OUT);
7617 break;
7618 default:
7619 break;
7623 if (!MONO_TYPE_IS_VOID(sig->ret))
7624 mono_mb_emit_ldloc (mb, 3);
7626 mono_mb_emit_byte (mb, CEE_RET);
7628 #endif /* DISABLE_JIT */
7631 * mono_marshal_get_native_wrapper:
7632 * @method: The MonoMethod to wrap.
7633 * @check_exceptions: Whenever to check for pending exceptions
7635 * generates IL code for the pinvoke wrapper (the generated method
7636 * calls the unmanaged code in piinfo->addr)
7638 MonoMethod *
7639 mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions, gboolean aot)
7641 MonoMethodSignature *sig, *csig;
7642 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
7643 MonoMethodBuilder *mb;
7644 MonoMarshalSpec **mspecs;
7645 MonoMethod *res;
7646 GHashTable *cache;
7647 gboolean pinvoke = FALSE;
7648 gpointer iter;
7649 int i;
7650 const char *exc_class = "MissingMethodException";
7651 const char *exc_arg = NULL;
7652 WrapperInfo *info;
7654 g_assert (method != NULL);
7655 g_assert (mono_method_signature (method)->pinvoke);
7657 GHashTable **cache_ptr;
7659 if (aot) {
7660 if (check_exceptions)
7661 cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_aot_check_cache;
7662 else
7663 cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_aot_cache;
7664 } else {
7665 if (check_exceptions)
7666 cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_check_cache;
7667 else
7668 cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_cache;
7671 cache = get_cache (cache_ptr, mono_aligned_addr_hash, NULL);
7673 if ((res = mono_marshal_find_in_cache (cache, method)))
7674 return res;
7676 if (MONO_CLASS_IS_IMPORT (method->klass)) {
7677 /* The COM code is not AOT compatible, it calls mono_custom_attrs_get_attr_checked () */
7678 if (aot)
7679 return method;
7680 #ifndef DISABLE_COM
7681 return mono_cominterop_get_native_wrapper (method);
7682 #else
7683 g_assert_not_reached ();
7684 #endif
7687 sig = mono_method_signature (method);
7689 if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
7690 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7691 pinvoke = TRUE;
7693 if (!piinfo->addr) {
7694 if (pinvoke) {
7695 if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)
7696 exc_arg = "Method contains unsupported native code";
7697 else if (!aot)
7698 mono_lookup_pinvoke_call (method, &exc_class, &exc_arg);
7699 } else {
7700 piinfo->addr = mono_lookup_internal_call (method);
7704 /* hack - redirect certain string constructors to CreateString */
7705 if (piinfo->addr == ves_icall_System_String_ctor_RedirectToCreateString) {
7706 g_assert (!pinvoke);
7707 g_assert (method->string_ctor);
7708 g_assert (sig->hasthis);
7710 /* CreateString returns a value */
7711 csig = mono_metadata_signature_dup_full (method->klass->image, sig);
7712 csig->ret = &mono_defaults.string_class->byval_arg;
7713 csig->pinvoke = 0;
7715 iter = NULL;
7716 while ((res = mono_class_get_methods (mono_defaults.string_class, &iter))) {
7717 if (!strcmp ("CreateString", res->name) &&
7718 mono_metadata_signature_equal (csig, mono_method_signature (res))) {
7719 WrapperInfo *info;
7721 g_assert (!(res->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL));
7722 g_assert (!(res->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL));
7724 /* create a wrapper to preserve .ctor in stack trace */
7725 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_MANAGED);
7727 #ifndef DISABLE_JIT
7728 mono_mb_emit_byte (mb, CEE_LDARG_0);
7729 for (i = 1; i <= csig->param_count; i++)
7730 mono_mb_emit_ldarg (mb, i);
7731 mono_mb_emit_managed_call (mb, res, NULL);
7732 mono_mb_emit_byte (mb, CEE_RET);
7733 #endif
7735 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_STRING_CTOR);
7736 info->d.string_ctor.method = method;
7738 /* use native_wrapper_cache because internal calls are looked up there */
7739 res = mono_mb_create_and_cache_full (cache, method, mb, csig,
7740 csig->param_count + 1, info, NULL);
7741 mono_mb_free (mb);
7743 return res;
7747 /* exception will be thrown */
7748 piinfo->addr = NULL;
7749 g_warning ("cannot find CreateString for .ctor");
7752 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_NATIVE);
7754 mb->method->save_lmf = 1;
7757 * In AOT mode and embedding scenarios, it is possible that the icall is not
7758 * registered in the runtime doing the AOT compilation.
7760 if (!piinfo->addr && !aot) {
7761 #ifndef DISABLE_JIT
7762 mono_mb_emit_exception (mb, exc_class, exc_arg);
7763 #endif
7764 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
7765 info->d.managed_to_native.method = method;
7767 csig = mono_metadata_signature_dup_full (method->klass->image, sig);
7768 csig->pinvoke = 0;
7769 res = mono_mb_create_and_cache_full (cache, method, mb, csig,
7770 csig->param_count + 16, info, NULL);
7771 mono_mb_free (mb);
7773 return res;
7776 /* internal calls: we simply push all arguments and call the method (no conversions) */
7777 if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
7778 if (sig->hasthis)
7779 csig = mono_metadata_signature_dup_add_this (method->klass->image, sig, method->klass);
7780 else
7781 csig = mono_metadata_signature_dup_full (method->klass->image, sig);
7783 //printf ("%s\n", mono_method_full_name (method, 1));
7785 /* hack - string constructors returns a value */
7786 if (method->string_ctor)
7787 csig->ret = &mono_defaults.string_class->byval_arg;
7789 #ifndef DISABLE_JIT
7790 // FIXME:
7791 MonoClass *handle_stack_mark_class;
7792 MonoClass *error_class;
7793 int thread_info_var = -1, stack_mark_var = -1, error_var = -1;
7794 MonoMethodSignature *call_sig = csig;
7795 gboolean uses_handles = FALSE;
7796 (void) mono_lookup_internal_call_full (method, &uses_handles);
7799 /* If it uses handles and MonoError, it had better check exceptions */
7800 g_assert (!uses_handles || check_exceptions);
7802 if (uses_handles) {
7803 MonoMethodSignature *ret;
7805 /* Add a MonoError argument */
7806 // FIXME: The stuff from mono_metadata_signature_dup_internal_with_padding ()
7807 ret = mono_metadata_signature_alloc (method->klass->image, csig->param_count + 1);
7809 ret->param_count = csig->param_count + 1;
7810 ret->ret = csig->ret;
7811 for (int i = 0; i < csig->param_count; ++i) {
7812 // FIXME: TODO implement handle wrapping for out and inout params.
7813 g_assert (!mono_signature_param_is_out (csig, i));
7814 ret->params [i] = csig->params [i];
7816 ret->params [csig->param_count] = &mono_get_intptr_class ()->byval_arg;
7817 call_sig = ret;
7820 if (uses_handles) {
7821 handle_stack_mark_class = mono_class_load_from_name (mono_get_corlib (), "Mono", "RuntimeStructs/HandleStackMark");
7822 error_class = mono_class_load_from_name (mono_get_corlib (), "Mono", "RuntimeStructs/MonoError");
7824 thread_info_var = mono_mb_add_local (mb, &mono_get_intptr_class ()->byval_arg);
7825 stack_mark_var = mono_mb_add_local (mb, &handle_stack_mark_class->byval_arg);
7826 error_var = mono_mb_add_local (mb, &error_class->byval_arg);
7828 // FIXME: Change csig so it passes a handle not an objref
7831 if (sig->hasthis) {
7832 int pos;
7835 * Add a null check since public icalls can be called with 'call' which
7836 * does no such check.
7838 mono_mb_emit_byte (mb, CEE_LDARG_0);
7839 pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
7840 mono_mb_emit_exception (mb, "NullReferenceException", NULL);
7841 mono_mb_patch_branch (mb, pos);
7844 if (uses_handles) {
7845 mono_mb_emit_ldloc_addr (mb, stack_mark_var);
7846 mono_mb_emit_ldloc_addr (mb, error_var);
7847 mono_mb_emit_icall (mb, mono_icall_start);
7848 mono_mb_emit_stloc (mb, thread_info_var);
7850 if (sig->hasthis) {
7851 mono_mb_emit_byte (mb, CEE_LDARG_0);
7852 mono_mb_emit_icall (mb, mono_handle_new);
7854 for (i = 0; i < sig->param_count; i++) {
7855 mono_mb_emit_ldarg (mb, i + sig->hasthis);
7856 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
7857 mono_mb_emit_icall (mb, mono_handle_new);
7860 mono_mb_emit_ldloc_addr (mb, error_var);
7861 } else {
7862 if (sig->hasthis)
7863 mono_mb_emit_byte (mb, CEE_LDARG_0);
7864 for (i = 0; i < sig->param_count; i++)
7865 mono_mb_emit_ldarg (mb, i + sig->hasthis);
7868 if (aot) {
7869 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7870 mono_mb_emit_op (mb, CEE_MONO_ICALL_ADDR, &piinfo->method);
7871 mono_mb_emit_calli (mb, call_sig);
7872 } else {
7873 g_assert (piinfo->addr);
7874 mono_mb_emit_native_call (mb, call_sig, piinfo->addr);
7877 if (uses_handles) {
7878 if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
7879 // if (ret != NULL_HANDLE) {
7880 // ret = MONO_HANDLE_RAW(ret)
7881 // }
7882 mono_mb_emit_byte (mb, CEE_DUP);
7883 int pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
7884 mono_mb_emit_ldflda (mb, MONO_HANDLE_PAYLOAD_OFFSET (MonoObject));
7885 mono_mb_emit_byte (mb, CEE_LDIND_REF);
7886 mono_mb_patch_branch (mb, pos);
7888 mono_mb_emit_ldloc (mb, thread_info_var);
7889 mono_mb_emit_ldloc_addr (mb, stack_mark_var);
7890 mono_mb_emit_ldloc_addr (mb, error_var);
7891 mono_mb_emit_icall (mb, mono_icall_end);
7894 if (check_exceptions)
7895 emit_thread_interrupt_checkpoint (mb);
7896 mono_mb_emit_byte (mb, CEE_RET);
7897 #endif
7898 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
7899 info->d.managed_to_native.method = method;
7901 csig = mono_metadata_signature_dup_full (method->klass->image, csig);
7902 csig->pinvoke = 0;
7903 res = mono_mb_create_and_cache_full (cache, method, mb, csig, csig->param_count + 16,
7904 info, NULL);
7906 mono_mb_free (mb);
7907 return res;
7910 g_assert (pinvoke);
7911 if (!aot)
7912 g_assert (piinfo->addr);
7914 #ifndef DISABLE_JIT
7915 mspecs = g_new (MonoMarshalSpec*, sig->param_count + 1);
7916 mono_method_get_marshal_info (method, mspecs);
7918 mono_marshal_emit_native_wrapper (mb->method->klass->image, mb, sig, piinfo, mspecs, piinfo->addr, aot, check_exceptions, FALSE);
7919 #endif
7920 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_PINVOKE);
7921 info->d.managed_to_native.method = method;
7923 csig = mono_metadata_signature_dup_full (method->klass->image, sig);
7924 csig->pinvoke = 0;
7925 res = mono_mb_create_and_cache_full (cache, method, mb, csig, csig->param_count + 16,
7926 info, NULL);
7927 mono_mb_free (mb);
7929 #ifndef DISABLE_JIT
7930 for (i = sig->param_count; i >= 0; i--)
7931 if (mspecs [i])
7932 mono_metadata_free_marshal_spec (mspecs [i]);
7933 g_free (mspecs);
7934 #endif
7936 /* mono_method_print_code (res); */
7938 return res;
7942 * mono_marshal_get_native_func_wrapper:
7943 * @image: The image to use for memory allocation and for looking up custom marshallers.
7944 * @sig: The signature of the function
7945 * @func: The native function to wrap
7947 * Returns a wrapper method around native functions, similar to the pinvoke
7948 * wrapper.
7950 MonoMethod *
7951 mono_marshal_get_native_func_wrapper (MonoImage *image, MonoMethodSignature *sig,
7952 MonoMethodPInvoke *piinfo, MonoMarshalSpec **mspecs, gpointer func)
7954 MonoMethodSignature *csig;
7956 SignaturePointerPair key, *new_key;
7957 MonoMethodBuilder *mb;
7958 MonoMethod *res;
7959 GHashTable *cache;
7960 gboolean found;
7961 char *name;
7963 key.sig = sig;
7964 key.pointer = func;
7966 // Generic types are not safe to place in MonoImage caches.
7967 g_assert (!sig->is_inflated);
7969 cache = get_cache (&image->native_func_wrapper_cache, signature_pointer_pair_hash, signature_pointer_pair_equal);
7970 if ((res = mono_marshal_find_in_cache (cache, &key)))
7971 return res;
7973 name = g_strdup_printf ("wrapper_native_%p", func);
7974 mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
7975 mb->method->save_lmf = 1;
7977 #ifndef DISABLE_JIT
7978 mono_marshal_emit_native_wrapper (image, mb, sig, piinfo, mspecs, func, FALSE, TRUE, FALSE);
7979 #endif
7981 csig = mono_metadata_signature_dup_full (image, sig);
7982 csig->pinvoke = 0;
7984 new_key = g_new (SignaturePointerPair,1);
7985 new_key->sig = csig;
7986 new_key->pointer = func;
7988 res = mono_mb_create_and_cache_full (cache, new_key, mb, csig, csig->param_count + 16, NULL, &found);
7989 if (found)
7990 g_free (new_key);
7992 mono_mb_free (mb);
7994 mono_marshal_set_wrapper_info (res, NULL);
7996 return res;
8000 * The wrapper receives the native function as a boxed IntPtr as its 'this' argument. This is easier to support in
8001 * AOT.
8003 MonoMethod*
8004 mono_marshal_get_native_func_wrapper_aot (MonoClass *klass)
8006 MonoMethodSignature *sig, *csig;
8007 MonoMethodBuilder *mb;
8008 MonoMethod *res;
8009 GHashTable *cache;
8010 char *name;
8011 WrapperInfo *info;
8012 MonoMethodPInvoke mpiinfo;
8013 MonoMethodPInvoke *piinfo = &mpiinfo;
8014 MonoMarshalSpec **mspecs;
8015 MonoMethod *invoke = mono_get_delegate_invoke (klass);
8016 MonoImage *image = invoke->klass->image;
8017 int i;
8019 // FIXME: include UnmanagedFunctionPointerAttribute info
8022 * The wrapper is associated with the delegate type, to pick up the marshalling info etc.
8024 cache = get_cache (&mono_method_get_wrapper_cache (invoke)->native_func_wrapper_aot_cache, mono_aligned_addr_hash, NULL);
8026 if ((res = mono_marshal_find_in_cache (cache, invoke)))
8027 return res;
8029 memset (&mpiinfo, 0, sizeof (mpiinfo));
8030 parse_unmanaged_function_pointer_attr (klass, &mpiinfo);
8032 mspecs = g_new0 (MonoMarshalSpec*, mono_method_signature (invoke)->param_count + 1);
8033 mono_method_get_marshal_info (invoke, mspecs);
8034 /* Freed below so don't alloc from mempool */
8035 sig = mono_metadata_signature_dup (mono_method_signature (invoke));
8036 sig->hasthis = 0;
8038 name = g_strdup_printf ("wrapper_aot_native");
8039 mb = mono_mb_new (invoke->klass, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
8040 mb->method->save_lmf = 1;
8042 #ifndef DISABLE_JIT
8043 mono_marshal_emit_native_wrapper (image, mb, sig, piinfo, mspecs, NULL, FALSE, TRUE, TRUE);
8044 #endif
8046 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NATIVE_FUNC_AOT);
8047 info->d.managed_to_native.method = invoke;
8049 g_assert (!sig->hasthis);
8050 csig = mono_metadata_signature_dup_add_this (image, sig, mono_defaults.object_class);
8051 csig->pinvoke = 0;
8052 res = mono_mb_create_and_cache_full (cache, invoke,
8053 mb, csig, csig->param_count + 16,
8054 info, NULL);
8055 mono_mb_free (mb);
8057 for (i = mono_method_signature (invoke)->param_count; i >= 0; i--)
8058 if (mspecs [i])
8059 mono_metadata_free_marshal_spec (mspecs [i]);
8060 g_free (mspecs);
8061 g_free (sig);
8063 return res;
8067 * mono_marshal_emit_managed_wrapper:
8069 * Emit the body of a native-to-managed wrapper. INVOKE_SIG is the signature of
8070 * the delegate which wraps the managed method to be called. For closed delegates,
8071 * it could have fewer parameters than the method it wraps.
8072 * THIS_LOC is the memory location where the target of the delegate is stored.
8074 void
8075 mono_marshal_emit_managed_wrapper (MonoMethodBuilder *mb, MonoMethodSignature *invoke_sig, MonoMarshalSpec **mspecs, EmitMarshalContext* m, MonoMethod *method, uint32_t target_handle)
8077 #ifdef DISABLE_JIT
8078 MonoMethodSignature *sig, *csig;
8079 int i;
8081 sig = m->sig;
8082 csig = m->csig;
8084 /* we first do all conversions */
8085 for (i = 0; i < sig->param_count; i ++) {
8086 MonoType *t = sig->params [i];
8088 switch (t->type) {
8089 case MONO_TYPE_OBJECT:
8090 case MONO_TYPE_CLASS:
8091 case MONO_TYPE_VALUETYPE:
8092 case MONO_TYPE_ARRAY:
8093 case MONO_TYPE_SZARRAY:
8094 case MONO_TYPE_STRING:
8095 case MONO_TYPE_BOOLEAN:
8096 emit_marshal (m, i, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_MANAGED_CONV_IN);
8100 if (!sig->ret->byref) {
8101 switch (sig->ret->type) {
8102 case MONO_TYPE_STRING:
8103 csig->ret = &mono_defaults.int_class->byval_arg;
8104 break;
8105 default:
8106 break;
8109 #else
8110 MonoMethodSignature *sig, *csig;
8111 MonoExceptionClause *clauses, *clause_finally, *clause_catch;
8112 int i, *tmp_locals, ex_local, e_local, attach_cookie_local, attach_dummy_local;
8113 int leave_try_pos, leave_catch_pos, ex_m1_pos;
8114 gboolean closed = FALSE;
8116 sig = m->sig;
8117 csig = m->csig;
8119 /* allocate local 0 (pointer) src_ptr */
8120 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8121 /* allocate local 1 (pointer) dst_ptr */
8122 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8123 /* allocate local 2 (boolean) delete_old */
8124 mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
8126 if (!sig->hasthis && sig->param_count != invoke_sig->param_count) {
8127 /* Closed delegate */
8128 g_assert (sig->param_count == invoke_sig->param_count + 1);
8129 closed = TRUE;
8130 /* Use a new signature without the first argument */
8131 sig = mono_metadata_signature_dup (sig);
8132 memmove (&sig->params [0], &sig->params [1], (sig->param_count - 1) * sizeof (MonoType*));
8133 sig->param_count --;
8136 if (!MONO_TYPE_IS_VOID(sig->ret)) {
8137 /* allocate local 3 to store the return value */
8138 mono_mb_add_local (mb, sig->ret);
8141 if (MONO_TYPE_ISSTRUCT (sig->ret))
8142 m->vtaddr_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8144 ex_local = mono_mb_add_local (mb, &mono_defaults.uint32_class->byval_arg);
8145 e_local = mono_mb_add_local (mb, &mono_defaults.exception_class->byval_arg);
8147 attach_cookie_local = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8148 attach_dummy_local = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8151 * guint32 ex = -1;
8152 * try {
8153 * // does (STARTING|RUNNING|BLOCKING) -> RUNNING + set/switch domain
8154 * mono_threads_attach_coop ();
8156 * <interrupt check>
8158 * ret = method (...);
8159 * } catch (Exception e) {
8160 * ex = mono_gchandle_new (e, false);
8161 * } finally {
8162 * // does RUNNING -> (RUNNING|BLOCKING) + unset/switch domain
8163 * mono_threads_detach_coop ();
8165 * if (ex != -1)
8166 * mono_marshal_ftnptr_eh_callback (ex);
8169 * return ret;
8172 clauses = g_new0 (MonoExceptionClause, 2);
8174 clause_catch = &clauses [0];
8175 clause_catch->flags = MONO_EXCEPTION_CLAUSE_NONE;
8176 clause_catch->data.catch_class = mono_defaults.exception_class;
8178 clause_finally = &clauses [1];
8179 clause_finally->flags = MONO_EXCEPTION_CLAUSE_FINALLY;
8181 mono_mb_emit_icon (mb, 0);
8182 mono_mb_emit_stloc (mb, 2);
8184 mono_mb_emit_icon (mb, -1);
8185 mono_mb_emit_byte (mb, CEE_CONV_U4);
8186 mono_mb_emit_stloc (mb, ex_local);
8188 /* try { */
8189 clause_catch->try_offset = clause_finally->try_offset = mono_mb_get_label (mb);
8191 if (!mono_threads_is_coop_enabled ()) {
8192 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8193 mono_mb_emit_byte (mb, CEE_MONO_JIT_ATTACH);
8194 } else {
8195 /* mono_threads_attach_coop (); */
8196 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8197 mono_mb_emit_byte (mb, CEE_MONO_LDDOMAIN);
8198 mono_mb_emit_ldloc_addr (mb, attach_dummy_local);
8199 mono_mb_emit_icall (mb, mono_threads_attach_coop);
8200 mono_mb_emit_stloc (mb, attach_cookie_local);
8203 /* <interrupt check> */
8204 emit_thread_interrupt_checkpoint (mb);
8206 /* we first do all conversions */
8207 tmp_locals = (int *)alloca (sizeof (int) * sig->param_count);
8208 for (i = 0; i < sig->param_count; i ++) {
8209 MonoType *t = sig->params [i];
8211 switch (t->type) {
8212 case MONO_TYPE_OBJECT:
8213 case MONO_TYPE_CLASS:
8214 case MONO_TYPE_VALUETYPE:
8215 case MONO_TYPE_ARRAY:
8216 case MONO_TYPE_SZARRAY:
8217 case MONO_TYPE_STRING:
8218 case MONO_TYPE_BOOLEAN:
8219 tmp_locals [i] = emit_marshal (m, i, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_MANAGED_CONV_IN);
8221 break;
8222 default:
8223 tmp_locals [i] = 0;
8224 break;
8228 if (sig->hasthis) {
8229 if (target_handle) {
8230 mono_mb_emit_icon (mb, (gint32)target_handle);
8231 mono_mb_emit_icall (mb, mono_gchandle_get_target);
8232 } else {
8233 /* fixme: */
8234 g_assert_not_reached ();
8236 } else if (closed) {
8237 mono_mb_emit_icon (mb, (gint32)target_handle);
8238 mono_mb_emit_icall (mb, mono_gchandle_get_target);
8241 for (i = 0; i < sig->param_count; i++) {
8242 MonoType *t = sig->params [i];
8244 if (tmp_locals [i]) {
8245 if (t->byref)
8246 mono_mb_emit_ldloc_addr (mb, tmp_locals [i]);
8247 else
8248 mono_mb_emit_ldloc (mb, tmp_locals [i]);
8250 else
8251 mono_mb_emit_ldarg (mb, i);
8254 /* ret = method (...) */
8255 mono_mb_emit_managed_call (mb, method, NULL);
8257 if (MONO_TYPE_ISSTRUCT (sig->ret)) {
8258 MonoClass *klass = mono_class_from_mono_type (sig->ret);
8259 mono_class_init (klass);
8260 if (!(mono_class_is_explicit_layout (klass) || klass->blittable)) {
8261 /* This is used by emit_marshal_vtype (), but it needs to go right before the call */
8262 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8263 mono_mb_emit_byte (mb, CEE_MONO_VTADDR);
8264 mono_mb_emit_stloc (mb, m->vtaddr_var);
8268 if (mspecs [0] && mspecs [0]->native == MONO_NATIVE_CUSTOM) {
8269 emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
8270 } else if (!sig->ret->byref) {
8271 switch (sig->ret->type) {
8272 case MONO_TYPE_VOID:
8273 break;
8274 case MONO_TYPE_BOOLEAN:
8275 case MONO_TYPE_I1:
8276 case MONO_TYPE_U1:
8277 case MONO_TYPE_CHAR:
8278 case MONO_TYPE_I2:
8279 case MONO_TYPE_U2:
8280 case MONO_TYPE_I4:
8281 case MONO_TYPE_U4:
8282 case MONO_TYPE_I:
8283 case MONO_TYPE_U:
8284 case MONO_TYPE_PTR:
8285 case MONO_TYPE_R4:
8286 case MONO_TYPE_R8:
8287 case MONO_TYPE_I8:
8288 case MONO_TYPE_U8:
8289 case MONO_TYPE_OBJECT:
8290 mono_mb_emit_stloc (mb, 3);
8291 break;
8292 case MONO_TYPE_STRING:
8293 csig->ret = &mono_defaults.int_class->byval_arg;
8294 emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
8295 break;
8296 case MONO_TYPE_VALUETYPE:
8297 case MONO_TYPE_CLASS:
8298 case MONO_TYPE_SZARRAY:
8299 emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
8300 break;
8301 default:
8302 g_warning ("return type 0x%02x unknown", sig->ret->type);
8303 g_assert_not_reached ();
8305 } else {
8306 mono_mb_emit_stloc (mb, 3);
8309 /* Convert byref arguments back */
8310 for (i = 0; i < sig->param_count; i ++) {
8311 MonoType *t = sig->params [i];
8312 MonoMarshalSpec *spec = mspecs [i + 1];
8314 if (spec && spec->native == MONO_NATIVE_CUSTOM) {
8315 emit_marshal (m, i, t, mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
8317 else if (t->byref) {
8318 switch (t->type) {
8319 case MONO_TYPE_CLASS:
8320 case MONO_TYPE_VALUETYPE:
8321 case MONO_TYPE_OBJECT:
8322 case MONO_TYPE_STRING:
8323 case MONO_TYPE_BOOLEAN:
8324 emit_marshal (m, i, t, mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
8325 break;
8326 default:
8327 break;
8330 else if (invoke_sig->params [i]->attrs & PARAM_ATTRIBUTE_OUT) {
8331 /* The [Out] information is encoded in the delegate signature */
8332 switch (t->type) {
8333 case MONO_TYPE_SZARRAY:
8334 case MONO_TYPE_CLASS:
8335 case MONO_TYPE_VALUETYPE:
8336 emit_marshal (m, i, invoke_sig->params [i], mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
8337 break;
8338 default:
8339 g_assert_not_reached ();
8344 leave_try_pos = mono_mb_emit_branch (mb, CEE_LEAVE);
8346 /* } [endtry] */
8348 /* catch (Exception e) { */
8349 clause_catch->try_len = mono_mb_get_label (mb) - clause_catch->try_offset;
8350 clause_catch->handler_offset = mono_mb_get_label (mb);
8352 mono_mb_emit_stloc (mb, e_local);
8354 /* ex = mono_gchandle_new (e, false); */
8355 mono_mb_emit_ldloc (mb, e_local);
8356 mono_mb_emit_icon (mb, 0);
8357 mono_mb_emit_icall (mb, mono_gchandle_new);
8358 mono_mb_emit_stloc (mb, ex_local);
8360 leave_catch_pos = mono_mb_emit_branch (mb, CEE_LEAVE);
8362 /* } [endcatch] */
8363 clause_catch->handler_len = mono_mb_get_pos (mb) - clause_catch->handler_offset;
8365 /* finally { */
8366 clause_finally->try_len = mono_mb_get_label (mb) - clause_finally->try_offset;
8367 clause_finally->handler_offset = mono_mb_get_label (mb);
8369 if (!mono_threads_is_coop_enabled ()) {
8370 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8371 mono_mb_emit_byte (mb, CEE_MONO_JIT_DETACH);
8372 } else {
8373 /* mono_threads_detach_coop (); */
8374 mono_mb_emit_ldloc (mb, attach_cookie_local);
8375 mono_mb_emit_ldloc_addr (mb, attach_dummy_local);
8376 mono_mb_emit_icall (mb, mono_threads_detach_coop);
8379 /* if (ex != -1) */
8380 mono_mb_emit_ldloc (mb, ex_local);
8381 mono_mb_emit_icon (mb, -1);
8382 mono_mb_emit_byte (mb, CEE_CONV_U4);
8383 ex_m1_pos = mono_mb_emit_branch (mb, CEE_BEQ);
8385 /* mono_marshal_ftnptr_eh_callback (ex) */
8386 mono_mb_emit_ldloc (mb, ex_local);
8387 mono_mb_emit_icall (mb, mono_marshal_ftnptr_eh_callback);
8389 /* [ex == -1] */
8390 mono_mb_patch_branch (mb, ex_m1_pos);
8392 mono_mb_emit_byte (mb, CEE_ENDFINALLY);
8394 /* } [endfinally] */
8395 clause_finally->handler_len = mono_mb_get_pos (mb) - clause_finally->handler_offset;
8397 mono_mb_patch_branch (mb, leave_try_pos);
8398 mono_mb_patch_branch (mb, leave_catch_pos);
8400 /* return ret; */
8401 if (m->retobj_var) {
8402 mono_mb_emit_ldloc (mb, m->retobj_var);
8403 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8404 mono_mb_emit_op (mb, CEE_MONO_RETOBJ, m->retobj_class);
8406 else {
8407 if (!MONO_TYPE_IS_VOID(sig->ret))
8408 mono_mb_emit_ldloc (mb, 3);
8409 mono_mb_emit_byte (mb, CEE_RET);
8412 mono_mb_set_clauses (mb, 2, clauses);
8414 if (closed)
8415 g_free (sig);
8416 #endif
8419 static void
8420 mono_marshal_set_callconv_from_modopt (MonoMethod *method, MonoMethodSignature *csig)
8422 MonoMethodSignature *sig;
8423 int i;
8425 #ifdef TARGET_WIN32
8427 * Under windows, delegates passed to native code must use the STDCALL
8428 * calling convention.
8430 csig->call_convention = MONO_CALL_STDCALL;
8431 #endif
8433 sig = mono_method_signature (method);
8435 /* Change default calling convention if needed */
8436 /* Why is this a modopt ? */
8437 if (sig->ret && sig->ret->num_mods) {
8438 for (i = 0; i < sig->ret->num_mods; ++i) {
8439 MonoError error;
8440 MonoClass *cmod_class = mono_class_get_checked (method->klass->image, sig->ret->modifiers [i].token, &error);
8441 g_assert (mono_error_ok (&error));
8442 if ((cmod_class->image == mono_defaults.corlib) && !strcmp (cmod_class->name_space, "System.Runtime.CompilerServices")) {
8443 if (!strcmp (cmod_class->name, "CallConvCdecl"))
8444 csig->call_convention = MONO_CALL_C;
8445 else if (!strcmp (cmod_class->name, "CallConvStdcall"))
8446 csig->call_convention = MONO_CALL_STDCALL;
8447 else if (!strcmp (cmod_class->name, "CallConvFastcall"))
8448 csig->call_convention = MONO_CALL_FASTCALL;
8449 else if (!strcmp (cmod_class->name, "CallConvThiscall"))
8450 csig->call_convention = MONO_CALL_THISCALL;
8457 * generates IL code to call managed methods from unmanaged code
8458 * If target_handle==0, the wrapper info will be a WrapperInfo structure.
8460 MonoMethod *
8461 mono_marshal_get_managed_wrapper (MonoMethod *method, MonoClass *delegate_klass, uint32_t target_handle)
8463 MonoError error;
8464 MonoMethodSignature *sig, *csig, *invoke_sig;
8465 MonoMethodBuilder *mb;
8466 MonoMethod *res, *invoke;
8467 MonoMarshalSpec **mspecs;
8468 MonoMethodPInvoke piinfo;
8469 GHashTable *cache;
8470 int i;
8471 EmitMarshalContext m;
8473 g_assert (method != NULL);
8474 g_assert (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL));
8477 * FIXME: Should cache the method+delegate type pair, since the same method
8478 * could be called with different delegates, thus different marshalling
8479 * options.
8481 cache = get_cache (&mono_method_get_wrapper_cache (method)->managed_wrapper_cache, mono_aligned_addr_hash, NULL);
8483 if (!target_handle && (res = mono_marshal_find_in_cache (cache, method)))
8484 return res;
8486 invoke = mono_get_delegate_invoke (delegate_klass);
8487 invoke_sig = mono_method_signature (invoke);
8489 mspecs = g_new0 (MonoMarshalSpec*, mono_method_signature (invoke)->param_count + 1);
8490 mono_method_get_marshal_info (invoke, mspecs);
8492 sig = mono_method_signature (method);
8494 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
8496 /*the target gchandle must be the first entry after size and the wrapper itself.*/
8497 mono_mb_add_data (mb, GUINT_TO_POINTER (target_handle));
8499 /* we copy the signature, so that we can modify it */
8500 if (target_handle)
8501 /* Need to free this later */
8502 csig = mono_metadata_signature_dup (invoke_sig);
8503 else
8504 csig = mono_metadata_signature_dup_full (method->klass->image, invoke_sig);
8505 csig->hasthis = 0;
8506 csig->pinvoke = 1;
8508 memset (&m, 0, sizeof (m));
8509 m.mb = mb;
8510 m.sig = sig;
8511 m.piinfo = NULL;
8512 m.retobj_var = 0;
8513 m.csig = csig;
8514 m.image = method->klass->image;
8516 mono_marshal_set_callconv_from_modopt (invoke, csig);
8518 /* The attribute is only available in Net 2.0 */
8519 if (mono_class_try_get_unmanaged_function_pointer_attribute_class ()) {
8520 MonoCustomAttrInfo *cinfo;
8521 MonoCustomAttrEntry *attr;
8524 * The pinvoke attributes are stored in a real custom attribute. Obtain the
8525 * contents of the attribute without constructing it, as that might not be
8526 * possible when running in cross-compiling mode.
8528 cinfo = mono_custom_attrs_from_class_checked (delegate_klass, &error);
8529 mono_error_assert_ok (&error);
8530 attr = NULL;
8531 if (cinfo) {
8532 for (i = 0; i < cinfo->num_attrs; ++i) {
8533 MonoClass *ctor_class = cinfo->attrs [i].ctor->klass;
8534 if (mono_class_has_parent (ctor_class, mono_class_try_get_unmanaged_function_pointer_attribute_class ())) {
8535 attr = &cinfo->attrs [i];
8536 break;
8540 if (attr) {
8541 MonoArray *typed_args, *named_args;
8542 CattrNamedArg *arginfo;
8543 MonoObject *o;
8544 gint32 call_conv;
8545 gint32 charset = 0;
8546 MonoBoolean set_last_error = 0;
8547 MonoError error;
8549 mono_reflection_create_custom_attr_data_args (mono_defaults.corlib, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
8550 g_assert (mono_error_ok (&error));
8551 g_assert (mono_array_length (typed_args) == 1);
8553 /* typed args */
8554 o = mono_array_get (typed_args, MonoObject*, 0);
8555 call_conv = *(gint32*)mono_object_unbox (o);
8557 /* named args */
8558 for (i = 0; i < mono_array_length (named_args); ++i) {
8559 CattrNamedArg *narg = &arginfo [i];
8561 o = mono_array_get (named_args, MonoObject*, i);
8563 g_assert (narg->field);
8564 if (!strcmp (narg->field->name, "CharSet")) {
8565 charset = *(gint32*)mono_object_unbox (o);
8566 } else if (!strcmp (narg->field->name, "SetLastError")) {
8567 set_last_error = *(MonoBoolean*)mono_object_unbox (o);
8568 } else if (!strcmp (narg->field->name, "BestFitMapping")) {
8569 // best_fit_mapping = *(MonoBoolean*)mono_object_unbox (o);
8570 } else if (!strcmp (narg->field->name, "ThrowOnUnmappableChar")) {
8571 // throw_on_unmappable = *(MonoBoolean*)mono_object_unbox (o);
8572 } else {
8573 g_assert_not_reached ();
8577 g_free (arginfo);
8579 memset (&piinfo, 0, sizeof (piinfo));
8580 m.piinfo = &piinfo;
8581 piinfo.piflags = (call_conv << 8) | (charset ? (charset - 1) * 2 : 1) | set_last_error;
8583 csig->call_convention = call_conv - 1;
8586 if (cinfo && !cinfo->cached)
8587 mono_custom_attrs_free (cinfo);
8590 mono_marshal_emit_managed_wrapper (mb, invoke_sig, mspecs, &m, method, target_handle);
8592 if (!target_handle) {
8593 WrapperInfo *info;
8595 // FIXME: Associate it with the method+delegate_klass pair
8596 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
8597 info->d.native_to_managed.method = method;
8598 info->d.native_to_managed.klass = delegate_klass;
8600 res = mono_mb_create_and_cache_full (cache, method,
8601 mb, csig, sig->param_count + 16,
8602 info, NULL);
8603 } else {
8604 #ifndef DISABLE_JIT
8605 mb->dynamic = TRUE;
8606 #endif
8607 res = mono_mb_create (mb, csig, sig->param_count + 16, NULL);
8609 mono_mb_free (mb);
8611 for (i = mono_method_signature (invoke)->param_count; i >= 0; i--)
8612 if (mspecs [i])
8613 mono_metadata_free_marshal_spec (mspecs [i]);
8614 g_free (mspecs);
8616 /* mono_method_print_code (res); */
8618 return res;
8621 gpointer
8622 mono_marshal_get_vtfixup_ftnptr (MonoImage *image, guint32 token, guint16 type)
8624 MonoError error;
8625 MonoMethod *method;
8626 MonoMethodSignature *sig;
8627 MonoMethodBuilder *mb;
8628 int i, param_count;
8630 g_assert (token);
8632 method = mono_get_method_checked (image, token, NULL, NULL, &error);
8633 if (!method)
8634 g_error ("Could not load vtfixup token 0x%x due to %s", token, mono_error_get_message (&error));
8635 g_assert (method);
8637 if (type & (VTFIXUP_TYPE_FROM_UNMANAGED | VTFIXUP_TYPE_FROM_UNMANAGED_RETAIN_APPDOMAIN)) {
8638 MonoMethodSignature *csig;
8639 MonoMarshalSpec **mspecs;
8640 EmitMarshalContext m;
8642 sig = mono_method_signature (method);
8643 g_assert (!sig->hasthis);
8645 mspecs = g_new0 (MonoMarshalSpec*, sig->param_count + 1);
8646 mono_method_get_marshal_info (method, mspecs);
8648 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
8649 csig = mono_metadata_signature_dup_full (image, sig);
8650 csig->hasthis = 0;
8651 csig->pinvoke = 1;
8653 memset (&m, 0, sizeof (m));
8654 m.mb = mb;
8655 m.sig = sig;
8656 m.piinfo = NULL;
8657 m.retobj_var = 0;
8658 m.csig = csig;
8659 m.image = image;
8661 mono_marshal_set_callconv_from_modopt (method, csig);
8663 /* FIXME: Implement VTFIXUP_TYPE_FROM_UNMANAGED_RETAIN_APPDOMAIN. */
8665 mono_marshal_emit_managed_wrapper (mb, sig, mspecs, &m, method, 0);
8667 #ifndef DISABLE_JIT
8668 mb->dynamic = TRUE;
8669 #endif
8670 method = mono_mb_create (mb, csig, sig->param_count + 16, NULL);
8671 mono_mb_free (mb);
8673 for (i = sig->param_count; i >= 0; i--)
8674 if (mspecs [i])
8675 mono_metadata_free_marshal_spec (mspecs [i]);
8676 g_free (mspecs);
8678 gpointer compiled_ptr = mono_compile_method_checked (method, &error);
8679 mono_error_assert_ok (&error);
8680 return compiled_ptr;
8683 sig = mono_method_signature (method);
8684 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_MANAGED);
8686 param_count = sig->param_count + sig->hasthis;
8687 #ifndef DISABLE_JIT
8688 for (i = 0; i < param_count; i++)
8689 mono_mb_emit_ldarg (mb, i);
8691 if (type & VTFIXUP_TYPE_CALL_MOST_DERIVED)
8692 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
8693 else
8694 mono_mb_emit_op (mb, CEE_CALL, method);
8695 mono_mb_emit_byte (mb, CEE_RET);
8697 mb->dynamic = TRUE;
8698 #endif
8700 method = mono_mb_create (mb, sig, param_count, NULL);
8701 mono_mb_free (mb);
8703 gpointer compiled_ptr = mono_compile_method_checked (method, &error);
8704 mono_error_assert_ok (&error);
8705 return compiled_ptr;
8708 #ifndef DISABLE_JIT
8711 * The code directly following this is the cache hit, value positive branch
8713 * This function takes a new method builder with 0 locals and adds two locals
8714 * to create multiple out-branches and the fall through state of having the object
8715 * on the stack after a cache miss
8717 static void
8718 generate_check_cache (int obj_arg_position, int class_arg_position, int cache_arg_position, // In-parameters
8719 int *null_obj, int *cache_hit_neg, int *cache_hit_pos, // Out-parameters
8720 MonoMethodBuilder *mb)
8722 int cache_miss_pos;
8724 /* allocate local 0 (pointer) obj_vtable */
8725 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8726 /* allocate local 1 (pointer) cached_vtable */
8727 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8729 /*if (!obj)*/
8730 mono_mb_emit_ldarg (mb, obj_arg_position);
8731 *null_obj = mono_mb_emit_branch (mb, CEE_BRFALSE);
8733 /*obj_vtable = obj->vtable;*/
8734 mono_mb_emit_ldarg (mb, obj_arg_position);
8735 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
8736 mono_mb_emit_byte (mb, CEE_LDIND_I);
8737 mono_mb_emit_stloc (mb, 0);
8739 /* cached_vtable = *cache*/
8740 mono_mb_emit_ldarg (mb, cache_arg_position);
8741 mono_mb_emit_byte (mb, CEE_LDIND_I);
8742 mono_mb_emit_stloc (mb, 1);
8744 mono_mb_emit_ldloc (mb, 1);
8745 mono_mb_emit_byte (mb, CEE_LDC_I4);
8746 mono_mb_emit_i4 (mb, ~0x1);
8747 mono_mb_emit_byte (mb, CEE_CONV_I);
8748 mono_mb_emit_byte (mb, CEE_AND);
8749 mono_mb_emit_ldloc (mb, 0);
8750 /*if ((cached_vtable & ~0x1)== obj_vtable)*/
8751 cache_miss_pos = mono_mb_emit_branch (mb, CEE_BNE_UN);
8753 /*return (cached_vtable & 0x1) ? NULL : obj;*/
8754 mono_mb_emit_ldloc (mb, 1);
8755 mono_mb_emit_byte(mb, CEE_LDC_I4_1);
8756 mono_mb_emit_byte (mb, CEE_CONV_U);
8757 mono_mb_emit_byte (mb, CEE_AND);
8758 *cache_hit_neg = mono_mb_emit_branch (mb, CEE_BRTRUE);
8759 *cache_hit_pos = mono_mb_emit_branch (mb, CEE_BR);
8761 // slow path
8762 mono_mb_patch_branch (mb, cache_miss_pos);
8764 // if isinst
8765 mono_mb_emit_ldarg (mb, obj_arg_position);
8766 mono_mb_emit_ldarg (mb, class_arg_position);
8767 mono_mb_emit_ldarg (mb, cache_arg_position);
8768 mono_mb_emit_icall (mb, mono_marshal_isinst_with_cache);
8771 #endif /* DISABLE_JIT */
8774 * This does the equivalent of mono_object_castclass_with_cache.
8776 MonoMethod *
8777 mono_marshal_get_castclass_with_cache (void)
8779 static MonoMethod *cached;
8780 MonoMethod *res;
8781 MonoMethodBuilder *mb;
8782 MonoMethodSignature *sig;
8783 int return_null_pos, positive_cache_hit_pos, negative_cache_hit_pos, invalid_cast_pos;
8784 WrapperInfo *info;
8786 const int obj_arg_position = 0;
8787 const int class_arg_position = 1;
8788 const int cache_arg_position = 2;
8790 if (cached)
8791 return cached;
8793 mb = mono_mb_new (mono_defaults.object_class, "__castclass_with_cache", MONO_WRAPPER_CASTCLASS);
8794 sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
8795 sig->params [obj_arg_position] = &mono_defaults.object_class->byval_arg;
8796 sig->params [class_arg_position] = &mono_defaults.int_class->byval_arg;
8797 sig->params [cache_arg_position] = &mono_defaults.int_class->byval_arg;
8798 sig->ret = &mono_defaults.object_class->byval_arg;
8799 sig->pinvoke = 0;
8801 #ifndef DISABLE_JIT
8802 generate_check_cache (obj_arg_position, class_arg_position, cache_arg_position,
8803 &return_null_pos, &negative_cache_hit_pos, &positive_cache_hit_pos, mb);
8804 invalid_cast_pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
8806 /*return obj;*/
8807 mono_mb_patch_branch (mb, positive_cache_hit_pos);
8808 mono_mb_emit_ldarg (mb, obj_arg_position);
8809 mono_mb_emit_byte (mb, CEE_RET);
8811 /*fails*/
8812 mono_mb_patch_branch (mb, negative_cache_hit_pos);
8813 mono_mb_patch_branch (mb, invalid_cast_pos);
8814 mono_mb_emit_exception (mb, "InvalidCastException", NULL);
8816 /*return null*/
8817 mono_mb_patch_branch (mb, return_null_pos);
8818 mono_mb_emit_byte (mb, CEE_LDNULL);
8819 mono_mb_emit_byte (mb, CEE_RET);
8820 #endif /* DISABLE_JIT */
8822 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE);
8823 res = mono_mb_create (mb, sig, 8, info);
8824 STORE_STORE_FENCE;
8826 if (InterlockedCompareExchangePointer ((volatile gpointer *)&cached, res, NULL)) {
8827 mono_free_method (res);
8828 mono_metadata_free_method_signature (sig);
8830 mono_mb_free (mb);
8832 return cached;
8835 /* this is an icall */
8836 static MonoObject *
8837 mono_marshal_isinst_with_cache (MonoObject *obj, MonoClass *klass, uintptr_t *cache)
8839 MonoError error;
8840 MonoObject *isinst = mono_object_isinst_checked (obj, klass, &error);
8841 if (mono_error_set_pending_exception (&error))
8842 return NULL;
8844 #ifndef DISABLE_REMOTING
8845 if (obj->vtable->klass == mono_defaults.transparent_proxy_class)
8846 return isinst;
8847 #endif
8849 uintptr_t cache_update = (uintptr_t)obj->vtable;
8850 if (!isinst)
8851 cache_update = cache_update | 0x1;
8853 *cache = cache_update;
8855 return isinst;
8859 * This does the equivalent of mono_object_isinst_with_cache.
8861 MonoMethod *
8862 mono_marshal_get_isinst_with_cache (void)
8864 static MonoMethod *cached;
8865 MonoMethod *res;
8866 MonoMethodBuilder *mb;
8867 MonoMethodSignature *sig;
8868 int return_null_pos, positive_cache_hit_pos, negative_cache_hit_pos;
8869 WrapperInfo *info;
8871 const int obj_arg_position = 0;
8872 const int class_arg_position = 1;
8873 const int cache_arg_position = 2;
8875 if (cached)
8876 return cached;
8878 mb = mono_mb_new (mono_defaults.object_class, "__isinst_with_cache", MONO_WRAPPER_CASTCLASS);
8879 sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
8880 // The object
8881 sig->params [obj_arg_position] = &mono_defaults.object_class->byval_arg;
8882 // The class
8883 sig->params [class_arg_position] = &mono_defaults.int_class->byval_arg;
8884 // The cache
8885 sig->params [cache_arg_position] = &mono_defaults.int_class->byval_arg;
8886 sig->ret = &mono_defaults.object_class->byval_arg;
8887 sig->pinvoke = 0;
8889 #ifndef DISABLE_JIT
8890 generate_check_cache (obj_arg_position, class_arg_position, cache_arg_position,
8891 &return_null_pos, &negative_cache_hit_pos, &positive_cache_hit_pos, mb);
8892 // Return the object gotten via the slow path.
8893 mono_mb_emit_byte (mb, CEE_RET);
8895 // return NULL;
8896 mono_mb_patch_branch (mb, negative_cache_hit_pos);
8897 mono_mb_patch_branch (mb, return_null_pos);
8898 mono_mb_emit_byte (mb, CEE_LDNULL);
8899 mono_mb_emit_byte (mb, CEE_RET);
8901 // return obj
8902 mono_mb_patch_branch (mb, positive_cache_hit_pos);
8903 mono_mb_emit_ldarg (mb, obj_arg_position);
8904 mono_mb_emit_byte (mb, CEE_RET);
8905 #endif
8907 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ISINST_WITH_CACHE);
8908 res = mono_mb_create (mb, sig, 8, info);
8909 STORE_STORE_FENCE;
8911 if (InterlockedCompareExchangePointer ((volatile gpointer *)&cached, res, NULL)) {
8912 mono_free_method (res);
8913 mono_metadata_free_method_signature (sig);
8915 mono_mb_free (mb);
8917 return cached;
8921 * mono_marshal_get_isinst:
8922 * @klass: the type of the field
8924 * This method generates a function which can be used to check if an object is
8925 * an instance of the given type, icluding the case where the object is a proxy.
8926 * The generated function has the following signature:
8927 * MonoObject* __isinst_wrapper_ (MonoObject *obj)
8929 MonoMethod *
8930 mono_marshal_get_isinst (MonoClass *klass)
8932 static MonoMethodSignature *isint_sig = NULL;
8933 GHashTable *cache;
8934 MonoMethod *res;
8935 WrapperInfo *info;
8936 int pos_was_ok, pos_end;
8937 #ifndef DISABLE_REMOTING
8938 int pos_end2, pos_failed;
8939 #endif
8940 char *name;
8941 MonoMethodBuilder *mb;
8943 cache = get_cache (&klass->image->isinst_cache, mono_aligned_addr_hash, NULL);
8944 if ((res = mono_marshal_find_in_cache (cache, klass)))
8945 return res;
8947 if (!isint_sig) {
8948 isint_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
8949 isint_sig->params [0] = &mono_defaults.object_class->byval_arg;
8950 isint_sig->ret = &mono_defaults.object_class->byval_arg;
8951 isint_sig->pinvoke = 0;
8954 name = g_strdup_printf ("__isinst_wrapper_%s", klass->name);
8955 mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_ISINST);
8956 g_free (name);
8958 mb->method->save_lmf = 1;
8960 #ifndef DISABLE_JIT
8961 /* check if the object is a proxy that needs special cast */
8962 mono_mb_emit_ldarg (mb, 0);
8963 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8964 mono_mb_emit_op (mb, CEE_MONO_CISINST, klass);
8966 /* The result of MONO_CISINST can be:
8967 0) the type check succeeded
8968 1) the type check did not succeed
8969 2) a CanCastTo call is needed */
8970 #ifndef DISABLE_REMOTING
8971 mono_mb_emit_byte (mb, CEE_DUP);
8972 pos_was_ok = mono_mb_emit_branch (mb, CEE_BRFALSE);
8974 mono_mb_emit_byte (mb, CEE_LDC_I4_2);
8975 pos_failed = mono_mb_emit_branch (mb, CEE_BNE_UN);
8977 /* get the real proxy from the transparent proxy*/
8979 mono_mb_emit_ldarg (mb, 0);
8980 mono_mb_emit_managed_call (mb, mono_marshal_get_proxy_cancast (klass), NULL);
8981 pos_end = mono_mb_emit_branch (mb, CEE_BR);
8983 /* fail */
8985 mono_mb_patch_branch (mb, pos_failed);
8986 mono_mb_emit_byte (mb, CEE_LDNULL);
8987 pos_end2 = mono_mb_emit_branch (mb, CEE_BR);
8989 /* success */
8991 mono_mb_patch_branch (mb, pos_was_ok);
8992 mono_mb_emit_byte (mb, CEE_POP);
8993 mono_mb_emit_ldarg (mb, 0);
8995 /* the end */
8997 mono_mb_patch_branch (mb, pos_end);
8998 mono_mb_patch_branch (mb, pos_end2);
8999 mono_mb_emit_byte (mb, CEE_RET);
9000 #else
9001 pos_was_ok = mono_mb_emit_branch (mb, CEE_BRFALSE);
9003 /* fail */
9005 mono_mb_emit_byte (mb, CEE_LDNULL);
9006 pos_end = mono_mb_emit_branch (mb, CEE_BR);
9008 /* success */
9010 mono_mb_patch_branch (mb, pos_was_ok);
9011 mono_mb_emit_ldarg (mb, 0);
9013 /* the end */
9015 mono_mb_patch_branch (mb, pos_end);
9016 mono_mb_emit_byte (mb, CEE_RET);
9017 #endif /* DISABLE_REMOTING */
9018 #endif /* DISABLE_JIT */
9020 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
9021 info->d.proxy.klass = klass;
9022 res = mono_mb_create_and_cache_full (cache, klass, mb, isint_sig, isint_sig->param_count + 16, info, NULL);
9023 mono_mb_free (mb);
9025 return res;
9029 * mono_marshal_get_castclass:
9030 * @klass: the type of the field
9032 * This method generates a function which can be used to cast an object to
9033 * an instance of the given type, icluding the case where the object is a proxy.
9034 * The generated function has the following signature:
9035 * MonoObject* __castclass_wrapper_ (MonoObject *obj)
9037 MonoMethod *
9038 mono_marshal_get_castclass (MonoClass *klass)
9040 static MonoMethodSignature *castclass_sig = NULL;
9041 GHashTable *cache;
9042 MonoMethod *res;
9043 #ifndef DISABLE_REMOTING
9044 int pos_was_ok, pos_was_ok2;
9045 #endif
9046 char *name;
9047 MonoMethodBuilder *mb;
9048 WrapperInfo *info;
9050 cache = get_cache (&klass->image->castclass_cache, mono_aligned_addr_hash, NULL);
9051 if ((res = mono_marshal_find_in_cache (cache, klass)))
9052 return res;
9054 if (!castclass_sig) {
9055 castclass_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
9056 castclass_sig->params [0] = &mono_defaults.object_class->byval_arg;
9057 castclass_sig->ret = &mono_defaults.object_class->byval_arg;
9058 castclass_sig->pinvoke = 0;
9061 name = g_strdup_printf ("__castclass_wrapper_%s", klass->name);
9062 mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_CASTCLASS);
9063 g_free (name);
9065 mb->method->save_lmf = 1;
9067 #ifndef DISABLE_JIT
9068 /* check if the object is a proxy that needs special cast */
9069 mono_mb_emit_ldarg (mb, 0);
9070 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
9071 mono_mb_emit_op (mb, CEE_MONO_CCASTCLASS, klass);
9073 /* The result of MONO_CCASTCLASS can be:
9074 0) the cast is valid
9075 1) cast of unknown proxy type
9076 or an exception if the cast is is invalid
9078 #ifndef DISABLE_REMOTING
9079 pos_was_ok = mono_mb_emit_branch (mb, CEE_BRFALSE);
9081 /* get the real proxy from the transparent proxy*/
9083 mono_mb_emit_ldarg (mb, 0);
9084 mono_mb_emit_managed_call (mb, mono_marshal_get_proxy_cancast (klass), NULL);
9085 pos_was_ok2 = mono_mb_emit_branch (mb, CEE_BRTRUE);
9087 /* fail */
9088 mono_mb_emit_exception (mb, "InvalidCastException", NULL);
9090 /* success */
9091 mono_mb_patch_branch (mb, pos_was_ok);
9092 mono_mb_patch_branch (mb, pos_was_ok2);
9093 #else
9094 /* MONO_CCASTCLASS leaves an int in the stack with the result, pop it. */
9095 mono_mb_emit_byte (mb, CEE_POP);
9096 #endif /* DISABLE_REMOTING */
9098 mono_mb_emit_ldarg (mb, 0);
9100 /* the end */
9101 mono_mb_emit_byte (mb, CEE_RET);
9102 #endif /* DISABLE_JIT */
9104 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
9106 res = mono_mb_create_and_cache_full (cache, klass, mb, castclass_sig, castclass_sig->param_count + 16,
9107 info, NULL);
9108 mono_mb_free (mb);
9110 return res;
9114 * mono_marshal_get_struct_to_ptr:
9115 * @klass:
9117 * generates IL code for StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld)
9119 MonoMethod *
9120 mono_marshal_get_struct_to_ptr (MonoClass *klass)
9122 MonoMethodBuilder *mb;
9123 static MonoMethod *stoptr = NULL;
9124 MonoMethod *res;
9125 WrapperInfo *info;
9127 g_assert (klass != NULL);
9129 mono_marshal_load_type_info (klass);
9131 MonoMarshalType *marshal_info = mono_class_get_marshal_info (klass);
9132 if (marshal_info->str_to_ptr)
9133 return marshal_info->str_to_ptr;
9135 if (!stoptr)
9136 stoptr = mono_class_get_method_from_name (mono_defaults.marshal_class, "StructureToPtr", 3);
9137 g_assert (stoptr);
9139 mb = mono_mb_new (klass, stoptr->name, MONO_WRAPPER_UNKNOWN);
9141 #ifndef DISABLE_JIT
9142 if (klass->blittable) {
9143 mono_mb_emit_byte (mb, CEE_LDARG_1);
9144 mono_mb_emit_byte (mb, CEE_LDARG_0);
9145 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
9146 mono_mb_emit_icon (mb, mono_class_value_size (klass, NULL));
9147 mono_mb_emit_byte (mb, CEE_PREFIX1);
9148 mono_mb_emit_byte (mb, CEE_CPBLK);
9149 } else {
9151 /* allocate local 0 (pointer) src_ptr */
9152 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9153 /* allocate local 1 (pointer) dst_ptr */
9154 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9155 /* allocate local 2 (boolean) delete_old */
9156 mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
9157 mono_mb_emit_byte (mb, CEE_LDARG_2);
9158 mono_mb_emit_stloc (mb, 2);
9160 /* initialize src_ptr to point to the start of object data */
9161 mono_mb_emit_byte (mb, CEE_LDARG_0);
9162 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
9163 mono_mb_emit_stloc (mb, 0);
9165 /* initialize dst_ptr */
9166 mono_mb_emit_byte (mb, CEE_LDARG_1);
9167 mono_mb_emit_stloc (mb, 1);
9169 emit_struct_conv (mb, klass, FALSE);
9172 mono_mb_emit_byte (mb, CEE_RET);
9173 #endif
9174 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_STRUCTURE_TO_PTR);
9175 res = mono_mb_create (mb, mono_signature_no_pinvoke (stoptr), 0, info);
9176 mono_mb_free (mb);
9178 mono_marshal_lock ();
9179 if (!marshal_info->str_to_ptr)
9180 marshal_info->str_to_ptr = res;
9181 else
9182 res = marshal_info->str_to_ptr;
9183 mono_marshal_unlock ();
9184 return res;
9188 * mono_marshal_get_ptr_to_struct:
9189 * @klass:
9191 * generates IL code for PtrToStructure (IntPtr src, object structure)
9193 MonoMethod *
9194 mono_marshal_get_ptr_to_struct (MonoClass *klass)
9196 MonoMethodBuilder *mb;
9197 static MonoMethodSignature *ptostr = NULL;
9198 MonoMethod *res;
9199 WrapperInfo *info;
9201 g_assert (klass != NULL);
9203 mono_marshal_load_type_info (klass);
9205 MonoMarshalType *marshal_info = mono_class_get_marshal_info (klass);
9206 if (marshal_info->ptr_to_str)
9207 return marshal_info->ptr_to_str;
9209 if (!ptostr) {
9210 MonoMethodSignature *sig;
9212 /* Create the signature corresponding to
9213 static void PtrToStructure (IntPtr ptr, object structure);
9214 defined in class/corlib/System.Runtime.InteropServices/Marshal.cs */
9215 sig = mono_create_icall_signature ("void ptr object");
9216 sig = mono_metadata_signature_dup_full (mono_defaults.corlib, sig);
9217 sig->pinvoke = 0;
9218 mono_memory_barrier ();
9219 ptostr = sig;
9222 mb = mono_mb_new (klass, "PtrToStructure", MONO_WRAPPER_UNKNOWN);
9224 #ifndef DISABLE_JIT
9225 if (klass->blittable) {
9226 mono_mb_emit_byte (mb, CEE_LDARG_1);
9227 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
9228 mono_mb_emit_byte (mb, CEE_LDARG_0);
9229 mono_mb_emit_icon (mb, mono_class_value_size (klass, NULL));
9230 mono_mb_emit_byte (mb, CEE_PREFIX1);
9231 mono_mb_emit_byte (mb, CEE_CPBLK);
9232 } else {
9234 /* allocate local 0 (pointer) src_ptr */
9235 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9236 /* allocate local 1 (pointer) dst_ptr */
9237 mono_mb_add_local (mb, &klass->this_arg);
9239 /* initialize src_ptr to point to the start of object data */
9240 mono_mb_emit_byte (mb, CEE_LDARG_0);
9241 mono_mb_emit_stloc (mb, 0);
9243 /* initialize dst_ptr */
9244 mono_mb_emit_byte (mb, CEE_LDARG_1);
9245 mono_mb_emit_op (mb, CEE_UNBOX, klass);
9246 mono_mb_emit_stloc (mb, 1);
9248 emit_struct_conv (mb, klass, TRUE);
9251 mono_mb_emit_byte (mb, CEE_RET);
9252 #endif
9253 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_PTR_TO_STRUCTURE);
9254 res = mono_mb_create (mb, ptostr, 0, info);
9255 mono_mb_free (mb);
9257 mono_marshal_lock ();
9258 if (!marshal_info->ptr_to_str)
9259 marshal_info->ptr_to_str = res;
9260 else
9261 res = marshal_info->ptr_to_str;
9262 mono_marshal_unlock ();
9263 return res;
9267 * Return a dummy wrapper for METHOD which is called by synchronized wrappers.
9268 * This is used to avoid infinite recursion since it is hard to determine where to
9269 * replace a method with its synchronized wrapper, and where not.
9270 * The runtime should execute METHOD instead of the wrapper.
9272 MonoMethod *
9273 mono_marshal_get_synchronized_inner_wrapper (MonoMethod *method)
9275 MonoMethodBuilder *mb;
9276 WrapperInfo *info;
9277 MonoMethodSignature *sig;
9278 MonoMethod *res;
9279 MonoGenericContext *ctx = NULL;
9280 MonoGenericContainer *container = NULL;
9282 if (method->is_inflated && !mono_method_get_context (method)->method_inst) {
9283 ctx = &((MonoMethodInflated*)method)->context;
9284 method = ((MonoMethodInflated*)method)->declaring;
9285 container = mono_method_get_generic_container (method);
9286 if (!container)
9287 container = mono_class_try_get_generic_container (method->klass); //FIXME is this a case of a try?
9288 g_assert (container);
9291 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNKNOWN);
9292 #ifndef DISABLE_JIT
9293 mono_mb_emit_exception_full (mb, "System", "ExecutionEngineException", "Shouldn't be called.");
9294 mono_mb_emit_byte (mb, CEE_RET);
9295 #endif
9296 sig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
9298 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_SYNCHRONIZED_INNER);
9299 info->d.synchronized_inner.method = method;
9300 res = mono_mb_create (mb, sig, 0, info);
9301 mono_mb_free (mb);
9302 if (ctx) {
9303 MonoError error;
9304 res = mono_class_inflate_generic_method_checked (res, ctx, &error);
9305 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9307 return res;
9311 * generates IL code for the synchronized wrapper: the generated method
9312 * calls METHOD while locking 'this' or the parent type.
9314 MonoMethod *
9315 mono_marshal_get_synchronized_wrapper (MonoMethod *method)
9317 static MonoMethod *enter_method, *exit_method, *gettypefromhandle_method;
9318 MonoMethodSignature *sig;
9319 MonoExceptionClause *clause;
9320 MonoMethodBuilder *mb;
9321 MonoMethod *res;
9322 GHashTable *cache;
9323 WrapperInfo *info;
9324 int i, pos, pos2, this_local, taken_local, ret_local = 0;
9325 MonoGenericContext *ctx = NULL;
9326 MonoMethod *orig_method = NULL;
9327 MonoGenericContainer *container = NULL;
9329 g_assert (method);
9331 if (method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED)
9332 return method;
9334 /* FIXME: Support generic methods too */
9335 if (method->is_inflated && !mono_method_get_context (method)->method_inst) {
9336 orig_method = method;
9337 ctx = &((MonoMethodInflated*)method)->context;
9338 method = ((MonoMethodInflated*)method)->declaring;
9339 container = mono_method_get_generic_container (method);
9340 if (!container)
9341 container = mono_class_try_get_generic_container (method->klass); //FIXME is this a case of a try?
9342 g_assert (container);
9346 * Check cache
9348 if (ctx) {
9349 cache = get_cache (&((MonoMethodInflated*)orig_method)->owner->wrapper_caches.synchronized_cache, mono_aligned_addr_hash, NULL);
9350 res = check_generic_wrapper_cache (cache, orig_method, orig_method, method);
9351 if (res)
9352 return res;
9353 } else {
9354 cache = get_cache (&method->klass->image->wrapper_caches.synchronized_cache, mono_aligned_addr_hash, NULL);
9355 if ((res = mono_marshal_find_in_cache (cache, method)))
9356 return res;
9359 sig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
9360 sig->pinvoke = 0;
9362 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_SYNCHRONIZED);
9364 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
9365 info->d.synchronized.method = method;
9367 #ifndef DISABLE_JIT
9368 mb->skip_visibility = 1;
9369 /* result */
9370 if (!MONO_TYPE_IS_VOID (sig->ret))
9371 ret_local = mono_mb_add_local (mb, sig->ret);
9372 #endif
9374 if (method->klass->valuetype && !(method->flags & MONO_METHOD_ATTR_STATIC)) {
9375 /* FIXME Is this really the best way to signal an error here? Isn't this called much later after class setup? -AK */
9376 mono_class_set_type_load_failure (method->klass, "");
9377 #ifndef DISABLE_JIT
9378 /* This will throw the type load exception when the wrapper is compiled */
9379 mono_mb_emit_byte (mb, CEE_LDNULL);
9380 mono_mb_emit_op (mb, CEE_ISINST, method->klass);
9381 mono_mb_emit_byte (mb, CEE_POP);
9383 if (!MONO_TYPE_IS_VOID (sig->ret))
9384 mono_mb_emit_ldloc (mb, ret_local);
9385 mono_mb_emit_byte (mb, CEE_RET);
9386 #endif
9388 res = mono_mb_create_and_cache_full (cache, method,
9389 mb, sig, sig->param_count + 16, info, NULL);
9390 mono_mb_free (mb);
9392 return res;
9395 #ifndef DISABLE_JIT
9396 /* this */
9397 this_local = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
9398 taken_local = mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
9400 clause = (MonoExceptionClause *)mono_image_alloc0 (method->klass->image, sizeof (MonoExceptionClause));
9401 clause->flags = MONO_EXCEPTION_CLAUSE_FINALLY;
9402 #endif
9404 mono_marshal_lock ();
9406 if (!enter_method) {
9407 MonoMethodDesc *desc;
9409 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
9410 enter_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
9411 g_assert (enter_method);
9412 mono_method_desc_free (desc);
9414 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
9415 exit_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
9416 g_assert (exit_method);
9417 mono_method_desc_free (desc);
9419 desc = mono_method_desc_new ("Type:GetTypeFromHandle", FALSE);
9420 gettypefromhandle_method = mono_method_desc_search_in_class (desc, mono_defaults.systemtype_class);
9421 g_assert (gettypefromhandle_method);
9422 mono_method_desc_free (desc);
9425 mono_marshal_unlock ();
9427 #ifndef DISABLE_JIT
9428 /* Push this or the type object */
9429 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
9430 /* We have special handling for this in the JIT */
9431 int index = mono_mb_add_data (mb, method->klass);
9432 mono_mb_add_data (mb, mono_defaults.typehandle_class);
9433 mono_mb_emit_byte (mb, CEE_LDTOKEN);
9434 mono_mb_emit_i4 (mb, index);
9436 mono_mb_emit_managed_call (mb, gettypefromhandle_method, NULL);
9438 else
9439 mono_mb_emit_ldarg (mb, 0);
9440 mono_mb_emit_stloc (mb, this_local);
9442 /* Call Monitor::Enter() */
9443 mono_mb_emit_ldloc (mb, this_local);
9444 mono_mb_emit_ldloc_addr (mb, taken_local);
9445 mono_mb_emit_managed_call (mb, enter_method, NULL);
9447 clause->try_offset = mono_mb_get_label (mb);
9449 /* Call the method */
9450 if (sig->hasthis)
9451 mono_mb_emit_ldarg (mb, 0);
9452 for (i = 0; i < sig->param_count; i++)
9453 mono_mb_emit_ldarg (mb, i + (sig->hasthis == TRUE));
9455 if (ctx) {
9456 MonoError error;
9457 mono_mb_emit_managed_call (mb, mono_class_inflate_generic_method_checked (method, &container->context, &error), NULL);
9458 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9459 } else {
9460 mono_mb_emit_managed_call (mb, method, NULL);
9463 if (!MONO_TYPE_IS_VOID (sig->ret))
9464 mono_mb_emit_stloc (mb, ret_local);
9466 pos = mono_mb_emit_branch (mb, CEE_LEAVE);
9468 clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
9469 clause->handler_offset = mono_mb_get_label (mb);
9471 /* Call Monitor::Exit() if needed */
9472 mono_mb_emit_ldloc (mb, taken_local);
9473 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9474 mono_mb_emit_ldloc (mb, this_local);
9475 mono_mb_emit_managed_call (mb, exit_method, NULL);
9476 mono_mb_patch_branch (mb, pos2);
9477 mono_mb_emit_byte (mb, CEE_ENDFINALLY);
9479 clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
9481 mono_mb_patch_branch (mb, pos);
9482 if (!MONO_TYPE_IS_VOID (sig->ret))
9483 mono_mb_emit_ldloc (mb, ret_local);
9484 mono_mb_emit_byte (mb, CEE_RET);
9486 mono_mb_set_clauses (mb, 1, clause);
9487 #endif
9489 if (ctx) {
9490 MonoMethod *def;
9491 def = mono_mb_create_and_cache_full (cache, method, mb, sig, sig->param_count + 16, info, NULL);
9492 res = cache_generic_wrapper (cache, orig_method, def, ctx, orig_method);
9493 } else {
9494 res = mono_mb_create_and_cache_full (cache, method,
9495 mb, sig, sig->param_count + 16, info, NULL);
9497 mono_mb_free (mb);
9499 return res;
9504 * the returned method calls 'method' unboxing the this argument
9506 MonoMethod *
9507 mono_marshal_get_unbox_wrapper (MonoMethod *method)
9509 MonoMethodSignature *sig = mono_method_signature (method);
9510 int i;
9511 MonoMethodBuilder *mb;
9512 MonoMethod *res;
9513 GHashTable *cache;
9514 WrapperInfo *info;
9516 cache = get_cache (&mono_method_get_wrapper_cache (method)->unbox_wrapper_cache, mono_aligned_addr_hash, NULL);
9518 if ((res = mono_marshal_find_in_cache (cache, method)))
9519 return res;
9521 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNBOX);
9523 g_assert (sig->hasthis);
9525 #ifndef DISABLE_JIT
9526 mono_mb_emit_ldarg (mb, 0);
9527 mono_mb_emit_icon (mb, sizeof (MonoObject));
9528 mono_mb_emit_byte (mb, CEE_ADD);
9529 for (i = 0; i < sig->param_count; ++i)
9530 mono_mb_emit_ldarg (mb, i + 1);
9531 mono_mb_emit_managed_call (mb, method, NULL);
9532 mono_mb_emit_byte (mb, CEE_RET);
9533 #endif
9535 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
9536 info->d.unbox.method = method;
9538 res = mono_mb_create_and_cache_full (cache, method,
9539 mb, sig, sig->param_count + 16, info, NULL);
9540 mono_mb_free (mb);
9542 /* mono_method_print_code (res); */
9544 return res;
9547 enum {
9548 STELEMREF_OBJECT, /*no check at all*/
9549 STELEMREF_SEALED_CLASS, /*check vtable->klass->element_type */
9550 STELEMREF_CLASS, /*only the klass->parents check*/
9551 STELEMREF_INTERFACE, /*interfaces without variant generic arguments. */
9552 STELEMREF_COMPLEX, /*arrays, MBR or types with variant generic args - go straight to icalls*/
9553 STELEMREF_KIND_COUNT
9556 static const char *strelemref_wrapper_name[] = {
9557 "object", "sealed_class", "class", "interface", "complex"
9560 static gboolean
9561 is_monomorphic_array (MonoClass *klass)
9563 MonoClass *element_class;
9564 if (klass->rank != 1)
9565 return FALSE;
9567 element_class = klass->element_class;
9568 return mono_class_is_sealed (element_class) || element_class->valuetype;
9571 static int
9572 get_virtual_stelemref_kind (MonoClass *element_class)
9574 if (element_class == mono_defaults.object_class)
9575 return STELEMREF_OBJECT;
9576 if (is_monomorphic_array (element_class))
9577 return STELEMREF_SEALED_CLASS;
9578 /* Compressed interface bitmaps require code that is quite complex, so don't optimize for it. */
9579 if (MONO_CLASS_IS_INTERFACE (element_class) && !mono_class_has_variant_generic_params (element_class))
9580 #ifdef COMPRESSED_INTERFACE_BITMAP
9581 return STELEMREF_COMPLEX;
9582 #else
9583 return STELEMREF_INTERFACE;
9584 #endif
9585 /*Arrays are sealed but are covariant on their element type, We can't use any of the fast paths.*/
9586 if (mono_class_is_marshalbyref (element_class) || element_class->rank || mono_class_has_variant_generic_params (element_class))
9587 return STELEMREF_COMPLEX;
9588 if (mono_class_is_sealed (element_class))
9589 return STELEMREF_SEALED_CLASS;
9590 return STELEMREF_CLASS;
9593 #ifndef DISABLE_JIT
9595 static void
9596 load_array_element_address (MonoMethodBuilder *mb)
9598 mono_mb_emit_ldarg (mb, 0);
9599 mono_mb_emit_ldarg (mb, 1);
9600 mono_mb_emit_op (mb, CEE_LDELEMA, mono_defaults.object_class);
9603 static void
9604 load_array_class (MonoMethodBuilder *mb, int aklass)
9606 mono_mb_emit_ldarg (mb, 0);
9607 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9608 mono_mb_emit_byte (mb, CEE_LDIND_I);
9609 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
9610 mono_mb_emit_byte (mb, CEE_LDIND_I);
9611 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, element_class));
9612 mono_mb_emit_byte (mb, CEE_LDIND_I);
9613 mono_mb_emit_stloc (mb, aklass);
9616 static void
9617 load_value_class (MonoMethodBuilder *mb, int vklass)
9619 mono_mb_emit_ldarg (mb, 2);
9620 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9621 mono_mb_emit_byte (mb, CEE_LDIND_I);
9622 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
9623 mono_mb_emit_byte (mb, CEE_LDIND_I);
9624 mono_mb_emit_stloc (mb, vklass);
9626 #endif
9628 #if 0
9629 static void
9630 record_slot_vstore (MonoObject *array, size_t index, MonoObject *value)
9632 char *name = mono_type_get_full_name (array->vtable->klass->element_class);
9633 printf ("slow vstore of %s\n", name);
9634 g_free (name);
9636 #endif
9639 * TODO:
9640 * - Separate simple interfaces from variant interfaces or mbr types. This way we can avoid the icall for them.
9641 * - Emit a (new) mono bytecode that produces OP_COND_EXC_NE_UN to raise ArrayTypeMismatch
9642 * - Maybe mve some MonoClass field into the vtable to reduce the number of loads
9643 * - Add a case for arrays of arrays.
9645 static MonoMethod*
9646 get_virtual_stelemref_wrapper (int kind)
9648 static MonoMethod *cached_methods [STELEMREF_KIND_COUNT] = { NULL }; /*object iface sealed regular*/
9649 static MonoMethodSignature *signature;
9650 MonoMethodBuilder *mb;
9651 MonoMethod *res;
9652 char *name;
9653 const char *param_names [16];
9654 guint32 b1, b2, b3, b4;
9655 int aklass, vklass, vtable, uiid;
9656 int array_slot_addr;
9657 WrapperInfo *info;
9659 if (cached_methods [kind])
9660 return cached_methods [kind];
9662 name = g_strdup_printf ("virt_stelemref_%s", strelemref_wrapper_name [kind]);
9663 mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_STELEMREF);
9664 g_free (name);
9666 if (!signature) {
9667 MonoMethodSignature *sig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
9669 /* void this::stelemref (size_t idx, void* value) */
9670 sig->ret = &mono_defaults.void_class->byval_arg;
9671 sig->hasthis = TRUE;
9672 sig->params [0] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
9673 sig->params [1] = &mono_defaults.object_class->byval_arg;
9674 signature = sig;
9677 #ifndef DISABLE_JIT
9678 param_names [0] = "index";
9679 param_names [1] = "value";
9680 mono_mb_set_param_names (mb, param_names);
9682 /*For now simply call plain old stelemref*/
9683 switch (kind) {
9684 case STELEMREF_OBJECT:
9685 /* ldelema (implicit bound check) */
9686 load_array_element_address (mb);
9687 /* do_store */
9688 mono_mb_emit_ldarg (mb, 2);
9689 mono_mb_emit_byte (mb, CEE_STIND_REF);
9690 mono_mb_emit_byte (mb, CEE_RET);
9691 break;
9693 case STELEMREF_COMPLEX:
9695 <ldelema (bound check)>
9696 if (!value)
9697 goto store;
9698 if (!mono_object_isinst (value, aklass))
9699 goto do_exception;
9701 do_store:
9702 *array_slot_addr = value;
9704 do_exception:
9705 throw new ArrayTypeMismatchException ();
9708 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9709 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9711 #if 0
9713 /*Use this to debug/record stores that are going thru the slow path*/
9714 MonoMethodSignature *csig;
9715 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
9716 csig->ret = &mono_defaults.void_class->byval_arg;
9717 csig->params [0] = &mono_defaults.object_class->byval_arg;
9718 csig->params [1] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
9719 csig->params [2] = &mono_defaults.object_class->byval_arg;
9720 mono_mb_emit_ldarg (mb, 0);
9721 mono_mb_emit_ldarg (mb, 1);
9722 mono_mb_emit_ldarg (mb, 2);
9723 mono_mb_emit_native_call (mb, csig, record_slot_vstore);
9725 #endif
9727 /* ldelema (implicit bound check) */
9728 load_array_element_address (mb);
9729 mono_mb_emit_stloc (mb, array_slot_addr);
9731 /* if (!value) goto do_store */
9732 mono_mb_emit_ldarg (mb, 2);
9733 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9735 /* aklass = array->vtable->klass->element_class */
9736 load_array_class (mb, aklass);
9738 /*if (mono_object_isinst (value, aklass)) */
9739 mono_mb_emit_ldarg (mb, 2);
9740 mono_mb_emit_ldloc (mb, aklass);
9741 mono_mb_emit_icall (mb, mono_object_isinst_icall);
9742 b2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9744 /* do_store: */
9745 mono_mb_patch_branch (mb, b1);
9746 mono_mb_emit_ldloc (mb, array_slot_addr);
9747 mono_mb_emit_ldarg (mb, 2);
9748 mono_mb_emit_byte (mb, CEE_STIND_REF);
9749 mono_mb_emit_byte (mb, CEE_RET);
9751 /* do_exception: */
9752 mono_mb_patch_branch (mb, b2);
9754 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9755 break;
9757 case STELEMREF_SEALED_CLASS:
9759 <ldelema (bound check)>
9760 if (!value)
9761 goto store;
9763 aklass = array->vtable->klass->element_class;
9764 vklass = value->vtable->klass;
9766 if (vklass != aklass)
9767 goto do_exception;
9769 do_store:
9770 *array_slot_addr = value;
9772 do_exception:
9773 throw new ArrayTypeMismatchException ();
9775 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9776 vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9777 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9780 /* ldelema (implicit bound check) */
9781 load_array_element_address (mb);
9782 mono_mb_emit_stloc (mb, array_slot_addr);
9784 /* if (!value) goto do_store */
9785 mono_mb_emit_ldarg (mb, 2);
9786 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9788 /* aklass = array->vtable->klass->element_class */
9789 load_array_class (mb, aklass);
9791 /* vklass = value->vtable->klass */
9792 load_value_class (mb, vklass);
9794 /*if (vklass != aklass) goto do_exception; */
9795 mono_mb_emit_ldloc (mb, aklass);
9796 mono_mb_emit_ldloc (mb, vklass);
9797 b2 = mono_mb_emit_branch (mb, CEE_BNE_UN);
9799 /* do_store: */
9800 mono_mb_patch_branch (mb, b1);
9801 mono_mb_emit_ldloc (mb, array_slot_addr);
9802 mono_mb_emit_ldarg (mb, 2);
9803 mono_mb_emit_byte (mb, CEE_STIND_REF);
9804 mono_mb_emit_byte (mb, CEE_RET);
9806 /* do_exception: */
9807 mono_mb_patch_branch (mb, b2);
9808 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9809 break;
9811 case STELEMREF_CLASS:
9813 the method:
9814 <ldelema (bound check)>
9815 if (!value)
9816 goto do_store;
9818 aklass = array->vtable->klass->element_class;
9819 vklass = value->vtable->klass;
9821 if (vklass->idepth < aklass->idepth)
9822 goto do_exception;
9824 if (vklass->supertypes [aklass->idepth - 1] != aklass)
9825 goto do_exception;
9827 do_store:
9828 *array_slot_addr = value;
9829 return;
9831 long:
9832 throw new ArrayTypeMismatchException ();
9834 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9835 vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9836 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9838 /* ldelema (implicit bound check) */
9839 load_array_element_address (mb);
9840 mono_mb_emit_stloc (mb, array_slot_addr);
9842 /* if (!value) goto do_store */
9843 mono_mb_emit_ldarg (mb, 2);
9844 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9846 /* aklass = array->vtable->klass->element_class */
9847 load_array_class (mb, aklass);
9849 /* vklass = value->vtable->klass */
9850 load_value_class (mb, vklass);
9852 /*if (mono_object_isinst (value, aklass)) */
9853 mono_mb_emit_ldarg (mb, 2);
9854 mono_mb_emit_ldloc (mb, aklass);
9855 mono_mb_emit_icall (mb, mono_object_isinst_icall);
9856 b2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9858 /* if (vklass->idepth < aklass->idepth) goto failue */
9859 mono_mb_emit_ldloc (mb, vklass);
9860 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9861 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9863 mono_mb_emit_ldloc (mb, aklass);
9864 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9865 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9867 b3 = mono_mb_emit_branch (mb, CEE_BLT_UN);
9869 /* if (vklass->supertypes [aklass->idepth - 1] != aklass) goto failure */
9870 mono_mb_emit_ldloc (mb, vklass);
9871 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, supertypes));
9872 mono_mb_emit_byte (mb, CEE_LDIND_I);
9874 mono_mb_emit_ldloc (mb, aklass);
9875 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9876 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9877 mono_mb_emit_icon (mb, 1);
9878 mono_mb_emit_byte (mb, CEE_SUB);
9879 mono_mb_emit_icon (mb, sizeof (void*));
9880 mono_mb_emit_byte (mb, CEE_MUL);
9881 mono_mb_emit_byte (mb, CEE_ADD);
9882 mono_mb_emit_byte (mb, CEE_LDIND_I);
9884 mono_mb_emit_ldloc (mb, aklass);
9885 b4 = mono_mb_emit_branch (mb, CEE_BNE_UN);
9887 /* do_store: */
9888 mono_mb_patch_branch (mb, b1);
9889 mono_mb_emit_ldloc (mb, array_slot_addr);
9890 mono_mb_emit_ldarg (mb, 2);
9891 mono_mb_emit_byte (mb, CEE_STIND_REF);
9892 mono_mb_emit_byte (mb, CEE_RET);
9894 /* do_exception: */
9895 mono_mb_patch_branch (mb, b2);
9896 mono_mb_patch_branch (mb, b3);
9897 mono_mb_patch_branch (mb, b4);
9899 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9900 break;
9902 case STELEMREF_INTERFACE:
9903 /*Mono *klass;
9904 MonoVTable *vt;
9905 unsigned uiid;
9906 if (value == NULL)
9907 goto store;
9909 klass = array->obj.vtable->klass->element_class;
9910 vt = value->vtable;
9911 uiid = klass->interface_id;
9912 if (uiid > vt->max_interface_id)
9913 goto exception;
9914 if (!(vt->interface_bitmap [(uiid) >> 3] & (1 << ((uiid)&7))))
9915 goto exception;
9916 store:
9917 mono_array_setref (array, index, value);
9918 return;
9919 exception:
9920 mono_raise_exception (mono_get_exception_array_type_mismatch ());*/
9922 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9923 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9924 vtable = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9925 uiid = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
9927 /* ldelema (implicit bound check) */
9928 load_array_element_address (mb);
9929 mono_mb_emit_stloc (mb, array_slot_addr);
9931 /* if (!value) goto do_store */
9932 mono_mb_emit_ldarg (mb, 2);
9933 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9935 /* klass = array->vtable->klass->element_class */
9936 load_array_class (mb, aklass);
9938 /* vt = value->vtable */
9939 mono_mb_emit_ldarg (mb, 2);
9940 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9941 mono_mb_emit_byte (mb, CEE_LDIND_I);
9942 mono_mb_emit_stloc (mb, vtable);
9944 /* uiid = klass->interface_id; */
9945 mono_mb_emit_ldloc (mb, aklass);
9946 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, interface_id));
9947 mono_mb_emit_byte (mb, CEE_LDIND_U4);
9948 mono_mb_emit_stloc (mb, uiid);
9950 /*if (uiid > vt->max_interface_id)*/
9951 mono_mb_emit_ldloc (mb, uiid);
9952 mono_mb_emit_ldloc (mb, vtable);
9953 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, max_interface_id));
9954 mono_mb_emit_byte (mb, CEE_LDIND_U4);
9955 b2 = mono_mb_emit_branch (mb, CEE_BGT_UN);
9957 /* if (!(vt->interface_bitmap [(uiid) >> 3] & (1 << ((uiid)&7)))) */
9959 /*vt->interface_bitmap*/
9960 mono_mb_emit_ldloc (mb, vtable);
9961 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, interface_bitmap));
9962 mono_mb_emit_byte (mb, CEE_LDIND_I);
9964 /*uiid >> 3*/
9965 mono_mb_emit_ldloc (mb, uiid);
9966 mono_mb_emit_icon (mb, 3);
9967 mono_mb_emit_byte (mb, CEE_SHR_UN);
9969 /*vt->interface_bitmap [(uiid) >> 3]*/
9970 mono_mb_emit_byte (mb, CEE_ADD); /*interface_bitmap is a guint8 array*/
9971 mono_mb_emit_byte (mb, CEE_LDIND_U1);
9973 /*(1 << ((uiid)&7)))*/
9974 mono_mb_emit_icon (mb, 1);
9975 mono_mb_emit_ldloc (mb, uiid);
9976 mono_mb_emit_icon (mb, 7);
9977 mono_mb_emit_byte (mb, CEE_AND);
9978 mono_mb_emit_byte (mb, CEE_SHL);
9980 /*bitwise and the whole thing*/
9981 mono_mb_emit_byte (mb, CEE_AND);
9982 b3 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9984 /* do_store: */
9985 mono_mb_patch_branch (mb, b1);
9986 mono_mb_emit_ldloc (mb, array_slot_addr);
9987 mono_mb_emit_ldarg (mb, 2);
9988 mono_mb_emit_byte (mb, CEE_STIND_REF);
9989 mono_mb_emit_byte (mb, CEE_RET);
9991 /* do_exception: */
9992 mono_mb_patch_branch (mb, b2);
9993 mono_mb_patch_branch (mb, b3);
9994 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9995 break;
9997 default:
9998 mono_mb_emit_ldarg (mb, 0);
9999 mono_mb_emit_ldarg (mb, 1);
10000 mono_mb_emit_ldarg (mb, 2);
10001 mono_mb_emit_managed_call (mb, mono_marshal_get_stelemref (), NULL);
10002 mono_mb_emit_byte (mb, CEE_RET);
10003 g_assert (0);
10005 #endif /* DISABLE_JIT */
10006 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_VIRTUAL_STELEMREF);
10007 info->d.virtual_stelemref.kind = kind;
10008 res = mono_mb_create (mb, signature, 4, info);
10009 res->flags |= METHOD_ATTRIBUTE_VIRTUAL;
10011 mono_marshal_lock ();
10012 if (!cached_methods [kind]) {
10013 cached_methods [kind] = res;
10014 mono_marshal_unlock ();
10015 } else {
10016 mono_marshal_unlock ();
10017 mono_free_method (res);
10020 mono_mb_free (mb);
10021 return cached_methods [kind];
10024 MonoMethod*
10025 mono_marshal_get_virtual_stelemref (MonoClass *array_class)
10027 int kind;
10029 g_assert (array_class->rank == 1);
10030 kind = get_virtual_stelemref_kind (array_class->element_class);
10032 return get_virtual_stelemref_wrapper (kind);
10035 MonoMethod**
10036 mono_marshal_get_virtual_stelemref_wrappers (int *nwrappers)
10038 MonoMethod **res;
10039 int i;
10041 *nwrappers = STELEMREF_KIND_COUNT;
10042 res = (MonoMethod **)g_malloc0 (STELEMREF_KIND_COUNT * sizeof (MonoMethod*));
10043 for (i = 0; i < STELEMREF_KIND_COUNT; ++i)
10044 res [i] = get_virtual_stelemref_wrapper (i);
10045 return res;
10048 MonoMethod*
10049 mono_marshal_get_stelemref (void)
10051 static MonoMethod* ret = NULL;
10052 MonoMethodSignature *sig;
10053 MonoMethodBuilder *mb;
10054 WrapperInfo *info;
10056 guint32 b1, b2, b3, b4;
10057 guint32 copy_pos;
10058 int aklass, vklass;
10059 int array_slot_addr;
10061 if (ret)
10062 return ret;
10064 mb = mono_mb_new (mono_defaults.object_class, "stelemref", MONO_WRAPPER_STELEMREF);
10067 sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
10069 /* void stelemref (void* array, int idx, void* value) */
10070 sig->ret = &mono_defaults.void_class->byval_arg;
10071 sig->params [0] = &mono_defaults.object_class->byval_arg;
10072 sig->params [1] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
10073 sig->params [2] = &mono_defaults.object_class->byval_arg;
10075 #ifndef DISABLE_JIT
10076 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10077 vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10078 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
10081 the method:
10082 <ldelema (bound check)>
10083 if (!value)
10084 goto store;
10086 aklass = array->vtable->klass->element_class;
10087 vklass = value->vtable->klass;
10089 if (vklass->idepth < aklass->idepth)
10090 goto long;
10092 if (vklass->supertypes [aklass->idepth - 1] != aklass)
10093 goto long;
10095 store:
10096 *array_slot_addr = value;
10097 return;
10099 long:
10100 if (mono_object_isinst (value, aklass))
10101 goto store;
10103 throw new ArrayTypeMismatchException ();
10106 /* ldelema (implicit bound check) */
10107 mono_mb_emit_ldarg (mb, 0);
10108 mono_mb_emit_ldarg (mb, 1);
10109 mono_mb_emit_op (mb, CEE_LDELEMA, mono_defaults.object_class);
10110 mono_mb_emit_stloc (mb, array_slot_addr);
10112 /* if (!value) goto do_store */
10113 mono_mb_emit_ldarg (mb, 2);
10114 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
10116 /* aklass = array->vtable->klass->element_class */
10117 mono_mb_emit_ldarg (mb, 0);
10118 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
10119 mono_mb_emit_byte (mb, CEE_LDIND_I);
10120 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
10121 mono_mb_emit_byte (mb, CEE_LDIND_I);
10122 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, element_class));
10123 mono_mb_emit_byte (mb, CEE_LDIND_I);
10124 mono_mb_emit_stloc (mb, aklass);
10126 /* vklass = value->vtable->klass */
10127 mono_mb_emit_ldarg (mb, 2);
10128 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
10129 mono_mb_emit_byte (mb, CEE_LDIND_I);
10130 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
10131 mono_mb_emit_byte (mb, CEE_LDIND_I);
10132 mono_mb_emit_stloc (mb, vklass);
10134 /* if (vklass->idepth < aklass->idepth) goto failue */
10135 mono_mb_emit_ldloc (mb, vklass);
10136 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
10137 mono_mb_emit_byte (mb, CEE_LDIND_U2);
10139 mono_mb_emit_ldloc (mb, aklass);
10140 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
10141 mono_mb_emit_byte (mb, CEE_LDIND_U2);
10143 b2 = mono_mb_emit_branch (mb, CEE_BLT_UN);
10145 /* if (vklass->supertypes [aklass->idepth - 1] != aklass) goto failure */
10146 mono_mb_emit_ldloc (mb, vklass);
10147 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, supertypes));
10148 mono_mb_emit_byte (mb, CEE_LDIND_I);
10150 mono_mb_emit_ldloc (mb, aklass);
10151 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
10152 mono_mb_emit_byte (mb, CEE_LDIND_U2);
10153 mono_mb_emit_icon (mb, 1);
10154 mono_mb_emit_byte (mb, CEE_SUB);
10155 mono_mb_emit_icon (mb, sizeof (void*));
10156 mono_mb_emit_byte (mb, CEE_MUL);
10157 mono_mb_emit_byte (mb, CEE_ADD);
10158 mono_mb_emit_byte (mb, CEE_LDIND_I);
10160 mono_mb_emit_ldloc (mb, aklass);
10162 b3 = mono_mb_emit_branch (mb, CEE_BNE_UN);
10164 copy_pos = mono_mb_get_label (mb);
10165 /* do_store */
10166 mono_mb_patch_branch (mb, b1);
10167 mono_mb_emit_ldloc (mb, array_slot_addr);
10168 mono_mb_emit_ldarg (mb, 2);
10169 mono_mb_emit_byte (mb, CEE_STIND_REF);
10171 mono_mb_emit_byte (mb, CEE_RET);
10173 /* the hard way */
10174 mono_mb_patch_branch (mb, b2);
10175 mono_mb_patch_branch (mb, b3);
10177 mono_mb_emit_ldarg (mb, 2);
10178 mono_mb_emit_ldloc (mb, aklass);
10179 mono_mb_emit_icall (mb, mono_object_isinst_icall);
10181 b4 = mono_mb_emit_branch (mb, CEE_BRTRUE);
10182 mono_mb_patch_addr (mb, b4, copy_pos - (b4 + 4));
10183 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
10185 mono_mb_emit_byte (mb, CEE_RET);
10186 #endif
10187 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
10188 ret = mono_mb_create (mb, sig, 4, info);
10189 mono_mb_free (mb);
10191 return ret;
10195 * mono_marshal_get_gsharedvt_in_wrapper:
10197 * This wrapper handles calls from normal code to gsharedvt code.
10199 MonoMethod*
10200 mono_marshal_get_gsharedvt_in_wrapper (void)
10202 static MonoMethod* ret = NULL;
10203 MonoMethodSignature *sig;
10204 MonoMethodBuilder *mb;
10205 WrapperInfo *info;
10207 if (ret)
10208 return ret;
10210 mb = mono_mb_new (mono_defaults.object_class, "gsharedvt_in", MONO_WRAPPER_UNKNOWN);
10212 sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
10213 sig->ret = &mono_defaults.void_class->byval_arg;
10215 #ifndef DISABLE_JIT
10217 * The body is generated by the JIT, we use a wrapper instead of a trampoline so EH works.
10219 mono_mb_emit_byte (mb, CEE_RET);
10220 #endif
10221 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_GSHAREDVT_IN);
10222 ret = mono_mb_create (mb, sig, 4, info);
10223 mono_mb_free (mb);
10225 return ret;
10229 * mono_marshal_get_gsharedvt_out_wrapper:
10231 * This wrapper handles calls from gsharedvt code to normal code.
10233 MonoMethod*
10234 mono_marshal_get_gsharedvt_out_wrapper (void)
10236 static MonoMethod* ret = NULL;
10237 MonoMethodSignature *sig;
10238 MonoMethodBuilder *mb;
10239 WrapperInfo *info;
10241 if (ret)
10242 return ret;
10244 mb = mono_mb_new (mono_defaults.object_class, "gsharedvt_out", MONO_WRAPPER_UNKNOWN);
10246 sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
10247 sig->ret = &mono_defaults.void_class->byval_arg;
10249 #ifndef DISABLE_JIT
10251 * The body is generated by the JIT, we use a wrapper instead of a trampoline so EH works.
10253 mono_mb_emit_byte (mb, CEE_RET);
10254 #endif
10255 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_GSHAREDVT_OUT);
10256 ret = mono_mb_create (mb, sig, 4, info);
10257 mono_mb_free (mb);
10259 return ret;
10262 typedef struct {
10263 int rank;
10264 int elem_size;
10265 MonoMethod *method;
10266 } ArrayElemAddr;
10268 /* LOCKING: vars accessed under the marshal lock */
10269 static ArrayElemAddr *elem_addr_cache = NULL;
10270 static int elem_addr_cache_size = 0;
10271 static int elem_addr_cache_next = 0;
10274 * mono_marshal_get_array_address:
10275 * @rank: rank of the array type
10276 * @elem_size: size in bytes of an element of an array.
10278 * Returns a MonoMethod that implements the code to get the address
10279 * of an element in a multi-dimenasional array of @rank dimensions.
10280 * The returned method takes an array as the first argument and then
10281 * @rank indexes for the @rank dimensions.
10282 * If ELEM_SIZE is 0, read the array size from the array object.
10284 MonoMethod*
10285 mono_marshal_get_array_address (int rank, int elem_size)
10287 MonoMethod *ret;
10288 MonoMethodBuilder *mb;
10289 MonoMethodSignature *sig;
10290 WrapperInfo *info;
10291 char *name;
10292 int i, bounds, ind, realidx;
10293 int branch_pos, *branch_positions;
10294 int cached;
10296 ret = NULL;
10297 mono_marshal_lock ();
10298 for (i = 0; i < elem_addr_cache_next; ++i) {
10299 if (elem_addr_cache [i].rank == rank && elem_addr_cache [i].elem_size == elem_size) {
10300 ret = elem_addr_cache [i].method;
10301 break;
10304 mono_marshal_unlock ();
10305 if (ret)
10306 return ret;
10308 branch_positions = g_new0 (int, rank);
10310 sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1 + rank);
10312 /* void* address (void* array, int idx0, int idx1, int idx2, ...) */
10313 sig->ret = &mono_defaults.int_class->byval_arg;
10314 sig->params [0] = &mono_defaults.object_class->byval_arg;
10315 for (i = 0; i < rank; ++i) {
10316 sig->params [i + 1] = &mono_defaults.int32_class->byval_arg;
10319 name = g_strdup_printf ("ElementAddr_%d", elem_size);
10320 mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_MANAGED);
10321 g_free (name);
10323 #ifndef DISABLE_JIT
10324 bounds = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10325 ind = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
10326 realidx = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
10328 /* bounds = array->bounds; */
10329 mono_mb_emit_ldarg (mb, 0);
10330 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoArray, bounds));
10331 mono_mb_emit_byte (mb, CEE_LDIND_I);
10332 mono_mb_emit_stloc (mb, bounds);
10334 /* ind is the overall element index, realidx is the partial index in a single dimension */
10335 /* ind = idx0 - bounds [0].lower_bound */
10336 mono_mb_emit_ldarg (mb, 1);
10337 mono_mb_emit_ldloc (mb, bounds);
10338 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
10339 mono_mb_emit_byte (mb, CEE_ADD);
10340 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10341 mono_mb_emit_byte (mb, CEE_SUB);
10342 mono_mb_emit_stloc (mb, ind);
10343 /* if (ind >= bounds [0].length) goto exeception; */
10344 mono_mb_emit_ldloc (mb, ind);
10345 mono_mb_emit_ldloc (mb, bounds);
10346 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArrayBounds, length));
10347 mono_mb_emit_byte (mb, CEE_ADD);
10348 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10349 /* note that we use unsigned comparison */
10350 branch_pos = mono_mb_emit_branch (mb, CEE_BGE_UN);
10352 /* For large ranks (> 4?) use a loop n IL later to reduce code size.
10353 * We could also decide to ignore the passed elem_size and get it
10354 * from the array object, to reduce the number of methods we generate:
10355 * the additional cost is 3 memory loads and a non-immediate mul.
10357 for (i = 1; i < rank; ++i) {
10358 /* realidx = idxi - bounds [i].lower_bound */
10359 mono_mb_emit_ldarg (mb, 1 + i);
10360 mono_mb_emit_ldloc (mb, bounds);
10361 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
10362 mono_mb_emit_byte (mb, CEE_ADD);
10363 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10364 mono_mb_emit_byte (mb, CEE_SUB);
10365 mono_mb_emit_stloc (mb, realidx);
10366 /* if (realidx >= bounds [i].length) goto exeception; */
10367 mono_mb_emit_ldloc (mb, realidx);
10368 mono_mb_emit_ldloc (mb, bounds);
10369 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + MONO_STRUCT_OFFSET (MonoArrayBounds, length));
10370 mono_mb_emit_byte (mb, CEE_ADD);
10371 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10372 branch_positions [i] = mono_mb_emit_branch (mb, CEE_BGE_UN);
10373 /* ind = ind * bounds [i].length + realidx */
10374 mono_mb_emit_ldloc (mb, ind);
10375 mono_mb_emit_ldloc (mb, bounds);
10376 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + MONO_STRUCT_OFFSET (MonoArrayBounds, length));
10377 mono_mb_emit_byte (mb, CEE_ADD);
10378 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10379 mono_mb_emit_byte (mb, CEE_MUL);
10380 mono_mb_emit_ldloc (mb, realidx);
10381 mono_mb_emit_byte (mb, CEE_ADD);
10382 mono_mb_emit_stloc (mb, ind);
10385 /* return array->vector + ind * element_size */
10386 mono_mb_emit_ldarg (mb, 0);
10387 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
10388 mono_mb_emit_ldloc (mb, ind);
10389 if (elem_size) {
10390 mono_mb_emit_icon (mb, elem_size);
10391 } else {
10392 /* Load arr->vtable->klass->sizes.element_class */
10393 mono_mb_emit_ldarg (mb, 0);
10394 mono_mb_emit_byte (mb, CEE_CONV_I);
10395 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
10396 mono_mb_emit_byte (mb, CEE_ADD);
10397 mono_mb_emit_byte (mb, CEE_LDIND_I);
10398 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
10399 mono_mb_emit_byte (mb, CEE_ADD);
10400 mono_mb_emit_byte (mb, CEE_LDIND_I);
10401 /* sizes is an union, so this reads sizes.element_size */
10402 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoClass, sizes));
10403 mono_mb_emit_byte (mb, CEE_ADD);
10404 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10406 mono_mb_emit_byte (mb, CEE_MUL);
10407 mono_mb_emit_byte (mb, CEE_ADD);
10408 mono_mb_emit_byte (mb, CEE_RET);
10410 /* patch the branches to get here and throw */
10411 for (i = 1; i < rank; ++i) {
10412 mono_mb_patch_branch (mb, branch_positions [i]);
10414 mono_mb_patch_branch (mb, branch_pos);
10415 /* throw exception */
10416 mono_mb_emit_exception (mb, "IndexOutOfRangeException", NULL);
10418 g_free (branch_positions);
10419 #endif /* DISABLE_JIT */
10421 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ELEMENT_ADDR);
10422 info->d.element_addr.rank = rank;
10423 info->d.element_addr.elem_size = elem_size;
10424 ret = mono_mb_create (mb, sig, 4, info);
10425 mono_mb_free (mb);
10427 /* cache the result */
10428 cached = 0;
10429 mono_marshal_lock ();
10430 for (i = 0; i < elem_addr_cache_next; ++i) {
10431 if (elem_addr_cache [i].rank == rank && elem_addr_cache [i].elem_size == elem_size) {
10432 /* FIXME: free ret */
10433 ret = elem_addr_cache [i].method;
10434 cached = TRUE;
10435 break;
10438 if (!cached) {
10439 if (elem_addr_cache_next >= elem_addr_cache_size) {
10440 int new_size = elem_addr_cache_size + 4;
10441 ArrayElemAddr *new_array = g_new0 (ArrayElemAddr, new_size);
10442 memcpy (new_array, elem_addr_cache, elem_addr_cache_size * sizeof (ArrayElemAddr));
10443 g_free (elem_addr_cache);
10444 elem_addr_cache = new_array;
10445 elem_addr_cache_size = new_size;
10447 elem_addr_cache [elem_addr_cache_next].rank = rank;
10448 elem_addr_cache [elem_addr_cache_next].elem_size = elem_size;
10449 elem_addr_cache [elem_addr_cache_next].method = ret;
10450 elem_addr_cache_next ++;
10452 mono_marshal_unlock ();
10453 return ret;
10457 * mono_marshal_get_array_accessor_wrapper:
10459 * Return a wrapper which just calls METHOD, which should be an Array Get/Set/Address method.
10461 MonoMethod *
10462 mono_marshal_get_array_accessor_wrapper (MonoMethod *method)
10464 MonoMethodSignature *sig;
10465 MonoMethodBuilder *mb;
10466 MonoMethod *res;
10467 GHashTable *cache;
10468 int i;
10469 MonoGenericContext *ctx = NULL;
10470 MonoMethod *orig_method = NULL;
10471 MonoGenericContainer *container = NULL;
10472 WrapperInfo *info;
10475 * These wrappers are needed to avoid the JIT replacing the calls to these methods with intrinsics
10476 * inside runtime invoke wrappers, thereby making the wrappers not unshareable.
10477 * FIXME: Use generic methods.
10480 * Check cache
10482 if (ctx) {
10483 cache = NULL;
10484 g_assert_not_reached ();
10485 } else {
10486 cache = get_cache (&method->klass->image->array_accessor_cache, mono_aligned_addr_hash, NULL);
10487 if ((res = mono_marshal_find_in_cache (cache, method)))
10488 return res;
10491 sig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
10492 sig->pinvoke = 0;
10494 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNKNOWN);
10496 #ifndef DISABLE_JIT
10497 /* Call the method */
10498 if (sig->hasthis)
10499 mono_mb_emit_ldarg (mb, 0);
10500 for (i = 0; i < sig->param_count; i++)
10501 mono_mb_emit_ldarg (mb, i + (sig->hasthis == TRUE));
10503 if (ctx) {
10504 MonoError error;
10505 mono_mb_emit_managed_call (mb, mono_class_inflate_generic_method_checked (method, &container->context, &error), NULL);
10506 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
10507 } else {
10508 mono_mb_emit_managed_call (mb, method, NULL);
10510 mono_mb_emit_byte (mb, CEE_RET);
10511 #endif
10513 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ARRAY_ACCESSOR);
10514 info->d.array_accessor.method = method;
10516 if (ctx) {
10517 MonoMethod *def;
10518 def = mono_mb_create_and_cache_full (cache, method, mb, sig, sig->param_count + 16, info, NULL);
10519 res = cache_generic_wrapper (cache, orig_method, def, ctx, orig_method);
10520 } else {
10521 res = mono_mb_create_and_cache_full (cache, method,
10522 mb, sig, sig->param_count + 16,
10523 info, NULL);
10525 mono_mb_free (mb);
10527 return res;
10530 #ifndef HOST_WIN32
10531 static inline void*
10532 mono_marshal_alloc_co_task_mem (size_t size)
10534 if ((gulong)size == 0)
10535 /* This returns a valid pointer for size 0 on MS.NET */
10536 size = 4;
10538 return g_try_malloc ((gulong)size);
10540 #endif
10542 void*
10543 mono_marshal_alloc (gulong size, MonoError *error)
10545 gpointer res;
10547 mono_error_init (error);
10549 res = mono_marshal_alloc_co_task_mem (size);
10550 if (!res)
10551 mono_error_set_out_of_memory (error, "Could not allocate %lu bytes", size);
10553 return res;
10556 /* This is a JIT icall, it sets the pending exception and returns NULL on error. */
10557 static void*
10558 ves_icall_marshal_alloc (gulong size)
10560 MonoError error;
10561 void *ret = mono_marshal_alloc (size, &error);
10562 if (!mono_error_ok (&error)) {
10563 mono_error_set_pending_exception (&error);
10564 return NULL;
10567 return ret;
10570 #ifndef HOST_WIN32
10571 static inline void
10572 mono_marshal_free_co_task_mem (void *ptr)
10574 g_free (ptr);
10575 return;
10577 #endif
10579 void
10580 mono_marshal_free (gpointer ptr)
10582 mono_marshal_free_co_task_mem (ptr);
10585 void
10586 mono_marshal_free_array (gpointer *ptr, int size)
10588 int i;
10590 if (!ptr)
10591 return;
10593 for (i = 0; i < size; i++)
10594 if (ptr [i])
10595 g_free (ptr [i]);
10598 void *
10599 mono_marshal_string_to_utf16 (MonoString *s)
10601 return s ? mono_string_chars (s) : NULL;
10604 /* This is a JIT icall, it sets the pending exception and returns NULL on error. */
10605 static void *
10606 mono_marshal_string_to_utf16_copy (MonoString *s)
10608 if (s == NULL) {
10609 return NULL;
10610 } else {
10611 MonoError error;
10612 gunichar2 *res = (gunichar2 *)mono_marshal_alloc ((mono_string_length (s) * 2) + 2, &error);
10613 if (!mono_error_ok (&error)) {
10614 mono_error_set_pending_exception (&error);
10615 return NULL;
10617 memcpy (res, mono_string_chars (s), mono_string_length (s) * 2);
10618 res [mono_string_length (s)] = 0;
10619 return res;
10624 * mono_marshal_set_last_error:
10626 * This function is invoked to set the last error value from a P/Invoke call
10627 * which has SetLastError set.
10629 void
10630 mono_marshal_set_last_error (void)
10632 #ifdef WIN32
10633 mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (GetLastError ()));
10634 #else
10635 mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (errno));
10636 #endif
10639 static void
10640 mono_marshal_set_last_error_windows (int error)
10642 #ifdef WIN32
10643 mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (error));
10644 #endif
10647 void
10648 ves_icall_System_Runtime_InteropServices_Marshal_copy_to_unmanaged (MonoArray *src, gint32 start_index,
10649 gpointer dest, gint32 length)
10651 int element_size;
10652 void *source_addr;
10654 MONO_CHECK_ARG_NULL (src,);
10655 MONO_CHECK_ARG_NULL (dest,);
10657 if (src->obj.vtable->klass->rank != 1) {
10658 mono_set_pending_exception (mono_get_exception_argument ("array", "array is multi-dimensional"));
10659 return;
10661 if (start_index < 0) {
10662 mono_set_pending_exception (mono_get_exception_argument ("startIndex", "Must be >= 0"));
10663 return;
10665 if (length < 0) {
10666 mono_set_pending_exception (mono_get_exception_argument ("length", "Must be >= 0"));
10667 return;
10669 if (start_index + length > mono_array_length (src)) {
10670 mono_set_pending_exception (mono_get_exception_argument ("length", "start_index + length > array length"));
10671 return;
10674 element_size = mono_array_element_size (src->obj.vtable->klass);
10676 /* no references should be involved */
10677 source_addr = mono_array_addr_with_size_fast (src, element_size, start_index);
10679 memcpy (dest, source_addr, length * element_size);
10682 void
10683 ves_icall_System_Runtime_InteropServices_Marshal_copy_from_unmanaged (gpointer src, gint32 start_index,
10684 MonoArray *dest, gint32 length)
10686 int element_size;
10687 void *dest_addr;
10689 MONO_CHECK_ARG_NULL (src,);
10690 MONO_CHECK_ARG_NULL (dest,);
10692 if (dest->obj.vtable->klass->rank != 1) {
10693 mono_set_pending_exception (mono_get_exception_argument ("array", "array is multi-dimensional"));
10694 return;
10696 if (start_index < 0) {
10697 mono_set_pending_exception (mono_get_exception_argument ("startIndex", "Must be >= 0"));
10698 return;
10700 if (length < 0) {
10701 mono_set_pending_exception (mono_get_exception_argument ("length", "Must be >= 0"));
10702 return;
10704 if (start_index + length > mono_array_length (dest)) {
10705 mono_set_pending_exception (mono_get_exception_argument ("length", "start_index + length > array length"));
10706 return;
10708 element_size = mono_array_element_size (dest->obj.vtable->klass);
10710 /* no references should be involved */
10711 dest_addr = mono_array_addr_with_size_fast (dest, element_size, start_index);
10713 memcpy (dest_addr, src, length * element_size);
10716 MonoString *
10717 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi (char *ptr)
10719 if (ptr == NULL)
10720 return NULL;
10721 else
10722 return mono_string_new (mono_domain_get (), ptr);
10725 MonoString *
10726 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi_len (char *ptr, gint32 len)
10728 MonoError error;
10729 MonoString *result = NULL;
10730 mono_error_init (&error);
10731 if (ptr == NULL)
10732 mono_error_set_argument_null (&error, "ptr", "");
10733 else
10734 result = mono_string_new_len_checked (mono_domain_get (), ptr, len, &error);
10735 mono_error_set_pending_exception (&error);
10736 return result;
10739 MonoString *
10740 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni (guint16 *ptr)
10742 MonoError error;
10743 MonoString *res = NULL;
10744 MonoDomain *domain = mono_domain_get ();
10745 int len = 0;
10746 guint16 *t = ptr;
10748 if (ptr == NULL)
10749 return NULL;
10751 while (*t++)
10752 len++;
10754 res = mono_string_new_utf16_checked (domain, ptr, len, &error);
10755 if (!mono_error_ok (&error)) {
10756 mono_error_set_pending_exception (&error);
10757 return NULL;
10759 return res;
10762 MonoString *
10763 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni_len (guint16 *ptr, gint32 len)
10765 MonoError error;
10766 MonoString *res = NULL;
10767 MonoDomain *domain = mono_domain_get ();
10769 mono_error_init (&error);
10771 if (ptr == NULL) {
10772 res = NULL;
10773 mono_error_set_argument_null (&error, "ptr", "");
10774 } else {
10775 res = mono_string_new_utf16_checked (domain, ptr, len, &error);
10778 if (!mono_error_ok (&error))
10779 mono_error_set_pending_exception (&error);
10780 return res;
10783 guint32
10784 ves_icall_System_Runtime_InteropServices_Marshal_GetLastWin32Error (void)
10786 return (GPOINTER_TO_INT (mono_native_tls_get_value (last_error_tls_id)));
10789 guint32
10790 ves_icall_System_Runtime_InteropServices_Marshal_SizeOf (MonoReflectionType *rtype)
10792 MonoClass *klass;
10793 MonoType *type;
10794 guint32 layout;
10796 MONO_CHECK_ARG_NULL (rtype, 0);
10798 type = rtype->type;
10799 klass = mono_class_from_mono_type (type);
10800 if (!mono_class_init (klass)) {
10801 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
10802 return 0;
10805 layout = (mono_class_get_flags (klass) & TYPE_ATTRIBUTE_LAYOUT_MASK);
10807 if (type->type == MONO_TYPE_PTR || type->type == MONO_TYPE_FNPTR) {
10808 return sizeof (gpointer);
10809 } else if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
10810 gchar *msg;
10811 MonoException *exc;
10813 msg = g_strdup_printf ("Type %s cannot be marshaled as an unmanaged structure.", klass->name);
10814 exc = mono_get_exception_argument ("t", msg);
10815 g_free (msg);
10816 mono_set_pending_exception (exc);
10817 return 0;
10820 return mono_class_native_size (klass, NULL);
10823 void
10824 ves_icall_System_Runtime_InteropServices_Marshal_StructureToPtr (MonoObject *obj, gpointer dst, MonoBoolean delete_old)
10826 MonoError error;
10827 MonoMethod *method;
10828 gpointer pa [3];
10830 MONO_CHECK_ARG_NULL (obj,);
10831 MONO_CHECK_ARG_NULL (dst,);
10833 method = mono_marshal_get_struct_to_ptr (obj->vtable->klass);
10835 pa [0] = obj;
10836 pa [1] = &dst;
10837 pa [2] = &delete_old;
10839 mono_runtime_invoke_checked (method, NULL, pa, &error);
10840 if (!mono_error_ok (&error))
10841 mono_error_set_pending_exception (&error);
10844 static void
10845 ptr_to_structure (gpointer src, MonoObject *dst, MonoError *error)
10847 MonoMethod *method;
10848 gpointer pa [2];
10850 mono_error_init (error);
10852 method = mono_marshal_get_ptr_to_struct (dst->vtable->klass);
10854 pa [0] = &src;
10855 pa [1] = dst;
10857 mono_runtime_invoke_checked (method, NULL, pa, error);
10860 void
10861 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure (gpointer src, MonoObject *dst)
10863 MonoType *t;
10864 MonoError error;
10866 MONO_CHECK_ARG_NULL (src,);
10867 MONO_CHECK_ARG_NULL (dst,);
10869 t = mono_type_get_underlying_type (mono_class_get_type (dst->vtable->klass));
10871 if (t->type == MONO_TYPE_VALUETYPE) {
10872 MonoException *exc;
10873 gchar *tmp;
10875 tmp = g_strdup_printf ("Destination is a boxed value type.");
10876 exc = mono_get_exception_argument ("dst", tmp);
10877 g_free (tmp);
10879 mono_set_pending_exception (exc);
10880 return;
10883 ptr_to_structure (src, dst, &error);
10884 if (!mono_error_ok (&error))
10885 mono_error_set_pending_exception (&error);
10888 MonoObject *
10889 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure_type (gpointer src, MonoReflectionType *type)
10891 MonoError error;
10892 MonoClass *klass;
10893 MonoDomain *domain = mono_domain_get ();
10894 MonoObject *res;
10896 if (src == NULL)
10897 return NULL;
10898 MONO_CHECK_ARG_NULL (type, NULL);
10900 klass = mono_class_from_mono_type (type->type);
10901 if (!mono_class_init (klass)) {
10902 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
10903 return NULL;
10906 res = mono_object_new_checked (domain, klass, &error);
10907 if (!mono_error_ok (&error)) {
10908 mono_error_set_pending_exception (&error);
10909 return NULL;
10912 ptr_to_structure (src, res, &error);
10913 if (!mono_error_ok (&error)) {
10914 mono_error_set_pending_exception (&error);
10915 return NULL;
10918 return res;
10922 ves_icall_System_Runtime_InteropServices_Marshal_OffsetOf (MonoReflectionType *type, MonoString *field_name)
10924 MonoError error;
10925 MonoMarshalType *info;
10926 MonoClass *klass;
10927 char *fname;
10928 int match_index = -1;
10930 MONO_CHECK_ARG_NULL (type, 0);
10931 MONO_CHECK_ARG_NULL (field_name, 0);
10933 fname = mono_string_to_utf8_checked (field_name, &error);
10934 if (mono_error_set_pending_exception (&error))
10935 return 0;
10936 klass = mono_class_from_mono_type (type->type);
10937 if (!mono_class_init (klass)) {
10938 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
10939 return 0;
10942 while (klass && match_index == -1) {
10943 MonoClassField* field;
10944 int i = 0;
10945 gpointer iter = NULL;
10946 while ((field = mono_class_get_fields (klass, &iter))) {
10947 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
10948 continue;
10949 if (!strcmp (fname, mono_field_get_name (field))) {
10950 match_index = i;
10951 break;
10953 i ++;
10956 if (match_index == -1)
10957 klass = klass->parent;
10960 g_free (fname);
10962 if(match_index == -1) {
10963 MonoException* exc;
10964 gchar *tmp;
10966 /* Get back original class instance */
10967 klass = mono_class_from_mono_type (type->type);
10969 tmp = g_strdup_printf ("Field passed in is not a marshaled member of the type %s", klass->name);
10970 exc = mono_get_exception_argument ("fieldName", tmp);
10971 g_free (tmp);
10973 mono_set_pending_exception ((MonoException*)exc);
10974 return 0;
10977 info = mono_marshal_load_type_info (klass);
10978 return info->fields [match_index].offset;
10981 #ifndef HOST_WIN32
10982 gpointer
10983 ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalAnsi (MonoString *string)
10985 MonoError error;
10986 char *ret = mono_string_to_utf8_checked (string, &error);
10987 mono_error_set_pending_exception (&error);
10988 return ret;
10991 gpointer
10992 ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalUni (MonoString *string)
10994 if (string == NULL)
10995 return NULL;
10996 else {
10997 gunichar2 *res = (gunichar2 *)g_malloc ((mono_string_length (string) + 1) * 2);
10999 memcpy (res, mono_string_chars (string), mono_string_length (string) * 2);
11000 res [mono_string_length (string)] = 0;
11001 return res;
11004 #endif /* !HOST_WIN32 */
11006 static void
11007 mono_struct_delete_old (MonoClass *klass, char *ptr)
11009 MonoMarshalType *info;
11010 int i;
11012 info = mono_marshal_load_type_info (klass);
11014 for (i = 0; i < info->num_fields; i++) {
11015 MonoMarshalConv conv;
11016 MonoType *ftype = info->fields [i].field->type;
11017 char *cpos;
11019 if (ftype->attrs & FIELD_ATTRIBUTE_STATIC)
11020 continue;
11022 mono_type_to_unmanaged (ftype, info->fields [i].mspec, TRUE,
11023 klass->unicode, &conv);
11025 cpos = ptr + info->fields [i].offset;
11027 switch (conv) {
11028 case MONO_MARSHAL_CONV_NONE:
11029 if (MONO_TYPE_ISSTRUCT (ftype)) {
11030 mono_struct_delete_old (ftype->data.klass, cpos);
11031 continue;
11033 break;
11034 case MONO_MARSHAL_CONV_STR_LPWSTR:
11035 /* We assume this field points inside a MonoString */
11036 break;
11037 case MONO_MARSHAL_CONV_STR_LPTSTR:
11038 #ifdef TARGET_WIN32
11039 /* We assume this field points inside a MonoString
11040 * on Win32 */
11041 break;
11042 #endif
11043 case MONO_MARSHAL_CONV_STR_LPSTR:
11044 case MONO_MARSHAL_CONV_STR_BSTR:
11045 case MONO_MARSHAL_CONV_STR_ANSIBSTR:
11046 case MONO_MARSHAL_CONV_STR_TBSTR:
11047 case MONO_MARSHAL_CONV_STR_UTF8STR:
11048 mono_marshal_free (*(gpointer *)cpos);
11049 break;
11051 default:
11052 continue;
11057 void
11058 ves_icall_System_Runtime_InteropServices_Marshal_DestroyStructure (gpointer src, MonoReflectionType *type)
11060 MonoClass *klass;
11062 MONO_CHECK_ARG_NULL (src,);
11063 MONO_CHECK_ARG_NULL (type,);
11065 klass = mono_class_from_mono_type (type->type);
11066 if (!mono_class_init (klass)) {
11067 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
11068 return;
11071 mono_struct_delete_old (klass, (char *)src);
11074 #ifndef HOST_WIN32
11075 static inline void *
11076 mono_marshal_alloc_hglobal (size_t size)
11078 return g_try_malloc (size);
11080 #endif
11082 void*
11083 ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (gpointer size)
11085 gpointer res;
11086 size_t s = (size_t)size;
11088 if (s == 0)
11089 /* This returns a valid pointer for size 0 on MS.NET */
11090 s = 4;
11092 res = mono_marshal_alloc_hglobal (s);
11094 if (!res) {
11095 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11096 return NULL;
11099 return res;
11102 #ifndef HOST_WIN32
11103 static inline gpointer
11104 mono_marshal_realloc_hglobal (gpointer ptr, size_t size)
11106 return g_try_realloc (ptr, size);
11108 #endif
11110 gpointer
11111 ves_icall_System_Runtime_InteropServices_Marshal_ReAllocHGlobal (gpointer ptr, gpointer size)
11113 gpointer res;
11114 size_t s = (size_t)size;
11116 if (ptr == NULL) {
11117 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11118 return NULL;
11121 res = mono_marshal_realloc_hglobal (ptr, s);
11123 if (!res) {
11124 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11125 return NULL;
11128 return res;
11131 #ifndef HOST_WIN32
11132 static inline void
11133 mono_marshal_free_hglobal (gpointer ptr)
11135 g_free (ptr);
11136 return;
11138 #endif
11140 void
11141 ves_icall_System_Runtime_InteropServices_Marshal_FreeHGlobal (void *ptr)
11143 mono_marshal_free_hglobal (ptr);
11146 void*
11147 ves_icall_System_Runtime_InteropServices_Marshal_AllocCoTaskMem (int size)
11149 void *res = mono_marshal_alloc_co_task_mem (size);
11151 if (!res) {
11152 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11153 return NULL;
11155 return res;
11158 void*
11159 ves_icall_System_Runtime_InteropServices_Marshal_AllocCoTaskMemSize (gulong size)
11161 void *res = mono_marshal_alloc_co_task_mem (size);
11163 if (!res) {
11164 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11165 return NULL;
11167 return res;
11170 void
11171 ves_icall_System_Runtime_InteropServices_Marshal_FreeCoTaskMem (void *ptr)
11173 mono_marshal_free_co_task_mem (ptr);
11174 return;
11177 #ifndef HOST_WIN32
11178 static inline gpointer
11179 mono_marshal_realloc_co_task_mem (gpointer ptr, size_t size)
11181 return g_try_realloc (ptr, (gulong)size);
11183 #endif
11185 gpointer
11186 ves_icall_System_Runtime_InteropServices_Marshal_ReAllocCoTaskMem (gpointer ptr, int size)
11188 void *res = mono_marshal_realloc_co_task_mem (ptr, size);
11190 if (!res) {
11191 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11192 return NULL;
11194 return res;
11197 void*
11198 ves_icall_System_Runtime_InteropServices_Marshal_UnsafeAddrOfPinnedArrayElement (MonoArray *arrayobj, int index)
11200 return mono_array_addr_with_size_fast (arrayobj, mono_array_element_size (arrayobj->obj.vtable->klass), index);
11203 MonoDelegate*
11204 ves_icall_System_Runtime_InteropServices_Marshal_GetDelegateForFunctionPointerInternal (void *ftn, MonoReflectionType *type)
11206 MonoClass *klass = mono_type_get_class (type->type);
11207 if (!mono_class_init (klass)) {
11208 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
11209 return NULL;
11212 return mono_ftnptr_to_delegate (klass, ftn);
11215 gpointer
11216 ves_icall_System_Runtime_InteropServices_Marshal_GetFunctionPointerForDelegateInternal (MonoDelegate *delegate)
11218 return mono_delegate_to_ftnptr (delegate);
11222 * mono_marshal_is_loading_type_info:
11224 * Return whenever mono_marshal_load_type_info () is being executed for KLASS by this
11225 * thread.
11227 static gboolean
11228 mono_marshal_is_loading_type_info (MonoClass *klass)
11230 GSList *loads_list = (GSList *)mono_native_tls_get_value (load_type_info_tls_id);
11232 return g_slist_find (loads_list, klass) != NULL;
11236 * mono_marshal_load_type_info:
11238 * Initialize klass::marshal_info using information from metadata. This function can
11239 * recursively call itself, and the caller is responsible to avoid that by calling
11240 * mono_marshal_is_loading_type_info () beforehand.
11242 * LOCKING: Acquires the loader lock.
11244 MonoMarshalType *
11245 mono_marshal_load_type_info (MonoClass* klass)
11247 int j, count = 0;
11248 guint32 native_size = 0, min_align = 1, packing;
11249 MonoMarshalType *info;
11250 MonoClassField* field;
11251 gpointer iter;
11252 guint32 layout;
11253 GSList *loads_list;
11255 g_assert (klass != NULL);
11257 info = mono_class_get_marshal_info (klass);
11258 if (info)
11259 return info;
11261 if (!klass->inited)
11262 mono_class_init (klass);
11264 info = mono_class_get_marshal_info (klass);
11265 if (info)
11266 return info;
11269 * This function can recursively call itself, so we keep the list of classes which are
11270 * under initialization in a TLS list.
11272 g_assert (!mono_marshal_is_loading_type_info (klass));
11273 loads_list = (GSList *)mono_native_tls_get_value (load_type_info_tls_id);
11274 loads_list = g_slist_prepend (loads_list, klass);
11275 mono_native_tls_set_value (load_type_info_tls_id, loads_list);
11277 iter = NULL;
11278 while ((field = mono_class_get_fields (klass, &iter))) {
11279 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
11280 continue;
11281 if (mono_field_is_deleted (field))
11282 continue;
11283 count++;
11286 layout = mono_class_get_flags (klass) & TYPE_ATTRIBUTE_LAYOUT_MASK;
11288 /* The mempool is protected by the loader lock */
11289 info = (MonoMarshalType *)mono_image_alloc0 (klass->image, MONO_SIZEOF_MARSHAL_TYPE + sizeof (MonoMarshalField) * count);
11290 info->num_fields = count;
11292 /* Try to find a size for this type in metadata */
11293 mono_metadata_packing_from_typedef (klass->image, klass->type_token, NULL, &native_size);
11295 if (klass->parent) {
11296 int parent_size = mono_class_native_size (klass->parent, NULL);
11298 /* Add parent size to real size */
11299 native_size += parent_size;
11300 info->native_size = parent_size;
11303 packing = klass->packing_size ? klass->packing_size : 8;
11304 iter = NULL;
11305 j = 0;
11306 while ((field = mono_class_get_fields (klass, &iter))) {
11307 int size;
11308 guint32 align;
11310 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
11311 continue;
11313 if (mono_field_is_deleted (field))
11314 continue;
11315 if (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL)
11316 mono_metadata_field_info_with_mempool (klass->image, mono_metadata_token_index (mono_class_get_field_token (field)) - 1,
11317 NULL, NULL, &info->fields [j].mspec);
11319 info->fields [j].field = field;
11321 if ((mono_class_num_fields (klass) == 1) && (klass->instance_size == sizeof (MonoObject)) &&
11322 (strcmp (mono_field_get_name (field), "$PRIVATE$") == 0)) {
11323 /* This field is a hack inserted by MCS to empty structures */
11324 continue;
11327 switch (layout) {
11328 case TYPE_ATTRIBUTE_AUTO_LAYOUT:
11329 case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
11330 size = mono_marshal_type_size (field->type, info->fields [j].mspec,
11331 &align, TRUE, klass->unicode);
11332 align = klass->packing_size ? MIN (klass->packing_size, align): align;
11333 min_align = MAX (align, min_align);
11334 info->fields [j].offset = info->native_size;
11335 info->fields [j].offset += align - 1;
11336 info->fields [j].offset &= ~(align - 1);
11337 info->native_size = info->fields [j].offset + size;
11338 break;
11339 case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
11340 size = mono_marshal_type_size (field->type, info->fields [j].mspec,
11341 &align, TRUE, klass->unicode);
11342 min_align = MAX (align, min_align);
11343 info->fields [j].offset = field->offset - sizeof (MonoObject);
11344 info->native_size = MAX (info->native_size, info->fields [j].offset + size);
11345 break;
11347 j++;
11350 if (klass->byval_arg.type == MONO_TYPE_PTR)
11351 info->native_size = sizeof (gpointer);
11353 if (layout != TYPE_ATTRIBUTE_AUTO_LAYOUT) {
11354 info->native_size = MAX (native_size, info->native_size);
11356 * If the provided Size is equal or larger than the calculated size, and there
11357 * was no Pack attribute, we set min_align to 1 to avoid native_size being increased
11359 if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
11360 if (native_size && native_size == info->native_size && klass->packing_size == 0)
11361 min_align = 1;
11362 else
11363 min_align = MIN (min_align, packing);
11367 if (info->native_size & (min_align - 1)) {
11368 info->native_size += min_align - 1;
11369 info->native_size &= ~(min_align - 1);
11372 info->min_align = min_align;
11374 /* Update the class's blittable info, if the layouts don't match */
11375 if (info->native_size != mono_class_value_size (klass, NULL))
11376 klass->blittable = FALSE;
11378 /* If this is an array type, ensure that we have element info */
11379 if (klass->rank && !mono_marshal_is_loading_type_info (klass->element_class)) {
11380 mono_marshal_load_type_info (klass->element_class);
11383 loads_list = (GSList *)mono_native_tls_get_value (load_type_info_tls_id);
11384 loads_list = g_slist_remove (loads_list, klass);
11385 mono_native_tls_set_value (load_type_info_tls_id, loads_list);
11387 mono_marshal_lock ();
11388 MonoMarshalType *info2 = mono_class_get_marshal_info (klass);
11389 if (!info2) {
11390 /*We do double-checking locking on marshal_info */
11391 mono_memory_barrier ();
11392 mono_class_set_marshal_info (klass, info);
11393 ++class_marshal_info_count;
11394 info2 = info;
11396 mono_marshal_unlock ();
11398 return info2;
11402 * mono_class_native_size:
11403 * @klass: a class
11405 * Returns: the native size of an object instance (when marshaled
11406 * to unmanaged code)
11408 gint32
11409 mono_class_native_size (MonoClass *klass, guint32 *align)
11411 MonoMarshalType *info = mono_class_get_marshal_info (klass);
11412 if (!info) {
11413 if (mono_marshal_is_loading_type_info (klass)) {
11414 if (align)
11415 *align = 0;
11416 return 0;
11417 } else {
11418 mono_marshal_load_type_info (klass);
11420 info = mono_class_get_marshal_info (klass);
11423 if (align)
11424 *align = info->min_align;
11426 return info->native_size;
11430 * mono_type_native_stack_size:
11431 * @t: the type to return the size it uses on the stack
11433 * Returns: the number of bytes required to hold an instance of this
11434 * type on the native stack
11437 mono_type_native_stack_size (MonoType *t, guint32 *align)
11439 guint32 tmp;
11441 g_assert (t != NULL);
11443 if (!align)
11444 align = &tmp;
11446 if (t->byref) {
11447 *align = sizeof (gpointer);
11448 return sizeof (gpointer);
11451 switch (t->type){
11452 case MONO_TYPE_BOOLEAN:
11453 case MONO_TYPE_CHAR:
11454 case MONO_TYPE_I1:
11455 case MONO_TYPE_U1:
11456 case MONO_TYPE_I2:
11457 case MONO_TYPE_U2:
11458 case MONO_TYPE_I4:
11459 case MONO_TYPE_U4:
11460 *align = 4;
11461 return 4;
11462 case MONO_TYPE_I:
11463 case MONO_TYPE_U:
11464 case MONO_TYPE_STRING:
11465 case MONO_TYPE_OBJECT:
11466 case MONO_TYPE_CLASS:
11467 case MONO_TYPE_SZARRAY:
11468 case MONO_TYPE_PTR:
11469 case MONO_TYPE_FNPTR:
11470 case MONO_TYPE_ARRAY:
11471 *align = sizeof (gpointer);
11472 return sizeof (gpointer);
11473 case MONO_TYPE_R4:
11474 *align = 4;
11475 return 4;
11476 case MONO_TYPE_R8:
11477 *align = MONO_ABI_ALIGNOF (double);
11478 return 8;
11479 case MONO_TYPE_I8:
11480 case MONO_TYPE_U8:
11481 *align = MONO_ABI_ALIGNOF (gint64);
11482 return 8;
11483 case MONO_TYPE_GENERICINST:
11484 if (!mono_type_generic_inst_is_valuetype (t)) {
11485 *align = sizeof (gpointer);
11486 return sizeof (gpointer);
11488 /* Fall through */
11489 case MONO_TYPE_TYPEDBYREF:
11490 case MONO_TYPE_VALUETYPE: {
11491 guint32 size;
11492 MonoClass *klass = mono_class_from_mono_type (t);
11494 if (klass->enumtype)
11495 return mono_type_native_stack_size (mono_class_enum_basetype (klass), align);
11496 else {
11497 size = mono_class_native_size (klass, align);
11498 *align = *align + 3;
11499 *align &= ~3;
11501 size += 3;
11502 size &= ~3;
11504 return size;
11507 default:
11508 g_error ("type 0x%02x unknown", t->type);
11510 return 0;
11513 gint32
11514 mono_marshal_type_size (MonoType *type, MonoMarshalSpec *mspec, guint32 *align,
11515 gboolean as_field, gboolean unicode)
11517 MonoMarshalNative native_type = mono_type_to_unmanaged (type, mspec, as_field, unicode, NULL);
11518 MonoClass *klass;
11520 switch (native_type) {
11521 case MONO_NATIVE_BOOLEAN:
11522 *align = 4;
11523 return 4;
11524 case MONO_NATIVE_I1:
11525 case MONO_NATIVE_U1:
11526 *align = 1;
11527 return 1;
11528 case MONO_NATIVE_I2:
11529 case MONO_NATIVE_U2:
11530 case MONO_NATIVE_VARIANTBOOL:
11531 *align = 2;
11532 return 2;
11533 case MONO_NATIVE_I4:
11534 case MONO_NATIVE_U4:
11535 case MONO_NATIVE_ERROR:
11536 *align = 4;
11537 return 4;
11538 case MONO_NATIVE_I8:
11539 case MONO_NATIVE_U8:
11540 *align = MONO_ABI_ALIGNOF (gint64);
11541 return 8;
11542 case MONO_NATIVE_R4:
11543 *align = 4;
11544 return 4;
11545 case MONO_NATIVE_R8:
11546 *align = MONO_ABI_ALIGNOF (double);
11547 return 8;
11548 case MONO_NATIVE_INT:
11549 case MONO_NATIVE_UINT:
11550 case MONO_NATIVE_LPSTR:
11551 case MONO_NATIVE_LPWSTR:
11552 case MONO_NATIVE_LPTSTR:
11553 case MONO_NATIVE_BSTR:
11554 case MONO_NATIVE_ANSIBSTR:
11555 case MONO_NATIVE_TBSTR:
11556 case MONO_NATIVE_UTF8STR:
11557 case MONO_NATIVE_LPARRAY:
11558 case MONO_NATIVE_SAFEARRAY:
11559 case MONO_NATIVE_IUNKNOWN:
11560 case MONO_NATIVE_IDISPATCH:
11561 case MONO_NATIVE_INTERFACE:
11562 case MONO_NATIVE_ASANY:
11563 case MONO_NATIVE_FUNC:
11564 case MONO_NATIVE_LPSTRUCT:
11565 *align = MONO_ABI_ALIGNOF (gpointer);
11566 return sizeof (gpointer);
11567 case MONO_NATIVE_STRUCT:
11568 klass = mono_class_from_mono_type (type);
11569 if (klass == mono_defaults.object_class &&
11570 (mspec && mspec->native == MONO_NATIVE_STRUCT)) {
11571 *align = 16;
11572 return 16;
11574 return mono_class_native_size (klass, align);
11575 case MONO_NATIVE_BYVALTSTR: {
11576 int esize = unicode ? 2: 1;
11577 g_assert (mspec);
11578 *align = esize;
11579 return mspec->data.array_data.num_elem * esize;
11581 case MONO_NATIVE_BYVALARRAY: {
11582 // FIXME: Have to consider ArraySubType
11583 int esize;
11584 klass = mono_class_from_mono_type (type);
11585 if (klass->element_class == mono_defaults.char_class) {
11586 esize = unicode ? 2 : 1;
11587 *align = esize;
11588 } else {
11589 esize = mono_class_native_size (klass->element_class, align);
11591 g_assert (mspec);
11592 return mspec->data.array_data.num_elem * esize;
11594 case MONO_NATIVE_CUSTOM:
11595 *align = sizeof (gpointer);
11596 return sizeof (gpointer);
11597 break;
11598 case MONO_NATIVE_CURRENCY:
11599 case MONO_NATIVE_VBBYREFSTR:
11600 default:
11601 g_error ("native type %02x not implemented", native_type);
11602 break;
11604 g_assert_not_reached ();
11605 return 0;
11608 /* This is a JIT icall, it sets the pending exception and return NULL on error */
11609 gpointer
11610 mono_marshal_asany (MonoObject *o, MonoMarshalNative string_encoding, int param_attrs)
11612 MonoError error;
11613 MonoType *t;
11614 MonoClass *klass;
11616 if (o == NULL)
11617 return NULL;
11619 t = &o->vtable->klass->byval_arg;
11620 switch (t->type) {
11621 case MONO_TYPE_I4:
11622 case MONO_TYPE_U4:
11623 case MONO_TYPE_PTR:
11624 case MONO_TYPE_I1:
11625 case MONO_TYPE_U1:
11626 case MONO_TYPE_BOOLEAN:
11627 case MONO_TYPE_I2:
11628 case MONO_TYPE_U2:
11629 case MONO_TYPE_CHAR:
11630 case MONO_TYPE_I8:
11631 case MONO_TYPE_U8:
11632 case MONO_TYPE_R4:
11633 case MONO_TYPE_R8:
11634 return mono_object_unbox (o);
11635 break;
11636 case MONO_TYPE_STRING:
11637 switch (string_encoding) {
11638 case MONO_NATIVE_LPWSTR:
11639 return mono_marshal_string_to_utf16_copy ((MonoString*)o);
11640 case MONO_NATIVE_LPSTR:
11641 case MONO_NATIVE_UTF8STR:
11642 // Same code path, because in Mono, we treated strings as Utf8
11643 return mono_string_to_utf8str ((MonoString*)o);
11644 default:
11645 g_warning ("marshaling conversion %d not implemented", string_encoding);
11646 g_assert_not_reached ();
11648 break;
11649 case MONO_TYPE_CLASS:
11650 case MONO_TYPE_VALUETYPE: {
11651 MonoMethod *method;
11652 gpointer pa [3];
11653 gpointer res;
11654 MonoBoolean delete_old = FALSE;
11656 klass = t->data.klass;
11658 if (mono_class_is_auto_layout (klass))
11659 break;
11661 if (klass->valuetype && (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype))
11662 return mono_object_unbox (o);
11664 res = mono_marshal_alloc (mono_class_native_size (klass, NULL), &error);
11665 if (!mono_error_ok (&error)) {
11666 mono_error_set_pending_exception (&error);
11667 return NULL;
11670 if (!((param_attrs & PARAM_ATTRIBUTE_OUT) && !(param_attrs & PARAM_ATTRIBUTE_IN))) {
11671 method = mono_marshal_get_struct_to_ptr (o->vtable->klass);
11673 pa [0] = o;
11674 pa [1] = &res;
11675 pa [2] = &delete_old;
11677 mono_runtime_invoke_checked (method, NULL, pa, &error);
11678 if (!mono_error_ok (&error)) {
11679 mono_error_set_pending_exception (&error);
11680 return NULL;
11684 return res;
11686 default:
11687 break;
11689 mono_set_pending_exception (mono_get_exception_argument ("", "No PInvoke conversion exists for value passed to Object-typed parameter."));
11690 return NULL;
11693 /* This is a JIT icall, it sets the pending exception */
11694 void
11695 mono_marshal_free_asany (MonoObject *o, gpointer ptr, MonoMarshalNative string_encoding, int param_attrs)
11697 MonoError error;
11698 MonoType *t;
11699 MonoClass *klass;
11701 if (o == NULL)
11702 return;
11704 t = &o->vtable->klass->byval_arg;
11705 switch (t->type) {
11706 case MONO_TYPE_STRING:
11707 switch (string_encoding) {
11708 case MONO_NATIVE_LPWSTR:
11709 case MONO_NATIVE_LPSTR:
11710 case MONO_NATIVE_UTF8STR:
11711 mono_marshal_free (ptr);
11712 break;
11713 default:
11714 g_warning ("marshaling conversion %d not implemented", string_encoding);
11715 g_assert_not_reached ();
11717 break;
11718 case MONO_TYPE_CLASS:
11719 case MONO_TYPE_VALUETYPE: {
11720 klass = t->data.klass;
11722 if (klass->valuetype && (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype))
11723 break;
11725 if (param_attrs & PARAM_ATTRIBUTE_OUT) {
11726 MonoMethod *method = mono_marshal_get_ptr_to_struct (o->vtable->klass);
11727 gpointer pa [2];
11729 pa [0] = &ptr;
11730 pa [1] = o;
11732 mono_runtime_invoke_checked (method, NULL, pa, &error);
11733 if (!mono_error_ok (&error)) {
11734 mono_error_set_pending_exception (&error);
11735 return;
11739 if (!((param_attrs & PARAM_ATTRIBUTE_OUT) && !(param_attrs & PARAM_ATTRIBUTE_IN))) {
11740 mono_struct_delete_old (klass, (char *)ptr);
11743 mono_marshal_free (ptr);
11744 break;
11746 default:
11747 break;
11751 MonoMethod *
11752 mono_marshal_get_generic_array_helper (MonoClass *klass, MonoClass *iface, gchar *name, MonoMethod *method)
11754 MonoMethodSignature *sig, *csig;
11755 MonoMethodBuilder *mb;
11756 MonoMethod *res;
11757 WrapperInfo *info;
11758 int i;
11760 mb = mono_mb_new_no_dup_name (klass, name, MONO_WRAPPER_MANAGED_TO_MANAGED);
11761 mb->method->slot = -1;
11763 mb->method->flags = METHOD_ATTRIBUTE_PRIVATE | METHOD_ATTRIBUTE_VIRTUAL |
11764 METHOD_ATTRIBUTE_NEW_SLOT | METHOD_ATTRIBUTE_HIDE_BY_SIG | METHOD_ATTRIBUTE_FINAL;
11766 sig = mono_method_signature (method);
11767 csig = mono_metadata_signature_dup_full (method->klass->image, sig);
11768 csig->generic_param_count = 0;
11770 #ifndef DISABLE_JIT
11771 mono_mb_emit_ldarg (mb, 0);
11772 for (i = 0; i < csig->param_count; i++)
11773 mono_mb_emit_ldarg (mb, i + 1);
11774 mono_mb_emit_managed_call (mb, method, NULL);
11775 mono_mb_emit_byte (mb, CEE_RET);
11777 /* We can corlib internal methods */
11778 mb->skip_visibility = TRUE;
11779 #endif
11780 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER);
11781 info->d.generic_array_helper.method = method;
11782 res = mono_mb_create (mb, csig, csig->param_count + 16, info);
11784 mono_mb_free (mb);
11786 return res;
11790 * The mono_win32_compat_* functions are implementations of inline
11791 * Windows kernel32 APIs, which are DllImport-able under MS.NET,
11792 * although not exported by kernel32.
11794 * We map the appropiate kernel32 entries to these functions using
11795 * dllmaps declared in the global etc/mono/config.
11798 void
11799 mono_win32_compat_CopyMemory (gpointer dest, gconstpointer source, gsize length)
11801 if (!dest || !source)
11802 return;
11804 memcpy (dest, source, length);
11807 void
11808 mono_win32_compat_FillMemory (gpointer dest, gsize length, guchar fill)
11810 memset (dest, fill, length);
11813 void
11814 mono_win32_compat_MoveMemory (gpointer dest, gconstpointer source, gsize length)
11816 if (!dest || !source)
11817 return;
11819 memmove (dest, source, length);
11822 void
11823 mono_win32_compat_ZeroMemory (gpointer dest, gsize length)
11825 memset (dest, 0, length);
11828 void
11829 mono_marshal_find_nonzero_bit_offset (guint8 *buf, int len, int *byte_offset, guint8 *bitmask)
11831 int i;
11832 guint8 byte;
11834 for (i = 0; i < len; ++i)
11835 if (buf [i])
11836 break;
11838 g_assert (i < len);
11840 byte = buf [i];
11841 while (byte && !(byte & 1))
11842 byte >>= 1;
11843 g_assert (byte == 1);
11845 *byte_offset = i;
11846 *bitmask = buf [i];
11849 MonoMethod *
11850 mono_marshal_get_thunk_invoke_wrapper (MonoMethod *method)
11852 MonoMethodBuilder *mb;
11853 MonoMethodSignature *sig, *csig;
11854 MonoExceptionClause *clause;
11855 MonoImage *image;
11856 MonoClass *klass;
11857 GHashTable *cache;
11858 MonoMethod *res;
11859 int i, param_count, sig_size, pos_leave;
11861 g_assert (method);
11863 // FIXME: we need to store the exception into a MonoHandle
11864 g_assert (!mono_threads_is_coop_enabled ());
11866 klass = method->klass;
11867 image = method->klass->image;
11869 cache = get_cache (&mono_method_get_wrapper_cache (method)->thunk_invoke_cache, mono_aligned_addr_hash, NULL);
11871 if ((res = mono_marshal_find_in_cache (cache, method)))
11872 return res;
11874 sig = mono_method_signature (method);
11875 mb = mono_mb_new (klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
11877 /* add "this" and exception param */
11878 param_count = sig->param_count + sig->hasthis + 1;
11880 /* dup & extend signature */
11881 csig = mono_metadata_signature_alloc (image, param_count);
11882 sig_size = MONO_SIZEOF_METHOD_SIGNATURE + sig->param_count * sizeof (MonoType *);
11883 memcpy (csig, sig, sig_size);
11884 csig->param_count = param_count;
11885 csig->hasthis = 0;
11886 csig->pinvoke = 1;
11887 csig->call_convention = MONO_CALL_DEFAULT;
11889 if (sig->hasthis) {
11890 /* add "this" */
11891 csig->params [0] = &klass->byval_arg;
11892 /* move params up by one */
11893 for (i = 0; i < sig->param_count; i++)
11894 csig->params [i + 1] = sig->params [i];
11897 /* setup exception param as byref+[out] */
11898 csig->params [param_count - 1] = mono_metadata_type_dup (image,
11899 &mono_defaults.exception_class->byval_arg);
11900 csig->params [param_count - 1]->byref = 1;
11901 csig->params [param_count - 1]->attrs = PARAM_ATTRIBUTE_OUT;
11903 /* convert struct return to object */
11904 if (MONO_TYPE_ISSTRUCT (sig->ret))
11905 csig->ret = &mono_defaults.object_class->byval_arg;
11907 #ifndef DISABLE_JIT
11908 /* local 0 (temp for exception object) */
11909 mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
11911 /* local 1 (temp for result) */
11912 if (!MONO_TYPE_IS_VOID (sig->ret))
11913 mono_mb_add_local (mb, sig->ret);
11915 /* clear exception arg */
11916 mono_mb_emit_ldarg (mb, param_count - 1);
11917 mono_mb_emit_byte (mb, CEE_LDNULL);
11918 mono_mb_emit_byte (mb, CEE_STIND_REF);
11920 /* try */
11921 clause = (MonoExceptionClause *)mono_image_alloc0 (image, sizeof (MonoExceptionClause));
11922 clause->try_offset = mono_mb_get_label (mb);
11924 /* push method's args */
11925 for (i = 0; i < param_count - 1; i++) {
11926 MonoType *type;
11927 MonoClass *klass;
11929 mono_mb_emit_ldarg (mb, i);
11931 /* get the byval type of the param */
11932 klass = mono_class_from_mono_type (csig->params [i]);
11933 type = &klass->byval_arg;
11935 /* unbox struct args */
11936 if (MONO_TYPE_ISSTRUCT (type)) {
11937 mono_mb_emit_op (mb, CEE_UNBOX, klass);
11939 /* byref args & and the "this" arg must remain a ptr.
11940 Otherwise make a copy of the value type */
11941 if (!(csig->params [i]->byref || (i == 0 && sig->hasthis)))
11942 mono_mb_emit_op (mb, CEE_LDOBJ, klass);
11944 csig->params [i] = &mono_defaults.object_class->byval_arg;
11948 /* call */
11949 if (method->flags & METHOD_ATTRIBUTE_VIRTUAL)
11950 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
11951 else
11952 mono_mb_emit_op (mb, CEE_CALL, method);
11954 /* save result at local 1 */
11955 if (!MONO_TYPE_IS_VOID (sig->ret))
11956 mono_mb_emit_stloc (mb, 1);
11958 pos_leave = mono_mb_emit_branch (mb, CEE_LEAVE);
11960 /* catch */
11961 clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
11962 clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
11963 clause->data.catch_class = mono_defaults.object_class;
11965 clause->handler_offset = mono_mb_get_label (mb);
11967 /* store exception at local 0 */
11968 mono_mb_emit_stloc (mb, 0);
11969 mono_mb_emit_ldarg (mb, param_count - 1);
11970 mono_mb_emit_ldloc (mb, 0);
11971 mono_mb_emit_byte (mb, CEE_STIND_REF);
11972 mono_mb_emit_branch (mb, CEE_LEAVE);
11974 clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
11976 mono_mb_set_clauses (mb, 1, clause);
11978 mono_mb_patch_branch (mb, pos_leave);
11979 /* end-try */
11981 if (!MONO_TYPE_IS_VOID (sig->ret)) {
11982 mono_mb_emit_ldloc (mb, 1);
11984 /* box the return value */
11985 if (MONO_TYPE_ISSTRUCT (sig->ret))
11986 mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (sig->ret));
11989 mono_mb_emit_byte (mb, CEE_RET);
11990 #endif
11992 res = mono_mb_create_and_cache (cache, method, mb, csig, param_count + 16);
11993 mono_mb_free (mb);
11995 return res;
11999 * mono_marshal_free_dynamic_wrappers:
12001 * Free wrappers of the dynamic method METHOD.
12003 void
12004 mono_marshal_free_dynamic_wrappers (MonoMethod *method)
12006 MonoImage *image = method->klass->image;
12008 g_assert (method_is_dynamic (method));
12010 /* This could be called during shutdown */
12011 if (marshal_mutex_initialized)
12012 mono_marshal_lock ();
12014 * FIXME: We currently leak the wrappers. Freeing them would be tricky as
12015 * they could be shared with other methods ?
12017 if (image->wrapper_caches.runtime_invoke_direct_cache)
12018 g_hash_table_remove (image->wrapper_caches.runtime_invoke_direct_cache, method);
12019 if (image->wrapper_caches.delegate_abstract_invoke_cache)
12020 g_hash_table_foreach_remove (image->wrapper_caches.delegate_abstract_invoke_cache, signature_pointer_pair_matches_pointer, method);
12021 // FIXME: Need to clear the caches in other images as well
12022 if (image->delegate_bound_static_invoke_cache)
12023 g_hash_table_remove (image->delegate_bound_static_invoke_cache, mono_method_signature (method));
12025 if (marshal_mutex_initialized)
12026 mono_marshal_unlock ();
12029 static void
12030 mono_marshal_ftnptr_eh_callback (guint32 gchandle)
12032 g_assert (ftnptr_eh_callback);
12033 ftnptr_eh_callback (gchandle);
12036 static void
12037 ftnptr_eh_callback_default (guint32 gchandle)
12039 MonoException *exc;
12040 gpointer stackdata;
12042 mono_threads_enter_gc_unsafe_region_unbalanced (&stackdata);
12044 exc = (MonoException*) mono_gchandle_get_target (gchandle);
12046 mono_gchandle_free (gchandle);
12048 mono_raise_exception (exc);
12052 * mono_install_ftnptr_eh_callback:
12054 * Install a callback that should be called when there is a managed exception
12055 * in a native-to-managed wrapper. This is mainly used by iOS to convert a
12056 * managed exception to a native exception, to properly unwind the native
12057 * stack; this native exception will then be converted back to a managed
12058 * exception in their managed-to-native wrapper.
12060 void
12061 mono_install_ftnptr_eh_callback (MonoFtnPtrEHCallback callback)
12063 ftnptr_eh_callback = callback;
12066 static MonoThreadInfo*
12067 mono_icall_start (HandleStackMark *stackmark, MonoError *error)
12069 MonoThreadInfo *info = mono_thread_info_current ();
12071 mono_stack_mark_init (info, stackmark);
12072 mono_error_init (error);
12073 return info;
12076 static void
12077 mono_icall_end (MonoThreadInfo *info, HandleStackMark *stackmark, MonoError *error)
12079 mono_stack_mark_pop (info, stackmark);
12080 mono_error_set_pending_exception (error);