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 * enable to get a good speedup: we still need to figure out
32 * how the sync structure is freed.
34 #define CREATION_SPEEDUP 0
37 mono_runtime_object_init (MonoObject *this)
40 MonoMethod *method = NULL;
41 MonoClass *klass = this->vtable->klass;
43 for (i = 0; i < klass->method.count; ++i) {
44 if (!strcmp (".ctor", klass->methods [i]->name) &&
45 klass->methods [i]->signature->param_count == 0) {
46 method = klass->methods [i];
53 mono_runtime_invoke (method, this, NULL, NULL);
58 * @klass: klass that needs to be initialized
60 * This routine calls the class constructor for @class.
63 mono_runtime_class_init (MonoClass *klass)
67 for (i = 0; i < klass->method.count; ++i) {
68 MonoMethod *method = klass->methods [i];
69 if ((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
70 (strcmp (".cctor", method->name) == 0)) {
71 mono_runtime_invoke (method, NULL, NULL, NULL);
76 /* No class constructor found */
80 default_trampoline (MonoMethod *method)
86 default_remoting_trampoline (MonoMethod *method)
88 g_error ("remoting not installed");
92 static MonoTrampoline arch_create_jit_trampoline = default_trampoline;
93 static MonoTrampoline arch_create_remoting_trampoline = default_remoting_trampoline;
96 mono_install_trampoline (MonoTrampoline func)
98 arch_create_jit_trampoline = func? func: default_trampoline;
102 mono_install_remoting_trampoline (MonoTrampoline func)
104 arch_create_remoting_trampoline = func? func: default_remoting_trampoline;
107 static MonoCompileFunc default_mono_compile_method = NULL;
110 mono_install_compile_method (MonoCompileFunc func)
112 default_mono_compile_method = func;
116 mono_compile_method (MonoMethod *method)
118 if (!default_mono_compile_method) {
119 g_error ("compile method called on uninitialized runtime");
122 return default_mono_compile_method (method);
126 #if 0 && HAVE_BOEHM_GC
128 vtable_finalizer (void *obj, void *data) {
129 g_print ("%s finalized (%p)\n", (char*)data, obj);
135 * @domain: the application domain
136 * @class: the class to initialize
138 * VTables are domain specific because we create domain specific code, and
139 * they contain the domain specific static class data.
142 mono_class_vtable (MonoDomain *domain, MonoClass *class)
146 MonoClassField *field;
148 guint32 cols [MONO_CONSTANT_SIZE];
155 vt = class->cached_vtable;
156 if (vt && vt->domain == domain)
159 /* can interfaces have static fields? */
160 if (class->flags & TYPE_ATTRIBUTE_INTERFACE)
161 g_assert_not_reached ();
163 mono_domain_lock (domain);
164 if ((vt = mono_g_hash_table_lookup (domain->class_vtable_hash, class))) {
165 mono_domain_unlock (domain);
170 mono_class_init (class);
172 mono_stats.used_class_count++;
173 mono_stats.class_vtable_size += sizeof (MonoVTable) + class->vtable_size * sizeof (gpointer);
175 vt = mono_mempool_alloc0 (domain->mp, sizeof (MonoVTable) +
176 class->vtable_size * sizeof (gpointer));
180 if (class->class_size) {
182 vt->data = GC_malloc (class->class_size + 8);
183 /*vt->data = GC_debug_malloc (class->class_size + 8, class->name, 2);*/
184 /*GC_register_finalizer (vt->data, vtable_finalizer, class->name, NULL, NULL);*/
185 mono_g_hash_table_insert (domain->static_data_hash, class, vt->data);
187 vt->data = mono_mempool_alloc0 (domain->mp, class->class_size + 8);
190 mono_stats.class_static_data_size += class->class_size + 8;
193 for (i = class->field.first; i < class->field.last; ++i) {
194 field = &class->fields [i - class->field.first];
195 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
197 if ((field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA)) {
198 MonoClass *fklass = mono_class_from_mono_type (field->type);
199 t = (char*)vt->data + field->offset;
200 g_assert (fklass->valuetype);
201 memcpy (t, field->data, mono_class_value_size (fklass, NULL));
204 if (!(field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT))
206 cindex = mono_metadata_get_constant_index (class->image, MONO_TOKEN_FIELD_DEF | (i + 1));
208 g_warning ("constant for field %s not found", field->name);
211 mono_metadata_decode_row (&class->image->tables [MONO_TABLE_CONSTANT], cindex - 1, cols, MONO_CONSTANT_SIZE);
212 p = mono_metadata_blob_heap (class->image, cols [MONO_CONSTANT_VALUE]);
213 len = mono_metadata_decode_blob_size (p, &p);
214 t = (char*)vt->data + field->offset;
215 /* should we check that the type matches? */
216 switch (cols [MONO_CONSTANT_TYPE]) {
217 case MONO_TYPE_BOOLEAN:
225 guint16 *val = (guint16*)t;
231 guint32 *val = (guint32*)t;
237 guint64 *val = (guint64*)t;
242 float *val = (float*)t;
247 double *val = (double*)t;
251 case MONO_TYPE_STRING: {
252 gpointer *val = (gpointer*)t;
253 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
254 gunichar2 *copy = g_malloc (len);
256 for (j = 0; j < len/2; j++) {
257 copy [j] = read16 (p);
260 *val = mono_string_new_utf16 (domain, copy, len/2);
263 *val = mono_string_new_utf16 (domain, (const guint16*)p, len/2);
267 case MONO_TYPE_CLASS:
268 /* nothing to do, we malloc0 the data and the value can be 0 only */
271 g_warning ("type 0x%02x should not be in constant table", cols [MONO_CONSTANT_TYPE]);
275 vt->max_interface_id = class->max_interface_id;
277 vt->interface_offsets = mono_mempool_alloc0 (domain->mp,
278 sizeof (gpointer) * (class->max_interface_id + 1));
280 /* initialize interface offsets */
281 for (k = class; k ; k = k->parent) {
282 for (i = 0; i < k->interface_count; i++) {
284 MonoClass *ic = k->interfaces [i];
285 slot = class->interface_offsets [ic->interface_id];
286 vt->interface_offsets [ic->interface_id] = &vt->vtable [slot];
290 /* initialize vtable */
291 for (i = 0; i < class->vtable_size; ++i) {
294 if ((cm = class->vtable [i]))
295 vt->vtable [i] = arch_create_jit_trampoline (cm);
298 mono_g_hash_table_insert (domain->class_vtable_hash, class, vt);
299 if (!class->cached_vtable)
300 class->cached_vtable = vt;
302 mono_domain_unlock (domain);
304 /* make sure the the parent is initialized */
306 mono_class_vtable (domain, class->parent);
308 mono_runtime_class_init (class);
314 * mono_class_proxy_vtable:
315 * @domain: the application domain
316 * @class: the class to proxy
318 * Creates a vtable for transparent proxies. It is basically
319 * a copy of the real vtable of @class, but all function pointers invoke
320 * the remoting functions, and vtable->klass points to the
321 * transparent proxy class, and not to @class.
324 mono_class_proxy_vtable (MonoDomain *domain, MonoClass *class)
326 MonoVTable *vt, *pvt;
329 if ((pvt = mono_g_hash_table_lookup (domain->proxy_vtable_hash, class)))
332 vt = mono_class_vtable (domain, class);
333 vtsize = sizeof (MonoVTable) + class->vtable_size * sizeof (gpointer);
335 mono_stats.class_vtable_size += vtsize;
337 pvt = mono_mempool_alloc (domain->mp, vtsize);
338 memcpy (pvt, vt, vtsize);
340 pvt->klass = mono_defaults.transparent_proxy_class;
342 /* initialize vtable */
343 for (i = 0; i < class->vtable_size; ++i) {
346 if ((cm = class->vtable [i]))
347 pvt->vtable [i] = arch_create_remoting_trampoline (cm);
350 mono_g_hash_table_insert (domain->proxy_vtable_hash, class, pvt);
355 static MonoInvokeFunc default_mono_runtime_invoke = NULL;
358 mono_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
360 if (!default_mono_runtime_invoke) {
361 g_error ("runtime invoke called on uninitialized runtime");
365 return default_mono_runtime_invoke (method, obj, params, exc);
369 set_value (MonoType *type, void *dest, void *value, int deref_pointer) {
372 gpointer *p = (gpointer*)dest;
379 case MONO_TYPE_BOOLEAN:
382 guint8 *p = (guint8*)dest;
383 *p = *(guint8*)value;
388 case MONO_TYPE_CHAR: {
389 guint16 *p = (guint16*)dest;
390 *p = *(guint16*)value;
393 #if SIZEOF_VOID_P == 4
399 gint32 *p = (gint32*)dest;
400 *p = *(gint32*)value;
403 #if SIZEOF_VOID_P == 8
409 gint64 *p = (gint64*)dest;
410 *p = *(gint64*)value;
414 float *p = (float*)dest;
419 double *p = (double*)dest;
420 *p = *(double*)value;
423 case MONO_TYPE_STRING:
424 case MONO_TYPE_SZARRAY:
425 case MONO_TYPE_CLASS:
426 case MONO_TYPE_OBJECT:
427 case MONO_TYPE_ARRAY:
428 case MONO_TYPE_PTR: {
429 gpointer *p = (gpointer*)dest;
430 *p = deref_pointer? *(gpointer*)value: value;
433 case MONO_TYPE_VALUETYPE:
434 if (type->data.klass->enumtype) {
435 t = type->data.klass->enum_basetype->type;
439 size = mono_class_value_size (type->data.klass, NULL);
440 memcpy (dest, value, size);
444 g_warning ("got type %x", type->type);
445 g_assert_not_reached ();
450 mono_field_set_value (MonoObject *obj, MonoClassField *field, void *value)
454 g_return_if_fail (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC));
456 dest = (char*)obj + field->offset;
457 set_value (field->type, dest, value, FALSE);
461 mono_field_static_set_value (MonoVTable *vt, MonoClassField *field, void *value)
465 g_return_if_fail (field->type->attrs & FIELD_ATTRIBUTE_STATIC);
467 dest = (char*)vt->data + field->offset;
468 set_value (field->type, dest, value, FALSE);
472 mono_field_get_value (MonoObject *obj, MonoClassField *field, void *value)
476 g_return_if_fail (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC));
478 src = (char*)obj + field->offset;
479 set_value (field->type, value, src, TRUE);
483 mono_field_static_get_value (MonoVTable *vt, MonoClassField *field, void *value)
487 g_return_if_fail (field->type->attrs & FIELD_ATTRIBUTE_STATIC);
489 src = (char*)vt->data + field->offset;
490 set_value (field->type, value, src, TRUE);
494 mono_property_set_value (MonoProperty *prop, void *obj, void **params, MonoObject **exc)
496 default_mono_runtime_invoke (prop->set, obj, params, exc);
500 mono_property_get_value (MonoProperty *prop, void *obj, void **params, MonoObject **exc)
502 return default_mono_runtime_invoke (prop->get, obj, params, exc);
507 mono_get_delegate_invoke (MonoClass *klass)
514 for (i = 0; i < klass->method.count; ++i) {
515 if (klass->methods [i]->name[0] == 'I' &&
516 !strcmp ("Invoke", klass->methods [i]->name)) {
517 im = klass->methods [i];
527 mono_runtime_delegate_invoke (MonoObject *delegate, void **params, MonoObject **exc)
531 im = mono_get_delegate_invoke (delegate->vtable->klass);
534 return mono_runtime_invoke (im, delegate, params, exc);
537 static MonoArray* main_args;
540 mono_runtime_get_main_args (void)
545 MonoMethod *mono_start_method = NULL;
548 * Execute a standard Main() method (argc/argv contains the
549 * executable name). This method also sets the command line argument value
550 * needed by System.Environment.
553 mono_runtime_run_main (MonoMethod *method, int argc, char* argv[],
557 MonoArray *args = NULL;
558 MonoDomain *domain = mono_domain_get ();
560 main_args = (MonoArray*)mono_array_new (domain, mono_defaults.string_class, argc);
561 for (i = 0; i < argc; ++i) {
562 MonoString *arg = mono_string_new (domain, argv [i]);
563 mono_array_set (main_args, gpointer, i, arg);
567 if (method->signature->param_count) {
568 args = (MonoArray*)mono_array_new (domain, mono_defaults.string_class, argc);
569 for (i = 0; i < argc; ++i) {
570 MonoString *arg = mono_string_new (domain, argv [i]);
571 mono_array_set (args, gpointer, i, arg);
574 args = (MonoArray*)mono_array_new (domain, mono_defaults.string_class, 0);
577 mono_assembly_set_main (method->klass->image->assembly);
579 mono_start_method = mono_marshal_get_runtime_invoke (method);
581 return mono_runtime_exec_main (method, args, exc);
585 * We call this function when we dectect an unhandled exception. It invokes the
586 * UnhandledException event in AppDomain or print a warning to the console
589 mono_unhandled_exception (MonoObject *exc)
591 MonoDomain *domain = mono_domain_get ();
592 MonoClassField *field;
593 MonoObject *delegate;
595 field=mono_class_get_field_from_name(mono_defaults.appdomain_class,
596 "UnhandledException");
599 if (exc->vtable->klass != mono_defaults.threadabortexception_class) {
600 delegate = *(MonoObject **)(((char *)domain->domain) + field->offset);
603 mono_print_unhandled_exception (exc);
605 MonoObject *e = NULL;
608 /* fixme: pass useful arguments */
611 mono_runtime_delegate_invoke (delegate, pa, &e);
614 g_warning ("exception inside UnhandledException handler!");
620 * Execute a standard Main() method (args doesn't contain the
624 mono_runtime_exec_main (MonoMethod *method, MonoArray *args, MonoObject **exc)
634 domain = mono_object_domain (args);
635 if (!domain->entry_assembly)
636 domain->entry_assembly = method->klass->image->assembly;
638 /* FIXME: check signature of method */
639 if (method->signature->ret->type == MONO_TYPE_I4) {
641 res = mono_runtime_invoke (method, NULL, pa, exc);
643 rval = *(guint32 *)((char *)res + sizeof (MonoObject));
647 mono_runtime_invoke (method, NULL, pa, exc);
658 mono_install_runtime_invoke (MonoInvokeFunc func)
660 default_mono_runtime_invoke = func;
664 mono_runtime_invoke_array (MonoMethod *method, void *obj, MonoArray *params,
667 MonoMethodSignature *sig = method->signature;
671 if (NULL != params) {
672 pa = alloca (sizeof (gpointer) * mono_array_length (params));
673 for (i = 0; i < mono_array_length (params); i++) {
674 if (sig->params [i]->byref) {
678 switch (sig->params [i]->type) {
681 case MONO_TYPE_BOOLEAN:
691 case MONO_TYPE_VALUETYPE:
692 pa [i] = (char *)(((gpointer *)params->vector)[i]) + sizeof (MonoObject);
694 case MONO_TYPE_STRING:
695 case MONO_TYPE_OBJECT:
696 case MONO_TYPE_CLASS:
697 case MONO_TYPE_ARRAY:
698 case MONO_TYPE_SZARRAY:
699 pa [i] = (char *)(((gpointer *)params->vector)[i]);
702 g_error ("type 0x%x not handled in ves_icall_InternalInvoke", sig->params [i]->type);
707 if (!strcmp (method->name, ".ctor") && method->klass != mono_defaults.string_class) {
708 obj = mono_object_new (mono_domain_get (), method->klass);
709 mono_runtime_invoke (method, obj, pa, exc);
712 return mono_runtime_invoke (method, obj, pa, exc);
716 * mono_object_allocate:
717 * @size: number of bytes to allocate
719 * This is a very simplistic routine until we have our GC-aware
722 * Returns: an allocated object of size @size, or NULL on failure.
725 mono_object_allocate (size_t size)
728 /* if this is changed to GC_debug_malloc(), we need to change also metadata/gc.c */
729 void *o = GC_malloc (size);
731 void *o = calloc (1, size);
734 mono_stats.new_object_count++;
742 * Frees the memory used by the object. Debugging purposes
743 * only, as we will have our GC system.
746 mono_object_free (MonoObject *o)
749 g_error ("mono_object_free called with boehm gc.");
751 MonoClass *c = o->vtable->klass;
753 memset (o, 0, c->instance_size);
760 * @klass: the class of the object that we want to create
762 * Returns: A newly created object whose definition is
763 * looked up using @klass
766 mono_object_new (MonoDomain *domain, MonoClass *klass)
768 return mono_object_new_specific (mono_class_vtable (domain, klass));
772 * mono_object_new_specific:
773 * @vtable: the vtable of the object that we want to create
775 * Returns: A newly created object with class and domain specified
779 mono_object_new_specific (MonoVTable *vtable)
783 o = mono_object_allocate (vtable->klass->instance_size);
785 if (vtable->klass->has_finalize)
786 mono_object_register_finalizer (o);
792 * mono_object_new_from_token:
793 * @image: Context where the type_token is hosted
794 * @token: a token of the type that we want to create
796 * Returns: A newly created object whose definition is
797 * looked up using @token in the @image image
800 mono_object_new_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
804 class = mono_class_get (image, token);
806 return mono_object_new (domain, class);
812 * @obj: the object to clone
814 * Returns: A newly created object who is a shallow copy of @obj
817 mono_object_clone (MonoObject *obj)
822 size = obj->vtable->klass->instance_size;
823 o = mono_object_allocate (size);
825 memcpy (o, obj, size);
827 if (obj->vtable->klass->has_finalize)
828 mono_object_register_finalizer (o);
834 * @array: the array to clone
836 * Returns: A newly created array who is a shallow copy of @array
839 mono_array_clone (MonoArray *array)
844 MonoClass *klass = array->obj.vtable->klass;
846 if (array->bounds == NULL) {
847 size = mono_array_length (array);
848 o = mono_array_new_full (((MonoObject *)array)->vtable->domain,
851 size *= mono_array_element_size (klass);
852 memcpy (o, array, sizeof (MonoArray) + size);
857 sizes = alloca (klass->rank * sizeof(guint32) * 2);
858 size = mono_array_element_size (klass);
859 for (i = 0; i < klass->rank; ++i) {
860 sizes [i] = array->bounds [i].length;
861 size *= array->bounds [i].length;
862 sizes [i + klass->rank] = array->bounds [i].lower_bound;
864 o = mono_array_new_full (((MonoObject *)array)->vtable->domain,
865 klass, sizes, sizes + klass->rank);
866 memcpy (o, array, sizeof(MonoArray) + size);
872 * mono_array_new_full:
873 * @domain: domain where the object is created
874 * @array_class: array class
875 * @lengths: lengths for each dimension in the array
876 * @lower_bounds: lower bounds for each dimension in the array (may be NULL)
878 * This routine creates a new array objects with the given dimensions,
879 * lower bounds and type.
882 mono_array_new_full (MonoDomain *domain, MonoClass *array_class,
883 guint32 *lengths, guint32 *lower_bounds)
885 guint32 byte_len, len;
888 MonoArrayBounds *bounds;
891 if (!array_class->inited)
892 mono_class_init (array_class);
894 byte_len = mono_array_element_size (array_class);
897 if (array_class->rank == 1 &&
898 (lower_bounds == NULL || lower_bounds [0] == 0)) {
903 bounds = GC_malloc (sizeof (MonoArrayBounds) * array_class->rank);
905 bounds = g_malloc0 (sizeof (MonoArrayBounds) * array_class->rank);
907 for (i = 0; i < array_class->rank; ++i) {
908 bounds [i].length = lengths [i];
913 for (i = 0; i < array_class->rank; ++i)
914 bounds [i].lower_bound = lower_bounds [i];
919 * Following three lines almost taken from mono_object_new ():
920 * they need to be kept in sync.
922 o = mono_object_allocate (sizeof (MonoArray) + byte_len);
925 o->vtable = mono_class_vtable (domain, array_class);
927 array = (MonoArray*)o;
929 array->bounds = bounds;
930 array->max_length = len;
937 * @domain: domain where the object is created
938 * @eclass: element class
939 * @n: number of array elements
941 * This routine creates a new szarray with @n elements of type @eclass.
944 mono_array_new (MonoDomain *domain, MonoClass *eclass, guint32 n)
948 ac = mono_array_class_get (&eclass->byval_arg, 1);
949 g_assert (ac != NULL);
951 return mono_array_new_specific (mono_class_vtable (domain, ac), n);
955 * mono_array_new_specific:
956 * @vtable: a vtable in the appropriate domain for an initialized class
957 * @n: number of array elements
959 * This routine is a fast alternative to mono_array_new() for code which
960 * can be sure about the domain it operates in.
963 mono_array_new_specific (MonoVTable *vtable, guint32 n)
969 byte_len = n * mono_array_element_size (vtable->klass);
971 if (vtable->klass->element_class->byval_arg.type >= MONO_TYPE_BOOLEAN && vtable->klass->element_class->byval_arg.type <= MONO_TYPE_R4) {
972 o = GC_malloc_atomic (sizeof (MonoArray) + byte_len);
973 o->synchronisation = 0;
974 memset (((MonoArray*)o)->vector, 0, byte_len);
976 o = mono_object_allocate (sizeof (MonoArray) + byte_len);
979 o = mono_object_allocate (sizeof (MonoArray) + byte_len);
993 * mono_string_new_utf16:
994 * @text: a pointer to an utf16 string
995 * @len: the length of the string
997 * Returns: A newly created string object which contains @text.
1000 mono_string_new_utf16 (MonoDomain *domain, const guint16 *text, gint32 len)
1004 s = mono_string_new_size (domain, len);
1005 g_assert (s != NULL);
1007 memcpy (mono_string_chars (s), text, len * 2);
1013 * mono_string_new_size:
1014 * @text: a pointer to an utf16 string
1015 * @len: the length of the string
1017 * Returns: A newly created string object of @len
1020 mono_string_new_size (MonoDomain *domain, gint32 len)
1024 #if CREATION_SPEEDUP
1025 s = GC_malloc_atomic (sizeof (MonoString) + ((len + 1) * 2));
1026 s->object.synchronisation = 0;
1027 mono_string_chars (s) [len] = 0;
1029 s = (MonoString*)mono_object_allocate (sizeof (MonoString) + ((len + 1) * 2));
1034 s->object.vtable = mono_class_vtable (domain, mono_defaults.string_class);
1041 * mono_string_new_len:
1042 * @text: a pointer to an utf8 string
1043 * @length: number of bytes in @text to consider
1045 * Returns: A newly created string object which contains @text.
1048 mono_string_new_len (MonoDomain *domain, const char *text, guint length)
1050 GError *error = NULL;
1051 MonoString *o = NULL;
1053 glong items_written;
1056 ut = g_utf8_to_utf16 (text, length, NULL, &items_written, &error);
1059 o = mono_string_new_utf16 (domain, ut, items_written);
1061 g_error_free (error);
1070 * @text: a pointer to an utf8 string
1072 * Returns: A newly created string object which contains @text.
1075 mono_string_new (MonoDomain *domain, const char *text)
1077 GError *error = NULL;
1078 MonoString *o = NULL;
1080 glong items_written;
1085 ut = g_utf8_to_utf16 (text, l, NULL, &items_written, &error);
1088 o = mono_string_new_utf16 (domain, ut, items_written);
1090 g_error_free (error);
1098 * mono_string_new_wrapper:
1099 * @text: pointer to utf8 characters.
1101 * Helper function to create a string object from @text in the current domain.
1104 mono_string_new_wrapper (const char *text)
1106 MonoDomain *domain = mono_domain_get ();
1109 return mono_string_new (domain, text);
1116 * @class: the class of the value
1117 * @value: a pointer to the unboxed data
1119 * Returns: A newly created object which contains @value.
1122 mono_value_box (MonoDomain *domain, MonoClass *class, gpointer value)
1127 g_assert (class->valuetype);
1129 size = mono_class_instance_size (class);
1130 res = mono_object_allocate (size);
1131 res->vtable = mono_class_vtable (domain, class);
1133 size = size - sizeof (MonoObject);
1135 #if NO_UNALIGNED_ACCESS
1136 memcpy ((char *)res + sizeof (MonoObject), value, size);
1140 *((guint8 *) res + sizeof (MonoObject)) = *(guint8 *) value;
1143 *(guint16 *)((guint8 *) res + sizeof (MonoObject)) = *(guint16 *) value;
1146 *(guint32 *)((guint8 *) res + sizeof (MonoObject)) = *(guint32 *) value;
1149 *(guint64 *)((guint8 *) res + sizeof (MonoObject)) = *(guint64 *) value;
1152 memcpy ((char *)res + sizeof (MonoObject), value, size);
1155 if (class->has_finalize)
1156 mono_object_register_finalizer (res);
1161 * mono_object_isinst:
1163 * @klass: a pointer to a class
1165 * Returns: @obj if @obj is derived from @klass
1168 mono_object_isinst (MonoObject *obj, MonoClass *klass)
1180 mono_class_init (klass);
1182 if (klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
1183 if ((klass->interface_id <= oklass->max_interface_id) &&
1184 vt->interface_offsets [klass->interface_id])
1187 if (oklass == mono_defaults.transparent_proxy_class) {
1188 /* fixme: add check for IRemotingTypeInfo */
1189 oklass = ((MonoTransparentProxy *)obj)->klass;
1192 if (oklass->rank == klass->rank &&
1193 (oklass->element_class->baseval - klass->element_class->baseval) <=
1194 klass->element_class->diffval)
1197 } else if ((oklass->baseval - klass->baseval) <= klass->diffval)
1205 mono_string_is_interned_lookup (MonoString *str, int insert)
1207 MonoGHashTable *ldstr_table;
1210 char *ins = g_malloc (4 + str->length * 2);
1214 /* Encode the length */
1216 mono_metadata_encode_value (2 * str->length, p, &p);
1219 mono_metadata_encode_value (bloblen + 2 * str->length, p, &p);
1220 bloblen = (p - ins) + 2 * str->length;
1222 * ins is stored in the hash table as a key and needs to have the same
1223 * representation as in the metadata: we swap the character bytes on big
1226 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
1229 char *p2 = mono_string_chars (str);
1230 for (i = 0; i < str->length; ++i) {
1237 memcpy (p, mono_string_chars (str), str->length * 2);
1239 domain = ((MonoObject *)str)->vtable->domain;
1240 ldstr_table = domain->ldstr_table;
1241 mono_domain_lock (domain);
1242 if ((res = mono_g_hash_table_lookup (ldstr_table, ins))) {
1243 mono_domain_unlock (domain);
1248 mono_g_hash_table_insert (ldstr_table, ins, str);
1249 mono_domain_unlock (domain);
1252 mono_domain_unlock (domain);
1258 mono_string_is_interned (MonoString *o)
1260 return mono_string_is_interned_lookup (o, FALSE);
1264 mono_string_intern (MonoString *str)
1266 return mono_string_is_interned_lookup (str, TRUE);
1271 * @domain: the domain where the string will be used.
1272 * @image: a metadata context
1273 * @idx: index into the user string table.
1275 * Implementation for the ldstr opcode.
1278 mono_ldstr (MonoDomain *domain, MonoImage *image, guint32 idx)
1280 const char *str, *sig;
1284 sig = str = mono_metadata_user_string (image, idx);
1286 mono_domain_lock (domain);
1287 if ((o = mono_g_hash_table_lookup (domain->ldstr_table, sig))) {
1288 mono_domain_unlock (domain);
1292 len2 = mono_metadata_decode_blob_size (str, &str);
1295 o = mono_string_new_utf16 (domain, (guint16*)str, len2);
1296 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
1299 guint16 *p2 = (guint16*)mono_string_chars (o);
1300 for (i = 0; i < len2; ++i) {
1301 *p2 = GUINT16_FROM_LE (*p2);
1306 mono_g_hash_table_insert (domain->ldstr_table, (gpointer)sig, o);
1307 mono_domain_unlock (domain);
1313 * mono_string_to_utf8:
1314 * @s: a System.String
1316 * Return the UTF8 representation for @s.
1317 * the resulting buffer nedds to be freed with g_free().
1320 mono_string_to_utf8 (MonoString *s)
1323 GError *error = NULL;
1329 return g_strdup ("");
1331 as = g_utf16_to_utf8 (mono_string_chars (s), s->length, NULL, NULL, &error);
1333 g_warning (error->message);
1339 * mono_string_to_utf16:
1342 * Return an null-terminated array of the utf-16 chars
1343 * contained in @s. The result must be freed with g_free().
1344 * This is a temporary helper until our string implementation
1345 * is reworked to always include the null terminating char.
1348 mono_string_to_utf16 (MonoString *s)
1355 as = g_malloc ((s->length * 2) + 2);
1356 as [(s->length * 2)] = '\0';
1357 as [(s->length * 2) + 1] = '\0';
1360 return (gunichar2 *)(as);
1363 memcpy (as, mono_string_chars(s), s->length * 2);
1364 return (gunichar2 *)(as);
1368 default_ex_handler (MonoException *ex)
1370 MonoObject *o = (MonoObject*)ex;
1371 g_error ("Exception %s.%s raised in C code", o->vtable->klass->name_space, o->vtable->klass->name);
1374 static MonoExceptionFunc ex_handler = default_ex_handler;
1377 mono_install_handler (MonoExceptionFunc func)
1379 ex_handler = func? func: default_ex_handler;
1383 * mono_raise_exception:
1384 * @ex: exception object
1386 * Signal the runtime that the exception @ex has been raised in unmanaged code.
1389 mono_raise_exception (MonoException *ex)
1395 mono_wait_handle_new (MonoDomain *domain, HANDLE handle)
1397 MonoWaitHandle *res;
1399 res = (MonoWaitHandle *)mono_object_new (domain, mono_defaults.waithandle_class);
1401 res->handle = handle;
1407 mono_async_result_new (MonoDomain *domain, HANDLE handle, MonoObject *state, gpointer data)
1409 MonoAsyncResult *res;
1411 res = (MonoAsyncResult *)mono_object_new (domain, mono_defaults.asyncresult_class);
1414 res->async_state = state;
1415 res->handle = (MonoObject *)mono_wait_handle_new (domain, handle);
1416 res->sync_completed = FALSE;
1417 res->completed = FALSE;
1423 mono_message_init (MonoDomain *domain,
1424 MonoMethodMessage *this,
1425 MonoReflectionMethod *method,
1426 MonoArray *out_args)
1428 MonoMethodSignature *sig = method->method->signature;
1434 this->method = method;
1436 this->args = mono_array_new (domain, mono_defaults.object_class, sig->param_count);
1437 this->arg_types = mono_array_new (domain, mono_defaults.byte_class, sig->param_count);
1439 names = g_new (char *, sig->param_count);
1440 mono_method_get_param_names (method->method, (const char **) names);
1441 this->names = mono_array_new (domain, mono_defaults.string_class, sig->param_count);
1443 for (i = 0; i < sig->param_count; i++) {
1444 name = mono_string_new (domain, names [i]);
1445 mono_array_set (this->names, gpointer, i, name);
1450 for (i = 0, j = 0; i < sig->param_count; i++) {
1452 if (sig->params [i]->byref) {
1454 gpointer arg = mono_array_get (out_args, gpointer, j);
1455 mono_array_set (this->args, gpointer, i, arg);
1459 if (sig->params [i]->attrs & PARAM_ATTRIBUTE_IN)
1465 mono_array_set (this->arg_types, guint8, i, arg_type);
1470 * mono_remoting_invoke:
1471 * @real_proxy: pointer to a RealProxy object
1472 * @msg: The MonoMethodMessage to execute
1473 * @exc: used to store exceptions
1474 * @out_args: used to store output arguments
1476 * This is used to call RealProxy::Invoke(). RealProxy::Invoke() returns an
1477 * IMessage interface and it is not trivial to extract results from there. So
1478 * we call an helper method PrivateInvoke instead of calling
1479 * RealProxy::Invoke() directly.
1481 * Returns: the result object.
1484 mono_remoting_invoke (MonoObject *real_proxy, MonoMethodMessage *msg,
1485 MonoObject **exc, MonoArray **out_args)
1487 static MonoMethod *im = NULL;
1490 /*static MonoObject *(*invoke) (gpointer, gpointer, MonoObject **, MonoArray **) = NULL;*/
1492 /* FIXME: make this domain dependent */
1497 klass = mono_defaults.real_proxy_class;
1499 for (i = 0; i < klass->method.count; ++i) {
1500 if (!strcmp ("PrivateInvoke", klass->methods [i]->name) &&
1501 klass->methods [i]->signature->param_count == 4) {
1502 im = klass->methods [i];
1510 pa [0] = real_proxy;
1515 return mono_runtime_invoke (im, NULL, pa, exc);
1519 mono_message_invoke (MonoObject *target, MonoMethodMessage *msg,
1520 MonoObject **exc, MonoArray **out_args)
1522 if (target && target->vtable->klass == mono_defaults.transparent_proxy_class) {
1524 return mono_remoting_invoke ((MonoObject *)((MonoTransparentProxy *)target)->rp,
1525 msg, exc, out_args);
1528 MonoDomain *domain = mono_domain_get ();
1529 MonoMethod *method = msg->method->method;
1530 MonoMethodSignature *sig = method->signature;
1531 int i, j, outarg_count = 0;
1533 for (i = 0; i < sig->param_count; i++) {
1534 if (sig->params [i]->byref)
1538 *out_args = mono_array_new (domain, mono_defaults.object_class, outarg_count);
1541 for (i = 0, j = 0; i < sig->param_count; i++) {
1542 if (sig->params [i]->byref) {
1544 arg = mono_array_get (msg->args, gpointer, i);
1545 mono_array_set (*out_args, gpointer, j, arg);
1550 return mono_runtime_invoke_array (method, target, msg->args, exc);
1555 mono_print_unhandled_exception (MonoObject *exc)
1557 char *message = (char *) "";
1561 gboolean free_message = FALSE;
1564 if (mono_object_isinst (exc, mono_defaults.exception_class)) {
1565 klass = exc->vtable->klass;
1567 while (klass && method == NULL) {
1568 for (i = 0; i < klass->method.count; ++i) {
1569 method = klass->methods [i];
1570 if (!strcmp ("ToString", method->name) &&
1571 method->signature->param_count == 0 &&
1572 method->flags & METHOD_ATTRIBUTE_VIRTUAL &&
1573 method->flags & METHOD_ATTRIBUTE_PUBLIC) {
1580 klass = klass->parent;
1585 str = (MonoString *) mono_runtime_invoke (method, exc, NULL, NULL);
1587 message = mono_string_to_utf8 (str);
1588 free_message = TRUE;
1593 * g_printerr ("\nUnhandled Exception: %s.%s: %s\n", exc->vtable->klass->name_space,
1594 * exc->vtable->klass->name, message);
1596 g_printerr ("\nUnhandled Exception: %s\n", message);
1603 * mono_delegate_ctor:
1604 * @this: pointer to an uninitialized delegate object
1605 * @target: target object
1606 * @addr: pointer to native code
1608 * This is used to initialize a delegate. We also insert the method_info if
1609 * we find the info with mono_jit_info_table_find().
1612 mono_delegate_ctor (MonoObject *this, MonoObject *target, gpointer addr)
1614 MonoDomain *domain = mono_domain_get ();
1615 MonoDelegate *delegate = (MonoDelegate *)this;
1616 MonoMethod *method = NULL;
1623 class = this->vtable->klass;
1625 if ((ji = mono_jit_info_table_find (domain, addr))) {
1626 method = ji->method;
1627 delegate->method_info = mono_method_get_object (domain, method, NULL);
1630 if (target && target->vtable->klass == mono_defaults.transparent_proxy_class) {
1632 method = mono_marshal_get_remoting_invoke (method);
1633 delegate->method_ptr = mono_compile_method (method);
1634 delegate->target = target;
1636 delegate->method_ptr = addr;
1637 delegate->target = target;
1642 * mono_method_call_message_new:
1644 * Translates arguments pointers into a Message.
1647 mono_method_call_message_new (MonoMethod *method, gpointer *params, MonoMethod *invoke,
1648 MonoDelegate **cb, MonoObject **state)
1650 MonoDomain *domain = mono_domain_get ();
1651 MonoMethodSignature *sig = method->signature;
1652 MonoMethodMessage *msg;
1655 msg = (MonoMethodMessage *)mono_object_new (domain, mono_defaults.mono_method_message_class);
1658 mono_message_init (domain, msg, mono_method_get_object (domain, invoke, NULL), NULL);
1659 count = sig->param_count - 2;
1661 mono_message_init (domain, msg, mono_method_get_object (domain, method, NULL), NULL);
1662 count = sig->param_count;
1665 for (i = 0; i < count; i++) {
1670 if (sig->params [i]->byref)
1671 vpos = *((gpointer *)params [i]);
1675 type = sig->params [i]->type;
1676 class = mono_class_from_mono_type (sig->params [i]);
1678 if (class->valuetype)
1679 arg = mono_value_box (domain, class, vpos);
1681 arg = *((MonoObject **)vpos);
1683 mono_array_set (msg->args, gpointer, i, arg);
1687 *cb = *((MonoDelegate **)params [i]);
1689 *state = *((MonoObject **)params [i]);
1696 * mono_method_return_message_restore:
1698 * Restore results from message based processing back to arguments pointers
1701 mono_method_return_message_restore (MonoMethod *method, gpointer *params, MonoArray *out_args)
1703 MonoMethodSignature *sig = method->signature;
1704 int i, j, type, size;
1706 for (i = 0, j = 0; i < sig->param_count; i++) {
1707 MonoType *pt = sig->params [i];
1709 size = mono_type_stack_size (pt, NULL);
1712 char *arg = mono_array_get (out_args, gpointer, j);
1716 case MONO_TYPE_VOID:
1717 g_assert_not_reached ();
1721 case MONO_TYPE_BOOLEAN:
1724 case MONO_TYPE_CHAR:
1731 case MONO_TYPE_VALUETYPE: {
1732 memcpy (*((gpointer *)params [i]), arg + sizeof (MonoObject), size);
1735 case MONO_TYPE_STRING:
1736 case MONO_TYPE_CLASS:
1737 case MONO_TYPE_ARRAY:
1738 case MONO_TYPE_SZARRAY:
1739 *((MonoObject **)params [i]) = (MonoObject *)arg;
1742 g_assert_not_reached ();
1751 * mono_load_remote_field:
1752 * @this: pointer to an object
1753 * @klass: klass of the object containing @field
1754 * @field: the field to load
1755 * @res: a storage to store the result
1757 * This method is called by the runtime on attempts to load fields of
1758 * transparent proxy objects. @this points to such TP, @klass is the class of
1759 * the object containing @field. @res is a storage location which can be
1760 * used to store the result.
1762 * Returns: an address pointing to the value of field.
1765 mono_load_remote_field (MonoObject *this, MonoClass *klass, MonoClassField *field, gpointer *res)
1767 static MonoMethod *getter = NULL;
1768 MonoDomain *domain = mono_domain_get ();
1769 MonoClass *field_class;
1770 MonoMethodMessage *msg;
1771 MonoArray *out_args;
1775 g_assert (this->vtable->klass == mono_defaults.transparent_proxy_class);
1783 for (i = 0; i < mono_defaults.object_class->method.count; ++i) {
1784 MonoMethod *cm = mono_defaults.object_class->methods [i];
1786 if (!strcmp (cm->name, "FieldGetter")) {
1794 field_class = mono_class_from_mono_type (field->type);
1796 msg = (MonoMethodMessage *)mono_object_new (domain, mono_defaults.mono_method_message_class);
1797 out_args = mono_array_new (domain, mono_defaults.object_class, 1);
1798 mono_message_init (domain, msg, mono_method_get_object (domain, getter, NULL), out_args);
1800 mono_array_set (msg->args, gpointer, 0, mono_string_new (domain, klass->name));
1801 mono_array_set (msg->args, gpointer, 1, mono_string_new (domain, field->name));
1803 mono_remoting_invoke ((MonoObject *)((MonoTransparentProxy *)this)->rp, msg, &exc, &out_args);
1805 *res = mono_array_get (out_args, MonoObject *, 0);
1807 if (field_class->valuetype) {
1808 return ((char *)*res) + sizeof (MonoObject);
1814 * mono_store_remote_field:
1815 * @this: pointer to an object
1816 * @klass: klass of the object containing @field
1817 * @field: the field to load
1818 * @val: the value/object to store
1820 * This method is called by the runtime on attempts to store fields of
1821 * transparent proxy objects. @this points to such TP, @klass is the class of
1822 * the object containing @field. @val is the new value to store in @field.
1825 mono_store_remote_field (MonoObject *this, MonoClass *klass, MonoClassField *field, gpointer val)
1827 static MonoMethod *setter = NULL;
1828 MonoDomain *domain = mono_domain_get ();
1829 MonoClass *field_class;
1830 MonoMethodMessage *msg;
1831 MonoArray *out_args;
1835 g_assert (this->vtable->klass == mono_defaults.transparent_proxy_class);
1840 for (i = 0; i < mono_defaults.object_class->method.count; ++i) {
1841 MonoMethod *cm = mono_defaults.object_class->methods [i];
1843 if (!strcmp (cm->name, "FieldSetter")) {
1851 field_class = mono_class_from_mono_type (field->type);
1853 if (field_class->valuetype)
1854 arg = mono_value_box (domain, field_class, val);
1856 arg = *((MonoObject **)val);
1859 msg = (MonoMethodMessage *)mono_object_new (domain, mono_defaults.mono_method_message_class);
1860 mono_message_init (domain, msg, mono_method_get_object (domain, setter, NULL), NULL);
1862 mono_array_set (msg->args, gpointer, 0, mono_string_new (domain, klass->name));
1863 mono_array_set (msg->args, gpointer, 1, mono_string_new (domain, field->name));
1864 mono_array_set (msg->args, gpointer, 2, arg);
1866 mono_remoting_invoke ((MonoObject *)((MonoTransparentProxy *)this)->rp, msg, &exc, &out_args);