Merge pull request #1588 from BrzVlad/feature-aot-wbarrier
[mono.git] / mono / metadata / marshal.c
1 /*
2  * marshal.c: Routines for marshaling complex types in P/Invoke methods.
3  * 
4  * Author:
5  *   Paolo Molaro (lupus@ximian.com)
6  *
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)
10  *
11  */
12
13 #include "config.h"
14 #ifdef HAVE_ALLOCA_H
15 #include <alloca.h>
16 #endif
17
18 #include "object.h"
19 #include "loader.h"
20 #include "cil-coff.h"
21 #include "metadata/marshal.h"
22 #include "metadata/method-builder.h"
23 #include "metadata/tabledefs.h"
24 #include "metadata/exception.h"
25 #include "metadata/appdomain.h"
26 #include "mono/metadata/abi-details.h"
27 #include "mono/metadata/debug-helpers.h"
28 #include "mono/metadata/threadpool.h"
29 #include "mono/metadata/threads.h"
30 #include "mono/metadata/monitor.h"
31 #include "mono/metadata/metadata-internals.h"
32 #include "mono/metadata/domain-internals.h"
33 #include "mono/metadata/gc-internal.h"
34 #include "mono/metadata/threads-types.h"
35 #include "mono/metadata/string-icalls.h"
36 #include "mono/metadata/attrdefs.h"
37 #include "mono/metadata/gc-internal.h"
38 #include "mono/metadata/cominterop.h"
39 #include "mono/metadata/remoting.h"
40 #include "mono/metadata/reflection-internals.h"
41 #include "mono/utils/mono-counters.h"
42 #include "mono/utils/mono-tls.h"
43 #include "mono/utils/mono-memory-model.h"
44 #include "mono/utils/atomic.h"
45 #include <string.h>
46 #include <errno.h>
47
48 /* #define DEBUG_RUNTIME_CODE */
49
50 #define OPDEF(a,b,c,d,e,f,g,h,i,j) \
51         a = i,
52
53 enum {
54 #include "mono/cil/opcode.def"
55         LAST = 0xff
56 };
57 #undef OPDEF
58
59 /* 
60  * This mutex protects the various marshalling related caches in MonoImage
61  * and a few other data structures static to this file.
62  *
63  * The marshal lock is a non-recursive complex lock that sits below the domain lock in the
64  * runtime locking latice. Which means it can take simple locks suck as the image lock.
65  */
66 #define mono_marshal_lock() mono_locks_acquire (&marshal_mutex, MarshalLock)
67 #define mono_marshal_unlock() mono_locks_release (&marshal_mutex, MarshalLock)
68 static mono_mutex_t marshal_mutex;
69 static gboolean marshal_mutex_initialized;
70
71 static MonoNativeTlsKey last_error_tls_id;
72
73 static MonoNativeTlsKey load_type_info_tls_id;
74
75 static gboolean use_aot_wrappers;
76
77 static void
78 delegate_hash_table_add (MonoDelegate *d);
79
80 static void
81 emit_struct_conv (MonoMethodBuilder *mb, MonoClass *klass, gboolean to_object);
82
83 static void
84 emit_struct_conv_full (MonoMethodBuilder *mb, MonoClass *klass, gboolean to_object, MonoMarshalNative string_encoding);
85
86 static void 
87 mono_struct_delete_old (MonoClass *klass, char *ptr);
88
89 MONO_API void *
90 mono_marshal_string_to_utf16 (MonoString *s);
91
92 static void *
93 mono_marshal_string_to_utf16_copy (MonoString *s);
94
95 static gpointer
96 mono_string_to_lpstr (MonoString *string_obj);
97
98 static MonoStringBuilder *
99 mono_string_utf8_to_builder2 (char *text);
100
101 static MonoStringBuilder *
102 mono_string_utf16_to_builder2 (gunichar2 *text);
103
104 static MonoString*
105 mono_string_new_len_wrapper (const char *text, guint length);
106
107 static MonoString *
108 mono_string_from_byvalstr (const char *data, int len);
109
110 static MonoString *
111 mono_string_from_byvalwstr (gunichar2 *data, int len);
112
113 static void
114 mono_byvalarray_to_array (MonoArray *arr, gpointer native_arr, MonoClass *eltype, guint32 elnum);
115
116 static void
117 mono_byvalarray_to_byte_array (MonoArray *arr, gpointer native_arr, guint32 elnum);
118
119 static void
120 mono_array_to_byvalarray (gpointer native_arr, MonoArray *arr, MonoClass *eltype, guint32 elnum);
121
122 static void
123 mono_array_to_byte_byvalarray (gpointer native_arr, MonoArray *arr, guint32 elnum);
124
125 static MonoAsyncResult *
126 mono_delegate_begin_invoke (MonoDelegate *delegate, gpointer *params);
127
128 static MonoObject *
129 mono_delegate_end_invoke (MonoDelegate *delegate, gpointer *params);
130
131 static void
132 mono_marshal_set_last_error_windows (int error);
133
134 static void init_safe_handle (void);
135
136 /* MonoMethod pointers to SafeHandle::DangerousAddRef and ::DangerousRelease */
137 static MonoMethod *sh_dangerous_add_ref;
138 static MonoMethod *sh_dangerous_release;
139
140
141 static void
142 init_safe_handle ()
143 {
144         sh_dangerous_add_ref = mono_class_get_method_from_name (
145                 mono_defaults.safehandle_class, "DangerousAddRef", 1);
146         sh_dangerous_release = mono_class_get_method_from_name (
147                 mono_defaults.safehandle_class, "DangerousRelease", 0);
148 }
149
150 static void
151 register_icall (gpointer func, const char *name, const char *sigstr, gboolean save)
152 {
153         MonoMethodSignature *sig = mono_create_icall_signature (sigstr);
154
155         mono_register_jit_icall (func, name, sig, save);
156 }
157
158 static MonoMethodSignature*
159 signature_dup (MonoImage *image, MonoMethodSignature *sig)
160 {
161         MonoMethodSignature *res;
162         int sigsize;
163
164         res = mono_metadata_signature_alloc (image, sig->param_count);
165         sigsize = MONO_SIZEOF_METHOD_SIGNATURE + sig->param_count * sizeof (MonoType *);
166         memcpy (res, sig, sigsize);
167
168         return res;
169 }
170
171 MonoMethodSignature*
172 mono_signature_no_pinvoke (MonoMethod *method)
173 {
174         MonoMethodSignature *sig = mono_method_signature (method);
175         if (sig->pinvoke) {
176                 sig = signature_dup (method->klass->image, sig);
177                 sig->pinvoke = FALSE;
178         }
179         
180         return sig;
181 }
182
183 void
184 mono_marshal_init_tls (void)
185 {
186         mono_native_tls_alloc (&last_error_tls_id, NULL);
187         mono_native_tls_alloc (&load_type_info_tls_id, NULL);
188 }
189
190 void
191 mono_marshal_init (void)
192 {
193         static gboolean module_initialized = FALSE;
194
195         if (!module_initialized) {
196                 module_initialized = TRUE;
197                 mono_mutex_init_recursive (&marshal_mutex);
198                 marshal_mutex_initialized = TRUE;
199
200                 register_icall (ves_icall_System_Threading_Thread_ResetAbort, "ves_icall_System_Threading_Thread_ResetAbort", "void", TRUE);
201                 register_icall (mono_marshal_string_to_utf16, "mono_marshal_string_to_utf16", "ptr obj", FALSE);
202                 register_icall (mono_marshal_string_to_utf16_copy, "mono_marshal_string_to_utf16_copy", "ptr obj", FALSE);
203                 register_icall (mono_string_to_utf16, "mono_string_to_utf16", "ptr obj", FALSE);
204                 register_icall (mono_string_from_utf16, "mono_string_from_utf16", "obj ptr", FALSE);
205                 register_icall (mono_string_from_byvalstr, "mono_string_from_byvalstr", "obj ptr int", FALSE);
206                 register_icall (mono_string_from_byvalwstr, "mono_string_from_byvalwstr", "obj ptr int", FALSE);
207                 register_icall (mono_string_new_wrapper, "mono_string_new_wrapper", "obj ptr", FALSE);
208                 register_icall (mono_string_new_len_wrapper, "mono_string_new_len_wrapper", "obj ptr int", FALSE);
209                 register_icall (mono_string_to_utf8, "mono_string_to_utf8", "ptr obj", FALSE);
210                 register_icall (mono_string_to_lpstr, "mono_string_to_lpstr", "ptr obj", FALSE);
211                 register_icall (mono_string_to_ansibstr, "mono_string_to_ansibstr", "ptr object", FALSE);
212                 register_icall (mono_string_builder_to_utf8, "mono_string_builder_to_utf8", "ptr object", FALSE);
213                 register_icall (mono_string_builder_to_utf16, "mono_string_builder_to_utf16", "ptr object", FALSE);
214                 register_icall (mono_array_to_savearray, "mono_array_to_savearray", "ptr object", FALSE);
215                 register_icall (mono_array_to_lparray, "mono_array_to_lparray", "ptr object", FALSE);
216                 register_icall (mono_free_lparray, "mono_free_lparray", "void object ptr", FALSE);
217                 register_icall (mono_byvalarray_to_array, "mono_byvalarray_to_array", "void object ptr ptr int32", FALSE);
218                 register_icall (mono_byvalarray_to_byte_array, "mono_byvalarray_to_byte_array", "void object ptr int32", FALSE);
219                 register_icall (mono_array_to_byvalarray, "mono_array_to_byvalarray", "void ptr object ptr int32", FALSE);
220                 register_icall (mono_array_to_byte_byvalarray, "mono_array_to_byte_byvalarray", "void ptr object int32", FALSE);
221                 register_icall (mono_delegate_to_ftnptr, "mono_delegate_to_ftnptr", "ptr object", FALSE);
222                 register_icall (mono_ftnptr_to_delegate, "mono_ftnptr_to_delegate", "object ptr ptr", FALSE);
223                 register_icall (mono_marshal_asany, "mono_marshal_asany", "ptr object int32 int32", FALSE);
224                 register_icall (mono_marshal_free_asany, "mono_marshal_free_asany", "void object ptr int32 int32", FALSE);
225                 register_icall (mono_marshal_alloc, "mono_marshal_alloc", "ptr int32", FALSE);
226                 register_icall (mono_marshal_free, "mono_marshal_free", "void ptr", FALSE);
227                 register_icall (mono_marshal_set_last_error, "mono_marshal_set_last_error", "void", FALSE);
228                 register_icall (mono_marshal_set_last_error_windows, "mono_marshal_set_last_error_windows", "void int32", FALSE);
229                 register_icall (mono_string_utf8_to_builder, "mono_string_utf8_to_builder", "void ptr ptr", FALSE);
230                 register_icall (mono_string_utf8_to_builder2, "mono_string_utf8_to_builder2", "object ptr", FALSE);
231                 register_icall (mono_string_utf16_to_builder, "mono_string_utf16_to_builder", "void ptr ptr", FALSE);
232                 register_icall (mono_string_utf16_to_builder2, "mono_string_utf16_to_builder2", "object ptr", FALSE);
233                 register_icall (mono_marshal_free_array, "mono_marshal_free_array", "void ptr int32", FALSE);
234                 register_icall (mono_string_to_byvalstr, "mono_string_to_byvalstr", "void ptr ptr int32", FALSE);
235                 register_icall (mono_string_to_byvalwstr, "mono_string_to_byvalwstr", "void ptr ptr int32", FALSE);
236                 register_icall (g_free, "g_free", "void ptr", FALSE);
237                 register_icall (mono_object_isinst, "mono_object_isinst", "object object ptr", FALSE);
238                 register_icall (mono_struct_delete_old, "mono_struct_delete_old", "void ptr ptr", FALSE);
239                 register_icall (mono_delegate_begin_invoke, "mono_delegate_begin_invoke", "object object ptr", FALSE);
240                 register_icall (mono_delegate_end_invoke, "mono_delegate_end_invoke", "object object ptr", FALSE);
241                 register_icall (mono_compile_method, "mono_compile_method", "ptr ptr", FALSE);
242                 register_icall (mono_context_get, "mono_context_get", "object", FALSE);
243                 register_icall (mono_context_set, "mono_context_set", "void object", FALSE);
244                 register_icall (mono_gc_wbarrier_generic_nostore, "wb_generic", "void ptr", FALSE);
245                 register_icall (mono_gchandle_get_target, "mono_gchandle_get_target", "object int32", TRUE);
246
247                 mono_cominterop_init ();
248                 mono_remoting_init ();
249         }
250 }
251
252 void
253 mono_marshal_cleanup (void)
254 {
255         mono_cominterop_cleanup ();
256
257         mono_native_tls_free (load_type_info_tls_id);
258         mono_native_tls_free (last_error_tls_id);
259         mono_mutex_destroy (&marshal_mutex);
260         marshal_mutex_initialized = FALSE;
261 }
262
263 void
264 mono_marshal_lock_internal (void)
265 {
266         mono_marshal_lock ();
267 }
268
269 void
270 mono_marshal_unlock_internal (void)
271 {
272         mono_marshal_unlock ();
273 }
274
275 gpointer
276 mono_delegate_to_ftnptr (MonoDelegate *delegate)
277 {
278         MonoMethod *method, *wrapper;
279         MonoClass *klass;
280         uint32_t target_handle = 0;
281
282         if (!delegate)
283                 return NULL;
284
285         if (delegate->delegate_trampoline)
286                 return delegate->delegate_trampoline;
287
288         klass = ((MonoObject *)delegate)->vtable->klass;
289         g_assert (klass->delegate);
290
291         method = delegate->method;
292
293         if (mono_method_signature (method)->pinvoke) {
294                 const char *exc_class, *exc_arg;
295                 gpointer ftnptr;
296
297                 ftnptr = mono_lookup_pinvoke_call (method, &exc_class, &exc_arg);
298                 if (!ftnptr) {
299                         g_assert (exc_class);
300                         mono_raise_exception (mono_exception_from_name_msg (mono_defaults.corlib, "System", exc_class, exc_arg));
301                 }
302                 return ftnptr;
303         }
304
305         if (delegate->target) {
306                 /* Produce a location which can be embedded in JITted code */
307                 target_handle = mono_gchandle_new_weakref (delegate->target, FALSE);
308         }
309
310         wrapper = mono_marshal_get_managed_wrapper (method, klass, target_handle);
311
312         delegate->delegate_trampoline = mono_compile_method (wrapper);
313
314         // Add the delegate to the delegate hash table
315         delegate_hash_table_add (delegate);
316
317         /* when the object is collected, collect the dynamic method, too */
318         mono_object_register_finalizer ((MonoObject*)delegate);
319
320         return delegate->delegate_trampoline;
321 }
322
323 /* 
324  * this hash table maps from a delegate trampoline object to a weak reference
325  * of the delegate. As an optimizations with a non-moving GC we store the
326  * object pointer itself, otherwise we use a GC handle.
327  */
328 static GHashTable *delegate_hash_table;
329
330 static GHashTable *
331 delegate_hash_table_new (void) {
332         return g_hash_table_new (NULL, NULL);
333 }
334
335 static void 
336 delegate_hash_table_remove (MonoDelegate *d)
337 {
338         guint32 gchandle = 0;
339
340         mono_marshal_lock ();
341         if (delegate_hash_table == NULL)
342                 delegate_hash_table = delegate_hash_table_new ();
343         if (mono_gc_is_moving ())
344                 gchandle = GPOINTER_TO_UINT (g_hash_table_lookup (delegate_hash_table, d->delegate_trampoline));
345         g_hash_table_remove (delegate_hash_table, d->delegate_trampoline);
346         mono_marshal_unlock ();
347         if (mono_gc_is_moving ())
348                 mono_gchandle_free (gchandle);
349 }
350
351 static void
352 delegate_hash_table_add (MonoDelegate *d)
353 {
354         guint32 gchandle;
355         guint32 old_gchandle;
356
357         mono_marshal_lock ();
358         if (delegate_hash_table == NULL)
359                 delegate_hash_table = delegate_hash_table_new ();
360         if (mono_gc_is_moving ()) {
361                 gchandle = mono_gchandle_new_weakref ((MonoObject*)d, FALSE);
362                 old_gchandle = GPOINTER_TO_UINT (g_hash_table_lookup (delegate_hash_table, d->delegate_trampoline));
363                 g_hash_table_insert (delegate_hash_table, d->delegate_trampoline, GUINT_TO_POINTER (gchandle));
364                 if (old_gchandle)
365                         mono_gchandle_free (old_gchandle);
366         } else {
367                 g_hash_table_insert (delegate_hash_table, d->delegate_trampoline, d);
368         }
369         mono_marshal_unlock ();
370 }
371
372 /*
373  * mono_marshal_use_aot_wrappers:
374  *
375  *   Instructs this module to use AOT compatible wrappers.
376  */
377 void
378 mono_marshal_use_aot_wrappers (gboolean use)
379 {
380         use_aot_wrappers = use;
381 }
382
383 static void
384 parse_unmanaged_function_pointer_attr (MonoClass *klass, MonoMethodPInvoke *piinfo)
385 {
386         static MonoClass *UnmanagedFunctionPointerAttribute;
387         MonoCustomAttrInfo *cinfo;
388         MonoReflectionUnmanagedFunctionPointerAttribute *attr;
389
390         if (!UnmanagedFunctionPointerAttribute)
391                 UnmanagedFunctionPointerAttribute = mono_class_from_name (mono_defaults.corlib, "System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute");
392
393         /* The attribute is only available in Net 2.0 */
394         if (UnmanagedFunctionPointerAttribute) {
395                 /* 
396                  * The pinvoke attributes are stored in a real custom attribute so we have to
397                  * construct it.
398                  */
399                 cinfo = mono_custom_attrs_from_class (klass);
400                 if (cinfo && !mono_runtime_get_no_exec ()) {
401                         MonoError error;
402                         attr = (MonoReflectionUnmanagedFunctionPointerAttribute*)mono_custom_attrs_get_attr_checked (cinfo, UnmanagedFunctionPointerAttribute, &error);
403                         if (attr) {
404                                 piinfo->piflags = (attr->call_conv << 8) | (attr->charset ? (attr->charset - 1) * 2 : 1) | attr->set_last_error;
405                         } else {
406                                 if (!mono_error_ok (&error)) {
407                                         g_warning ("Could not load UnmanagedFunctionPointerAttribute due to %s", mono_error_get_message (&error));
408                                         mono_error_cleanup (&error);
409                                 }
410                         }
411                         if (!cinfo->cached)
412                                 mono_custom_attrs_free (cinfo);
413                 }
414         }
415 }
416
417 MonoDelegate*
418 mono_ftnptr_to_delegate (MonoClass *klass, gpointer ftn)
419 {
420         guint32 gchandle;
421         MonoDelegate *d;
422
423         if (ftn == NULL)
424                 return NULL;
425
426         mono_marshal_lock ();
427         if (delegate_hash_table == NULL)
428                 delegate_hash_table = delegate_hash_table_new ();
429
430         if (mono_gc_is_moving ()) {
431                 gchandle = GPOINTER_TO_UINT (g_hash_table_lookup (delegate_hash_table, ftn));
432                 mono_marshal_unlock ();
433                 if (gchandle)
434                         d = (MonoDelegate*)mono_gchandle_get_target (gchandle);
435                 else
436                         d = NULL;
437         } else {
438                 d = g_hash_table_lookup (delegate_hash_table, ftn);
439                 mono_marshal_unlock ();
440         }
441         if (d == NULL) {
442                 /* This is a native function, so construct a delegate for it */
443                 MonoMethodSignature *sig;
444                 MonoMethod *wrapper;
445                 MonoMarshalSpec **mspecs;
446                 MonoMethod *invoke = mono_get_delegate_invoke (klass);
447                 MonoMethodPInvoke piinfo;
448                 MonoObject *this;
449                 int i;
450
451                 if (use_aot_wrappers) {
452                         wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
453                         this = mono_value_box (mono_domain_get (), mono_defaults.int_class, &ftn);
454                 } else {
455                         memset (&piinfo, 0, sizeof (piinfo));
456                         parse_unmanaged_function_pointer_attr (klass, &piinfo);
457
458                         mspecs = g_new0 (MonoMarshalSpec*, mono_method_signature (invoke)->param_count + 1);
459                         mono_method_get_marshal_info (invoke, mspecs);
460                         /* Freed below so don't alloc from mempool */
461                         sig = mono_metadata_signature_dup (mono_method_signature (invoke));
462                         sig->hasthis = 0;
463
464                         wrapper = mono_marshal_get_native_func_wrapper (klass->image, sig, &piinfo, mspecs, ftn);
465                         this = NULL;
466
467                         for (i = mono_method_signature (invoke)->param_count; i >= 0; i--)
468                                 if (mspecs [i])
469                                         mono_metadata_free_marshal_spec (mspecs [i]);
470                         g_free (mspecs);
471                         g_free (sig);
472                 }
473
474                 d = (MonoDelegate*)mono_object_new (mono_domain_get (), klass);
475                 mono_delegate_ctor_with_method ((MonoObject*)d, this, mono_compile_method (wrapper), wrapper);
476         }
477
478         if (d->object.vtable->domain != mono_domain_get ())
479                 mono_raise_exception (mono_get_exception_not_supported ("Delegates cannot be marshalled from native code into a domain other than their home domain"));
480
481         return d;
482 }
483
484 void
485 mono_delegate_free_ftnptr (MonoDelegate *delegate)
486 {
487         MonoJitInfo *ji;
488         void *ptr;
489
490         delegate_hash_table_remove (delegate);
491
492         ptr = (gpointer)InterlockedExchangePointer (&delegate->delegate_trampoline, NULL);
493
494         if (!delegate->target) {
495                 /* The wrapper method is shared between delegates -> no need to free it */
496                 return;
497         }
498
499         if (ptr) {
500                 uint32_t gchandle;
501                 void **method_data;
502                 MonoMethod *method;
503
504                 ji = mono_jit_info_table_find (mono_domain_get (), mono_get_addr_from_ftnptr (ptr));
505                 g_assert (ji);
506
507                 method = mono_jit_info_get_method (ji);
508                 method_data = ((MonoMethodWrapper*)method)->method_data;
509
510                 /*the target gchandle is the first entry after size and the wrapper itself.*/
511                 gchandle = GPOINTER_TO_UINT (method_data [2]);
512
513                 if (gchandle)
514                         mono_gchandle_free (gchandle);
515
516                 mono_runtime_free_method (mono_object_domain (delegate), method);
517         }
518 }
519
520 static MonoString *
521 mono_string_from_byvalstr (const char *data, int max_len)
522 {
523         MonoDomain *domain = mono_domain_get ();
524         int len = 0;
525
526         if (!data)
527                 return NULL;
528
529         while (len < max_len - 1 && data [len])
530                 len++;
531
532         return mono_string_new_len (domain, data, len);
533 }
534
535 static MonoString *
536 mono_string_from_byvalwstr (gunichar2 *data, int max_len)
537 {
538         MonoDomain *domain = mono_domain_get ();
539         int len = 0;
540
541         if (!data)
542                 return NULL;
543
544         while (data [len]) len++;
545
546         return mono_string_new_utf16 (domain, data, MIN (len, max_len));
547 }
548
549 gpointer
550 mono_array_to_savearray (MonoArray *array)
551 {
552         if (!array)
553                 return NULL;
554
555         g_assert_not_reached ();
556         return NULL;
557 }
558
559 gpointer
560 mono_array_to_lparray (MonoArray *array)
561 {
562 #ifndef DISABLE_COM
563         gpointer *nativeArray = NULL;
564         int nativeArraySize = 0;
565
566         int i = 0;
567         MonoClass *klass;
568 #endif
569
570         if (!array)
571                 return NULL;
572 #ifndef DISABLE_COM
573
574         klass = array->obj.vtable->klass;
575
576         switch (klass->element_class->byval_arg.type) {
577         case MONO_TYPE_VOID:
578                 g_assert_not_reached ();
579                 break;
580         case MONO_TYPE_CLASS:
581                 nativeArraySize = array->max_length;
582                 nativeArray = malloc(sizeof(gpointer) * nativeArraySize);
583                 for(i = 0; i < nativeArraySize; ++i)    
584                         nativeArray[i] = ves_icall_System_Runtime_InteropServices_Marshal_GetIUnknownForObjectInternal(((gpointer*)array->vector)[i]);
585                 return nativeArray;
586         case MONO_TYPE_U1:
587         case MONO_TYPE_BOOLEAN:
588         case MONO_TYPE_I1:
589         case MONO_TYPE_U2:
590         case MONO_TYPE_CHAR:
591         case MONO_TYPE_I2:
592         case MONO_TYPE_I:
593         case MONO_TYPE_U:
594         case MONO_TYPE_I4:
595         case MONO_TYPE_U4:
596         case MONO_TYPE_U8:
597         case MONO_TYPE_I8:
598         case MONO_TYPE_R4:
599         case MONO_TYPE_R8:
600         case MONO_TYPE_VALUETYPE:
601         case MONO_TYPE_PTR:
602                 /* nothing to do */
603                 break;
604         case MONO_TYPE_GENERICINST:
605         case MONO_TYPE_OBJECT:
606         case MONO_TYPE_ARRAY: 
607         case MONO_TYPE_SZARRAY:
608         case MONO_TYPE_STRING:
609         default:
610                 g_warning ("type 0x%x not handled", klass->element_class->byval_arg.type);
611                 g_assert_not_reached ();
612         }
613 #endif
614         return array->vector;
615 }
616
617 void
618 mono_free_lparray (MonoArray *array, gpointer* nativeArray)
619 {
620 #ifndef DISABLE_COM
621         MonoClass *klass;
622         int i = 0;
623
624         if (!array)
625                 return;
626
627         if (!nativeArray)
628                 return;
629         klass = array->obj.vtable->klass;
630
631         if (klass->element_class->byval_arg.type == MONO_TYPE_CLASS) {
632                 for(i = 0; i < array->max_length; ++i)
633                         mono_marshal_free_ccw (mono_array_get (array, MonoObject*, i));
634                 free(nativeArray);
635         }
636 #endif
637 }
638
639 static void
640 mono_byvalarray_to_array (MonoArray *arr, gpointer native_arr, MonoClass *elclass, guint32 elnum)
641 {
642         g_assert (arr->obj.vtable->klass->element_class == mono_defaults.char_class);
643
644         if (elclass == mono_defaults.byte_class) {
645                 GError *error = NULL;
646                 guint16 *ut;
647                 glong items_written;
648
649                 ut = g_utf8_to_utf16 (native_arr, elnum, NULL, &items_written, &error);
650
651                 if (!error) {
652                         memcpy (mono_array_addr (arr, guint16, 0), ut, items_written * sizeof (guint16));
653                         g_free (ut);
654                 }
655                 else
656                         g_error_free (error);
657         }
658         else
659                 g_assert_not_reached ();
660 }
661
662 static void
663 mono_byvalarray_to_byte_array (MonoArray *arr, gpointer native_arr, guint32 elnum)
664 {
665         mono_byvalarray_to_array (arr, native_arr, mono_defaults.byte_class, elnum);
666 }
667
668 static void
669 mono_array_to_byvalarray (gpointer native_arr, MonoArray *arr, MonoClass *elclass, guint32 elnum)
670 {
671         g_assert (arr->obj.vtable->klass->element_class == mono_defaults.char_class);
672
673         if (elclass == mono_defaults.byte_class) {
674                 char *as;
675                 GError *error = NULL;
676
677                 as = g_utf16_to_utf8 (mono_array_addr (arr, gunichar2, 0), mono_array_length (arr), NULL, NULL, &error);
678                 if (error) {
679                         MonoException *exc = mono_get_exception_argument ("string", error->message);
680                         g_error_free (error);
681                         mono_raise_exception (exc);
682                 }
683
684                 memcpy (native_arr, as, MIN (strlen (as), elnum));
685                 g_free (as);
686         } else {
687                 g_assert_not_reached ();
688         }
689 }
690
691 static void
692 mono_array_to_byte_byvalarray (gpointer native_arr, MonoArray *arr, guint32 elnum)
693 {
694         mono_array_to_byvalarray (native_arr, arr, mono_defaults.byte_class, elnum);
695 }
696
697 static MonoStringBuilder *
698 mono_string_builder_new (void)
699 {
700         static MonoClass *string_builder_class;
701         static MonoMethod *sb_ctor;
702         static void *args [1];
703         static int initial_len;
704
705         if (!string_builder_class) {
706                 MonoMethodDesc *desc;
707
708                 string_builder_class = mono_class_from_name (mono_defaults.corlib, "System.Text", "StringBuilder");
709                 g_assert (string_builder_class);
710                 desc = mono_method_desc_new (":.ctor(int)", FALSE);
711                 sb_ctor = mono_method_desc_search_in_class (desc, string_builder_class);
712                 g_assert (sb_ctor);
713                 mono_method_desc_free (desc);
714
715                 // We make a new array in the _to_builder function, so this
716                 // array will always be garbage collected.
717                 initial_len = 1;
718                 args [0] = &initial_len;
719         }
720
721         MonoStringBuilder *sb = (MonoStringBuilder*)mono_object_new (mono_domain_get (), string_builder_class);
722         MonoObject *exc;
723         g_assert (sb);
724
725         mono_runtime_invoke (sb_ctor, sb, args, &exc);
726
727         g_assert (sb->chunkChars->max_length == initial_len);
728         g_assert (!exc);
729
730         return sb;
731 }
732
733 static void
734 mono_string_utf16_to_builder_copy (MonoStringBuilder *sb, gunichar2 *text, size_t len)
735 {
736         MonoClass *ac = mono_array_class_get (mono_defaults.char_class, 1);
737         g_assert (ac);
738
739         MonoArray* newArray = mono_array_new (mono_domain_get (), mono_defaults.char_class, len);
740
741         gunichar2 *charDst = (gunichar2 *)newArray->vector;
742         gunichar2 *charSrc = (gunichar2 *)text;
743         memcpy (charDst, charSrc, sizeof (gunichar2) * len);
744
745         MONO_OBJECT_SETREF (sb, chunkChars, newArray);
746         sb->chunkOffset = 0;
747         sb->chunkLength = len;
748
749         return;
750 }
751
752 MonoStringBuilder *
753 mono_string_utf16_to_builder2 (gunichar2 *text)
754 {
755         if (!text)
756                 return NULL;
757
758         MonoStringBuilder *sb = mono_string_builder_new ();
759         mono_string_utf16_to_builder (sb, text);
760
761         return sb;
762 }
763
764 void
765 mono_string_utf8_to_builder (MonoStringBuilder *sb, char *text)
766 {
767
768         if (!sb || !text)
769                 return;
770
771         int len = strlen (text);
772         GError *error = NULL;
773         gunichar2* ut = g_utf8_to_utf16 (text, len, NULL, NULL, &error);
774
775         if (!error) {
776                 MONO_OBJECT_SETREF (sb, chunkPrevious, NULL);
777                 mono_string_utf16_to_builder_copy (sb, ut, len);
778         } else
779                 g_error_free (error);
780
781         g_free (ut);
782 }
783
784 MonoStringBuilder *
785 mono_string_utf8_to_builder2 (char *text)
786 {
787         if (!text)
788                 return NULL;
789
790         MonoStringBuilder *sb = mono_string_builder_new ();
791         mono_string_utf8_to_builder (sb, text);
792
793         return sb;
794 }
795
796
797 void
798 mono_string_utf16_to_builder (MonoStringBuilder *sb, gunichar2 *text)
799 {
800         if (!sb || !text)
801                 return;
802
803         guint32 len;
804         for (len = 0; text [len] != 0; ++len);
805
806         mono_string_utf16_to_builder_copy (sb, text, len);
807 }
808
809 /**
810  * mono_string_builder_to_utf8:
811  * @sb: the string builder
812  *
813  * Converts to utf8 the contents of the MonoStringBuilder.
814  *
815  * Returns: a utf8 string with the contents of the StringBuilder.
816  *
817  * The return value must be released with g_free.
818  */
819 gchar*
820 mono_string_builder_to_utf8 (MonoStringBuilder *sb)
821 {
822         GError *error = NULL;
823
824         if (!sb)
825                 return NULL;
826
827
828         gunichar2 *str_utf16 = mono_string_builder_to_utf16 (sb);
829
830         guint str_len = mono_string_builder_string_length (sb);
831
832         gchar *tmp = g_utf16_to_utf8 (str_utf16, str_len, NULL, NULL, &error);
833
834         if (error) {
835                 g_error_free (error);
836                 g_free (str_utf16);
837                 mono_raise_exception (mono_get_exception_execution_engine ("Failed to convert StringBuilder from utf16 to utf8"));
838                 return NULL;
839         } else {
840                 guint len = mono_string_builder_length (sb) + 1;
841                 gchar *res = mono_marshal_alloc (len * sizeof (gchar));
842                 g_assert (str_len < len);
843                 memcpy (res, tmp, str_len * sizeof (gchar));
844                 res[str_len] = '\0';
845
846
847                 g_free (str_utf16);
848                 g_free (tmp);
849                 return res;
850         }
851 }
852
853 /**
854  * mono_string_builder_to_utf16:
855  * @sb: the string builder
856  *
857  * Converts to utf16 the contents of the MonoStringBuilder.
858  *
859  * Returns: a utf16 string with the contents of the StringBuilder.
860  *
861  * The return value must not be freed.
862  */
863 gunichar2*
864 mono_string_builder_to_utf16 (MonoStringBuilder *sb)
865 {
866         if (!sb)
867                 return NULL;
868
869         g_assert (sb->chunkChars);
870
871         guint len = mono_string_builder_length (sb);
872
873         if (len == 0)
874                 len = 1;
875
876         gunichar2 *str = mono_marshal_alloc ((len + 1) * sizeof (gunichar2));
877         str[len] = '\0';
878
879         if (len == 0)
880                 return str;
881
882         MonoStringBuilder* chunk = sb;
883         do {
884                 if (chunk->chunkLength > 0) {
885                         // Check that we will not overrun our boundaries.
886                         gunichar2 *source = (gunichar2 *)chunk->chunkChars->vector;
887
888                         if (chunk->chunkLength <= len) {
889                                 memcpy (str + chunk->chunkOffset, source, chunk->chunkLength * sizeof(gunichar2));
890                         } else {
891                                 g_error ("A chunk in the StringBuilder had a length longer than expected from the offset.");
892                         }
893
894                         len -= chunk->chunkLength;
895                 }
896                 chunk = chunk->chunkPrevious;
897         } while (chunk != NULL);
898
899         return str;
900 }
901
902 static gpointer
903 mono_string_to_lpstr (MonoString *s)
904 {
905 #ifdef TARGET_WIN32
906         char *as, *tmp;
907         glong len;
908         GError *error = NULL;
909
910         if (s == NULL)
911                 return NULL;
912
913         if (!s->length) {
914                 as = CoTaskMemAlloc (1);
915                 as [0] = '\0';
916                 return as;
917         }
918
919         tmp = g_utf16_to_utf8 (mono_string_chars (s), s->length, NULL, &len, &error);
920         if (error) {
921                 MonoException *exc = mono_get_exception_argument ("string", error->message);
922                 g_error_free (error);
923                 mono_raise_exception(exc);
924                 return NULL;
925         } else {
926                 as = CoTaskMemAlloc (len + 1);
927                 memcpy (as, tmp, len + 1);
928                 g_free (tmp);
929                 return as;
930         }
931 #else
932         return mono_string_to_utf8 (s);
933 #endif
934 }       
935
936 gpointer
937 mono_string_to_ansibstr (MonoString *string_obj)
938 {
939         g_error ("UnmanagedMarshal.BStr is not implemented.");
940         return NULL;
941 }
942
943 /**
944  * mono_string_to_byvalstr:
945  * @dst: Where to store the null-terminated utf8 decoded string.
946  * @src: the MonoString to copy.
947  * @size: the maximum number of bytes to copy.
948  *
949  * Copies the MonoString pointed to by @src as a utf8 string
950  * into @dst, it copies at most @size bytes into the destination.
951  */
952 void
953 mono_string_to_byvalstr (gpointer dst, MonoString *src, int size)
954 {
955         char *s;
956         int len;
957
958         g_assert (dst != NULL);
959         g_assert (size > 0);
960
961         memset (dst, 0, size);
962         if (!src)
963                 return;
964
965         s = mono_string_to_utf8 (src);
966         len = MIN (size, strlen (s));
967         if (len >= size)
968                 len--;
969         memcpy (dst, s, len);
970         g_free (s);
971 }
972
973 /**
974  * mono_string_to_byvalwstr:
975  * @dst: Where to store the null-terminated utf16 decoded string.
976  * @src: the MonoString to copy.
977  * @size: the maximum number of bytes to copy.
978  *
979  * Copies the MonoString pointed to by @src as a utf16 string into
980  * @dst, it copies at most @size bytes into the destination (including
981  * a terminating 16-bit zero terminator).
982  */
983 void
984 mono_string_to_byvalwstr (gpointer dst, MonoString *src, int size)
985 {
986         int len;
987
988         g_assert (dst != NULL);
989         g_assert (size > 1);
990
991         if (!src) {
992                 memset (dst, 0, size * 2);
993                 return;
994         }
995
996         len = MIN (size, (mono_string_length (src)));
997         memcpy (dst, mono_string_chars (src), size * 2);
998         if (size <= mono_string_length (src))
999                 len--;
1000         *((gunichar2 *) dst + len) = 0;
1001 }
1002
1003 static MonoString*
1004 mono_string_new_len_wrapper (const char *text, guint length)
1005 {
1006         return mono_string_new_len (mono_domain_get (), text, length);
1007 }
1008
1009 #ifndef DISABLE_JIT
1010
1011 /*
1012  * mono_mb_emit_exception_marshal_directive:
1013  *
1014  *   This function assumes ownership of MSG, which should be malloc-ed.
1015  */
1016 static void
1017 mono_mb_emit_exception_marshal_directive (MonoMethodBuilder *mb, char *msg)
1018 {
1019         char *s;
1020
1021         if (!mb->dynamic) {
1022                 s = mono_image_strdup (mb->method->klass->image, msg);
1023                 g_free (msg);
1024         } else {
1025                 s = g_strdup (msg);
1026         }
1027         mono_mb_emit_exception_full (mb, "System.Runtime.InteropServices", "MarshalDirectiveException", s);
1028 }
1029
1030 #endif /* !DISABLE_JIT */
1031
1032 guint
1033 mono_type_to_ldind (MonoType *type)
1034 {
1035         if (type->byref)
1036                 return CEE_LDIND_I;
1037
1038 handle_enum:
1039         switch (type->type) {
1040         case MONO_TYPE_I1:
1041                 return CEE_LDIND_I1;
1042         case MONO_TYPE_U1:
1043         case MONO_TYPE_BOOLEAN:
1044                 return CEE_LDIND_U1;
1045         case MONO_TYPE_I2:
1046                 return CEE_LDIND_I2;
1047         case MONO_TYPE_U2:
1048         case MONO_TYPE_CHAR:
1049                 return CEE_LDIND_U2;
1050         case MONO_TYPE_I4:
1051                 return CEE_LDIND_I4;
1052         case MONO_TYPE_U4:
1053                 return CEE_LDIND_U4;
1054         case MONO_TYPE_I:
1055         case MONO_TYPE_U:
1056         case MONO_TYPE_PTR:
1057         case MONO_TYPE_FNPTR:
1058                 return CEE_LDIND_I;
1059         case MONO_TYPE_CLASS:
1060         case MONO_TYPE_STRING:
1061         case MONO_TYPE_OBJECT:
1062         case MONO_TYPE_SZARRAY:
1063         case MONO_TYPE_ARRAY:    
1064                 return CEE_LDIND_REF;
1065         case MONO_TYPE_I8:
1066         case MONO_TYPE_U8:
1067                 return CEE_LDIND_I8;
1068         case MONO_TYPE_R4:
1069                 return CEE_LDIND_R4;
1070         case MONO_TYPE_R8:
1071                 return CEE_LDIND_R8;
1072         case MONO_TYPE_VALUETYPE:
1073                 if (type->data.klass->enumtype) {
1074                         type = mono_class_enum_basetype (type->data.klass);
1075                         goto handle_enum;
1076                 }
1077                 return CEE_LDOBJ;
1078         case MONO_TYPE_TYPEDBYREF:
1079                 return CEE_LDOBJ;
1080         case MONO_TYPE_GENERICINST:
1081                 type = &type->data.generic_class->container_class->byval_arg;
1082                 goto handle_enum;
1083         default:
1084                 g_error ("unknown type 0x%02x in type_to_ldind", type->type);
1085         }
1086         return -1;
1087 }
1088
1089 guint
1090 mono_type_to_stind (MonoType *type)
1091 {
1092         if (type->byref)
1093                 return CEE_STIND_I;
1094
1095 handle_enum:
1096         switch (type->type) {
1097         case MONO_TYPE_I1:
1098         case MONO_TYPE_U1:
1099         case MONO_TYPE_BOOLEAN:
1100                 return CEE_STIND_I1;
1101         case MONO_TYPE_I2:
1102         case MONO_TYPE_U2:
1103         case MONO_TYPE_CHAR:
1104                 return CEE_STIND_I2;
1105         case MONO_TYPE_I4:
1106         case MONO_TYPE_U4:
1107                 return CEE_STIND_I4;
1108         case MONO_TYPE_I:
1109         case MONO_TYPE_U:
1110         case MONO_TYPE_PTR:
1111         case MONO_TYPE_FNPTR:
1112                 return CEE_STIND_I;
1113         case MONO_TYPE_CLASS:
1114         case MONO_TYPE_STRING:
1115         case MONO_TYPE_OBJECT:
1116         case MONO_TYPE_SZARRAY:
1117         case MONO_TYPE_ARRAY:    
1118                 return CEE_STIND_REF;
1119         case MONO_TYPE_I8:
1120         case MONO_TYPE_U8:
1121                 return CEE_STIND_I8;
1122         case MONO_TYPE_R4:
1123                 return CEE_STIND_R4;
1124         case MONO_TYPE_R8:
1125                 return CEE_STIND_R8;
1126         case MONO_TYPE_VALUETYPE:
1127                 if (type->data.klass->enumtype) {
1128                         type = mono_class_enum_basetype (type->data.klass);
1129                         goto handle_enum;
1130                 }
1131                 return CEE_STOBJ;
1132         case MONO_TYPE_TYPEDBYREF:
1133                 return CEE_STOBJ;
1134         case MONO_TYPE_GENERICINST:
1135                 type = &type->data.generic_class->container_class->byval_arg;
1136                 goto handle_enum;
1137         default:
1138                 g_error ("unknown type 0x%02x in type_to_stind", type->type);
1139         }
1140         return -1;
1141 }
1142
1143 #ifndef DISABLE_JIT
1144
1145 static void
1146 emit_ptr_to_object_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv conv, MonoMarshalSpec *mspec)
1147 {
1148         switch (conv) {
1149         case MONO_MARSHAL_CONV_BOOL_I4:
1150                 mono_mb_emit_ldloc (mb, 1);
1151                 mono_mb_emit_ldloc (mb, 0);
1152                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
1153                 mono_mb_emit_byte (mb, CEE_BRFALSE_S);
1154                 mono_mb_emit_byte (mb, 3);
1155                 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
1156                 mono_mb_emit_byte (mb, CEE_BR_S);
1157                 mono_mb_emit_byte (mb, 1);
1158                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
1159                 mono_mb_emit_byte (mb, CEE_STIND_I1);
1160                 break;
1161         case MONO_MARSHAL_CONV_BOOL_VARIANTBOOL:
1162                 mono_mb_emit_ldloc (mb, 1);
1163                 mono_mb_emit_ldloc (mb, 0);
1164                 mono_mb_emit_byte (mb, CEE_LDIND_I2);
1165                 mono_mb_emit_byte (mb, CEE_BRFALSE_S);
1166                 mono_mb_emit_byte (mb, 3);
1167                 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
1168                 mono_mb_emit_byte (mb, CEE_BR_S);
1169                 mono_mb_emit_byte (mb, 1);
1170                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
1171                 mono_mb_emit_byte (mb, CEE_STIND_I1);
1172                 break;
1173         case MONO_MARSHAL_CONV_ARRAY_BYVALARRAY: {
1174                 MonoClass *eklass = NULL;
1175                 int esize;
1176
1177                 if (type->type == MONO_TYPE_SZARRAY) {
1178                         eklass = type->data.klass;
1179                 } else {
1180                         g_assert_not_reached ();
1181                 }
1182
1183                 esize = mono_class_native_size (eklass, NULL);
1184
1185                 /* create a new array */
1186                 mono_mb_emit_ldloc (mb, 1);
1187                 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1188                 mono_mb_emit_op (mb, CEE_NEWARR, eklass);       
1189                 mono_mb_emit_byte (mb, CEE_STIND_I);
1190
1191                 if (eklass->blittable) {
1192                         /* copy the elements */
1193                         mono_mb_emit_ldloc (mb, 1);
1194                         mono_mb_emit_byte (mb, CEE_LDIND_I);
1195                         mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
1196                         mono_mb_emit_byte (mb, CEE_ADD);
1197                         mono_mb_emit_ldloc (mb, 0);
1198                         mono_mb_emit_icon (mb, mspec->data.array_data.num_elem * esize);
1199                         mono_mb_emit_byte (mb, CEE_PREFIX1);
1200                         mono_mb_emit_byte (mb, CEE_CPBLK);                      
1201                 }
1202                 else {
1203                         int array_var, src_var, dst_var, index_var;
1204                         guint32 label2, label3;
1205
1206                         array_var = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
1207                         src_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1208                         dst_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1209
1210                         /* set array_var */
1211                         mono_mb_emit_ldloc (mb, 1);
1212                         mono_mb_emit_byte (mb, CEE_LDIND_REF);
1213                         mono_mb_emit_stloc (mb, array_var);
1214                 
1215                         /* save the old src pointer */
1216                         mono_mb_emit_ldloc (mb, 0);
1217                         mono_mb_emit_stloc (mb, src_var);
1218                         /* save the old dst pointer */
1219                         mono_mb_emit_ldloc (mb, 1);
1220                         mono_mb_emit_stloc (mb, dst_var);
1221
1222                         /* Emit marshalling loop */
1223                         index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1224                         mono_mb_emit_byte (mb, CEE_LDC_I4_0);
1225                         mono_mb_emit_stloc (mb, index_var);
1226
1227                         /* Loop header */
1228                         label2 = mono_mb_get_label (mb);
1229                         mono_mb_emit_ldloc (mb, index_var);
1230                         mono_mb_emit_ldloc (mb, array_var);
1231                         mono_mb_emit_byte (mb, CEE_LDLEN);
1232                         label3 = mono_mb_emit_branch (mb, CEE_BGE);
1233
1234                         /* src is already set */
1235
1236                         /* Set dst */
1237                         mono_mb_emit_ldloc (mb, array_var);
1238                         mono_mb_emit_ldloc (mb, index_var);
1239                         mono_mb_emit_op (mb, CEE_LDELEMA, eklass);
1240                         mono_mb_emit_stloc (mb, 1);
1241
1242                         /* Do the conversion */
1243                         emit_struct_conv (mb, eklass, TRUE);
1244
1245                         /* Loop footer */
1246                         mono_mb_emit_add_to_local (mb, index_var, 1);
1247
1248                         mono_mb_emit_branch_label (mb, CEE_BR, label2);
1249
1250                         mono_mb_patch_branch (mb, label3);
1251                 
1252                         /* restore the old src pointer */
1253                         mono_mb_emit_ldloc (mb, src_var);
1254                         mono_mb_emit_stloc (mb, 0);
1255                         /* restore the old dst pointer */
1256                         mono_mb_emit_ldloc (mb, dst_var);
1257                         mono_mb_emit_stloc (mb, 1);
1258                 }
1259                 break;
1260         }
1261         case MONO_MARSHAL_CONV_ARRAY_BYVALCHARARRAY: {
1262                 MonoClass *eclass = mono_defaults.char_class;
1263
1264                 /* create a new array */
1265                 mono_mb_emit_ldloc (mb, 1);
1266                 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1267                 mono_mb_emit_op (mb, CEE_NEWARR, eclass);       
1268                 mono_mb_emit_byte (mb, CEE_STIND_REF);
1269
1270                 mono_mb_emit_ldloc (mb, 1);
1271                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1272                 mono_mb_emit_ldloc (mb, 0);
1273                 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1274                 mono_mb_emit_icall (mb, mono_byvalarray_to_byte_array);
1275                 break;
1276         }
1277         case MONO_MARSHAL_CONV_STR_BYVALSTR: 
1278                 if (mspec && mspec->native == MONO_NATIVE_BYVALTSTR && mspec->data.array_data.num_elem) {
1279                         mono_mb_emit_ldloc (mb, 1);
1280                         mono_mb_emit_ldloc (mb, 0);
1281                         mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1282                         mono_mb_emit_icall (mb, mono_string_from_byvalstr);
1283                 } else {
1284                         mono_mb_emit_ldloc (mb, 1);
1285                         mono_mb_emit_ldloc (mb, 0);
1286                         mono_mb_emit_icall (mb, mono_string_new_wrapper);
1287                 }
1288                 mono_mb_emit_byte (mb, CEE_STIND_REF);          
1289                 break;
1290         case MONO_MARSHAL_CONV_STR_BYVALWSTR:
1291                 if (mspec && mspec->native == MONO_NATIVE_BYVALTSTR && mspec->data.array_data.num_elem) {
1292                         mono_mb_emit_ldloc (mb, 1);
1293                         mono_mb_emit_ldloc (mb, 0);
1294                         mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1295                         mono_mb_emit_icall (mb, mono_string_from_byvalwstr);
1296                 } else {
1297                         mono_mb_emit_ldloc (mb, 1);
1298                         mono_mb_emit_ldloc (mb, 0);
1299                         mono_mb_emit_icall (mb, mono_string_from_utf16);
1300                 }
1301                 mono_mb_emit_byte (mb, CEE_STIND_REF);          
1302                 break;          
1303         case MONO_MARSHAL_CONV_STR_LPTSTR:
1304                 mono_mb_emit_ldloc (mb, 1);
1305                 mono_mb_emit_ldloc (mb, 0);
1306                 mono_mb_emit_byte (mb, CEE_LDIND_I);
1307 #ifdef TARGET_WIN32
1308                 mono_mb_emit_icall (mb, mono_string_from_utf16);
1309 #else
1310                 mono_mb_emit_icall (mb, mono_string_new_wrapper);
1311 #endif
1312                 mono_mb_emit_byte (mb, CEE_STIND_REF);  
1313                 break;
1314         case MONO_MARSHAL_CONV_STR_LPSTR:
1315                 mono_mb_emit_ldloc (mb, 1);
1316                 mono_mb_emit_ldloc (mb, 0);
1317                 mono_mb_emit_byte (mb, CEE_LDIND_I);
1318                 mono_mb_emit_icall (mb, mono_string_new_wrapper);
1319                 mono_mb_emit_byte (mb, CEE_STIND_REF);          
1320                 break;
1321         case MONO_MARSHAL_CONV_STR_LPWSTR:
1322                 mono_mb_emit_ldloc (mb, 1);
1323                 mono_mb_emit_ldloc (mb, 0);
1324                 mono_mb_emit_byte (mb, CEE_LDIND_I);
1325                 mono_mb_emit_icall (mb, mono_string_from_utf16);
1326                 mono_mb_emit_byte (mb, CEE_STIND_REF);
1327                 break;
1328         case MONO_MARSHAL_CONV_OBJECT_STRUCT: {
1329                 MonoClass *klass = mono_class_from_mono_type (type);
1330                 int src_var, dst_var;
1331
1332                 src_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1333                 dst_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1334                 
1335                 /* *dst = new object */
1336                 mono_mb_emit_ldloc (mb, 1);
1337                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
1338                 mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, klass);   
1339                 mono_mb_emit_byte (mb, CEE_STIND_REF);
1340         
1341                 /* save the old src pointer */
1342                 mono_mb_emit_ldloc (mb, 0);
1343                 mono_mb_emit_stloc (mb, src_var);
1344                 /* save the old dst pointer */
1345                 mono_mb_emit_ldloc (mb, 1);
1346                 mono_mb_emit_stloc (mb, dst_var);
1347
1348                 /* dst = pointer to newly created object data */
1349                 mono_mb_emit_ldloc (mb, 1);
1350                 mono_mb_emit_byte (mb, CEE_LDIND_I);
1351                 mono_mb_emit_icon (mb, sizeof (MonoObject));
1352                 mono_mb_emit_byte (mb, CEE_ADD);
1353                 mono_mb_emit_stloc (mb, 1); 
1354
1355                 emit_struct_conv (mb, klass, TRUE);
1356                 
1357                 /* restore the old src pointer */
1358                 mono_mb_emit_ldloc (mb, src_var);
1359                 mono_mb_emit_stloc (mb, 0);
1360                 /* restore the old dst pointer */
1361                 mono_mb_emit_ldloc (mb, dst_var);
1362                 mono_mb_emit_stloc (mb, 1);
1363                 break;
1364         }
1365         case MONO_MARSHAL_CONV_DEL_FTN: {
1366                 MonoClass *klass = mono_class_from_mono_type (type);
1367
1368                 mono_mb_emit_ldloc (mb, 1);
1369                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
1370                 mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
1371                 mono_mb_emit_ldloc (mb, 0);
1372                 mono_mb_emit_byte (mb, CEE_LDIND_I);
1373                 mono_mb_emit_icall (mb, mono_ftnptr_to_delegate);
1374                 mono_mb_emit_byte (mb, CEE_STIND_REF);
1375                 break;
1376         }
1377         case MONO_MARSHAL_CONV_ARRAY_LPARRAY:
1378                 g_error ("Structure field of type %s can't be marshalled as LPArray", mono_class_from_mono_type (type)->name);
1379                 break;
1380
1381 #ifndef DISABLE_COM
1382         case MONO_MARSHAL_CONV_OBJECT_INTERFACE:
1383         case MONO_MARSHAL_CONV_OBJECT_IUNKNOWN:
1384         case MONO_MARSHAL_CONV_OBJECT_IDISPATCH:
1385                 mono_cominterop_emit_ptr_to_object_conv (mb, type, conv, mspec);
1386                 break;
1387 #endif /* DISABLE_COM */
1388
1389         case MONO_MARSHAL_CONV_SAFEHANDLE: {
1390                 /*
1391                  * Passing SafeHandles as ref does not allow the unmanaged code
1392                  * to change the SafeHandle value.   If the value is changed,
1393                  * we should issue a diagnostic exception (NotSupportedException)
1394                  * that informs the user that changes to handles in unmanaged code
1395                  * is not supported. 
1396                  *
1397                  * Since we currently have no access to the original
1398                  * SafeHandle that was used during the marshalling,
1399                  * for now we just ignore this, and ignore/discard any
1400                  * changes that might have happened to the handle.
1401                  */
1402                 break;
1403         }
1404                 
1405         case MONO_MARSHAL_CONV_HANDLEREF: {
1406                 /*
1407                  * Passing HandleRefs in a struct that is ref()ed does not 
1408                  * copy the values back to the HandleRef
1409                  */
1410                 break;
1411         }
1412                 
1413         case MONO_MARSHAL_CONV_STR_BSTR:
1414         case MONO_MARSHAL_CONV_STR_ANSIBSTR:
1415         case MONO_MARSHAL_CONV_STR_TBSTR:
1416         case MONO_MARSHAL_CONV_ARRAY_SAVEARRAY:
1417         default: {
1418                 char *msg = g_strdup_printf ("marshaling conversion %d not implemented", conv);
1419
1420                 mono_mb_emit_exception_marshal_directive (mb, msg);
1421                 break;
1422         }
1423         }
1424 }
1425
1426 static gpointer
1427 conv_to_icall (MonoMarshalConv conv)
1428 {
1429         switch (conv) {
1430         case MONO_MARSHAL_CONV_STR_LPWSTR:
1431                 return mono_marshal_string_to_utf16;            
1432         case MONO_MARSHAL_CONV_LPWSTR_STR:
1433                 return mono_string_from_utf16;
1434         case MONO_MARSHAL_CONV_LPTSTR_STR:
1435                 return mono_string_new_wrapper;
1436         case MONO_MARSHAL_CONV_LPSTR_STR:
1437                 return mono_string_new_wrapper;
1438         case MONO_MARSHAL_CONV_STR_LPTSTR:
1439 #ifdef TARGET_WIN32
1440                 return mono_marshal_string_to_utf16;
1441 #else
1442                 return mono_string_to_lpstr;
1443 #endif
1444         case MONO_MARSHAL_CONV_STR_LPSTR:
1445                 return mono_string_to_lpstr;
1446         case MONO_MARSHAL_CONV_STR_BSTR:
1447                 return mono_string_to_bstr;
1448         case MONO_MARSHAL_CONV_BSTR_STR:
1449                 return mono_string_from_bstr;
1450         case MONO_MARSHAL_CONV_STR_TBSTR:
1451         case MONO_MARSHAL_CONV_STR_ANSIBSTR:
1452                 return mono_string_to_ansibstr;
1453         case MONO_MARSHAL_CONV_SB_LPSTR:
1454                 return mono_string_builder_to_utf8;
1455         case MONO_MARSHAL_CONV_SB_LPTSTR:
1456 #ifdef TARGET_WIN32
1457                 return mono_string_builder_to_utf16;
1458 #else
1459                 return mono_string_builder_to_utf8;
1460 #endif
1461         case MONO_MARSHAL_CONV_SB_LPWSTR:
1462                 return mono_string_builder_to_utf16;
1463         case MONO_MARSHAL_CONV_ARRAY_SAVEARRAY:
1464                 return mono_array_to_savearray;
1465         case MONO_MARSHAL_CONV_ARRAY_LPARRAY:
1466                 return mono_array_to_lparray;
1467         case MONO_MARSHAL_FREE_LPARRAY:
1468                 return mono_free_lparray;
1469         case MONO_MARSHAL_CONV_DEL_FTN:
1470                 return mono_delegate_to_ftnptr;
1471         case MONO_MARSHAL_CONV_FTN_DEL:
1472                 return mono_ftnptr_to_delegate;
1473         case MONO_MARSHAL_CONV_LPSTR_SB:
1474                 return mono_string_utf8_to_builder;
1475         case MONO_MARSHAL_CONV_LPTSTR_SB:
1476 #ifdef TARGET_WIN32
1477                 return mono_string_utf16_to_builder;
1478 #else
1479                 return mono_string_utf8_to_builder;
1480 #endif
1481         case MONO_MARSHAL_CONV_LPWSTR_SB:
1482                 return mono_string_utf16_to_builder;
1483         case MONO_MARSHAL_FREE_ARRAY:
1484                 return mono_marshal_free_array;
1485         case MONO_MARSHAL_CONV_STR_BYVALSTR:
1486                 return mono_string_to_byvalstr;
1487         case MONO_MARSHAL_CONV_STR_BYVALWSTR:
1488                 return mono_string_to_byvalwstr;
1489         default:
1490                 g_assert_not_reached ();
1491         }
1492
1493         return NULL;
1494 }
1495
1496 static void
1497 emit_object_to_ptr_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv conv, MonoMarshalSpec *mspec)
1498 {
1499         int pos;
1500
1501         switch (conv) {
1502         case MONO_MARSHAL_CONV_BOOL_I4:
1503                 mono_mb_emit_ldloc (mb, 1);
1504                 mono_mb_emit_ldloc (mb, 0);
1505                 mono_mb_emit_byte (mb, CEE_LDIND_U1);
1506                 mono_mb_emit_byte (mb, CEE_STIND_I4);
1507                 break;
1508         case MONO_MARSHAL_CONV_BOOL_VARIANTBOOL:
1509                 mono_mb_emit_ldloc (mb, 1);
1510                 mono_mb_emit_ldloc (mb, 0);
1511                 mono_mb_emit_byte (mb, CEE_LDIND_U1);
1512                 mono_mb_emit_byte (mb, CEE_NEG);
1513                 mono_mb_emit_byte (mb, CEE_STIND_I2);
1514                 break;
1515         case MONO_MARSHAL_CONV_STR_LPWSTR:
1516         case MONO_MARSHAL_CONV_STR_LPSTR:
1517         case MONO_MARSHAL_CONV_STR_LPTSTR:
1518         case MONO_MARSHAL_CONV_STR_BSTR:
1519         case MONO_MARSHAL_CONV_STR_ANSIBSTR:
1520         case MONO_MARSHAL_CONV_STR_TBSTR: {
1521                 int pos;
1522
1523                 /* free space if free == true */
1524                 mono_mb_emit_ldloc (mb, 2);
1525                 pos = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
1526                 mono_mb_emit_ldloc (mb, 1);
1527                 mono_mb_emit_byte (mb, CEE_LDIND_I);
1528                 mono_mb_emit_icall (mb, g_free);
1529                 mono_mb_patch_short_branch (mb, pos);
1530
1531                 mono_mb_emit_ldloc (mb, 1);
1532                 mono_mb_emit_ldloc (mb, 0);
1533                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1534                 mono_mb_emit_icall (mb, conv_to_icall (conv));
1535                 mono_mb_emit_byte (mb, CEE_STIND_I);    
1536                 break;
1537         }
1538         case MONO_MARSHAL_CONV_ARRAY_SAVEARRAY:
1539         case MONO_MARSHAL_CONV_ARRAY_LPARRAY:
1540         case MONO_MARSHAL_CONV_DEL_FTN:
1541                 mono_mb_emit_ldloc (mb, 1);
1542                 mono_mb_emit_ldloc (mb, 0);
1543                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1544                 mono_mb_emit_icall (mb, conv_to_icall (conv));
1545                 mono_mb_emit_byte (mb, CEE_STIND_I);    
1546                 break;
1547         case MONO_MARSHAL_CONV_STR_BYVALSTR: 
1548         case MONO_MARSHAL_CONV_STR_BYVALWSTR: {
1549                 g_assert (mspec);
1550
1551                 mono_mb_emit_ldloc (mb, 1); /* dst */
1552                 mono_mb_emit_ldloc (mb, 0);     
1553                 mono_mb_emit_byte (mb, CEE_LDIND_REF); /* src String */
1554                 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1555                 mono_mb_emit_icall (mb, conv_to_icall (conv));
1556                 break;
1557         }
1558         case MONO_MARSHAL_CONV_ARRAY_BYVALARRAY: {
1559                 MonoClass *eklass = NULL;
1560                 int esize;
1561
1562                 if (type->type == MONO_TYPE_SZARRAY) {
1563                         eklass = type->data.klass;
1564                 } else {
1565                         g_assert_not_reached ();
1566                 }
1567
1568                 if (eklass->valuetype)
1569                         esize = mono_class_native_size (eklass, NULL);
1570                 else
1571                         esize = sizeof (gpointer);
1572
1573                 mono_mb_emit_ldloc (mb, 0);
1574                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1575                 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
1576
1577                 if (eklass->blittable) {
1578                         mono_mb_emit_ldloc (mb, 1);
1579                         mono_mb_emit_ldloc (mb, 0);     
1580                         mono_mb_emit_byte (mb, CEE_LDIND_REF);  
1581                         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
1582                         mono_mb_emit_icon (mb, mspec->data.array_data.num_elem * esize);
1583                         mono_mb_emit_byte (mb, CEE_PREFIX1);
1584                         mono_mb_emit_byte (mb, CEE_CPBLK);                      
1585                 } else {
1586                         int array_var, src_var, dst_var, index_var;
1587                         guint32 label2, label3;
1588
1589                         array_var = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
1590                         src_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1591                         dst_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1592
1593                         /* set array_var */
1594                         mono_mb_emit_ldloc (mb, 0);     
1595                         mono_mb_emit_byte (mb, CEE_LDIND_REF);
1596                         mono_mb_emit_stloc (mb, array_var);
1597
1598                         /* save the old src pointer */
1599                         mono_mb_emit_ldloc (mb, 0);
1600                         mono_mb_emit_stloc (mb, src_var);
1601                         /* save the old dst pointer */
1602                         mono_mb_emit_ldloc (mb, 1);
1603                         mono_mb_emit_stloc (mb, dst_var);
1604
1605                         /* Emit marshalling loop */
1606                         index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1607                         mono_mb_emit_byte (mb, CEE_LDC_I4_0);
1608                         mono_mb_emit_stloc (mb, index_var);
1609
1610                         /* Loop header */
1611                         label2 = mono_mb_get_label (mb);
1612                         mono_mb_emit_ldloc (mb, index_var);
1613                         mono_mb_emit_ldloc (mb, array_var);
1614                         mono_mb_emit_byte (mb, CEE_LDLEN);
1615                         label3 = mono_mb_emit_branch (mb, CEE_BGE);
1616
1617                         /* Set src */
1618                         mono_mb_emit_ldloc (mb, array_var);
1619                         mono_mb_emit_ldloc (mb, index_var);
1620                         mono_mb_emit_op (mb, CEE_LDELEMA, eklass);
1621                         mono_mb_emit_stloc (mb, 0);
1622
1623                         /* dst is already set */
1624
1625                         /* Do the conversion */
1626                         emit_struct_conv (mb, eklass, FALSE);
1627
1628                         /* Loop footer */
1629                         mono_mb_emit_add_to_local (mb, index_var, 1);
1630
1631                         mono_mb_emit_branch_label (mb, CEE_BR, label2);
1632
1633                         mono_mb_patch_branch (mb, label3);
1634                 
1635                         /* restore the old src pointer */
1636                         mono_mb_emit_ldloc (mb, src_var);
1637                         mono_mb_emit_stloc (mb, 0);
1638                         /* restore the old dst pointer */
1639                         mono_mb_emit_ldloc (mb, dst_var);
1640                         mono_mb_emit_stloc (mb, 1);
1641                 }
1642
1643                 mono_mb_patch_branch (mb, pos);
1644                 break;
1645         }
1646         case MONO_MARSHAL_CONV_ARRAY_BYVALCHARARRAY: {
1647                 mono_mb_emit_ldloc (mb, 0);
1648                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1649                 pos = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
1650
1651                 mono_mb_emit_ldloc (mb, 1);
1652                 mono_mb_emit_ldloc (mb, 0);     
1653                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1654                 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1655                 mono_mb_emit_icall (mb, mono_array_to_byte_byvalarray);
1656                 mono_mb_patch_short_branch (mb, pos);
1657                 break;
1658         }
1659         case MONO_MARSHAL_CONV_OBJECT_STRUCT: {
1660                 int src_var, dst_var;
1661
1662                 src_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1663                 dst_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1664                 
1665                 mono_mb_emit_ldloc (mb, 0);
1666                 mono_mb_emit_byte (mb, CEE_LDIND_I);
1667                 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
1668                 
1669                 /* save the old src pointer */
1670                 mono_mb_emit_ldloc (mb, 0);
1671                 mono_mb_emit_stloc (mb, src_var);
1672                 /* save the old dst pointer */
1673                 mono_mb_emit_ldloc (mb, 1);
1674                 mono_mb_emit_stloc (mb, dst_var);
1675
1676                 /* src = pointer to object data */
1677                 mono_mb_emit_ldloc (mb, 0);
1678                 mono_mb_emit_byte (mb, CEE_LDIND_I);            
1679                 mono_mb_emit_icon (mb, sizeof (MonoObject));
1680                 mono_mb_emit_byte (mb, CEE_ADD);
1681                 mono_mb_emit_stloc (mb, 0); 
1682
1683                 emit_struct_conv (mb, mono_class_from_mono_type (type), FALSE);
1684                 
1685                 /* restore the old src pointer */
1686                 mono_mb_emit_ldloc (mb, src_var);
1687                 mono_mb_emit_stloc (mb, 0);
1688                 /* restore the old dst pointer */
1689                 mono_mb_emit_ldloc (mb, dst_var);
1690                 mono_mb_emit_stloc (mb, 1);
1691
1692                 mono_mb_patch_branch (mb, pos);
1693                 break;
1694         }
1695
1696 #ifndef DISABLE_COM
1697         case MONO_MARSHAL_CONV_OBJECT_INTERFACE:
1698         case MONO_MARSHAL_CONV_OBJECT_IDISPATCH:
1699         case MONO_MARSHAL_CONV_OBJECT_IUNKNOWN:
1700                 mono_cominterop_emit_object_to_ptr_conv (mb, type, conv, mspec);
1701                 break;
1702 #endif /* DISABLE_COM */
1703
1704         case MONO_MARSHAL_CONV_SAFEHANDLE: {
1705                 int pos;
1706                 
1707                 mono_mb_emit_ldloc (mb, 0);
1708                 mono_mb_emit_byte (mb, CEE_LDIND_I);
1709                 pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
1710                 mono_mb_emit_exception (mb, "ArgumentNullException", NULL);
1711                 mono_mb_patch_branch (mb, pos);
1712                 
1713                 /* Pull the handle field from SafeHandle */
1714                 mono_mb_emit_ldloc (mb, 1);
1715                 mono_mb_emit_ldloc (mb, 0);
1716                 mono_mb_emit_byte (mb, CEE_LDIND_I);
1717                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoSafeHandle, handle));
1718                 mono_mb_emit_byte (mb, CEE_LDIND_I);
1719                 mono_mb_emit_byte (mb, CEE_STIND_I);
1720                 break;
1721         }
1722
1723         case MONO_MARSHAL_CONV_HANDLEREF: {
1724                 mono_mb_emit_ldloc (mb, 1);
1725                 mono_mb_emit_ldloc (mb, 0);
1726                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoHandleRef, handle));
1727                 mono_mb_emit_byte (mb, CEE_ADD);
1728                 mono_mb_emit_byte (mb, CEE_LDIND_I);
1729                 mono_mb_emit_byte (mb, CEE_STIND_I);
1730                 break;
1731         }
1732                 
1733         default: {
1734                 char *msg = g_strdup_printf ("marshalling conversion %d not implemented", conv);
1735                 MonoException *exc = mono_get_exception_not_implemented (msg);
1736                 g_warning ("%s", msg);
1737                 g_free (msg);
1738                 mono_raise_exception (exc);
1739         }
1740         }
1741 }
1742
1743 static void
1744 emit_struct_conv_full (MonoMethodBuilder *mb, MonoClass *klass, gboolean to_object,
1745                                            MonoMarshalNative string_encoding)
1746 {
1747         MonoMarshalType *info;
1748         int i;
1749
1750         if (klass->parent)
1751                 emit_struct_conv(mb, klass->parent, to_object);
1752
1753         info = mono_marshal_load_type_info (klass);
1754
1755         if (info->native_size == 0)
1756                 return;
1757
1758         if (klass->blittable) {
1759                 int msize = mono_class_value_size (klass, NULL);
1760                 g_assert (msize == info->native_size);
1761                 mono_mb_emit_ldloc (mb, 1);
1762                 mono_mb_emit_ldloc (mb, 0);
1763                 mono_mb_emit_icon (mb, msize);
1764                 mono_mb_emit_byte (mb, CEE_PREFIX1);
1765                 mono_mb_emit_byte (mb, CEE_CPBLK);
1766
1767                 mono_mb_emit_add_to_local (mb, 0, msize);
1768                 mono_mb_emit_add_to_local (mb, 1, msize);
1769                 return;
1770         }
1771
1772         if (klass != mono_defaults.safehandle_class) {
1773                 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
1774                         char *msg = g_strdup_printf ("Type %s which is passed to unmanaged code must have a StructLayout attribute.",
1775                                                                                  mono_type_full_name (&klass->byval_arg));
1776                         mono_mb_emit_exception_marshal_directive (mb, msg);
1777                         return;
1778                 }
1779         }
1780
1781         for (i = 0; i < info->num_fields; i++) {
1782                 MonoMarshalNative ntype;
1783                 MonoMarshalConv conv;
1784                 MonoType *ftype = info->fields [i].field->type;
1785                 int msize = 0;
1786                 int usize = 0;
1787                 gboolean last_field = i < (info->num_fields -1) ? 0 : 1;
1788
1789                 if (ftype->attrs & FIELD_ATTRIBUTE_STATIC)
1790                         continue;
1791
1792                 ntype = mono_type_to_unmanaged (ftype, info->fields [i].mspec, TRUE, klass->unicode, &conv);
1793
1794                 if (last_field) {
1795                         msize = klass->instance_size - info->fields [i].field->offset;
1796                         usize = info->native_size - info->fields [i].offset;
1797                 } else {
1798                         msize = info->fields [i + 1].field->offset - info->fields [i].field->offset;
1799                         usize = info->fields [i + 1].offset - info->fields [i].offset;
1800                 }
1801
1802                 if (klass != mono_defaults.safehandle_class){
1803                         /* 
1804                          * FIXME: Should really check for usize==0 and msize>0, but we apply 
1805                          * the layout to the managed structure as well.
1806                          */
1807                         
1808                         if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) && (usize == 0)) {
1809                                 if (MONO_TYPE_IS_REFERENCE (info->fields [i].field->type) ||
1810                                     ((!last_field && MONO_TYPE_IS_REFERENCE (info->fields [i + 1].field->type))))
1811                                         g_error ("Type %s which has an [ExplicitLayout] attribute cannot have a "
1812                                                  "reference field at the same offset as another field.",
1813                                                  mono_type_full_name (&klass->byval_arg));
1814                         }
1815                 }
1816                 
1817                 switch (conv) {
1818                 case MONO_MARSHAL_CONV_NONE: {
1819                         int t;
1820
1821                         if (ftype->byref || ftype->type == MONO_TYPE_I ||
1822                             ftype->type == MONO_TYPE_U) {
1823                                 mono_mb_emit_ldloc (mb, 1);
1824                                 mono_mb_emit_ldloc (mb, 0);
1825                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
1826                                 mono_mb_emit_byte (mb, CEE_STIND_I);
1827                                 break;
1828                         }
1829
1830                 handle_enum:
1831                         t = ftype->type;
1832                         switch (t) {
1833                         case MONO_TYPE_I4:
1834                         case MONO_TYPE_U4:
1835                         case MONO_TYPE_I1:
1836                         case MONO_TYPE_U1:
1837                         case MONO_TYPE_BOOLEAN:
1838                         case MONO_TYPE_I2:
1839                         case MONO_TYPE_U2:
1840                         case MONO_TYPE_CHAR:
1841                         case MONO_TYPE_I8:
1842                         case MONO_TYPE_U8:
1843                         case MONO_TYPE_PTR:
1844                         case MONO_TYPE_R4:
1845                         case MONO_TYPE_R8:
1846                                 mono_mb_emit_ldloc (mb, 1);
1847                                 mono_mb_emit_ldloc (mb, 0);
1848                                 if (t == MONO_TYPE_CHAR && ntype == MONO_NATIVE_U1 && string_encoding != MONO_NATIVE_LPWSTR) {
1849                                         if (to_object) {
1850                                                 mono_mb_emit_byte (mb, CEE_LDIND_U1);
1851                                                 mono_mb_emit_byte (mb, CEE_STIND_I2);
1852                                         } else {
1853                                                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
1854                                                 mono_mb_emit_byte (mb, CEE_STIND_I1);
1855                                         }
1856                                 } else {
1857                                         mono_mb_emit_byte (mb, mono_type_to_ldind (ftype));
1858                                         mono_mb_emit_byte (mb, mono_type_to_stind (ftype));
1859                                 }
1860                                 break;
1861                         case MONO_TYPE_VALUETYPE: {
1862                                 int src_var, dst_var;
1863
1864                                 if (ftype->data.klass->enumtype) {
1865                                         ftype = mono_class_enum_basetype (ftype->data.klass);
1866                                         goto handle_enum;
1867                                 }
1868
1869                                 src_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1870                                 dst_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1871         
1872                                 /* save the old src pointer */
1873                                 mono_mb_emit_ldloc (mb, 0);
1874                                 mono_mb_emit_stloc (mb, src_var);
1875                                 /* save the old dst pointer */
1876                                 mono_mb_emit_ldloc (mb, 1);
1877                                 mono_mb_emit_stloc (mb, dst_var);
1878
1879                                 emit_struct_conv (mb, ftype->data.klass, to_object);
1880
1881                                 /* restore the old src pointer */
1882                                 mono_mb_emit_ldloc (mb, src_var);
1883                                 mono_mb_emit_stloc (mb, 0);
1884                                 /* restore the old dst pointer */
1885                                 mono_mb_emit_ldloc (mb, dst_var);
1886                                 mono_mb_emit_stloc (mb, 1);
1887                                 break;
1888                         }
1889                         case MONO_TYPE_OBJECT: {
1890 #ifndef DISABLE_COM
1891                                 if (to_object) {
1892                                         static MonoMethod *variant_clear = NULL;
1893                                         static MonoMethod *get_object_for_native_variant = NULL;
1894
1895                                         if (!variant_clear)
1896                                                 variant_clear = mono_class_get_method_from_name (mono_class_get_variant_class (), "Clear", 0);
1897                                         if (!get_object_for_native_variant)
1898                                                 get_object_for_native_variant = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetObjectForNativeVariant", 1);
1899                                         mono_mb_emit_ldloc (mb, 1);
1900                                         mono_mb_emit_ldloc (mb, 0);
1901                                         mono_mb_emit_managed_call (mb, get_object_for_native_variant, NULL);
1902                                         mono_mb_emit_byte (mb, CEE_STIND_REF);
1903
1904                                         mono_mb_emit_ldloc (mb, 0);
1905                                         mono_mb_emit_managed_call (mb, variant_clear, NULL);
1906                                 }
1907                                 else {
1908                                         static MonoMethod *get_native_variant_for_object = NULL;
1909
1910                                         if (!get_native_variant_for_object)
1911                                                 get_native_variant_for_object = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetNativeVariantForObject", 2);
1912
1913                                         mono_mb_emit_ldloc (mb, 0);
1914                                         mono_mb_emit_byte(mb, CEE_LDIND_REF);
1915                                         mono_mb_emit_ldloc (mb, 1);
1916                                         mono_mb_emit_managed_call (mb, get_native_variant_for_object, NULL);
1917                                 }
1918 #else
1919                                 char *msg = g_strdup_printf ("COM support was disabled at compilation time.");
1920                                 mono_mb_emit_exception_marshal_directive (mb, msg);
1921 #endif
1922                                 break;
1923                         }
1924
1925                         default: 
1926                                 g_warning ("marshaling type %02x not implemented", ftype->type);
1927                                 g_assert_not_reached ();
1928                         }
1929                         break;
1930                 }
1931                 default: {
1932                         int src_var, dst_var;
1933
1934                         src_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1935                         dst_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1936
1937                         /* save the old src pointer */
1938                         mono_mb_emit_ldloc (mb, 0);
1939                         mono_mb_emit_stloc (mb, src_var);
1940                         /* save the old dst pointer */
1941                         mono_mb_emit_ldloc (mb, 1);
1942                         mono_mb_emit_stloc (mb, dst_var);
1943
1944                         if (to_object) 
1945                                 emit_ptr_to_object_conv (mb, ftype, conv, info->fields [i].mspec);
1946                         else
1947                                 emit_object_to_ptr_conv (mb, ftype, conv, info->fields [i].mspec);
1948
1949                         /* restore the old src pointer */
1950                         mono_mb_emit_ldloc (mb, src_var);
1951                         mono_mb_emit_stloc (mb, 0);
1952                         /* restore the old dst pointer */
1953                         mono_mb_emit_ldloc (mb, dst_var);
1954                         mono_mb_emit_stloc (mb, 1);
1955                 }
1956                 }
1957
1958                 if (to_object) {
1959                         mono_mb_emit_add_to_local (mb, 0, usize);
1960                         mono_mb_emit_add_to_local (mb, 1, msize);
1961                 } else {
1962                         mono_mb_emit_add_to_local (mb, 0, msize);
1963                         mono_mb_emit_add_to_local (mb, 1, usize);
1964                 }                               
1965         }
1966 }
1967
1968 static void
1969 emit_struct_conv (MonoMethodBuilder *mb, MonoClass *klass, gboolean to_object)
1970 {
1971         emit_struct_conv_full (mb, klass, to_object, -1);
1972 }
1973
1974 static void
1975 emit_struct_free (MonoMethodBuilder *mb, MonoClass *klass, int struct_var)
1976 {
1977         /* Call DestroyStructure */
1978         /* FIXME: Only do this if needed */
1979         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
1980         mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
1981         mono_mb_emit_ldloc (mb, struct_var);
1982         mono_mb_emit_icall (mb, mono_struct_delete_old);
1983 }
1984
1985 static void
1986 emit_thread_interrupt_checkpoint_call (MonoMethodBuilder *mb, gpointer checkpoint_func)
1987 {
1988         int pos_noabort, pos_noex;
1989
1990         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
1991         mono_mb_emit_byte (mb, CEE_MONO_LDPTR_INT_REQ_FLAG);
1992         mono_mb_emit_byte (mb, CEE_LDIND_U4);
1993         pos_noabort = mono_mb_emit_branch (mb, CEE_BRFALSE);
1994
1995         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
1996         mono_mb_emit_byte (mb, CEE_MONO_NOT_TAKEN);
1997
1998         mono_mb_emit_icall (mb, checkpoint_func);
1999         /* Throw the exception returned by the checkpoint function, if any */
2000         mono_mb_emit_byte (mb, CEE_DUP);
2001         pos_noex = mono_mb_emit_branch (mb, CEE_BRFALSE);
2002         mono_mb_emit_byte (mb, CEE_THROW);
2003         mono_mb_patch_branch (mb, pos_noex);
2004         mono_mb_emit_byte (mb, CEE_POP);
2005         
2006         mono_mb_patch_branch (mb, pos_noabort);
2007 }
2008
2009 static void
2010 emit_thread_interrupt_checkpoint (MonoMethodBuilder *mb)
2011 {
2012         if (strstr (mb->name, "mono_thread_interruption_checkpoint"))
2013                 return;
2014         
2015         emit_thread_interrupt_checkpoint_call (mb, mono_thread_interruption_checkpoint);
2016 }
2017
2018 static void
2019 emit_thread_force_interrupt_checkpoint (MonoMethodBuilder *mb)
2020 {
2021         emit_thread_interrupt_checkpoint_call (mb, mono_thread_force_interruption_checkpoint_noraise);
2022 }
2023
2024 void
2025 mono_marshal_emit_thread_interrupt_checkpoint (MonoMethodBuilder *mb)
2026 {
2027         emit_thread_interrupt_checkpoint (mb);
2028 }
2029
2030 void
2031 mono_marshal_emit_thread_force_interrupt_checkpoint (MonoMethodBuilder *mb)
2032 {
2033         emit_thread_force_interrupt_checkpoint (mb);
2034 }
2035
2036 #endif /* DISABLE_JIT */
2037
2038 static MonoAsyncResult *
2039 mono_delegate_begin_invoke (MonoDelegate *delegate, gpointer *params)
2040 {
2041         MonoMethodMessage *msg;
2042         MonoDelegate *async_callback;
2043         MonoMulticastDelegate *mcast_delegate;
2044         MonoObject *state;
2045         MonoMethod *im;
2046         MonoClass *klass;
2047         MonoMethod *method = NULL, *method2 = NULL;
2048
2049         g_assert (delegate);
2050         mcast_delegate = (MonoMulticastDelegate *) delegate;
2051         if (mcast_delegate->prev != NULL)
2052                 mono_raise_exception (mono_get_exception_argument (NULL, "The delegate must have only one target"));
2053
2054 #ifndef DISABLE_REMOTING
2055         if (delegate->target && mono_object_class (delegate->target) == mono_defaults.transparent_proxy_class) {
2056
2057                 MonoTransparentProxy* tp = (MonoTransparentProxy *)delegate->target;
2058                 if (!mono_class_is_contextbound (tp->remote_class->proxy_class) || tp->rp->context != (MonoObject *) mono_context_get ()) {
2059
2060                         /* If the target is a proxy, make a direct call. Is proxy's work
2061                         // to make the call asynchronous.
2062                         */
2063                         MonoAsyncResult *ares;
2064                         MonoObject *exc;
2065                         MonoArray *out_args;
2066                         method = delegate->method;
2067
2068                         msg = mono_method_call_message_new (mono_marshal_method_from_wrapper (method), params, NULL, &async_callback, &state);
2069                         ares = mono_async_result_new (mono_domain_get (), NULL, state, NULL, NULL);
2070                         MONO_OBJECT_SETREF (ares, async_delegate, (MonoObject *)delegate);
2071                         MONO_OBJECT_SETREF (ares, async_callback, (MonoObject *)async_callback);
2072                         MONO_OBJECT_SETREF (msg, async_result, ares);
2073                         msg->call_type = CallType_BeginInvoke;
2074
2075                         exc = NULL;
2076                         mono_remoting_invoke ((MonoObject *)tp->rp, msg, &exc, &out_args);
2077                         if (exc)
2078                                 mono_raise_exception ((MonoException *) exc);
2079                         return ares;
2080                 }
2081         }
2082 #endif
2083
2084         klass = delegate->object.vtable->klass;
2085
2086         method = mono_get_delegate_invoke (klass);
2087         method2 = mono_class_get_method_from_name (klass, "BeginInvoke", -1);
2088         if (method2)
2089                 method = method2;
2090         g_assert (method != NULL);
2091
2092         im = mono_get_delegate_invoke (method->klass);
2093         msg = mono_method_call_message_new (method, params, im, &async_callback, &state);
2094
2095         return mono_thread_pool_add ((MonoObject *)delegate, msg, async_callback, state);
2096 }
2097
2098 #ifndef DISABLE_JIT
2099
2100 int
2101 mono_mb_emit_save_args (MonoMethodBuilder *mb, MonoMethodSignature *sig, gboolean save_this)
2102 {
2103         int i, params_var, tmp_var;
2104
2105         /* allocate local (pointer) *params[] */
2106         params_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
2107         /* allocate local (pointer) tmp */
2108         tmp_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
2109
2110         /* alloate space on stack to store an array of pointers to the arguments */
2111         mono_mb_emit_icon (mb, sizeof (gpointer) * (sig->param_count + 1));
2112         mono_mb_emit_byte (mb, CEE_PREFIX1);
2113         mono_mb_emit_byte (mb, CEE_LOCALLOC);
2114         mono_mb_emit_stloc (mb, params_var);
2115
2116         /* tmp = params */
2117         mono_mb_emit_ldloc (mb, params_var);
2118         mono_mb_emit_stloc (mb, tmp_var);
2119
2120         if (save_this && sig->hasthis) {
2121                 mono_mb_emit_ldloc (mb, tmp_var);
2122                 mono_mb_emit_ldarg_addr (mb, 0);
2123                 mono_mb_emit_byte (mb, CEE_STIND_I);
2124                 /* tmp = tmp + sizeof (gpointer) */
2125                 if (sig->param_count)
2126                         mono_mb_emit_add_to_local (mb, tmp_var, sizeof (gpointer));
2127
2128         }
2129
2130         for (i = 0; i < sig->param_count; i++) {
2131                 mono_mb_emit_ldloc (mb, tmp_var);
2132                 mono_mb_emit_ldarg_addr (mb, i + sig->hasthis);
2133                 mono_mb_emit_byte (mb, CEE_STIND_I);
2134                 /* tmp = tmp + sizeof (gpointer) */
2135                 if (i < (sig->param_count - 1))
2136                         mono_mb_emit_add_to_local (mb, tmp_var, sizeof (gpointer));
2137         }
2138
2139         return params_var;
2140 }
2141
2142 #endif /* DISABLE_JIT */
2143
2144 static char*
2145 mono_signature_to_name (MonoMethodSignature *sig, const char *prefix)
2146 {
2147         int i;
2148         char *result;
2149         GString *res = g_string_new ("");
2150
2151         if (prefix) {
2152                 g_string_append (res, prefix);
2153                 g_string_append_c (res, '_');
2154         }
2155
2156         mono_type_get_desc (res, sig->ret, FALSE);
2157
2158         if (sig->hasthis)
2159                 g_string_append (res, "__this__");
2160
2161         for (i = 0; i < sig->param_count; ++i) {
2162                 g_string_append_c (res, '_');
2163                 mono_type_get_desc (res, sig->params [i], FALSE);
2164         }
2165         result = res->str;
2166         g_string_free (res, FALSE);
2167         return result;
2168 }
2169
2170 /**
2171  * mono_marshal_get_string_encoding:
2172  *
2173  *  Return the string encoding which should be used for a given parameter.
2174  */
2175 static MonoMarshalNative
2176 mono_marshal_get_string_encoding (MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec)
2177 {
2178         /* First try the parameter marshal info */
2179         if (spec) {
2180                 if (spec->native == MONO_NATIVE_LPARRAY) {
2181                         if ((spec->data.array_data.elem_type != 0) && (spec->data.array_data.elem_type != MONO_NATIVE_MAX))
2182                                 return spec->data.array_data.elem_type;
2183                 }
2184                 else
2185                         return spec->native;
2186         }
2187
2188         if (!piinfo)
2189                 return MONO_NATIVE_LPSTR;
2190
2191         /* Then try the method level marshal info */
2192         switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
2193         case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
2194                 return MONO_NATIVE_LPSTR;
2195         case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
2196                 return MONO_NATIVE_LPWSTR;
2197         case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
2198 #ifdef TARGET_WIN32
2199                 return MONO_NATIVE_LPWSTR;
2200 #else
2201                 return MONO_NATIVE_LPSTR;
2202 #endif
2203         default:
2204                 return MONO_NATIVE_LPSTR;
2205         }
2206 }
2207
2208 static MonoMarshalConv
2209 mono_marshal_get_string_to_ptr_conv (MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec)
2210 {
2211         MonoMarshalNative encoding = mono_marshal_get_string_encoding (piinfo, spec);
2212
2213         switch (encoding) {
2214         case MONO_NATIVE_LPWSTR:
2215                 return MONO_MARSHAL_CONV_STR_LPWSTR;
2216         case MONO_NATIVE_LPSTR:
2217         case MONO_NATIVE_VBBYREFSTR:
2218                 return MONO_MARSHAL_CONV_STR_LPSTR;
2219         case MONO_NATIVE_LPTSTR:
2220                 return MONO_MARSHAL_CONV_STR_LPTSTR;
2221         case MONO_NATIVE_BSTR:
2222                 return MONO_MARSHAL_CONV_STR_BSTR;
2223         default:
2224                 return -1;
2225         }
2226 }
2227
2228 static MonoMarshalConv
2229 mono_marshal_get_stringbuilder_to_ptr_conv (MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec)
2230 {
2231         MonoMarshalNative encoding = mono_marshal_get_string_encoding (piinfo, spec);
2232
2233         switch (encoding) {
2234         case MONO_NATIVE_LPWSTR:
2235                 return MONO_MARSHAL_CONV_SB_LPWSTR;
2236                 break;
2237         case MONO_NATIVE_LPSTR:
2238                 return MONO_MARSHAL_CONV_SB_LPSTR;
2239                 break;
2240         case MONO_NATIVE_LPTSTR:
2241                 return MONO_MARSHAL_CONV_SB_LPTSTR;
2242                 break;
2243         default:
2244                 return -1;
2245         }
2246 }
2247
2248 static MonoMarshalConv
2249 mono_marshal_get_ptr_to_string_conv (MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec, gboolean *need_free)
2250 {
2251         MonoMarshalNative encoding = mono_marshal_get_string_encoding (piinfo, spec);
2252
2253         *need_free = TRUE;
2254
2255         switch (encoding) {
2256         case MONO_NATIVE_LPWSTR:
2257                 *need_free = FALSE;
2258                 return MONO_MARSHAL_CONV_LPWSTR_STR;
2259         case MONO_NATIVE_LPSTR:
2260         case MONO_NATIVE_VBBYREFSTR:
2261                 return MONO_MARSHAL_CONV_LPSTR_STR;
2262         case MONO_NATIVE_LPTSTR:
2263                 return MONO_MARSHAL_CONV_LPTSTR_STR;
2264         case MONO_NATIVE_BSTR:
2265                 return MONO_MARSHAL_CONV_BSTR_STR;
2266         default:
2267                 return -1;
2268         }
2269 }
2270
2271 static MonoMarshalConv
2272 mono_marshal_get_ptr_to_stringbuilder_conv (MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec, gboolean *need_free)
2273 {
2274         MonoMarshalNative encoding = mono_marshal_get_string_encoding (piinfo, spec);
2275
2276         *need_free = TRUE;
2277
2278         switch (encoding) {
2279         case MONO_NATIVE_LPWSTR:
2280                 /* 
2281                  * mono_string_builder_to_utf16 does not allocate a 
2282                  * new buffer, so no need to free it.
2283                  */
2284                 *need_free = FALSE;
2285                 return MONO_MARSHAL_CONV_LPWSTR_SB;
2286         case MONO_NATIVE_LPSTR:
2287                 return MONO_MARSHAL_CONV_LPSTR_SB;
2288                 break;
2289         case MONO_NATIVE_LPTSTR:
2290                 return MONO_MARSHAL_CONV_LPTSTR_SB;
2291                 break;
2292         default:
2293                 return -1;
2294         }
2295 }
2296
2297 /*
2298  * Return whenever a field of a native structure or an array member needs to 
2299  * be freed.
2300  */
2301 static gboolean
2302 mono_marshal_need_free (MonoType *t, MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec)
2303 {
2304         MonoMarshalNative encoding;
2305
2306         switch (t->type) {
2307         case MONO_TYPE_VALUETYPE:
2308                 /* FIXME: Optimize this */
2309                 return TRUE;
2310         case MONO_TYPE_OBJECT:
2311         case MONO_TYPE_CLASS:
2312                 if (t->data.klass == mono_defaults.stringbuilder_class) {
2313                         gboolean need_free;
2314                         mono_marshal_get_ptr_to_stringbuilder_conv (piinfo, spec, &need_free);
2315                         return need_free;
2316                 }
2317                 return FALSE;
2318         case MONO_TYPE_STRING:
2319                 encoding = mono_marshal_get_string_encoding (piinfo, spec);
2320                 return (encoding == MONO_NATIVE_LPWSTR) ? FALSE : TRUE;
2321         default:
2322                 return FALSE;
2323         }
2324 }
2325
2326 /*
2327  * Return the hash table pointed to by VAR, lazily creating it if neccesary.
2328  */
2329 static GHashTable*
2330 get_cache (GHashTable **var, GHashFunc hash_func, GCompareFunc equal_func)
2331 {
2332         if (!(*var)) {
2333                 mono_marshal_lock ();
2334                 if (!(*var)) {
2335                         GHashTable *cache = 
2336                                 g_hash_table_new (hash_func, equal_func);
2337                         mono_memory_barrier ();
2338                         *var = cache;
2339                 }
2340                 mono_marshal_unlock ();
2341         }
2342         return *var;
2343 }
2344
2345 GHashTable*
2346 mono_marshal_get_cache (GHashTable **var, GHashFunc hash_func, GCompareFunc equal_func)
2347 {
2348         return get_cache (var, hash_func, equal_func);
2349 }
2350
2351 MonoMethod*
2352 mono_marshal_find_in_cache (GHashTable *cache, gpointer key)
2353 {
2354         MonoMethod *res;
2355
2356         mono_marshal_lock ();
2357         res = g_hash_table_lookup (cache, key);
2358         mono_marshal_unlock ();
2359         return res;
2360 }
2361
2362 /*
2363  * mono_mb_create:
2364  *
2365  *   Create a MonoMethod from MB, set INFO as wrapper info.
2366  */
2367 MonoMethod*
2368 mono_mb_create (MonoMethodBuilder *mb, MonoMethodSignature *sig,
2369                                 int max_stack, WrapperInfo *info)
2370 {
2371         MonoMethod *res;
2372
2373         res = mono_mb_create_method (mb, sig, max_stack);
2374         if (info)
2375                 mono_marshal_set_wrapper_info (res, info);
2376         return res;
2377 }
2378
2379 /* Create the method from the builder and place it in the cache */
2380 MonoMethod*
2381 mono_mb_create_and_cache_full (GHashTable *cache, gpointer key,
2382                                                            MonoMethodBuilder *mb, MonoMethodSignature *sig,
2383                                                            int max_stack, WrapperInfo *info, gboolean *out_found)
2384 {
2385         MonoMethod *res;
2386
2387         if (out_found)
2388                 *out_found = FALSE;
2389
2390         mono_marshal_lock ();
2391         res = g_hash_table_lookup (cache, key);
2392         mono_marshal_unlock ();
2393         if (!res) {
2394                 MonoMethod *newm;
2395                 newm = mono_mb_create_method (mb, sig, max_stack);
2396                 mono_marshal_lock ();
2397                 res = g_hash_table_lookup (cache, key);
2398                 if (!res) {
2399                         res = newm;
2400                         g_hash_table_insert (cache, key, res);
2401                         if (info)
2402                                 mono_marshal_set_wrapper_info (res, info);
2403                         else
2404                                 mono_marshal_set_wrapper_info (res, key);
2405                         mono_marshal_unlock ();
2406                 } else {
2407                         if (out_found)
2408                                 *out_found = TRUE;
2409                         mono_marshal_unlock ();
2410                         mono_free_method (newm);
2411                 }
2412         }
2413
2414         return res;
2415 }               
2416
2417 MonoMethod*
2418 mono_mb_create_and_cache (GHashTable *cache, gpointer key,
2419                                                            MonoMethodBuilder *mb, MonoMethodSignature *sig,
2420                                                            int max_stack)
2421 {
2422         return mono_mb_create_and_cache_full (cache, key, mb, sig, max_stack, NULL, NULL);
2423 }
2424
2425 MonoMethod *
2426 mono_marshal_method_from_wrapper (MonoMethod *wrapper)
2427 {
2428         gpointer res;
2429         int wrapper_type = wrapper->wrapper_type;
2430         WrapperInfo *info;
2431
2432         if (wrapper_type == MONO_WRAPPER_NONE || wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
2433                 return wrapper;
2434
2435         switch (wrapper_type) {
2436         case MONO_WRAPPER_REMOTING_INVOKE:
2437         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2438         case MONO_WRAPPER_XDOMAIN_INVOKE:
2439         case MONO_WRAPPER_SYNCHRONIZED:
2440         case MONO_WRAPPER_UNBOX:
2441                 res = mono_marshal_get_wrapper_info (wrapper);
2442                 if (res == NULL)
2443                         return wrapper;
2444                 if (wrapper->is_inflated) {
2445                         MonoError error;
2446                         MonoMethod *result;
2447                         /*
2448                          * A method cannot be inflated and a wrapper at the same time, so the wrapper info
2449                          * contains an uninflated method.
2450                          */
2451                         result = mono_class_inflate_generic_method_checked (res, mono_method_get_context (wrapper), &error);
2452                         g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
2453                         return result;
2454                 }
2455                 return res;
2456         case MONO_WRAPPER_MANAGED_TO_NATIVE:
2457                 info = mono_marshal_get_wrapper_info (wrapper);
2458                 if (info && (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT || info->subtype == WRAPPER_SUBTYPE_PINVOKE))
2459                         return info->d.managed_to_native.method;
2460                 else
2461                         return NULL;
2462         case MONO_WRAPPER_RUNTIME_INVOKE:
2463                 info = mono_marshal_get_wrapper_info (wrapper);
2464                 if (info && (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL))
2465                         return info->d.runtime_invoke.method;
2466                 else
2467                         return NULL;
2468         default:
2469                 return NULL;
2470         }
2471 }
2472
2473 /*
2474  * mono_marshal_get_wrapper_info:
2475  *
2476  *   Retrieve the pointer stored by mono_marshal_set_wrapper_info. The type of data
2477  * returned depends on the wrapper type. It is usually a method, a class, or a
2478  * WrapperInfo structure.
2479  */
2480 gpointer
2481 mono_marshal_get_wrapper_info (MonoMethod *wrapper)
2482 {
2483         g_assert (wrapper->wrapper_type);
2484
2485         return mono_method_get_wrapper_data (wrapper, 1);
2486 }
2487
2488 /*
2489  * mono_marshal_set_wrapper_info:
2490  *
2491  *   Store an arbitrary pointer inside the wrapper which is retrievable by 
2492  * mono_marshal_get_wrapper_info. The format of the data depends on the type of the
2493  * wrapper (method->wrapper_type).
2494  */
2495 void
2496 mono_marshal_set_wrapper_info (MonoMethod *method, gpointer data)
2497 {
2498         void **datav;
2499         /* assert */
2500         if (method->wrapper_type == MONO_WRAPPER_NONE || method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
2501                 return;
2502
2503         datav = ((MonoMethodWrapper *)method)->method_data;
2504         datav [1] = data;
2505 }
2506
2507 WrapperInfo*
2508 mono_wrapper_info_create (MonoMethodBuilder *mb, WrapperSubtype subtype)
2509 {
2510         WrapperInfo *info;
2511
2512         info = mono_image_alloc0 (mb->method->klass->image, sizeof (WrapperInfo));
2513         info->subtype = subtype;
2514         return info;
2515 }
2516
2517 /*
2518  * get_wrapper_target_class:
2519  *
2520  *   Return the class where a wrapper method should be placed.
2521  */
2522 static MonoClass*
2523 get_wrapper_target_class (MonoImage *image)
2524 {
2525         MonoError error;
2526         MonoClass *klass;
2527
2528         /*
2529          * Notes:
2530          * - can't put all wrappers into an mscorlib class, because they reference
2531          *   metadata (signature) so they should be put into the same image as the 
2532          *   method they wrap, so they are unloaded together.
2533          * - putting them into a class with a type initalizer could cause the 
2534          *   initializer to be executed which can be a problem if the wrappers are 
2535          *   shared.
2536          * - putting them into an inflated class can cause problems if the the 
2537          *   class is deleted because it references an image which is unloaded.
2538          * To avoid these problems, we put the wrappers into the <Module> class of 
2539          * the image.
2540          */
2541         if (image_is_dynamic (image)) {
2542                 klass = ((MonoDynamicImage*)image)->wrappers_type;
2543         } else {
2544                 klass = mono_class_get_checked (image, mono_metadata_make_token (MONO_TABLE_TYPEDEF, 1), &error);
2545                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
2546         }
2547         g_assert (klass);
2548
2549         return klass;
2550 }
2551
2552 /*
2553  * Wrappers for generic methods should be instances of generic wrapper methods, i.e .the wrapper for Sort<int> should be
2554  * an instance of the wrapper for Sort<T>. This is required for full-aot to work.
2555  */
2556
2557 /*
2558  * check_generic_wrapper_cache:
2559  *
2560  *   Check CACHE for the wrapper of the generic instance ORIG_METHOD, and return it if it is found.
2561  * KEY should be the key for ORIG_METHOD in the cache, while DEF_KEY should be the key of its
2562  * generic method definition.
2563  */
2564 static MonoMethod*
2565 check_generic_wrapper_cache (GHashTable *cache, MonoMethod *orig_method, gpointer key, gpointer def_key)
2566 {
2567         MonoMethod *res;
2568         MonoMethod *inst, *def;
2569         MonoGenericContext *ctx;
2570
2571         g_assert (orig_method->is_inflated);
2572         ctx = mono_method_get_context (orig_method);
2573
2574         /*
2575          * Look for the instance
2576          */
2577         res = mono_marshal_find_in_cache (cache, key);
2578         if (res)
2579                 return res;
2580
2581         /*
2582          * Look for the definition
2583          */
2584         def = mono_marshal_find_in_cache (cache, def_key);
2585         if (def) {
2586                 MonoError error;
2587                 inst = mono_class_inflate_generic_method_checked (def, ctx, &error);
2588                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
2589                 /* Cache it */
2590                 mono_memory_barrier ();
2591                 mono_marshal_lock ();
2592                 res = g_hash_table_lookup (cache, key);
2593                 if (!res) {
2594                         g_hash_table_insert (cache, key, inst);
2595                         res = inst;
2596                 }
2597                 mono_marshal_unlock ();
2598                 return res;
2599         }
2600         return NULL;
2601 }
2602
2603 static MonoMethod*
2604 cache_generic_wrapper (GHashTable *cache, MonoMethod *orig_method, MonoMethod *def, MonoGenericContext *ctx, gpointer key)
2605 {
2606         MonoError error;
2607         MonoMethod *inst, *res;
2608
2609         /*
2610          * We use the same cache for the generic definition and the instances.
2611          */
2612         inst = mono_class_inflate_generic_method_checked (def, ctx, &error);
2613         g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
2614         mono_memory_barrier ();
2615         mono_marshal_lock ();
2616         res = g_hash_table_lookup (cache, key);
2617         if (!res) {
2618                 g_hash_table_insert (cache, key, inst);
2619                 res = inst;
2620         }
2621         mono_marshal_unlock ();
2622         return res;
2623 }
2624
2625 static MonoMethod*
2626 check_generic_delegate_wrapper_cache (GHashTable *cache, MonoMethod *orig_method, MonoMethod *def_method, MonoGenericContext *ctx)
2627 {
2628         MonoError error;
2629         MonoMethod *res;
2630         MonoMethod *inst, *def;
2631
2632         /*
2633          * Look for the instance
2634          */
2635         res = mono_marshal_find_in_cache (cache, orig_method->klass);
2636         if (res)
2637                 return res;
2638
2639         /*
2640          * Look for the definition
2641          */
2642         def = mono_marshal_find_in_cache (cache, def_method->klass);
2643         if (def) {
2644                 inst = mono_class_inflate_generic_method_checked (def, ctx, &error);
2645                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
2646
2647                 /* Cache it */
2648                 mono_memory_barrier ();
2649                 mono_marshal_lock ();
2650                 res = g_hash_table_lookup (cache, orig_method->klass);
2651                 if (!res) {
2652                         g_hash_table_insert (cache, orig_method->klass, inst);
2653                         res = inst;
2654                 }
2655                 mono_marshal_unlock ();
2656                 return res;
2657         }
2658         return NULL;
2659 }
2660
2661 static MonoMethod*
2662 cache_generic_delegate_wrapper (GHashTable *cache, MonoMethod *orig_method, MonoMethod *def, MonoGenericContext *ctx)
2663 {
2664         MonoError error;
2665         MonoMethod *inst, *res;
2666
2667         /*
2668          * We use the same cache for the generic definition and the instances.
2669          */
2670         inst = mono_class_inflate_generic_method_checked (def, ctx, &error);
2671         g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
2672
2673         mono_memory_barrier ();
2674         mono_marshal_lock ();
2675         res = g_hash_table_lookup (cache, orig_method->klass);
2676         if (!res) {
2677                 g_hash_table_insert (cache, orig_method->klass, inst);
2678                 res = inst;
2679         }
2680         mono_marshal_unlock ();
2681         return res;
2682 }
2683
2684 MonoMethod *
2685 mono_marshal_get_delegate_begin_invoke (MonoMethod *method)
2686 {
2687         MonoMethodSignature *sig;
2688         MonoMethodBuilder *mb;
2689         MonoMethod *res;
2690         GHashTable *cache;
2691         int params_var;
2692         char *name;
2693         MonoGenericContext *ctx = NULL;
2694         MonoMethod *orig_method = NULL;
2695
2696         g_assert (method && method->klass->parent == mono_defaults.multicastdelegate_class &&
2697                   !strcmp (method->name, "BeginInvoke"));
2698
2699         /*
2700          * For generic delegates, create a generic wrapper, and returns an instance to help AOT.
2701          */
2702         if (method->is_inflated) {
2703                 orig_method = method;
2704                 ctx = &((MonoMethodInflated*)method)->context;
2705                 method = ((MonoMethodInflated*)method)->declaring;
2706         }
2707
2708         sig = mono_signature_no_pinvoke (method);
2709
2710         /*
2711          * Check cache
2712          */
2713         if (ctx) {
2714                 cache = get_cache (&method->klass->image->delegate_begin_invoke_generic_cache, mono_aligned_addr_hash, NULL);
2715                 res = check_generic_delegate_wrapper_cache (cache, orig_method, method, ctx);
2716                 if (res)
2717                         return res;
2718         } else {
2719                 cache = get_cache (&method->klass->image->delegate_begin_invoke_cache,
2720                                                    (GHashFunc)mono_signature_hash, 
2721                                                    (GCompareFunc)mono_metadata_signature_equal);
2722                 if ((res = mono_marshal_find_in_cache (cache, sig)))
2723                         return res;
2724         }
2725
2726         g_assert (sig->hasthis);
2727
2728         name = mono_signature_to_name (sig, "begin_invoke");
2729         if (ctx)
2730                 mb = mono_mb_new (method->klass, name, MONO_WRAPPER_DELEGATE_BEGIN_INVOKE);
2731         else
2732                 mb = mono_mb_new (get_wrapper_target_class (method->klass->image), name, MONO_WRAPPER_DELEGATE_BEGIN_INVOKE);
2733         g_free (name);
2734
2735 #ifndef DISABLE_JIT
2736         params_var = mono_mb_emit_save_args (mb, sig, FALSE);
2737
2738         mono_mb_emit_ldarg (mb, 0);
2739         mono_mb_emit_ldloc (mb, params_var);
2740         mono_mb_emit_icall (mb, mono_delegate_begin_invoke);
2741         mono_mb_emit_byte (mb, CEE_RET);
2742 #endif
2743
2744         if (ctx) {
2745                 MonoMethod *def;
2746                 def = mono_mb_create_and_cache (cache, method->klass, mb, sig, sig->param_count + 16);
2747                 res = cache_generic_delegate_wrapper (cache, orig_method, def, ctx);
2748         } else {
2749                 res = mono_mb_create_and_cache (cache, sig, mb, sig, sig->param_count + 16);
2750         }
2751
2752         mono_mb_free (mb);
2753         return res;
2754 }
2755
2756 static MonoObject *
2757 mono_delegate_end_invoke (MonoDelegate *delegate, gpointer *params)
2758 {
2759         MonoDomain *domain = mono_domain_get ();
2760         MonoAsyncResult *ares;
2761         MonoMethod *method = NULL;
2762         MonoMethodSignature *sig;
2763         MonoMethodMessage *msg;
2764         MonoObject *res, *exc;
2765         MonoArray *out_args;
2766         MonoClass *klass;
2767
2768         g_assert (delegate);
2769
2770         if (!delegate->method_info) {
2771                 g_assert (delegate->method);
2772                 MONO_OBJECT_SETREF (delegate, method_info, mono_method_get_object (domain, delegate->method, NULL));
2773         }
2774
2775         if (!delegate->method_info || !delegate->method_info->method)
2776                 g_assert_not_reached ();
2777
2778         klass = delegate->object.vtable->klass;
2779
2780         method = mono_class_get_method_from_name (klass, "EndInvoke", -1);
2781         g_assert (method != NULL);
2782
2783         sig = mono_signature_no_pinvoke (method);
2784
2785         msg = mono_method_call_message_new (method, params, NULL, NULL, NULL);
2786
2787         ares = mono_array_get (msg->args, gpointer, sig->param_count - 1);
2788         if (ares == NULL) {
2789                 mono_raise_exception (mono_exception_from_name_msg (mono_defaults.corlib, "System.Runtime.Remoting", "RemotingException", "The async result object is null or of an unexpected type."));
2790                 return NULL;
2791         }
2792
2793         if (ares->async_delegate != (MonoObject*)delegate) {
2794                 mono_raise_exception (mono_get_exception_invalid_operation (
2795                         "The IAsyncResult object provided does not match this delegate."));
2796                 return NULL;
2797         }
2798
2799 #ifndef DISABLE_REMOTING
2800         if (delegate->target && mono_object_is_transparent_proxy (delegate->target)) {
2801                 MonoTransparentProxy* tp = (MonoTransparentProxy *)delegate->target;
2802                 msg = (MonoMethodMessage *)mono_object_new (domain, mono_defaults.mono_method_message_class);
2803                 mono_message_init (domain, msg, delegate->method_info, NULL);
2804                 msg->call_type = CallType_EndInvoke;
2805                 MONO_OBJECT_SETREF (msg, async_result, ares);
2806                 res = mono_remoting_invoke ((MonoObject *)tp->rp, msg, &exc, &out_args);
2807         } else
2808 #endif
2809         {
2810                 res = mono_thread_pool_finish (ares, &out_args, &exc);
2811         }
2812
2813         if (exc) {
2814                 if (((MonoException*)exc)->stack_trace) {
2815                         char *strace = mono_string_to_utf8 (((MonoException*)exc)->stack_trace);
2816                         char  *tmp;
2817                         tmp = g_strdup_printf ("%s\nException Rethrown at:\n", strace);
2818                         g_free (strace);        
2819                         MONO_OBJECT_SETREF (((MonoException*)exc), stack_trace, mono_string_new (domain, tmp));
2820                         g_free (tmp);
2821                 }
2822                 mono_raise_exception ((MonoException*)exc);
2823         }
2824
2825         mono_method_return_message_restore (method, params, out_args);
2826         return res;
2827 }
2828
2829 #ifndef DISABLE_JIT
2830
2831 void
2832 mono_mb_emit_restore_result (MonoMethodBuilder *mb, MonoType *return_type)
2833 {
2834         MonoType *t = mono_type_get_underlying_type (return_type);
2835
2836         if (return_type->byref)
2837                 return_type = &mono_defaults.int_class->byval_arg;
2838
2839         switch (t->type) {
2840         case MONO_TYPE_VOID:
2841                 g_assert_not_reached ();
2842                 break;
2843         case MONO_TYPE_PTR:
2844         case MONO_TYPE_STRING:
2845         case MONO_TYPE_CLASS: 
2846         case MONO_TYPE_OBJECT: 
2847         case MONO_TYPE_ARRAY: 
2848         case MONO_TYPE_SZARRAY: 
2849                 /* nothing to do */
2850                 break;
2851         case MONO_TYPE_U1:
2852         case MONO_TYPE_BOOLEAN:
2853         case MONO_TYPE_I1:
2854         case MONO_TYPE_U2:
2855         case MONO_TYPE_CHAR:
2856         case MONO_TYPE_I2:
2857         case MONO_TYPE_I:
2858         case MONO_TYPE_U:
2859         case MONO_TYPE_I4:
2860         case MONO_TYPE_U4:
2861         case MONO_TYPE_U8:
2862         case MONO_TYPE_I8:
2863         case MONO_TYPE_R4:
2864         case MONO_TYPE_R8:
2865                 mono_mb_emit_op (mb, CEE_UNBOX, mono_class_from_mono_type (return_type));
2866                 mono_mb_emit_byte (mb, mono_type_to_ldind (return_type));
2867                 break;
2868         case MONO_TYPE_GENERICINST:
2869                 if (!mono_type_generic_inst_is_valuetype (t))
2870                         break;
2871                 /* fall through */
2872         case MONO_TYPE_VALUETYPE: {
2873                 MonoClass *klass = mono_class_from_mono_type (return_type);
2874                 mono_mb_emit_op (mb, CEE_UNBOX, klass);
2875                 mono_mb_emit_op (mb, CEE_LDOBJ, klass);
2876                 break;
2877         }
2878         case MONO_TYPE_VAR:
2879         case MONO_TYPE_MVAR: {
2880                 MonoClass *klass = mono_class_from_mono_type (return_type);
2881                 mono_mb_emit_op (mb, CEE_UNBOX_ANY, klass);
2882                 break;
2883         }
2884         default:
2885                 g_warning ("type 0x%x not handled", return_type->type);
2886                 g_assert_not_reached ();
2887         }
2888
2889         mono_mb_emit_byte (mb, CEE_RET);
2890 }
2891
2892 #endif /* DISABLE_JIT */
2893
2894 MonoMethod *
2895 mono_marshal_get_delegate_end_invoke (MonoMethod *method)
2896 {
2897         MonoMethodSignature *sig;
2898         MonoMethodBuilder *mb;
2899         MonoMethod *res;
2900         GHashTable *cache;
2901         int params_var;
2902         char *name;
2903         MonoGenericContext *ctx = NULL;
2904         MonoMethod *orig_method = NULL;
2905
2906         g_assert (method && method->klass->parent == mono_defaults.multicastdelegate_class &&
2907                   !strcmp (method->name, "EndInvoke"));
2908
2909         /*
2910          * For generic delegates, create a generic wrapper, and returns an instance to help AOT.
2911          */
2912         if (method->is_inflated) {
2913                 orig_method = method;
2914                 ctx = &((MonoMethodInflated*)method)->context;
2915                 method = ((MonoMethodInflated*)method)->declaring;
2916         }
2917
2918         sig = mono_signature_no_pinvoke (method);
2919
2920         /*
2921          * Check cache
2922          */
2923         if (ctx) {
2924                 cache = get_cache (&method->klass->image->delegate_end_invoke_generic_cache, mono_aligned_addr_hash, NULL);
2925                 res = check_generic_delegate_wrapper_cache (cache, orig_method, method, ctx);
2926                 if (res)
2927                         return res;
2928         } else {
2929                 cache = get_cache (&method->klass->image->delegate_end_invoke_cache,
2930                                                    (GHashFunc)mono_signature_hash, 
2931                                                    (GCompareFunc)mono_metadata_signature_equal);
2932                 if ((res = mono_marshal_find_in_cache (cache, sig)))
2933                         return res;
2934         }
2935
2936         g_assert (sig->hasthis);
2937
2938         name = mono_signature_to_name (sig, "end_invoke");
2939         if (ctx)
2940                 mb = mono_mb_new (method->klass, name, MONO_WRAPPER_DELEGATE_END_INVOKE);
2941         else
2942                 mb = mono_mb_new (get_wrapper_target_class (method->klass->image), name, MONO_WRAPPER_DELEGATE_END_INVOKE);
2943         g_free (name);
2944
2945 #ifndef DISABLE_JIT
2946         params_var = mono_mb_emit_save_args (mb, sig, FALSE);
2947
2948         mono_mb_emit_ldarg (mb, 0);
2949         mono_mb_emit_ldloc (mb, params_var);
2950         mono_mb_emit_icall (mb, mono_delegate_end_invoke);
2951
2952         if (sig->ret->type == MONO_TYPE_VOID) {
2953                 mono_mb_emit_byte (mb, CEE_POP);
2954                 mono_mb_emit_byte (mb, CEE_RET);
2955         } else
2956                 mono_mb_emit_restore_result (mb, sig->ret);
2957 #endif
2958
2959         if (ctx) {
2960                 MonoMethod *def;
2961                 def = mono_mb_create_and_cache (cache, method->klass, mb, sig, sig->param_count + 16);
2962                 res = cache_generic_delegate_wrapper (cache, orig_method, def, ctx);
2963         } else {
2964                 res = mono_mb_create_and_cache (cache, sig,
2965                                                                                 mb, sig, sig->param_count + 16);
2966         }
2967         mono_mb_free (mb);
2968
2969         return res;
2970 }
2971
2972 typedef struct
2973 {
2974         MonoMethodSignature *sig;
2975         gpointer pointer;
2976 } SignaturePointerPair;
2977
2978 static guint
2979 signature_pointer_pair_hash (gconstpointer data)
2980 {
2981         SignaturePointerPair *pair = (SignaturePointerPair*)data;
2982
2983         return mono_signature_hash (pair->sig) ^ mono_aligned_addr_hash (pair->pointer);
2984 }
2985
2986 static gboolean
2987 signature_pointer_pair_equal (gconstpointer data1, gconstpointer data2)
2988 {
2989         SignaturePointerPair *pair1 = (SignaturePointerPair*) data1, *pair2 = (SignaturePointerPair*) data2;
2990         return mono_metadata_signature_equal (pair1->sig, pair2->sig) && (pair1->pointer == pair2->pointer);
2991 }
2992
2993 static gboolean
2994 signature_pointer_pair_matches_pointer (gpointer key, gpointer value, gpointer user_data)
2995 {
2996         SignaturePointerPair *pair = (SignaturePointerPair*)key;
2997
2998         return pair->pointer == user_data;
2999 }
3000
3001 static void
3002 free_signature_pointer_pair (SignaturePointerPair *pair)
3003 {
3004         g_free (pair);
3005 }
3006
3007 static MonoMethod *
3008 mono_marshal_get_delegate_invoke_internal (MonoMethod *method, gboolean callvirt, gboolean static_method_with_first_arg_bound, MonoMethod *target_method)
3009 {
3010         MonoMethodSignature *sig, *static_sig, *invoke_sig;
3011         int i;
3012         MonoMethodBuilder *mb;
3013         MonoMethod *res;
3014         GHashTable *cache;
3015         gpointer cache_key = NULL;
3016         SignaturePointerPair key;
3017         SignaturePointerPair *new_key;
3018         int local_prev, local_target;
3019         int pos0;
3020         char *name;
3021         MonoClass *target_class = NULL;
3022         gboolean closed_over_null = FALSE;
3023         MonoGenericContext *ctx = NULL;
3024         MonoGenericContainer *container = NULL;
3025         MonoMethod *orig_method = NULL;
3026         WrapperInfo *info;
3027         WrapperSubtype subtype = WRAPPER_SUBTYPE_NONE;
3028         gboolean found;
3029
3030         g_assert (method && method->klass->parent == mono_defaults.multicastdelegate_class &&
3031                   !strcmp (method->name, "Invoke"));
3032
3033         invoke_sig = sig = mono_signature_no_pinvoke (method);
3034
3035         /*
3036          * If the delegate target is null, and the target method is not static, a virtual 
3037          * call is made to that method with the first delegate argument as this. This is 
3038          * a non-documented .NET feature.
3039          */
3040         if (callvirt) {
3041                 subtype = WRAPPER_SUBTYPE_DELEGATE_INVOKE_VIRTUAL;
3042                 if (target_method->is_inflated) {
3043                         MonoType *target_type;
3044
3045                         g_assert (method->signature->hasthis);
3046                         target_type = mono_class_inflate_generic_type (method->signature->params [0],
3047                                 mono_method_get_context (method));
3048                         target_class = mono_class_from_mono_type (target_type);
3049                 } else {
3050                         target_class = target_method->klass;
3051                 }
3052
3053                 closed_over_null = sig->param_count == mono_method_signature (target_method)->param_count;
3054         }
3055
3056         if (static_method_with_first_arg_bound) {
3057                 subtype = WRAPPER_SUBTYPE_DELEGATE_INVOKE_BOUND;
3058                 g_assert (!callvirt);
3059                 invoke_sig = mono_method_signature (target_method);
3060         }
3061
3062         /*
3063          * For generic delegates, create a generic wrapper, and return an instance to help AOT.
3064          */
3065         if (method->is_inflated && subtype == WRAPPER_SUBTYPE_NONE) {
3066                 orig_method = method;
3067                 ctx = &((MonoMethodInflated*)method)->context;
3068                 method = ((MonoMethodInflated*)method)->declaring;
3069
3070                 container = mono_method_get_generic_container (method);
3071                 if (!container)
3072                         container = method->klass->generic_container;
3073                 g_assert (container);
3074
3075                 invoke_sig = sig = mono_signature_no_pinvoke (method);
3076         }
3077
3078         /*
3079          * Check cache
3080          */
3081         if (ctx) {
3082                 cache = get_cache (&method->klass->image->delegate_invoke_generic_cache, mono_aligned_addr_hash, NULL);
3083                 res = check_generic_delegate_wrapper_cache (cache, orig_method, method, ctx);
3084                 if (res)
3085                         return res;
3086                 cache_key = method->klass;
3087         } else if (static_method_with_first_arg_bound) {
3088                 cache = get_cache (&method->klass->image->delegate_bound_static_invoke_cache,
3089                                                    (GHashFunc)mono_signature_hash, 
3090                                                    (GCompareFunc)mono_metadata_signature_equal);
3091                 /*
3092                  * The wrapper is based on sig+invoke_sig, but sig can be derived from invoke_sig.
3093                  */
3094                 res = mono_marshal_find_in_cache (cache, invoke_sig);
3095                 if (res)
3096                         return res;
3097                 cache_key = invoke_sig;
3098         } else if (callvirt) {
3099                 GHashTable **cache_ptr;
3100
3101                 cache_ptr = &method->klass->image->delegate_abstract_invoke_cache;
3102
3103                 /* We need to cache the signature+method pair */
3104                 mono_marshal_lock ();
3105                 if (!*cache_ptr)
3106                         *cache_ptr = g_hash_table_new_full (signature_pointer_pair_hash, (GEqualFunc)signature_pointer_pair_equal, (GDestroyNotify)free_signature_pointer_pair, NULL);
3107                 cache = *cache_ptr;
3108                 key.sig = invoke_sig;
3109                 key.pointer = target_method;
3110                 res = g_hash_table_lookup (cache, &key);
3111                 mono_marshal_unlock ();
3112                 if (res)
3113                         return res;
3114         } else {
3115                 cache = get_cache (&method->klass->image->delegate_invoke_cache,
3116                                                    (GHashFunc)mono_signature_hash, 
3117                                                    (GCompareFunc)mono_metadata_signature_equal);
3118                 res = mono_marshal_find_in_cache (cache, sig);
3119                 if (res)
3120                         return res;
3121                 cache_key = sig;
3122         }
3123
3124         static_sig = signature_dup (method->klass->image, sig);
3125         static_sig->hasthis = 0;
3126         if (!static_method_with_first_arg_bound)
3127                 invoke_sig = static_sig;
3128
3129         if (static_method_with_first_arg_bound)
3130                 name = mono_signature_to_name (invoke_sig, "invoke_bound");
3131         else if (closed_over_null)
3132                 name = mono_signature_to_name (invoke_sig, "invoke_closed_over_null");
3133         else if (callvirt)
3134                 name = mono_signature_to_name (invoke_sig, "invoke_callvirt");
3135         else
3136                 name = mono_signature_to_name (invoke_sig, "invoke");
3137         if (ctx)
3138                 mb = mono_mb_new (method->klass, name, MONO_WRAPPER_DELEGATE_INVOKE);
3139         else
3140                 mb = mono_mb_new (get_wrapper_target_class (method->klass->image), name, MONO_WRAPPER_DELEGATE_INVOKE);
3141         g_free (name);
3142
3143 #ifndef DISABLE_JIT
3144         /* allocate local 0 (object) */
3145         local_target = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
3146         local_prev = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
3147
3148         g_assert (sig->hasthis);
3149         
3150         /*
3151          * if (prev != null)
3152          *      prev.Invoke( args .. );
3153          * return this.<target>( args .. );
3154          */
3155         
3156         /* this wrapper can be used in unmanaged-managed transitions */
3157         emit_thread_interrupt_checkpoint (mb);
3158         
3159         /* get this->prev */
3160         mono_mb_emit_ldarg (mb, 0);
3161         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoMulticastDelegate, prev));
3162         mono_mb_emit_byte (mb, CEE_LDIND_REF);
3163         mono_mb_emit_stloc (mb, local_prev);
3164         mono_mb_emit_ldloc (mb, local_prev);
3165
3166         /* if prev != null */
3167         pos0 = mono_mb_emit_branch (mb, CEE_BRFALSE);
3168
3169         /* then recurse */
3170
3171         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
3172         mono_mb_emit_byte (mb, CEE_MONO_NOT_TAKEN);
3173
3174         mono_mb_emit_ldloc (mb, local_prev);
3175         for (i = 0; i < sig->param_count; i++)
3176                 mono_mb_emit_ldarg (mb, i + 1);
3177         if (ctx) {
3178                 MonoError error;
3179                 mono_mb_emit_op (mb, CEE_CALLVIRT, mono_class_inflate_generic_method_checked (method, &container->context, &error));
3180                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3181         } else {
3182                 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
3183         }
3184         if (sig->ret->type != MONO_TYPE_VOID)
3185                 mono_mb_emit_byte (mb, CEE_POP);
3186
3187         /* continued or prev == null */
3188         mono_mb_patch_branch (mb, pos0);
3189
3190         /* get this->target */
3191         mono_mb_emit_ldarg (mb, 0);
3192         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoDelegate, target));
3193         mono_mb_emit_byte (mb, CEE_LDIND_REF);
3194         mono_mb_emit_stloc (mb, local_target);
3195
3196         /*static methods with bound first arg can have null target and still be bound*/
3197         if (!static_method_with_first_arg_bound) {
3198                 /* if target != null */
3199                 mono_mb_emit_ldloc (mb, local_target);
3200                 pos0 = mono_mb_emit_branch (mb, CEE_BRFALSE);
3201
3202                 /* then call this->method_ptr nonstatic */
3203                 if (callvirt) {
3204                         // FIXME:
3205                         mono_mb_emit_exception_full (mb, "System", "NotImplementedException", "");
3206                 } else {
3207                         mono_mb_emit_ldloc (mb, local_target);
3208                         for (i = 0; i < sig->param_count; ++i)
3209                                 mono_mb_emit_ldarg (mb, i + 1);
3210                         mono_mb_emit_ldarg (mb, 0);
3211                         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoDelegate, method_ptr));
3212                         mono_mb_emit_byte (mb, CEE_LDIND_I );
3213                         mono_mb_emit_op (mb, CEE_CALLI, sig);
3214
3215                         mono_mb_emit_byte (mb, CEE_RET);
3216                 }
3217         
3218                 /* else [target == null] call this->method_ptr static */
3219                 mono_mb_patch_branch (mb, pos0);
3220         }
3221
3222         if (callvirt) {
3223                 if (!closed_over_null) {
3224                         mono_mb_emit_ldarg (mb, 1);
3225                         mono_mb_emit_op (mb, CEE_CASTCLASS, target_class);
3226                         for (i = 1; i < sig->param_count; ++i)
3227                                 mono_mb_emit_ldarg (mb, i + 1);
3228                         mono_mb_emit_op (mb, CEE_CALLVIRT, target_method);
3229                 } else {
3230                         mono_mb_emit_byte (mb, CEE_LDNULL);
3231                         for (i = 0; i < sig->param_count; ++i)
3232                                 mono_mb_emit_ldarg (mb, i + 1);
3233                         mono_mb_emit_op (mb, CEE_CALL, target_method);
3234                 }
3235         } else {
3236                 if (static_method_with_first_arg_bound) {
3237                         mono_mb_emit_ldloc (mb, local_target);
3238                         if (!MONO_TYPE_IS_REFERENCE (invoke_sig->params[0]))
3239                                 mono_mb_emit_op (mb, CEE_UNBOX_ANY, mono_class_from_mono_type (invoke_sig->params[0]));
3240                 }
3241                 for (i = 0; i < sig->param_count; ++i)
3242                         mono_mb_emit_ldarg (mb, i + 1);
3243                 mono_mb_emit_ldarg (mb, 0);
3244                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoDelegate, method_ptr));
3245                 mono_mb_emit_byte (mb, CEE_LDIND_I );
3246                 mono_mb_emit_op (mb, CEE_CALLI, invoke_sig);
3247         }
3248
3249         mono_mb_emit_byte (mb, CEE_RET);
3250
3251         mb->skip_visibility = 1;
3252 #endif /* DISABLE_JIT */
3253
3254         if (ctx) {
3255                 MonoMethod *def;
3256
3257                 def = mono_mb_create_and_cache (cache, cache_key, mb, sig, sig->param_count + 16);
3258                 res = cache_generic_delegate_wrapper (cache, orig_method, def, ctx);
3259         } else if (callvirt) {
3260                 new_key = g_new0 (SignaturePointerPair, 1);
3261                 *new_key = key;
3262
3263                 info = mono_wrapper_info_create (mb, subtype);
3264
3265                 res = mono_mb_create_and_cache_full (cache, new_key, mb, sig, sig->param_count + 16, info, &found);
3266                 if (found)
3267                         g_free (new_key);
3268         } else {
3269                 info = mono_wrapper_info_create (mb, subtype);
3270
3271                 res = mono_mb_create_and_cache_full (cache, cache_key, mb, sig, sig->param_count + 16, info, NULL);
3272         }
3273         mono_mb_free (mb);
3274
3275         return res;     
3276 }
3277
3278 /*
3279  * the returned method invokes all methods in a multicast delegate.
3280  */
3281 MonoMethod *
3282 mono_marshal_get_delegate_invoke (MonoMethod *method, MonoDelegate *del)
3283 {
3284         gboolean callvirt = FALSE;
3285         gboolean static_method_with_first_arg_bound = FALSE;
3286         MonoMethod *target_method = NULL;
3287         MonoMethodSignature *sig;
3288
3289         sig = mono_signature_no_pinvoke (method);
3290
3291         if (del && !del->target && del->method && mono_method_signature (del->method)->hasthis) {
3292                 callvirt = TRUE;
3293                 target_method = del->method;
3294         }
3295
3296         if (del && del->method && mono_method_signature (del->method)->param_count == sig->param_count + 1 && (del->method->flags & METHOD_ATTRIBUTE_STATIC)) {
3297                 static_method_with_first_arg_bound = TRUE;
3298                 target_method = del->method;
3299         }
3300
3301         return mono_marshal_get_delegate_invoke_internal (method, callvirt, static_method_with_first_arg_bound, target_method);
3302 }
3303
3304 /*
3305  * signature_dup_add_this:
3306  *
3307  *  Make a copy of @sig, adding an explicit this argument.
3308  */
3309 static MonoMethodSignature*
3310 signature_dup_add_this (MonoImage *image, MonoMethodSignature *sig, MonoClass *klass)
3311 {
3312         MonoMethodSignature *res;
3313         int i;
3314
3315         res = mono_metadata_signature_alloc (image, sig->param_count + 1);
3316         memcpy (res, sig, MONO_SIZEOF_METHOD_SIGNATURE);
3317         res->param_count = sig->param_count + 1;
3318         res->hasthis = FALSE;
3319         for (i = sig->param_count - 1; i >= 0; i --)
3320                 res->params [i + 1] = sig->params [i];
3321         res->params [0] = klass->valuetype ? &klass->this_arg : &klass->byval_arg;
3322
3323         return res;
3324 }
3325
3326 typedef struct {
3327         MonoMethodSignature *ctor_sig;
3328         MonoMethodSignature *sig;
3329 } CtorSigPair;
3330
3331 /* protected by the marshal lock, contains CtorSigPair pointers */
3332 static GSList *strsig_list = NULL;
3333
3334 static MonoMethodSignature *
3335 lookup_string_ctor_signature (MonoMethodSignature *sig)
3336 {
3337         MonoMethodSignature *callsig;
3338         CtorSigPair *cs;
3339         GSList *item;
3340
3341         mono_marshal_lock ();
3342         callsig = NULL;
3343         for (item = strsig_list; item; item = item->next) {
3344                 cs = item->data;
3345                 /* mono_metadata_signature_equal () is safe to call with the marshal lock
3346                  * because it is lock-free.
3347                  */
3348                 if (mono_metadata_signature_equal (sig, cs->ctor_sig)) {
3349                         callsig = cs->sig;
3350                         break;
3351                 }
3352         }
3353         mono_marshal_unlock ();
3354         return callsig;
3355 }
3356
3357 static MonoMethodSignature *
3358 add_string_ctor_signature (MonoMethod *method)
3359 {
3360         MonoMethodSignature *callsig;
3361         CtorSigPair *cs;
3362
3363         callsig = signature_dup (method->klass->image, mono_method_signature (method));
3364         callsig->ret = &mono_defaults.string_class->byval_arg;
3365         cs = g_new (CtorSigPair, 1);
3366         cs->sig = callsig;
3367         cs->ctor_sig = mono_method_signature (method);
3368
3369         mono_marshal_lock ();
3370         strsig_list = g_slist_prepend (strsig_list, cs);
3371         mono_marshal_unlock ();
3372         return callsig;
3373 }
3374
3375 /*
3376  * mono_marshal_get_string_ctor_signature:
3377  *
3378  *   Return the modified signature used by string ctors (they return the newly created
3379  * string).
3380  */
3381 MonoMethodSignature*
3382 mono_marshal_get_string_ctor_signature (MonoMethod *method)
3383 {
3384         MonoMethodSignature *sig = lookup_string_ctor_signature (mono_method_signature (method));
3385         if (!sig)
3386                 sig = add_string_ctor_signature (method);
3387
3388         return sig;
3389 }
3390
3391 static MonoType*
3392 get_runtime_invoke_type (MonoType *t, gboolean ret)
3393 {
3394         if (t->byref) {
3395                 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t)))
3396                         return t;
3397                 /* Can't share this with 'I' as that needs another indirection */
3398                 return &mono_defaults.int_class->this_arg;
3399         }
3400
3401         if (MONO_TYPE_IS_REFERENCE (t))
3402                 return &mono_defaults.object_class->byval_arg;
3403
3404         if (ret)
3405                 /* The result needs to be boxed */
3406                 return t;
3407
3408 handle_enum:
3409         switch (t->type) {
3410                 /* Can't share these as the argument needs to be loaded using sign/zero extension */
3411                 /*
3412         case MONO_TYPE_U1:
3413                 return &mono_defaults.sbyte_class->byval_arg;
3414         case MONO_TYPE_U2:
3415                 return &mono_defaults.int16_class->byval_arg;
3416         case MONO_TYPE_U4:
3417                 return &mono_defaults.int32_class->byval_arg;
3418                 */
3419         case MONO_TYPE_U8:
3420                 return &mono_defaults.int64_class->byval_arg;
3421         case MONO_TYPE_BOOLEAN:
3422                 return &mono_defaults.byte_class->byval_arg;
3423         case MONO_TYPE_CHAR:
3424                 return &mono_defaults.uint16_class->byval_arg;
3425         case MONO_TYPE_U:
3426         case MONO_TYPE_PTR:
3427                 return &mono_defaults.int_class->byval_arg;
3428         case MONO_TYPE_VALUETYPE:
3429                 if (t->data.klass->enumtype) {
3430                         t = mono_class_enum_basetype (t->data.klass);
3431                         goto handle_enum;
3432                 }
3433                 return t;
3434         default:
3435                 return t;
3436         }
3437 }
3438
3439 /*
3440  * mono_marshal_get_runtime_invoke_sig:
3441  *
3442  *   Return a common signature used for sharing runtime invoke wrappers.
3443  */
3444 static MonoMethodSignature*
3445 mono_marshal_get_runtime_invoke_sig (MonoMethodSignature *sig)
3446 {
3447         MonoMethodSignature *res = mono_metadata_signature_dup (sig);
3448         int i;
3449
3450         res->generic_param_count = 0;
3451         res->ret = get_runtime_invoke_type (sig->ret, TRUE);
3452         for (i = 0; i < res->param_count; ++i)
3453                 res->params [i] = get_runtime_invoke_type (sig->params [i], FALSE);
3454
3455         return res;
3456 }
3457
3458 static gboolean
3459 runtime_invoke_signature_equal (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
3460 {
3461         /* Can't share wrappers which return a vtype since it needs to be boxed */
3462         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))
3463                 return FALSE;
3464         else
3465                 return mono_metadata_signature_equal (sig1, sig2);
3466 }
3467
3468 #ifndef DISABLE_JIT
3469
3470 /*
3471  * emit_invoke_call:
3472  *
3473  *   Emit the call to the wrapper method from a runtime invoke wrapper.
3474  */
3475 static void
3476 emit_invoke_call (MonoMethodBuilder *mb, MonoMethod *method,
3477                                   MonoMethodSignature *sig, MonoMethodSignature *callsig,
3478                                   int loc_res,
3479                                   gboolean virtual, gboolean need_direct_wrapper)
3480 {
3481         static MonoString *string_dummy = NULL;
3482         int i;
3483         int *tmp_nullable_locals;
3484         gboolean void_ret = FALSE;
3485
3486         /* to make it work with our special string constructors */
3487         if (!string_dummy) {
3488                 MONO_GC_REGISTER_ROOT_SINGLE (string_dummy);
3489                 string_dummy = mono_string_new_wrapper ("dummy");
3490         }
3491
3492         if (virtual) {
3493                 g_assert (sig->hasthis);
3494                 g_assert (method->flags & METHOD_ATTRIBUTE_VIRTUAL);
3495         }
3496
3497         if (sig->hasthis) {
3498                 if (method->string_ctor) {
3499                         if (mono_gc_is_moving ()) {
3500                                 mono_mb_emit_ptr (mb, &string_dummy);
3501                                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
3502                         } else {
3503                                 mono_mb_emit_ptr (mb, string_dummy);
3504                         }
3505                 } else {
3506                         mono_mb_emit_ldarg (mb, 0);
3507                 }
3508         }
3509
3510         tmp_nullable_locals = g_new0 (int, sig->param_count);
3511
3512         for (i = 0; i < sig->param_count; i++) {
3513                 MonoType *t = sig->params [i];
3514                 int type;
3515
3516                 mono_mb_emit_ldarg (mb, 1);
3517                 if (i) {
3518                         mono_mb_emit_icon (mb, sizeof (gpointer) * i);
3519                         mono_mb_emit_byte (mb, CEE_ADD);
3520                 }
3521
3522                 if (t->byref) {
3523                         mono_mb_emit_byte (mb, CEE_LDIND_I);
3524                         /* A Nullable<T> type don't have a boxed form, it's either null or a boxed T.
3525                          * So to make this work we unbox it to a local variablee and push a reference to that.
3526                          */
3527                         if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
3528                                 tmp_nullable_locals [i] = mono_mb_add_local (mb, &mono_class_from_mono_type (t)->byval_arg);
3529
3530                                 mono_mb_emit_op (mb, CEE_UNBOX_ANY, mono_class_from_mono_type (t));
3531                                 mono_mb_emit_stloc (mb, tmp_nullable_locals [i]);
3532                                 mono_mb_emit_ldloc_addr (mb, tmp_nullable_locals [i]);
3533                         }
3534                         continue;
3535                 }
3536
3537                 /*FIXME 'this doesn't handle generic enums. Shouldn't we?*/
3538                 type = sig->params [i]->type;
3539 handle_enum:
3540                 switch (type) {
3541                 case MONO_TYPE_I1:
3542                 case MONO_TYPE_BOOLEAN:
3543                 case MONO_TYPE_U1:
3544                 case MONO_TYPE_I2:
3545                 case MONO_TYPE_U2:
3546                 case MONO_TYPE_CHAR:
3547                 case MONO_TYPE_I:
3548                 case MONO_TYPE_U:
3549                 case MONO_TYPE_I4:
3550                 case MONO_TYPE_U4:
3551                 case MONO_TYPE_R4:
3552                 case MONO_TYPE_R8:
3553                 case MONO_TYPE_I8:
3554                 case MONO_TYPE_U8:
3555                         mono_mb_emit_byte (mb, CEE_LDIND_I);
3556                         mono_mb_emit_byte (mb, mono_type_to_ldind (sig->params [i]));
3557                         break;
3558                 case MONO_TYPE_STRING:
3559                 case MONO_TYPE_CLASS:  
3560                 case MONO_TYPE_ARRAY:
3561                 case MONO_TYPE_PTR:
3562                 case MONO_TYPE_SZARRAY:
3563                 case MONO_TYPE_OBJECT:
3564                         mono_mb_emit_byte (mb, mono_type_to_ldind (sig->params [i]));
3565                         break;
3566                 case MONO_TYPE_GENERICINST:
3567                         if (!mono_type_generic_inst_is_valuetype (sig->params [i])) {
3568                                 mono_mb_emit_byte (mb, mono_type_to_ldind (sig->params [i]));
3569                                 break;
3570                         }
3571
3572                         /* fall through */
3573                 case MONO_TYPE_VALUETYPE:
3574                         if (type == MONO_TYPE_VALUETYPE && t->data.klass->enumtype) {
3575                                 type = mono_class_enum_basetype (t->data.klass)->type;
3576                                 goto handle_enum;
3577                         }
3578                         mono_mb_emit_byte (mb, CEE_LDIND_I);
3579                         if (mono_class_is_nullable (mono_class_from_mono_type (sig->params [i]))) {
3580                                 /* Need to convert a boxed vtype to an mp to a Nullable struct */
3581                                 mono_mb_emit_op (mb, CEE_UNBOX, mono_class_from_mono_type (sig->params [i]));
3582                                 mono_mb_emit_op (mb, CEE_LDOBJ, mono_class_from_mono_type (sig->params [i]));
3583                         } else {
3584                                 mono_mb_emit_op (mb, CEE_LDOBJ, mono_class_from_mono_type (sig->params [i]));
3585                         }
3586                         break;
3587                 default:
3588                         g_assert_not_reached ();
3589                 }
3590         }
3591         
3592         if (virtual) {
3593                 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
3594         } else if (need_direct_wrapper) {
3595                 mono_mb_emit_op (mb, CEE_CALL, method);
3596         } else {
3597                 mono_mb_emit_ldarg (mb, 3);
3598                 mono_mb_emit_calli (mb, callsig);
3599         }
3600
3601         if (sig->ret->byref) {
3602                 /* fixme: */
3603                 g_assert_not_reached ();
3604         }
3605
3606         switch (sig->ret->type) {
3607         case MONO_TYPE_VOID:
3608                 if (!method->string_ctor)
3609                         void_ret = TRUE;
3610                 break;
3611         case MONO_TYPE_BOOLEAN:
3612         case MONO_TYPE_CHAR:
3613         case MONO_TYPE_I1:
3614         case MONO_TYPE_U1:
3615         case MONO_TYPE_I2:
3616         case MONO_TYPE_U2:
3617         case MONO_TYPE_I4:
3618         case MONO_TYPE_U4:
3619         case MONO_TYPE_I:
3620         case MONO_TYPE_U:
3621         case MONO_TYPE_R4:
3622         case MONO_TYPE_R8:
3623         case MONO_TYPE_I8:
3624         case MONO_TYPE_U8:
3625         case MONO_TYPE_VALUETYPE:
3626         case MONO_TYPE_TYPEDBYREF:
3627         case MONO_TYPE_GENERICINST:
3628                 /* box value types */
3629                 mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (sig->ret));
3630                 break;
3631         case MONO_TYPE_STRING:
3632         case MONO_TYPE_CLASS:  
3633         case MONO_TYPE_ARRAY:
3634         case MONO_TYPE_SZARRAY:
3635         case MONO_TYPE_OBJECT:
3636                 /* nothing to do */
3637                 break;
3638         case MONO_TYPE_PTR:
3639                 /* The result is an IntPtr */
3640                 mono_mb_emit_op (mb, CEE_BOX, mono_defaults.int_class);
3641                 break;
3642         default:
3643                 g_assert_not_reached ();
3644         }
3645
3646         if (!void_ret)
3647                 mono_mb_emit_stloc (mb, loc_res);
3648
3649         /* Convert back nullable-byref arguments */
3650         for (i = 0; i < sig->param_count; i++) {
3651                 MonoType *t = sig->params [i];
3652
3653                 /* 
3654                  * Box the result and put it back into the array, the caller will have
3655                  * to obtain it from there.
3656                  */
3657                 if (t->byref && t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
3658                         mono_mb_emit_ldarg (mb, 1);                     
3659                         mono_mb_emit_icon (mb, sizeof (gpointer) * i);
3660                         mono_mb_emit_byte (mb, CEE_ADD);
3661
3662                         mono_mb_emit_ldloc (mb, tmp_nullable_locals [i]);
3663                         mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (t));
3664
3665                         mono_mb_emit_byte (mb, CEE_STIND_REF);
3666                 }
3667         }
3668
3669         g_free (tmp_nullable_locals);
3670 }
3671
3672 static void
3673 emit_runtime_invoke_body (MonoMethodBuilder *mb, MonoClass *target_klass, MonoMethod *method,
3674                                                   MonoMethodSignature *sig, MonoMethodSignature *callsig,
3675                                                   gboolean virtual, gboolean need_direct_wrapper)
3676 {
3677         gint32 labels [16];
3678         MonoExceptionClause *clause;
3679         int loc_res, loc_exc;
3680
3681         /* The wrapper looks like this:
3682          *
3683          * <interrupt check>
3684          * if (exc) {
3685          *       try {
3686          *         return <call>
3687          *       } catch (Exception e) {
3688          *     *exc = e;
3689          *   }
3690          * } else {
3691          *     return <call>
3692          * }
3693          */
3694
3695         /* allocate local 0 (object) tmp */
3696         loc_res = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
3697         /* allocate local 1 (object) exc */
3698         loc_exc = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
3699
3700         /* *exc is assumed to be initialized to NULL by the caller */
3701
3702         mono_mb_emit_byte (mb, CEE_LDARG_2);
3703         labels [0] = mono_mb_emit_branch (mb, CEE_BRFALSE);
3704
3705         /*
3706          * if (exc) case
3707          */
3708         labels [1] = mono_mb_get_label (mb);
3709         emit_thread_force_interrupt_checkpoint (mb);
3710         emit_invoke_call (mb, method, sig, callsig, loc_res, virtual, need_direct_wrapper);
3711
3712         labels [2] = mono_mb_emit_branch (mb, CEE_LEAVE);
3713
3714         /* Add a try clause around the call */
3715         clause = mono_image_alloc0 (target_klass->image, sizeof (MonoExceptionClause));
3716         clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
3717         clause->data.catch_class = mono_defaults.exception_class;
3718         clause->try_offset = labels [1];
3719         clause->try_len = mono_mb_get_label (mb) - labels [1];
3720
3721         clause->handler_offset = mono_mb_get_label (mb);
3722
3723         /* handler code */
3724         mono_mb_emit_stloc (mb, loc_exc);       
3725         mono_mb_emit_byte (mb, CEE_LDARG_2);
3726         mono_mb_emit_ldloc (mb, loc_exc);
3727         mono_mb_emit_byte (mb, CEE_STIND_REF);
3728
3729         mono_mb_emit_branch (mb, CEE_LEAVE);
3730
3731         clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
3732
3733         mono_mb_set_clauses (mb, 1, clause);
3734
3735         mono_mb_patch_branch (mb, labels [2]);
3736         mono_mb_emit_ldloc (mb, loc_res);
3737         mono_mb_emit_byte (mb, CEE_RET);
3738
3739         /*
3740          * if (!exc) case
3741          */
3742         mono_mb_patch_branch (mb, labels [0]);
3743         emit_thread_force_interrupt_checkpoint (mb);
3744         emit_invoke_call (mb, method, sig, callsig, loc_res, virtual, need_direct_wrapper);
3745
3746         mono_mb_emit_ldloc (mb, 0);
3747         mono_mb_emit_byte (mb, CEE_RET);
3748 }
3749 #endif
3750
3751 /*
3752  * generates IL code for the runtime invoke function 
3753  * MonoObject *runtime_invoke (MonoObject *this, void **params, MonoObject **exc, void* method)
3754  *
3755  * we also catch exceptions if exc != null
3756  * If VIRTUAL is TRUE, then METHOD is invoked virtually on THIS. This is useful since
3757  * it means that the compiled code for METHOD does not have to be looked up 
3758  * before calling the runtime invoke wrapper. In this case, the wrapper ignores
3759  * its METHOD argument.
3760  */
3761 MonoMethod *
3762 mono_marshal_get_runtime_invoke (MonoMethod *method, gboolean virtual)
3763 {
3764         MonoMethodSignature *sig, *csig, *callsig;
3765         MonoMethodBuilder *mb;
3766         GHashTable *cache = NULL;
3767         MonoClass *target_klass;
3768         MonoMethod *res = NULL;
3769         static MonoMethodSignature *cctor_signature = NULL;
3770         static MonoMethodSignature *finalize_signature = NULL;
3771         char *name;
3772         const char *param_names [16];
3773         gboolean need_direct_wrapper = FALSE;
3774         WrapperInfo *info;
3775
3776         g_assert (method);
3777
3778         if (!cctor_signature) {
3779                 cctor_signature = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3780                 cctor_signature->ret = &mono_defaults.void_class->byval_arg;
3781         }
3782         if (!finalize_signature) {
3783                 finalize_signature = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3784                 finalize_signature->ret = &mono_defaults.void_class->byval_arg;
3785                 finalize_signature->hasthis = 1;
3786         }
3787
3788         if (virtual)
3789                 need_direct_wrapper = TRUE;
3790
3791         /* 
3792          * Use a separate cache indexed by methods to speed things up and to avoid the
3793          * boundless mempool growth caused by the signature_dup stuff below.
3794          */
3795         if (virtual)
3796                 cache = get_cache (&method->klass->image->runtime_invoke_vcall_cache, mono_aligned_addr_hash, NULL);
3797         else
3798                 cache = get_cache (&method->klass->image->runtime_invoke_direct_cache, mono_aligned_addr_hash, NULL);
3799         res = mono_marshal_find_in_cache (cache, method);
3800         if (res)
3801                 return res;
3802                 
3803         if (method->klass->rank && (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
3804                 (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
3805                 /* 
3806                  * Array Get/Set/Address methods. The JIT implements them using inline code
3807                  * so we need to create an invoke wrapper which calls the method directly.
3808                  */
3809                 need_direct_wrapper = TRUE;
3810         }
3811                 
3812         if (method->string_ctor) {
3813                 callsig = lookup_string_ctor_signature (mono_method_signature (method));
3814                 if (!callsig)
3815                         callsig = add_string_ctor_signature (method);
3816                 /* Can't share this as we push a string as this */
3817                 need_direct_wrapper = TRUE;
3818         } else {
3819                 if (method_is_dynamic (method))
3820                         callsig = signature_dup (method->klass->image, mono_method_signature (method));
3821                 else
3822                         callsig = mono_method_signature (method);
3823         }
3824
3825         target_klass = get_wrapper_target_class (method->klass->image);
3826
3827         /* Try to share wrappers for non-corlib methods with simple signatures */
3828         if (mono_metadata_signature_equal (callsig, cctor_signature)) {
3829                 callsig = cctor_signature;
3830                 target_klass = mono_defaults.object_class;
3831         } else if (mono_metadata_signature_equal (callsig, finalize_signature)) {
3832                 callsig = finalize_signature;
3833                 target_klass = mono_defaults.object_class;
3834         }
3835
3836         if (need_direct_wrapper) {
3837                 /* Already searched at the start */
3838         } else {
3839                 MonoMethodSignature *tmp_sig;
3840
3841                 callsig = mono_marshal_get_runtime_invoke_sig (callsig);
3842
3843                 if (method->klass->valuetype && mono_method_signature (method)->hasthis)
3844                         /* These have a different csig */
3845                         cache = get_cache (&target_klass->image->runtime_invoke_vtype_cache,
3846                                                            (GHashFunc)mono_signature_hash,
3847                                                            (GCompareFunc)runtime_invoke_signature_equal);
3848                 else
3849                         cache = get_cache (&target_klass->image->runtime_invoke_cache,
3850                                                            (GHashFunc)mono_signature_hash,
3851                                                            (GCompareFunc)runtime_invoke_signature_equal);
3852
3853                 /* from mono_marshal_find_in_cache */
3854                 mono_marshal_lock ();
3855                 res = g_hash_table_lookup (cache, callsig);
3856                 mono_marshal_unlock ();
3857
3858                 if (res) {
3859                         g_free (callsig);
3860                         return res;
3861                 }
3862
3863                 /* Make a copy of the signature from the image mempool */
3864                 tmp_sig = callsig;
3865                 callsig = mono_metadata_signature_dup_full (target_klass->image, callsig);
3866                 g_free (tmp_sig);
3867         }
3868         
3869         sig = mono_method_signature (method);
3870
3871         csig = mono_metadata_signature_alloc (target_klass->image, 4);
3872
3873         csig->ret = &mono_defaults.object_class->byval_arg;
3874         if (method->klass->valuetype && mono_method_signature (method)->hasthis)
3875                 csig->params [0] = get_runtime_invoke_type (&method->klass->this_arg, FALSE);
3876         else
3877                 csig->params [0] = &mono_defaults.object_class->byval_arg;
3878         csig->params [1] = &mono_defaults.int_class->byval_arg;
3879         csig->params [2] = &mono_defaults.int_class->byval_arg;
3880         csig->params [3] = &mono_defaults.int_class->byval_arg;
3881         csig->pinvoke = 1;
3882 #if TARGET_WIN32
3883         /* This is called from runtime code so it has to be cdecl */
3884         csig->call_convention = MONO_CALL_C;
3885 #endif
3886
3887         name = mono_signature_to_name (callsig, virtual ? "runtime_invoke_virtual" : "runtime_invoke");
3888         mb = mono_mb_new (target_klass, name,  MONO_WRAPPER_RUNTIME_INVOKE);
3889         g_free (name);
3890
3891 #ifndef DISABLE_JIT
3892         param_names [0] = "this";
3893         param_names [1] = "params";
3894         param_names [2] = "exc";
3895         param_names [3] = "method";
3896         mono_mb_set_param_names (mb, param_names);
3897
3898         emit_runtime_invoke_body (mb, target_klass, method, sig, callsig, virtual, need_direct_wrapper);
3899 #endif
3900
3901         if (need_direct_wrapper) {
3902 #ifndef DISABLE_JIT
3903                 mb->skip_visibility = 1;
3904 #endif
3905                 info = mono_wrapper_info_create (mb, virtual ? WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL : WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT);
3906                 info->d.runtime_invoke.method = method;
3907                 res = mono_mb_create_and_cache_full (cache, method, mb, csig, sig->param_count + 16, info, NULL);
3908         } else {
3909                 /* taken from mono_mb_create_and_cache */
3910                 mono_marshal_lock ();
3911                 res = g_hash_table_lookup (cache, callsig);
3912                 mono_marshal_unlock ();
3913
3914                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL);
3915                 info->d.runtime_invoke.sig = callsig;
3916
3917                 /* Somebody may have created it before us */
3918                 if (!res) {
3919                         MonoMethod *newm;
3920                         newm = mono_mb_create (mb, csig, sig->param_count + 16, info);
3921
3922                         mono_marshal_lock ();
3923                         res = g_hash_table_lookup (cache, callsig);
3924                         if (!res) {
3925                                 res = newm;
3926                                 g_hash_table_insert (cache, callsig, res);
3927                                 /* Can't insert it into wrapper_hash since the key is a signature */
3928                                 g_hash_table_insert (method->klass->image->runtime_invoke_direct_cache, method, res);
3929                         } else {
3930                                 mono_free_method (newm);
3931                         }
3932                         mono_marshal_unlock ();
3933                 }
3934
3935                 /* end mono_mb_create_and_cache */
3936         }
3937
3938         mono_mb_free (mb);
3939
3940         return res;     
3941 }
3942
3943 /*
3944  * mono_marshal_get_runtime_invoke_dynamic:
3945  *
3946  *   Return a method which can be used to invoke managed methods from native code
3947  * dynamically.
3948  * The signature of the returned method is given by RuntimeInvokeDynamicFunction:
3949  * void runtime_invoke (void *args, MonoObject **exc, void *compiled_method)
3950  * ARGS should point to an architecture specific structure containing 
3951  * the arguments and space for the return value.
3952  * The other arguments are the same as for runtime_invoke (), except that
3953  * ARGS should contain the this argument too.
3954  * This wrapper serves the same purpose as the runtime-invoke wrappers, but there
3955  * is only one copy of it, which is useful in full-aot.
3956  * The wrapper info for the wrapper is a WrapperInfo structure.
3957  */
3958 MonoMethod*
3959 mono_marshal_get_runtime_invoke_dynamic (void)
3960 {
3961         static MonoMethod *method;
3962         MonoMethodSignature *csig;
3963         MonoExceptionClause *clause;
3964         MonoMethodBuilder *mb;
3965         int pos, posna;
3966         char *name;
3967         WrapperInfo *info;
3968
3969         if (method)
3970                 return method;
3971
3972         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 4);
3973
3974         csig->ret = &mono_defaults.void_class->byval_arg;
3975         csig->params [0] = &mono_defaults.int_class->byval_arg;
3976         csig->params [1] = &mono_defaults.int_class->byval_arg;
3977         csig->params [2] = &mono_defaults.int_class->byval_arg;
3978         csig->params [3] = &mono_defaults.int_class->byval_arg;
3979
3980         name = g_strdup ("runtime_invoke_dynamic");
3981         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_RUNTIME_INVOKE);
3982         g_free (name);
3983
3984 #ifndef DISABLE_JIT
3985         /* allocate local 0 (object) tmp */
3986         mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
3987         /* allocate local 1 (object) exc */
3988         mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
3989
3990         /* cond set *exc to null */
3991         mono_mb_emit_byte (mb, CEE_LDARG_1);
3992         mono_mb_emit_byte (mb, CEE_BRFALSE_S);
3993         mono_mb_emit_byte (mb, 3);      
3994         mono_mb_emit_byte (mb, CEE_LDARG_1);
3995         mono_mb_emit_byte (mb, CEE_LDNULL);
3996         mono_mb_emit_byte (mb, CEE_STIND_REF);
3997
3998         emit_thread_force_interrupt_checkpoint (mb);
3999
4000         mono_mb_emit_byte (mb, CEE_LDARG_0);
4001         mono_mb_emit_byte (mb, CEE_LDARG_2);
4002         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
4003         mono_mb_emit_byte (mb, CEE_MONO_DYN_CALL);
4004
4005         pos = mono_mb_emit_branch (mb, CEE_LEAVE);
4006
4007         clause = mono_image_alloc0 (mono_defaults.corlib, sizeof (MonoExceptionClause));
4008         clause->flags = MONO_EXCEPTION_CLAUSE_FILTER;
4009         clause->try_len = mono_mb_get_label (mb);
4010
4011         /* filter code */
4012         clause->data.filter_offset = mono_mb_get_label (mb);
4013         
4014         mono_mb_emit_byte (mb, CEE_POP);
4015         mono_mb_emit_byte (mb, CEE_LDARG_1);
4016         mono_mb_emit_byte (mb, CEE_LDC_I4_0);
4017         mono_mb_emit_byte (mb, CEE_PREFIX1);
4018         mono_mb_emit_byte (mb, CEE_CGT_UN);
4019         mono_mb_emit_byte (mb, CEE_PREFIX1);
4020         mono_mb_emit_byte (mb, CEE_ENDFILTER);
4021
4022         clause->handler_offset = mono_mb_get_label (mb);
4023
4024         /* handler code */
4025         /* store exception */
4026         mono_mb_emit_stloc (mb, 1);
4027         
4028         mono_mb_emit_byte (mb, CEE_LDARG_1);
4029         mono_mb_emit_ldloc (mb, 1);
4030         mono_mb_emit_byte (mb, CEE_STIND_REF);
4031
4032         mono_mb_emit_byte (mb, CEE_LDNULL);
4033         mono_mb_emit_stloc (mb, 0);
4034
4035         /* Check for the abort exception */
4036         mono_mb_emit_ldloc (mb, 1);
4037         mono_mb_emit_op (mb, CEE_ISINST, mono_defaults.threadabortexception_class);
4038         posna = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
4039
4040         /* Delay the abort exception */
4041         mono_mb_emit_icall (mb, ves_icall_System_Threading_Thread_ResetAbort);
4042
4043         mono_mb_patch_short_branch (mb, posna);
4044         mono_mb_emit_branch (mb, CEE_LEAVE);
4045
4046         clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
4047
4048         mono_mb_set_clauses (mb, 1, clause);
4049
4050         /* return result */
4051         mono_mb_patch_branch (mb, pos);
4052         //mono_mb_emit_ldloc (mb, 0);
4053         mono_mb_emit_byte (mb, CEE_RET);
4054 #endif /* DISABLE_JIT */
4055
4056         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC);
4057
4058         mono_marshal_lock ();
4059         /* double-checked locking */
4060         if (!method)
4061                 method = mono_mb_create (mb, csig, 16, info);
4062
4063         mono_marshal_unlock ();
4064
4065         mono_mb_free (mb);
4066
4067         return method;
4068 }
4069
4070 #ifndef DISABLE_JIT
4071 static void
4072 mono_mb_emit_auto_layout_exception (MonoMethodBuilder *mb, MonoClass *klass)
4073 {
4074         char *msg = g_strdup_printf ("The type `%s.%s' layout needs to be Sequential or Explicit",
4075                                      klass->name_space, klass->name);
4076
4077         mono_mb_emit_exception_marshal_directive (mb, msg);
4078 }
4079 #endif
4080
4081 /*
4082  * generates IL code for the icall wrapper (the generated method
4083  * calls the unmanaged code in func)
4084  * The wrapper info for the wrapper is a WrapperInfo structure.
4085  */
4086 MonoMethod *
4087 mono_marshal_get_icall_wrapper (MonoMethodSignature *sig, const char *name, gconstpointer func, gboolean check_exceptions)
4088 {
4089         MonoMethodSignature *csig, *csig2;
4090         MonoMethodBuilder *mb;
4091         MonoMethod *res;
4092         int i;
4093         WrapperInfo *info;
4094         
4095         g_assert (sig->pinvoke);
4096
4097         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
4098
4099         mb->method->save_lmf = 1;
4100
4101         /* Add an explicit this argument */
4102         if (sig->hasthis)
4103                 csig2 = signature_dup_add_this (mono_defaults.corlib, sig, mono_defaults.object_class);
4104         else
4105                 csig2 = signature_dup (mono_defaults.corlib, sig);
4106
4107 #ifndef DISABLE_JIT
4108         if (sig->hasthis)
4109                 mono_mb_emit_byte (mb, CEE_LDARG_0);
4110
4111         for (i = 0; i < sig->param_count; i++)
4112                 mono_mb_emit_ldarg (mb, i + sig->hasthis);
4113
4114         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
4115         mono_mb_emit_op (mb, CEE_MONO_JIT_ICALL_ADDR, (gpointer)func);
4116         mono_mb_emit_calli (mb, csig2);
4117         if (check_exceptions)
4118                 emit_thread_interrupt_checkpoint (mb);
4119         mono_mb_emit_byte (mb, CEE_RET);
4120 #endif
4121
4122         csig = signature_dup (mono_defaults.corlib, sig);
4123         csig->pinvoke = 0;
4124         if (csig->call_convention == MONO_CALL_VARARG)
4125                 csig->call_convention = 0;
4126
4127         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ICALL_WRAPPER);
4128         info->d.icall.func = (gpointer)func;
4129         res = mono_mb_create (mb, csig, csig->param_count + 16, info);
4130         mono_mb_free (mb);
4131
4132         return res;
4133 }
4134
4135 static int
4136 emit_marshal_custom (EmitMarshalContext *m, int argnum, MonoType *t,
4137                                          MonoMarshalSpec *spec, 
4138                                          int conv_arg, MonoType **conv_arg_type, 
4139                                          MarshalAction action)
4140 {
4141 #ifdef DISABLE_JIT
4142         if (action == MARSHAL_ACTION_CONV_IN && t->type == MONO_TYPE_VALUETYPE)
4143                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
4144         return conv_arg;
4145 #else
4146         MonoType *mtype;
4147         MonoClass *mklass;
4148         static MonoClass *ICustomMarshaler = NULL;
4149         static MonoMethod *cleanup_native, *cleanup_managed;
4150         static MonoMethod *marshal_managed_to_native, *marshal_native_to_managed;
4151         MonoMethod *get_instance = NULL;
4152         MonoMethodBuilder *mb = m->mb;
4153         char *exception_msg = NULL;
4154         guint32 loc1;
4155         int pos2;
4156
4157         if (!ICustomMarshaler) {
4158                 MonoClass *klass = mono_class_from_name (mono_defaults.corlib, "System.Runtime.InteropServices", "ICustomMarshaler");
4159                 if (!klass) {
4160                         exception_msg = g_strdup ("Current profile doesn't support ICustomMarshaler");
4161                         goto handle_exception;
4162                 }
4163
4164                 cleanup_native = mono_class_get_method_from_name (klass, "CleanUpNativeData", 1);
4165                 g_assert (cleanup_native);
4166                 cleanup_managed = mono_class_get_method_from_name (klass, "CleanUpManagedData", 1);
4167                 g_assert (cleanup_managed);
4168                 marshal_managed_to_native = mono_class_get_method_from_name (klass, "MarshalManagedToNative", 1);
4169                 g_assert (marshal_managed_to_native);
4170                 marshal_native_to_managed = mono_class_get_method_from_name (klass, "MarshalNativeToManaged", 1);
4171                 g_assert (marshal_native_to_managed);
4172
4173                 mono_memory_barrier ();
4174                 ICustomMarshaler = klass;
4175         }
4176
4177         if (spec->data.custom_data.image)
4178                 mtype = mono_reflection_type_from_name (spec->data.custom_data.custom_name, spec->data.custom_data.image);
4179         else
4180                 mtype = mono_reflection_type_from_name (spec->data.custom_data.custom_name, m->image);
4181         g_assert (mtype != NULL);
4182         mklass = mono_class_from_mono_type (mtype);
4183         g_assert (mklass != NULL);
4184
4185         if (!mono_class_is_assignable_from (ICustomMarshaler, mklass))
4186                 exception_msg = g_strdup_printf ("Custom marshaler '%s' does not implement the ICustomMarshaler interface.", mklass->name);
4187
4188         get_instance = mono_class_get_method_from_name_flags (mklass, "GetInstance", 1, METHOD_ATTRIBUTE_STATIC);
4189         if (get_instance) {
4190                 MonoMethodSignature *get_sig = mono_method_signature (get_instance);
4191                 if ((get_sig->ret->type != MONO_TYPE_CLASS) ||
4192                         (mono_class_from_mono_type (get_sig->ret) != ICustomMarshaler) ||
4193                         (get_sig->params [0]->type != MONO_TYPE_STRING))
4194                         get_instance = NULL;
4195         }
4196
4197         if (!get_instance)
4198                 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);
4199
4200 handle_exception:
4201         /* Throw exception and emit compensation code if neccesary */
4202         if (exception_msg) {
4203                 switch (action) {
4204                 case MARSHAL_ACTION_CONV_IN:
4205                 case MARSHAL_ACTION_CONV_RESULT:
4206                 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
4207                         if ((action == MARSHAL_ACTION_CONV_RESULT) || (action == MARSHAL_ACTION_MANAGED_CONV_RESULT))
4208                                 mono_mb_emit_byte (mb, CEE_POP);
4209
4210                         mono_mb_emit_exception_full (mb, "System", "ApplicationException", exception_msg);
4211                         g_free (exception_msg);
4212
4213                         break;
4214                 case MARSHAL_ACTION_PUSH:
4215                         mono_mb_emit_byte (mb, CEE_LDNULL);
4216                         break;
4217                 default:
4218                         break;
4219                 }
4220                 return 0;
4221         }
4222
4223         /* FIXME: MS.NET seems to create one instance for each klass + cookie pair */
4224         /* FIXME: MS.NET throws an exception if GetInstance returns null */
4225
4226         switch (action) {
4227         case MARSHAL_ACTION_CONV_IN:
4228                 switch (t->type) {
4229                 case MONO_TYPE_CLASS:
4230                 case MONO_TYPE_OBJECT:
4231                 case MONO_TYPE_STRING:
4232                 case MONO_TYPE_ARRAY:
4233                 case MONO_TYPE_SZARRAY:
4234                 case MONO_TYPE_VALUETYPE:
4235                         break;
4236
4237                 default:
4238                         g_warning ("custom marshalling of type %x is currently not supported", t->type);
4239                         g_assert_not_reached ();
4240                         break;
4241                 }
4242
4243                 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
4244
4245                 mono_mb_emit_byte (mb, CEE_LDNULL);
4246                 mono_mb_emit_stloc (mb, conv_arg);
4247
4248                 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT))
4249                         break;
4250
4251                 /* Minic MS.NET behavior */
4252                 if (!t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT) && !(t->attrs & PARAM_ATTRIBUTE_IN))
4253                         break;
4254
4255                 /* Check for null */
4256                 mono_mb_emit_ldarg (mb, argnum);
4257                 if (t->byref)
4258                         mono_mb_emit_byte (mb, CEE_LDIND_I);
4259                 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4260
4261                 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4262
4263                 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4264                                 
4265                 mono_mb_emit_ldarg (mb, argnum);
4266                 if (t->byref)
4267                         mono_mb_emit_byte (mb, CEE_LDIND_REF);
4268
4269                 if (t->type == MONO_TYPE_VALUETYPE) {
4270                         /*
4271                          * Since we can't determine the type of the argument, we
4272                          * will assume the unmanaged function takes a pointer.
4273                          */
4274                         *conv_arg_type = &mono_defaults.int_class->byval_arg;
4275
4276                         mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (t));
4277                 }
4278
4279                 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_managed_to_native);
4280                 mono_mb_emit_stloc (mb, conv_arg);
4281
4282                 mono_mb_patch_branch (mb, pos2);
4283                 break;
4284
4285         case MARSHAL_ACTION_CONV_OUT:
4286                 /* Check for null */
4287                 mono_mb_emit_ldloc (mb, conv_arg);
4288                 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4289
4290                 if (t->byref) {
4291                         mono_mb_emit_ldarg (mb, argnum);
4292
4293                         mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4294
4295                         mono_mb_emit_op (mb, CEE_CALL, get_instance);
4296
4297                         mono_mb_emit_ldloc (mb, conv_arg);
4298                         mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
4299                         mono_mb_emit_byte (mb, CEE_STIND_REF);
4300                 } else if (t->attrs & PARAM_ATTRIBUTE_OUT) {
4301                         mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4302
4303                         mono_mb_emit_op (mb, CEE_CALL, get_instance);
4304
4305                         mono_mb_emit_ldloc (mb, conv_arg);
4306                         mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
4307
4308                         /* We have nowhere to store the result */
4309                         mono_mb_emit_byte (mb, CEE_POP);
4310                 }
4311
4312                 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4313
4314                 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4315
4316                 mono_mb_emit_ldloc (mb, conv_arg);
4317
4318                 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_native);
4319
4320                 mono_mb_patch_branch (mb, pos2);
4321                 break;
4322
4323         case MARSHAL_ACTION_PUSH:
4324                 if (t->byref)
4325                         mono_mb_emit_ldloc_addr (mb, conv_arg);
4326                 else
4327                         mono_mb_emit_ldloc (mb, conv_arg);
4328                 break;
4329
4330         case MARSHAL_ACTION_CONV_RESULT:
4331                 loc1 = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
4332                         
4333                 mono_mb_emit_stloc (mb, 3);
4334
4335                 mono_mb_emit_ldloc (mb, 3);
4336                 mono_mb_emit_stloc (mb, loc1);
4337
4338                 /* Check for null */
4339                 mono_mb_emit_ldloc (mb, 3);
4340                 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4341
4342                 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4343
4344                 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4345                 mono_mb_emit_byte (mb, CEE_DUP);
4346
4347                 mono_mb_emit_ldloc (mb, 3);
4348                 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
4349                 mono_mb_emit_stloc (mb, 3);
4350
4351                 mono_mb_emit_ldloc (mb, loc1);
4352                 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_native);
4353
4354                 mono_mb_patch_branch (mb, pos2);
4355                 break;
4356
4357         case MARSHAL_ACTION_MANAGED_CONV_IN:
4358                 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
4359
4360                 mono_mb_emit_byte (mb, CEE_LDNULL);
4361                 mono_mb_emit_stloc (mb, conv_arg);
4362
4363                 if (t->byref && t->attrs & PARAM_ATTRIBUTE_OUT)
4364                         break;
4365
4366                 /* Check for null */
4367                 mono_mb_emit_ldarg (mb, argnum);
4368                 if (t->byref)
4369                         mono_mb_emit_byte (mb, CEE_LDIND_I);
4370                 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4371
4372                 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4373                 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4374                                 
4375                 mono_mb_emit_ldarg (mb, argnum);
4376                 if (t->byref)
4377                         mono_mb_emit_byte (mb, CEE_LDIND_I);
4378                                 
4379                 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
4380                 mono_mb_emit_stloc (mb, conv_arg);
4381
4382                 mono_mb_patch_branch (mb, pos2);
4383                 break;
4384
4385         case MARSHAL_ACTION_MANAGED_CONV_RESULT:
4386                 g_assert (!t->byref);
4387
4388                 loc1 = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
4389                         
4390                 mono_mb_emit_stloc (mb, 3);
4391                         
4392                 mono_mb_emit_ldloc (mb, 3);
4393                 mono_mb_emit_stloc (mb, loc1);
4394
4395                 /* Check for null */
4396                 mono_mb_emit_ldloc (mb, 3);
4397                 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4398
4399                 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4400                 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4401                 mono_mb_emit_byte (mb, CEE_DUP);
4402
4403                 mono_mb_emit_ldloc (mb, 3);
4404                 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_managed_to_native);
4405                 mono_mb_emit_stloc (mb, 3);
4406
4407                 mono_mb_emit_ldloc (mb, loc1);
4408                 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_managed);
4409
4410                 mono_mb_patch_branch (mb, pos2);
4411                 break;
4412
4413         case MARSHAL_ACTION_MANAGED_CONV_OUT:
4414
4415                 /* Check for null */
4416                 mono_mb_emit_ldloc (mb, conv_arg);
4417                 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4418
4419                 if (t->byref) {
4420                         mono_mb_emit_ldarg (mb, argnum);
4421
4422                         mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4423
4424                         mono_mb_emit_op (mb, CEE_CALL, get_instance);
4425
4426                         mono_mb_emit_ldloc (mb, conv_arg);
4427                         mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_managed_to_native);
4428                         mono_mb_emit_byte (mb, CEE_STIND_I);
4429                 }
4430
4431                 /* Call CleanUpManagedData */
4432                 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4433
4434                 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4435                                 
4436                 mono_mb_emit_ldloc (mb, conv_arg);
4437                 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_managed);
4438
4439                 mono_mb_patch_branch (mb, pos2);
4440                 break;
4441
4442         default:
4443                 g_assert_not_reached ();
4444         }
4445         return conv_arg;
4446 #endif
4447
4448 }
4449
4450 static int
4451 emit_marshal_asany (EmitMarshalContext *m, int argnum, MonoType *t,
4452                                         MonoMarshalSpec *spec, 
4453                                         int conv_arg, MonoType **conv_arg_type, 
4454                                         MarshalAction action)
4455 {
4456 #ifndef DISABLE_JIT
4457         MonoMethodBuilder *mb = m->mb;
4458
4459         switch (action) {
4460         case MARSHAL_ACTION_CONV_IN: {
4461                 MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, NULL);
4462
4463                 g_assert (t->type == MONO_TYPE_OBJECT);
4464                 g_assert (!t->byref);
4465
4466                 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
4467                 mono_mb_emit_ldarg (mb, argnum);
4468                 mono_mb_emit_icon (mb, encoding);
4469                 mono_mb_emit_icon (mb, t->attrs);
4470                 mono_mb_emit_icall (mb, mono_marshal_asany);
4471                 mono_mb_emit_stloc (mb, conv_arg);
4472                 break;
4473         }
4474
4475         case MARSHAL_ACTION_PUSH:
4476                 mono_mb_emit_ldloc (mb, conv_arg);
4477                 break;
4478
4479         case MARSHAL_ACTION_CONV_OUT: {
4480                 MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, NULL);
4481
4482                 mono_mb_emit_ldarg (mb, argnum);
4483                 mono_mb_emit_ldloc (mb, conv_arg);
4484                 mono_mb_emit_icon (mb, encoding);
4485                 mono_mb_emit_icon (mb, t->attrs);
4486                 mono_mb_emit_icall (mb, mono_marshal_free_asany);
4487                 break;
4488         }
4489
4490         default:
4491                 g_assert_not_reached ();
4492         }
4493 #endif
4494         return conv_arg;
4495 }
4496
4497 static int
4498 emit_marshal_vtype (EmitMarshalContext *m, int argnum, MonoType *t,
4499                                         MonoMarshalSpec *spec, 
4500                                         int conv_arg, MonoType **conv_arg_type, 
4501                                         MarshalAction action)
4502 {
4503 #ifndef DISABLE_JIT
4504         MonoMethodBuilder *mb = m->mb;
4505         MonoClass *klass, *date_time_class;
4506         int pos = 0, pos2;
4507
4508         klass = mono_class_from_mono_type (t);
4509
4510         date_time_class = mono_class_from_name_cached (mono_defaults.corlib, "System", "DateTime");
4511
4512         switch (action) {
4513         case MARSHAL_ACTION_CONV_IN:
4514                 if (klass == date_time_class) {
4515                         /* Convert it to an OLE DATE type */
4516                         static MonoMethod *to_oadate;
4517
4518                         if (!to_oadate)
4519                                 to_oadate = mono_class_get_method_from_name (date_time_class, "ToOADate", 0);
4520                         g_assert (to_oadate);
4521
4522                         conv_arg = mono_mb_add_local (mb, &mono_defaults.double_class->byval_arg);
4523
4524                         if (t->byref) {
4525                                 mono_mb_emit_ldarg (mb, argnum);
4526                                 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
4527                         }
4528
4529                         if (!(t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && (t->attrs & PARAM_ATTRIBUTE_OUT))) {
4530                                 if (!t->byref)
4531                                         m->csig->params [argnum - m->csig->hasthis] = &mono_defaults.double_class->byval_arg;
4532
4533                                 mono_mb_emit_ldarg_addr (mb, argnum);
4534                                 mono_mb_emit_managed_call (mb, to_oadate, NULL);
4535                                 mono_mb_emit_stloc (mb, conv_arg);
4536                         }
4537
4538                         if (t->byref)
4539                                 mono_mb_patch_branch (mb, pos);
4540                         break;
4541                 }
4542
4543                 if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
4544                         klass->blittable || klass->enumtype)
4545                         break;
4546
4547                 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
4548                         
4549                 /* store the address of the source into local variable 0 */
4550                 if (t->byref)
4551                         mono_mb_emit_ldarg (mb, argnum);
4552                 else
4553                         mono_mb_emit_ldarg_addr (mb, argnum);
4554                 
4555                 mono_mb_emit_stloc (mb, 0);
4556                         
4557                 /* allocate space for the native struct and
4558                  * store the address into local variable 1 (dest) */
4559                 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
4560                 mono_mb_emit_byte (mb, CEE_PREFIX1);
4561                 mono_mb_emit_byte (mb, CEE_LOCALLOC);
4562                 mono_mb_emit_stloc (mb, conv_arg);
4563
4564                 if (t->byref) {
4565                         mono_mb_emit_ldloc (mb, 0);
4566                         pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
4567                 }
4568
4569                 if (!(t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && (t->attrs & PARAM_ATTRIBUTE_OUT))) {
4570                         /* set dst_ptr */
4571                         mono_mb_emit_ldloc (mb, conv_arg);
4572                         mono_mb_emit_stloc (mb, 1);
4573
4574                         /* emit valuetype conversion code */
4575                         emit_struct_conv (mb, klass, FALSE);
4576                 }
4577
4578                 if (t->byref)
4579                         mono_mb_patch_branch (mb, pos);
4580                 break;
4581
4582         case MARSHAL_ACTION_PUSH:
4583                 if (spec && spec->native == MONO_NATIVE_LPSTRUCT) {
4584                         /* FIXME: */
4585                         g_assert (!t->byref);
4586
4587                         /* Have to change the signature since the vtype is passed byref */
4588                         m->csig->params [argnum - m->csig->hasthis] = &mono_defaults.int_class->byval_arg;
4589
4590                         if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
4591                                 klass->blittable || klass->enumtype)
4592                                 mono_mb_emit_ldarg_addr (mb, argnum);
4593                         else
4594                                 mono_mb_emit_ldloc (mb, conv_arg);
4595                         break;
4596                 }
4597
4598                 if (klass == date_time_class) {
4599                         if (t->byref)
4600                                 mono_mb_emit_ldloc_addr (mb, conv_arg);
4601                         else
4602                                 mono_mb_emit_ldloc (mb, conv_arg);
4603                         break;
4604                 }
4605
4606                 if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
4607                         klass->blittable || klass->enumtype) {
4608                         mono_mb_emit_ldarg (mb, argnum);
4609                         break;
4610                 }                       
4611                 mono_mb_emit_ldloc (mb, conv_arg);
4612                 if (!t->byref) {
4613                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
4614                         mono_mb_emit_op (mb, CEE_MONO_LDNATIVEOBJ, klass);
4615                 }
4616                 break;
4617
4618         case MARSHAL_ACTION_CONV_OUT:
4619                 if (klass == date_time_class) {
4620                         /* Convert from an OLE DATE type */
4621                         static MonoMethod *from_oadate;
4622
4623                         if (!t->byref)
4624                                 break;
4625
4626                         if (!((t->attrs & PARAM_ATTRIBUTE_IN) && !(t->attrs & PARAM_ATTRIBUTE_OUT))) {
4627                                 if (!from_oadate)
4628                                         from_oadate = mono_class_get_method_from_name (date_time_class, "FromOADate", 1);
4629                                 g_assert (from_oadate);
4630
4631                                 mono_mb_emit_ldarg (mb, argnum);
4632                                 mono_mb_emit_ldloc (mb, conv_arg);
4633                                 mono_mb_emit_managed_call (mb, from_oadate, NULL);
4634                                 mono_mb_emit_op (mb, CEE_STOBJ, date_time_class);
4635                         }
4636                         break;
4637                 }
4638
4639                 if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
4640                         klass->blittable || klass->enumtype)
4641                         break;
4642
4643                 if (t->byref) {
4644                         /* dst = argument */
4645                         mono_mb_emit_ldarg (mb, argnum);
4646                         mono_mb_emit_stloc (mb, 1);
4647
4648                         mono_mb_emit_ldloc (mb, 1);
4649                         pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
4650
4651                         if (!((t->attrs & PARAM_ATTRIBUTE_IN) && !(t->attrs & PARAM_ATTRIBUTE_OUT))) {
4652                                 /* src = tmp_locals [i] */
4653                                 mono_mb_emit_ldloc (mb, conv_arg);
4654                                 mono_mb_emit_stloc (mb, 0);
4655
4656                                 /* emit valuetype conversion code */
4657                                 emit_struct_conv (mb, klass, TRUE);
4658                         }
4659                 }
4660
4661                 emit_struct_free (mb, klass, conv_arg);
4662                 
4663                 if (t->byref)
4664                         mono_mb_patch_branch (mb, pos);
4665                 break;
4666
4667         case MARSHAL_ACTION_CONV_RESULT:
4668                 if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
4669                         klass->blittable) {
4670                         mono_mb_emit_stloc (mb, 3);
4671                         break;
4672                 }
4673
4674                 /* load pointer to returned value type */
4675                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
4676                 mono_mb_emit_byte (mb, CEE_MONO_VTADDR);
4677                 /* store the address of the source into local variable 0 */
4678                 mono_mb_emit_stloc (mb, 0);
4679                 /* set dst_ptr */
4680                 mono_mb_emit_ldloc_addr (mb, 3);
4681                 mono_mb_emit_stloc (mb, 1);
4682                                 
4683                 /* emit valuetype conversion code */
4684                 emit_struct_conv (mb, klass, TRUE);
4685                 break;
4686
4687         case MARSHAL_ACTION_MANAGED_CONV_IN:
4688                 if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
4689                         klass->blittable || klass->enumtype) {
4690                         conv_arg = 0;
4691                         break;
4692                 }
4693
4694                 conv_arg = mono_mb_add_local (mb, &klass->byval_arg);
4695
4696                 if (t->attrs & PARAM_ATTRIBUTE_OUT)
4697                         break;
4698
4699                 if (t->byref) 
4700                         mono_mb_emit_ldarg (mb, argnum);
4701                 else
4702                         mono_mb_emit_ldarg_addr (mb, argnum);
4703                 mono_mb_emit_stloc (mb, 0);
4704
4705                 if (t->byref) {
4706                         mono_mb_emit_ldloc (mb, 0);
4707                         pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
4708                 }                       
4709
4710                 mono_mb_emit_ldloc_addr (mb, conv_arg);
4711                 mono_mb_emit_stloc (mb, 1);
4712
4713                 /* emit valuetype conversion code */
4714                 emit_struct_conv (mb, klass, TRUE);
4715
4716                 if (t->byref)
4717                         mono_mb_patch_branch (mb, pos);
4718                 break;
4719
4720         case MARSHAL_ACTION_MANAGED_CONV_OUT:
4721                 if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
4722                         klass->blittable || klass->enumtype) {
4723                         break;
4724                 }
4725
4726                 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_IN) && !(t->attrs & PARAM_ATTRIBUTE_OUT))
4727                         break;
4728
4729                 /* Check for null */
4730                 mono_mb_emit_ldarg (mb, argnum);
4731                 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4732
4733                 /* Set src */
4734                 mono_mb_emit_ldloc_addr (mb, conv_arg);
4735                 mono_mb_emit_stloc (mb, 0);
4736
4737                 /* Set dest */
4738                 mono_mb_emit_ldarg (mb, argnum);
4739                 mono_mb_emit_stloc (mb, 1);
4740
4741                 /* emit valuetype conversion code */
4742                 emit_struct_conv (mb, klass, FALSE);
4743
4744                 mono_mb_patch_branch (mb, pos2);
4745                 break;
4746
4747         case MARSHAL_ACTION_MANAGED_CONV_RESULT:
4748                 if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
4749                         klass->blittable || klass->enumtype) {
4750                         mono_mb_emit_stloc (mb, 3);
4751                         m->retobj_var = 0;
4752                         break;
4753                 }
4754                         
4755                 /* load pointer to returned value type */
4756                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
4757                 mono_mb_emit_byte (mb, CEE_MONO_VTADDR);
4758                         
4759                 /* store the address of the source into local variable 0 */
4760                 mono_mb_emit_stloc (mb, 0);
4761                 /* allocate space for the native struct and
4762                  * store the address into dst_ptr */
4763                 m->retobj_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
4764                 m->retobj_class = klass;
4765                 g_assert (m->retobj_var);
4766                 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
4767                 mono_mb_emit_byte (mb, CEE_CONV_I);
4768                 mono_mb_emit_icall (mb, mono_marshal_alloc);
4769                 mono_mb_emit_stloc (mb, 1);
4770                 mono_mb_emit_ldloc (mb, 1);
4771                 mono_mb_emit_stloc (mb, m->retobj_var);
4772
4773                 /* emit valuetype conversion code */
4774                 emit_struct_conv (mb, klass, FALSE);
4775                 break;
4776
4777         default:
4778                 g_assert_not_reached ();
4779         }
4780 #endif
4781         return conv_arg;
4782 }
4783
4784 static int
4785 emit_marshal_string (EmitMarshalContext *m, int argnum, MonoType *t,
4786                                          MonoMarshalSpec *spec, 
4787                                          int conv_arg, MonoType **conv_arg_type, 
4788                                          MarshalAction action)
4789 {
4790 #ifdef DISABLE_JIT
4791         switch (action) {
4792         case MARSHAL_ACTION_CONV_IN:
4793                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
4794                 break;
4795         case MARSHAL_ACTION_MANAGED_CONV_IN:
4796                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
4797                 break;
4798         }
4799 #else
4800         MonoMethodBuilder *mb = m->mb;
4801         MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
4802         MonoMarshalConv conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
4803         gboolean need_free;
4804
4805         switch (action) {
4806         case MARSHAL_ACTION_CONV_IN:
4807                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
4808                 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
4809
4810                 if (t->byref) {
4811                         if (t->attrs & PARAM_ATTRIBUTE_OUT)
4812                                 break;
4813
4814                         mono_mb_emit_ldarg (mb, argnum);
4815                         mono_mb_emit_byte (mb, CEE_LDIND_I);                            
4816                 } else {
4817                         mono_mb_emit_ldarg (mb, argnum);
4818                 }
4819
4820                 if (conv == -1) {
4821                         char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
4822                         mono_mb_emit_exception_marshal_directive (mb, msg);
4823                 } else {
4824                         mono_mb_emit_icall (mb, conv_to_icall (conv));
4825
4826                         mono_mb_emit_stloc (mb, conv_arg);
4827                 }
4828                 break;
4829
4830         case MARSHAL_ACTION_CONV_OUT:
4831                 conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
4832                 if (conv == -1) {
4833                         char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
4834                         mono_mb_emit_exception_marshal_directive (mb, msg);
4835                         break;
4836                 }
4837
4838                 if (encoding == MONO_NATIVE_VBBYREFSTR) {
4839                         static MonoMethod *m;
4840
4841                         if (!m) {
4842                                 m = mono_class_get_method_from_name_flags (mono_defaults.string_class, "get_Length", -1, 0);
4843                                 g_assert (m);
4844                         }
4845
4846                         if (!t->byref) {
4847                                 char *msg = g_strdup_printf ("VBByRefStr marshalling requires a ref parameter.", encoding);
4848                                 mono_mb_emit_exception_marshal_directive (mb, msg);
4849                                 break;
4850                         }
4851
4852                         /* 
4853                          * Have to allocate a new string with the same length as the original, and
4854                          * copy the contents of the buffer pointed to by CONV_ARG into it.
4855                          */
4856                         g_assert (t->byref);
4857                         mono_mb_emit_ldarg (mb, argnum);
4858                         mono_mb_emit_ldloc (mb, conv_arg);
4859                         mono_mb_emit_ldarg (mb, argnum);
4860                         mono_mb_emit_byte (mb, CEE_LDIND_I);                            
4861                         mono_mb_emit_managed_call (mb, m, NULL);
4862                         mono_mb_emit_icall (mb, mono_string_new_len_wrapper);
4863                         mono_mb_emit_byte (mb, CEE_STIND_REF);
4864                 } else if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT || !(t->attrs & PARAM_ATTRIBUTE_IN))) {
4865                         mono_mb_emit_ldarg (mb, argnum);
4866                         mono_mb_emit_ldloc (mb, conv_arg);
4867                         mono_mb_emit_icall (mb, conv_to_icall (conv));
4868                         mono_mb_emit_byte (mb, CEE_STIND_REF);
4869                         need_free = TRUE;
4870                 }
4871
4872                 if (need_free) {
4873                         mono_mb_emit_ldloc (mb, conv_arg);
4874                         if (conv == MONO_MARSHAL_CONV_BSTR_STR)
4875                                 mono_mb_emit_icall (mb, mono_free_bstr);
4876                         else
4877                                 mono_mb_emit_icall (mb, mono_marshal_free);
4878                 }
4879                 break;
4880
4881         case MARSHAL_ACTION_PUSH:
4882                 if (t->byref && encoding != MONO_NATIVE_VBBYREFSTR)
4883                         mono_mb_emit_ldloc_addr (mb, conv_arg);
4884                 else
4885                         mono_mb_emit_ldloc (mb, conv_arg);
4886                 break;
4887
4888         case MARSHAL_ACTION_CONV_RESULT:
4889                 mono_mb_emit_stloc (mb, 0);
4890                                 
4891                 conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
4892                 if (conv == -1) {
4893                         char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
4894                         mono_mb_emit_exception_marshal_directive (mb, msg);
4895                         break;
4896                 }
4897
4898                 mono_mb_emit_ldloc (mb, 0);
4899                 mono_mb_emit_icall (mb, conv_to_icall (conv));
4900                 mono_mb_emit_stloc (mb, 3);
4901
4902                 /* free the string */
4903                 mono_mb_emit_ldloc (mb, 0);
4904                 if (conv == MONO_MARSHAL_CONV_BSTR_STR)
4905                         mono_mb_emit_icall (mb, mono_free_bstr);
4906                 else
4907                         mono_mb_emit_icall (mb, mono_marshal_free);
4908                 break;
4909
4910         case MARSHAL_ACTION_MANAGED_CONV_IN:
4911                 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
4912
4913                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
4914
4915                 if (t->byref) {
4916                         if (t->attrs & PARAM_ATTRIBUTE_OUT)
4917                                 break;
4918                 }
4919
4920                 conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
4921                 if (conv == -1) {
4922                         char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
4923                         mono_mb_emit_exception_marshal_directive (mb, msg);
4924                         break;
4925                 }
4926
4927                 mono_mb_emit_ldarg (mb, argnum);
4928                 if (t->byref)
4929                         mono_mb_emit_byte (mb, CEE_LDIND_I);
4930                 mono_mb_emit_icall (mb, conv_to_icall (conv));
4931                 mono_mb_emit_stloc (mb, conv_arg);
4932                 break;
4933
4934         case MARSHAL_ACTION_MANAGED_CONV_OUT:
4935                 if (t->byref) {
4936                         if (conv_arg) {
4937                                 mono_mb_emit_ldarg (mb, argnum);
4938                                 mono_mb_emit_ldloc (mb, conv_arg);
4939                                 mono_mb_emit_icall (mb, conv_to_icall (conv));
4940                                 mono_mb_emit_byte (mb, CEE_STIND_I);
4941                         }
4942                 }
4943                 break;
4944
4945         case MARSHAL_ACTION_MANAGED_CONV_RESULT:
4946                 if (conv_to_icall (conv) == mono_marshal_string_to_utf16)
4947                         /* We need to make a copy so the caller is able to free it */
4948                         mono_mb_emit_icall (mb, mono_marshal_string_to_utf16_copy);
4949                 else
4950                         mono_mb_emit_icall (mb, conv_to_icall (conv));
4951                 mono_mb_emit_stloc (mb, 3);
4952                 break;
4953
4954         default:
4955                 g_assert_not_reached ();
4956         }
4957 #endif
4958         return conv_arg;
4959 }
4960
4961
4962 static int
4963 emit_marshal_safehandle (EmitMarshalContext *m, int argnum, MonoType *t, 
4964                          MonoMarshalSpec *spec, int conv_arg, 
4965                          MonoType **conv_arg_type, MarshalAction action)
4966 {
4967 #ifdef DISABLE_JIT
4968         if (action == MARSHAL_ACTION_CONV_IN)
4969                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
4970 #else
4971         MonoMethodBuilder *mb = m->mb;
4972
4973         switch (action){
4974         case MARSHAL_ACTION_CONV_IN: {
4975                 MonoType *intptr_type;
4976                 int dar_release_slot, pos;
4977
4978                 intptr_type = &mono_defaults.int_class->byval_arg;
4979                 conv_arg = mono_mb_add_local (mb, intptr_type);
4980                 *conv_arg_type = intptr_type;
4981
4982                 if (!sh_dangerous_add_ref)
4983                         init_safe_handle ();
4984
4985                 mono_mb_emit_ldarg (mb, argnum);
4986                 pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
4987                 mono_mb_emit_exception (mb, "ArgumentNullException", NULL);
4988                 
4989                 mono_mb_patch_branch (mb, pos);
4990                 if (t->byref){
4991                         /*
4992                          * My tests in show that ref SafeHandles are not really
4993                          * passed as ref objects.  Instead a NULL is passed as the
4994                          * value of the ref
4995                          */
4996                         mono_mb_emit_icon (mb, 0);
4997                         mono_mb_emit_stloc (mb, conv_arg);
4998                         break;
4999                 } 
5000
5001                 /* Create local to hold the ref parameter to DangerousAddRef */
5002                 dar_release_slot = mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
5003
5004                 /* set release = false; */
5005                 mono_mb_emit_icon (mb, 0);
5006                 mono_mb_emit_stloc (mb, dar_release_slot);
5007
5008                 /* safehandle.DangerousAddRef (ref release) */
5009                 mono_mb_emit_ldarg (mb, argnum);
5010                 mono_mb_emit_ldloc_addr (mb, dar_release_slot);
5011                 mono_mb_emit_managed_call (mb, sh_dangerous_add_ref, NULL);
5012
5013                 /* Pull the handle field from SafeHandle */
5014                 mono_mb_emit_ldarg (mb, argnum);
5015                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoSafeHandle, handle));
5016                 mono_mb_emit_byte (mb, CEE_LDIND_I);
5017                 mono_mb_emit_stloc (mb, conv_arg);
5018
5019                 break;
5020         }
5021
5022         case MARSHAL_ACTION_PUSH:
5023                 if (t->byref)
5024                         mono_mb_emit_ldloc_addr (mb, conv_arg);
5025                 else 
5026                         mono_mb_emit_ldloc (mb, conv_arg);
5027                 break;
5028
5029         case MARSHAL_ACTION_CONV_OUT: {
5030                 /* The slot for the boolean is the next temporary created after conv_arg, see the CONV_IN code */
5031                 int dar_release_slot = conv_arg + 1;
5032                 int label_next;
5033
5034                 if (!sh_dangerous_release)
5035                         init_safe_handle ();
5036
5037                 if (t->byref){
5038                         MonoMethod *ctor;
5039                         
5040                         /*
5041                          * My tests indicate that ref SafeHandles parameters are not actually
5042                          * passed by ref, but instead a new Handle is created regardless of
5043                          * whether a change happens in the unmanaged side.
5044                          *
5045                          * Also, the Handle is created before calling into unmanaged code,
5046                          * but we do not support that mechanism (getting to the original
5047                          * handle) and it makes no difference where we create this
5048                          */
5049                         ctor = mono_class_get_method_from_name (t->data.klass, ".ctor", 0);
5050                         if (ctor == NULL){
5051                                 mono_mb_emit_exception (mb, "MissingMethodException", "paramterless constructor required");
5052                                 break;
5053                         }
5054                         /* refval = new SafeHandleDerived ()*/
5055                         mono_mb_emit_ldarg (mb, argnum);
5056                         mono_mb_emit_op (mb, CEE_NEWOBJ, ctor);
5057                         mono_mb_emit_byte (mb, CEE_STIND_REF);
5058
5059                         /* refval.handle = returned_handle */
5060                         mono_mb_emit_ldarg (mb, argnum);
5061                         mono_mb_emit_byte (mb, CEE_LDIND_REF);
5062                         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoSafeHandle, handle));
5063                         mono_mb_emit_ldloc (mb, conv_arg);
5064                         mono_mb_emit_byte (mb, CEE_STIND_I);
5065                 } else {
5066                         mono_mb_emit_ldloc (mb, dar_release_slot);
5067                         label_next = mono_mb_emit_branch (mb, CEE_BRFALSE);
5068                         mono_mb_emit_ldarg (mb, argnum);
5069                         mono_mb_emit_managed_call (mb, sh_dangerous_release, NULL);
5070                         mono_mb_patch_branch (mb, label_next);
5071                 }
5072                 break;
5073         }
5074                 
5075         case MARSHAL_ACTION_CONV_RESULT: {
5076                 MonoMethod *ctor = NULL;
5077                 int intptr_handle_slot;
5078                 
5079                 if (t->data.klass->flags & TYPE_ATTRIBUTE_ABSTRACT){
5080                         mono_mb_emit_byte (mb, CEE_POP);
5081                         mono_mb_emit_exception_marshal_directive (mb, g_strdup ("Returned SafeHandles should not be abstract"));
5082                         break;
5083                 }
5084
5085                 ctor = mono_class_get_method_from_name (t->data.klass, ".ctor", 0);
5086                 if (ctor == NULL){
5087                         mono_mb_emit_byte (mb, CEE_POP);
5088                         mono_mb_emit_exception (mb, "MissingMethodException", "paramterless constructor required");
5089                         break;
5090                 }
5091                 /* Store the IntPtr results into a local */
5092                 intptr_handle_slot = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5093                 mono_mb_emit_stloc (mb, intptr_handle_slot);
5094
5095                 /* Create return value */
5096                 mono_mb_emit_op (mb, CEE_NEWOBJ, ctor);
5097                 mono_mb_emit_stloc (mb, 3);
5098
5099                 /* Set the return.handle to the value, am using ldflda, not sure if thats a good idea */
5100                 mono_mb_emit_ldloc (mb, 3);
5101                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoSafeHandle, handle));
5102                 mono_mb_emit_ldloc (mb, intptr_handle_slot);
5103                 mono_mb_emit_byte (mb, CEE_STIND_I);
5104                 break;
5105         }
5106                 
5107         case MARSHAL_ACTION_MANAGED_CONV_IN:
5108                 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_IN\n");
5109                 break;
5110                 
5111         case MARSHAL_ACTION_MANAGED_CONV_OUT:
5112                 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_OUT\n");
5113                 break;
5114
5115         case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5116                 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_RESULT\n");
5117                 break;
5118         default:
5119                 printf ("Unhandled case for MarshalAction: %d\n", action);
5120         }
5121 #endif
5122         return conv_arg;
5123 }
5124
5125
5126 static int
5127 emit_marshal_handleref (EmitMarshalContext *m, int argnum, MonoType *t, 
5128                         MonoMarshalSpec *spec, int conv_arg, 
5129                         MonoType **conv_arg_type, MarshalAction action)
5130 {
5131 #ifdef DISABLE_JIT
5132         if (action == MARSHAL_ACTION_CONV_IN)
5133                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5134 #else
5135         MonoMethodBuilder *mb = m->mb;
5136
5137         switch (action){
5138         case MARSHAL_ACTION_CONV_IN: {
5139                 MonoType *intptr_type;
5140
5141                 intptr_type = &mono_defaults.int_class->byval_arg;
5142                 conv_arg = mono_mb_add_local (mb, intptr_type);
5143                 *conv_arg_type = intptr_type;
5144
5145                 if (t->byref){
5146                         char *msg = g_strdup ("HandleRefs can not be returned from unmanaged code (or passed by ref)");
5147                         mono_mb_emit_exception_marshal_directive (mb, msg);
5148                         break;
5149                 } 
5150                 mono_mb_emit_ldarg_addr (mb, argnum);
5151                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoHandleRef, handle));
5152                 mono_mb_emit_byte (mb, CEE_ADD);
5153                 mono_mb_emit_byte (mb, CEE_LDIND_I);
5154                 mono_mb_emit_stloc (mb, conv_arg);
5155                 break;
5156         }
5157
5158         case MARSHAL_ACTION_PUSH:
5159                 mono_mb_emit_ldloc (mb, conv_arg);
5160                 break;
5161
5162         case MARSHAL_ACTION_CONV_OUT: {
5163                 /* no resource release required */
5164                 break;
5165         }
5166                 
5167         case MARSHAL_ACTION_CONV_RESULT: {
5168                 char *msg = g_strdup ("HandleRefs can not be returned from unmanaged code (or passed by ref)");
5169                 mono_mb_emit_exception_marshal_directive (mb, msg);
5170                 break;
5171         }
5172                 
5173         case MARSHAL_ACTION_MANAGED_CONV_IN:
5174                 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_IN\n");
5175                 break;
5176                 
5177         case MARSHAL_ACTION_MANAGED_CONV_OUT:
5178                 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_OUT\n");
5179                 break;
5180
5181         case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5182                 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_RESULT\n");
5183                 break;
5184         default:
5185                 fprintf (stderr, "Unhandled case for MarshalAction: %d\n", action);
5186         }
5187 #endif
5188         return conv_arg;
5189 }
5190
5191
5192 static int
5193 emit_marshal_object (EmitMarshalContext *m, int argnum, MonoType *t,
5194                      MonoMarshalSpec *spec, 
5195                      int conv_arg, MonoType **conv_arg_type, 
5196                      MarshalAction action)
5197 {
5198 #ifdef DISABLE_JIT
5199         if (action == MARSHAL_ACTION_CONV_IN)
5200                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5201 #else
5202         MonoMethodBuilder *mb = m->mb;
5203         MonoClass *klass = mono_class_from_mono_type (t);
5204         int pos, pos2, loc;
5205
5206         switch (action) {
5207         case MARSHAL_ACTION_CONV_IN:
5208                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5209                 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5210
5211                 m->orig_conv_args [argnum] = 0;
5212
5213                 if (mono_class_from_mono_type (t) == mono_defaults.object_class) {
5214                         char *msg = g_strdup_printf ("Marshalling of type object is not implemented");
5215                         mono_mb_emit_exception_marshal_directive (mb, msg);
5216                         break;
5217                 }
5218
5219                 if (klass->delegate) {
5220                         if (t->byref) {
5221                                 if (!(t->attrs & PARAM_ATTRIBUTE_OUT)) {
5222                                         char *msg = g_strdup_printf ("Byref marshalling of delegates is not implemented.");
5223                                         mono_mb_emit_exception_marshal_directive (mb, msg);
5224                                 }
5225                                 mono_mb_emit_byte (mb, CEE_LDNULL);
5226                                 mono_mb_emit_stloc (mb, conv_arg);
5227                         } else {
5228                                 mono_mb_emit_ldarg (mb, argnum);
5229                                 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_DEL_FTN));
5230                                 mono_mb_emit_stloc (mb, conv_arg);
5231                         }
5232                 } else if (klass == mono_defaults.stringbuilder_class) {
5233                         MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
5234                         MonoMarshalConv conv = mono_marshal_get_stringbuilder_to_ptr_conv (m->piinfo, spec);
5235
5236 #if 0                   
5237                         if (t->byref) {
5238                                 if (!(t->attrs & PARAM_ATTRIBUTE_OUT)) {
5239                                         char *msg = g_strdup_printf ("Byref marshalling of stringbuilders is not implemented.");
5240                                         mono_mb_emit_exception_marshal_directive (mb, msg);
5241                                 }
5242                                 break;
5243                         }
5244 #endif
5245
5246                         if (t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && (t->attrs & PARAM_ATTRIBUTE_OUT))
5247                                 break;
5248
5249                         if (conv == -1) {
5250                                 char *msg = g_strdup_printf ("stringbuilder marshalling conversion %d not implemented", encoding);
5251                                 mono_mb_emit_exception_marshal_directive (mb, msg);
5252                                 break;
5253                         }
5254
5255                         mono_mb_emit_ldarg (mb, argnum);
5256                         if (t->byref)
5257                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
5258
5259                         mono_mb_emit_icall (mb, conv_to_icall (conv));
5260                         mono_mb_emit_stloc (mb, conv_arg);
5261                 } else if (klass->blittable) {
5262                         mono_mb_emit_byte (mb, CEE_LDNULL);
5263                         mono_mb_emit_stloc (mb, conv_arg);
5264
5265                         mono_mb_emit_ldarg (mb, argnum);
5266                         pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5267
5268                         mono_mb_emit_ldarg (mb, argnum);
5269                         mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5270                         mono_mb_emit_stloc (mb, conv_arg);
5271
5272                         mono_mb_patch_branch (mb, pos);
5273                         break;
5274                 } else {
5275                         mono_mb_emit_byte (mb, CEE_LDNULL);
5276                         mono_mb_emit_stloc (mb, conv_arg);
5277
5278                         if (t->byref) {
5279                                 /* we dont need any conversions for out parameters */
5280                                 if (t->attrs & PARAM_ATTRIBUTE_OUT)
5281                                         break;
5282
5283                                 mono_mb_emit_ldarg (mb, argnum);                                
5284                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
5285
5286                         } else {
5287                                 mono_mb_emit_ldarg (mb, argnum);
5288                                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5289                                 mono_mb_emit_byte (mb, CEE_MONO_OBJADDR);
5290                         }
5291                                 
5292                         /* store the address of the source into local variable 0 */
5293                         mono_mb_emit_stloc (mb, 0);
5294                         mono_mb_emit_ldloc (mb, 0);
5295                         pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5296
5297                         /* allocate space for the native struct and store the address */
5298                         mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
5299                         mono_mb_emit_byte (mb, CEE_PREFIX1);
5300                         mono_mb_emit_byte (mb, CEE_LOCALLOC);
5301                         mono_mb_emit_stloc (mb, conv_arg);
5302
5303                         if (t->byref) {
5304                                 /* Need to store the original buffer so we can free it later */
5305                                 m->orig_conv_args [argnum] = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5306                                 mono_mb_emit_ldloc (mb, conv_arg);
5307                                 mono_mb_emit_stloc (mb, m->orig_conv_args [argnum]);
5308                         }
5309
5310                         /* set the src_ptr */
5311                         mono_mb_emit_ldloc (mb, 0);
5312                         mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5313                         mono_mb_emit_stloc (mb, 0);
5314
5315                         /* set dst_ptr */
5316                         mono_mb_emit_ldloc (mb, conv_arg);
5317                         mono_mb_emit_stloc (mb, 1);
5318
5319                         /* emit valuetype conversion code */
5320                         emit_struct_conv (mb, klass, FALSE);
5321
5322                         mono_mb_patch_branch (mb, pos);
5323                 }
5324                 break;
5325
5326         case MARSHAL_ACTION_CONV_OUT:
5327                 if (klass == mono_defaults.stringbuilder_class) {
5328                         gboolean need_free;
5329                         MonoMarshalNative encoding;
5330                         MonoMarshalConv conv;
5331
5332                         encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
5333                         conv = mono_marshal_get_ptr_to_stringbuilder_conv (m->piinfo, spec, &need_free);
5334
5335                         g_assert (encoding != -1);
5336
5337                         if (t->byref) {
5338                                 //g_assert (!(t->attrs & PARAM_ATTRIBUTE_OUT));
5339
5340                                 need_free = TRUE;
5341
5342                                 mono_mb_emit_ldarg (mb, argnum);
5343                                 mono_mb_emit_ldloc (mb, conv_arg);
5344
5345                                 switch (encoding) {
5346                                 case MONO_NATIVE_LPWSTR:
5347                                         mono_mb_emit_icall (mb, mono_string_utf16_to_builder2);
5348                                         break;
5349                                 case MONO_NATIVE_LPSTR:
5350                                         mono_mb_emit_icall (mb, mono_string_utf8_to_builder2);
5351                                         break;
5352                                 default:
5353                                         g_assert_not_reached ();
5354                                 }
5355
5356                                 mono_mb_emit_byte (mb, CEE_STIND_REF);
5357                         } else {
5358                                 mono_mb_emit_ldarg (mb, argnum);
5359                                 mono_mb_emit_ldloc (mb, conv_arg);
5360
5361                                 mono_mb_emit_icall (mb, conv_to_icall (conv));
5362                         }
5363
5364                         if (need_free) {
5365                                 mono_mb_emit_ldloc (mb, conv_arg);
5366                                 mono_mb_emit_icall (mb, mono_marshal_free);
5367                         }
5368                         break;
5369                 }
5370
5371                 if (klass->delegate) {
5372                         if (t->byref) {
5373                                 mono_mb_emit_ldarg (mb, argnum);
5374                                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5375                                 mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
5376                                 mono_mb_emit_ldloc (mb, conv_arg);
5377                                 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL));
5378                                 mono_mb_emit_byte (mb, CEE_STIND_REF);
5379                         }
5380                         break;
5381                 }
5382
5383                 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT)) {
5384                         /* allocate a new object */
5385                         mono_mb_emit_ldarg (mb, argnum);
5386                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5387                         mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, klass);
5388                         mono_mb_emit_byte (mb, CEE_STIND_REF);
5389                 }
5390
5391                 /* dst = *argument */
5392                 mono_mb_emit_ldarg (mb, argnum);
5393
5394                 if (t->byref)
5395                         mono_mb_emit_byte (mb, CEE_LDIND_I);
5396
5397                 mono_mb_emit_stloc (mb, 1);
5398
5399                 mono_mb_emit_ldloc (mb, 1);
5400                 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5401
5402                 if (t->byref || (t->attrs & PARAM_ATTRIBUTE_OUT)) {
5403                         mono_mb_emit_ldloc (mb, 1);
5404                         mono_mb_emit_icon (mb, sizeof (MonoObject));
5405                         mono_mb_emit_byte (mb, CEE_ADD);
5406                         mono_mb_emit_stloc (mb, 1);
5407                         
5408                         /* src = tmp_locals [i] */
5409                         mono_mb_emit_ldloc (mb, conv_arg);
5410                         mono_mb_emit_stloc (mb, 0);
5411
5412                         /* emit valuetype conversion code */
5413                         emit_struct_conv (mb, klass, TRUE);
5414
5415                         /* Free the structure returned by the native code */
5416                         emit_struct_free (mb, klass, conv_arg);
5417
5418                         if (m->orig_conv_args [argnum]) {
5419                                 /* 
5420                                  * If the native function changed the pointer, then free
5421                                  * the original structure plus the new pointer.
5422                                  */
5423                                 mono_mb_emit_ldloc (mb, m->orig_conv_args [argnum]);
5424                                 mono_mb_emit_ldloc (mb, conv_arg);
5425                                 pos2 = mono_mb_emit_branch (mb, CEE_BEQ);
5426
5427                                 if (!(t->attrs & PARAM_ATTRIBUTE_OUT)) {
5428                                         g_assert (m->orig_conv_args [argnum]);
5429
5430                                         emit_struct_free (mb, klass, m->orig_conv_args [argnum]);
5431                                 }
5432
5433                                 mono_mb_emit_ldloc (mb, conv_arg);
5434                                 mono_mb_emit_icall (mb, mono_marshal_free);
5435
5436                                 mono_mb_patch_branch (mb, pos2);
5437                         }
5438                 }
5439                 else
5440                         /* Free the original structure passed to native code */
5441                         emit_struct_free (mb, klass, conv_arg);
5442
5443                 mono_mb_patch_branch (mb, pos);
5444                 break;
5445
5446         case MARSHAL_ACTION_PUSH:
5447                 if (t->byref)
5448                         mono_mb_emit_ldloc_addr (mb, conv_arg);
5449                 else
5450                         mono_mb_emit_ldloc (mb, conv_arg);
5451                 break;
5452
5453         case MARSHAL_ACTION_CONV_RESULT:
5454                 if (klass->delegate) {
5455                         g_assert (!t->byref);
5456                         mono_mb_emit_stloc (mb, 0);
5457                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5458                         mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
5459                         mono_mb_emit_ldloc (mb, 0);
5460                         mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL));
5461                         mono_mb_emit_stloc (mb, 3);
5462                 } else {
5463                         /* set src */
5464                         mono_mb_emit_stloc (mb, 0);
5465         
5466                         /* Make a copy since emit_conv modifies local 0 */
5467                         loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5468                         mono_mb_emit_ldloc (mb, 0);
5469                         mono_mb_emit_stloc (mb, loc);
5470         
5471                         mono_mb_emit_byte (mb, CEE_LDNULL);
5472                         mono_mb_emit_stloc (mb, 3);
5473         
5474                         mono_mb_emit_ldloc (mb, 0);
5475                         pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5476         
5477                         /* allocate result object */
5478         
5479                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5480                         mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, klass);   
5481                         mono_mb_emit_stloc (mb, 3);
5482                                         
5483                         /* set dst  */
5484         
5485                         mono_mb_emit_ldloc (mb, 3);
5486                         mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5487                         mono_mb_emit_stloc (mb, 1);
5488                                                                 
5489                         /* emit conversion code */
5490                         emit_struct_conv (mb, klass, TRUE);
5491         
5492                         emit_struct_free (mb, klass, loc);
5493         
5494                         /* Free the pointer allocated by unmanaged code */
5495                         mono_mb_emit_ldloc (mb, loc);
5496                         mono_mb_emit_icall (mb, mono_marshal_free);
5497                         mono_mb_patch_branch (mb, pos);
5498                 }
5499                 break;
5500
5501         case MARSHAL_ACTION_MANAGED_CONV_IN:
5502                 conv_arg = mono_mb_add_local (mb, &klass->byval_arg);
5503
5504                 if (klass->delegate) {
5505                         g_assert (!t->byref);
5506                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5507                         mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
5508                         mono_mb_emit_ldarg (mb, argnum);
5509                         mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL));
5510                         mono_mb_emit_stloc (mb, conv_arg);
5511                         break;
5512                 }
5513
5514                 if (klass == mono_defaults.stringbuilder_class) {
5515                         MonoMarshalNative encoding;
5516
5517                         encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
5518
5519                         // FIXME:
5520                         g_assert (encoding == MONO_NATIVE_LPSTR);
5521
5522                         g_assert (!t->byref);
5523                         g_assert (encoding != -1);
5524
5525                         mono_mb_emit_ldarg (mb, argnum);
5526                         mono_mb_emit_icall (mb, mono_string_utf8_to_builder2);
5527                         mono_mb_emit_stloc (mb, conv_arg);
5528                         break;
5529                 }
5530
5531                 /* The class can not have an automatic layout */
5532                 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
5533                         mono_mb_emit_auto_layout_exception (mb, klass);
5534                         break;
5535                 }
5536
5537                 if (t->attrs & PARAM_ATTRIBUTE_OUT) {
5538                         mono_mb_emit_byte (mb, CEE_LDNULL);
5539                         mono_mb_emit_stloc (mb, conv_arg);
5540                         break;
5541                 }
5542
5543                 /* Set src */
5544                 mono_mb_emit_ldarg (mb, argnum);
5545                 if (t->byref) {
5546                         int pos2;
5547
5548                         /* Check for NULL and raise an exception */
5549                         pos2 = mono_mb_emit_branch (mb, CEE_BRTRUE);
5550
5551                         mono_mb_emit_exception (mb, "ArgumentNullException", NULL);
5552
5553                         mono_mb_patch_branch (mb, pos2);
5554                         mono_mb_emit_ldarg (mb, argnum);
5555                         mono_mb_emit_byte (mb, CEE_LDIND_I);
5556                 }                               
5557
5558                 mono_mb_emit_stloc (mb, 0);
5559
5560                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
5561                 mono_mb_emit_stloc (mb, conv_arg);
5562
5563                 mono_mb_emit_ldloc (mb, 0);
5564                 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5565
5566                 /* Create and set dst */
5567                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5568                 mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, klass);   
5569                 mono_mb_emit_stloc (mb, conv_arg);
5570                 mono_mb_emit_ldloc (mb, conv_arg);
5571                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5572                 mono_mb_emit_stloc (mb, 1); 
5573
5574                 /* emit valuetype conversion code */
5575                 emit_struct_conv (mb, klass, TRUE);
5576
5577                 mono_mb_patch_branch (mb, pos);
5578                 break;
5579
5580         case MARSHAL_ACTION_MANAGED_CONV_OUT:
5581                 if (t->byref) {
5582                         /* Check for null */
5583                         mono_mb_emit_ldloc (mb, conv_arg);
5584                         pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
5585                         mono_mb_emit_ldarg (mb, argnum);
5586                         mono_mb_emit_byte (mb, CEE_LDC_I4_0);
5587                         mono_mb_emit_byte (mb, CEE_STIND_REF);
5588                         pos2 = mono_mb_emit_branch (mb, CEE_BR);
5589
5590                         mono_mb_patch_branch (mb, pos);                 
5591                         
5592                         /* Set src */
5593                         mono_mb_emit_ldloc (mb, conv_arg);
5594                         mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5595                         mono_mb_emit_stloc (mb, 0);
5596
5597                         /* Allocate and set dest */
5598                         mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
5599                         mono_mb_emit_byte (mb, CEE_CONV_I);
5600                         mono_mb_emit_icall (mb, mono_marshal_alloc);
5601                         mono_mb_emit_stloc (mb, 1);
5602                         
5603                         /* Update argument pointer */
5604                         mono_mb_emit_ldarg (mb, argnum);
5605                         mono_mb_emit_ldloc (mb, 1);
5606                         mono_mb_emit_byte (mb, CEE_STIND_I);
5607                 
5608                         /* emit valuetype conversion code */
5609                         emit_struct_conv (mb, klass, FALSE);
5610
5611                         mono_mb_patch_branch (mb, pos2);
5612                 } else {
5613                         /* byval [Out] marshalling */
5614
5615                         /* FIXME: Handle null */
5616
5617                         /* Set src */
5618                         mono_mb_emit_ldloc (mb, conv_arg);
5619                         mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5620                         mono_mb_emit_stloc (mb, 0);
5621
5622                         /* Set dest */
5623                         mono_mb_emit_ldarg (mb, argnum);
5624                         mono_mb_emit_stloc (mb, 1);
5625                         
5626                         /* emit valuetype conversion code */
5627                         emit_struct_conv (mb, klass, FALSE);
5628                 }                       
5629                 break;
5630
5631         case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5632                 if (klass->delegate) {
5633                         mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_DEL_FTN));
5634                         mono_mb_emit_stloc (mb, 3);
5635                         break;
5636                 }
5637
5638                 /* The class can not have an automatic layout */
5639                 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
5640                         mono_mb_emit_auto_layout_exception (mb, klass);
5641                         break;
5642                 }
5643
5644                 mono_mb_emit_stloc (mb, 0);
5645                 /* Check for null */
5646                 mono_mb_emit_ldloc (mb, 0);
5647                 pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
5648                 mono_mb_emit_byte (mb, CEE_LDNULL);
5649                 mono_mb_emit_stloc (mb, 3);
5650                 pos2 = mono_mb_emit_branch (mb, CEE_BR);
5651
5652                 mono_mb_patch_branch (mb, pos);
5653
5654                 /* Set src */
5655                 mono_mb_emit_ldloc (mb, 0);
5656                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5657                 mono_mb_emit_stloc (mb, 0);
5658
5659                 /* Allocate and set dest */
5660                 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
5661                 mono_mb_emit_byte (mb, CEE_CONV_I);
5662                 mono_mb_emit_icall (mb, mono_marshal_alloc);
5663                 mono_mb_emit_byte (mb, CEE_DUP);
5664                 mono_mb_emit_stloc (mb, 1);
5665                 mono_mb_emit_stloc (mb, 3);
5666
5667                 emit_struct_conv (mb, klass, FALSE);
5668
5669                 mono_mb_patch_branch (mb, pos2);
5670                 break;
5671
5672         default:
5673                 g_assert_not_reached ();
5674         }
5675 #endif
5676         return conv_arg;
5677 }
5678
5679 #ifndef DISABLE_JIT
5680
5681 #ifndef DISABLE_COM
5682
5683 static int
5684 emit_marshal_variant (EmitMarshalContext *m, int argnum, MonoType *t,
5685                      MonoMarshalSpec *spec, 
5686                      int conv_arg, MonoType **conv_arg_type, 
5687                      MarshalAction action)
5688 {
5689         MonoMethodBuilder *mb = m->mb;
5690         static MonoMethod *get_object_for_native_variant = NULL;
5691         static MonoMethod *get_native_variant_for_object = NULL;
5692
5693         if (!get_object_for_native_variant)
5694                 get_object_for_native_variant = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetObjectForNativeVariant", 1);
5695         g_assert (get_object_for_native_variant);
5696
5697         if (!get_native_variant_for_object)
5698                 get_native_variant_for_object = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetNativeVariantForObject", 2);
5699         g_assert (get_native_variant_for_object);
5700
5701         switch (action) {
5702         case MARSHAL_ACTION_CONV_IN: {
5703                 conv_arg = mono_mb_add_local (mb, &mono_class_get_variant_class ()->byval_arg);
5704                 
5705                 if (t->byref)
5706                         *conv_arg_type = &mono_class_get_variant_class ()->this_arg;
5707                 else
5708                         *conv_arg_type = &mono_class_get_variant_class ()->byval_arg;
5709
5710                 if (t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && t->attrs & PARAM_ATTRIBUTE_OUT)
5711                         break;
5712
5713                 mono_mb_emit_ldarg (mb, argnum);
5714                 if (t->byref)
5715                         mono_mb_emit_byte(mb, CEE_LDIND_REF);
5716                 mono_mb_emit_ldloc_addr (mb, conv_arg);
5717                 mono_mb_emit_managed_call (mb, get_native_variant_for_object, NULL);
5718                 break;
5719         }
5720
5721         case MARSHAL_ACTION_CONV_OUT: {
5722                 static MonoMethod *variant_clear = NULL;
5723
5724                 if (!variant_clear)
5725                         variant_clear = mono_class_get_method_from_name (mono_class_get_variant_class (), "Clear", 0);
5726                 g_assert (variant_clear);
5727
5728
5729                 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT || !(t->attrs & PARAM_ATTRIBUTE_IN))) {
5730                         mono_mb_emit_ldarg (mb, argnum);
5731                         mono_mb_emit_ldloc_addr (mb, conv_arg);
5732                         mono_mb_emit_managed_call (mb, get_object_for_native_variant, NULL);
5733                         mono_mb_emit_byte (mb, CEE_STIND_REF);
5734                 }
5735
5736                 mono_mb_emit_ldloc_addr (mb, conv_arg);
5737                 mono_mb_emit_managed_call (mb, variant_clear, NULL);
5738                 break;
5739         }
5740
5741         case MARSHAL_ACTION_PUSH:
5742                 if (t->byref)
5743                         mono_mb_emit_ldloc_addr (mb, conv_arg);
5744                 else
5745                         mono_mb_emit_ldloc (mb, conv_arg);
5746                 break;
5747
5748         case MARSHAL_ACTION_CONV_RESULT: {
5749                 char *msg = g_strdup ("Marshalling of VARIANT not supported as a return type.");
5750                 mono_mb_emit_exception_marshal_directive (mb, msg);
5751                 break;
5752         }
5753
5754         case MARSHAL_ACTION_MANAGED_CONV_IN: {
5755                 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
5756
5757                 if (t->byref)
5758                         *conv_arg_type = &mono_class_get_variant_class ()->this_arg;
5759                 else
5760                         *conv_arg_type = &mono_class_get_variant_class ()->byval_arg;
5761
5762                 if (t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && t->attrs & PARAM_ATTRIBUTE_OUT)
5763                         break;
5764
5765                 if (t->byref)
5766                         mono_mb_emit_ldarg (mb, argnum);
5767                 else
5768                         mono_mb_emit_ldarg_addr (mb, argnum);
5769                 mono_mb_emit_managed_call (mb, get_object_for_native_variant, NULL);
5770                 mono_mb_emit_stloc (mb, conv_arg);
5771                 break;
5772         }
5773
5774         case MARSHAL_ACTION_MANAGED_CONV_OUT: {
5775                 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT || !(t->attrs & PARAM_ATTRIBUTE_IN))) {
5776                         mono_mb_emit_ldloc (mb, conv_arg);
5777                         mono_mb_emit_ldarg (mb, argnum);
5778                         mono_mb_emit_managed_call (mb, get_native_variant_for_object, NULL);
5779                 }
5780                 break;
5781         }
5782
5783         case MARSHAL_ACTION_MANAGED_CONV_RESULT: {
5784                 char *msg = g_strdup ("Marshalling of VARIANT not supported as a return type.");
5785                 mono_mb_emit_exception_marshal_directive (mb, msg);
5786                 break;
5787         }
5788
5789         default:
5790                 g_assert_not_reached ();
5791         }
5792
5793         return conv_arg;
5794 }
5795
5796 #endif /* DISABLE_COM */
5797 #endif /* DISABLE_JIT */
5798
5799 static gboolean
5800 mono_pinvoke_is_unicode (MonoMethodPInvoke *piinfo)
5801 {
5802         switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
5803         case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
5804                 return FALSE;
5805         case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
5806                 return TRUE;
5807         case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
5808         default:
5809 #ifdef TARGET_WIN32
5810                 return TRUE;
5811 #else
5812                 return FALSE;
5813 #endif
5814         }
5815 }
5816
5817
5818 static int
5819 emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
5820                                         MonoMarshalSpec *spec, 
5821                                         int conv_arg, MonoType **conv_arg_type, 
5822                                         MarshalAction action)
5823 {
5824 #ifdef DISABLE_JIT
5825         switch (action) {
5826         case MARSHAL_ACTION_CONV_IN:
5827                 *conv_arg_type = &mono_defaults.object_class->byval_arg;
5828                 break;
5829         case MARSHAL_ACTION_MANAGED_CONV_IN:
5830                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5831                 break;
5832         }
5833 #else
5834         MonoMethodBuilder *mb = m->mb;
5835         MonoClass *klass = mono_class_from_mono_type (t);
5836         gboolean need_convert, need_free;
5837         MonoMarshalNative encoding;
5838
5839         encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
5840
5841         switch (action) {
5842         case MARSHAL_ACTION_CONV_IN:
5843                 *conv_arg_type = &mono_defaults.object_class->byval_arg;
5844                 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
5845
5846                 if (klass->element_class->blittable) {
5847                         mono_mb_emit_ldarg (mb, argnum);
5848                         if (t->byref)
5849                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
5850                         mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_ARRAY_LPARRAY));
5851                         mono_mb_emit_stloc (mb, conv_arg);
5852                 } else {
5853                         MonoClass *eklass;
5854                         guint32 label1, label2, label3;
5855                         int index_var, src_var, dest_ptr, esize;
5856                         MonoMarshalConv conv;
5857                         gboolean is_string = FALSE;
5858
5859                         dest_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5860
5861                         eklass = klass->element_class;
5862
5863                         if (eklass == mono_defaults.string_class) {
5864                                 is_string = TRUE;
5865                                 conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
5866                         }
5867                         else if (eklass == mono_defaults.stringbuilder_class) {
5868                                 is_string = TRUE;
5869                                 conv = mono_marshal_get_stringbuilder_to_ptr_conv (m->piinfo, spec);
5870                         }
5871                         else
5872                                 conv = -1;
5873
5874                         if (is_string && conv == -1) {
5875                                 char *msg = g_strdup_printf ("string/stringbuilder marshalling conversion %d not implemented", encoding);
5876                                 mono_mb_emit_exception_marshal_directive (mb, msg);
5877                                 break;
5878                         }
5879
5880                         src_var = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
5881                         mono_mb_emit_ldarg (mb, argnum);
5882                         if (t->byref)
5883                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
5884                         mono_mb_emit_stloc (mb, src_var);
5885
5886                         /* Check null */
5887                         mono_mb_emit_ldloc (mb, src_var);
5888                         mono_mb_emit_stloc (mb, conv_arg);
5889                         mono_mb_emit_ldloc (mb, src_var);
5890                         label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
5891
5892                         if (is_string)
5893                                 esize = sizeof (gpointer);
5894                         else if (eklass == mono_defaults.char_class) /*can't call mono_marshal_type_size since it causes all sorts of asserts*/
5895                                 esize = mono_pinvoke_is_unicode (m->piinfo) ? 2 : 1;
5896                         else
5897                                 esize = mono_class_native_size (eklass, NULL);
5898
5899                         /* allocate space for the native struct and store the address */
5900                         mono_mb_emit_icon (mb, esize);
5901                         mono_mb_emit_ldloc (mb, src_var);
5902                         mono_mb_emit_byte (mb, CEE_LDLEN);
5903
5904                         if (eklass == mono_defaults.string_class) {
5905                                 /* Make the array bigger for the terminating null */
5906                                 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
5907                                 mono_mb_emit_byte (mb, CEE_ADD);
5908                         }
5909                         mono_mb_emit_byte (mb, CEE_MUL);
5910                         mono_mb_emit_byte (mb, CEE_PREFIX1);
5911                         mono_mb_emit_byte (mb, CEE_LOCALLOC);
5912                         mono_mb_emit_stloc (mb, conv_arg);
5913
5914                         mono_mb_emit_ldloc (mb, conv_arg);
5915                         mono_mb_emit_stloc (mb, dest_ptr);
5916
5917                         /* Emit marshalling loop */
5918                         index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);                                
5919                         mono_mb_emit_byte (mb, CEE_LDC_I4_0);
5920                         mono_mb_emit_stloc (mb, index_var);
5921                         label2 = mono_mb_get_label (mb);
5922                         mono_mb_emit_ldloc (mb, index_var);
5923                         mono_mb_emit_ldloc (mb, src_var);
5924                         mono_mb_emit_byte (mb, CEE_LDLEN);
5925                         label3 = mono_mb_emit_branch (mb, CEE_BGE);
5926
5927                         /* Emit marshalling code */
5928
5929                         if (is_string) {
5930                                 mono_mb_emit_ldloc (mb, dest_ptr);
5931                                 mono_mb_emit_ldloc (mb, src_var);
5932                                 mono_mb_emit_ldloc (mb, index_var);
5933                                 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
5934                                 mono_mb_emit_icall (mb, conv_to_icall (conv));
5935                                 mono_mb_emit_byte (mb, CEE_STIND_I);
5936                         } else {
5937                                 /* set the src_ptr */
5938                                 mono_mb_emit_ldloc (mb, src_var);
5939                                 mono_mb_emit_ldloc (mb, index_var);
5940                                 mono_mb_emit_op (mb, CEE_LDELEMA, eklass);
5941                                 mono_mb_emit_stloc (mb, 0);
5942
5943                                 /* set dst_ptr */
5944                                 mono_mb_emit_ldloc (mb, dest_ptr);
5945                                 mono_mb_emit_stloc (mb, 1);
5946
5947                                 /* emit valuetype conversion code */
5948                                 emit_struct_conv_full (mb, eklass, FALSE, eklass == mono_defaults.char_class ? encoding : -1);
5949                         }
5950
5951                         mono_mb_emit_add_to_local (mb, index_var, 1);
5952                         mono_mb_emit_add_to_local (mb, dest_ptr, esize);
5953                         
5954                         mono_mb_emit_branch_label (mb, CEE_BR, label2);
5955
5956                         mono_mb_patch_branch (mb, label3);
5957
5958                         if (eklass == mono_defaults.string_class) {
5959                                 /* Null terminate */
5960                                 mono_mb_emit_ldloc (mb, dest_ptr);
5961                                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
5962                                 mono_mb_emit_byte (mb, CEE_STIND_REF);
5963                         }
5964
5965                         mono_mb_patch_branch (mb, label1);
5966                 }
5967
5968                 break;
5969
5970         case MARSHAL_ACTION_CONV_OUT:
5971                 /* Unicode character arrays are implicitly marshalled as [Out] under MS.NET */
5972                 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);
5973                 need_free = mono_marshal_need_free (&klass->element_class->byval_arg, 
5974                                                                                         m->piinfo, spec);
5975
5976                 if ((t->attrs & PARAM_ATTRIBUTE_OUT) && spec && spec->native == MONO_NATIVE_LPARRAY && spec->data.array_data.param_num != -1) {
5977                         int param_num = spec->data.array_data.param_num;
5978                         MonoType *param_type;
5979
5980                         param_type = m->sig->params [param_num];
5981
5982                         if (param_type->byref && param_type->type != MONO_TYPE_I4) {
5983                                 char *msg = g_strdup ("Not implemented.");
5984                                 mono_mb_emit_exception_marshal_directive (mb, msg);
5985                                 break;
5986                         }
5987
5988                         mono_mb_emit_ldarg (mb, argnum);
5989
5990                         /* Create the managed array */
5991                         mono_mb_emit_ldarg (mb, param_num);
5992                         if (m->sig->params [param_num]->byref)
5993                                 // FIXME: Support other types
5994                                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
5995                         mono_mb_emit_byte (mb, CEE_CONV_OVF_I);
5996                         mono_mb_emit_op (mb, CEE_NEWARR, klass->element_class);
5997                         /* Store into argument */
5998                         mono_mb_emit_byte (mb, CEE_STIND_I);
5999                 }
6000
6001                 if (need_convert || need_free) {
6002                         /* FIXME: Optimize blittable case */
6003                         MonoClass *eklass;
6004                         guint32 label1, label2, label3;
6005                         int index_var, src_ptr, loc, esize;
6006
6007                         eklass = klass->element_class;
6008                         if ((eklass == mono_defaults.stringbuilder_class) || (eklass == mono_defaults.string_class))
6009                                 esize = sizeof (gpointer);
6010                         else if (eklass == mono_defaults.char_class)
6011                                 esize = mono_pinvoke_is_unicode (m->piinfo) ? 2 : 1;
6012                         else
6013                                 esize = mono_class_native_size (eklass, NULL);
6014                         src_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6015                         loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6016
6017                         /* Check null */
6018                         mono_mb_emit_ldarg (mb, argnum);
6019                         if (t->byref)
6020                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
6021                         label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6022
6023                         mono_mb_emit_ldloc (mb, conv_arg);
6024                         mono_mb_emit_stloc (mb, src_ptr);
6025
6026                         /* Emit marshalling loop */
6027                         index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);                                
6028                         mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6029                         mono_mb_emit_stloc (mb, index_var);
6030                         label2 = mono_mb_get_label (mb);
6031                         mono_mb_emit_ldloc (mb, index_var);
6032                         mono_mb_emit_ldarg (mb, argnum);
6033                         if (t->byref)
6034                                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
6035                         mono_mb_emit_byte (mb, CEE_LDLEN);
6036                         label3 = mono_mb_emit_branch (mb, CEE_BGE);
6037
6038                         /* Emit marshalling code */
6039
6040                         if (eklass == mono_defaults.stringbuilder_class) {
6041                                 gboolean need_free2;
6042                                 MonoMarshalConv conv = mono_marshal_get_ptr_to_stringbuilder_conv (m->piinfo, spec, &need_free2);
6043
6044                                 g_assert (conv != -1);
6045
6046                                 /* dest */
6047                                 mono_mb_emit_ldarg (mb, argnum);
6048                                 if (t->byref)
6049                                         mono_mb_emit_byte (mb, CEE_LDIND_I);
6050                                 mono_mb_emit_ldloc (mb, index_var);
6051                                 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
6052
6053                                 /* src */
6054                                 mono_mb_emit_ldloc (mb, src_ptr);
6055                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
6056
6057                                 mono_mb_emit_icall (mb, conv_to_icall (conv));
6058
6059                                 if (need_free) {
6060                                         /* src */
6061                                         mono_mb_emit_ldloc (mb, src_ptr);
6062                                         mono_mb_emit_byte (mb, CEE_LDIND_I);
6063
6064                                         mono_mb_emit_icall (mb, mono_marshal_free);
6065                                 }
6066                         }
6067                         else if (eklass == mono_defaults.string_class) {
6068                                 if (need_free) {
6069                                         /* src */
6070                                         mono_mb_emit_ldloc (mb, src_ptr);
6071                                         mono_mb_emit_byte (mb, CEE_LDIND_I);
6072
6073                                         mono_mb_emit_icall (mb, mono_marshal_free);
6074                                 }
6075                         }
6076                         else {
6077                                 if (need_convert) {
6078                                         /* set the src_ptr */
6079                                         mono_mb_emit_ldloc (mb, src_ptr);
6080                                         mono_mb_emit_stloc (mb, 0);
6081
6082                                         /* set dst_ptr */
6083                                         mono_mb_emit_ldarg (mb, argnum);
6084                                         if (t->byref)
6085                                                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
6086                                         mono_mb_emit_ldloc (mb, index_var);
6087                                         mono_mb_emit_op (mb, CEE_LDELEMA, eklass);
6088                                         mono_mb_emit_stloc (mb, 1);
6089
6090                                         /* emit valuetype conversion code */
6091                                         emit_struct_conv_full (mb, eklass, TRUE, eklass == mono_defaults.char_class ? encoding : -1);
6092                                 }
6093
6094                                 if (need_free) {
6095                                         mono_mb_emit_ldloc (mb, src_ptr);
6096                                         mono_mb_emit_stloc (mb, loc);
6097                                         mono_mb_emit_ldloc (mb, loc);
6098
6099                                         emit_struct_free (mb, eklass, loc);
6100                                 }
6101                         }
6102
6103                         mono_mb_emit_add_to_local (mb, index_var, 1);
6104                         mono_mb_emit_add_to_local (mb, src_ptr, esize);
6105
6106                         mono_mb_emit_branch_label (mb, CEE_BR, label2);
6107
6108                         mono_mb_patch_branch (mb, label1);
6109                         mono_mb_patch_branch (mb, label3);
6110                 }
6111                 
6112                 if (klass->element_class->blittable) {
6113                         /* free memory allocated (if any) by MONO_MARSHAL_CONV_ARRAY_LPARRAY */
6114
6115                         mono_mb_emit_ldarg (mb, argnum);
6116                         if (t->byref)
6117                                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
6118                         mono_mb_emit_ldloc (mb, conv_arg);
6119                         mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_FREE_LPARRAY));
6120                 }
6121
6122                 break;
6123
6124         case MARSHAL_ACTION_PUSH:
6125                 if (t->byref)
6126                         mono_mb_emit_ldloc_addr (mb, conv_arg);
6127                 else
6128                         mono_mb_emit_ldloc (mb, conv_arg);
6129                 break;
6130
6131         case MARSHAL_ACTION_CONV_RESULT:
6132                 /* fixme: we need conversions here */
6133                 mono_mb_emit_stloc (mb, 3);
6134                 break;
6135
6136         case MARSHAL_ACTION_MANAGED_CONV_IN: {
6137                 MonoClass *eklass;
6138                 guint32 label1, label2, label3;
6139                 int index_var, src_ptr, esize, param_num, num_elem;
6140                 MonoMarshalConv conv;
6141                 gboolean is_string = FALSE;
6142                 
6143                 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6144                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
6145
6146                 if (t->byref) {
6147                         char *msg = g_strdup ("Byref array marshalling to managed code is not implemented.");
6148                         mono_mb_emit_exception_marshal_directive (mb, msg);
6149                         return conv_arg;
6150                 }
6151                 if (!spec) {
6152                         char *msg = g_strdup ("[MarshalAs] attribute required to marshal arrays to managed code.");
6153                         mono_mb_emit_exception_marshal_directive (mb, msg);
6154                         return conv_arg;
6155                 }                       
6156                 if (spec->native != MONO_NATIVE_LPARRAY) {
6157                         char *msg = g_strdup ("Non LPArray marshalling of arrays to managed code is not implemented.");
6158                         mono_mb_emit_exception_marshal_directive (mb, msg);
6159                         return conv_arg;                        
6160                 }
6161
6162                 /* FIXME: t is from the method which is wrapped, not the delegate type */
6163                 /* g_assert (t->attrs & PARAM_ATTRIBUTE_IN); */
6164
6165                 param_num = spec->data.array_data.param_num;
6166                 num_elem = spec->data.array_data.num_elem;
6167                 if (spec->data.array_data.elem_mult == 0)
6168                         /* param_num is not specified */
6169                         param_num = -1;
6170
6171                 if (param_num == -1) {
6172                         if (num_elem <= 0) {
6173                                 char *msg = g_strdup ("Either SizeConst or SizeParamIndex should be specified when marshalling arrays to managed code.");
6174                                 mono_mb_emit_exception_marshal_directive (mb, msg);
6175                                 return conv_arg;
6176                         }
6177                 }
6178
6179                 /* FIXME: Optimize blittable case */
6180
6181                 eklass = klass->element_class;
6182                 if (eklass == mono_defaults.string_class) {
6183                         is_string = TRUE;
6184                         conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
6185                 }
6186                 else if (eklass == mono_defaults.stringbuilder_class) {
6187                         is_string = TRUE;
6188                         conv = mono_marshal_get_ptr_to_stringbuilder_conv (m->piinfo, spec, &need_free);
6189                 }
6190                 else
6191                         conv = -1;
6192
6193                 mono_marshal_load_type_info (eklass);
6194
6195                 if (is_string)
6196                         esize = sizeof (gpointer);
6197                 else
6198                         esize = mono_class_native_size (eklass, NULL);
6199                 src_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6200
6201                 mono_mb_emit_byte (mb, CEE_LDNULL);
6202                 mono_mb_emit_stloc (mb, conv_arg);
6203
6204                 /* Check param index */
6205                 if (param_num != -1) {
6206                         if (param_num >= m->sig->param_count) {
6207                                 char *msg = g_strdup ("Array size control parameter index is out of range.");
6208                                 mono_mb_emit_exception_marshal_directive (mb, msg);
6209                                 return conv_arg;
6210                         }
6211                         switch (m->sig->params [param_num]->type) {
6212                         case MONO_TYPE_I1:
6213                         case MONO_TYPE_U1:
6214                         case MONO_TYPE_I2:
6215                         case MONO_TYPE_U2:
6216                         case MONO_TYPE_I4:
6217                         case MONO_TYPE_U4:
6218                         case MONO_TYPE_I:
6219                         case MONO_TYPE_U:
6220                         case MONO_TYPE_I8:
6221                         case MONO_TYPE_U8:
6222                                 break;
6223                         default: {
6224                                 char *msg = g_strdup ("Array size control parameter must be an integral type.");
6225                                 mono_mb_emit_exception_marshal_directive (mb, msg);
6226                                 return conv_arg;
6227                         }
6228                         }
6229                 }
6230
6231                 /* Check null */
6232                 mono_mb_emit_ldarg (mb, argnum);
6233                 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6234
6235                 mono_mb_emit_ldarg (mb, argnum);
6236                 mono_mb_emit_stloc (mb, src_ptr);
6237
6238                 /* Create managed array */
6239                 /* 
6240                  * The LPArray marshalling spec says that sometimes param_num starts 
6241                  * from 1, sometimes it starts from 0. But MS seems to allways start
6242                  * from 0.
6243                  */
6244
6245                 if (param_num == -1) {
6246                         mono_mb_emit_icon (mb, num_elem);
6247                 } else {
6248                         mono_mb_emit_ldarg (mb, param_num);
6249                         if (num_elem > 0) {
6250                                 mono_mb_emit_icon (mb, num_elem);
6251                                 mono_mb_emit_byte (mb, CEE_ADD);
6252                         }
6253                         mono_mb_emit_byte (mb, CEE_CONV_OVF_I);
6254                 }
6255
6256                 mono_mb_emit_op (mb, CEE_NEWARR, eklass);
6257                 mono_mb_emit_stloc (mb, conv_arg);
6258
6259                 if (eklass->blittable) {
6260                         mono_mb_emit_ldloc (mb, conv_arg);
6261                         mono_mb_emit_byte (mb, CEE_CONV_I);
6262                         mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
6263                         mono_mb_emit_byte (mb, CEE_ADD);
6264                         mono_mb_emit_ldarg (mb, argnum);
6265                         mono_mb_emit_ldloc (mb, conv_arg);
6266                         mono_mb_emit_byte (mb, CEE_LDLEN);
6267                         mono_mb_emit_icon (mb, esize);
6268                         mono_mb_emit_byte (mb, CEE_MUL);
6269                         mono_mb_emit_byte (mb, CEE_PREFIX1);
6270                         mono_mb_emit_byte (mb, CEE_CPBLK);                      
6271                         break;
6272                 }
6273
6274                 /* Emit marshalling loop */
6275                 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6276                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6277                 mono_mb_emit_stloc (mb, index_var);
6278                 label2 = mono_mb_get_label (mb);
6279                 mono_mb_emit_ldloc (mb, index_var);
6280                 mono_mb_emit_ldloc (mb, conv_arg);
6281                 mono_mb_emit_byte (mb, CEE_LDLEN);
6282                 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6283
6284                 /* Emit marshalling code */
6285                 if (is_string) {
6286                         g_assert (conv != -1);
6287
6288                         mono_mb_emit_ldloc (mb, conv_arg);
6289                         mono_mb_emit_ldloc (mb, index_var);
6290
6291                         mono_mb_emit_ldloc (mb, src_ptr);
6292                         mono_mb_emit_byte (mb, CEE_LDIND_I);
6293
6294                         mono_mb_emit_icall (mb, conv_to_icall (conv));
6295                         mono_mb_emit_byte (mb, CEE_STELEM_REF);
6296                 }
6297                 else {
6298                         char *msg = g_strdup ("Marshalling of non-string and non-blittable arrays to managed code is not implemented.");
6299                         mono_mb_emit_exception_marshal_directive (mb, msg);
6300                         return conv_arg;
6301                 }
6302
6303                 mono_mb_emit_add_to_local (mb, index_var, 1);
6304                 mono_mb_emit_add_to_local (mb, src_ptr, esize);
6305
6306                 mono_mb_emit_branch_label (mb, CEE_BR, label2);
6307
6308                 mono_mb_patch_branch (mb, label1);
6309                 mono_mb_patch_branch (mb, label3);
6310                 
6311                 break;
6312         }
6313         case MARSHAL_ACTION_MANAGED_CONV_OUT: {
6314                 MonoClass *eklass;
6315                 guint32 label1, label2, label3;
6316                 int index_var, dest_ptr, esize, param_num, num_elem;
6317                 MonoMarshalConv conv;
6318                 gboolean is_string = FALSE;
6319
6320                 if (!spec)
6321                         /* Already handled in CONV_IN */
6322                         break;
6323                 
6324                 /* These are already checked in CONV_IN */
6325                 g_assert (!t->byref);
6326                 g_assert (spec->native == MONO_NATIVE_LPARRAY);
6327                 g_assert (t->attrs & PARAM_ATTRIBUTE_OUT);
6328
6329                 param_num = spec->data.array_data.param_num;
6330                 num_elem = spec->data.array_data.num_elem;
6331
6332                 if (spec->data.array_data.elem_mult == 0)
6333                         /* param_num is not specified */
6334                         param_num = -1;
6335
6336                 if (param_num == -1) {
6337                         if (num_elem <= 0) {
6338                                 g_assert_not_reached ();
6339                         }
6340                 }
6341
6342                 /* FIXME: Optimize blittable case */
6343
6344                 eklass = klass->element_class;
6345                 if (eklass == mono_defaults.string_class) {
6346                         is_string = TRUE;
6347                         conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
6348                 }
6349                 else if (eklass == mono_defaults.stringbuilder_class) {
6350                         is_string = TRUE;
6351                         conv = mono_marshal_get_stringbuilder_to_ptr_conv (m->piinfo, spec);
6352                 }
6353                 else
6354                         conv = -1;
6355
6356                 mono_marshal_load_type_info (eklass);
6357
6358                 if (is_string)
6359                         esize = sizeof (gpointer);
6360                 else
6361                         esize = mono_class_native_size (eklass, NULL);
6362
6363                 dest_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6364
6365                 /* Check null */
6366                 mono_mb_emit_ldloc (mb, conv_arg);
6367                 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6368
6369                 mono_mb_emit_ldarg (mb, argnum);
6370                 mono_mb_emit_stloc (mb, dest_ptr);
6371
6372                 if (eklass->blittable) {
6373                         /* dest */
6374                         mono_mb_emit_ldarg (mb, argnum);
6375                         /* src */
6376                         mono_mb_emit_ldloc (mb, conv_arg);
6377                         mono_mb_emit_byte (mb, CEE_CONV_I);
6378                         mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
6379                         mono_mb_emit_byte (mb, CEE_ADD);
6380                         /* length */
6381                         mono_mb_emit_ldloc (mb, conv_arg);
6382                         mono_mb_emit_byte (mb, CEE_LDLEN);
6383                         mono_mb_emit_icon (mb, esize);
6384                         mono_mb_emit_byte (mb, CEE_MUL);
6385                         mono_mb_emit_byte (mb, CEE_PREFIX1);
6386                         mono_mb_emit_byte (mb, CEE_CPBLK);                      
6387                         break;
6388                 }
6389
6390                 /* Emit marshalling loop */
6391                 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6392                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6393                 mono_mb_emit_stloc (mb, index_var);
6394                 label2 = mono_mb_get_label (mb);
6395                 mono_mb_emit_ldloc (mb, index_var);
6396                 mono_mb_emit_ldloc (mb, conv_arg);
6397                 mono_mb_emit_byte (mb, CEE_LDLEN);
6398                 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6399
6400                 /* Emit marshalling code */
6401                 if (is_string) {
6402                         g_assert (conv != -1);
6403
6404                         /* dest */
6405                         mono_mb_emit_ldloc (mb, dest_ptr);
6406
6407                         /* src */
6408                         mono_mb_emit_ldloc (mb, conv_arg);
6409                         mono_mb_emit_ldloc (mb, index_var);
6410
6411                         mono_mb_emit_byte (mb, CEE_LDELEM_REF);
6412
6413                         mono_mb_emit_icall (mb, conv_to_icall (conv));
6414                         mono_mb_emit_byte (mb, CEE_STIND_I);
6415                 }
6416                 else {
6417                         char *msg = g_strdup ("Marshalling of non-string and non-blittable arrays to managed code is not implemented.");
6418                         mono_mb_emit_exception_marshal_directive (mb, msg);
6419                         return conv_arg;
6420                 }
6421
6422                 mono_mb_emit_add_to_local (mb, index_var, 1);
6423                 mono_mb_emit_add_to_local (mb, dest_ptr, esize);
6424
6425                 mono_mb_emit_branch_label (mb, CEE_BR, label2);
6426
6427                 mono_mb_patch_branch (mb, label1);
6428                 mono_mb_patch_branch (mb, label3);
6429
6430                 break;
6431         }
6432         case MARSHAL_ACTION_MANAGED_CONV_RESULT: {
6433                 MonoClass *eklass;
6434                 guint32 label1, label2, label3;
6435                 int index_var, src, dest, esize;
6436                 MonoMarshalConv conv = -1;
6437                 gboolean is_string = FALSE;
6438                 
6439                 g_assert (!t->byref);
6440
6441                 eklass = klass->element_class;
6442
6443                 mono_marshal_load_type_info (eklass);
6444
6445                 if (eklass == mono_defaults.string_class) {
6446                         is_string = TRUE;
6447                         conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
6448                 }
6449                 else {
6450                         g_assert_not_reached ();
6451                 }
6452
6453                 if (is_string)
6454                         esize = sizeof (gpointer);
6455                 else if (eklass == mono_defaults.char_class)
6456                         esize = mono_pinvoke_is_unicode (m->piinfo) ? 2 : 1;
6457                 else
6458                         esize = mono_class_native_size (eklass, NULL);
6459
6460                 src = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6461                 dest = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6462                         
6463                 mono_mb_emit_stloc (mb, src);
6464                 mono_mb_emit_ldloc (mb, src);
6465                 mono_mb_emit_stloc (mb, 3);
6466
6467                 /* Check for null */
6468                 mono_mb_emit_ldloc (mb, src);
6469                 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6470
6471                 /* Allocate native array */
6472                 mono_mb_emit_icon (mb, esize);
6473                 mono_mb_emit_ldloc (mb, src);
6474                 mono_mb_emit_byte (mb, CEE_LDLEN);
6475
6476                 if (eklass == mono_defaults.string_class) {
6477                         /* Make the array bigger for the terminating null */
6478                         mono_mb_emit_byte (mb, CEE_LDC_I4_1);
6479                         mono_mb_emit_byte (mb, CEE_ADD);
6480                 }
6481                 mono_mb_emit_byte (mb, CEE_MUL);
6482                 mono_mb_emit_icall (mb, mono_marshal_alloc);
6483                 mono_mb_emit_stloc (mb, dest);
6484                 mono_mb_emit_ldloc (mb, dest);
6485                 mono_mb_emit_stloc (mb, 3);
6486
6487                 /* Emit marshalling loop */
6488                 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6489                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6490                 mono_mb_emit_stloc (mb, index_var);
6491                 label2 = mono_mb_get_label (mb);
6492                 mono_mb_emit_ldloc (mb, index_var);
6493                 mono_mb_emit_ldloc (mb, src);
6494                 mono_mb_emit_byte (mb, CEE_LDLEN);
6495                 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6496
6497                 /* Emit marshalling code */
6498                 if (is_string) {
6499                         g_assert (conv != -1);
6500
6501                         /* dest */
6502                         mono_mb_emit_ldloc (mb, dest);
6503
6504                         /* src */
6505                         mono_mb_emit_ldloc (mb, src);
6506                         mono_mb_emit_ldloc (mb, index_var);
6507
6508                         mono_mb_emit_byte (mb, CEE_LDELEM_REF);
6509
6510                         mono_mb_emit_icall (mb, conv_to_icall (conv));
6511                         mono_mb_emit_byte (mb, CEE_STIND_I);
6512                 }
6513                 else {
6514                         char *msg = g_strdup ("Marshalling of non-string arrays to managed code is not implemented.");
6515                         mono_mb_emit_exception_marshal_directive (mb, msg);
6516                         return conv_arg;
6517                 }
6518
6519                 mono_mb_emit_add_to_local (mb, index_var, 1);
6520                 mono_mb_emit_add_to_local (mb, dest, esize);
6521
6522                 mono_mb_emit_branch_label (mb, CEE_BR, label2);
6523
6524                 mono_mb_patch_branch (mb, label3);
6525                 mono_mb_patch_branch (mb, label1);
6526                 break;
6527         }
6528         default:
6529                 g_assert_not_reached ();
6530         }
6531 #endif
6532         return conv_arg;
6533 }
6534
6535 static MonoType*
6536 marshal_boolean_conv_in_get_local_type (MonoMarshalSpec *spec, guint8 *ldc_op /*out*/)
6537 {
6538         if (spec == NULL) {
6539                 return &mono_defaults.int32_class->byval_arg;
6540         } else {
6541                 switch (spec->native) {
6542                 case MONO_NATIVE_I1:
6543                 case MONO_NATIVE_U1:
6544                         return &mono_defaults.byte_class->byval_arg;
6545                 case MONO_NATIVE_VARIANTBOOL:
6546                         if (ldc_op) *ldc_op = CEE_LDC_I4_M1;
6547                         return &mono_defaults.int16_class->byval_arg;
6548                 case MONO_NATIVE_BOOLEAN:
6549                         return &mono_defaults.int32_class->byval_arg;
6550                 default:
6551                         g_warning ("marshalling bool as native type %x is currently not supported", spec->native);
6552                         return &mono_defaults.int32_class->byval_arg;
6553                 }
6554         }
6555 }
6556
6557 static MonoClass*
6558 marshal_boolean_managed_conv_in_get_conv_arg_class (MonoMarshalSpec *spec, guint8 *ldop/*out*/)
6559 {
6560         MonoClass* conv_arg_class = mono_defaults.int32_class;
6561         if (spec) {
6562                 switch (spec->native) {
6563                 case MONO_NATIVE_I1:
6564                 case MONO_NATIVE_U1:
6565                         conv_arg_class = mono_defaults.byte_class;
6566                         if (ldop) *ldop = CEE_LDIND_I1;
6567                         break;
6568                 case MONO_NATIVE_VARIANTBOOL:
6569                         conv_arg_class = mono_defaults.int16_class;
6570                         if (ldop) *ldop = CEE_LDIND_I2;
6571                         break;
6572                 case MONO_NATIVE_BOOLEAN:
6573                         break;
6574                 default:
6575                         g_warning ("marshalling bool as native type %x is currently not supported", spec->native);
6576                 }
6577         }
6578         return conv_arg_class;
6579 }
6580
6581 static int
6582 emit_marshal_boolean (EmitMarshalContext *m, int argnum, MonoType *t,
6583                       MonoMarshalSpec *spec, 
6584                       int conv_arg, MonoType **conv_arg_type, 
6585                       MarshalAction action)
6586 {
6587 #ifdef DISABLE_JIT
6588         switch (action) {
6589         case MARSHAL_ACTION_CONV_IN:
6590                 if (t->byref)
6591                         *conv_arg_type = &mono_defaults.int_class->byval_arg;
6592                 else
6593                         *conv_arg_type = marshal_boolean_conv_in_get_local_type (spec, NULL);
6594                 break;
6595
6596         case MARSHAL_ACTION_MANAGED_CONV_IN: {
6597                 MonoClass* conv_arg_class = marshal_boolean_managed_conv_in_get_conv_arg_class (spec, NULL);
6598                 if (t->byref)
6599                         *conv_arg_type = &conv_arg_class->this_arg;
6600                 else
6601                         *conv_arg_type = &conv_arg_class->byval_arg;
6602                 break;
6603         }
6604
6605         }
6606 #else
6607         MonoMethodBuilder *mb = m->mb;
6608
6609         switch (action) {
6610         case MARSHAL_ACTION_CONV_IN: {
6611                 MonoType *local_type;
6612                 int label_false;
6613                 guint8 ldc_op = CEE_LDC_I4_1;
6614
6615                 local_type = marshal_boolean_conv_in_get_local_type (spec, &ldc_op);
6616                 if (t->byref)
6617                         *conv_arg_type = &mono_defaults.int_class->byval_arg;
6618                 else
6619                         *conv_arg_type = local_type;
6620                 conv_arg = mono_mb_add_local (mb, local_type);
6621                 
6622                 mono_mb_emit_ldarg (mb, argnum);
6623                 if (t->byref)
6624                         mono_mb_emit_byte (mb, CEE_LDIND_I1);
6625                 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
6626                 mono_mb_emit_byte (mb, ldc_op);
6627                 mono_mb_emit_stloc (mb, conv_arg);
6628                 mono_mb_patch_branch (mb, label_false);
6629
6630                 break;
6631         }
6632
6633         case MARSHAL_ACTION_CONV_OUT:
6634         {
6635                 int label_false, label_end;
6636                 if (!t->byref)
6637                         break;
6638
6639                 mono_mb_emit_ldarg (mb, argnum);
6640                 mono_mb_emit_ldloc (mb, conv_arg);
6641                 
6642                 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
6643                 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
6644
6645                 label_end = mono_mb_emit_branch (mb, CEE_BR);
6646                 mono_mb_patch_branch (mb, label_false);
6647                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6648                 mono_mb_patch_branch (mb, label_end);
6649
6650                 mono_mb_emit_byte (mb, CEE_STIND_I1);
6651                 break;
6652         }
6653
6654         case MARSHAL_ACTION_PUSH:
6655                 if (t->byref)
6656                         mono_mb_emit_ldloc_addr (mb, conv_arg);
6657                 else if (conv_arg)
6658                         mono_mb_emit_ldloc (mb, conv_arg);
6659                 else
6660                         mono_mb_emit_ldarg (mb, argnum);
6661                 break;
6662
6663         case MARSHAL_ACTION_CONV_RESULT:
6664                 /* maybe we need to make sure that it fits within 8 bits */
6665                 mono_mb_emit_stloc (mb, 3);
6666                 break;
6667
6668         case MARSHAL_ACTION_MANAGED_CONV_IN: {
6669                 MonoClass* conv_arg_class = mono_defaults.int32_class;
6670                 guint8 ldop = CEE_LDIND_I4;
6671                 int label_null, label_false;
6672
6673                 conv_arg_class = marshal_boolean_managed_conv_in_get_conv_arg_class (spec, &ldop);
6674                 conv_arg = mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
6675
6676                 if (t->byref)
6677                         *conv_arg_type = &conv_arg_class->this_arg;
6678                 else
6679                         *conv_arg_type = &conv_arg_class->byval_arg;
6680
6681
6682                 mono_mb_emit_ldarg (mb, argnum);
6683                 
6684                 /* Check null */
6685                 if (t->byref) {
6686                         label_null = mono_mb_emit_branch (mb, CEE_BRFALSE);
6687                         mono_mb_emit_ldarg (mb, argnum);
6688                         mono_mb_emit_byte (mb, ldop);
6689                 } else
6690                         label_null = 0;
6691
6692                 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
6693                 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
6694                 mono_mb_emit_stloc (mb, conv_arg);
6695                 mono_mb_patch_branch (mb, label_false);
6696
6697                 if (t->byref) 
6698                         mono_mb_patch_branch (mb, label_null);
6699                 break;
6700         }
6701
6702         case MARSHAL_ACTION_MANAGED_CONV_OUT: {
6703                 guint8 stop = CEE_STIND_I4;
6704                 guint8 ldc_op = CEE_LDC_I4_1;
6705                 int label_null,label_false, label_end;;
6706
6707                 if (!t->byref)
6708                         break;
6709                 if (spec) {
6710                         switch (spec->native) {
6711                         case MONO_NATIVE_I1:
6712                         case MONO_NATIVE_U1:
6713                                 stop = CEE_STIND_I1;
6714                                 break;
6715                         case MONO_NATIVE_VARIANTBOOL:
6716                                 stop = CEE_STIND_I2;
6717                                 ldc_op = CEE_LDC_I4_M1;
6718                                 break;
6719                         default:
6720                                 break;
6721                         }
6722                 }
6723                 
6724                 /* Check null */
6725                 mono_mb_emit_ldarg (mb, argnum);
6726                 label_null = mono_mb_emit_branch (mb, CEE_BRFALSE);
6727
6728                 mono_mb_emit_ldarg (mb, argnum);
6729                 mono_mb_emit_ldloc (mb, conv_arg);
6730
6731                 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
6732                 mono_mb_emit_byte (mb, ldc_op);
6733                 label_end = mono_mb_emit_branch (mb, CEE_BR);
6734
6735                 mono_mb_patch_branch (mb, label_false);
6736                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6737                 mono_mb_patch_branch (mb, label_end);
6738
6739                 mono_mb_emit_byte (mb, stop);
6740                 mono_mb_patch_branch (mb, label_null);
6741                 break;
6742         }
6743
6744         default:
6745                 g_assert_not_reached ();
6746         }
6747 #endif
6748         return conv_arg;
6749 }
6750
6751 static int
6752 emit_marshal_ptr (EmitMarshalContext *m, int argnum, MonoType *t, 
6753                   MonoMarshalSpec *spec, int conv_arg, 
6754                   MonoType **conv_arg_type, MarshalAction action)
6755 {
6756 #ifndef DISABLE_JIT
6757         MonoMethodBuilder *mb = m->mb;
6758
6759         switch (action) {
6760         case MARSHAL_ACTION_CONV_IN:
6761                 /* MS seems to allow this in some cases, ie. bxc #158 */
6762                 /*
6763                 if (MONO_TYPE_ISSTRUCT (t->data.type) && !mono_class_from_mono_type (t->data.type)->blittable) {
6764                         char *msg = g_strdup_printf ("Can not marshal 'parameter #%d': Pointers can not reference marshaled structures. Use byref instead.", argnum + 1);
6765                         mono_mb_emit_exception_marshal_directive (m->mb, msg);
6766                 }
6767                 */
6768                 break;
6769
6770         case MARSHAL_ACTION_PUSH:
6771                 mono_mb_emit_ldarg (mb, argnum);
6772                 break;
6773
6774         case MARSHAL_ACTION_CONV_RESULT:
6775                 /* no conversions necessary */
6776                 mono_mb_emit_stloc (mb, 3);
6777                 break;
6778
6779         default:
6780                 break;
6781         }
6782 #endif
6783         return conv_arg;
6784 }
6785
6786 static int
6787 emit_marshal_char (EmitMarshalContext *m, int argnum, MonoType *t, 
6788                    MonoMarshalSpec *spec, int conv_arg, 
6789                    MonoType **conv_arg_type, MarshalAction action)
6790 {
6791 #ifndef DISABLE_JIT
6792         MonoMethodBuilder *mb = m->mb;
6793
6794         switch (action) {
6795         case MARSHAL_ACTION_PUSH:
6796                 /* fixme: dont know how to marshal that. We cant simply
6797                  * convert it to a one byte UTF8 character, because an
6798                  * unicode character may need more that one byte in UTF8 */
6799                 mono_mb_emit_ldarg (mb, argnum);
6800                 break;
6801
6802         case MARSHAL_ACTION_CONV_RESULT:
6803                 /* fixme: we need conversions here */
6804                 mono_mb_emit_stloc (mb, 3);
6805                 break;
6806
6807         default:
6808                 break;
6809         }
6810 #endif
6811         return conv_arg;
6812 }
6813
6814 static int
6815 emit_marshal_scalar (EmitMarshalContext *m, int argnum, MonoType *t, 
6816                      MonoMarshalSpec *spec, int conv_arg, 
6817                      MonoType **conv_arg_type, MarshalAction action)
6818 {
6819 #ifndef DISABLE_JIT
6820         MonoMethodBuilder *mb = m->mb;
6821
6822         switch (action) {
6823         case MARSHAL_ACTION_PUSH:
6824                 mono_mb_emit_ldarg (mb, argnum);
6825                 break;
6826
6827         case MARSHAL_ACTION_CONV_RESULT:
6828                 /* no conversions necessary */
6829                 mono_mb_emit_stloc (mb, 3);
6830                 break;
6831
6832         default:
6833                 break;
6834         }
6835 #endif
6836         return conv_arg;
6837 }
6838
6839 static int
6840 emit_marshal (EmitMarshalContext *m, int argnum, MonoType *t, 
6841               MonoMarshalSpec *spec, int conv_arg, 
6842               MonoType **conv_arg_type, MarshalAction action)
6843 {
6844         /* Ensure that we have marshalling info for this param */
6845         mono_marshal_load_type_info (mono_class_from_mono_type (t));
6846
6847         if (spec && spec->native == MONO_NATIVE_CUSTOM)
6848                 return emit_marshal_custom (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6849
6850         if (spec && spec->native == MONO_NATIVE_ASANY)
6851                 return emit_marshal_asany (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6852                         
6853         switch (t->type) {
6854         case MONO_TYPE_VALUETYPE:
6855                 if (t->data.klass == mono_defaults.handleref_class)
6856                         return emit_marshal_handleref (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6857                 
6858                 return emit_marshal_vtype (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6859         case MONO_TYPE_STRING:
6860                 return emit_marshal_string (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6861         case MONO_TYPE_CLASS:
6862         case MONO_TYPE_OBJECT:
6863 #ifndef DISABLE_COM
6864                 if (spec && spec->native == MONO_NATIVE_STRUCT)
6865                         return emit_marshal_variant (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6866
6867                 if (spec && (spec->native == MONO_NATIVE_IUNKNOWN ||
6868                         spec->native == MONO_NATIVE_IDISPATCH ||
6869                         spec->native == MONO_NATIVE_INTERFACE))
6870                         return mono_cominterop_emit_marshal_com_interface (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6871                 if (spec && (spec->native == MONO_NATIVE_SAFEARRAY) && 
6872                         (spec->data.safearray_data.elem_type == MONO_VARIANT_VARIANT) && 
6873                         ((action == MARSHAL_ACTION_CONV_OUT) || (action == MARSHAL_ACTION_CONV_IN) || (action == MARSHAL_ACTION_PUSH)))
6874                         return mono_cominterop_emit_marshal_safearray (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6875 #endif
6876
6877                 if (mono_defaults.safehandle_class != NULL && t->data.klass &&
6878                     mono_class_is_subclass_of (t->data.klass,  mono_defaults.safehandle_class, FALSE))
6879                         return emit_marshal_safehandle (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6880                 
6881                 return emit_marshal_object (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6882         case MONO_TYPE_ARRAY:
6883         case MONO_TYPE_SZARRAY:
6884                 return emit_marshal_array (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6885         case MONO_TYPE_BOOLEAN:
6886                 return emit_marshal_boolean (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6887         case MONO_TYPE_PTR:
6888                 return emit_marshal_ptr (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6889         case MONO_TYPE_CHAR:
6890                 return emit_marshal_char (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6891         case MONO_TYPE_I1:
6892         case MONO_TYPE_U1:
6893         case MONO_TYPE_I2:
6894         case MONO_TYPE_U2:
6895         case MONO_TYPE_I4:
6896         case MONO_TYPE_U4:
6897         case MONO_TYPE_I:
6898         case MONO_TYPE_U:
6899         case MONO_TYPE_R4:
6900         case MONO_TYPE_R8:
6901         case MONO_TYPE_I8:
6902         case MONO_TYPE_U8:
6903         case MONO_TYPE_FNPTR:
6904                 return emit_marshal_scalar (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6905         case MONO_TYPE_GENERICINST:
6906                 if (mono_type_generic_inst_is_valuetype (t))
6907                         return emit_marshal_vtype (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6908                 else
6909                         return emit_marshal_object (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6910         default:
6911                 return conv_arg;
6912         }
6913 }
6914
6915 #ifndef DISABLE_JIT
6916 /**
6917  * mono_marshal_emit_native_wrapper:
6918  * @image: the image to use for looking up custom marshallers
6919  * @sig: The signature of the native function
6920  * @piinfo: Marshalling information
6921  * @mspecs: Marshalling information
6922  * @aot: whenever the created method will be compiled by the AOT compiler
6923  * @method: if non-NULL, the pinvoke method to call
6924  * @check_exceptions: Whenever to check for pending exceptions after the native call
6925  * @func_param: the function to call is passed as a boxed IntPtr as the first parameter
6926  *
6927  * generates IL code for the pinvoke wrapper, the generated code calls @func.
6928  */
6929 void
6930 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)
6931 {
6932         EmitMarshalContext m;
6933         MonoMethodSignature *csig;
6934         MonoClass *klass;
6935         int i, argnum, *tmp_locals;
6936         int type, param_shift = 0;
6937         static MonoMethodSignature *get_last_error_sig = NULL;
6938
6939         memset (&m, 0, sizeof (m));
6940         m.mb = mb;
6941         m.sig = sig;
6942         m.piinfo = piinfo;
6943
6944         /* we copy the signature, so that we can set pinvoke to 0 */
6945         if (func_param) {
6946                 /* The function address is passed as the first argument */
6947                 g_assert (!sig->hasthis);
6948                 param_shift += 1;
6949         }
6950         csig = signature_dup (mb->method->klass->image, sig);
6951         csig->pinvoke = 1;
6952         m.csig = csig;
6953         m.image = image;
6954
6955         if (sig->hasthis)
6956                 param_shift += 1;
6957
6958         /* we allocate local for use with emit_struct_conv() */
6959         /* allocate local 0 (pointer) src_ptr */
6960         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6961         /* allocate local 1 (pointer) dst_ptr */
6962         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6963         /* allocate local 2 (boolean) delete_old */
6964         mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
6965
6966         /* delete_old = FALSE */
6967         mono_mb_emit_icon (mb, 0);
6968         mono_mb_emit_stloc (mb, 2);
6969
6970         if (!MONO_TYPE_IS_VOID(sig->ret)) {
6971                 /* allocate local 3 to store the return value */
6972                 mono_mb_add_local (mb, sig->ret);
6973         }
6974
6975         if (mspecs [0] && mspecs [0]->native == MONO_NATIVE_CUSTOM) {
6976                 /* Return type custom marshaling */
6977                 /*
6978                  * Since we can't determine the return type of the unmanaged function,
6979                  * we assume it returns a pointer, and pass that pointer to
6980                  * MarshalNativeToManaged.
6981                  */
6982                 csig->ret = &mono_defaults.int_class->byval_arg;
6983         }
6984
6985         /* we first do all conversions */
6986         tmp_locals = alloca (sizeof (int) * sig->param_count);
6987         m.orig_conv_args = alloca (sizeof (int) * (sig->param_count + 1));
6988
6989         for (i = 0; i < sig->param_count; i ++) {
6990                 tmp_locals [i] = emit_marshal (&m, i + param_shift, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_CONV_IN);
6991         }
6992
6993         /* push all arguments */
6994
6995         if (sig->hasthis)
6996                 mono_mb_emit_byte (mb, CEE_LDARG_0);
6997
6998         for (i = 0; i < sig->param_count; i++) {
6999                 emit_marshal (&m, i + param_shift, sig->params [i], mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_PUSH);
7000         }                       
7001
7002         /* call the native method */
7003         if (func_param) {
7004                 mono_mb_emit_byte (mb, CEE_LDARG_0);
7005                 mono_mb_emit_op (mb, CEE_UNBOX, mono_defaults.int_class);
7006                 mono_mb_emit_byte (mb, CEE_LDIND_I);
7007                 mono_mb_emit_calli (mb, csig);
7008         } else if (MONO_CLASS_IS_IMPORT (mb->method->klass)) {
7009 #ifndef DISABLE_COM
7010                 mono_mb_emit_cominterop_call (mb, csig, &piinfo->method);
7011 #else
7012                 g_assert_not_reached ();
7013 #endif
7014         }
7015         else {
7016                 if (aot) {
7017                         /* Reuse the ICALL_ADDR opcode for pinvokes too */
7018                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7019                         mono_mb_emit_op (mb, CEE_MONO_ICALL_ADDR, &piinfo->method);
7020                         mono_mb_emit_calli (mb, csig);
7021                 } else {                        
7022                         mono_mb_emit_native_call (mb, csig, func);
7023                 }
7024         }
7025
7026         /* Set LastError if needed */
7027         if (piinfo->piflags & PINVOKE_ATTRIBUTE_SUPPORTS_LAST_ERROR) {
7028                 if (!get_last_error_sig) {
7029                         get_last_error_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
7030                         get_last_error_sig->ret = &mono_defaults.int_class->byval_arg;
7031                         get_last_error_sig->pinvoke = 1;
7032                 }
7033
7034 #ifdef TARGET_WIN32
7035                 /* 
7036                  * Have to call GetLastError () early and without a wrapper, since various runtime components could
7037                  * clobber its value.
7038                  */
7039                 mono_mb_emit_native_call (mb, get_last_error_sig, GetLastError);
7040                 mono_mb_emit_icall (mb, mono_marshal_set_last_error_windows);
7041 #else
7042                 mono_mb_emit_icall (mb, mono_marshal_set_last_error);
7043 #endif
7044         }               
7045
7046         /* convert the result */
7047         if (!sig->ret->byref) {
7048                 MonoMarshalSpec *spec = mspecs [0];
7049                 type = sig->ret->type;
7050
7051                 if (spec && spec->native == MONO_NATIVE_CUSTOM) {
7052                         emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7053                 } else {
7054
7055                 handle_enum:
7056                         switch (type) {
7057                         case MONO_TYPE_VOID:
7058                                 break;
7059                         case MONO_TYPE_VALUETYPE:
7060                                 klass = sig->ret->data.klass;
7061                                 if (klass->enumtype) {
7062                                         type = mono_class_enum_basetype (sig->ret->data.klass)->type;
7063                                         goto handle_enum;
7064                                 }
7065                                 emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7066                                 break;
7067                         case MONO_TYPE_I1:
7068                         case MONO_TYPE_U1:
7069                         case MONO_TYPE_I2:
7070                         case MONO_TYPE_U2:
7071                         case MONO_TYPE_I4:
7072                         case MONO_TYPE_U4:
7073                         case MONO_TYPE_I:
7074                         case MONO_TYPE_U:
7075                         case MONO_TYPE_R4:
7076                         case MONO_TYPE_R8:
7077                         case MONO_TYPE_I8:
7078                         case MONO_TYPE_U8:
7079                         case MONO_TYPE_FNPTR:
7080                         case MONO_TYPE_STRING:
7081                         case MONO_TYPE_CLASS:
7082                         case MONO_TYPE_OBJECT:
7083                         case MONO_TYPE_BOOLEAN:
7084                         case MONO_TYPE_ARRAY:
7085                         case MONO_TYPE_SZARRAY:
7086                         case MONO_TYPE_CHAR:
7087                         case MONO_TYPE_PTR:
7088                         case MONO_TYPE_GENERICINST:
7089                                 emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7090                                 break;
7091                         case MONO_TYPE_TYPEDBYREF:
7092                         default:
7093                                 g_warning ("return type 0x%02x unknown", sig->ret->type);       
7094                                 g_assert_not_reached ();
7095                         }
7096                 }
7097         } else {
7098                 mono_mb_emit_stloc (mb, 3);
7099         }
7100
7101         /* 
7102          * Need to call this after converting the result since MONO_VTADDR needs 
7103          * to be adjacent to the call instruction.
7104          */
7105         if (check_exceptions)
7106                 emit_thread_interrupt_checkpoint (mb);
7107
7108         /* we need to convert byref arguments back and free string arrays */
7109         for (i = 0; i < sig->param_count; i++) {
7110                 MonoType *t = sig->params [i];
7111                 MonoMarshalSpec *spec = mspecs [i + 1];
7112
7113                 argnum = i + param_shift;
7114
7115                 if (spec && ((spec->native == MONO_NATIVE_CUSTOM) || (spec->native == MONO_NATIVE_ASANY))) {
7116                         emit_marshal (&m, argnum, t, spec, tmp_locals [i], NULL, MARSHAL_ACTION_CONV_OUT);
7117                         continue;
7118                 }
7119
7120                 switch (t->type) {
7121                 case MONO_TYPE_STRING:
7122                 case MONO_TYPE_VALUETYPE:
7123                 case MONO_TYPE_CLASS:
7124                 case MONO_TYPE_OBJECT:
7125                 case MONO_TYPE_SZARRAY:
7126                 case MONO_TYPE_BOOLEAN:
7127                         emit_marshal (&m, argnum, t, spec, tmp_locals [i], NULL, MARSHAL_ACTION_CONV_OUT);
7128                         break;
7129                 default:
7130                         break;
7131                 }
7132         }
7133
7134         if (!MONO_TYPE_IS_VOID(sig->ret))
7135                 mono_mb_emit_ldloc (mb, 3);
7136
7137         mono_mb_emit_byte (mb, CEE_RET);
7138 }
7139 #endif /* DISABLE_JIT */
7140
7141
7142 G_GNUC_UNUSED static void
7143 code_for (MonoMethod *method) {
7144         MonoMethodHeader *header = mono_method_get_header (method);
7145         printf ("CODE FOR %s: \n%s.\n", mono_method_full_name (method, TRUE), mono_disasm_code (0, method, header->code, header->code + header->code_size));
7146 }
7147
7148 /**
7149  * mono_marshal_get_native_wrapper:
7150  * @method: The MonoMethod to wrap.
7151  * @check_exceptions: Whenever to check for pending exceptions
7152  *
7153  * generates IL code for the pinvoke wrapper (the generated method
7154  * calls the unmanaged code in piinfo->addr)
7155  * The wrapper info for the wrapper is a WrapperInfo structure.
7156  */
7157 MonoMethod *
7158 mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions, gboolean aot)
7159 {
7160         MonoMethodSignature *sig, *csig;
7161         MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
7162         MonoMethodBuilder *mb;
7163         MonoMarshalSpec **mspecs;
7164         MonoMethod *res;
7165         GHashTable *cache;
7166         gboolean pinvoke = FALSE;
7167         gpointer iter;
7168         int i;
7169         const char *exc_class = "MissingMethodException";
7170         const char *exc_arg = NULL;
7171         WrapperInfo *info;
7172
7173         g_assert (method != NULL);
7174         g_assert (mono_method_signature (method)->pinvoke);
7175
7176         if (aot)
7177                 cache = get_cache (&method->klass->image->native_wrapper_aot_cache, mono_aligned_addr_hash, NULL);
7178         else
7179                 cache = get_cache (&method->klass->image->native_wrapper_cache, mono_aligned_addr_hash, NULL);
7180         if ((res = mono_marshal_find_in_cache (cache, method)))
7181                 return res;
7182
7183         if (MONO_CLASS_IS_IMPORT (method->klass)) {
7184                 /* The COM code is not AOT compatible, it calls mono_custom_attrs_get_attr_checked () */
7185                 if (aot)
7186                         return method;
7187 #ifndef DISABLE_COM
7188                 return mono_cominterop_get_native_wrapper (method);
7189 #else
7190                 g_assert_not_reached ();
7191 #endif
7192         }
7193
7194         sig = mono_method_signature (method);
7195
7196         if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
7197             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7198                 pinvoke = TRUE;
7199
7200         if (!piinfo->addr) {
7201                 if (pinvoke) {
7202                         if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)
7203                                 exc_arg = "Method contains unsupported native code";
7204                         else if (!aot)
7205                                 mono_lookup_pinvoke_call (method, &exc_class, &exc_arg);
7206                 } else {
7207                         piinfo->addr = mono_lookup_internal_call (method);
7208                 }
7209         }
7210
7211         /* hack - redirect certain string constructors to CreateString */
7212         if (piinfo->addr == ves_icall_System_String_ctor_RedirectToCreateString) {
7213                 g_assert (!pinvoke);
7214                 g_assert (method->string_ctor);
7215                 g_assert (sig->hasthis);
7216
7217                 /* CreateString returns a value */
7218                 csig = signature_dup (method->klass->image, sig);
7219                 csig->ret = &mono_defaults.string_class->byval_arg;
7220                 csig->pinvoke = 0;
7221
7222                 iter = NULL;
7223                 while ((res = mono_class_get_methods (mono_defaults.string_class, &iter))) {
7224                         if (!strcmp ("CreateString", res->name) &&
7225                                 mono_metadata_signature_equal (csig, mono_method_signature (res))) {
7226                                 WrapperInfo *info;
7227
7228                                 g_assert (!(res->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL));
7229                                 g_assert (!(res->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL));
7230
7231                                 /* create a wrapper to preserve .ctor in stack trace */
7232                                 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_MANAGED);
7233
7234 #ifndef DISABLE_JIT
7235                                 mono_mb_emit_byte (mb, CEE_LDARG_0);
7236                                 for (i = 1; i <= csig->param_count; i++)
7237                                         mono_mb_emit_ldarg (mb, i);
7238                                 mono_mb_emit_managed_call (mb, res, NULL);
7239                                 mono_mb_emit_byte (mb, CEE_RET);
7240 #endif
7241
7242                                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_STRING_CTOR);
7243                                 info->d.string_ctor.method = method;
7244
7245                                 /* use native_wrapper_cache because internal calls are looked up there */
7246                                 res = mono_mb_create_and_cache_full (cache, method, mb, csig,
7247                                                                                                          csig->param_count + 1, info, NULL);
7248                                 mono_mb_free (mb);
7249
7250                                 return res;
7251                         }
7252                 }
7253
7254                 /* exception will be thrown */
7255                 piinfo->addr = NULL;
7256                 g_warning ("cannot find CreateString for .ctor");
7257         }
7258
7259         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_NATIVE);
7260
7261         mb->method->save_lmf = 1;
7262
7263         /*
7264          * In AOT mode and embedding scenarios, it is possible that the icall is not
7265          * registered in the runtime doing the AOT compilation.
7266          */
7267         if (!piinfo->addr && !aot) {
7268 #ifndef DISABLE_JIT
7269                 mono_mb_emit_exception (mb, exc_class, exc_arg);
7270 #endif
7271                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
7272                 info->d.managed_to_native.method = method;
7273
7274                 csig = signature_dup (method->klass->image, sig);
7275                 csig->pinvoke = 0;
7276                 res = mono_mb_create_and_cache_full (cache, method, mb, csig,
7277                                                                                          csig->param_count + 16, info, NULL);
7278                 mono_mb_free (mb);
7279
7280                 return res;
7281         }
7282
7283         /* internal calls: we simply push all arguments and call the method (no conversions) */
7284         if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
7285                 if (sig->hasthis)
7286                         csig = signature_dup_add_this (method->klass->image, sig, method->klass);
7287                 else
7288                         csig = signature_dup (method->klass->image, sig);
7289
7290                 /* hack - string constructors returns a value */
7291                 if (method->string_ctor)
7292                         csig->ret = &mono_defaults.string_class->byval_arg;
7293
7294 #ifndef DISABLE_JIT
7295                 if (sig->hasthis) {
7296                         int pos;
7297
7298                         /*
7299                          * Add a null check since public icalls can be called with 'call' which
7300                          * does no such check.
7301                          */
7302                         mono_mb_emit_byte (mb, CEE_LDARG_0);                    
7303                         pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
7304                         mono_mb_emit_exception (mb, "NullReferenceException", NULL);
7305                         mono_mb_patch_branch (mb, pos);
7306
7307                         mono_mb_emit_byte (mb, CEE_LDARG_0);
7308                 }
7309
7310                 for (i = 0; i < sig->param_count; i++)
7311                         mono_mb_emit_ldarg (mb, i + sig->hasthis);
7312
7313                 if (aot) {
7314                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7315                         mono_mb_emit_op (mb, CEE_MONO_ICALL_ADDR, &piinfo->method);
7316                         mono_mb_emit_calli (mb, csig);
7317                 } else {
7318                         g_assert (piinfo->addr);
7319                         mono_mb_emit_native_call (mb, csig, piinfo->addr);
7320                 }
7321                 if (check_exceptions)
7322                         emit_thread_interrupt_checkpoint (mb);
7323                 mono_mb_emit_byte (mb, CEE_RET);
7324 #endif
7325                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
7326                 info->d.managed_to_native.method = method;
7327
7328                 csig = signature_dup (method->klass->image, csig);
7329                 csig->pinvoke = 0;
7330                 res = mono_mb_create_and_cache_full (cache, method, mb, csig, csig->param_count + 16,
7331                                                                                          info, NULL);
7332
7333                 mono_mb_free (mb);
7334                 return res;
7335         }
7336
7337         g_assert (pinvoke);
7338         if (!aot)
7339                 g_assert (piinfo->addr);
7340
7341 #ifndef DISABLE_JIT
7342         mspecs = g_new (MonoMarshalSpec*, sig->param_count + 1);
7343         mono_method_get_marshal_info (method, mspecs);
7344
7345         mono_marshal_emit_native_wrapper (mb->method->klass->image, mb, sig, piinfo, mspecs, piinfo->addr, aot, check_exceptions, FALSE);
7346 #endif
7347         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_PINVOKE);
7348         info->d.managed_to_native.method = method;
7349
7350         csig = signature_dup (method->klass->image, sig);
7351         csig->pinvoke = 0;
7352         res = mono_mb_create_and_cache_full (cache, method, mb, csig, csig->param_count + 16,
7353                                                                                  info, NULL);
7354         mono_mb_free (mb);
7355
7356 #ifndef DISABLE_JIT
7357         for (i = sig->param_count; i >= 0; i--)
7358                 if (mspecs [i])
7359                         mono_metadata_free_marshal_spec (mspecs [i]);
7360         g_free (mspecs);
7361 #endif
7362
7363         /* code_for (res); */
7364
7365         return res;
7366 }
7367
7368 /**
7369  * mono_marshal_get_native_func_wrapper:
7370  * @image: The image to use for memory allocation and for looking up custom marshallers.
7371  * @sig: The signature of the function
7372  * @func: The native function to wrap
7373  *
7374  *   Returns a wrapper method around native functions, similar to the pinvoke
7375  * wrapper.
7376  */
7377 MonoMethod *
7378 mono_marshal_get_native_func_wrapper (MonoImage *image, MonoMethodSignature *sig, 
7379                                                                           MonoMethodPInvoke *piinfo, MonoMarshalSpec **mspecs, gpointer func)
7380 {
7381         MonoMethodSignature *csig;
7382
7383         SignaturePointerPair key, *new_key;
7384         MonoMethodBuilder *mb;
7385         MonoMethod *res;
7386         GHashTable *cache;
7387         gboolean found;
7388         char *name;
7389
7390         key.sig = sig;
7391         key.pointer = func;
7392
7393         cache = get_cache (&image->native_func_wrapper_cache, signature_pointer_pair_hash, signature_pointer_pair_equal);
7394         if ((res = mono_marshal_find_in_cache (cache, &key)))
7395                 return res;
7396
7397         name = g_strdup_printf ("wrapper_native_%p", func);
7398         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
7399         mb->method->save_lmf = 1;
7400
7401 #ifndef DISABLE_JIT
7402         mono_marshal_emit_native_wrapper (image, mb, sig, piinfo, mspecs, func, FALSE, TRUE, FALSE);
7403 #endif
7404
7405         csig = signature_dup (image, sig);
7406         csig->pinvoke = 0;
7407
7408         new_key = g_new (SignaturePointerPair,1);
7409         new_key->sig = csig;
7410         new_key->pointer = func;
7411
7412         res = mono_mb_create_and_cache_full (cache, new_key, mb, csig, csig->param_count + 16, NULL, &found);
7413         if (found)
7414                 g_free (new_key);
7415
7416         mono_mb_free (mb);
7417
7418         mono_marshal_set_wrapper_info (res, NULL);
7419
7420         return res;
7421 }
7422
7423 /*
7424  * The wrapper receives the native function as a boxed IntPtr as its 'this' argument. This is easier to support in
7425  * AOT.
7426  */
7427 MonoMethod*
7428 mono_marshal_get_native_func_wrapper_aot (MonoClass *klass)
7429 {
7430         MonoMethodSignature *sig, *csig;
7431         MonoMethodBuilder *mb;
7432         MonoMethod *res;
7433         GHashTable *cache;
7434         char *name;
7435         WrapperInfo *info;
7436         MonoMethodPInvoke mpiinfo;
7437         MonoMethodPInvoke *piinfo = &mpiinfo;
7438         MonoMarshalSpec **mspecs;
7439         MonoMethod *invoke = mono_get_delegate_invoke (klass);
7440         MonoImage *image = invoke->klass->image;
7441         int i;
7442
7443         // FIXME: include UnmanagedFunctionPointerAttribute info
7444
7445         /*
7446          * The wrapper is associated with the delegate type, to pick up the marshalling info etc.
7447          */
7448         cache = get_cache (&image->native_func_wrapper_aot_cache, mono_aligned_addr_hash, NULL);
7449         if ((res = mono_marshal_find_in_cache (cache, invoke)))
7450                 return res;
7451
7452         memset (&mpiinfo, 0, sizeof (mpiinfo));
7453         parse_unmanaged_function_pointer_attr (klass, &mpiinfo);
7454
7455         mspecs = g_new0 (MonoMarshalSpec*, mono_method_signature (invoke)->param_count + 1);
7456         mono_method_get_marshal_info (invoke, mspecs);
7457         /* Freed below so don't alloc from mempool */
7458         sig = mono_metadata_signature_dup (mono_method_signature (invoke));
7459         sig->hasthis = 0;
7460
7461         name = g_strdup_printf ("wrapper_aot_native");
7462         mb = mono_mb_new (invoke->klass, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
7463         mb->method->save_lmf = 1;
7464
7465 #ifndef DISABLE_JIT
7466         mono_marshal_emit_native_wrapper (image, mb, sig, piinfo, mspecs, NULL, FALSE, TRUE, TRUE);
7467 #endif
7468
7469         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NATIVE_FUNC_AOT);
7470         info->d.managed_to_native.method = invoke;
7471
7472         g_assert (!sig->hasthis);
7473         csig = signature_dup_add_this (image, sig, mono_defaults.int_class);
7474         csig->pinvoke = 0;
7475         res = mono_mb_create_and_cache_full (cache, invoke,
7476                                                                                  mb, csig, csig->param_count + 16,
7477                                                                                  info, NULL);
7478         mono_mb_free (mb);
7479
7480         for (i = mono_method_signature (invoke)->param_count; i >= 0; i--)
7481                 if (mspecs [i])
7482                         mono_metadata_free_marshal_spec (mspecs [i]);
7483         g_free (mspecs);
7484         g_free (sig);
7485
7486         return res;
7487 }
7488
7489 /*
7490  * mono_marshal_emit_managed_wrapper:
7491  *
7492  *   Emit the body of a native-to-managed wrapper. INVOKE_SIG is the signature of
7493  * the delegate which wraps the managed method to be called. For closed delegates,
7494  * it could have fewer parameters than the method it wraps.
7495  * THIS_LOC is the memory location where the target of the delegate is stored.
7496  */
7497 void
7498 mono_marshal_emit_managed_wrapper (MonoMethodBuilder *mb, MonoMethodSignature *invoke_sig, MonoMarshalSpec **mspecs, EmitMarshalContext* m, MonoMethod *method, uint32_t target_handle)
7499 {
7500 #ifdef DISABLE_JIT
7501         MonoMethodSignature *sig, *csig;
7502         int i;
7503
7504         sig = m->sig;
7505         csig = m->csig;
7506
7507         /* we first do all conversions */
7508         for (i = 0; i < sig->param_count; i ++) {
7509                 MonoType *t = sig->params [i];
7510
7511                 switch (t->type) {
7512                 case MONO_TYPE_OBJECT:
7513                 case MONO_TYPE_CLASS:
7514                 case MONO_TYPE_VALUETYPE:
7515                 case MONO_TYPE_ARRAY:
7516                 case MONO_TYPE_SZARRAY:
7517                 case MONO_TYPE_STRING:
7518                 case MONO_TYPE_BOOLEAN:
7519                         emit_marshal (m, i, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_MANAGED_CONV_IN);
7520                 }
7521         }
7522
7523         if (!sig->ret->byref) {
7524                 switch (sig->ret->type) {
7525                 case MONO_TYPE_STRING:
7526                         csig->ret = &mono_defaults.int_class->byval_arg;
7527                         break;
7528                 default:
7529                         break;
7530                 }
7531         }
7532 #else
7533         MonoMethodSignature *sig, *csig;
7534         int i, *tmp_locals;
7535         gboolean closed = FALSE;
7536
7537         sig = m->sig;
7538         csig = m->csig;
7539
7540         /* allocate local 0 (pointer) src_ptr */
7541         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7542         /* allocate local 1 (pointer) dst_ptr */
7543         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7544         /* allocate local 2 (boolean) delete_old */
7545         mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
7546
7547         if (!sig->hasthis && sig->param_count != invoke_sig->param_count) {
7548                 /* Closed delegate */
7549                 g_assert (sig->param_count == invoke_sig->param_count + 1);
7550                 closed = TRUE;
7551                 /* Use a new signature without the first argument */
7552                 sig = mono_metadata_signature_dup (sig);
7553                 memmove (&sig->params [0], &sig->params [1], (sig->param_count - 1) * sizeof (MonoType*));
7554                 sig->param_count --;
7555         }
7556
7557         if (!MONO_TYPE_IS_VOID(sig->ret)) {
7558                 /* allocate local 3 to store the return value */
7559                 mono_mb_add_local (mb, sig->ret);
7560         }
7561
7562         mono_mb_emit_icon (mb, 0);
7563         mono_mb_emit_stloc (mb, 2);
7564
7565         /*
7566          * Might need to attach the thread to the JIT or change the
7567          * domain for the callback.
7568          */
7569         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7570         mono_mb_emit_byte (mb, CEE_MONO_JIT_ATTACH);
7571
7572         /* we first do all conversions */
7573         tmp_locals = alloca (sizeof (int) * sig->param_count);
7574         for (i = 0; i < sig->param_count; i ++) {
7575                 MonoType *t = sig->params [i];
7576
7577                 switch (t->type) {
7578                 case MONO_TYPE_OBJECT:
7579                 case MONO_TYPE_CLASS:
7580                 case MONO_TYPE_VALUETYPE:
7581                 case MONO_TYPE_ARRAY:
7582                 case MONO_TYPE_SZARRAY:
7583                 case MONO_TYPE_STRING:
7584                 case MONO_TYPE_BOOLEAN:
7585                         tmp_locals [i] = emit_marshal (m, i, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_MANAGED_CONV_IN);
7586
7587                         break;
7588                 default:
7589                         tmp_locals [i] = 0;
7590                         break;
7591                 }
7592         }
7593
7594         emit_thread_interrupt_checkpoint (mb);
7595
7596         if (sig->hasthis) {
7597                 if (target_handle) {
7598                         mono_mb_emit_icon (mb, (gint32)target_handle);
7599                         mono_mb_emit_icall (mb, mono_gchandle_get_target);
7600                 } else {
7601                         /* fixme: */
7602                         g_assert_not_reached ();
7603                 }
7604         } else if (closed) {
7605                 mono_mb_emit_icon (mb, (gint32)target_handle);
7606                 mono_mb_emit_icall (mb, mono_gchandle_get_target);
7607         }
7608
7609         for (i = 0; i < sig->param_count; i++) {
7610                 MonoType *t = sig->params [i];
7611
7612                 if (tmp_locals [i]) {
7613                         if (t->byref)
7614                                 mono_mb_emit_ldloc_addr (mb, tmp_locals [i]);
7615                         else
7616                                 mono_mb_emit_ldloc (mb, tmp_locals [i]);
7617                 }
7618                 else
7619                         mono_mb_emit_ldarg (mb, i);
7620         }
7621
7622         mono_mb_emit_managed_call (mb, method, NULL);
7623
7624         if (mspecs [0] && mspecs [0]->native == MONO_NATIVE_CUSTOM) {
7625                 emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
7626         } else if (!sig->ret->byref) { 
7627                 switch (sig->ret->type) {
7628                 case MONO_TYPE_VOID:
7629                         break;
7630                 case MONO_TYPE_BOOLEAN:
7631                 case MONO_TYPE_I1:
7632                 case MONO_TYPE_U1:
7633                 case MONO_TYPE_CHAR:
7634                 case MONO_TYPE_I2:
7635                 case MONO_TYPE_U2:
7636                 case MONO_TYPE_I4:
7637                 case MONO_TYPE_U4:
7638                 case MONO_TYPE_I:
7639                 case MONO_TYPE_U:
7640                 case MONO_TYPE_PTR:
7641                 case MONO_TYPE_R4:
7642                 case MONO_TYPE_R8:
7643                 case MONO_TYPE_I8:
7644                 case MONO_TYPE_U8:
7645                 case MONO_TYPE_OBJECT:
7646                         mono_mb_emit_stloc (mb, 3);
7647                         break;
7648                 case MONO_TYPE_STRING:
7649                         csig->ret = &mono_defaults.int_class->byval_arg;
7650                         emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
7651                         break;
7652                 case MONO_TYPE_VALUETYPE:
7653                 case MONO_TYPE_CLASS:
7654                 case MONO_TYPE_SZARRAY:
7655                         emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
7656                         break;
7657                 default:
7658                         g_warning ("return type 0x%02x unknown", sig->ret->type);       
7659                         g_assert_not_reached ();
7660                 }
7661         } else {
7662                 mono_mb_emit_stloc (mb, 3);
7663         }
7664
7665         /* Convert byref arguments back */
7666         for (i = 0; i < sig->param_count; i ++) {
7667                 MonoType *t = sig->params [i];
7668                 MonoMarshalSpec *spec = mspecs [i + 1];
7669
7670                 if (spec && spec->native == MONO_NATIVE_CUSTOM) {
7671                         emit_marshal (m, i, t, mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
7672                 }
7673                 else if (t->byref) {
7674                         switch (t->type) {
7675                         case MONO_TYPE_CLASS:
7676                         case MONO_TYPE_VALUETYPE:
7677                         case MONO_TYPE_OBJECT:
7678                         case MONO_TYPE_STRING:
7679                         case MONO_TYPE_BOOLEAN:
7680                                 emit_marshal (m, i, t, mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
7681                                 break;
7682                         default:
7683                                 break;
7684                         }
7685                 }
7686                 else if (invoke_sig->params [i]->attrs & PARAM_ATTRIBUTE_OUT) {
7687                         /* The [Out] information is encoded in the delegate signature */
7688                         switch (t->type) {
7689                         case MONO_TYPE_SZARRAY:
7690                         case MONO_TYPE_CLASS:
7691                         case MONO_TYPE_VALUETYPE:
7692                                 emit_marshal (m, i, invoke_sig->params [i], mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
7693                                 break;
7694                         default:
7695                                 g_assert_not_reached ();
7696                         }
7697                 }
7698         }
7699
7700         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7701         mono_mb_emit_byte (mb, CEE_MONO_JIT_DETACH);
7702
7703         if (m->retobj_var) {
7704                 mono_mb_emit_ldloc (mb, m->retobj_var);
7705                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7706                 mono_mb_emit_op (mb, CEE_MONO_RETOBJ, m->retobj_class);
7707         }
7708         else {
7709                 if (!MONO_TYPE_IS_VOID(sig->ret))
7710                         mono_mb_emit_ldloc (mb, 3);
7711                 mono_mb_emit_byte (mb, CEE_RET);
7712         }
7713
7714         if (closed)
7715                 g_free (sig);
7716 #endif
7717 }
7718
7719 static void 
7720 mono_marshal_set_callconv_from_modopt (MonoMethod *method, MonoMethodSignature *csig)
7721 {
7722         MonoMethodSignature *sig;
7723         int i;
7724
7725 #ifdef TARGET_WIN32
7726         /* 
7727          * Under windows, delegates passed to native code must use the STDCALL
7728          * calling convention.
7729          */
7730         csig->call_convention = MONO_CALL_STDCALL;
7731 #endif
7732
7733         sig = mono_method_signature (method);
7734
7735         /* Change default calling convention if needed */
7736         /* Why is this a modopt ? */
7737         if (sig->ret && sig->ret->num_mods) {
7738                 for (i = 0; i < sig->ret->num_mods; ++i) {
7739                         MonoError error;
7740                         MonoClass *cmod_class = mono_class_get_checked (method->klass->image, sig->ret->modifiers [i].token, &error);
7741                         g_assert (mono_error_ok (&error));
7742                         if ((cmod_class->image == mono_defaults.corlib) && !strcmp (cmod_class->name_space, "System.Runtime.CompilerServices")) {
7743                                 if (!strcmp (cmod_class->name, "CallConvCdecl"))
7744                                         csig->call_convention = MONO_CALL_C;
7745                                 else if (!strcmp (cmod_class->name, "CallConvStdcall"))
7746                                         csig->call_convention = MONO_CALL_STDCALL;
7747                                 else if (!strcmp (cmod_class->name, "CallConvFastcall"))
7748                                         csig->call_convention = MONO_CALL_FASTCALL;
7749                                 else if (!strcmp (cmod_class->name, "CallConvThiscall"))
7750                                         csig->call_convention = MONO_CALL_THISCALL;
7751                         }
7752                 }
7753         }
7754 }
7755
7756 /*
7757  * generates IL code to call managed methods from unmanaged code 
7758  * If target_handle==0, the wrapper info will be a WrapperInfo structure.
7759  */
7760 MonoMethod *
7761 mono_marshal_get_managed_wrapper (MonoMethod *method, MonoClass *delegate_klass, uint32_t target_handle)
7762 {
7763         static MonoClass *UnmanagedFunctionPointerAttribute;
7764         MonoMethodSignature *sig, *csig, *invoke_sig;
7765         MonoMethodBuilder *mb;
7766         MonoMethod *res, *invoke;
7767         MonoMarshalSpec **mspecs;
7768         MonoMethodPInvoke piinfo;
7769         GHashTable *cache;
7770         int i;
7771         EmitMarshalContext m;
7772
7773         g_assert (method != NULL);
7774         g_assert (!mono_method_signature (method)->pinvoke);
7775
7776         /* 
7777          * FIXME: Should cache the method+delegate type pair, since the same method
7778          * could be called with different delegates, thus different marshalling
7779          * options.
7780          */
7781         cache = get_cache (&method->klass->image->managed_wrapper_cache, mono_aligned_addr_hash, NULL);
7782         if (!target_handle && (res = mono_marshal_find_in_cache (cache, method)))
7783                 return res;
7784
7785         invoke = mono_get_delegate_invoke (delegate_klass);
7786         invoke_sig = mono_method_signature (invoke);
7787
7788         mspecs = g_new0 (MonoMarshalSpec*, mono_method_signature (invoke)->param_count + 1);
7789         mono_method_get_marshal_info (invoke, mspecs);
7790
7791         sig = mono_method_signature (method);
7792
7793         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
7794
7795         /*the target gchandle must be the first entry after size and the wrapper itself.*/
7796         mono_mb_add_data (mb, GUINT_TO_POINTER (target_handle));
7797
7798         /* we copy the signature, so that we can modify it */
7799         if (target_handle)
7800                 /* Need to free this later */
7801                 csig = mono_metadata_signature_dup (invoke_sig);
7802         else
7803                 csig = signature_dup (method->klass->image, invoke_sig);
7804         csig->hasthis = 0;
7805         csig->pinvoke = 1;
7806
7807         memset (&m, 0, sizeof (m));
7808         m.mb = mb;
7809         m.sig = sig;
7810         m.piinfo = NULL;
7811         m.retobj_var = 0;
7812         m.csig = csig;
7813         m.image = method->klass->image;
7814
7815         mono_marshal_set_callconv_from_modopt (invoke, csig);
7816
7817         /* Handle the UnmanagedFunctionPointerAttribute */
7818         if (!UnmanagedFunctionPointerAttribute)
7819                 UnmanagedFunctionPointerAttribute = mono_class_from_name (mono_defaults.corlib, "System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute");
7820
7821         /* The attribute is only available in Net 2.0 */
7822         if (UnmanagedFunctionPointerAttribute) {
7823                 MonoCustomAttrInfo *cinfo;
7824                 MonoCustomAttrEntry *attr;
7825
7826                 /* 
7827                  * The pinvoke attributes are stored in a real custom attribute. Obtain the
7828                  * contents of the attribute without constructing it, as that might not be
7829                  * possible when running in cross-compiling mode.
7830                  */
7831                 cinfo = mono_custom_attrs_from_class (delegate_klass);
7832                 attr = NULL;
7833                 if (cinfo) {
7834                         for (i = 0; i < cinfo->num_attrs; ++i) {
7835                                 MonoClass *ctor_class = cinfo->attrs [i].ctor->klass;
7836                                 if (mono_class_has_parent (ctor_class, UnmanagedFunctionPointerAttribute)) {
7837                                         attr = &cinfo->attrs [i];
7838                                         break;
7839                                 }
7840                         }
7841                 }
7842                 if (attr) {
7843                         MonoArray *typed_args, *named_args;
7844                         CattrNamedArg *arginfo;
7845                         MonoObject *o;
7846                         gint32 call_conv;
7847                         gint32 charset = 0;
7848                         MonoBoolean set_last_error = 0;
7849                         MonoError error;
7850
7851                         mono_reflection_create_custom_attr_data_args (mono_defaults.corlib, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7852                         g_assert (mono_error_ok (&error));
7853                         g_assert (mono_array_length (typed_args) == 1);
7854
7855                         /* typed args */
7856                         o = mono_array_get (typed_args, MonoObject*, 0);
7857                         call_conv = *(gint32*)mono_object_unbox (o);
7858
7859                         /* named args */
7860                         for (i = 0; i < mono_array_length (named_args); ++i) {
7861                                 CattrNamedArg *narg = &arginfo [i];
7862
7863                                 o = mono_array_get (named_args, MonoObject*, i);
7864
7865                                 g_assert (narg->field);
7866                                 if (!strcmp (narg->field->name, "CharSet")) {
7867                                         charset = *(gint32*)mono_object_unbox (o);
7868                                 } else if (!strcmp (narg->field->name, "SetLastError")) {
7869                                         set_last_error = *(MonoBoolean*)mono_object_unbox (o);
7870                                 } else if (!strcmp (narg->field->name, "BestFitMapping")) {
7871                                         // best_fit_mapping = *(MonoBoolean*)mono_object_unbox (o);
7872                                 } else if (!strcmp (narg->field->name, "ThrowOnUnmappableChar")) {
7873                                         // throw_on_unmappable = *(MonoBoolean*)mono_object_unbox (o);
7874                                 } else {
7875                                         g_assert_not_reached ();
7876                                 }
7877                         }
7878
7879                         g_free (arginfo);
7880
7881                         memset (&piinfo, 0, sizeof (piinfo));
7882                         m.piinfo = &piinfo;
7883                         piinfo.piflags = (call_conv << 8) | (charset ? (charset - 1) * 2 : 1) | set_last_error;
7884
7885                         csig->call_convention = call_conv - 1;
7886                 }
7887
7888                 if (cinfo && !cinfo->cached)
7889                         mono_custom_attrs_free (cinfo);
7890         }
7891
7892         mono_marshal_emit_managed_wrapper (mb, invoke_sig, mspecs, &m, method, target_handle);
7893
7894         if (!target_handle) {
7895                 WrapperInfo *info;
7896
7897                 // FIXME: Associate it with the method+delegate_klass pair
7898                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
7899                 info->d.native_to_managed.method = method;
7900                 info->d.native_to_managed.klass = delegate_klass;
7901
7902                 res = mono_mb_create_and_cache_full (cache, method,
7903                                                                                          mb, csig, sig->param_count + 16,
7904                                                                                          info, NULL);
7905         } else {
7906 #ifndef DISABLE_JIT
7907                 mb->dynamic = 1;
7908 #endif
7909                 res = mono_mb_create (mb, csig, sig->param_count + 16, NULL);
7910         }
7911         mono_mb_free (mb);
7912
7913         for (i = mono_method_signature (invoke)->param_count; i >= 0; i--)
7914                 if (mspecs [i])
7915                         mono_metadata_free_marshal_spec (mspecs [i]);
7916         g_free (mspecs);
7917
7918         /* code_for (res); */
7919
7920         return res;
7921 }
7922
7923 gpointer
7924 mono_marshal_get_vtfixup_ftnptr (MonoImage *image, guint32 token, guint16 type)
7925 {
7926         MonoMethod *method;
7927         MonoMethodSignature *sig;
7928         MonoMethodBuilder *mb;
7929         int i, param_count;
7930
7931         g_assert (token);
7932
7933         method = mono_get_method (image, token, NULL);
7934         g_assert (method);
7935
7936         if (type & (VTFIXUP_TYPE_FROM_UNMANAGED | VTFIXUP_TYPE_FROM_UNMANAGED_RETAIN_APPDOMAIN)) {
7937                 MonoMethodSignature *csig;
7938                 MonoMarshalSpec **mspecs;
7939                 EmitMarshalContext m;
7940
7941                 sig = mono_method_signature (method);
7942                 g_assert (!sig->hasthis);
7943
7944                 mspecs = g_new0 (MonoMarshalSpec*, sig->param_count + 1);
7945                 mono_method_get_marshal_info (method, mspecs);
7946
7947                 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
7948                 csig = signature_dup (image, sig);
7949                 csig->hasthis = 0;
7950                 csig->pinvoke = 1;
7951
7952                 memset (&m, 0, sizeof (m));
7953                 m.mb = mb;
7954                 m.sig = sig;
7955                 m.piinfo = NULL;
7956                 m.retobj_var = 0;
7957                 m.csig = csig;
7958                 m.image = image;
7959
7960                 mono_marshal_set_callconv_from_modopt (method, csig);
7961
7962                 /* FIXME: Implement VTFIXUP_TYPE_FROM_UNMANAGED_RETAIN_APPDOMAIN. */
7963
7964                 mono_marshal_emit_managed_wrapper (mb, sig, mspecs, &m, method, 0);
7965
7966 #ifndef DISABLE_JIT
7967                 mb->dynamic = 1;
7968 #endif
7969                 method = mono_mb_create (mb, csig, sig->param_count + 16, NULL);
7970                 mono_mb_free (mb);
7971
7972                 for (i = sig->param_count; i >= 0; i--)
7973                         if (mspecs [i])
7974                                 mono_metadata_free_marshal_spec (mspecs [i]);
7975                 g_free (mspecs);
7976
7977                 return mono_compile_method (method);
7978         }
7979
7980         sig = mono_method_signature (method);
7981         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_MANAGED);
7982
7983         param_count = sig->param_count + sig->hasthis;
7984 #ifndef DISABLE_JIT
7985         for (i = 0; i < param_count; i++)
7986                 mono_mb_emit_ldarg (mb, i);
7987
7988         if (type & VTFIXUP_TYPE_CALL_MOST_DERIVED)
7989                 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
7990         else
7991                 mono_mb_emit_op (mb, CEE_CALL, method);
7992         mono_mb_emit_byte (mb, CEE_RET);
7993
7994         mb->dynamic = 1;
7995 #endif
7996
7997         method = mono_mb_create (mb, sig, param_count, NULL);
7998         mono_mb_free (mb);
7999
8000         return mono_compile_method (method);
8001 }
8002
8003 /*
8004  * This does the equivalent of mono_object_castclass_with_cache.
8005  * The wrapper info for the wrapper is a WrapperInfo structure.
8006  */
8007 MonoMethod *
8008 mono_marshal_get_castclass_with_cache (void)
8009 {
8010         static MonoMethod *cached;
8011         MonoMethod *res;
8012         MonoMethodBuilder *mb;
8013         MonoMethodSignature *sig;
8014         int return_null_pos, cache_miss_pos, invalid_cast_pos;
8015         WrapperInfo *info;
8016
8017         if (cached)
8018                 return cached;
8019
8020         mb = mono_mb_new (mono_defaults.object_class, "__castclass_with_cache", MONO_WRAPPER_CASTCLASS);
8021         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
8022         sig->params [0] = &mono_defaults.object_class->byval_arg;
8023         sig->params [1] = &mono_defaults.int_class->byval_arg;
8024         sig->params [2] = &mono_defaults.int_class->byval_arg;
8025         sig->ret = &mono_defaults.object_class->byval_arg;
8026         sig->pinvoke = 0;
8027
8028 #ifndef DISABLE_JIT
8029         /* allocate local 0 (pointer) obj_vtable */
8030         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8031
8032         /*if (!obj)*/
8033         mono_mb_emit_ldarg (mb, 0);
8034         return_null_pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
8035
8036         /*obj_vtable = obj->vtable;*/
8037         mono_mb_emit_ldarg (mb, 0);
8038         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
8039         mono_mb_emit_byte (mb, CEE_LDIND_I);
8040         mono_mb_emit_stloc (mb, 0);
8041
8042         /* *cache */
8043         mono_mb_emit_ldarg (mb, 2);
8044         mono_mb_emit_byte (mb, CEE_LDIND_I);
8045         mono_mb_emit_ldloc (mb, 0);
8046
8047         /*if (*cache == obj_vtable)*/
8048         cache_miss_pos = mono_mb_emit_branch (mb, CEE_BNE_UN);
8049
8050         /*return obj;*/
8051         mono_mb_emit_ldarg (mb, 0);
8052         mono_mb_emit_byte (mb, CEE_RET);
8053
8054         mono_mb_patch_branch (mb, cache_miss_pos);
8055         /*if (mono_object_isinst (obj, klass)) */
8056         mono_mb_emit_ldarg (mb, 0);
8057         mono_mb_emit_ldarg (mb, 1);
8058         mono_mb_emit_icall (mb, mono_object_isinst);
8059         invalid_cast_pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
8060
8061         /**cache = obj_vtable;*/
8062         mono_mb_emit_ldarg (mb, 2);
8063         mono_mb_emit_ldloc (mb, 0);
8064         mono_mb_emit_byte (mb, CEE_STIND_I);
8065
8066         /*return obj;*/
8067         mono_mb_emit_ldarg (mb, 0);
8068         mono_mb_emit_byte (mb, CEE_RET);
8069
8070         /*fails*/
8071         mono_mb_patch_branch (mb, invalid_cast_pos);
8072         mono_mb_emit_exception (mb, "InvalidCastException", NULL);
8073
8074         /*return null*/
8075         mono_mb_patch_branch (mb, return_null_pos);
8076         mono_mb_emit_byte (mb, CEE_LDNULL);
8077         mono_mb_emit_byte (mb, CEE_RET);
8078 #endif /* DISABLE_JIT */
8079
8080         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE);
8081         res = mono_mb_create (mb, sig, 8, info);
8082         STORE_STORE_FENCE;
8083
8084         if (InterlockedCompareExchangePointer ((volatile gpointer *)&cached, res, NULL)) {
8085                 mono_free_method (res);
8086                 mono_metadata_free_method_signature (sig);
8087         }
8088         mono_mb_free (mb);
8089
8090         return cached;
8091 }
8092
8093 /*
8094  * This does the equivalent of mono_object_isinst_with_cache.
8095  * The wrapper info for the wrapper is a WrapperInfo structure.
8096  */
8097 MonoMethod *
8098 mono_marshal_get_isinst_with_cache (void)
8099 {
8100         static MonoMethod *cached;
8101         MonoMethod *res;
8102         MonoMethodBuilder *mb;
8103         MonoMethodSignature *sig;
8104         int return_null_pos, cache_miss_pos, cache_hit_pos, not_an_instance_pos, negative_cache_hit_pos;
8105         WrapperInfo *info;
8106
8107         if (cached)
8108                 return cached;
8109
8110         mb = mono_mb_new (mono_defaults.object_class, "__isinst_with_cache", MONO_WRAPPER_CASTCLASS);
8111         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
8112         sig->params [0] = &mono_defaults.object_class->byval_arg;
8113         sig->params [1] = &mono_defaults.int_class->byval_arg;
8114         sig->params [2] = &mono_defaults.int_class->byval_arg;
8115         sig->ret = &mono_defaults.object_class->byval_arg;
8116         sig->pinvoke = 0;
8117
8118 #ifndef DISABLE_JIT
8119         /* allocate local 0 (pointer) obj_vtable */
8120         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8121         /* allocate local 1 (pointer) cached_vtable */
8122         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8123
8124         /*if (!obj)*/
8125         mono_mb_emit_ldarg (mb, 0);
8126         return_null_pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
8127
8128         /*obj_vtable = obj->vtable;*/
8129         mono_mb_emit_ldarg (mb, 0);
8130         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
8131         mono_mb_emit_byte (mb, CEE_LDIND_I);
8132         mono_mb_emit_stloc (mb, 0);
8133
8134         /* cached_vtable = *cache*/
8135         mono_mb_emit_ldarg (mb, 2);
8136         mono_mb_emit_byte (mb, CEE_LDIND_I);
8137         mono_mb_emit_stloc (mb, 1);
8138
8139         mono_mb_emit_ldloc (mb, 1);
8140         mono_mb_emit_byte (mb, CEE_LDC_I4);
8141         mono_mb_emit_i4 (mb, ~0x1);
8142         mono_mb_emit_byte (mb, CEE_CONV_I);
8143         mono_mb_emit_byte (mb, CEE_AND);
8144         mono_mb_emit_ldloc (mb, 0);
8145         /*if ((cached_vtable & ~0x1)== obj_vtable)*/
8146         cache_miss_pos = mono_mb_emit_branch (mb, CEE_BNE_UN);
8147
8148         /*return (cached_vtable & 0x1) ? NULL : obj;*/
8149         mono_mb_emit_ldloc (mb, 1);
8150         mono_mb_emit_byte(mb, CEE_LDC_I4_1);
8151         mono_mb_emit_byte (mb, CEE_CONV_U);
8152         mono_mb_emit_byte (mb, CEE_AND);
8153         negative_cache_hit_pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
8154
8155         /*obj*/
8156         mono_mb_emit_ldarg (mb, 0);
8157         cache_hit_pos = mono_mb_emit_branch (mb, CEE_BR);
8158
8159         /*NULL*/
8160         mono_mb_patch_branch (mb, negative_cache_hit_pos);
8161         mono_mb_emit_byte (mb, CEE_LDNULL);
8162
8163         mono_mb_patch_branch (mb, cache_hit_pos);
8164         mono_mb_emit_byte (mb, CEE_RET);
8165
8166         mono_mb_patch_branch (mb, cache_miss_pos);
8167         /*if (mono_object_isinst (obj, klass)) */
8168         mono_mb_emit_ldarg (mb, 0);
8169         mono_mb_emit_ldarg (mb, 1);
8170         mono_mb_emit_icall (mb, mono_object_isinst);
8171         not_an_instance_pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
8172
8173         /**cache = obj_vtable;*/
8174         mono_mb_emit_ldarg (mb, 2);
8175         mono_mb_emit_ldloc (mb, 0);
8176         mono_mb_emit_byte (mb, CEE_STIND_I);
8177
8178         /*return obj;*/
8179         mono_mb_emit_ldarg (mb, 0);
8180         mono_mb_emit_byte (mb, CEE_RET);
8181
8182         /*not an instance*/
8183         mono_mb_patch_branch (mb, not_an_instance_pos);
8184         /* *cache = (gpointer)(obj_vtable | 0x1);*/
8185         mono_mb_emit_ldarg (mb, 2);
8186         /*obj_vtable | 0x1*/
8187         mono_mb_emit_ldloc (mb, 0);
8188         mono_mb_emit_byte(mb, CEE_LDC_I4_1);
8189         mono_mb_emit_byte (mb, CEE_CONV_U);
8190         mono_mb_emit_byte (mb, CEE_OR);
8191
8192         /* *cache = ... */
8193         mono_mb_emit_byte (mb, CEE_STIND_I);
8194
8195         /*return null*/
8196         mono_mb_patch_branch (mb, return_null_pos);
8197         mono_mb_emit_byte (mb, CEE_LDNULL);
8198         mono_mb_emit_byte (mb, CEE_RET);
8199 #endif
8200
8201         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ISINST_WITH_CACHE);
8202         res = mono_mb_create (mb, sig, 8, info);
8203         STORE_STORE_FENCE;
8204
8205         if (InterlockedCompareExchangePointer ((volatile gpointer *)&cached, res, NULL)) {
8206                 mono_free_method (res);
8207                 mono_metadata_free_method_signature (sig);
8208         }
8209         mono_mb_free (mb);
8210
8211         return cached;
8212 }
8213
8214 /*
8215  * mono_marshal_get_isinst:
8216  * @klass: the type of the field
8217  *
8218  * This method generates a function which can be used to check if an object is
8219  * an instance of the given type, icluding the case where the object is a proxy.
8220  * The generated function has the following signature:
8221  * MonoObject* __isinst_wrapper_ (MonoObject *obj)
8222  */
8223 MonoMethod *
8224 mono_marshal_get_isinst (MonoClass *klass)
8225 {
8226         static MonoMethodSignature *isint_sig = NULL;
8227         GHashTable *cache;
8228         MonoMethod *res;
8229         WrapperInfo *info;
8230         int pos_was_ok, pos_end;
8231 #ifndef DISABLE_REMOTING
8232         int pos_end2, pos_failed;
8233 #endif
8234         char *name;
8235         MonoMethodBuilder *mb;
8236
8237         cache = get_cache (&klass->image->isinst_cache, mono_aligned_addr_hash, NULL);
8238         if ((res = mono_marshal_find_in_cache (cache, klass)))
8239                 return res;
8240
8241         if (!isint_sig) {
8242                 isint_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
8243                 isint_sig->params [0] = &mono_defaults.object_class->byval_arg;
8244                 isint_sig->ret = &mono_defaults.object_class->byval_arg;
8245                 isint_sig->pinvoke = 0;
8246         }
8247         
8248         name = g_strdup_printf ("__isinst_wrapper_%s", klass->name); 
8249         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_ISINST);
8250         g_free (name);
8251         
8252         mb->method->save_lmf = 1;
8253
8254 #ifndef DISABLE_JIT
8255         /* check if the object is a proxy that needs special cast */
8256         mono_mb_emit_ldarg (mb, 0);
8257         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8258         mono_mb_emit_op (mb, CEE_MONO_CISINST, klass);
8259
8260         /* The result of MONO_CISINST can be:
8261                 0) the type check succeeded
8262                 1) the type check did not succeed
8263                 2) a CanCastTo call is needed */
8264 #ifndef DISABLE_REMOTING
8265         mono_mb_emit_byte (mb, CEE_DUP);
8266         pos_was_ok = mono_mb_emit_branch (mb, CEE_BRFALSE);
8267
8268         mono_mb_emit_byte (mb, CEE_LDC_I4_2);
8269         pos_failed = mono_mb_emit_branch (mb, CEE_BNE_UN);
8270         
8271         /* get the real proxy from the transparent proxy*/
8272
8273         mono_mb_emit_ldarg (mb, 0);
8274         mono_mb_emit_managed_call (mb, mono_marshal_get_proxy_cancast (klass), NULL);
8275         pos_end = mono_mb_emit_branch (mb, CEE_BR);
8276         
8277         /* fail */
8278         
8279         mono_mb_patch_branch (mb, pos_failed);
8280         mono_mb_emit_byte (mb, CEE_LDNULL);
8281         pos_end2 = mono_mb_emit_branch (mb, CEE_BR);
8282         
8283         /* success */
8284         
8285         mono_mb_patch_branch (mb, pos_was_ok);
8286         mono_mb_emit_byte (mb, CEE_POP);
8287         mono_mb_emit_ldarg (mb, 0);
8288         
8289         /* the end */
8290         
8291         mono_mb_patch_branch (mb, pos_end);
8292         mono_mb_patch_branch (mb, pos_end2);
8293         mono_mb_emit_byte (mb, CEE_RET);
8294 #else
8295         pos_was_ok = mono_mb_emit_branch (mb, CEE_BRFALSE);
8296
8297         /* fail */
8298
8299         mono_mb_emit_byte (mb, CEE_LDNULL);
8300         pos_end = mono_mb_emit_branch (mb, CEE_BR);
8301
8302         /* success */
8303
8304         mono_mb_patch_branch (mb, pos_was_ok);
8305         mono_mb_emit_ldarg (mb, 0);
8306
8307         /* the end */
8308
8309         mono_mb_patch_branch (mb, pos_end);
8310         mono_mb_emit_byte (mb, CEE_RET);
8311 #endif /* DISABLE_REMOTING */
8312 #endif /* DISABLE_JIT */
8313
8314         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
8315         info->d.proxy.klass = klass;
8316         res = mono_mb_create_and_cache_full (cache, klass, mb, isint_sig, isint_sig->param_count + 16, info, NULL);
8317         mono_mb_free (mb);
8318
8319         return res;
8320 }
8321
8322 /*
8323  * mono_marshal_get_castclass:
8324  * @klass: the type of the field
8325  *
8326  * This method generates a function which can be used to cast an object to
8327  * an instance of the given type, icluding the case where the object is a proxy.
8328  * The generated function has the following signature:
8329  * MonoObject* __castclass_wrapper_ (MonoObject *obj)
8330  * The wrapper info for the wrapper is a WrapperInfo structure.
8331  */
8332 MonoMethod *
8333 mono_marshal_get_castclass (MonoClass *klass)
8334 {
8335         static MonoMethodSignature *castclass_sig = NULL;
8336         GHashTable *cache;
8337         MonoMethod *res;
8338 #ifndef DISABLE_REMOTING
8339         int pos_was_ok, pos_was_ok2;
8340 #endif
8341         char *name;
8342         MonoMethodBuilder *mb;
8343         WrapperInfo *info;
8344
8345         cache = get_cache (&klass->image->castclass_cache, mono_aligned_addr_hash, NULL);
8346         if ((res = mono_marshal_find_in_cache (cache, klass)))
8347                 return res;
8348
8349         if (!castclass_sig) {
8350                 castclass_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
8351                 castclass_sig->params [0] = &mono_defaults.object_class->byval_arg;
8352                 castclass_sig->ret = &mono_defaults.object_class->byval_arg;
8353                 castclass_sig->pinvoke = 0;
8354         }
8355         
8356         name = g_strdup_printf ("__castclass_wrapper_%s", klass->name); 
8357         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_CASTCLASS);
8358         g_free (name);
8359         
8360         mb->method->save_lmf = 1;
8361
8362 #ifndef DISABLE_JIT
8363         /* check if the object is a proxy that needs special cast */
8364         mono_mb_emit_ldarg (mb, 0);
8365         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8366         mono_mb_emit_op (mb, CEE_MONO_CCASTCLASS, klass);
8367
8368         /* The result of MONO_CCASTCLASS can be:
8369                 0) the cast is valid
8370                 1) cast of unknown proxy type
8371                 or an exception if the cast is is invalid
8372         */
8373 #ifndef DISABLE_REMOTING
8374         pos_was_ok = mono_mb_emit_branch (mb, CEE_BRFALSE);
8375
8376         /* get the real proxy from the transparent proxy*/
8377
8378         mono_mb_emit_ldarg (mb, 0);
8379         mono_mb_emit_managed_call (mb, mono_marshal_get_proxy_cancast (klass), NULL);
8380         pos_was_ok2 = mono_mb_emit_branch (mb, CEE_BRTRUE);
8381         
8382         /* fail */
8383         mono_mb_emit_exception (mb, "InvalidCastException", NULL);
8384         
8385         /* success */
8386         mono_mb_patch_branch (mb, pos_was_ok);
8387         mono_mb_patch_branch (mb, pos_was_ok2);
8388 #else
8389         /* MONO_CCASTCLASS leaves an int in the stack with the result, pop it. */
8390         mono_mb_emit_byte (mb, CEE_POP);
8391 #endif /* DISABLE_REMOTING */
8392
8393         mono_mb_emit_ldarg (mb, 0);
8394         
8395         /* the end */
8396         mono_mb_emit_byte (mb, CEE_RET);
8397 #endif /* DISABLE_JIT */
8398
8399         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
8400
8401         res = mono_mb_create_and_cache_full (cache, klass, mb, castclass_sig, castclass_sig->param_count + 16,
8402                                                                                  info, NULL);
8403         mono_mb_free (mb);
8404
8405         return res;
8406 }
8407
8408 /**
8409  * mono_marshal_get_struct_to_ptr:
8410  * @klass:
8411  *
8412  * generates IL code for StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld)
8413  * The wrapper info for the wrapper is a WrapperInfo structure.
8414  */
8415 MonoMethod *
8416 mono_marshal_get_struct_to_ptr (MonoClass *klass)
8417 {
8418         MonoMethodBuilder *mb;
8419         static MonoMethod *stoptr = NULL;
8420         MonoMethod *res;
8421         WrapperInfo *info;
8422
8423         g_assert (klass != NULL);
8424
8425         mono_marshal_load_type_info (klass);
8426
8427         if (klass->marshal_info->str_to_ptr)
8428                 return klass->marshal_info->str_to_ptr;
8429
8430         if (!stoptr) 
8431                 stoptr = mono_class_get_method_from_name (mono_defaults.marshal_class, "StructureToPtr", 3);
8432         g_assert (stoptr);
8433
8434         mb = mono_mb_new (klass, stoptr->name, MONO_WRAPPER_UNKNOWN);
8435
8436 #ifndef DISABLE_JIT
8437         if (klass->blittable) {
8438                 mono_mb_emit_byte (mb, CEE_LDARG_1);
8439                 mono_mb_emit_byte (mb, CEE_LDARG_0);
8440                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
8441                 mono_mb_emit_icon (mb, mono_class_value_size (klass, NULL));
8442                 mono_mb_emit_byte (mb, CEE_PREFIX1);
8443                 mono_mb_emit_byte (mb, CEE_CPBLK);
8444         } else {
8445
8446                 /* allocate local 0 (pointer) src_ptr */
8447                 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8448                 /* allocate local 1 (pointer) dst_ptr */
8449                 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8450                 /* allocate local 2 (boolean) delete_old */
8451                 mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
8452                 mono_mb_emit_byte (mb, CEE_LDARG_2);
8453                 mono_mb_emit_stloc (mb, 2);
8454
8455                 /* initialize src_ptr to point to the start of object data */
8456                 mono_mb_emit_byte (mb, CEE_LDARG_0);
8457                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
8458                 mono_mb_emit_stloc (mb, 0);
8459
8460                 /* initialize dst_ptr */
8461                 mono_mb_emit_byte (mb, CEE_LDARG_1);
8462                 mono_mb_emit_stloc (mb, 1);
8463
8464                 emit_struct_conv (mb, klass, FALSE);
8465         }
8466
8467         mono_mb_emit_byte (mb, CEE_RET);
8468 #endif
8469         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_STRUCTURE_TO_PTR);
8470         res = mono_mb_create (mb, mono_signature_no_pinvoke (stoptr), 0, info);
8471         mono_mb_free (mb);
8472
8473         klass->marshal_info->str_to_ptr = res;
8474         return res;
8475 }
8476
8477 /**
8478  * mono_marshal_get_ptr_to_struct:
8479  * @klass:
8480  *
8481  * generates IL code for PtrToStructure (IntPtr src, object structure)
8482  * The wrapper info for the wrapper is a WrapperInfo structure.
8483  */
8484 MonoMethod *
8485 mono_marshal_get_ptr_to_struct (MonoClass *klass)
8486 {
8487         MonoMethodBuilder *mb;
8488         static MonoMethodSignature *ptostr = NULL;
8489         MonoMethod *res;
8490         WrapperInfo *info;
8491
8492         g_assert (klass != NULL);
8493
8494         mono_marshal_load_type_info (klass);
8495
8496         if (klass->marshal_info->ptr_to_str)
8497                 return klass->marshal_info->ptr_to_str;
8498
8499         if (!ptostr) {
8500                 MonoMethodSignature *sig;
8501
8502                 /* Create the signature corresponding to
8503                           static void PtrToStructure (IntPtr ptr, object structure);
8504                    defined in class/corlib/System.Runtime.InteropServices/Marshal.cs */
8505                 sig = mono_create_icall_signature ("void ptr object");
8506                 sig = signature_dup (mono_defaults.corlib, sig);
8507                 sig->pinvoke = 0;
8508                 mono_memory_barrier ();
8509                 ptostr = sig;
8510         }
8511
8512         mb = mono_mb_new (klass, "PtrToStructure", MONO_WRAPPER_UNKNOWN);
8513
8514 #ifndef DISABLE_JIT
8515         if (klass->blittable) {
8516                 mono_mb_emit_byte (mb, CEE_LDARG_1);
8517                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
8518                 mono_mb_emit_byte (mb, CEE_LDARG_0);
8519                 mono_mb_emit_icon (mb, mono_class_value_size (klass, NULL));
8520                 mono_mb_emit_byte (mb, CEE_PREFIX1);
8521                 mono_mb_emit_byte (mb, CEE_CPBLK);
8522         } else {
8523
8524                 /* allocate local 0 (pointer) src_ptr */
8525                 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8526                 /* allocate local 1 (pointer) dst_ptr */
8527                 mono_mb_add_local (mb, &klass->this_arg);
8528                 
8529                 /* initialize src_ptr to point to the start of object data */
8530                 mono_mb_emit_byte (mb, CEE_LDARG_0);
8531                 mono_mb_emit_stloc (mb, 0);
8532
8533                 /* initialize dst_ptr */
8534                 mono_mb_emit_byte (mb, CEE_LDARG_1);
8535                 mono_mb_emit_op (mb, CEE_UNBOX, klass);
8536                 mono_mb_emit_stloc (mb, 1);
8537
8538                 emit_struct_conv (mb, klass, TRUE);
8539         }
8540
8541         mono_mb_emit_byte (mb, CEE_RET);
8542 #endif
8543         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_PTR_TO_STRUCTURE);
8544         res = mono_mb_create (mb, ptostr, 0, info);
8545         mono_mb_free (mb);
8546
8547         klass->marshal_info->ptr_to_str = res;
8548         return res;
8549 }
8550
8551 /*
8552  * Return a dummy wrapper for METHOD which is called by synchronized wrappers.
8553  * This is used to avoid infinite recursion since it is hard to determine where to
8554  * replace a method with its synchronized wrapper, and where not.
8555  * The runtime should execute METHOD instead of the wrapper.
8556  * The wrapper info for the wrapper is a WrapperInfo structure.
8557  */
8558 MonoMethod *
8559 mono_marshal_get_synchronized_inner_wrapper (MonoMethod *method)
8560 {
8561         MonoMethodBuilder *mb;
8562         WrapperInfo *info;
8563         MonoMethodSignature *sig;
8564         MonoMethod *res;
8565         MonoGenericContext *ctx = NULL;
8566         MonoGenericContainer *container = NULL;
8567
8568         if (method->is_inflated && !mono_method_get_context (method)->method_inst) {
8569                 ctx = &((MonoMethodInflated*)method)->context;
8570                 method = ((MonoMethodInflated*)method)->declaring;
8571                 container = mono_method_get_generic_container (method);
8572                 if (!container)
8573                         container = method->klass->generic_container;
8574                 g_assert (container);
8575         }
8576
8577         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNKNOWN);
8578 #ifndef DISABLE_JIT
8579         mono_mb_emit_exception_full (mb, "System", "ExecutionEngineException", "Shouldn't be called.");
8580         mono_mb_emit_byte (mb, CEE_RET);
8581 #endif
8582         sig = signature_dup (method->klass->image, mono_method_signature (method));
8583
8584         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_SYNCHRONIZED_INNER);
8585         info->d.synchronized_inner.method = method;
8586         res = mono_mb_create (mb, sig, 0, info);
8587         mono_mb_free (mb);
8588         if (ctx) {
8589                 MonoError error;
8590                 res = mono_class_inflate_generic_method_checked (res, ctx, &error);
8591                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8592         }
8593         return res;
8594 }
8595
8596 /*
8597  * generates IL code for the synchronized wrapper: the generated method
8598  * calls METHOD while locking 'this' or the parent type.
8599  */
8600 MonoMethod *
8601 mono_marshal_get_synchronized_wrapper (MonoMethod *method)
8602 {
8603         static MonoMethod *enter_method, *exit_method, *gettypefromhandle_method;
8604         MonoMethodSignature *sig;
8605         MonoExceptionClause *clause;
8606         MonoMethodBuilder *mb;
8607         MonoMethod *res;
8608         GHashTable *cache;
8609         int i, pos, this_local, ret_local = 0;
8610         MonoGenericContext *ctx = NULL;
8611         MonoMethod *orig_method = NULL;
8612         MonoGenericContainer *container = NULL;
8613
8614         g_assert (method);
8615
8616         if (method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED)
8617                 return method;
8618
8619         /* FIXME: Support generic methods too */
8620         if (method->is_inflated && !mono_method_get_context (method)->method_inst) {
8621                 orig_method = method;
8622                 ctx = &((MonoMethodInflated*)method)->context;
8623                 method = ((MonoMethodInflated*)method)->declaring;
8624                 container = mono_method_get_generic_container (method);
8625                 if (!container)
8626                         container = method->klass->generic_container;
8627                 g_assert (container);
8628         }
8629
8630         /*
8631          * Check cache
8632          */
8633         if (ctx) {
8634                 cache = get_cache (&method->klass->image->synchronized_generic_cache, mono_aligned_addr_hash, NULL);
8635                 res = check_generic_wrapper_cache (cache, orig_method, orig_method, method);
8636                 if (res)
8637                         return res;
8638         } else {
8639                 cache = get_cache (&method->klass->image->synchronized_cache, mono_aligned_addr_hash, NULL);
8640                 if ((res = mono_marshal_find_in_cache (cache, method)))
8641                         return res;
8642         }
8643
8644         sig = signature_dup (method->klass->image, mono_method_signature (method));
8645         sig->pinvoke = 0;
8646
8647         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_SYNCHRONIZED);
8648
8649 #ifndef DISABLE_JIT
8650         /* result */
8651         if (!MONO_TYPE_IS_VOID (sig->ret))
8652                 ret_local = mono_mb_add_local (mb, sig->ret);
8653 #endif
8654
8655         if (method->klass->valuetype && !(method->flags & MONO_METHOD_ATTR_STATIC)) {
8656                 mono_class_set_failure (method->klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
8657 #ifndef DISABLE_JIT
8658                 /* This will throw the type load exception when the wrapper is compiled */
8659                 mono_mb_emit_byte (mb, CEE_LDNULL);
8660                 mono_mb_emit_op (mb, CEE_ISINST, method->klass);
8661                 mono_mb_emit_byte (mb, CEE_POP);
8662
8663                 if (!MONO_TYPE_IS_VOID (sig->ret))
8664                         mono_mb_emit_ldloc (mb, ret_local);
8665                 mono_mb_emit_byte (mb, CEE_RET);
8666 #endif
8667
8668                 res = mono_mb_create_and_cache (cache, method,
8669                                                                                 mb, sig, sig->param_count + 16);
8670                 mono_mb_free (mb);
8671
8672                 return res;
8673         }
8674
8675 #ifndef DISABLE_JIT
8676         /* this */
8677         this_local = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
8678
8679         clause = mono_image_alloc0 (method->klass->image, sizeof (MonoExceptionClause));
8680         clause->flags = MONO_EXCEPTION_CLAUSE_FINALLY;
8681 #endif
8682
8683         mono_marshal_lock ();
8684
8685         if (!enter_method) {
8686                 MonoMethodDesc *desc;
8687
8688                 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
8689                 enter_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
8690                 g_assert (enter_method);
8691                 mono_method_desc_free (desc);
8692
8693                 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
8694                 exit_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
8695                 g_assert (exit_method);
8696                 mono_method_desc_free (desc);
8697
8698                 desc = mono_method_desc_new ("Type:GetTypeFromHandle", FALSE);
8699                 gettypefromhandle_method = mono_method_desc_search_in_class (desc, mono_defaults.systemtype_class);
8700                 g_assert (gettypefromhandle_method);
8701                 mono_method_desc_free (desc);
8702         }
8703
8704         mono_marshal_unlock ();
8705
8706 #ifndef DISABLE_JIT
8707         /* Push this or the type object */
8708         if (method->flags & METHOD_ATTRIBUTE_STATIC) {
8709                 /* We have special handling for this in the JIT */
8710                 int index = mono_mb_add_data (mb, method->klass);
8711                 mono_mb_add_data (mb, mono_defaults.typehandle_class);
8712                 mono_mb_emit_byte (mb, CEE_LDTOKEN);
8713                 mono_mb_emit_i4 (mb, index);
8714
8715                 mono_mb_emit_managed_call (mb, gettypefromhandle_method, NULL);
8716         }
8717         else
8718                 mono_mb_emit_ldarg (mb, 0);
8719         mono_mb_emit_stloc (mb, this_local);
8720
8721         /* Call Monitor::Enter() */
8722         mono_mb_emit_ldloc (mb, this_local);
8723         mono_mb_emit_managed_call (mb, enter_method, NULL);
8724
8725         clause->try_offset = mono_mb_get_label (mb);
8726
8727         /* Call the method */
8728         if (sig->hasthis)
8729                 mono_mb_emit_ldarg (mb, 0);
8730         for (i = 0; i < sig->param_count; i++)
8731                 mono_mb_emit_ldarg (mb, i + (sig->hasthis == TRUE));
8732
8733         if (ctx) {
8734                 MonoError error;
8735                 mono_mb_emit_managed_call (mb, mono_class_inflate_generic_method_checked (method, &container->context, &error), NULL);
8736                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8737         } else {
8738                 mono_mb_emit_managed_call (mb, method, NULL);
8739         }
8740
8741         if (!MONO_TYPE_IS_VOID (sig->ret))
8742                 mono_mb_emit_stloc (mb, ret_local);
8743
8744         pos = mono_mb_emit_branch (mb, CEE_LEAVE);
8745
8746         clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
8747         clause->handler_offset = mono_mb_get_label (mb);
8748
8749         /* Call Monitor::Exit() */
8750         mono_mb_emit_ldloc (mb, this_local);
8751         mono_mb_emit_managed_call (mb, exit_method, NULL);
8752         mono_mb_emit_byte (mb, CEE_ENDFINALLY);
8753
8754         clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
8755
8756         mono_mb_patch_branch (mb, pos);
8757         if (!MONO_TYPE_IS_VOID (sig->ret))
8758                 mono_mb_emit_ldloc (mb, ret_local);
8759         mono_mb_emit_byte (mb, CEE_RET);
8760
8761         mono_mb_set_clauses (mb, 1, clause);
8762 #endif
8763
8764         if (ctx) {
8765                 MonoMethod *def;
8766                 def = mono_mb_create_and_cache (cache, method, mb, sig, sig->param_count + 16);
8767                 res = cache_generic_wrapper (cache, orig_method, def, ctx, orig_method);
8768         } else {
8769                 res = mono_mb_create_and_cache (cache, method,
8770                                                                                 mb, sig, sig->param_count + 16);
8771         }
8772         mono_mb_free (mb);
8773
8774         return res;     
8775 }
8776
8777
8778 /*
8779  * the returned method calls 'method' unboxing the this argument
8780  */
8781 MonoMethod *
8782 mono_marshal_get_unbox_wrapper (MonoMethod *method)
8783 {
8784         MonoMethodSignature *sig = mono_method_signature (method);
8785         int i;
8786         MonoMethodBuilder *mb;
8787         MonoMethod *res;
8788         GHashTable *cache;
8789
8790         cache = get_cache (&method->klass->image->unbox_wrapper_cache, mono_aligned_addr_hash, NULL);
8791         if ((res = mono_marshal_find_in_cache (cache, method)))
8792                 return res;
8793
8794         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNBOX);
8795
8796         g_assert (sig->hasthis);
8797         
8798 #ifndef DISABLE_JIT
8799         mono_mb_emit_ldarg (mb, 0); 
8800         mono_mb_emit_icon (mb, sizeof (MonoObject));
8801         mono_mb_emit_byte (mb, CEE_ADD);
8802         for (i = 0; i < sig->param_count; ++i)
8803                 mono_mb_emit_ldarg (mb, i + 1);
8804         mono_mb_emit_managed_call (mb, method, NULL);
8805         mono_mb_emit_byte (mb, CEE_RET);
8806 #endif
8807
8808         res = mono_mb_create_and_cache (cache, method,
8809                                                                                  mb, sig, sig->param_count + 16);
8810         mono_mb_free (mb);
8811
8812         /* code_for (res); */
8813
8814         return res;     
8815 }
8816
8817 enum {
8818         STELEMREF_OBJECT, /*no check at all*/
8819         STELEMREF_SEALED_CLASS, /*check vtable->klass->element_type */
8820         STELEMREF_CLASS, /*only the klass->parents check*/
8821         STELEMREF_INTERFACE, /*interfaces without variant generic arguments. */
8822         STELEMREF_COMPLEX, /*arrays, MBR or types with variant generic args - go straight to icalls*/
8823         STELEMREF_KIND_COUNT
8824 };
8825
8826 static const char *strelemref_wrapper_name[] = {
8827         "object", "sealed_class", "class", "interface", "complex"
8828 };
8829
8830 static gboolean
8831 is_monomorphic_array (MonoClass *klass)
8832 {
8833         MonoClass *element_class;
8834         if (klass->rank != 1)
8835                 return FALSE;
8836
8837         element_class = klass->element_class;
8838         return (element_class->flags & TYPE_ATTRIBUTE_SEALED) || element_class->valuetype;
8839 }
8840
8841 static int
8842 get_virtual_stelemref_kind (MonoClass *element_class)
8843 {
8844         if (element_class == mono_defaults.object_class)
8845                 return STELEMREF_OBJECT;
8846         if (is_monomorphic_array (element_class))
8847                 return STELEMREF_SEALED_CLASS;
8848         /* Compressed interface bitmaps require code that is quite complex, so don't optimize for it. */
8849         if (MONO_CLASS_IS_INTERFACE (element_class) && !mono_class_has_variant_generic_params (element_class))
8850 #ifdef COMPRESSED_INTERFACE_BITMAP
8851                 return STELEMREF_COMPLEX;
8852 #else
8853                 return STELEMREF_INTERFACE;
8854 #endif
8855         /*Arrays are sealed but are covariant on their element type, We can't use any of the fast paths.*/
8856         if (mono_class_is_marshalbyref (element_class) || element_class->rank || mono_class_has_variant_generic_params (element_class))
8857                 return STELEMREF_COMPLEX;
8858         if (element_class->flags & TYPE_ATTRIBUTE_SEALED)
8859                 return STELEMREF_SEALED_CLASS;
8860         return STELEMREF_CLASS;
8861 }
8862
8863 #ifndef DISABLE_JIT
8864
8865 static void
8866 load_array_element_address (MonoMethodBuilder *mb)
8867 {
8868         mono_mb_emit_ldarg (mb, 0);
8869         mono_mb_emit_ldarg (mb, 1);
8870         mono_mb_emit_op (mb, CEE_LDELEMA, mono_defaults.object_class);
8871 }
8872
8873 static void
8874 load_array_class (MonoMethodBuilder *mb, int aklass)
8875 {
8876         mono_mb_emit_ldarg (mb, 0);
8877         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
8878         mono_mb_emit_byte (mb, CEE_LDIND_I);
8879         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
8880         mono_mb_emit_byte (mb, CEE_LDIND_I);
8881         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, element_class));
8882         mono_mb_emit_byte (mb, CEE_LDIND_I);
8883         mono_mb_emit_stloc (mb, aklass);
8884 }
8885
8886 static void
8887 load_value_class (MonoMethodBuilder *mb, int vklass)
8888 {
8889         mono_mb_emit_ldarg (mb, 2);
8890         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
8891         mono_mb_emit_byte (mb, CEE_LDIND_I);
8892         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
8893         mono_mb_emit_byte (mb, CEE_LDIND_I);
8894         mono_mb_emit_stloc (mb, vklass);
8895 }
8896 #endif
8897
8898 #if 0
8899 static void
8900 record_slot_vstore (MonoObject *array, size_t index, MonoObject *value)
8901 {
8902         char *name = mono_type_get_full_name (array->vtable->klass->element_class);
8903         printf ("slow vstore of %s\n", name);
8904         g_free (name);
8905 }
8906 #endif
8907
8908 /*
8909  * The wrapper info for the wrapper is a WrapperInfo structure.
8910  *
8911  * TODO:
8912  *      - Separate simple interfaces from variant interfaces or mbr types. This way we can avoid the icall for them.
8913  *      - Emit a (new) mono bytecode that produces OP_COND_EXC_NE_UN to raise ArrayTypeMismatch
8914  *      - Maybe mve some MonoClass field into the vtable to reduce the number of loads
8915  *      - Add a case for arrays of arrays.
8916  */
8917 static MonoMethod*
8918 get_virtual_stelemref_wrapper (int kind)
8919 {
8920         static MonoMethod *cached_methods [STELEMREF_KIND_COUNT] = { NULL }; /*object iface sealed regular*/
8921         static MonoMethodSignature *signature;
8922         MonoMethodBuilder *mb;
8923         MonoMethod *res;
8924         char *name;
8925         const char *param_names [16];
8926         guint32 b1, b2, b3;
8927         int aklass, vklass, vtable, uiid;
8928         int array_slot_addr;
8929         WrapperInfo *info;
8930
8931         if (cached_methods [kind])
8932                 return cached_methods [kind];
8933
8934         name = g_strdup_printf ("virt_stelemref_%s", strelemref_wrapper_name [kind]);
8935         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_STELEMREF);
8936         g_free (name);
8937
8938         if (!signature) {
8939                 MonoMethodSignature *sig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
8940
8941                 /* void this::stelemref (size_t idx, void* value) */
8942                 sig->ret = &mono_defaults.void_class->byval_arg;
8943                 sig->hasthis = TRUE;
8944                 sig->params [0] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
8945                 sig->params [1] = &mono_defaults.object_class->byval_arg;
8946                 signature = sig;
8947         }
8948
8949 #ifndef DISABLE_JIT
8950         param_names [0] = "index";
8951         param_names [1] = "value";
8952         mono_mb_set_param_names (mb, param_names);
8953
8954         /*For now simply call plain old stelemref*/
8955         switch (kind) {
8956         case STELEMREF_OBJECT:
8957                 /* ldelema (implicit bound check) */
8958                 load_array_element_address (mb);
8959                 /* do_store */
8960                 mono_mb_emit_ldarg (mb, 2);
8961                 mono_mb_emit_byte (mb, CEE_STIND_REF);
8962                 mono_mb_emit_byte (mb, CEE_RET);
8963                 break;
8964
8965         case STELEMREF_COMPLEX:
8966                 /*
8967                 <ldelema (bound check)>
8968                 if (!value)
8969                         goto store;
8970                 if (!mono_object_isinst (value, aklass))
8971                         goto do_exception;
8972
8973                  do_store:
8974                          *array_slot_addr = value;
8975
8976                 do_exception:
8977                         throw new ArrayTypeMismatchException ();
8978                 */
8979
8980                 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8981                 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
8982
8983 #if 0
8984                 {
8985                         /*Use this to debug/record stores that are going thru the slow path*/
8986                         MonoMethodSignature *csig;
8987                         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
8988                         csig->ret = &mono_defaults.void_class->byval_arg;
8989                         csig->params [0] = &mono_defaults.object_class->byval_arg;
8990                         csig->params [1] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
8991                         csig->params [2] = &mono_defaults.object_class->byval_arg;
8992                         mono_mb_emit_ldarg (mb, 0);
8993                         mono_mb_emit_ldarg (mb, 1);
8994                         mono_mb_emit_ldarg (mb, 2);
8995                         mono_mb_emit_native_call (mb, csig, record_slot_vstore);
8996                 }
8997 #endif
8998
8999                 /* ldelema (implicit bound check) */
9000                 load_array_element_address (mb);
9001                 mono_mb_emit_stloc (mb, array_slot_addr);
9002
9003                 /* if (!value) goto do_store */
9004                 mono_mb_emit_ldarg (mb, 2);
9005                 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9006
9007                 /* aklass = array->vtable->klass->element_class */
9008                 load_array_class (mb, aklass);
9009
9010                 /*if (mono_object_isinst (value, aklass)) */
9011                 mono_mb_emit_ldarg (mb, 2);
9012                 mono_mb_emit_ldloc (mb, aklass);
9013                 mono_mb_emit_icall (mb, mono_object_isinst);
9014                 b2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9015
9016                 /* do_store: */
9017                 mono_mb_patch_branch (mb, b1);
9018                 mono_mb_emit_ldloc (mb, array_slot_addr);
9019                 mono_mb_emit_ldarg (mb, 2);
9020                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9021                 mono_mb_emit_byte (mb, CEE_RET);
9022
9023                 /* do_exception: */
9024                 mono_mb_patch_branch (mb, b2);
9025
9026                 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9027                 break;
9028
9029         case STELEMREF_SEALED_CLASS:
9030                 /*
9031                 <ldelema (bound check)>
9032                 if (!value)
9033                         goto store;
9034
9035                 aklass = array->vtable->klass->element_class;
9036                 vklass = value->vtable->klass;
9037
9038                 if (vklass != aklass)
9039                         goto do_exception;
9040
9041                 do_store:
9042                          *array_slot_addr = value;
9043
9044                 do_exception:
9045                         throw new ArrayTypeMismatchException ();
9046                 */
9047                 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9048                 vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9049                 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9050
9051
9052                 /* ldelema (implicit bound check) */
9053                 load_array_element_address (mb);
9054                 mono_mb_emit_stloc (mb, array_slot_addr);
9055
9056                 /* if (!value) goto do_store */
9057                 mono_mb_emit_ldarg (mb, 2);
9058                 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9059
9060                 /* aklass = array->vtable->klass->element_class */
9061                 load_array_class (mb, aklass);
9062
9063                 /* vklass = value->vtable->klass */
9064                 load_value_class (mb, vklass);
9065
9066                 /*if (vklass != aklass) goto do_exception; */
9067                 mono_mb_emit_ldloc (mb, aklass);
9068                 mono_mb_emit_ldloc (mb, vklass);
9069                 b2 = mono_mb_emit_branch (mb, CEE_BNE_UN);
9070
9071                 /* do_store: */
9072                 mono_mb_patch_branch (mb, b1);
9073                 mono_mb_emit_ldloc (mb, array_slot_addr);
9074                 mono_mb_emit_ldarg (mb, 2);
9075                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9076                 mono_mb_emit_byte (mb, CEE_RET);
9077
9078                 /* do_exception: */
9079                 mono_mb_patch_branch (mb, b2);
9080                 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9081                 break;
9082
9083         case STELEMREF_CLASS:
9084                 /*
9085                 the method:
9086                 <ldelema (bound check)>
9087                 if (!value)
9088                         goto do_store;
9089
9090                 aklass = array->vtable->klass->element_class;
9091                 vklass = value->vtable->klass;
9092
9093                 if (vklass->idepth < aklass->idepth)
9094                         goto do_exception;
9095
9096                 if (vklass->supertypes [aklass->idepth - 1] != aklass)
9097                         goto do_exception;
9098
9099                 do_store:
9100                         *array_slot_addr = value;
9101                         return;
9102
9103                 long:
9104                         throw new ArrayTypeMismatchException ();
9105                 */
9106                 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9107                 vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9108                 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9109
9110                 /* ldelema (implicit bound check) */
9111                 load_array_element_address (mb);
9112                 mono_mb_emit_stloc (mb, array_slot_addr);
9113
9114                 /* if (!value) goto do_store */
9115                 mono_mb_emit_ldarg (mb, 2);
9116                 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9117
9118                 /* aklass = array->vtable->klass->element_class */
9119                 load_array_class (mb, aklass);
9120
9121                 /* vklass = value->vtable->klass */
9122                 load_value_class (mb, vklass);
9123
9124                 /*if (mono_object_isinst (value, aklass)) */
9125                 mono_mb_emit_ldarg (mb, 2);
9126                 mono_mb_emit_ldloc (mb, aklass);
9127                 mono_mb_emit_icall (mb, mono_object_isinst);
9128                 b2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9129
9130                 /* if (vklass->idepth < aklass->idepth) goto failue */
9131                 mono_mb_emit_ldloc (mb, vklass);
9132                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9133                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9134
9135                 mono_mb_emit_ldloc (mb, aklass);
9136                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9137                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9138
9139                 b2 = mono_mb_emit_branch (mb, CEE_BLT_UN);
9140
9141                 /* if (vklass->supertypes [aklass->idepth - 1] != aklass) goto failure */
9142                 mono_mb_emit_ldloc (mb, vklass);
9143                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, supertypes));
9144                 mono_mb_emit_byte (mb, CEE_LDIND_I);
9145
9146                 mono_mb_emit_ldloc (mb, aklass);
9147                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9148                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9149                 mono_mb_emit_icon (mb, 1);
9150                 mono_mb_emit_byte (mb, CEE_SUB);
9151                 mono_mb_emit_icon (mb, sizeof (void*));
9152                 mono_mb_emit_byte (mb, CEE_MUL);
9153                 mono_mb_emit_byte (mb, CEE_ADD);
9154                 mono_mb_emit_byte (mb, CEE_LDIND_I);
9155
9156                 mono_mb_emit_ldloc (mb, aklass);
9157                 b3 = mono_mb_emit_branch (mb, CEE_BNE_UN);
9158
9159                 /* do_store: */
9160                 mono_mb_patch_branch (mb, b1);
9161                 mono_mb_emit_ldloc (mb, array_slot_addr);
9162                 mono_mb_emit_ldarg (mb, 2);
9163                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9164                 mono_mb_emit_byte (mb, CEE_RET);
9165
9166                 /* do_exception: */
9167                 mono_mb_patch_branch (mb, b2);
9168                 mono_mb_patch_branch (mb, b3);
9169
9170                 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9171                 break;
9172
9173         case STELEMREF_INTERFACE:
9174                 /*Mono *klass;
9175                 MonoVTable *vt;
9176                 unsigned uiid;
9177                 if (value == NULL)
9178                         goto store;
9179
9180                 klass = array->obj.vtable->klass->element_class;
9181                 vt = value->vtable;
9182                 uiid = klass->interface_id;
9183                 if (uiid > vt->max_interface_id)
9184                         goto exception;
9185                 if (!(vt->interface_bitmap [(uiid) >> 3] & (1 << ((uiid)&7))))
9186                         goto exception;
9187                 store:
9188                         mono_array_setref (array, index, value);
9189                         return;
9190                 exception:
9191                         mono_raise_exception (mono_get_exception_array_type_mismatch ());*/
9192
9193                 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9194                 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9195                 vtable = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9196                 uiid = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
9197
9198                 /* ldelema (implicit bound check) */
9199                 load_array_element_address (mb);
9200                 mono_mb_emit_stloc (mb, array_slot_addr);
9201
9202                 /* if (!value) goto do_store */
9203                 mono_mb_emit_ldarg (mb, 2);
9204                 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9205
9206                 /* klass = array->vtable->klass->element_class */
9207                 load_array_class (mb, aklass);
9208
9209                 /* vt = value->vtable */
9210                 mono_mb_emit_ldarg (mb, 2);
9211                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9212                 mono_mb_emit_byte (mb, CEE_LDIND_I);
9213                 mono_mb_emit_stloc (mb, vtable);
9214
9215                 /* uiid = klass->interface_id; */
9216                 mono_mb_emit_ldloc (mb, aklass);
9217                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, interface_id));
9218                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9219                 mono_mb_emit_stloc (mb, uiid);
9220
9221                 /*if (uiid > vt->max_interface_id)*/
9222                 mono_mb_emit_ldloc (mb, uiid);
9223                 mono_mb_emit_ldloc (mb, vtable);
9224                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, max_interface_id));
9225                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9226                 b2 = mono_mb_emit_branch (mb, CEE_BGT_UN);
9227
9228                 /* if (!(vt->interface_bitmap [(uiid) >> 3] & (1 << ((uiid)&7)))) */
9229
9230                 /*vt->interface_bitmap*/
9231                 mono_mb_emit_ldloc (mb, vtable);
9232                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, interface_bitmap));
9233                 mono_mb_emit_byte (mb, CEE_LDIND_I);
9234
9235                 /*uiid >> 3*/
9236                 mono_mb_emit_ldloc (mb, uiid);
9237                 mono_mb_emit_icon (mb, 3);
9238                 mono_mb_emit_byte (mb, CEE_SHR_UN);
9239
9240                 /*vt->interface_bitmap [(uiid) >> 3]*/
9241                 mono_mb_emit_byte (mb, CEE_ADD); /*interface_bitmap is a guint8 array*/
9242                 mono_mb_emit_byte (mb, CEE_LDIND_U1);
9243
9244                 /*(1 << ((uiid)&7)))*/
9245                 mono_mb_emit_icon (mb, 1);
9246                 mono_mb_emit_ldloc (mb, uiid);
9247                 mono_mb_emit_icon (mb, 7);
9248                 mono_mb_emit_byte (mb, CEE_AND);
9249                 mono_mb_emit_byte (mb, CEE_SHL);
9250
9251                 /*bitwise and the whole thing*/
9252                 mono_mb_emit_byte (mb, CEE_AND);
9253                 b3 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9254
9255                 /* do_store: */
9256                 mono_mb_patch_branch (mb, b1);
9257                 mono_mb_emit_ldloc (mb, array_slot_addr);
9258                 mono_mb_emit_ldarg (mb, 2);
9259                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9260                 mono_mb_emit_byte (mb, CEE_RET);
9261
9262                 /* do_exception: */
9263                 mono_mb_patch_branch (mb, b2);
9264                 mono_mb_patch_branch (mb, b3);
9265                 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9266                 break;
9267
9268         default:
9269                 mono_mb_emit_ldarg (mb, 0);
9270                 mono_mb_emit_ldarg (mb, 1);
9271                 mono_mb_emit_ldarg (mb, 2);
9272                 mono_mb_emit_managed_call (mb, mono_marshal_get_stelemref (), NULL);
9273                 mono_mb_emit_byte (mb, CEE_RET);
9274                 g_assert (0);
9275         }
9276 #endif /* DISABLE_JIT */
9277         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_VIRTUAL_STELEMREF);
9278         info->d.virtual_stelemref.kind = kind;
9279         res = mono_mb_create (mb, signature, 4, info);
9280         res->flags |= METHOD_ATTRIBUTE_VIRTUAL;
9281
9282         mono_marshal_lock ();
9283         if (!cached_methods [kind]) {
9284                 cached_methods [kind] = res;
9285                 mono_marshal_unlock ();
9286         } else {
9287                 mono_marshal_unlock ();
9288                 mono_free_method (res);
9289         }
9290
9291         mono_mb_free (mb);
9292         return cached_methods [kind];
9293 }
9294
9295 MonoMethod*
9296 mono_marshal_get_virtual_stelemref (MonoClass *array_class)
9297 {
9298         int kind;
9299
9300         g_assert (array_class->rank == 1);
9301         kind = get_virtual_stelemref_kind (array_class->element_class);
9302
9303         return get_virtual_stelemref_wrapper (kind);
9304 }
9305
9306 MonoMethod**
9307 mono_marshal_get_virtual_stelemref_wrappers (int *nwrappers)
9308 {
9309         MonoMethod **res;
9310         int i;
9311
9312         *nwrappers = STELEMREF_KIND_COUNT;
9313         res = g_malloc0 (STELEMREF_KIND_COUNT * sizeof (MonoMethod*));
9314         for (i = 0; i < STELEMREF_KIND_COUNT; ++i)
9315                 res [i] = get_virtual_stelemref_wrapper (i);
9316         return res;
9317 }
9318
9319 /*
9320  * The wrapper info for the wrapper is a WrapperInfo structure.
9321  */
9322 MonoMethod*
9323 mono_marshal_get_stelemref (void)
9324 {
9325         static MonoMethod* ret = NULL;
9326         MonoMethodSignature *sig;
9327         MonoMethodBuilder *mb;
9328         WrapperInfo *info;
9329         
9330         guint32 b1, b2, b3, b4;
9331         guint32 copy_pos;
9332         int aklass, vklass;
9333         int array_slot_addr;
9334         
9335         if (ret)
9336                 return ret;
9337         
9338         mb = mono_mb_new (mono_defaults.object_class, "stelemref", MONO_WRAPPER_STELEMREF);
9339         
9340
9341         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
9342
9343         /* void stelemref (void* array, int idx, void* value) */
9344         sig->ret = &mono_defaults.void_class->byval_arg;
9345         sig->params [0] = &mono_defaults.object_class->byval_arg;
9346         sig->params [1] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
9347         sig->params [2] = &mono_defaults.object_class->byval_arg;
9348
9349 #ifndef DISABLE_JIT
9350         aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9351         vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9352         array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9353         
9354         /*
9355         the method:
9356         <ldelema (bound check)>
9357         if (!value)
9358                 goto store;
9359         
9360         aklass = array->vtable->klass->element_class;
9361         vklass = value->vtable->klass;
9362         
9363         if (vklass->idepth < aklass->idepth)
9364                 goto long;
9365         
9366         if (vklass->supertypes [aklass->idepth - 1] != aklass)
9367                 goto long;
9368         
9369         store:
9370                 *array_slot_addr = value;
9371                 return;
9372         
9373         long:
9374                 if (mono_object_isinst (value, aklass))
9375                         goto store;
9376                 
9377                 throw new ArrayTypeMismatchException ();
9378         */
9379         
9380         /* ldelema (implicit bound check) */
9381         mono_mb_emit_ldarg (mb, 0);
9382         mono_mb_emit_ldarg (mb, 1);
9383         mono_mb_emit_op (mb, CEE_LDELEMA, mono_defaults.object_class);
9384         mono_mb_emit_stloc (mb, array_slot_addr);
9385                 
9386         /* if (!value) goto do_store */
9387         mono_mb_emit_ldarg (mb, 2);
9388         b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9389         
9390         /* aklass = array->vtable->klass->element_class */
9391         mono_mb_emit_ldarg (mb, 0);
9392         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9393         mono_mb_emit_byte (mb, CEE_LDIND_I);
9394         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
9395         mono_mb_emit_byte (mb, CEE_LDIND_I);
9396         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, element_class));
9397         mono_mb_emit_byte (mb, CEE_LDIND_I);
9398         mono_mb_emit_stloc (mb, aklass);
9399         
9400         /* vklass = value->vtable->klass */
9401         mono_mb_emit_ldarg (mb, 2);
9402         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9403         mono_mb_emit_byte (mb, CEE_LDIND_I);
9404         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
9405         mono_mb_emit_byte (mb, CEE_LDIND_I);
9406         mono_mb_emit_stloc (mb, vklass);
9407         
9408         /* if (vklass->idepth < aklass->idepth) goto failue */
9409         mono_mb_emit_ldloc (mb, vklass);
9410         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9411         mono_mb_emit_byte (mb, CEE_LDIND_U2);
9412         
9413         mono_mb_emit_ldloc (mb, aklass);
9414         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9415         mono_mb_emit_byte (mb, CEE_LDIND_U2);
9416         
9417         b2 = mono_mb_emit_branch (mb, CEE_BLT_UN);
9418         
9419         /* if (vklass->supertypes [aklass->idepth - 1] != aklass) goto failure */
9420         mono_mb_emit_ldloc (mb, vklass);
9421         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, supertypes));
9422         mono_mb_emit_byte (mb, CEE_LDIND_I);
9423         
9424         mono_mb_emit_ldloc (mb, aklass);
9425         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9426         mono_mb_emit_byte (mb, CEE_LDIND_U2);
9427         mono_mb_emit_icon (mb, 1);
9428         mono_mb_emit_byte (mb, CEE_SUB);
9429         mono_mb_emit_icon (mb, sizeof (void*));
9430         mono_mb_emit_byte (mb, CEE_MUL);
9431         mono_mb_emit_byte (mb, CEE_ADD);
9432         mono_mb_emit_byte (mb, CEE_LDIND_I);
9433         
9434         mono_mb_emit_ldloc (mb, aklass);
9435         
9436         b3 = mono_mb_emit_branch (mb, CEE_BNE_UN);
9437         
9438         copy_pos = mono_mb_get_label (mb);
9439         /* do_store */
9440         mono_mb_patch_branch (mb, b1);
9441         mono_mb_emit_ldloc (mb, array_slot_addr);
9442         mono_mb_emit_ldarg (mb, 2);
9443         mono_mb_emit_byte (mb, CEE_STIND_REF);
9444         
9445         mono_mb_emit_byte (mb, CEE_RET);
9446         
9447         /* the hard way */
9448         mono_mb_patch_branch (mb, b2);
9449         mono_mb_patch_branch (mb, b3);
9450         
9451         mono_mb_emit_ldarg (mb, 2);
9452         mono_mb_emit_ldloc (mb, aklass);
9453         mono_mb_emit_icall (mb, mono_object_isinst);
9454         
9455         b4 = mono_mb_emit_branch (mb, CEE_BRTRUE);
9456         mono_mb_patch_addr (mb, b4, copy_pos - (b4 + 4));
9457         mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9458         
9459         mono_mb_emit_byte (mb, CEE_RET);
9460 #endif
9461         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
9462         ret = mono_mb_create (mb, sig, 4, info);
9463         mono_mb_free (mb);
9464
9465         return ret;
9466 }
9467
9468 /*
9469  * mono_marshal_get_gsharedvt_in_wrapper:
9470  *
9471  *   This wrapper handles calls from normal code to gsharedvt code.
9472  *
9473  * The wrapper info for the wrapper is a WrapperInfo structure.
9474  */
9475 MonoMethod*
9476 mono_marshal_get_gsharedvt_in_wrapper (void)
9477 {
9478         static MonoMethod* ret = NULL;
9479         MonoMethodSignature *sig;
9480         MonoMethodBuilder *mb;
9481         WrapperInfo *info;
9482
9483         if (ret)
9484                 return ret;
9485         
9486         mb = mono_mb_new (mono_defaults.object_class, "gsharedvt_in", MONO_WRAPPER_UNKNOWN);
9487         
9488         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
9489         sig->ret = &mono_defaults.void_class->byval_arg;
9490
9491 #ifndef DISABLE_JIT
9492         /*
9493          * The body is generated by the JIT, we use a wrapper instead of a trampoline so EH works.
9494          */
9495         mono_mb_emit_byte (mb, CEE_RET);
9496 #endif
9497         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_GSHAREDVT_IN);
9498         ret = mono_mb_create (mb, sig, 4, info);
9499         mono_mb_free (mb);
9500
9501         return ret;
9502 }
9503
9504 /*
9505  * mono_marshal_get_gsharedvt_out_wrapper:
9506  *
9507  *   This wrapper handles calls from gsharedvt code to normal code.
9508  *
9509  * The wrapper info for the wrapper is a WrapperInfo structure.
9510  */
9511 MonoMethod*
9512 mono_marshal_get_gsharedvt_out_wrapper (void)
9513 {
9514         static MonoMethod* ret = NULL;
9515         MonoMethodSignature *sig;
9516         MonoMethodBuilder *mb;
9517         WrapperInfo *info;
9518
9519         if (ret)
9520                 return ret;
9521         
9522         mb = mono_mb_new (mono_defaults.object_class, "gsharedvt_out", MONO_WRAPPER_UNKNOWN);
9523         
9524         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
9525         sig->ret = &mono_defaults.void_class->byval_arg;
9526
9527 #ifndef DISABLE_JIT
9528         /*
9529          * The body is generated by the JIT, we use a wrapper instead of a trampoline so EH works.
9530          */
9531         mono_mb_emit_byte (mb, CEE_RET);
9532 #endif
9533         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_GSHAREDVT_OUT);
9534         ret = mono_mb_create (mb, sig, 4, info);
9535         mono_mb_free (mb);
9536
9537         return ret;
9538 }
9539
9540 typedef struct {
9541         int rank;
9542         int elem_size;
9543         MonoMethod *method;
9544 } ArrayElemAddr;
9545
9546 /* LOCKING: vars accessed under the marshal lock */
9547 static ArrayElemAddr *elem_addr_cache = NULL;
9548 static int elem_addr_cache_size = 0;
9549 static int elem_addr_cache_next = 0;
9550
9551 /**
9552  * mono_marshal_get_array_address:
9553  * @rank: rank of the array type
9554  * @elem_size: size in bytes of an element of an array.
9555  *
9556  * Returns a MonoMethod that implements the code to get the address
9557  * of an element in a multi-dimenasional array of @rank dimensions.
9558  * The returned method takes an array as the first argument and then
9559  * @rank indexes for the @rank dimensions.
9560  * If ELEM_SIZE is 0, read the array size from the array object.
9561  */
9562 MonoMethod*
9563 mono_marshal_get_array_address (int rank, int elem_size)
9564 {
9565         MonoMethod *ret;
9566         MonoMethodBuilder *mb;
9567         MonoMethodSignature *sig;
9568         WrapperInfo *info;
9569         char *name;
9570         int i, bounds, ind, realidx;
9571         int branch_pos, *branch_positions;
9572         int cached;
9573
9574         ret = NULL;
9575         mono_marshal_lock ();
9576         for (i = 0; i < elem_addr_cache_next; ++i) {
9577                 if (elem_addr_cache [i].rank == rank && elem_addr_cache [i].elem_size == elem_size) {
9578                         ret = elem_addr_cache [i].method;
9579                         break;
9580                 }
9581         }
9582         mono_marshal_unlock ();
9583         if (ret)
9584                 return ret;
9585
9586         branch_positions = g_new0 (int, rank);
9587
9588         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1 + rank);
9589
9590         /* void* address (void* array, int idx0, int idx1, int idx2, ...) */
9591         sig->ret = &mono_defaults.int_class->byval_arg;
9592         sig->params [0] = &mono_defaults.object_class->byval_arg;
9593         for (i = 0; i < rank; ++i) {
9594                 sig->params [i + 1] = &mono_defaults.int32_class->byval_arg;
9595         }
9596
9597         name = g_strdup_printf ("ElementAddr_%d", elem_size);
9598         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_MANAGED);
9599         g_free (name);
9600         
9601 #ifndef DISABLE_JIT
9602         bounds = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9603         ind = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
9604         realidx = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
9605
9606         /* bounds = array->bounds; */
9607         mono_mb_emit_ldarg (mb, 0);
9608         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoArray, bounds));
9609         mono_mb_emit_byte (mb, CEE_LDIND_I);
9610         mono_mb_emit_stloc (mb, bounds);
9611
9612         /* ind is the overall element index, realidx is the partial index in a single dimension */
9613         /* ind = idx0 - bounds [0].lower_bound */
9614         mono_mb_emit_ldarg (mb, 1);
9615         mono_mb_emit_ldloc (mb, bounds);
9616         mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
9617         mono_mb_emit_byte (mb, CEE_ADD);
9618         mono_mb_emit_byte (mb, CEE_LDIND_I4);
9619         mono_mb_emit_byte (mb, CEE_SUB);
9620         mono_mb_emit_stloc (mb, ind);
9621         /* if (ind >= bounds [0].length) goto exeception; */
9622         mono_mb_emit_ldloc (mb, ind);
9623         mono_mb_emit_ldloc (mb, bounds);
9624         mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArrayBounds, length));
9625         mono_mb_emit_byte (mb, CEE_ADD);
9626         mono_mb_emit_byte (mb, CEE_LDIND_I4);
9627         /* note that we use unsigned comparison */
9628         branch_pos = mono_mb_emit_branch (mb, CEE_BGE_UN);
9629
9630         /* For large ranks (> 4?) use a loop n IL later to reduce code size.
9631          * We could also decide to ignore the passed elem_size and get it
9632          * from the array object, to reduce the number of methods we generate:
9633          * the additional cost is 3 memory loads and a non-immediate mul.
9634          */
9635         for (i = 1; i < rank; ++i) {
9636                 /* realidx = idxi - bounds [i].lower_bound */
9637                 mono_mb_emit_ldarg (mb, 1 + i);
9638                 mono_mb_emit_ldloc (mb, bounds);
9639                 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
9640                 mono_mb_emit_byte (mb, CEE_ADD);
9641                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
9642                 mono_mb_emit_byte (mb, CEE_SUB);
9643                 mono_mb_emit_stloc (mb, realidx);
9644                 /* if (realidx >= bounds [i].length) goto exeception; */
9645                 mono_mb_emit_ldloc (mb, realidx);
9646                 mono_mb_emit_ldloc (mb, bounds);
9647                 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + MONO_STRUCT_OFFSET (MonoArrayBounds, length));
9648                 mono_mb_emit_byte (mb, CEE_ADD);
9649                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
9650                 branch_positions [i] = mono_mb_emit_branch (mb, CEE_BGE_UN);
9651                 /* ind = ind * bounds [i].length + realidx */
9652                 mono_mb_emit_ldloc (mb, ind);
9653                 mono_mb_emit_ldloc (mb, bounds);
9654                 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + MONO_STRUCT_OFFSET (MonoArrayBounds, length));
9655                 mono_mb_emit_byte (mb, CEE_ADD);
9656                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
9657                 mono_mb_emit_byte (mb, CEE_MUL);
9658                 mono_mb_emit_ldloc (mb, realidx);
9659                 mono_mb_emit_byte (mb, CEE_ADD);
9660                 mono_mb_emit_stloc (mb, ind);
9661         }
9662
9663         /* return array->vector + ind * element_size */
9664         mono_mb_emit_ldarg (mb, 0);
9665         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
9666         mono_mb_emit_ldloc (mb, ind);
9667         if (elem_size) {
9668                 mono_mb_emit_icon (mb, elem_size);
9669         } else {
9670                 /* Load arr->vtable->klass->sizes.element_class */
9671                 mono_mb_emit_ldarg (mb, 0);
9672                 mono_mb_emit_byte (mb, CEE_CONV_I);
9673                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9674                 mono_mb_emit_byte (mb, CEE_ADD);
9675                 mono_mb_emit_byte (mb, CEE_LDIND_I);
9676                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
9677                 mono_mb_emit_byte (mb, CEE_ADD);
9678                 mono_mb_emit_byte (mb, CEE_LDIND_I);
9679                 /* sizes is an union, so this reads sizes.element_size */
9680                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoClass, sizes));
9681                 mono_mb_emit_byte (mb, CEE_ADD);
9682                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
9683         }
9684                 mono_mb_emit_byte (mb, CEE_MUL);
9685         mono_mb_emit_byte (mb, CEE_ADD);
9686         mono_mb_emit_byte (mb, CEE_RET);
9687
9688         /* patch the branches to get here and throw */
9689         for (i = 1; i < rank; ++i) {
9690                 mono_mb_patch_branch (mb, branch_positions [i]);
9691         }
9692         mono_mb_patch_branch (mb, branch_pos);
9693         /* throw exception */
9694         mono_mb_emit_exception (mb, "IndexOutOfRangeException", NULL);
9695
9696         g_free (branch_positions);
9697 #endif /* DISABLE_JIT */
9698
9699         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ELEMENT_ADDR);
9700         info->d.element_addr.rank = rank;
9701         info->d.element_addr.elem_size = elem_size;
9702         ret = mono_mb_create (mb, sig, 4, info);
9703         mono_mb_free (mb);
9704
9705         /* cache the result */
9706         cached = 0;
9707         mono_marshal_lock ();
9708         for (i = 0; i < elem_addr_cache_next; ++i) {
9709                 if (elem_addr_cache [i].rank == rank && elem_addr_cache [i].elem_size == elem_size) {
9710                         /* FIXME: free ret */
9711                         ret = elem_addr_cache [i].method;
9712                         cached = TRUE;
9713                         break;
9714                 }
9715         }
9716         if (!cached) {
9717                 if (elem_addr_cache_next >= elem_addr_cache_size) {
9718                         int new_size = elem_addr_cache_size + 4;
9719                         ArrayElemAddr *new_array = g_new0 (ArrayElemAddr, new_size);
9720                         memcpy (new_array, elem_addr_cache, elem_addr_cache_size * sizeof (ArrayElemAddr));
9721                         g_free (elem_addr_cache);
9722                         elem_addr_cache = new_array;
9723                         elem_addr_cache_size = new_size;
9724                 }
9725                 elem_addr_cache [elem_addr_cache_next].rank = rank;
9726                 elem_addr_cache [elem_addr_cache_next].elem_size = elem_size;
9727                 elem_addr_cache [elem_addr_cache_next].method = ret;
9728                 elem_addr_cache_next ++;
9729         }
9730         mono_marshal_unlock ();
9731         return ret;
9732 }
9733
9734 /*
9735  * mono_marshal_get_array_accessor_wrapper:
9736  *
9737  *   Return a wrapper which just calls METHOD, which should be an Array Get/Set/Address method.
9738  */
9739 MonoMethod *
9740 mono_marshal_get_array_accessor_wrapper (MonoMethod *method)
9741 {
9742         MonoMethodSignature *sig;
9743         MonoMethodBuilder *mb;
9744         MonoMethod *res;
9745         GHashTable *cache;
9746         int i;
9747         MonoGenericContext *ctx = NULL;
9748         MonoMethod *orig_method = NULL;
9749         MonoGenericContainer *container = NULL;
9750         WrapperInfo *info;
9751
9752         /*
9753          * These wrappers are needed to avoid the JIT replacing the calls to these methods with intrinsics
9754          * inside runtime invoke wrappers, thereby making the wrappers not unshareable.
9755          * FIXME: Use generic methods.
9756          */
9757         /*
9758          * Check cache
9759          */
9760         if (ctx) {
9761                 cache = NULL;
9762                 g_assert_not_reached ();
9763         } else {
9764                 cache = get_cache (&method->klass->image->array_accessor_cache, mono_aligned_addr_hash, NULL);
9765                 if ((res = mono_marshal_find_in_cache (cache, method)))
9766                         return res;
9767         }
9768
9769         sig = signature_dup (method->klass->image, mono_method_signature (method));
9770         sig->pinvoke = 0;
9771
9772         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNKNOWN);
9773
9774 #ifndef DISABLE_JIT
9775         /* Call the method */
9776         if (sig->hasthis)
9777                 mono_mb_emit_ldarg (mb, 0);
9778         for (i = 0; i < sig->param_count; i++)
9779                 mono_mb_emit_ldarg (mb, i + (sig->hasthis == TRUE));
9780
9781         if (ctx) {
9782                 MonoError error;
9783                 mono_mb_emit_managed_call (mb, mono_class_inflate_generic_method_checked (method, &container->context, &error), NULL);
9784                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9785         } else {
9786                 mono_mb_emit_managed_call (mb, method, NULL);
9787         }
9788         mono_mb_emit_byte (mb, CEE_RET);
9789 #endif
9790
9791         if (ctx) {
9792                 MonoMethod *def;
9793                 def = mono_mb_create_and_cache (cache, method, mb, sig, sig->param_count + 16);
9794                 res = cache_generic_wrapper (cache, orig_method, def, ctx, orig_method);
9795         } else {
9796                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ARRAY_ACCESSOR);
9797                 info->d.array_accessor.method = method;
9798
9799                 res = mono_mb_create_and_cache_full (cache, method,
9800                                                                                          mb, sig, sig->param_count + 16,
9801                                                                                          info, NULL);
9802         }
9803         mono_mb_free (mb);
9804
9805         return res;     
9806 }
9807
9808 void*
9809 mono_marshal_alloc (gulong size)
9810 {
9811         gpointer res;
9812
9813 #ifdef HOST_WIN32
9814         res = CoTaskMemAlloc (size);
9815 #else
9816         res = g_try_malloc ((gulong)size);
9817         if (!res)
9818                 mono_gc_out_of_memory ((gulong)size);
9819 #endif
9820         return res;
9821 }
9822
9823 void
9824 mono_marshal_free (gpointer ptr)
9825 {
9826 #ifdef HOST_WIN32
9827         CoTaskMemFree (ptr);
9828 #else
9829         g_free (ptr);
9830 #endif
9831 }
9832
9833 void
9834 mono_marshal_free_array (gpointer *ptr, int size) 
9835 {
9836         int i;
9837
9838         if (!ptr)
9839                 return;
9840
9841         for (i = 0; i < size; i++)
9842                 if (ptr [i])
9843                         g_free (ptr [i]);
9844 }
9845
9846 void *
9847 mono_marshal_string_to_utf16 (MonoString *s)
9848 {
9849         return s ? mono_string_chars (s) : NULL;
9850 }
9851
9852 static void *
9853 mono_marshal_string_to_utf16_copy (MonoString *s)
9854 {
9855         if (s == NULL) {
9856                 return NULL;
9857         } else {
9858                 gunichar2 *res = mono_marshal_alloc ((mono_string_length (s) * 2) + 2);
9859                 memcpy (res, mono_string_chars (s), mono_string_length (s) * 2);
9860                 res [mono_string_length (s)] = 0;
9861                 return res;
9862         }
9863 }
9864
9865 /**
9866  * mono_marshal_set_last_error:
9867  *
9868  * This function is invoked to set the last error value from a P/Invoke call
9869  * which has SetLastError set.
9870  */
9871 void
9872 mono_marshal_set_last_error (void)
9873 {
9874 #ifdef WIN32
9875         mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (GetLastError ()));
9876 #else
9877         mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (errno));
9878 #endif
9879 }
9880
9881 static void
9882 mono_marshal_set_last_error_windows (int error)
9883 {
9884 #ifdef WIN32
9885         mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (error));
9886 #endif
9887 }
9888
9889 void
9890 ves_icall_System_Runtime_InteropServices_Marshal_copy_to_unmanaged (MonoArray *src, gint32 start_index,
9891                                                                     gpointer dest, gint32 length)
9892 {
9893         int element_size;
9894         void *source_addr;
9895
9896         MONO_CHECK_ARG_NULL (src,);
9897         MONO_CHECK_ARG_NULL (dest,);
9898
9899         if (src->obj.vtable->klass->rank != 1) {
9900                 mono_set_pending_exception (mono_get_exception_argument ("array", "array is multi-dimensional"));
9901                 return;
9902         }
9903         if (start_index < 0) {
9904                 mono_set_pending_exception (mono_get_exception_argument ("startIndex", "Must be >= 0"));
9905                 return;
9906         }
9907         if (length < 0) {
9908                 mono_set_pending_exception (mono_get_exception_argument ("length", "Must be >= 0"));
9909                 return;
9910         }
9911         if (start_index + length > mono_array_length (src)) {
9912                 mono_set_pending_exception (mono_get_exception_argument ("length", "start_index + length > array length"));
9913                 return;
9914         }
9915
9916         element_size = mono_array_element_size (src->obj.vtable->klass);
9917
9918         /* no references should be involved */
9919         source_addr = mono_array_addr_with_size_fast (src, element_size, start_index);
9920
9921         memcpy (dest, source_addr, length * element_size);
9922 }
9923
9924 void
9925 ves_icall_System_Runtime_InteropServices_Marshal_copy_from_unmanaged (gpointer src, gint32 start_index,
9926                                                                       MonoArray *dest, gint32 length)
9927 {
9928         int element_size;
9929         void *dest_addr;
9930
9931         MONO_CHECK_ARG_NULL (src,);
9932         MONO_CHECK_ARG_NULL (dest,);
9933
9934         if (dest->obj.vtable->klass->rank != 1) {
9935                 mono_set_pending_exception (mono_get_exception_argument ("array", "array is multi-dimensional"));
9936                 return;
9937         }
9938         if (start_index < 0) {
9939                 mono_set_pending_exception (mono_get_exception_argument ("startIndex", "Must be >= 0"));
9940                 return;
9941         }
9942         if (length < 0) {
9943                 mono_set_pending_exception (mono_get_exception_argument ("length", "Must be >= 0"));
9944                 return;
9945         }
9946         if (start_index + length > mono_array_length (dest)) {
9947                 mono_set_pending_exception (mono_get_exception_argument ("length", "start_index + length > array length"));
9948                 return;
9949         }
9950         element_size = mono_array_element_size (dest->obj.vtable->klass);
9951           
9952         /* no references should be involved */
9953         dest_addr = mono_array_addr_with_size_fast (dest, element_size, start_index);
9954
9955         memcpy (dest_addr, src, length * element_size);
9956 }
9957
9958 MonoString *
9959 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi (char *ptr)
9960 {
9961         if (ptr == NULL)
9962                 return NULL;
9963         else
9964                 return mono_string_new (mono_domain_get (), ptr);
9965 }
9966
9967 MonoString *
9968 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi_len (char *ptr, gint32 len)
9969 {
9970         if (ptr == NULL) {
9971                 mono_set_pending_exception (mono_get_exception_argument_null ("ptr"));
9972                 return NULL;
9973         } else {
9974                 return mono_string_new_len (mono_domain_get (), ptr, len);
9975         }
9976 }
9977
9978 MonoString *
9979 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni (guint16 *ptr)
9980 {
9981         MonoDomain *domain = mono_domain_get (); 
9982         int len = 0;
9983         guint16 *t = ptr;
9984
9985         if (ptr == NULL)
9986                 return NULL;
9987
9988         while (*t++)
9989                 len++;
9990
9991         return mono_string_new_utf16 (domain, ptr, len);
9992 }
9993
9994 MonoString *
9995 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni_len (guint16 *ptr, gint32 len)
9996 {
9997         MonoDomain *domain = mono_domain_get (); 
9998
9999         if (ptr == NULL) {
10000                 mono_set_pending_exception (mono_get_exception_argument_null ("ptr"));
10001                 return NULL;
10002         } else {
10003                 return mono_string_new_utf16 (domain, ptr, len);
10004         }
10005 }
10006
10007 guint32 
10008 ves_icall_System_Runtime_InteropServices_Marshal_GetLastWin32Error (void)
10009 {
10010         return (GPOINTER_TO_INT (mono_native_tls_get_value (last_error_tls_id)));
10011 }
10012
10013 guint32 
10014 ves_icall_System_Runtime_InteropServices_Marshal_SizeOf (MonoReflectionType *rtype)
10015 {
10016         MonoClass *klass;
10017         MonoType *type;
10018         guint32 layout;
10019
10020         MONO_CHECK_ARG_NULL (rtype, 0);
10021
10022         type = rtype->type;
10023         klass = mono_class_from_mono_type (type);
10024         if (!mono_class_init (klass)) {
10025                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
10026                 return 0;
10027         }
10028
10029         layout = (klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK);
10030
10031         if (type->type == MONO_TYPE_PTR || type->type == MONO_TYPE_FNPTR) {
10032                 return sizeof (gpointer);
10033         } else if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
10034                 gchar *msg;
10035                 MonoException *exc;
10036
10037                 msg = g_strdup_printf ("Type %s cannot be marshaled as an unmanaged structure.", klass->name);
10038                 exc = mono_get_exception_argument ("t", msg);
10039                 g_free (msg);
10040                 mono_set_pending_exception (exc);
10041                 return 0;
10042         }
10043
10044         return mono_class_native_size (klass, NULL);
10045 }
10046
10047 void
10048 ves_icall_System_Runtime_InteropServices_Marshal_StructureToPtr (MonoObject *obj, gpointer dst, MonoBoolean delete_old)
10049 {
10050         MonoMethod *method;
10051         gpointer pa [3];
10052
10053         MONO_CHECK_ARG_NULL (obj,);
10054         MONO_CHECK_ARG_NULL (dst,);
10055
10056         method = mono_marshal_get_struct_to_ptr (obj->vtable->klass);
10057
10058         pa [0] = obj;
10059         pa [1] = &dst;
10060         pa [2] = &delete_old;
10061
10062         mono_runtime_invoke (method, NULL, pa, NULL);
10063 }
10064
10065 static void
10066 ptr_to_structure (gpointer src, MonoObject *dst)
10067 {
10068         MonoMethod *method;
10069         gpointer pa [2];
10070
10071         method = mono_marshal_get_ptr_to_struct (dst->vtable->klass);
10072
10073         pa [0] = &src;
10074         pa [1] = dst;
10075
10076         mono_runtime_invoke (method, NULL, pa, NULL);
10077 }
10078
10079 void
10080 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure (gpointer src, MonoObject *dst)
10081 {
10082         MonoType *t;
10083
10084         MONO_CHECK_ARG_NULL (src,);
10085         MONO_CHECK_ARG_NULL (dst,);
10086         
10087         t = mono_type_get_underlying_type (mono_class_get_type (dst->vtable->klass));
10088
10089         if (t->type == MONO_TYPE_VALUETYPE) {
10090                 MonoException *exc;
10091                 gchar *tmp;
10092
10093                 tmp = g_strdup_printf ("Destination is a boxed value type.");
10094                 exc = mono_get_exception_argument ("dst", tmp);
10095                 g_free (tmp);  
10096
10097                 mono_set_pending_exception (exc);
10098                 return;
10099         }
10100
10101         ptr_to_structure (src, dst);
10102 }
10103
10104 MonoObject *
10105 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure_type (gpointer src, MonoReflectionType *type)
10106 {
10107         MonoClass *klass;
10108         MonoDomain *domain = mono_domain_get (); 
10109         MonoObject *res;
10110
10111         if (src == NULL)
10112                 return NULL;
10113         MONO_CHECK_ARG_NULL (type, NULL);
10114
10115         klass = mono_class_from_mono_type (type->type);
10116         if (!mono_class_init (klass)) {
10117                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
10118                 return NULL;
10119         }
10120
10121         res = mono_object_new (domain, klass);
10122
10123         ptr_to_structure (src, res);
10124
10125         return res;
10126 }
10127
10128 int
10129 ves_icall_System_Runtime_InteropServices_Marshal_OffsetOf (MonoReflectionType *type, MonoString *field_name)
10130 {
10131         MonoMarshalType *info;
10132         MonoClass *klass;
10133         char *fname;
10134         int match_index = -1;
10135         
10136         MONO_CHECK_ARG_NULL (type, 0);
10137         MONO_CHECK_ARG_NULL (field_name, 0);
10138
10139         fname = mono_string_to_utf8 (field_name);
10140         klass = mono_class_from_mono_type (type->type);
10141         if (!mono_class_init (klass)) {
10142                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
10143                 return 0;
10144         }
10145
10146         while (klass && match_index == -1) {
10147                 MonoClassField* field;
10148                 int i = 0;
10149                 gpointer iter = NULL;
10150                 while ((field = mono_class_get_fields (klass, &iter))) {
10151                         if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
10152                                 continue;
10153                         if (!strcmp (fname, mono_field_get_name (field))) {
10154                                 match_index = i;
10155                                 break;
10156                         }
10157                         i ++;
10158                 }
10159
10160                 if (match_index == -1)
10161                         klass = klass->parent;
10162         }
10163
10164         g_free (fname);
10165
10166         if(match_index == -1) {
10167                 MonoException* exc;
10168                 gchar *tmp;
10169
10170                 /* Get back original class instance */
10171                 klass = mono_class_from_mono_type (type->type);
10172
10173                 tmp = g_strdup_printf ("Field passed in is not a marshaled member of the type %s", klass->name);
10174                 exc = mono_get_exception_argument ("fieldName", tmp);
10175                 g_free (tmp);
10176  
10177                 mono_set_pending_exception ((MonoException*)exc);
10178                 return 0;
10179         }
10180
10181         info = mono_marshal_load_type_info (klass);     
10182         return info->fields [match_index].offset;
10183 }
10184
10185 gpointer
10186 ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalAnsi (MonoString *string)
10187 {
10188 #ifdef HOST_WIN32
10189         char* tres, *ret;
10190         size_t len;
10191         tres = mono_string_to_utf8 (string);
10192         if (!tres)
10193                 return tres;
10194
10195         len = strlen (tres) + 1;
10196         ret = ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (len);
10197         memcpy (ret, tres, len);
10198         g_free (tres);
10199         return ret;
10200
10201 #else
10202         return mono_string_to_utf8 (string);
10203 #endif
10204 }
10205
10206 gpointer
10207 ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalUni (MonoString *string)
10208 {
10209         if (string == NULL)
10210                 return NULL;
10211         else {
10212 #ifdef TARGET_WIN32
10213                 gunichar2 *res = ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal 
10214                         ((mono_string_length (string) + 1) * 2);
10215 #else
10216                 gunichar2 *res = g_malloc ((mono_string_length (string) + 1) * 2);              
10217 #endif
10218                 memcpy (res, mono_string_chars (string), mono_string_length (string) * 2);
10219                 res [mono_string_length (string)] = 0;
10220                 return res;
10221         }
10222 }
10223
10224 static void
10225 mono_struct_delete_old (MonoClass *klass, char *ptr)
10226 {
10227         MonoMarshalType *info;
10228         int i;
10229
10230         info = mono_marshal_load_type_info (klass);
10231
10232         for (i = 0; i < info->num_fields; i++) {
10233                 MonoMarshalConv conv;
10234                 MonoType *ftype = info->fields [i].field->type;
10235                 char *cpos;
10236
10237                 if (ftype->attrs & FIELD_ATTRIBUTE_STATIC)
10238                         continue;
10239
10240                 mono_type_to_unmanaged (ftype, info->fields [i].mspec, TRUE, 
10241                                 klass->unicode, &conv);
10242                         
10243                 cpos = ptr + info->fields [i].offset;
10244
10245                 switch (conv) {
10246                 case MONO_MARSHAL_CONV_NONE:
10247                         if (MONO_TYPE_ISSTRUCT (ftype)) {
10248                                 mono_struct_delete_old (ftype->data.klass, cpos);
10249                                 continue;
10250                         }
10251                         break;
10252                 case MONO_MARSHAL_CONV_STR_LPWSTR:
10253                         /* We assume this field points inside a MonoString */
10254                         break;
10255                 case MONO_MARSHAL_CONV_STR_LPTSTR:
10256 #ifdef TARGET_WIN32
10257                         /* We assume this field points inside a MonoString 
10258                          * on Win32 */
10259                         break;
10260 #endif
10261                 case MONO_MARSHAL_CONV_STR_LPSTR:
10262                 case MONO_MARSHAL_CONV_STR_BSTR:
10263                 case MONO_MARSHAL_CONV_STR_ANSIBSTR:
10264                 case MONO_MARSHAL_CONV_STR_TBSTR:
10265                         mono_marshal_free (*(gpointer *)cpos);
10266                         break;
10267
10268                 default:
10269                         continue;
10270                 }
10271         }
10272 }
10273
10274 void
10275 ves_icall_System_Runtime_InteropServices_Marshal_DestroyStructure (gpointer src, MonoReflectionType *type)
10276 {
10277         MonoClass *klass;
10278
10279         MONO_CHECK_ARG_NULL (src,);
10280         MONO_CHECK_ARG_NULL (type,);
10281
10282         klass = mono_class_from_mono_type (type->type);
10283         if (!mono_class_init (klass)) {
10284                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
10285                 return;
10286         }
10287
10288         mono_struct_delete_old (klass, (char *)src);
10289 }
10290
10291 void*
10292 ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (int size)
10293 {
10294         gpointer res;
10295
10296         if ((gulong)size == 0)
10297                 /* This returns a valid pointer for size 0 on MS.NET */
10298                 size = 4;
10299
10300 #ifdef HOST_WIN32
10301         res = GlobalAlloc (GMEM_FIXED, (gulong)size);
10302 #else
10303         res = g_try_malloc ((gulong)size);
10304 #endif
10305         if (!res)
10306                 mono_gc_out_of_memory ((gulong)size);
10307
10308         return res;
10309 }
10310
10311 gpointer
10312 ves_icall_System_Runtime_InteropServices_Marshal_ReAllocHGlobal (gpointer ptr, int size)
10313 {
10314         gpointer res;
10315
10316         if (ptr == NULL) {
10317                 mono_gc_out_of_memory ((gulong)size);
10318                 return NULL;
10319         }
10320
10321 #ifdef HOST_WIN32
10322         res = GlobalReAlloc (ptr, (gulong)size, GMEM_MOVEABLE);
10323 #else
10324         res = g_try_realloc (ptr, (gulong)size);
10325 #endif
10326         if (!res)
10327                 mono_gc_out_of_memory ((gulong)size);
10328
10329         return res;
10330 }
10331
10332 void
10333 ves_icall_System_Runtime_InteropServices_Marshal_FreeHGlobal (void *ptr)
10334 {
10335 #ifdef HOST_WIN32
10336         GlobalFree (ptr);
10337 #else
10338         g_free (ptr);
10339 #endif
10340 }
10341
10342 void*
10343 ves_icall_System_Runtime_InteropServices_Marshal_AllocCoTaskMem (int size)
10344 {
10345         void *res;
10346
10347 #ifdef HOST_WIN32
10348         res = CoTaskMemAlloc (size);
10349 #else
10350         res = g_try_malloc ((gulong)size);
10351 #endif
10352         if (!res)
10353                 mono_gc_out_of_memory ((gulong)size);
10354         return res;
10355 }
10356
10357 void
10358 ves_icall_System_Runtime_InteropServices_Marshal_FreeCoTaskMem (void *ptr)
10359 {
10360 #ifdef HOST_WIN32
10361         CoTaskMemFree (ptr);
10362 #else
10363         g_free (ptr);
10364 #endif
10365 }
10366
10367 gpointer
10368 ves_icall_System_Runtime_InteropServices_Marshal_ReAllocCoTaskMem (gpointer ptr, int size)
10369 {
10370         void *res;
10371
10372 #ifdef HOST_WIN32
10373         res = CoTaskMemRealloc (ptr, size);
10374 #else
10375         res = g_try_realloc (ptr, (gulong)size);
10376 #endif
10377         if (!res)
10378                 mono_gc_out_of_memory ((gulong)size);
10379         return res;
10380 }
10381
10382 void*
10383 ves_icall_System_Runtime_InteropServices_Marshal_UnsafeAddrOfPinnedArrayElement (MonoArray *arrayobj, int index)
10384 {
10385         return mono_array_addr_with_size_fast (arrayobj, mono_array_element_size (arrayobj->obj.vtable->klass), index);
10386 }
10387
10388 MonoDelegate*
10389 ves_icall_System_Runtime_InteropServices_Marshal_GetDelegateForFunctionPointerInternal (void *ftn, MonoReflectionType *type)
10390 {
10391         MonoClass *klass = mono_type_get_class (type->type);
10392         if (!mono_class_init (klass)) {
10393                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
10394                 return NULL;
10395         }
10396
10397         return mono_ftnptr_to_delegate (klass, ftn);
10398 }
10399
10400 /**
10401  * mono_marshal_is_loading_type_info:
10402  *
10403  *  Return whenever mono_marshal_load_type_info () is being executed for KLASS by this
10404  * thread.
10405  */
10406 static gboolean
10407 mono_marshal_is_loading_type_info (MonoClass *klass)
10408 {
10409         GSList *loads_list = mono_native_tls_get_value (load_type_info_tls_id);
10410
10411         return g_slist_find (loads_list, klass) != NULL;
10412 }
10413
10414 /**
10415  * mono_marshal_load_type_info:
10416  *
10417  *  Initialize klass->marshal_info using information from metadata. This function can
10418  * recursively call itself, and the caller is responsible to avoid that by calling 
10419  * mono_marshal_is_loading_type_info () beforehand.
10420  *
10421  * LOCKING: Acquires the loader lock.
10422  */
10423 MonoMarshalType *
10424 mono_marshal_load_type_info (MonoClass* klass)
10425 {
10426         int j, count = 0;
10427         guint32 native_size = 0, min_align = 1, packing;
10428         MonoMarshalType *info;
10429         MonoClassField* field;
10430         gpointer iter;
10431         guint32 layout;
10432         GSList *loads_list;
10433
10434         g_assert (klass != NULL);
10435
10436         if (klass->marshal_info)
10437                 return klass->marshal_info;
10438
10439         if (!klass->inited)
10440                 mono_class_init (klass);
10441
10442         if (klass->marshal_info)
10443                 return klass->marshal_info;
10444
10445         /*
10446          * This function can recursively call itself, so we keep the list of classes which are
10447          * under initialization in a TLS list.
10448          */
10449         g_assert (!mono_marshal_is_loading_type_info (klass));
10450         loads_list = mono_native_tls_get_value (load_type_info_tls_id);
10451         loads_list = g_slist_prepend (loads_list, klass);
10452         mono_native_tls_set_value (load_type_info_tls_id, loads_list);
10453         
10454         iter = NULL;
10455         while ((field = mono_class_get_fields (klass, &iter))) {
10456                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
10457                         continue;
10458                 if (mono_field_is_deleted (field))
10459                         continue;
10460                 count++;
10461         }
10462
10463         layout = klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
10464
10465         /* The mempool is protected by the loader lock */
10466         info = mono_image_alloc0 (klass->image, MONO_SIZEOF_MARSHAL_TYPE + sizeof (MonoMarshalField) * count);
10467         info->num_fields = count;
10468         
10469         /* Try to find a size for this type in metadata */
10470         mono_metadata_packing_from_typedef (klass->image, klass->type_token, NULL, &native_size);
10471
10472         if (klass->parent) {
10473                 int parent_size = mono_class_native_size (klass->parent, NULL);
10474
10475                 /* Add parent size to real size */
10476                 native_size += parent_size;
10477                 info->native_size = parent_size;
10478         }
10479
10480         packing = klass->packing_size ? klass->packing_size : 8;
10481         iter = NULL;
10482         j = 0;
10483         while ((field = mono_class_get_fields (klass, &iter))) {
10484                 int size;
10485                 guint32 align;
10486                 
10487                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
10488                         continue;
10489
10490                 if (mono_field_is_deleted (field))
10491                         continue;
10492                 if (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL)
10493                         mono_metadata_field_info_with_mempool (klass->image, mono_metadata_token_index (mono_class_get_field_token (field)) - 1, 
10494                                                   NULL, NULL, &info->fields [j].mspec);
10495
10496                 info->fields [j].field = field;
10497
10498                 if ((mono_class_num_fields (klass) == 1) && (klass->instance_size == sizeof (MonoObject)) &&
10499                         (strcmp (mono_field_get_name (field), "$PRIVATE$") == 0)) {
10500                         /* This field is a hack inserted by MCS to empty structures */
10501                         continue;
10502                 }
10503
10504                 switch (layout) {
10505                 case TYPE_ATTRIBUTE_AUTO_LAYOUT:
10506                 case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
10507                         size = mono_marshal_type_size (field->type, info->fields [j].mspec, 
10508                                                        &align, TRUE, klass->unicode);
10509                         align = klass->packing_size ? MIN (klass->packing_size, align): align;
10510                         min_align = MAX (align, min_align);
10511                         info->fields [j].offset = info->native_size;
10512                         info->fields [j].offset += align - 1;
10513                         info->fields [j].offset &= ~(align - 1);
10514                         info->native_size = info->fields [j].offset + size;
10515                         break;
10516                 case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
10517                         size = mono_marshal_type_size (field->type, info->fields [j].mspec, 
10518                                                        &align, TRUE, klass->unicode);
10519                         min_align = MAX (align, min_align);
10520                         info->fields [j].offset = field->offset - sizeof (MonoObject);
10521                         info->native_size = MAX (info->native_size, info->fields [j].offset + size);
10522                         break;
10523                 }       
10524                 j++;
10525         }
10526
10527         if (layout != TYPE_ATTRIBUTE_AUTO_LAYOUT) {
10528                 info->native_size = MAX (native_size, info->native_size);
10529                 /*
10530                  * If the provided Size is equal or larger than the calculated size, and there
10531                  * was no Pack attribute, we set min_align to 1 to avoid native_size being increased
10532                  */
10533                 if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
10534                         if (native_size && native_size == info->native_size && klass->packing_size == 0)
10535                                 min_align = 1;
10536                         else
10537                                 min_align = MIN (min_align, packing);
10538                 }
10539         }
10540
10541         if (info->native_size & (min_align - 1)) {
10542                 info->native_size += min_align - 1;
10543                 info->native_size &= ~(min_align - 1);
10544         }
10545
10546         info->min_align = min_align;
10547
10548         /* Update the class's blittable info, if the layouts don't match */
10549         if (info->native_size != mono_class_value_size (klass, NULL))
10550                 klass->blittable = FALSE;
10551
10552         /* If this is an array type, ensure that we have element info */
10553         if (klass->rank && !mono_marshal_is_loading_type_info (klass->element_class)) {
10554                 mono_marshal_load_type_info (klass->element_class);
10555         }
10556
10557         loads_list = mono_native_tls_get_value (load_type_info_tls_id);
10558         loads_list = g_slist_remove (loads_list, klass);
10559         mono_native_tls_set_value (load_type_info_tls_id, loads_list);
10560
10561         mono_marshal_lock ();
10562         if (!klass->marshal_info) {
10563                 /*We do double-checking locking on marshal_info */
10564                 mono_memory_barrier ();
10565                 klass->marshal_info = info;
10566         }
10567         mono_marshal_unlock ();
10568
10569         return klass->marshal_info;
10570 }
10571
10572 /**
10573  * mono_class_native_size:
10574  * @klass: a class 
10575  * 
10576  * Returns: the native size of an object instance (when marshaled 
10577  * to unmanaged code) 
10578  */
10579 gint32
10580 mono_class_native_size (MonoClass *klass, guint32 *align)
10581 {       
10582         if (!klass->marshal_info) {
10583                 if (mono_marshal_is_loading_type_info (klass)) {
10584                         if (align)
10585                                 *align = 0;
10586                         return 0;
10587                 } else {
10588                         mono_marshal_load_type_info (klass);
10589                 }
10590         }
10591
10592         if (align)
10593                 *align = klass->marshal_info->min_align;
10594
10595         return klass->marshal_info->native_size;
10596 }
10597
10598 /*
10599  * mono_type_native_stack_size:
10600  * @t: the type to return the size it uses on the stack
10601  *
10602  * Returns: the number of bytes required to hold an instance of this
10603  * type on the native stack
10604  */
10605 int
10606 mono_type_native_stack_size (MonoType *t, guint32 *align)
10607 {
10608         guint32 tmp;
10609
10610         g_assert (t != NULL);
10611
10612         if (!align)
10613                 align = &tmp;
10614
10615         if (t->byref) {
10616                 *align = sizeof (gpointer);
10617                 return sizeof (gpointer);
10618         }
10619
10620         switch (t->type){
10621         case MONO_TYPE_BOOLEAN:
10622         case MONO_TYPE_CHAR:
10623         case MONO_TYPE_I1:
10624         case MONO_TYPE_U1:
10625         case MONO_TYPE_I2:
10626         case MONO_TYPE_U2:
10627         case MONO_TYPE_I4:
10628         case MONO_TYPE_U4:
10629                 *align = 4;
10630                 return 4;
10631         case MONO_TYPE_I:
10632         case MONO_TYPE_U:
10633         case MONO_TYPE_STRING:
10634         case MONO_TYPE_OBJECT:
10635         case MONO_TYPE_CLASS:
10636         case MONO_TYPE_SZARRAY:
10637         case MONO_TYPE_PTR:
10638         case MONO_TYPE_FNPTR:
10639         case MONO_TYPE_ARRAY:
10640                 *align = sizeof (gpointer);
10641                 return sizeof (gpointer);
10642         case MONO_TYPE_R4:
10643                 *align = 4;
10644                 return 4;
10645         case MONO_TYPE_R8:
10646                 *align = MONO_ABI_ALIGNOF (double);
10647                 return 8;
10648         case MONO_TYPE_I8:
10649         case MONO_TYPE_U8:
10650                 *align = MONO_ABI_ALIGNOF (gint64);
10651                 return 8;
10652         case MONO_TYPE_GENERICINST:
10653                 if (!mono_type_generic_inst_is_valuetype (t)) {
10654                         *align = sizeof (gpointer);
10655                         return sizeof (gpointer);
10656                 } 
10657                 /* Fall through */
10658         case MONO_TYPE_TYPEDBYREF:
10659         case MONO_TYPE_VALUETYPE: {
10660                 guint32 size;
10661                 MonoClass *klass = mono_class_from_mono_type (t);
10662
10663                 if (klass->enumtype)
10664                         return mono_type_native_stack_size (mono_class_enum_basetype (klass), align);
10665                 else {
10666                         size = mono_class_native_size (klass, align);
10667                         *align = *align + 3;
10668                         *align &= ~3;
10669                         
10670                         size +=  3;
10671                         size &= ~3;
10672
10673                         return size;
10674                 }
10675         }
10676         default:
10677                 g_error ("type 0x%02x unknown", t->type);
10678         }
10679         return 0;
10680 }
10681
10682 gint32
10683 mono_marshal_type_size (MonoType *type, MonoMarshalSpec *mspec, guint32 *align,
10684                         gboolean as_field, gboolean unicode)
10685 {
10686         MonoMarshalNative native_type = mono_type_to_unmanaged (type, mspec, as_field, unicode, NULL);
10687         MonoClass *klass;
10688
10689         switch (native_type) {
10690         case MONO_NATIVE_BOOLEAN:
10691                 *align = 4;
10692                 return 4;
10693         case MONO_NATIVE_I1:
10694         case MONO_NATIVE_U1:
10695                 *align = 1;
10696                 return 1;
10697         case MONO_NATIVE_I2:
10698         case MONO_NATIVE_U2:
10699         case MONO_NATIVE_VARIANTBOOL:
10700                 *align = 2;
10701                 return 2;
10702         case MONO_NATIVE_I4:
10703         case MONO_NATIVE_U4:
10704         case MONO_NATIVE_ERROR:
10705                 *align = 4;
10706                 return 4;
10707         case MONO_NATIVE_I8:
10708         case MONO_NATIVE_U8:
10709                 *align = MONO_ABI_ALIGNOF (gint64);
10710                 return 8;
10711         case MONO_NATIVE_R4:
10712                 *align = 4;
10713                 return 4;
10714         case MONO_NATIVE_R8:
10715                 *align = MONO_ABI_ALIGNOF (double);
10716                 return 8;
10717         case MONO_NATIVE_INT:
10718         case MONO_NATIVE_UINT:
10719         case MONO_NATIVE_LPSTR:
10720         case MONO_NATIVE_LPWSTR:
10721         case MONO_NATIVE_LPTSTR:
10722         case MONO_NATIVE_BSTR:
10723         case MONO_NATIVE_ANSIBSTR:
10724         case MONO_NATIVE_TBSTR:
10725         case MONO_NATIVE_LPARRAY:
10726         case MONO_NATIVE_SAFEARRAY:
10727         case MONO_NATIVE_IUNKNOWN:
10728         case MONO_NATIVE_IDISPATCH:
10729         case MONO_NATIVE_INTERFACE:
10730         case MONO_NATIVE_ASANY:
10731         case MONO_NATIVE_FUNC:
10732         case MONO_NATIVE_LPSTRUCT:
10733                 *align = MONO_ABI_ALIGNOF (gpointer);
10734                 return sizeof (gpointer);
10735         case MONO_NATIVE_STRUCT: 
10736                 klass = mono_class_from_mono_type (type);
10737                 if (klass == mono_defaults.object_class &&
10738                         (mspec && mspec->native == MONO_NATIVE_STRUCT)) {
10739                 *align = 16;
10740                 return 16;
10741                 }
10742                 return mono_class_native_size (klass, align);
10743         case MONO_NATIVE_BYVALTSTR: {
10744                 int esize = unicode ? 2: 1;
10745                 g_assert (mspec);
10746                 *align = esize;
10747                 return mspec->data.array_data.num_elem * esize;
10748         }
10749         case MONO_NATIVE_BYVALARRAY: {
10750                 // FIXME: Have to consider ArraySubType
10751                 int esize;
10752                 klass = mono_class_from_mono_type (type);
10753                 if (klass->element_class == mono_defaults.char_class) {
10754                         esize = unicode ? 2 : 1;
10755                         *align = esize;
10756                 } else {
10757                         esize = mono_class_native_size (klass->element_class, align);
10758                 }
10759                 g_assert (mspec);
10760                 return mspec->data.array_data.num_elem * esize;
10761         }
10762         case MONO_NATIVE_CUSTOM:
10763                 *align = sizeof (gpointer);
10764                 return sizeof (gpointer);
10765                 break;
10766         case MONO_NATIVE_CURRENCY:
10767         case MONO_NATIVE_VBBYREFSTR:
10768         default:
10769                 g_error ("native type %02x not implemented", native_type); 
10770                 break;
10771         }
10772         g_assert_not_reached ();
10773         return 0;
10774 }
10775
10776 gpointer
10777 mono_marshal_asany (MonoObject *o, MonoMarshalNative string_encoding, int param_attrs)
10778 {
10779         MonoType *t;
10780         MonoClass *klass;
10781
10782         if (o == NULL)
10783                 return NULL;
10784
10785         t = &o->vtable->klass->byval_arg;
10786         switch (t->type) {
10787         case MONO_TYPE_I4:
10788         case MONO_TYPE_U4:
10789         case MONO_TYPE_PTR:
10790         case MONO_TYPE_I1:
10791         case MONO_TYPE_U1:
10792         case MONO_TYPE_BOOLEAN:
10793         case MONO_TYPE_I2:
10794         case MONO_TYPE_U2:
10795         case MONO_TYPE_CHAR:
10796         case MONO_TYPE_I8:
10797         case MONO_TYPE_U8:
10798         case MONO_TYPE_R4:
10799         case MONO_TYPE_R8:
10800                 return mono_object_unbox (o);
10801                 break;
10802         case MONO_TYPE_STRING:
10803                 switch (string_encoding) {
10804                 case MONO_NATIVE_LPWSTR:
10805                         return mono_marshal_string_to_utf16_copy ((MonoString*)o);
10806                         break;
10807                 case MONO_NATIVE_LPSTR:
10808                         return mono_string_to_lpstr ((MonoString*)o);
10809                         break;
10810                 default:
10811                         g_warning ("marshaling conversion %d not implemented", string_encoding);
10812                         g_assert_not_reached ();
10813                 }
10814                 break;
10815         case MONO_TYPE_CLASS:
10816         case MONO_TYPE_VALUETYPE: {
10817                 MonoMethod *method;
10818                 gpointer pa [3];
10819                 gpointer res;
10820                 MonoBoolean delete_old = FALSE;
10821
10822                 klass = t->data.klass;
10823
10824                 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
10825                         break;
10826
10827                 if (klass->valuetype && (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
10828                         klass->blittable || klass->enumtype))
10829                         return mono_object_unbox (o);
10830
10831                 res = mono_marshal_alloc (mono_class_native_size (klass, NULL));
10832
10833                 if (!((param_attrs & PARAM_ATTRIBUTE_OUT) && !(param_attrs & PARAM_ATTRIBUTE_IN))) {
10834                         method = mono_marshal_get_struct_to_ptr (o->vtable->klass);
10835
10836                         pa [0] = o;
10837                         pa [1] = &res;
10838                         pa [2] = &delete_old;
10839
10840                         mono_runtime_invoke (method, NULL, pa, NULL);
10841                 }
10842
10843                 return res;
10844         }
10845         default:
10846                 break;
10847         }
10848         mono_raise_exception (mono_get_exception_argument ("", "No PInvoke conversion exists for value passed to Object-typed parameter."));
10849         return NULL;
10850 }
10851
10852 void
10853 mono_marshal_free_asany (MonoObject *o, gpointer ptr, MonoMarshalNative string_encoding, int param_attrs)
10854 {
10855         MonoType *t;
10856         MonoClass *klass;
10857
10858         if (o == NULL)
10859                 return;
10860
10861         t = &o->vtable->klass->byval_arg;
10862         switch (t->type) {
10863         case MONO_TYPE_STRING:
10864                 switch (string_encoding) {
10865                 case MONO_NATIVE_LPWSTR:
10866                 case MONO_NATIVE_LPSTR:
10867                         mono_marshal_free (ptr);
10868                         break;
10869                 default:
10870                         g_warning ("marshaling conversion %d not implemented", string_encoding);
10871                         g_assert_not_reached ();
10872                 }
10873                 break;
10874         case MONO_TYPE_CLASS:
10875         case MONO_TYPE_VALUETYPE: {
10876                 klass = t->data.klass;
10877
10878                 if (klass->valuetype && (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
10879                                                                  klass->blittable || klass->enumtype))
10880                         break;
10881
10882                 if (param_attrs & PARAM_ATTRIBUTE_OUT) {
10883                         MonoMethod *method = mono_marshal_get_ptr_to_struct (o->vtable->klass);
10884                         gpointer pa [2];
10885
10886                         pa [0] = &ptr;
10887                         pa [1] = o;
10888
10889                         mono_runtime_invoke (method, NULL, pa, NULL);
10890                 }
10891
10892                 if (!((param_attrs & PARAM_ATTRIBUTE_OUT) && !(param_attrs & PARAM_ATTRIBUTE_IN))) {
10893                         mono_struct_delete_old (klass, ptr);
10894                 }
10895
10896                 mono_marshal_free (ptr);
10897                 break;
10898         }
10899         default:
10900                 break;
10901         }
10902 }
10903
10904 MonoMethod *
10905 mono_marshal_get_generic_array_helper (MonoClass *class, MonoClass *iface, gchar *name, MonoMethod *method)
10906 {
10907         MonoMethodSignature *sig, *csig;
10908         MonoMethodBuilder *mb;
10909         MonoMethod *res;
10910         WrapperInfo *info;
10911         int i;
10912
10913         mb = mono_mb_new_no_dup_name (class, name, MONO_WRAPPER_MANAGED_TO_MANAGED);
10914         mb->method->slot = -1;
10915
10916         mb->method->flags = METHOD_ATTRIBUTE_PRIVATE | METHOD_ATTRIBUTE_VIRTUAL |
10917                 METHOD_ATTRIBUTE_NEW_SLOT | METHOD_ATTRIBUTE_HIDE_BY_SIG | METHOD_ATTRIBUTE_FINAL;
10918
10919         sig = mono_method_signature (method);
10920         csig = signature_dup (method->klass->image, sig);
10921         csig->generic_param_count = 0;
10922
10923 #ifndef DISABLE_JIT
10924         mono_mb_emit_ldarg (mb, 0);
10925         for (i = 0; i < csig->param_count; i++)
10926                 mono_mb_emit_ldarg (mb, i + 1);
10927         mono_mb_emit_managed_call (mb, method, NULL);
10928         mono_mb_emit_byte (mb, CEE_RET);
10929
10930         /* We can corlib internal methods */
10931         mb->skip_visibility = TRUE;
10932 #endif
10933         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER);
10934         info->d.generic_array_helper.method = method;
10935         res = mono_mb_create (mb, csig, csig->param_count + 16, info);
10936
10937         mono_mb_free (mb);
10938
10939         return res;
10940 }
10941
10942 /*
10943  * The mono_win32_compat_* functions are implementations of inline
10944  * Windows kernel32 APIs, which are DllImport-able under MS.NET,
10945  * although not exported by kernel32.
10946  *
10947  * We map the appropiate kernel32 entries to these functions using
10948  * dllmaps declared in the global etc/mono/config.
10949  */
10950
10951 void
10952 mono_win32_compat_CopyMemory (gpointer dest, gconstpointer source, gsize length)
10953 {
10954         if (!dest || !source)
10955                 return;
10956
10957         memcpy (dest, source, length);
10958 }
10959
10960 void
10961 mono_win32_compat_FillMemory (gpointer dest, gsize length, guchar fill)
10962 {
10963         memset (dest, fill, length);
10964 }
10965
10966 void
10967 mono_win32_compat_MoveMemory (gpointer dest, gconstpointer source, gsize length)
10968 {
10969         if (!dest || !source)
10970                 return;
10971
10972         memmove (dest, source, length);
10973 }
10974
10975 void
10976 mono_win32_compat_ZeroMemory (gpointer dest, gsize length)
10977 {
10978         memset (dest, 0, length);
10979 }
10980
10981 void
10982 mono_marshal_find_nonzero_bit_offset (guint8 *buf, int len, int *byte_offset, guint8 *bitmask)
10983 {
10984         int i;
10985         guint8 byte;
10986
10987         for (i = 0; i < len; ++i)
10988                 if (buf [i])
10989                         break;
10990
10991         g_assert (i < len);
10992
10993         byte = buf [i];
10994         while (byte && !(byte & 1))
10995                 byte >>= 1;
10996         g_assert (byte == 1);
10997
10998         *byte_offset = i;
10999         *bitmask = buf [i];
11000 }
11001
11002 MonoMethod *
11003 mono_marshal_get_thunk_invoke_wrapper (MonoMethod *method)
11004 {
11005         MonoMethodBuilder *mb;
11006         MonoMethodSignature *sig, *csig;
11007         MonoExceptionClause *clause;
11008         MonoImage *image;
11009         MonoClass *klass;
11010         GHashTable *cache;
11011         MonoMethod *res;
11012         int i, param_count, sig_size, pos_leave;
11013
11014         g_assert (method);
11015
11016         klass = method->klass;
11017         image = method->klass->image;
11018         cache = get_cache (&image->thunk_invoke_cache, mono_aligned_addr_hash, NULL);
11019
11020         if ((res = mono_marshal_find_in_cache (cache, method)))
11021                 return res;
11022
11023         sig = mono_method_signature (method);
11024         mb = mono_mb_new (klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
11025
11026         /* add "this" and exception param */
11027         param_count = sig->param_count + sig->hasthis + 1;
11028
11029         /* dup & extend signature */
11030         csig = mono_metadata_signature_alloc (image, param_count);
11031         sig_size = MONO_SIZEOF_METHOD_SIGNATURE + sig->param_count * sizeof (MonoType *);
11032         memcpy (csig, sig, sig_size);
11033         csig->param_count = param_count;
11034         csig->hasthis = 0;
11035         csig->pinvoke = 1;
11036         csig->call_convention = MONO_CALL_DEFAULT;
11037
11038         if (sig->hasthis) {
11039                 /* add "this" */
11040                 csig->params [0] = &klass->byval_arg;
11041                 /* move params up by one */
11042                 for (i = 0; i < sig->param_count; i++)
11043                         csig->params [i + 1] = sig->params [i];
11044         }
11045
11046         /* setup exception param as byref+[out] */
11047         csig->params [param_count - 1] = mono_metadata_type_dup (image,
11048                  &mono_defaults.exception_class->byval_arg);
11049         csig->params [param_count - 1]->byref = 1;
11050         csig->params [param_count - 1]->attrs = PARAM_ATTRIBUTE_OUT;
11051
11052         /* convert struct return to object */
11053         if (MONO_TYPE_ISSTRUCT (sig->ret))
11054                 csig->ret = &mono_defaults.object_class->byval_arg;
11055
11056 #ifndef DISABLE_JIT
11057         /* local 0 (temp for exception object) */
11058         mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
11059
11060         /* local 1 (temp for result) */
11061         if (!MONO_TYPE_IS_VOID (sig->ret))
11062                 mono_mb_add_local (mb, sig->ret);
11063
11064         /* clear exception arg */
11065         mono_mb_emit_ldarg (mb, param_count - 1);
11066         mono_mb_emit_byte (mb, CEE_LDNULL);
11067         mono_mb_emit_byte (mb, CEE_STIND_REF);
11068
11069         /* try */
11070         clause = mono_image_alloc0 (image, sizeof (MonoExceptionClause));
11071         clause->try_offset = mono_mb_get_label (mb);
11072
11073         /* push method's args */
11074         for (i = 0; i < param_count - 1; i++) {
11075                 MonoType *type;
11076                 MonoClass *klass;
11077
11078                 mono_mb_emit_ldarg (mb, i);
11079
11080                 /* get the byval type of the param */
11081                 klass = mono_class_from_mono_type (csig->params [i]);
11082                 type = &klass->byval_arg;
11083
11084                 /* unbox struct args */
11085                 if (MONO_TYPE_ISSTRUCT (type)) {
11086                         mono_mb_emit_op (mb, CEE_UNBOX, klass);
11087
11088                         /* byref args & and the "this" arg must remain a ptr.
11089                            Otherwise make a copy of the value type */
11090                         if (!(csig->params [i]->byref || (i == 0 && sig->hasthis)))
11091                                 mono_mb_emit_op (mb, CEE_LDOBJ, klass);
11092
11093                         csig->params [i] = &mono_defaults.object_class->byval_arg;
11094                 }
11095         }
11096
11097         /* call */
11098         if (method->flags & METHOD_ATTRIBUTE_VIRTUAL)
11099                 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
11100         else
11101                 mono_mb_emit_op (mb, CEE_CALL, method);
11102
11103         /* save result at local 1 */
11104         if (!MONO_TYPE_IS_VOID (sig->ret))
11105                 mono_mb_emit_stloc (mb, 1);
11106
11107         pos_leave = mono_mb_emit_branch (mb, CEE_LEAVE);
11108
11109         /* catch */
11110         clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
11111         clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
11112         clause->data.catch_class = mono_defaults.object_class;
11113
11114         clause->handler_offset = mono_mb_get_label (mb);
11115
11116         /* store exception at local 0 */
11117         mono_mb_emit_stloc (mb, 0);
11118         mono_mb_emit_ldarg (mb, param_count - 1);
11119         mono_mb_emit_ldloc (mb, 0);
11120         mono_mb_emit_byte (mb, CEE_STIND_REF);
11121         mono_mb_emit_branch (mb, CEE_LEAVE);
11122
11123         clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
11124
11125         mono_mb_set_clauses (mb, 1, clause);
11126
11127         mono_mb_patch_branch (mb, pos_leave);
11128         /* end-try */
11129
11130         if (!MONO_TYPE_IS_VOID (sig->ret)) {
11131                 mono_mb_emit_ldloc (mb, 1);
11132
11133                 /* box the return value */
11134                 if (MONO_TYPE_ISSTRUCT (sig->ret))
11135                         mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (sig->ret));
11136         }
11137
11138         mono_mb_emit_byte (mb, CEE_RET);
11139 #endif
11140
11141         res = mono_mb_create_and_cache (cache, method, mb, csig, param_count + 16);
11142         mono_mb_free (mb);
11143
11144         return res;
11145 }
11146
11147 /*
11148  * mono_marshal_free_dynamic_wrappers:
11149  *
11150  *   Free wrappers of the dynamic method METHOD.
11151  */
11152 void
11153 mono_marshal_free_dynamic_wrappers (MonoMethod *method)
11154 {
11155         MonoImage *image = method->klass->image;
11156
11157         g_assert (method_is_dynamic (method));
11158
11159         /* This could be called during shutdown */
11160         if (marshal_mutex_initialized)
11161                 mono_marshal_lock ();
11162         /* 
11163          * FIXME: We currently leak the wrappers. Freeing them would be tricky as
11164          * they could be shared with other methods ?
11165          */
11166         if (image->runtime_invoke_direct_cache)
11167                 g_hash_table_remove (image->runtime_invoke_direct_cache, method);
11168         if (image->delegate_abstract_invoke_cache)
11169                 g_hash_table_foreach_remove (image->delegate_abstract_invoke_cache, signature_pointer_pair_matches_pointer, method);
11170         // FIXME: Need to clear the caches in other images as well
11171         if (image->delegate_bound_static_invoke_cache)
11172                 g_hash_table_remove (image->delegate_bound_static_invoke_cache, mono_method_signature (method));
11173
11174         if (marshal_mutex_initialized)
11175                 mono_marshal_unlock ();
11176 }
11177
11178 static gboolean
11179 signature_pointer_pair_matches_signature (gpointer key, gpointer value, gpointer user_data)
11180 {
11181        SignaturePointerPair *pair = (SignaturePointerPair*)key;
11182        MonoMethodSignature *sig = (MonoMethodSignature*)user_data;
11183
11184        return mono_metadata_signature_equal (pair->sig, sig);
11185 }
11186
11187 /*
11188  * mono_marshal_free_inflated_wrappers:
11189  *
11190  *   Free wrappers of the inflated method METHOD.
11191  */
11192 void
11193 mono_marshal_free_inflated_wrappers (MonoMethod *method)
11194 {
11195        MonoMethodSignature *sig = method->signature;
11196
11197        g_assert (method->is_inflated);
11198
11199        /* Ignore calls occuring late during cleanup.  */
11200        if (!marshal_mutex_initialized)
11201                return;
11202
11203        mono_marshal_lock ();
11204        /*
11205         * FIXME: We currently leak the wrappers. Freeing them would be tricky as
11206         * they could be shared with other methods ?
11207         */
11208
11209         /*
11210          * indexed by MonoMethodSignature
11211          */
11212            /* FIXME: This could remove unrelated wrappers as well */
11213        if (sig && method->klass->image->delegate_begin_invoke_cache)
11214                g_hash_table_remove (method->klass->image->delegate_begin_invoke_cache, sig);
11215        if (sig && method->klass->image->delegate_end_invoke_cache)
11216                g_hash_table_remove (method->klass->image->delegate_end_invoke_cache, sig);
11217        if (sig && method->klass->image->delegate_invoke_cache)
11218                g_hash_table_remove (method->klass->image->delegate_invoke_cache, sig);
11219        if (sig && method->klass->image->runtime_invoke_cache)
11220                g_hash_table_remove (method->klass->image->runtime_invoke_cache, sig);
11221        if (sig && method->klass->image->runtime_invoke_vtype_cache)
11222                g_hash_table_remove (method->klass->image->runtime_invoke_vtype_cache, sig);
11223
11224         /*
11225          * indexed by SignaturePointerPair
11226          */
11227        if (sig && method->klass->image->delegate_abstract_invoke_cache)
11228                g_hash_table_foreach_remove (method->klass->image->delegate_abstract_invoke_cache,
11229                                             signature_pointer_pair_matches_signature, (gpointer)sig);
11230
11231         /*
11232          * indexed by MonoMethod pointers
11233          */
11234        if (method->klass->image->runtime_invoke_direct_cache)
11235                g_hash_table_remove (method->klass->image->runtime_invoke_direct_cache, method);
11236        if (method->klass->image->managed_wrapper_cache)
11237                g_hash_table_remove (method->klass->image->managed_wrapper_cache, method);
11238        if (method->klass->image->native_wrapper_cache)
11239                g_hash_table_remove (method->klass->image->native_wrapper_cache, method);
11240        if (method->klass->image->remoting_invoke_cache)
11241                g_hash_table_remove (method->klass->image->remoting_invoke_cache, method);
11242        if (method->klass->image->synchronized_cache)
11243                g_hash_table_remove (method->klass->image->synchronized_cache, method);
11244        if (method->klass->image->unbox_wrapper_cache)
11245                g_hash_table_remove (method->klass->image->unbox_wrapper_cache, method);
11246        if (method->klass->image->cominterop_invoke_cache)
11247                g_hash_table_remove (method->klass->image->cominterop_invoke_cache, method);
11248        if (method->klass->image->cominterop_wrapper_cache)
11249                g_hash_table_remove (method->klass->image->cominterop_wrapper_cache, method);
11250        if (method->klass->image->thunk_invoke_cache)
11251                g_hash_table_remove (method->klass->image->thunk_invoke_cache, method);
11252        if (method->klass->image->native_func_wrapper_aot_cache)
11253                g_hash_table_remove (method->klass->image->native_func_wrapper_aot_cache, method);
11254
11255        mono_marshal_unlock ();
11256 }