Wed Apr 24 18:43:29 CEST 2002 Paolo Molaro <lupus@ximian.com>
[mono.git] / mono / metadata / object.c
1 /*
2  * object.c: Object creation for the Mono runtime
3  *
4  * Author:
5  *   Miguel de Icaza (miguel@ximian.com)
6  *
7  * (C) 2001 Ximian, Inc.
8  */
9 #include <config.h>
10 #include <stdlib.h>
11 #include <stdio.h>
12 #include <signal.h>
13 #include <string.h>
14 #include <mono/metadata/mono-endian.h>
15 #include <mono/metadata/tabledefs.h>
16 #include <mono/metadata/tokentype.h>
17 #include <mono/metadata/loader.h>
18 #include <mono/metadata/object.h>
19 #include <mono/metadata/gc.h>
20 #include <mono/metadata/appdomain.h>
21 #if HAVE_BOEHM_GC
22 #include <gc/gc.h>
23 #endif
24
25 MonoStats mono_stats;
26
27 /* next object id for object hashcode */
28 static guint32 uoid = 0;
29
30 void
31 mono_runtime_object_init (MonoObject *this)
32 {
33         int i;
34         MonoMethod *method = NULL;
35         MonoClass *klass = this->vtable->klass;
36
37         for (i = 0; i < klass->method.count; ++i) {
38                 if (!strcmp (".ctor", klass->methods [i]->name) &&
39                     klass->methods [i]->signature->param_count == 0) {
40                         method = klass->methods [i];
41                         break;
42                 }
43         }
44
45         g_assert (method);
46
47         mono_runtime_invoke (method, this, NULL);
48 }
49
50 /*
51  * runtime_class_init:
52  * @klass: klass that needs to be initialized
53  *
54  * This routine calls the class constructor for @class.
55  */
56 void
57 mono_runtime_class_init (MonoClass *klass)
58 {
59         int i;
60
61         for (i = 0; i < klass->method.count; ++i) {
62                 MonoMethod *method = klass->methods [i];
63                 if ((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) && 
64                     (strcmp (".cctor", method->name) == 0)) {
65                         mono_runtime_invoke (method, NULL, NULL);
66                         return;
67                 }
68         }
69         /* No class constructor found */
70 }
71
72 static gpointer
73 default_trampoline (MonoMethod *method)
74 {
75         return method;
76 }
77
78 static gpointer
79 default_remoting_trampoline (MonoMethod *method)
80 {
81         g_error ("remoting not installed");
82         return NULL;
83 }
84
85 static MonoTrampoline arch_create_jit_trampoline = default_trampoline;
86 static MonoTrampoline arch_create_remoting_trampoline = default_remoting_trampoline;
87
88 void
89 mono_install_trampoline (MonoTrampoline func) 
90 {
91         arch_create_jit_trampoline = func? func: default_trampoline;
92 }
93
94 void
95 mono_install_remoting_trampoline (MonoTrampoline func) 
96 {
97         arch_create_remoting_trampoline = func? func: default_remoting_trampoline;
98 }
99
100 #if 0 && HAVE_BOEHM_GC
101 static void
102 vtable_finalizer (void *obj, void *data) {
103         g_print ("%s finalized (%p)\n", (char*)data, obj);
104 }
105 #endif
106
107 /**
108  * mono_class_vtable:
109  * @domain: the application domain
110  * @class: the class to initialize
111  *
112  * VTables are domain specific because we create domain specific code, and 
113  * they contain the domain specific static class data.
114  */
115 MonoVTable *
116 mono_class_vtable (MonoDomain *domain, MonoClass *class)
117 {
118         MonoClass *k;
119         MonoVTable *vt;
120         MonoClassField *field;
121         guint32 cindex;
122         guint32 cols [MONO_CONSTANT_SIZE];
123         const char *p;
124         char *t;
125         int i, len;
126
127         g_assert (class);
128
129         /* can interfaces have static fields? */
130         if (class->flags & TYPE_ATTRIBUTE_INTERFACE)
131                 g_assert_not_reached ();
132
133         mono_domain_lock (domain);
134         if ((vt = mono_g_hash_table_lookup (domain->class_vtable_hash, class))) {
135                 mono_domain_unlock (domain);
136                 return vt;
137         }
138         
139         if (!class->inited)
140                 mono_class_init (class);
141
142 //      mono_stats.used_class_count++;
143 //      mono_stats.class_vtable_size += sizeof (MonoVTable) + class->vtable_size * sizeof (gpointer);
144
145         vt = mono_mempool_alloc0 (domain->mp,  sizeof (MonoVTable) + 
146                                   class->vtable_size * sizeof (gpointer));
147         vt->klass = class;
148         vt->domain = domain;
149
150         if (class->class_size) {
151 #if HAVE_BOEHM_GC
152                 vt->data = GC_malloc (class->class_size + 8);
153                 /*vt->data = GC_debug_malloc (class->class_size + 8, class->name, 2);*/
154                 /*GC_register_finalizer (vt->data, vtable_finalizer, class->name, NULL, NULL);*/
155                 mono_g_hash_table_insert (domain->static_data_hash, class, vt->data);
156 #else
157                 vt->data = mono_mempool_alloc0 (domain->mp, class->class_size + 8);
158                 
159 #endif
160 //              mono_stats.class_static_data_size += class->class_size + 8;
161         }
162
163         for (i = class->field.first; i < class->field.last; ++i) {
164                 field = &class->fields [i - class->field.first];
165                 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
166                         continue;
167                 if (!(field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT))
168                         continue;
169                 cindex = mono_metadata_get_constant_index (class->image, MONO_TOKEN_FIELD_DEF | (i + 1));
170                 if (!cindex) {
171                         g_warning ("constant for field %s not found", field->name);
172                         continue;
173                 }
174                 mono_metadata_decode_row (&class->image->tables [MONO_TABLE_CONSTANT], cindex - 1, cols, MONO_CONSTANT_SIZE);
175                 p = mono_metadata_blob_heap (class->image, cols [MONO_CONSTANT_VALUE]);
176                 len = mono_metadata_decode_blob_size (p, &p);
177                 t = (char*)vt->data + field->offset;
178                 /* should we check that the type matches? */
179                 switch (cols [MONO_CONSTANT_TYPE]) {
180                 case MONO_TYPE_BOOLEAN:
181                 case MONO_TYPE_U1:
182                 case MONO_TYPE_I1:
183                         *t = *p;
184                         break;
185                 case MONO_TYPE_CHAR:
186                 case MONO_TYPE_U2:
187                 case MONO_TYPE_I2: {
188                         guint16 *val = (guint16*)t;
189                         *val = read16 (p);
190                         break;
191                 }
192                 case MONO_TYPE_U4:
193                 case MONO_TYPE_I4: {
194                         guint32 *val = (guint32*)t;
195                         *val = read32 (p);
196                         break;
197                 }
198                 case MONO_TYPE_U8:
199                 case MONO_TYPE_I8: {
200                         guint64 *val = (guint64*)t;
201                         *val = read64 (p);
202                         break;
203                 }
204                 case MONO_TYPE_R4: {
205                         float *val = (float*)t;
206                         readr4 (p, val);
207                         break;
208                 }
209                 case MONO_TYPE_R8: {
210                         double *val = (double*)t;
211                         readr8 (p, val);
212                         break;
213                 }
214                 case MONO_TYPE_STRING: {
215                         //gpointer *val = (gpointer*)t;
216                         //*val = mono_string_new_utf16 (domain, (const guint16*)p, len/2);
217                         break;
218                 }
219                 case MONO_TYPE_CLASS:
220                         /* nothing to do, we malloc0 the data and the value can be 0 only */
221                         break;
222                 default:
223                         g_warning ("type 0x%02x should not be in constant table", cols [MONO_CONSTANT_TYPE]);
224                 }
225         }
226
227         vt->max_interface_id = class->max_interface_id;
228         
229         vt->interface_offsets = mono_mempool_alloc0 (domain->mp, 
230                 sizeof (gpointer) * (class->max_interface_id + 1));
231
232         /* initialize interface offsets */
233         for (k = class; k ; k = k->parent) {
234                 for (i = 0; i < k->interface_count; i++) {
235                         int slot;
236                         MonoClass *ic = k->interfaces [i];
237                         slot = class->interface_offsets [ic->interface_id];
238                         vt->interface_offsets [ic->interface_id] = &vt->vtable [slot];
239                 }
240         }
241
242         /* initialize vtable */
243         for (i = 0; i < class->vtable_size; ++i) {
244                 MonoMethod *cm;
245                
246                 if ((cm = class->vtable [i]))
247                         vt->vtable [i] = arch_create_jit_trampoline (cm);
248         }
249
250         mono_g_hash_table_insert (domain->class_vtable_hash, class, vt);
251         mono_domain_unlock (domain);
252
253         mono_runtime_class_init (class);
254
255         return vt;
256 }
257
258 /**
259  * mono_class_proxy_vtable:
260  * @domain: the application domain
261  * @class: the class to proxy
262  *
263  * Creates a vtable for transparent proxies. It is basically
264  * a copy of the real vtable of @class, but all function pointers invoke
265  * the remoting functions, and vtable->klass points to the 
266  * transparent proxy class, and not to @class.
267  */
268 MonoVTable *
269 mono_class_proxy_vtable (MonoDomain *domain, MonoClass *class)
270 {
271         MonoVTable *vt, *pvt;
272         int i, vtsize;
273
274         if ((pvt = mono_g_hash_table_lookup (domain->proxy_vtable_hash, class)))
275                 return pvt;
276
277         vt = mono_class_vtable (domain, class);
278         vtsize = sizeof (MonoVTable) + class->vtable_size * sizeof (gpointer);
279
280 //      mono_stats.class_vtable_size += vtsize;
281
282         pvt = mono_mempool_alloc (domain->mp, vtsize);
283         memcpy (pvt, vt, vtsize);
284
285         pvt->klass = mono_defaults.transparent_proxy_class;
286
287         /* initialize vtable */
288         for (i = 0; i < class->vtable_size; ++i) {
289                 MonoMethod *cm;
290                
291                 if ((cm = class->vtable [i]))
292                         pvt->vtable [i] = arch_create_remoting_trampoline (cm);
293         }
294
295         mono_g_hash_table_insert (domain->proxy_vtable_hash, class, pvt);
296
297         return pvt;
298 }
299
300 static MonoInvokeFunc default_mono_runtime_invoke = NULL;
301
302 MonoObject*
303 mono_runtime_invoke (MonoMethod *method, void *obj, void **params)
304 {
305         if (!default_mono_runtime_invoke) {
306                 g_error ("runtime invoke called on uninitialized runtime");
307                 return NULL;
308         }
309         return default_mono_runtime_invoke (method, obj, params);
310 }
311
312 int
313 mono_runtime_exec_main (MonoMethod *method, MonoArray *args)
314 {
315         gpointer pa [1];
316
317         pa [0] = args;
318
319         if (method->signature->ret->type == MONO_TYPE_I4) {
320                 MonoObject *res;
321                 res = mono_runtime_invoke (method, NULL, pa);
322                 return *(guint32 *)((char *)res + sizeof (MonoObject));
323         } else {
324                 mono_runtime_invoke (method, NULL, pa);
325                 return 0;
326         }
327 }
328
329 void
330 mono_install_runtime_invoke (MonoInvokeFunc func)
331 {
332         default_mono_runtime_invoke = func;
333 }
334
335 MonoObject*
336 mono_runtime_invoke_array (MonoMethod *method, void *obj, MonoArray *params)
337 {
338         MonoMethodSignature *sig = method->signature;
339         gpointer *pa = NULL;
340         int i;
341                 
342         if (NULL != params) {
343                 pa = alloca (sizeof (gpointer) * mono_array_length (params));
344                 for (i = 0; i < mono_array_length (params); i++) {
345                         if (sig->params [i]->byref) {
346                                 /* nothing to do */
347                         }
348
349                         switch (sig->params [i]->type) {
350                         case MONO_TYPE_U1:
351                         case MONO_TYPE_I1:
352                         case MONO_TYPE_BOOLEAN:
353                         case MONO_TYPE_U2:
354                         case MONO_TYPE_I2:
355                         case MONO_TYPE_CHAR:
356                         case MONO_TYPE_U:
357                         case MONO_TYPE_I:
358                         case MONO_TYPE_U4:
359                         case MONO_TYPE_I4:
360                         case MONO_TYPE_U8:
361                         case MONO_TYPE_I8:
362                         case MONO_TYPE_VALUETYPE:
363                                 pa [i] = (char *)(((gpointer *)params->vector)[i]) + sizeof (MonoObject);
364                                 break;
365                         case MONO_TYPE_STRING:
366                         case MONO_TYPE_OBJECT:
367                         case MONO_TYPE_CLASS:
368                                 pa [i] = (char *)(((gpointer *)params->vector)[i]);
369                                 break;
370                         default:
371                                 g_error ("type 0x%x not handled in ves_icall_InternalInvoke", sig->params [i]->type);
372                         }
373                 }
374         }
375
376         if (!strcmp (method->name, ".ctor")) {
377                 obj = mono_object_new (mono_domain_get (), method->klass);
378                 mono_runtime_invoke (method, obj, pa);
379                 return obj;
380         } else
381                 return mono_runtime_invoke (method, obj, pa);
382 }
383
384 /**
385  * mono_object_allocate:
386  * @size: number of bytes to allocate
387  *
388  * This is a very simplistic routine until we have our GC-aware
389  * memory allocator. 
390  *
391  * Returns: an allocated object of size @size, or NULL on failure.
392  */
393 void *
394 mono_object_allocate (size_t size)
395 {
396 #if HAVE_BOEHM_GC
397         void *o = GC_debug_malloc (size, "object", 1);
398 #else
399         void *o = calloc (1, size);
400 #endif
401
402         return o;
403 }
404
405 /**
406  * mono_object_free:
407  *
408  * Frees the memory used by the object.  Debugging purposes
409  * only, as we will have our GC system.
410  */
411 void
412 mono_object_free (MonoObject *o)
413 {
414 #if HAVE_BOEHM_GC
415         g_error ("mono_object_free called with boehm gc.");
416 #else
417         MonoClass *c = o->vtable->klass;
418         
419         memset (o, 0, c->instance_size);
420         free (o);
421 #endif
422 }
423
424 /**
425  * mono_object_new:
426  * @klass: the class of the object that we want to create
427  *
428  * Returns: A newly created object whose definition is
429  * looked up using @klass
430  */
431 MonoObject *
432 mono_object_new (MonoDomain *domain, MonoClass *klass)
433 {
434         return mono_object_new_specific (mono_class_vtable (domain, klass));
435 }
436
437 /**
438  * mono_object_new_specific:
439  * @vtable: the vtable of the object that we want to create
440  *
441  * Returns: A newly created object with class and domain specified
442  * by @vtable
443  */
444 MonoObject *
445 mono_object_new_specific (MonoVTable *vtable)
446 {
447         MonoObject *o;
448
449         mono_stats.new_object_count++;          /* thread safe? */
450
451         if (vtable->klass->ghcimpl)
452                 o = mono_object_allocate (vtable->klass->instance_size);
453         else {
454                 guint32 *t;
455                 t = mono_object_allocate (vtable->klass->instance_size + 4);
456                 *t = ++uoid;
457                 o = (MonoObject *)(++t);
458         }
459         o->vtable = vtable;
460         if (vtable->klass->has_finalize)
461                 mono_object_register_finalizer (o);
462         
463         return o;
464 }
465
466 /**
467  * mono_object_new_from_token:
468  * @image: Context where the type_token is hosted
469  * @token: a token of the type that we want to create
470  *
471  * Returns: A newly created object whose definition is
472  * looked up using @token in the @image image
473  */
474 MonoObject *
475 mono_object_new_from_token  (MonoDomain *domain, MonoImage *image, guint32 token)
476 {
477         MonoClass *class;
478
479         class = mono_class_get (image, token);
480
481         return mono_object_new (domain, class);
482 }
483
484
485 /**
486  * mono_object_clone:
487  * @obj: the object to clone
488  *
489  * Returns: A newly created object who is a shallow copy of @obj
490  */
491 MonoObject *
492 mono_object_clone (MonoObject *obj)
493 {
494         MonoObject *o;
495         int size;
496
497         size = obj->vtable->klass->instance_size;
498         o = mono_object_allocate (size);
499
500         memcpy (o, obj, size);
501
502         if (obj->vtable->klass->has_finalize)
503                 mono_object_register_finalizer (o);
504         return o;
505 }
506
507 /**
508  * mono_array_clone:
509  * @array: the array to clone
510  *
511  * Returns: A newly created array who is a shallow copy of @array
512  */
513 MonoArray*
514 mono_array_clone (MonoArray *array)
515 {
516         MonoArray *o;
517         int size, i;
518         guint32 *sizes;
519         MonoClass *klass = array->obj.vtable->klass;
520
521         if (array->bounds == NULL) {
522                 size = mono_array_length (array);
523                 o = mono_array_new_full (((MonoObject *)array)->vtable->domain,
524                                          klass, &size, NULL);
525
526                 size *= mono_array_element_size (klass);
527                 memcpy (o, array, sizeof (MonoArray) + size);
528
529                 return o;
530         }
531         
532         sizes = alloca (klass->rank * sizeof(guint32) * 2);
533         size = mono_array_element_size (klass);
534         for (i = 0; i < klass->rank; ++i) {
535                 sizes [i] = array->bounds [i].length;
536                 size *= array->bounds [i].length;
537                 sizes [i + klass->rank] = array->bounds [i].lower_bound;
538         }
539         o = mono_array_new_full (((MonoObject *)array)->vtable->domain, 
540                                  klass, sizes, sizes + klass->rank);
541         memcpy (o, array, sizeof(MonoArray) + size);
542
543         return o;
544 }
545
546 /*
547  * mono_array_new_full:
548  * @domain: domain where the object is created
549  * @array_class: array class
550  * @lengths: lengths for each dimension in the array
551  * @lower_bounds: lower bounds for each dimension in the array (may be NULL)
552  *
553  * This routine creates a new array objects with the given dimensions,
554  * lower bounds and type.
555  */
556 MonoArray*
557 mono_array_new_full (MonoDomain *domain, MonoClass *array_class, 
558                      guint32 *lengths, guint32 *lower_bounds)
559 {
560         guint32 byte_len, len;
561         MonoObject *o;
562         MonoArray *array;
563         MonoArrayBounds *bounds;
564         int i;
565
566         if (!array_class->inited)
567                 mono_class_init (array_class);
568
569         byte_len = mono_array_element_size (array_class);
570         len = 1;
571
572         if (array_class->rank == 1 &&
573             (lower_bounds == NULL || lower_bounds [0] == 0)) {
574                 bounds = NULL;
575                 len = lengths [0];
576         } else {
577         #if HAVE_BOEHM_GC
578                 bounds = GC_debug_malloc (sizeof (MonoArrayBounds) * array_class->rank, "bounds", 0);
579         #else
580                 bounds = g_malloc0 (sizeof (MonoArrayBounds) * array_class->rank);
581         #endif
582                 for (i = 0; i < array_class->rank; ++i) {
583                         bounds [i].length = lengths [i];
584                         len *= lengths [i];
585                 }
586
587                 if (lower_bounds)
588                         for (i = 0; i < array_class->rank; ++i)
589                                 bounds [i].lower_bound = lower_bounds [i];
590         }
591
592         byte_len *= len;
593         /* 
594          * Following three lines almost taken from mono_object_new ():
595          * they need to be kept in sync.
596          */
597         o = mono_object_allocate (sizeof (MonoArray) + byte_len);
598         if (!o)
599                 G_BREAKPOINT ();
600         o->vtable = mono_class_vtable (domain, array_class);
601
602         array = (MonoArray*)o;
603
604         array->bounds = bounds;
605         array->max_length = len;
606
607         return array;
608 }
609
610 /*
611  * mono_array_new:
612  * @domain: domain where the object is created
613  * @eclass: element class
614  * @n: number of array elements
615  *
616  * This routine creates a new szarray with @n elements of type @eclass.
617  */
618 MonoArray *
619 mono_array_new (MonoDomain *domain, MonoClass *eclass, guint32 n)
620 {
621         MonoClass *ac;
622
623         ac = mono_array_class_get (&eclass->byval_arg, 1);
624         g_assert (ac != NULL);
625
626         return mono_array_new_specific (mono_class_vtable (domain, ac), n);
627 }
628
629 /*
630  * mono_array_new_specific:
631  * @vtable: a vtable in the appropriate domain for an initialized class
632  * @n: number of array elements
633  *
634  * This routine is a fast alternative to mono_array_new() for code which
635  * can be sure about the domain it operates in.
636  */
637 MonoArray *
638 mono_array_new_specific (MonoVTable *vtable, guint32 n)
639 {
640         MonoObject *o;
641         MonoArray *ao;
642         gsize byte_len;
643
644         byte_len = n * mono_array_element_size (vtable->klass);
645         o = mono_object_allocate (sizeof (MonoArray) + byte_len);
646         if (!o)
647                 G_BREAKPOINT ();
648         o->vtable = vtable;
649
650         ao = (MonoArray *)o;
651         ao->bounds = NULL;
652         ao->max_length = n;
653
654         return ao;
655 }
656
657 /**
658  * mono_string_new_utf16:
659  * @text: a pointer to an utf16 string
660  * @len: the length of the string
661  *
662  * Returns: A newly created string object which contains @text.
663  */
664 MonoString *
665 mono_string_new_utf16 (MonoDomain *domain, const guint16 *text, gint32 len)
666 {
667         MonoString *s;
668         
669         s = mono_string_new_size (domain, len);
670         g_assert (s != NULL);
671
672         memcpy (mono_string_chars (s), text, len * 2);
673
674         return s;
675 }
676
677 /**
678  * mono_string_new_size:
679  * @text: a pointer to an utf16 string
680  * @len: the length of the string
681  *
682  * Returns: A newly created string object of @len
683  */
684 MonoString *
685 mono_string_new_size (MonoDomain *domain, gint32 len)
686 {
687         MonoString *s;
688
689         s = (MonoString*)mono_object_allocate (sizeof (MonoString) + ((len + 1) * 2));
690         if (!s)
691                 G_BREAKPOINT ();
692
693         s->object.vtable = mono_class_vtable (domain, mono_defaults.string_class);
694         s->length = len;
695
696         return s;
697 }
698
699 /*
700  * mono_string_new_len:
701  * @text: a pointer to an utf8 string
702  * @length: number of bytes in @text to consider
703  *
704  * Returns: A newly created string object which contains @text.
705  */
706 MonoString*
707 mono_string_new_len (MonoDomain *domain, const char *text, guint length)
708 {
709         GError *error = NULL;
710         MonoString *o = NULL;
711         guint16 *ut;
712         glong items_written;
713
714         
715         ut = g_utf8_to_utf16 (text, length, NULL, &items_written, &error);
716
717         if (!error)
718                 o = mono_string_new_utf16 (domain, ut, items_written);
719         else 
720                 g_error_free (error);
721
722         g_free (ut);
723
724         return o;
725 }
726
727 /**
728  * mono_string_new:
729  * @text: a pointer to an utf8 string
730  *
731  * Returns: A newly created string object which contains @text.
732  */
733 MonoString*
734 mono_string_new (MonoDomain *domain, const char *text)
735 {
736         GError *error = NULL;
737         MonoString *o = NULL;
738         guint16 *ut;
739         glong items_written;
740         int l;
741
742         l = strlen (text);
743         
744         ut = g_utf8_to_utf16 (text, l, NULL, &items_written, &error);
745
746         if (!error)
747                 o = mono_string_new_utf16 (domain, ut, items_written);
748         else 
749                 g_error_free (error);
750
751         g_free (ut);
752
753         return o;
754 }
755
756 /*
757  * mono_string_new_wrapper:
758  * @text: pointer to utf8 characters.
759  *
760  * Helper function to create a string object from @text in the current domain.
761  */
762 MonoString*
763 mono_string_new_wrapper (const char *text)
764 {
765         MonoDomain *domain = mono_domain_get ();
766
767         return mono_string_new (domain, text);
768 }
769
770 /**
771  * mono_value_box:
772  * @class: the class of the value
773  * @value: a pointer to the unboxed data
774  *
775  * Returns: A newly created object which contains @value.
776  */
777 MonoObject *
778 mono_value_box (MonoDomain *domain, MonoClass *class, gpointer value)
779 {
780         MonoObject *res;
781         int size;
782
783         g_assert (class->valuetype);
784
785         size = mono_class_instance_size (class);
786         res = mono_object_allocate (size);
787         res->vtable = mono_class_vtable (domain, class);
788
789         size = size - sizeof (MonoObject);
790
791         memcpy ((char *)res + sizeof (MonoObject), value, size);
792
793         if (class->has_finalize)
794                 mono_object_register_finalizer (res);
795         return res;
796 }
797
798 /**
799  * mono_object_isinst:
800  * @obj: an object
801  * @klass: a pointer to a class 
802  *
803  * Returns: @obj if @obj is derived from @klass
804  */
805 MonoObject *
806 mono_object_isinst (MonoObject *obj, MonoClass *klass)
807 {
808         MonoVTable *vt;
809         MonoClass *oklass;
810
811         if (!obj)
812                 return NULL;
813
814         vt = obj->vtable;
815         oklass = vt->klass;
816
817         if (!klass->inited)
818                 mono_class_init (klass);
819
820         if (klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
821                 if ((klass->interface_id <= oklass->max_interface_id) &&
822                     vt->interface_offsets [klass->interface_id])
823                         return obj;
824         } else {
825                 if (oklass == mono_defaults.transparent_proxy_class) {
826                         /* fixme: add check for IRemotingTypeInfo */
827                         oklass = ((MonoTransparentProxy *)obj)->klass;
828                 }
829                 if (klass->rank) {
830                         if (oklass->rank == klass->rank && 
831                             (oklass->element_class->baseval - klass->element_class->baseval) <= 
832                             klass->element_class->diffval)
833                                 return obj;
834                         
835                 } else if ((oklass->baseval - klass->baseval) <= klass->diffval)
836                         return obj;
837         }
838
839         return NULL;
840 }
841
842 static MonoString*
843 mono_string_is_interned_lookup (MonoString *str, int insert)
844 {
845         MonoGHashTable *ldstr_table;
846         MonoString *res;
847         MonoDomain *domain;
848         char *ins = g_malloc (4 + str->length * 2);
849         char *p;
850         int bloblen;
851         
852         /* Encode the length */
853         p = ins;
854         mono_metadata_encode_value (2 * str->length, p, &p);
855         bloblen = p - ins;
856         p = ins;
857         mono_metadata_encode_value (bloblen + 2 * str->length, p, &p);
858         bloblen = (p - ins) + 2 * str->length;
859         /*
860          * ins is stored in the hash table as a key and needs to have the same
861          * representation as in the metadata: we swap the character bytes on big
862          * endian boxes.
863          */
864 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
865         {
866                 int i;
867                 char *p2 = mono_string_chars (str);
868                 for (i = 0; i < str->length; ++i) {
869                         *p++ = p2 [1];
870                         *p++ = p2 [0];
871                         p2 += 2;
872                 }
873         }
874 #else
875         memcpy (p, mono_string_chars (str), str->length * 2);
876 #endif
877         domain = ((MonoObject *)str)->vtable->domain;
878         ldstr_table = domain->ldstr_table;
879         mono_domain_lock (domain);
880         if ((res = mono_g_hash_table_lookup (ldstr_table, ins))) {
881                 mono_domain_unlock (domain);
882                 g_free (ins);
883                 return res;
884         }
885         if (insert) {
886                 mono_g_hash_table_insert (ldstr_table, ins, str);
887                 mono_domain_unlock (domain);
888                 return str;
889         }
890         mono_domain_unlock (domain);
891         g_free (ins);
892         return NULL;
893 }
894
895 MonoString*
896 mono_string_is_interned (MonoString *o)
897 {
898         return mono_string_is_interned_lookup (o, FALSE);
899 }
900
901 MonoString*
902 mono_string_intern (MonoString *str)
903 {
904         return mono_string_is_interned_lookup (str, TRUE);
905 }
906
907 /*
908  * mono_ldstr:
909  * @domain: the domain where the string will be used.
910  * @image: a metadata context
911  * @idx: index into the user string table.
912  * 
913  * Implementation for the ldstr opcode.
914  */
915 MonoString*
916 mono_ldstr (MonoDomain *domain, MonoImage *image, guint32 idx)
917 {
918         const char *str, *sig;
919         MonoString *o;
920         size_t len2;
921                 
922         sig = str = mono_metadata_user_string (image, idx);
923
924         mono_domain_lock (domain);
925         if ((o = mono_g_hash_table_lookup (domain->ldstr_table, sig))) {
926                 mono_domain_unlock (domain);
927                 return o;
928         }
929         
930         len2 = mono_metadata_decode_blob_size (str, &str);
931         len2 >>= 1;
932
933         o = mono_string_new_utf16 (domain, (guint16*)str, len2);
934 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
935         {
936                 int i;
937                 guint16 *p2 = (guint16*)mono_array_addr (o->c_str, guint16, 0);
938                 for (i = 0; i < len2; ++i) {
939                         *p2 = GUINT16_FROM_LE (*p2);
940                         ++p2;
941                 }
942         }
943 #endif
944         mono_g_hash_table_insert (domain->ldstr_table, (gpointer)sig, o);
945         mono_domain_unlock (domain);
946
947         return o;
948 }
949
950 /*
951  * mono_string_to_utf8:
952  * @s: a System.String
953  *
954  * Return the UTF8 representation for @s.
955  * the resulting buffer nedds to be freed with g_free().
956  */
957 char *
958 mono_string_to_utf8 (MonoString *s)
959 {
960         char *as;
961         GError *error = NULL;
962
963         g_assert (s != NULL);
964
965         if (!s->length)
966                 return g_strdup ("");
967
968         as = g_utf16_to_utf8 (mono_string_chars (s), s->length, NULL, NULL, &error);
969         if (error)
970                 g_warning (error->message);
971
972         return as;
973 }
974
975 /*
976  * mono_string_to_utf16:
977  * @s: a MonoString
978  *
979  * Return an null-terminated array of the utf-16 chars
980  * contained in @s. The result must be freed with g_free().
981  * This is a temporary helper until our string implementation
982  * is reworked to always include the null terminating char.
983  */
984 gunichar2 *
985 mono_string_to_utf16 (MonoString *s)
986 {
987         char *as;
988
989         g_assert (s != NULL);
990
991         as = g_malloc ((s->length * 2) + 2);
992         as [(s->length * 2)] = '\0';
993         as [(s->length * 2) + 1] = '\0';
994
995         if (!s->length) {
996                 return (gunichar2 *)(as);
997         }
998         
999         memcpy (as, mono_string_chars(s), s->length * 2);
1000         
1001         return (gunichar2 *)(as);
1002 }
1003
1004 static void
1005 default_ex_handler (MonoException *ex)
1006 {
1007         MonoObject *o = (MonoObject*)ex;
1008         g_error ("Exception %s.%s raised in C code", o->vtable->klass->name_space, o->vtable->klass->name);
1009 }
1010
1011 static MonoExceptionFunc ex_handler = default_ex_handler;
1012
1013 void
1014 mono_install_handler        (MonoExceptionFunc func)
1015 {
1016         ex_handler = func? func: default_ex_handler;
1017 }
1018
1019 /*
1020  * mono_raise_exception:
1021  * @ex: exception object
1022  *
1023  * Signal the runtime that the exception @ex has been raised in unmanaged code.
1024  */
1025 void
1026 mono_raise_exception (MonoException *ex) 
1027 {
1028         ex_handler (ex);
1029 }
1030
1031 MonoWaitHandle *
1032 mono_wait_handle_new (MonoDomain *domain, HANDLE handle)
1033 {
1034         MonoWaitHandle *res;
1035
1036         res = (MonoWaitHandle *)mono_object_new (domain, mono_defaults.waithandle_class);
1037
1038         res->handle = handle;
1039
1040         return res;
1041 }
1042
1043 MonoAsyncResult *
1044 mono_async_result_new (MonoDomain *domain, HANDLE handle, MonoObject *state, gpointer data)
1045 {
1046         MonoAsyncResult *res;
1047
1048         res = (MonoAsyncResult *)mono_object_new (domain, mono_defaults.asyncresult_class);
1049
1050         res->data = data;
1051         res->async_state = state;
1052         res->handle = (MonoObject *)mono_wait_handle_new (domain, handle);
1053         res->sync_completed = FALSE;
1054         res->completed = FALSE;
1055
1056         return res;
1057 }
1058
1059 void
1060 mono_message_init (MonoDomain *domain,
1061                    MonoMethodMessage *this, 
1062                    MonoReflectionMethod *method,
1063                    MonoArray *out_args)
1064 {
1065         MonoMethodSignature *sig = method->method->signature;
1066         MonoString *name;
1067         int i, j;
1068         char **names;
1069         guint8 arg_type;
1070
1071         this->method = method;
1072
1073         this->args = mono_array_new (domain, mono_defaults.object_class, sig->param_count);
1074         this->arg_types = mono_array_new (domain, mono_defaults.byte_class, sig->param_count);
1075
1076         names = g_new (char *, sig->param_count);
1077         mono_method_get_param_names (method->method, (const char **) names);
1078         this->names = mono_array_new (domain, mono_defaults.string_class, sig->param_count);
1079         
1080         for (i = 0; i < sig->param_count; i++) {
1081                  name = mono_string_new (domain, names [i]);
1082                  mono_array_set (this->names, gpointer, i, name);       
1083         }
1084
1085         g_free (names);
1086         
1087         for (i = 0, j = 0; i < sig->param_count; i++) {
1088
1089                 if (sig->params [i]->byref) {
1090                         if (out_args) {
1091                                 gpointer arg = mono_array_get (out_args, gpointer, j);
1092                                 mono_array_set (this->args, gpointer, i, arg);
1093                                 j++;
1094                         }
1095                         arg_type = 2;
1096                         if (sig->params [i]->attrs & PARAM_ATTRIBUTE_IN)
1097                                 arg_type |= 1;
1098                 } else {
1099                         arg_type = 1;
1100                 }
1101
1102                 mono_array_set (this->arg_types, guint8, i, arg_type);
1103         }
1104 }
1105
1106 /**
1107  * mono_remoting_invoke:
1108  * @real_proxy: pointer to a RealProxy object
1109  * @msg: The MonoMethodMessage to execute
1110  * @exc: used to store exceptions
1111  * @out_args: used to store output arguments
1112  *
1113  * This is used to call RealProxy::Invoke(). RealProxy::Invoke() returns an
1114  * IMessage interface and it is not trivial to extract results from there. So
1115  * we call an helper method PrivateInvoke instead of calling
1116  * RealProxy::Invoke() directly.
1117  *
1118  * Returns: the result object.
1119  */
1120 MonoObject *
1121 mono_remoting_invoke (MonoObject *real_proxy, MonoMethodMessage *msg, 
1122                       MonoObject **exc, MonoArray **out_args)
1123 {
1124         static MonoMethod *im = NULL;
1125         gpointer pa [4];
1126
1127         //static MonoObject *(*invoke) (gpointer, gpointer, MonoObject **, MonoArray **) = NULL;
1128
1129         /* fixme: make this domain dependent */
1130         if (!im) {
1131                 MonoClass *klass;
1132                 int i;
1133
1134                 klass = mono_defaults.real_proxy_class; 
1135                        
1136                 for (i = 0; i < klass->method.count; ++i) {
1137                         if (!strcmp ("PrivateInvoke", klass->methods [i]->name) &&
1138                             klass->methods [i]->signature->param_count == 4) {
1139                                 im = klass->methods [i];
1140                                 break;
1141                         }
1142                 }
1143         
1144                 g_assert (im);
1145         }
1146
1147         pa [0] = real_proxy;
1148         pa [1] = msg;
1149         pa [2] = exc;
1150         pa [3] = out_args;
1151
1152         return mono_runtime_invoke (im, NULL, pa);
1153 }
1154
1155 MonoObject *
1156 mono_message_invoke (MonoObject *target, MonoMethodMessage *msg, 
1157                      MonoObject **exc, MonoArray **out_args) 
1158 {
1159         if (target && target->vtable->klass == mono_defaults.transparent_proxy_class) {
1160
1161                 return mono_remoting_invoke ((MonoObject *)((MonoTransparentProxy *)target)->rp, 
1162                                              msg, exc, out_args);
1163
1164         } else {
1165                 MonoDomain *domain = mono_domain_get (); 
1166                 MonoMethod *method = msg->method->method;
1167                 MonoMethodSignature *sig = method->signature;
1168                 int i, j, outarg_count = 0;
1169
1170                 for (i = 0; i < sig->param_count; i++) {
1171                         if (sig->params [i]->byref) 
1172                                 outarg_count++;
1173                 }
1174
1175                 *out_args = mono_array_new (domain, mono_defaults.object_class, outarg_count);
1176                 *exc = NULL;
1177
1178                 for (i = 0, j = 0; i < sig->param_count; i++) {
1179                         if (sig->params [i]->byref) {
1180                                 gpointer arg;
1181                                 arg = mono_array_get (msg->args, gpointer, i);
1182                                 mono_array_set (*out_args, gpointer, j, arg);
1183                                 j++;
1184                         }
1185                 }
1186
1187                 return mono_runtime_invoke_array (method, target, msg->args);
1188         }
1189 }
1190
1191
1192