2 * object.c: Object creation for the Mono runtime
5 * Miguel de Icaza (miguel@ximian.com)
7 * (C) 2001 Ximian, Inc.
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 #include <mono/metadata/assembly.h>
22 #include <mono/metadata/threadpool.h>
23 #include <mono/metadata/marshal.h>
24 #include "mono/metadata/debug-helpers.h"
25 #include "mono/metadata/marshal.h"
31 mono_runtime_object_init (MonoObject *this)
34 MonoMethod *method = NULL;
35 MonoClass *klass = this->vtable->klass;
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];
47 mono_runtime_invoke (method, this, NULL, NULL);
52 * @klass: klass that needs to be initialized
54 * This routine calls the class constructor for @class.
57 mono_runtime_class_init (MonoClass *klass)
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, NULL);
70 /* No class constructor found */
74 default_trampoline (MonoMethod *method)
80 default_remoting_trampoline (MonoMethod *method)
82 g_error ("remoting not installed");
86 static MonoTrampoline arch_create_jit_trampoline = default_trampoline;
87 static MonoTrampoline arch_create_remoting_trampoline = default_remoting_trampoline;
90 mono_install_trampoline (MonoTrampoline func)
92 arch_create_jit_trampoline = func? func: default_trampoline;
96 mono_install_remoting_trampoline (MonoTrampoline func)
98 arch_create_remoting_trampoline = func? func: default_remoting_trampoline;
101 static MonoCompileFunc default_mono_compile_method = NULL;
104 mono_install_compile_method (MonoCompileFunc func)
106 default_mono_compile_method = func;
110 mono_compile_method (MonoMethod *method)
112 if (!default_mono_compile_method) {
113 g_error ("compile method called on uninitialized runtime");
116 return default_mono_compile_method (method);
120 #if 0 && HAVE_BOEHM_GC
122 vtable_finalizer (void *obj, void *data) {
123 g_print ("%s finalized (%p)\n", (char*)data, obj);
129 * @domain: the application domain
130 * @class: the class to initialize
132 * VTables are domain specific because we create domain specific code, and
133 * they contain the domain specific static class data.
136 mono_class_vtable (MonoDomain *domain, MonoClass *class)
140 MonoClassField *field;
142 guint32 cols [MONO_CONSTANT_SIZE];
149 vt = class->cached_vtable;
150 if (vt && vt->domain == domain)
153 /* can interfaces have static fields? */
154 if (class->flags & TYPE_ATTRIBUTE_INTERFACE)
155 g_assert_not_reached ();
157 mono_domain_lock (domain);
158 if ((vt = mono_g_hash_table_lookup (domain->class_vtable_hash, class))) {
159 mono_domain_unlock (domain);
164 mono_class_init (class);
166 mono_stats.used_class_count++;
167 mono_stats.class_vtable_size += sizeof (MonoVTable) + class->vtable_size * sizeof (gpointer);
169 vt = mono_mempool_alloc0 (domain->mp, sizeof (MonoVTable) +
170 class->vtable_size * sizeof (gpointer));
174 if (class->class_size) {
176 vt->data = GC_malloc (class->class_size + 8);
177 /*vt->data = GC_debug_malloc (class->class_size + 8, class->name, 2);*/
178 /*GC_register_finalizer (vt->data, vtable_finalizer, class->name, NULL, NULL);*/
179 mono_g_hash_table_insert (domain->static_data_hash, class, vt->data);
181 vt->data = mono_mempool_alloc0 (domain->mp, class->class_size + 8);
184 mono_stats.class_static_data_size += class->class_size + 8;
187 for (i = class->field.first; i < class->field.last; ++i) {
188 field = &class->fields [i - class->field.first];
189 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
191 if ((field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA)) {
192 MonoClass *fklass = mono_class_from_mono_type (field->type);
193 t = (char*)vt->data + field->offset;
194 g_assert (fklass->valuetype);
195 memcpy (t, field->data, mono_class_value_size (fklass, NULL));
198 if (!(field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT))
200 cindex = mono_metadata_get_constant_index (class->image, MONO_TOKEN_FIELD_DEF | (i + 1));
202 g_warning ("constant for field %s not found", field->name);
205 mono_metadata_decode_row (&class->image->tables [MONO_TABLE_CONSTANT], cindex - 1, cols, MONO_CONSTANT_SIZE);
206 p = mono_metadata_blob_heap (class->image, cols [MONO_CONSTANT_VALUE]);
207 len = mono_metadata_decode_blob_size (p, &p);
208 t = (char*)vt->data + field->offset;
209 /* should we check that the type matches? */
210 switch (cols [MONO_CONSTANT_TYPE]) {
211 case MONO_TYPE_BOOLEAN:
219 guint16 *val = (guint16*)t;
225 guint32 *val = (guint32*)t;
231 guint64 *val = (guint64*)t;
236 float *val = (float*)t;
241 double *val = (double*)t;
245 case MONO_TYPE_STRING: {
246 gpointer *val = (gpointer*)t;
247 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
248 gunichar2 *copy = g_malloc (len);
250 for (j = 0; j < len/2; j++) {
251 copy [j] = read16 (p);
254 *val = mono_string_new_utf16 (domain, copy, len/2);
257 *val = mono_string_new_utf16 (domain, (const guint16*)p, len/2);
261 case MONO_TYPE_CLASS:
262 /* nothing to do, we malloc0 the data and the value can be 0 only */
265 g_warning ("type 0x%02x should not be in constant table", cols [MONO_CONSTANT_TYPE]);
269 vt->max_interface_id = class->max_interface_id;
271 vt->interface_offsets = mono_mempool_alloc0 (domain->mp,
272 sizeof (gpointer) * (class->max_interface_id + 1));
274 /* initialize interface offsets */
275 for (k = class; k ; k = k->parent) {
276 for (i = 0; i < k->interface_count; i++) {
278 MonoClass *ic = k->interfaces [i];
279 slot = class->interface_offsets [ic->interface_id];
280 vt->interface_offsets [ic->interface_id] = &vt->vtable [slot];
284 /* initialize vtable */
285 for (i = 0; i < class->vtable_size; ++i) {
288 if ((cm = class->vtable [i]))
289 vt->vtable [i] = arch_create_jit_trampoline (cm);
292 mono_g_hash_table_insert (domain->class_vtable_hash, class, vt);
293 if (!class->cached_vtable)
294 class->cached_vtable = vt;
296 mono_domain_unlock (domain);
298 /* make sure the the parent is initialized */
300 mono_class_vtable (domain, class->parent);
302 mono_runtime_class_init (class);
308 * mono_class_proxy_vtable:
309 * @domain: the application domain
310 * @class: the class to proxy
312 * Creates a vtable for transparent proxies. It is basically
313 * a copy of the real vtable of @class, but all function pointers invoke
314 * the remoting functions, and vtable->klass points to the
315 * transparent proxy class, and not to @class.
318 mono_class_proxy_vtable (MonoDomain *domain, MonoClass *class)
320 MonoVTable *vt, *pvt;
323 if ((pvt = mono_g_hash_table_lookup (domain->proxy_vtable_hash, class)))
326 vt = mono_class_vtable (domain, class);
327 vtsize = sizeof (MonoVTable) + class->vtable_size * sizeof (gpointer);
329 mono_stats.class_vtable_size += vtsize;
331 pvt = mono_mempool_alloc (domain->mp, vtsize);
332 memcpy (pvt, vt, vtsize);
334 pvt->klass = mono_defaults.transparent_proxy_class;
336 /* initialize vtable */
337 for (i = 0; i < class->vtable_size; ++i) {
340 if ((cm = class->vtable [i]))
341 pvt->vtable [i] = arch_create_remoting_trampoline (cm);
344 mono_g_hash_table_insert (domain->proxy_vtable_hash, class, pvt);
349 static MonoInvokeFunc default_mono_runtime_invoke = NULL;
352 mono_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
354 if (!default_mono_runtime_invoke) {
355 g_error ("runtime invoke called on uninitialized runtime");
359 return default_mono_runtime_invoke (method, obj, params, exc);
363 set_value (MonoType *type, void *dest, void *value) {
366 gpointer *p = (gpointer*)dest;
373 case MONO_TYPE_BOOLEAN:
376 guint8 *p = (guint8*)dest;
377 *p = *(guint8*)value;
382 case MONO_TYPE_CHAR: {
383 guint16 *p = (guint16*)dest;
384 *p = *(guint16*)value;
387 #if SIZEOF_VOID_P == 4
393 gint32 *p = (gint32*)dest;
394 *p = *(gint32*)value;
397 #if SIZEOF_VOID_P == 8
403 gint64 *p = (gint64*)dest;
404 *p = *(gint64*)value;
408 float *p = (float*)dest;
413 double *p = (double*)dest;
414 *p = *(double*)value;
417 case MONO_TYPE_STRING:
418 case MONO_TYPE_SZARRAY:
419 case MONO_TYPE_CLASS:
420 case MONO_TYPE_OBJECT:
421 case MONO_TYPE_ARRAY:
422 case MONO_TYPE_PTR: {
423 gpointer *p = (gpointer*)dest;
427 case MONO_TYPE_VALUETYPE:
428 if (type->data.klass->enumtype) {
429 t = type->data.klass->enum_basetype->type;
433 size = mono_class_value_size (type->data.klass, NULL);
434 memcpy (dest, value, size);
438 g_warning ("got type %x", type->type);
439 g_assert_not_reached ();
444 mono_field_set_value (MonoObject *obj, MonoClassField *field, void *value)
448 g_return_if_fail (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC));
450 dest = (char*)obj + field->offset;
451 set_value (field->type, dest, value);
455 mono_field_static_set_value (MonoVTable *vt, MonoClassField *field, void *value)
459 g_return_if_fail (field->type->attrs & FIELD_ATTRIBUTE_STATIC);
461 dest = (char*)vt->data + field->offset;
462 set_value (field->type, dest, value);
466 mono_field_get_value (MonoObject *obj, MonoClassField *field, void *value)
470 g_return_if_fail (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC));
472 src = (char*)obj + field->offset;
473 set_value (field->type, value, src);
477 mono_field_static_get_value (MonoVTable *vt, MonoClassField *field, void *value)
481 g_return_if_fail (field->type->attrs & FIELD_ATTRIBUTE_STATIC);
483 src = (char*)vt->data + field->offset;
484 set_value (field->type, value, src);
488 mono_property_set_value (MonoProperty *prop, void *obj, void **params, MonoObject **exc)
490 default_mono_runtime_invoke (prop->set, obj, params, exc);
494 mono_property_get_value (MonoProperty *prop, void *obj, void **params, MonoObject **exc)
496 return default_mono_runtime_invoke (prop->get, obj, params, exc);
501 mono_get_delegate_invoke (MonoClass *klass)
508 for (i = 0; i < klass->method.count; ++i) {
509 if (klass->methods [i]->name[0] == 'I' &&
510 !strcmp ("Invoke", klass->methods [i]->name)) {
511 im = klass->methods [i];
521 mono_runtime_delegate_invoke (MonoObject *delegate, void **params, MonoObject **exc)
525 im = mono_get_delegate_invoke (delegate->vtable->klass);
528 return mono_runtime_invoke (im, delegate, params, exc);
531 static MonoArray* main_args;
534 mono_runtime_get_main_args (void)
539 MonoMethod *mono_start_method = NULL;
542 * Execute a standard Main() method (argc/argv contains the
543 * executable name). This method also sets the command line argument value
544 * needed by System.Environment.
547 mono_runtime_run_main (MonoMethod *method, int argc, char* argv[],
551 MonoArray *args = NULL;
552 MonoDomain *domain = mono_domain_get ();
554 main_args = (MonoArray*)mono_array_new (domain, mono_defaults.string_class, argc);
555 for (i = 0; i < argc; ++i) {
556 MonoString *arg = mono_string_new (domain, argv [i]);
557 mono_array_set (main_args, gpointer, i, arg);
561 if (method->signature->param_count) {
562 args = (MonoArray*)mono_array_new (domain, mono_defaults.string_class, argc);
563 for (i = 0; i < argc; ++i) {
564 MonoString *arg = mono_string_new (domain, argv [i]);
565 mono_array_set (args, gpointer, i, arg);
568 args = (MonoArray*)mono_array_new (domain, mono_defaults.string_class, 0);
571 mono_assembly_set_main (method->klass->image->assembly);
573 mono_start_method = mono_marshal_get_runtime_invoke (method);
575 return mono_runtime_exec_main (method, args, exc);
579 * We call this function when we dectect an unhandled exception. It invokes the
580 * UnhandledException event in AppDomain or print a warning to the console
583 mono_unhandled_exception (MonoObject *exc)
585 MonoDomain *domain = mono_domain_get ();
586 MonoClassField *field;
587 MonoObject *delegate;
589 field=mono_class_get_field_from_name(mono_defaults.appdomain_class,
590 "UnhandledException");
593 if (exc->vtable->klass != mono_defaults.threadabortexception_class) {
594 delegate = *(MonoObject **)(((char *)domain->domain) + field->offset);
597 mono_print_unhandled_exception (exc);
599 MonoObject *e = NULL;
602 /* fixme: pass useful arguments */
605 mono_runtime_delegate_invoke (delegate, pa, &e);
608 g_warning ("exception inside UnhandledException handler!");
614 * Execute a standard Main() method (args doesn't contain the
618 mono_runtime_exec_main (MonoMethod *method, MonoArray *args, MonoObject **exc)
628 domain = mono_object_domain (args);
629 g_assert (!domain->entry_assembly);
630 domain->entry_assembly = method->klass->image->assembly;
632 /* FIXME: check signature of method */
633 if (method->signature->ret->type == MONO_TYPE_I4) {
635 res = mono_runtime_invoke (method, NULL, pa, exc);
637 rval = *(guint32 *)((char *)res + sizeof (MonoObject));
641 mono_runtime_invoke (method, NULL, pa, exc);
652 mono_install_runtime_invoke (MonoInvokeFunc func)
654 default_mono_runtime_invoke = func;
658 mono_runtime_invoke_array (MonoMethod *method, void *obj, MonoArray *params,
661 MonoMethodSignature *sig = method->signature;
665 if (NULL != params) {
666 pa = alloca (sizeof (gpointer) * mono_array_length (params));
667 for (i = 0; i < mono_array_length (params); i++) {
668 if (sig->params [i]->byref) {
672 switch (sig->params [i]->type) {
675 case MONO_TYPE_BOOLEAN:
685 case MONO_TYPE_VALUETYPE:
686 pa [i] = (char *)(((gpointer *)params->vector)[i]) + sizeof (MonoObject);
688 case MONO_TYPE_STRING:
689 case MONO_TYPE_OBJECT:
690 case MONO_TYPE_CLASS:
691 case MONO_TYPE_ARRAY:
692 case MONO_TYPE_SZARRAY:
693 pa [i] = (char *)(((gpointer *)params->vector)[i]);
696 g_error ("type 0x%x not handled in ves_icall_InternalInvoke", sig->params [i]->type);
701 if (!strcmp (method->name, ".ctor") && method->klass != mono_defaults.string_class) {
702 obj = mono_object_new (mono_domain_get (), method->klass);
703 mono_runtime_invoke (method, obj, pa, exc);
706 return mono_runtime_invoke (method, obj, pa, exc);
710 * mono_object_allocate:
711 * @size: number of bytes to allocate
713 * This is a very simplistic routine until we have our GC-aware
716 * Returns: an allocated object of size @size, or NULL on failure.
719 mono_object_allocate (size_t size)
722 /* if this is changed to GC_debug_malloc(), we need to change also metadata/gc.c */
723 void *o = GC_malloc (size);
725 void *o = calloc (1, size);
734 * Frees the memory used by the object. Debugging purposes
735 * only, as we will have our GC system.
738 mono_object_free (MonoObject *o)
741 g_error ("mono_object_free called with boehm gc.");
743 MonoClass *c = o->vtable->klass;
745 memset (o, 0, c->instance_size);
752 * @klass: the class of the object that we want to create
754 * Returns: A newly created object whose definition is
755 * looked up using @klass
758 mono_object_new (MonoDomain *domain, MonoClass *klass)
760 return mono_object_new_specific (mono_class_vtable (domain, klass));
764 * mono_object_new_specific:
765 * @vtable: the vtable of the object that we want to create
767 * Returns: A newly created object with class and domain specified
771 mono_object_new_specific (MonoVTable *vtable)
775 mono_stats.new_object_count++;
777 o = mono_object_allocate (vtable->klass->instance_size);
779 if (vtable->klass->has_finalize)
780 mono_object_register_finalizer (o);
786 * mono_object_new_from_token:
787 * @image: Context where the type_token is hosted
788 * @token: a token of the type that we want to create
790 * Returns: A newly created object whose definition is
791 * looked up using @token in the @image image
794 mono_object_new_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
798 class = mono_class_get (image, token);
800 return mono_object_new (domain, class);
806 * @obj: the object to clone
808 * Returns: A newly created object who is a shallow copy of @obj
811 mono_object_clone (MonoObject *obj)
816 size = obj->vtable->klass->instance_size;
817 o = mono_object_allocate (size);
819 memcpy (o, obj, size);
821 if (obj->vtable->klass->has_finalize)
822 mono_object_register_finalizer (o);
828 * @array: the array to clone
830 * Returns: A newly created array who is a shallow copy of @array
833 mono_array_clone (MonoArray *array)
838 MonoClass *klass = array->obj.vtable->klass;
840 if (array->bounds == NULL) {
841 size = mono_array_length (array);
842 o = mono_array_new_full (((MonoObject *)array)->vtable->domain,
845 size *= mono_array_element_size (klass);
846 memcpy (o, array, sizeof (MonoArray) + size);
851 sizes = alloca (klass->rank * sizeof(guint32) * 2);
852 size = mono_array_element_size (klass);
853 for (i = 0; i < klass->rank; ++i) {
854 sizes [i] = array->bounds [i].length;
855 size *= array->bounds [i].length;
856 sizes [i + klass->rank] = array->bounds [i].lower_bound;
858 o = mono_array_new_full (((MonoObject *)array)->vtable->domain,
859 klass, sizes, sizes + klass->rank);
860 memcpy (o, array, sizeof(MonoArray) + size);
866 * mono_array_new_full:
867 * @domain: domain where the object is created
868 * @array_class: array class
869 * @lengths: lengths for each dimension in the array
870 * @lower_bounds: lower bounds for each dimension in the array (may be NULL)
872 * This routine creates a new array objects with the given dimensions,
873 * lower bounds and type.
876 mono_array_new_full (MonoDomain *domain, MonoClass *array_class,
877 guint32 *lengths, guint32 *lower_bounds)
879 guint32 byte_len, len;
882 MonoArrayBounds *bounds;
885 if (!array_class->inited)
886 mono_class_init (array_class);
888 byte_len = mono_array_element_size (array_class);
891 if (array_class->rank == 1 &&
892 (lower_bounds == NULL || lower_bounds [0] == 0)) {
897 bounds = GC_malloc (sizeof (MonoArrayBounds) * array_class->rank);
899 bounds = g_malloc0 (sizeof (MonoArrayBounds) * array_class->rank);
901 for (i = 0; i < array_class->rank; ++i) {
902 bounds [i].length = lengths [i];
907 for (i = 0; i < array_class->rank; ++i)
908 bounds [i].lower_bound = lower_bounds [i];
913 * Following three lines almost taken from mono_object_new ():
914 * they need to be kept in sync.
916 o = mono_object_allocate (sizeof (MonoArray) + byte_len);
919 o->vtable = mono_class_vtable (domain, array_class);
921 array = (MonoArray*)o;
923 array->bounds = bounds;
924 array->max_length = len;
931 * @domain: domain where the object is created
932 * @eclass: element class
933 * @n: number of array elements
935 * This routine creates a new szarray with @n elements of type @eclass.
938 mono_array_new (MonoDomain *domain, MonoClass *eclass, guint32 n)
942 ac = mono_array_class_get (&eclass->byval_arg, 1);
943 g_assert (ac != NULL);
945 return mono_array_new_specific (mono_class_vtable (domain, ac), n);
949 * mono_array_new_specific:
950 * @vtable: a vtable in the appropriate domain for an initialized class
951 * @n: number of array elements
953 * This routine is a fast alternative to mono_array_new() for code which
954 * can be sure about the domain it operates in.
957 mono_array_new_specific (MonoVTable *vtable, guint32 n)
963 byte_len = n * mono_array_element_size (vtable->klass);
964 o = mono_object_allocate (sizeof (MonoArray) + byte_len);
977 * mono_string_new_utf16:
978 * @text: a pointer to an utf16 string
979 * @len: the length of the string
981 * Returns: A newly created string object which contains @text.
984 mono_string_new_utf16 (MonoDomain *domain, const guint16 *text, gint32 len)
988 s = mono_string_new_size (domain, len);
989 g_assert (s != NULL);
991 memcpy (mono_string_chars (s), text, len * 2);
997 * mono_string_new_size:
998 * @text: a pointer to an utf16 string
999 * @len: the length of the string
1001 * Returns: A newly created string object of @len
1004 mono_string_new_size (MonoDomain *domain, gint32 len)
1009 * enable to get a good speedup: we still need to figure out
1010 * how the sync structure is freed.
1013 s = GC_malloc_atomic (sizeof (MonoString) + ((len + 1) * 2));
1014 s->object.synchronisation = 0;
1015 mono_string_chars (s) [len] = 0;
1017 s = (MonoString*)mono_object_allocate (sizeof (MonoString) + ((len + 1) * 2));
1022 s->object.vtable = mono_class_vtable (domain, mono_defaults.string_class);
1029 * mono_string_new_len:
1030 * @text: a pointer to an utf8 string
1031 * @length: number of bytes in @text to consider
1033 * Returns: A newly created string object which contains @text.
1036 mono_string_new_len (MonoDomain *domain, const char *text, guint length)
1038 GError *error = NULL;
1039 MonoString *o = NULL;
1041 glong items_written;
1044 ut = g_utf8_to_utf16 (text, length, NULL, &items_written, &error);
1047 o = mono_string_new_utf16 (domain, ut, items_written);
1049 g_error_free (error);
1058 * @text: a pointer to an utf8 string
1060 * Returns: A newly created string object which contains @text.
1063 mono_string_new (MonoDomain *domain, const char *text)
1065 GError *error = NULL;
1066 MonoString *o = NULL;
1068 glong items_written;
1073 ut = g_utf8_to_utf16 (text, l, NULL, &items_written, &error);
1076 o = mono_string_new_utf16 (domain, ut, items_written);
1078 g_error_free (error);
1086 * mono_string_new_wrapper:
1087 * @text: pointer to utf8 characters.
1089 * Helper function to create a string object from @text in the current domain.
1092 mono_string_new_wrapper (const char *text)
1094 MonoDomain *domain = mono_domain_get ();
1097 return mono_string_new (domain, text);
1104 * @class: the class of the value
1105 * @value: a pointer to the unboxed data
1107 * Returns: A newly created object which contains @value.
1110 mono_value_box (MonoDomain *domain, MonoClass *class, gpointer value)
1115 g_assert (class->valuetype);
1117 size = mono_class_instance_size (class);
1118 res = mono_object_allocate (size);
1119 res->vtable = mono_class_vtable (domain, class);
1121 size = size - sizeof (MonoObject);
1123 #if NO_UNALIGNED_ACCESS
1124 memcpy ((char *)res + sizeof (MonoObject), value, size);
1128 *((guint8 *) res + sizeof (MonoObject)) = *(guint8 *) value;
1131 *(guint16 *)((guint8 *) res + sizeof (MonoObject)) = *(guint16 *) value;
1134 *(guint32 *)((guint8 *) res + sizeof (MonoObject)) = *(guint32 *) value;
1137 *(guint64 *)((guint8 *) res + sizeof (MonoObject)) = *(guint64 *) value;
1140 memcpy ((char *)res + sizeof (MonoObject), value, size);
1143 if (class->has_finalize)
1144 mono_object_register_finalizer (res);
1149 * mono_object_isinst:
1151 * @klass: a pointer to a class
1153 * Returns: @obj if @obj is derived from @klass
1156 mono_object_isinst (MonoObject *obj, MonoClass *klass)
1168 mono_class_init (klass);
1170 if (klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
1171 if ((klass->interface_id <= oklass->max_interface_id) &&
1172 vt->interface_offsets [klass->interface_id])
1175 if (oklass == mono_defaults.transparent_proxy_class) {
1176 /* fixme: add check for IRemotingTypeInfo */
1177 oklass = ((MonoTransparentProxy *)obj)->klass;
1180 if (oklass->rank == klass->rank &&
1181 (oklass->element_class->baseval - klass->element_class->baseval) <=
1182 klass->element_class->diffval)
1185 } else if ((oklass->baseval - klass->baseval) <= klass->diffval)
1193 mono_string_is_interned_lookup (MonoString *str, int insert)
1195 MonoGHashTable *ldstr_table;
1198 char *ins = g_malloc (4 + str->length * 2);
1202 /* Encode the length */
1204 mono_metadata_encode_value (2 * str->length, p, &p);
1207 mono_metadata_encode_value (bloblen + 2 * str->length, p, &p);
1208 bloblen = (p - ins) + 2 * str->length;
1210 * ins is stored in the hash table as a key and needs to have the same
1211 * representation as in the metadata: we swap the character bytes on big
1214 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
1217 char *p2 = mono_string_chars (str);
1218 for (i = 0; i < str->length; ++i) {
1225 memcpy (p, mono_string_chars (str), str->length * 2);
1227 domain = ((MonoObject *)str)->vtable->domain;
1228 ldstr_table = domain->ldstr_table;
1229 mono_domain_lock (domain);
1230 if ((res = mono_g_hash_table_lookup (ldstr_table, ins))) {
1231 mono_domain_unlock (domain);
1236 mono_g_hash_table_insert (ldstr_table, ins, str);
1237 mono_domain_unlock (domain);
1240 mono_domain_unlock (domain);
1246 mono_string_is_interned (MonoString *o)
1248 return mono_string_is_interned_lookup (o, FALSE);
1252 mono_string_intern (MonoString *str)
1254 return mono_string_is_interned_lookup (str, TRUE);
1259 * @domain: the domain where the string will be used.
1260 * @image: a metadata context
1261 * @idx: index into the user string table.
1263 * Implementation for the ldstr opcode.
1266 mono_ldstr (MonoDomain *domain, MonoImage *image, guint32 idx)
1268 const char *str, *sig;
1272 sig = str = mono_metadata_user_string (image, idx);
1274 mono_domain_lock (domain);
1275 if ((o = mono_g_hash_table_lookup (domain->ldstr_table, sig))) {
1276 mono_domain_unlock (domain);
1280 len2 = mono_metadata_decode_blob_size (str, &str);
1283 o = mono_string_new_utf16 (domain, (guint16*)str, len2);
1284 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
1287 guint16 *p2 = (guint16*)mono_string_chars (o);
1288 for (i = 0; i < len2; ++i) {
1289 *p2 = GUINT16_FROM_LE (*p2);
1294 mono_g_hash_table_insert (domain->ldstr_table, (gpointer)sig, o);
1295 mono_domain_unlock (domain);
1301 * mono_string_to_utf8:
1302 * @s: a System.String
1304 * Return the UTF8 representation for @s.
1305 * the resulting buffer nedds to be freed with g_free().
1308 mono_string_to_utf8 (MonoString *s)
1311 GError *error = NULL;
1317 return g_strdup ("");
1319 as = g_utf16_to_utf8 (mono_string_chars (s), s->length, NULL, NULL, &error);
1321 g_warning (error->message);
1327 * mono_string_to_utf16:
1330 * Return an null-terminated array of the utf-16 chars
1331 * contained in @s. The result must be freed with g_free().
1332 * This is a temporary helper until our string implementation
1333 * is reworked to always include the null terminating char.
1336 mono_string_to_utf16 (MonoString *s)
1343 as = g_malloc ((s->length * 2) + 2);
1344 as [(s->length * 2)] = '\0';
1345 as [(s->length * 2) + 1] = '\0';
1348 return (gunichar2 *)(as);
1351 memcpy (as, mono_string_chars(s), s->length * 2);
1352 return (gunichar2 *)(as);
1356 default_ex_handler (MonoException *ex)
1358 MonoObject *o = (MonoObject*)ex;
1359 g_error ("Exception %s.%s raised in C code", o->vtable->klass->name_space, o->vtable->klass->name);
1362 static MonoExceptionFunc ex_handler = default_ex_handler;
1365 mono_install_handler (MonoExceptionFunc func)
1367 ex_handler = func? func: default_ex_handler;
1371 * mono_raise_exception:
1372 * @ex: exception object
1374 * Signal the runtime that the exception @ex has been raised in unmanaged code.
1377 mono_raise_exception (MonoException *ex)
1383 mono_wait_handle_new (MonoDomain *domain, HANDLE handle)
1385 MonoWaitHandle *res;
1387 res = (MonoWaitHandle *)mono_object_new (domain, mono_defaults.waithandle_class);
1389 res->handle = handle;
1395 mono_async_result_new (MonoDomain *domain, HANDLE handle, MonoObject *state, gpointer data)
1397 MonoAsyncResult *res;
1399 res = (MonoAsyncResult *)mono_object_new (domain, mono_defaults.asyncresult_class);
1402 res->async_state = state;
1403 res->handle = (MonoObject *)mono_wait_handle_new (domain, handle);
1404 res->sync_completed = FALSE;
1405 res->completed = FALSE;
1411 mono_message_init (MonoDomain *domain,
1412 MonoMethodMessage *this,
1413 MonoReflectionMethod *method,
1414 MonoArray *out_args)
1416 MonoMethodSignature *sig = method->method->signature;
1422 this->method = method;
1424 this->args = mono_array_new (domain, mono_defaults.object_class, sig->param_count);
1425 this->arg_types = mono_array_new (domain, mono_defaults.byte_class, sig->param_count);
1427 names = g_new (char *, sig->param_count);
1428 mono_method_get_param_names (method->method, (const char **) names);
1429 this->names = mono_array_new (domain, mono_defaults.string_class, sig->param_count);
1431 for (i = 0; i < sig->param_count; i++) {
1432 name = mono_string_new (domain, names [i]);
1433 mono_array_set (this->names, gpointer, i, name);
1438 for (i = 0, j = 0; i < sig->param_count; i++) {
1440 if (sig->params [i]->byref) {
1442 gpointer arg = mono_array_get (out_args, gpointer, j);
1443 mono_array_set (this->args, gpointer, i, arg);
1447 if (sig->params [i]->attrs & PARAM_ATTRIBUTE_IN)
1453 mono_array_set (this->arg_types, guint8, i, arg_type);
1458 * mono_remoting_invoke:
1459 * @real_proxy: pointer to a RealProxy object
1460 * @msg: The MonoMethodMessage to execute
1461 * @exc: used to store exceptions
1462 * @out_args: used to store output arguments
1464 * This is used to call RealProxy::Invoke(). RealProxy::Invoke() returns an
1465 * IMessage interface and it is not trivial to extract results from there. So
1466 * we call an helper method PrivateInvoke instead of calling
1467 * RealProxy::Invoke() directly.
1469 * Returns: the result object.
1472 mono_remoting_invoke (MonoObject *real_proxy, MonoMethodMessage *msg,
1473 MonoObject **exc, MonoArray **out_args)
1475 static MonoMethod *im = NULL;
1478 /*static MonoObject *(*invoke) (gpointer, gpointer, MonoObject **, MonoArray **) = NULL;*/
1480 /* FIXME: make this domain dependent */
1485 klass = mono_defaults.real_proxy_class;
1487 for (i = 0; i < klass->method.count; ++i) {
1488 if (!strcmp ("PrivateInvoke", klass->methods [i]->name) &&
1489 klass->methods [i]->signature->param_count == 4) {
1490 im = klass->methods [i];
1498 pa [0] = real_proxy;
1503 return mono_runtime_invoke (im, NULL, pa, exc);
1507 mono_message_invoke (MonoObject *target, MonoMethodMessage *msg,
1508 MonoObject **exc, MonoArray **out_args)
1510 if (target && target->vtable->klass == mono_defaults.transparent_proxy_class) {
1512 return mono_remoting_invoke ((MonoObject *)((MonoTransparentProxy *)target)->rp,
1513 msg, exc, out_args);
1516 MonoDomain *domain = mono_domain_get ();
1517 MonoMethod *method = msg->method->method;
1518 MonoMethodSignature *sig = method->signature;
1519 int i, j, outarg_count = 0;
1521 for (i = 0; i < sig->param_count; i++) {
1522 if (sig->params [i]->byref)
1526 *out_args = mono_array_new (domain, mono_defaults.object_class, outarg_count);
1529 for (i = 0, j = 0; i < sig->param_count; i++) {
1530 if (sig->params [i]->byref) {
1532 arg = mono_array_get (msg->args, gpointer, i);
1533 mono_array_set (*out_args, gpointer, j, arg);
1538 return mono_runtime_invoke_array (method, target, msg->args, exc);
1543 mono_print_unhandled_exception (MonoObject *exc)
1545 char *message = (char *) "";
1549 gboolean free_message = FALSE;
1552 if (mono_object_isinst (exc, mono_defaults.exception_class)) {
1553 klass = exc->vtable->klass;
1555 while (klass && method == NULL) {
1556 for (i = 0; i < klass->method.count; ++i) {
1557 method = klass->methods [i];
1558 if (!strcmp ("ToString", method->name) &&
1559 method->signature->param_count == 0 &&
1560 method->flags & METHOD_ATTRIBUTE_VIRTUAL &&
1561 method->flags & METHOD_ATTRIBUTE_PUBLIC) {
1568 klass = klass->parent;
1573 str = (MonoString *) mono_runtime_invoke (method, exc, NULL, NULL);
1575 message = mono_string_to_utf8 (str);
1576 free_message = TRUE;
1581 * g_printerr ("\nUnhandled Exception: %s.%s: %s\n", exc->vtable->klass->name_space,
1582 * exc->vtable->klass->name, message);
1584 g_printerr ("\nUnhandled Exception: %s\n", message);
1591 * mono_delegate_ctor:
1592 * @this: pointer to an uninitialized delegate object
1593 * @target: target object
1594 * @addr: pointer to native code
1596 * This is used to initialize a delegate. We also insert the method_info if
1597 * we find the info with mono_jit_info_table_find().
1600 mono_delegate_ctor (MonoObject *this, MonoObject *target, gpointer addr)
1602 MonoDomain *domain = mono_domain_get ();
1603 MonoDelegate *delegate = (MonoDelegate *)this;
1604 MonoMethod *method = NULL;
1611 class = this->vtable->klass;
1613 if ((ji = mono_jit_info_table_find (domain, addr))) {
1614 method = ji->method;
1615 delegate->method_info = mono_method_get_object (domain, method, NULL);
1618 if (target && target->vtable->klass == mono_defaults.transparent_proxy_class) {
1620 method = mono_marshal_get_remoting_invoke (method);
1621 delegate->method_ptr = mono_compile_method (method);
1622 delegate->target = target;
1624 delegate->method_ptr = addr;
1625 delegate->target = target;
1630 * mono_method_call_message_new:
1632 * Translates arguments pointers into a Message.
1635 mono_method_call_message_new (MonoMethod *method, gpointer *params, MonoMethod *invoke,
1636 MonoDelegate **cb, MonoObject **state)
1638 MonoDomain *domain = mono_domain_get ();
1639 MonoMethodSignature *sig = method->signature;
1640 MonoMethodMessage *msg;
1643 msg = (MonoMethodMessage *)mono_object_new (domain, mono_defaults.mono_method_message_class);
1646 mono_message_init (domain, msg, mono_method_get_object (domain, invoke, NULL), NULL);
1647 count = sig->param_count - 2;
1649 mono_message_init (domain, msg, mono_method_get_object (domain, method, NULL), NULL);
1650 count = sig->param_count;
1653 for (i = 0; i < count; i++) {
1658 if (sig->params [i]->byref)
1659 vpos = *((gpointer *)params [i]);
1663 type = sig->params [i]->type;
1664 class = mono_class_from_mono_type (sig->params [i]);
1666 if (class->valuetype)
1667 arg = mono_value_box (domain, class, vpos);
1669 arg = *((MonoObject **)vpos);
1671 mono_array_set (msg->args, gpointer, i, arg);
1675 *cb = *((MonoDelegate **)params [i]);
1677 *state = *((MonoObject **)params [i]);
1684 * mono_method_return_message_restore:
1686 * Restore results from message based processing back to arguments pointers
1689 mono_method_return_message_restore (MonoMethod *method, gpointer *params, MonoArray *out_args)
1691 MonoMethodSignature *sig = method->signature;
1692 int i, j, type, size;
1694 for (i = 0, j = 0; i < sig->param_count; i++) {
1695 MonoType *pt = sig->params [i];
1697 size = mono_type_stack_size (pt, NULL);
1700 char *arg = mono_array_get (out_args, gpointer, j);
1704 case MONO_TYPE_VOID:
1705 g_assert_not_reached ();
1709 case MONO_TYPE_BOOLEAN:
1712 case MONO_TYPE_CHAR:
1719 case MONO_TYPE_VALUETYPE: {
1720 memcpy (*((gpointer *)params [i]), arg + sizeof (MonoObject), size);
1723 case MONO_TYPE_STRING:
1724 case MONO_TYPE_CLASS:
1725 case MONO_TYPE_ARRAY:
1726 case MONO_TYPE_SZARRAY:
1727 *((MonoObject **)params [i]) = (MonoObject *)arg;
1730 g_assert_not_reached ();
1739 * mono_load_remote_field:
1740 * @this: pointer to an object
1741 * @klass: klass of the object containing @field
1742 * @field: the field to load
1743 * @res: a storage to store the result
1745 * This method is called by the runtime on attempts to load fields of
1746 * transparent proxy objects. @this points to such TP, @klass is the class of
1747 * the object containing @field. @res is a storage location which can be
1748 * used to store the result.
1750 * Returns: an address pointing to the value of field.
1753 mono_load_remote_field (MonoObject *this, MonoClass *klass, MonoClassField *field, gpointer *res)
1755 static MonoMethod *getter = NULL;
1756 MonoDomain *domain = mono_domain_get ();
1757 MonoClass *field_class;
1758 MonoMethodMessage *msg;
1759 MonoArray *out_args;
1763 g_assert (this->vtable->klass == mono_defaults.transparent_proxy_class);
1771 for (i = 0; i < mono_defaults.object_class->method.count; ++i) {
1772 MonoMethod *cm = mono_defaults.object_class->methods [i];
1774 if (!strcmp (cm->name, "FieldGetter")) {
1782 field_class = mono_class_from_mono_type (field->type);
1784 msg = (MonoMethodMessage *)mono_object_new (domain, mono_defaults.mono_method_message_class);
1785 out_args = mono_array_new (domain, mono_defaults.object_class, 1);
1786 mono_message_init (domain, msg, mono_method_get_object (domain, getter, NULL), out_args);
1788 mono_array_set (msg->args, gpointer, 0, mono_string_new (domain, klass->name));
1789 mono_array_set (msg->args, gpointer, 1, mono_string_new (domain, field->name));
1791 mono_remoting_invoke ((MonoObject *)((MonoTransparentProxy *)this)->rp, msg, &exc, &out_args);
1793 *res = mono_array_get (out_args, MonoObject *, 0);
1795 if (field_class->valuetype) {
1796 return ((char *)*res) + sizeof (MonoObject);
1802 * mono_store_remote_field:
1803 * @this: pointer to an object
1804 * @klass: klass of the object containing @field
1805 * @field: the field to load
1806 * @val: the value/object to store
1808 * This method is called by the runtime on attempts to store fields of
1809 * transparent proxy objects. @this points to such TP, @klass is the class of
1810 * the object containing @field. @val is the new value to store in @field.
1813 mono_store_remote_field (MonoObject *this, MonoClass *klass, MonoClassField *field, gpointer val)
1815 static MonoMethod *setter = NULL;
1816 MonoDomain *domain = mono_domain_get ();
1817 MonoClass *field_class;
1818 MonoMethodMessage *msg;
1819 MonoArray *out_args;
1823 g_assert (this->vtable->klass == mono_defaults.transparent_proxy_class);
1828 for (i = 0; i < mono_defaults.object_class->method.count; ++i) {
1829 MonoMethod *cm = mono_defaults.object_class->methods [i];
1831 if (!strcmp (cm->name, "FieldSetter")) {
1839 field_class = mono_class_from_mono_type (field->type);
1841 if (field_class->valuetype)
1842 arg = mono_value_box (domain, field_class, val);
1844 arg = *((MonoObject **)val);
1847 msg = (MonoMethodMessage *)mono_object_new (domain, mono_defaults.mono_method_message_class);
1848 mono_message_init (domain, msg, mono_method_get_object (domain, setter, NULL), NULL);
1850 mono_array_set (msg->args, gpointer, 0, mono_string_new (domain, klass->name));
1851 mono_array_set (msg->args, gpointer, 1, mono_string_new (domain, field->name));
1852 mono_array_set (msg->args, gpointer, 2, arg);
1854 mono_remoting_invoke ((MonoObject *)((MonoTransparentProxy *)this)->rp, msg, &exc, &out_args);