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/exception.h>
21 #include <mono/metadata/appdomain.h>
22 #include <mono/metadata/assembly.h>
23 #include <mono/metadata/threadpool.h>
24 #include <mono/metadata/marshal.h>
25 #include "mono/metadata/debug-helpers.h"
26 #include "mono/metadata/marshal.h"
27 #include <mono/os/gc_wrapper.h>
30 * enable to get a good speedup: we still need to figure out
31 * how the sync structure is freed.
33 #define CREATION_SPEEDUP 0
36 mono_runtime_object_init (MonoObject *this)
39 MonoMethod *method = NULL;
40 MonoClass *klass = this->vtable->klass;
42 for (i = 0; i < klass->method.count; ++i) {
43 if (!strcmp (".ctor", klass->methods [i]->name) &&
44 klass->methods [i]->signature->param_count == 0) {
45 method = klass->methods [i];
52 mono_runtime_invoke (method, this, NULL, NULL);
57 * @klass: klass that needs to be initialized
59 * This routine calls the class constructor for @class.
62 mono_runtime_class_init (MonoClass *klass)
66 for (i = 0; i < klass->method.count; ++i) {
67 MonoMethod *method = klass->methods [i];
68 if ((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
69 (strcmp (".cctor", method->name) == 0)) {
70 mono_runtime_invoke (method, NULL, NULL, NULL);
75 /* No class constructor found */
79 default_trampoline (MonoMethod *method)
85 default_remoting_trampoline (MonoMethod *method)
87 g_error ("remoting not installed");
91 static MonoTrampoline arch_create_jit_trampoline = default_trampoline;
92 static MonoTrampoline arch_create_remoting_trampoline = default_remoting_trampoline;
95 mono_install_trampoline (MonoTrampoline func)
97 arch_create_jit_trampoline = func? func: default_trampoline;
101 mono_install_remoting_trampoline (MonoTrampoline func)
103 arch_create_remoting_trampoline = func? func: default_remoting_trampoline;
106 static MonoCompileFunc default_mono_compile_method = NULL;
109 mono_install_compile_method (MonoCompileFunc func)
111 default_mono_compile_method = func;
115 mono_compile_method (MonoMethod *method)
117 if (!default_mono_compile_method) {
118 g_error ("compile method called on uninitialized runtime");
121 return default_mono_compile_method (method);
125 #if 0 && HAVE_BOEHM_GC
127 vtable_finalizer (void *obj, void *data) {
128 g_print ("%s finalized (%p)\n", (char*)data, obj);
134 * @domain: the application domain
135 * @class: the class to initialize
137 * VTables are domain specific because we create domain specific code, and
138 * they contain the domain specific static class data.
141 mono_class_vtable (MonoDomain *domain, MonoClass *class)
145 MonoClassField *field;
147 guint32 cols [MONO_CONSTANT_SIZE];
154 vt = class->cached_vtable;
155 if (vt && vt->domain == domain)
158 /* can interfaces have static fields? */
159 if (class->flags & TYPE_ATTRIBUTE_INTERFACE)
160 g_assert_not_reached ();
162 mono_domain_lock (domain);
163 if ((vt = mono_g_hash_table_lookup (domain->class_vtable_hash, class))) {
164 mono_domain_unlock (domain);
169 mono_class_init (class);
171 mono_stats.used_class_count++;
172 mono_stats.class_vtable_size += sizeof (MonoVTable) + class->vtable_size * sizeof (gpointer);
174 vt = mono_mempool_alloc0 (domain->mp, sizeof (MonoVTable) +
175 class->vtable_size * sizeof (gpointer));
179 if (class->class_size) {
181 vt->data = GC_MALLOC (class->class_size + 8);
182 /*vt->data = GC_debug_malloc (class->class_size + 8, class->name, 2);*/
183 /*GC_register_finalizer (vt->data, vtable_finalizer, class->name, NULL, NULL);*/
184 mono_g_hash_table_insert (domain->static_data_hash, class, vt->data);
186 vt->data = mono_mempool_alloc0 (domain->mp, class->class_size + 8);
189 mono_stats.class_static_data_size += class->class_size + 8;
192 for (i = class->field.first; i < class->field.last; ++i) {
193 field = &class->fields [i - class->field.first];
194 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
196 if ((field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA)) {
197 MonoClass *fklass = mono_class_from_mono_type (field->type);
198 t = (char*)vt->data + field->offset;
199 g_assert (fklass->valuetype);
200 memcpy (t, field->data, mono_class_value_size (fklass, NULL));
203 if (!(field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT))
205 cindex = mono_metadata_get_constant_index (class->image, MONO_TOKEN_FIELD_DEF | (i + 1));
207 g_warning ("constant for field %s not found", field->name);
210 mono_metadata_decode_row (&class->image->tables [MONO_TABLE_CONSTANT], cindex - 1, cols, MONO_CONSTANT_SIZE);
211 p = mono_metadata_blob_heap (class->image, cols [MONO_CONSTANT_VALUE]);
212 len = mono_metadata_decode_blob_size (p, &p);
213 t = (char*)vt->data + field->offset;
214 /* should we check that the type matches? */
215 switch (cols [MONO_CONSTANT_TYPE]) {
216 case MONO_TYPE_BOOLEAN:
224 guint16 *val = (guint16*)t;
230 guint32 *val = (guint32*)t;
236 guint64 *val = (guint64*)t;
241 float *val = (float*)t;
246 double *val = (double*)t;
250 case MONO_TYPE_STRING: {
251 gpointer *val = (gpointer*)t;
252 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
253 gunichar2 *copy = g_malloc (len);
255 for (j = 0; j < len/2; j++) {
256 copy [j] = read16 (p);
259 *val = mono_string_new_utf16 (domain, copy, len/2);
262 *val = mono_string_new_utf16 (domain, (const guint16*)p, len/2);
266 case MONO_TYPE_CLASS:
267 /* nothing to do, we malloc0 the data and the value can be 0 only */
270 g_warning ("type 0x%02x should not be in constant table", cols [MONO_CONSTANT_TYPE]);
274 vt->max_interface_id = class->max_interface_id;
276 vt->interface_offsets = mono_mempool_alloc0 (domain->mp,
277 sizeof (gpointer) * (class->max_interface_id + 1));
279 /* initialize interface offsets */
280 for (k = class; k ; k = k->parent) {
281 for (i = 0; i < k->interface_count; i++) {
283 MonoClass *ic = k->interfaces [i];
284 slot = class->interface_offsets [ic->interface_id];
285 vt->interface_offsets [ic->interface_id] = &vt->vtable [slot];
289 /* initialize vtable */
290 for (i = 0; i < class->vtable_size; ++i) {
293 if ((cm = class->vtable [i]))
294 vt->vtable [i] = arch_create_jit_trampoline (cm);
297 mono_g_hash_table_insert (domain->class_vtable_hash, class, vt);
298 if (!class->cached_vtable)
299 class->cached_vtable = vt;
301 mono_domain_unlock (domain);
303 /* make sure the the parent is initialized */
305 mono_class_vtable (domain, class->parent);
307 mono_runtime_class_init (class);
313 * mono_class_proxy_vtable:
314 * @domain: the application domain
315 * @class: the class to proxy
317 * Creates a vtable for transparent proxies. It is basically
318 * a copy of the real vtable of @class, but all function pointers invoke
319 * the remoting functions, and vtable->klass points to the
320 * transparent proxy class, and not to @class.
323 mono_class_proxy_vtable (MonoDomain *domain, MonoClass *class)
325 MonoVTable *vt, *pvt;
328 if ((pvt = mono_g_hash_table_lookup (domain->proxy_vtable_hash, class)))
331 vt = mono_class_vtable (domain, class);
332 vtsize = sizeof (MonoVTable) + class->vtable_size * sizeof (gpointer);
334 mono_stats.class_vtable_size += vtsize;
336 pvt = mono_mempool_alloc (domain->mp, vtsize);
337 memcpy (pvt, vt, vtsize);
339 pvt->klass = mono_defaults.transparent_proxy_class;
341 /* initialize vtable */
342 for (i = 0; i < class->vtable_size; ++i) {
345 if ((cm = class->vtable [i]))
346 pvt->vtable [i] = arch_create_remoting_trampoline (cm);
349 mono_g_hash_table_insert (domain->proxy_vtable_hash, class, pvt);
355 * Retrieve the MonoMethod that would to be called on obj if obj is passed as
356 * the instance of a callvirt of method.
359 mono_object_get_virtual_method (MonoObject *obj, MonoMethod *method) {
365 if ((method->flags & METHOD_ATTRIBUTE_FINAL) || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL))
368 klass = mono_object_class (obj);
369 if (klass == mono_defaults.transparent_proxy_class) {
370 klass = ((MonoTransparentProxy *)obj)->klass;
375 vtable = klass->vtable;
377 if (method->klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
378 res = vtable [method->klass->interface_id + method->slot];
380 res = vtable [method->slot];
385 return mono_marshal_get_remoting_invoke (res);
391 dummy_mono_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
393 g_error ("runtime invoke called on uninitialized runtime");
397 static MonoInvokeFunc default_mono_runtime_invoke = dummy_mono_runtime_invoke;
400 mono_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
402 return default_mono_runtime_invoke (method, obj, params, exc);
406 set_value (MonoType *type, void *dest, void *value, int deref_pointer) {
409 gpointer *p = (gpointer*)dest;
416 case MONO_TYPE_BOOLEAN:
419 guint8 *p = (guint8*)dest;
420 *p = *(guint8*)value;
425 case MONO_TYPE_CHAR: {
426 guint16 *p = (guint16*)dest;
427 *p = *(guint16*)value;
430 #if SIZEOF_VOID_P == 4
436 gint32 *p = (gint32*)dest;
437 *p = *(gint32*)value;
440 #if SIZEOF_VOID_P == 8
446 gint64 *p = (gint64*)dest;
447 *p = *(gint64*)value;
451 float *p = (float*)dest;
456 double *p = (double*)dest;
457 *p = *(double*)value;
460 case MONO_TYPE_STRING:
461 case MONO_TYPE_SZARRAY:
462 case MONO_TYPE_CLASS:
463 case MONO_TYPE_OBJECT:
464 case MONO_TYPE_ARRAY:
465 case MONO_TYPE_PTR: {
466 gpointer *p = (gpointer*)dest;
467 *p = deref_pointer? *(gpointer*)value: value;
470 case MONO_TYPE_VALUETYPE:
471 if (type->data.klass->enumtype) {
472 t = type->data.klass->enum_basetype->type;
476 size = mono_class_value_size (type->data.klass, NULL);
477 memcpy (dest, value, size);
481 g_warning ("got type %x", type->type);
482 g_assert_not_reached ();
487 mono_field_set_value (MonoObject *obj, MonoClassField *field, void *value)
491 g_return_if_fail (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC));
493 dest = (char*)obj + field->offset;
494 set_value (field->type, dest, value, FALSE);
498 mono_field_static_set_value (MonoVTable *vt, MonoClassField *field, void *value)
502 g_return_if_fail (field->type->attrs & FIELD_ATTRIBUTE_STATIC);
504 dest = (char*)vt->data + field->offset;
505 set_value (field->type, dest, value, FALSE);
509 mono_field_get_value (MonoObject *obj, MonoClassField *field, void *value)
513 g_return_if_fail (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC));
515 src = (char*)obj + field->offset;
516 set_value (field->type, value, src, TRUE);
520 mono_field_static_get_value (MonoVTable *vt, MonoClassField *field, void *value)
524 g_return_if_fail (field->type->attrs & FIELD_ATTRIBUTE_STATIC);
526 src = (char*)vt->data + field->offset;
527 set_value (field->type, value, src, TRUE);
531 mono_property_set_value (MonoProperty *prop, void *obj, void **params, MonoObject **exc)
533 default_mono_runtime_invoke (prop->set, obj, params, exc);
537 mono_property_get_value (MonoProperty *prop, void *obj, void **params, MonoObject **exc)
539 return default_mono_runtime_invoke (prop->get, obj, params, exc);
544 mono_get_delegate_invoke (MonoClass *klass)
551 for (i = 0; i < klass->method.count; ++i) {
552 if (klass->methods [i]->name[0] == 'I' &&
553 !strcmp ("Invoke", klass->methods [i]->name)) {
554 im = klass->methods [i];
564 mono_runtime_delegate_invoke (MonoObject *delegate, void **params, MonoObject **exc)
568 im = mono_get_delegate_invoke (delegate->vtable->klass);
571 return mono_runtime_invoke (im, delegate, params, exc);
574 static MonoArray* main_args;
577 mono_runtime_get_main_args (void)
582 MonoMethod *mono_start_method = NULL;
585 * Execute a standard Main() method (argc/argv contains the
586 * executable name). This method also sets the command line argument value
587 * needed by System.Environment.
590 mono_runtime_run_main (MonoMethod *method, int argc, char* argv[],
594 MonoArray *args = NULL;
595 MonoDomain *domain = mono_domain_get ();
597 main_args = (MonoArray*)mono_array_new (domain, mono_defaults.string_class, argc);
598 for (i = 0; i < argc; ++i) {
599 MonoString *arg = mono_string_new (domain, argv [i]);
600 mono_array_set (main_args, gpointer, i, arg);
604 if (method->signature->param_count) {
605 args = (MonoArray*)mono_array_new (domain, mono_defaults.string_class, argc);
606 for (i = 0; i < argc; ++i) {
607 MonoString *arg = mono_string_new (domain, argv [i]);
608 mono_array_set (args, gpointer, i, arg);
611 args = (MonoArray*)mono_array_new (domain, mono_defaults.string_class, 0);
614 mono_assembly_set_main (method->klass->image->assembly);
616 mono_start_method = mono_marshal_get_runtime_invoke (method);
618 return mono_runtime_exec_main (method, args, exc);
622 * We call this function when we dectect an unhandled exception. It invokes the
623 * UnhandledException event in AppDomain or print a warning to the console
626 mono_unhandled_exception (MonoObject *exc)
628 MonoDomain *domain = mono_domain_get ();
629 MonoClassField *field;
630 MonoObject *delegate;
632 field=mono_class_get_field_from_name(mono_defaults.appdomain_class,
633 "UnhandledException");
636 if (exc->vtable->klass != mono_defaults.threadabortexception_class) {
637 delegate = *(MonoObject **)(((char *)domain->domain) + field->offset);
640 mono_print_unhandled_exception (exc);
642 MonoObject *e = NULL;
645 /* fixme: pass useful arguments */
648 mono_runtime_delegate_invoke (delegate, pa, &e);
651 g_warning ("exception inside UnhandledException handler!");
657 * Execute a standard Main() method (args doesn't contain the
661 mono_runtime_exec_main (MonoMethod *method, MonoArray *args, MonoObject **exc)
671 domain = mono_object_domain (args);
672 if (!domain->entry_assembly) {
673 domain->entry_assembly = method->klass->image->assembly;
674 ves_icall_System_AppDomainSetup_InitAppDomainSetup (domain->setup);
677 /* FIXME: check signature of method */
678 if (method->signature->ret->type == MONO_TYPE_I4) {
680 res = mono_runtime_invoke (method, NULL, pa, exc);
682 rval = *(guint32 *)((char *)res + sizeof (MonoObject));
686 mono_runtime_invoke (method, NULL, pa, exc);
697 mono_install_runtime_invoke (MonoInvokeFunc func)
699 default_mono_runtime_invoke = func ? func: dummy_mono_runtime_invoke;
703 mono_runtime_invoke_array (MonoMethod *method, void *obj, MonoArray *params,
706 MonoMethodSignature *sig = method->signature;
710 if (NULL != params) {
711 pa = alloca (sizeof (gpointer) * mono_array_length (params));
712 for (i = 0; i < mono_array_length (params); i++) {
713 if (sig->params [i]->byref) {
717 switch (sig->params [i]->type) {
720 case MONO_TYPE_BOOLEAN:
732 case MONO_TYPE_VALUETYPE:
733 pa [i] = (char *)(((gpointer *)params->vector)[i]) + sizeof (MonoObject);
735 case MONO_TYPE_STRING:
736 case MONO_TYPE_OBJECT:
737 case MONO_TYPE_CLASS:
738 case MONO_TYPE_ARRAY:
739 case MONO_TYPE_SZARRAY:
740 pa [i] = (char *)(((gpointer *)params->vector)[i]);
743 g_error ("type 0x%x not handled in ves_icall_InternalInvoke", sig->params [i]->type);
748 if (!strcmp (method->name, ".ctor") && method->klass != mono_defaults.string_class) {
750 obj = mono_object_new (mono_domain_get (), method->klass);
751 mono_runtime_invoke (method, obj, pa, exc);
754 return mono_runtime_invoke (method, obj, pa, exc);
758 * mono_object_allocate:
759 * @size: number of bytes to allocate
761 * This is a very simplistic routine until we have our GC-aware
764 * Returns: an allocated object of size @size, or NULL on failure.
767 mono_object_allocate (size_t size)
770 /* if this is changed to GC_debug_malloc(), we need to change also metadata/gc.c */
771 void *o = GC_MALLOC (size);
773 void *o = calloc (1, size);
776 mono_stats.new_object_count++;
784 * Frees the memory used by the object. Debugging purposes
785 * only, as we will have our GC system.
788 mono_object_free (MonoObject *o)
791 g_error ("mono_object_free called with boehm gc.");
793 MonoClass *c = o->vtable->klass;
795 memset (o, 0, c->instance_size);
802 * @klass: the class of the object that we want to create
804 * Returns: A newly created object whose definition is
805 * looked up using @klass
808 mono_object_new (MonoDomain *domain, MonoClass *klass)
810 return mono_object_new_specific (mono_class_vtable (domain, klass));
814 * mono_object_new_specific:
815 * @vtable: the vtable of the object that we want to create
817 * Returns: A newly created object with class and domain specified
821 mono_object_new_specific (MonoVTable *vtable)
825 o = mono_object_allocate (vtable->klass->instance_size);
827 if (vtable->klass->has_finalize)
828 mono_object_register_finalizer (o);
834 * mono_object_new_from_token:
835 * @image: Context where the type_token is hosted
836 * @token: a token of the type that we want to create
838 * Returns: A newly created object whose definition is
839 * looked up using @token in the @image image
842 mono_object_new_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
846 class = mono_class_get (image, token);
848 return mono_object_new (domain, class);
854 * @obj: the object to clone
856 * Returns: A newly created object who is a shallow copy of @obj
859 mono_object_clone (MonoObject *obj)
864 size = obj->vtable->klass->instance_size;
865 o = mono_object_allocate (size);
867 memcpy (o, obj, size);
869 if (obj->vtable->klass->has_finalize)
870 mono_object_register_finalizer (o);
876 * @array: the array to clone
878 * Returns: A newly created array who is a shallow copy of @array
881 mono_array_clone (MonoArray *array)
886 MonoClass *klass = array->obj.vtable->klass;
890 if (array->bounds == NULL) {
891 size = mono_array_length (array);
892 o = mono_array_new_full (((MonoObject *)array)->vtable->domain,
895 size *= mono_array_element_size (klass);
896 memcpy (o, array, sizeof (MonoArray) + size);
901 sizes = alloca (klass->rank * sizeof(guint32) * 2);
902 size = mono_array_element_size (klass);
903 for (i = 0; i < klass->rank; ++i) {
904 sizes [i] = array->bounds [i].length;
905 size *= array->bounds [i].length;
906 sizes [i + klass->rank] = array->bounds [i].lower_bound;
908 o = mono_array_new_full (((MonoObject *)array)->vtable->domain,
909 klass, sizes, sizes + klass->rank);
910 memcpy (o, array, sizeof(MonoArray) + size);
916 * mono_array_new_full:
917 * @domain: domain where the object is created
918 * @array_class: array class
919 * @lengths: lengths for each dimension in the array
920 * @lower_bounds: lower bounds for each dimension in the array (may be NULL)
922 * This routine creates a new array objects with the given dimensions,
923 * lower bounds and type.
926 mono_array_new_full (MonoDomain *domain, MonoClass *array_class,
927 guint32 *lengths, guint32 *lower_bounds)
929 guint32 byte_len, len;
932 MonoArrayBounds *bounds;
935 if (!array_class->inited)
936 mono_class_init (array_class);
938 byte_len = mono_array_element_size (array_class);
941 if (array_class->rank == 1 &&
942 (lower_bounds == NULL || lower_bounds [0] == 0)) {
947 bounds = GC_MALLOC (sizeof (MonoArrayBounds) * array_class->rank);
949 bounds = g_malloc0 (sizeof (MonoArrayBounds) * array_class->rank);
951 for (i = 0; i < array_class->rank; ++i) {
952 bounds [i].length = lengths [i];
957 for (i = 0; i < array_class->rank; ++i)
958 bounds [i].lower_bound = lower_bounds [i];
963 * Following three lines almost taken from mono_object_new ():
964 * they need to be kept in sync.
966 o = mono_object_allocate (sizeof (MonoArray) + byte_len);
969 o->vtable = mono_class_vtable (domain, array_class);
971 array = (MonoArray*)o;
973 array->bounds = bounds;
974 array->max_length = len;
981 * @domain: domain where the object is created
982 * @eclass: element class
983 * @n: number of array elements
985 * This routine creates a new szarray with @n elements of type @eclass.
988 mono_array_new (MonoDomain *domain, MonoClass *eclass, guint32 n)
992 ac = mono_array_class_get (&eclass->byval_arg, 1);
993 g_assert (ac != NULL);
995 return mono_array_new_specific (mono_class_vtable (domain, ac), n);
999 * mono_array_new_specific:
1000 * @vtable: a vtable in the appropriate domain for an initialized class
1001 * @n: number of array elements
1003 * This routine is a fast alternative to mono_array_new() for code which
1004 * can be sure about the domain it operates in.
1007 mono_array_new_specific (MonoVTable *vtable, guint32 n)
1013 byte_len = n * mono_array_element_size (vtable->klass);
1014 #if CREATION_SPEEDUP
1015 if (vtable->klass->element_class->byval_arg.type >= MONO_TYPE_BOOLEAN && vtable->klass->element_class->byval_arg.type <= MONO_TYPE_R4) {
1016 o = GC_MALLOC_ATOMIC (sizeof (MonoArray) + byte_len);
1017 o->synchronisation = 0;
1018 memset (((MonoArray*)o)->vector, 0, byte_len);
1020 o = mono_object_allocate (sizeof (MonoArray) + byte_len);
1023 o = mono_object_allocate (sizeof (MonoArray) + byte_len);
1029 ao = (MonoArray *)o;
1037 * mono_string_new_utf16:
1038 * @text: a pointer to an utf16 string
1039 * @len: the length of the string
1041 * Returns: A newly created string object which contains @text.
1044 mono_string_new_utf16 (MonoDomain *domain, const guint16 *text, gint32 len)
1048 s = mono_string_new_size (domain, len);
1049 g_assert (s != NULL);
1051 memcpy (mono_string_chars (s), text, len * 2);
1057 * mono_string_new_size:
1058 * @text: a pointer to an utf16 string
1059 * @len: the length of the string
1061 * Returns: A newly created string object of @len
1064 mono_string_new_size (MonoDomain *domain, gint32 len)
1068 #if CREATION_SPEEDUP
1069 s = GC_MALLOC_ATOMIC (sizeof (MonoString) + ((len + 1) * 2));
1070 s->object.synchronisation = 0;
1071 mono_string_chars (s) [len] = 0;
1073 s = (MonoString*)mono_object_allocate (sizeof (MonoString) + ((len + 1) * 2));
1078 s->object.vtable = mono_class_vtable (domain, mono_defaults.string_class);
1085 * mono_string_new_len:
1086 * @text: a pointer to an utf8 string
1087 * @length: number of bytes in @text to consider
1089 * Returns: A newly created string object which contains @text.
1092 mono_string_new_len (MonoDomain *domain, const char *text, guint length)
1094 GError *error = NULL;
1095 MonoString *o = NULL;
1097 glong items_written;
1100 ut = g_utf8_to_utf16 (text, length, NULL, &items_written, &error);
1103 o = mono_string_new_utf16 (domain, ut, items_written);
1105 g_error_free (error);
1114 * @text: a pointer to an utf8 string
1116 * Returns: A newly created string object which contains @text.
1119 mono_string_new (MonoDomain *domain, const char *text)
1121 GError *error = NULL;
1122 MonoString *o = NULL;
1124 glong items_written;
1129 ut = g_utf8_to_utf16 (text, l, NULL, &items_written, &error);
1132 o = mono_string_new_utf16 (domain, ut, items_written);
1134 g_error_free (error);
1142 * mono_string_new_wrapper:
1143 * @text: pointer to utf8 characters.
1145 * Helper function to create a string object from @text in the current domain.
1148 mono_string_new_wrapper (const char *text)
1150 MonoDomain *domain = mono_domain_get ();
1153 return mono_string_new (domain, text);
1160 * @class: the class of the value
1161 * @value: a pointer to the unboxed data
1163 * Returns: A newly created object which contains @value.
1166 mono_value_box (MonoDomain *domain, MonoClass *class, gpointer value)
1171 g_assert (class->valuetype);
1173 size = mono_class_instance_size (class);
1174 res = mono_object_allocate (size);
1175 res->vtable = mono_class_vtable (domain, class);
1177 size = size - sizeof (MonoObject);
1179 #if NO_UNALIGNED_ACCESS
1180 memcpy ((char *)res + sizeof (MonoObject), value, size);
1184 *((guint8 *) res + sizeof (MonoObject)) = *(guint8 *) value;
1187 *(guint16 *)((guint8 *) res + sizeof (MonoObject)) = *(guint16 *) value;
1190 *(guint32 *)((guint8 *) res + sizeof (MonoObject)) = *(guint32 *) value;
1193 *(guint64 *)((guint8 *) res + sizeof (MonoObject)) = *(guint64 *) value;
1196 memcpy ((char *)res + sizeof (MonoObject), value, size);
1199 if (class->has_finalize)
1200 mono_object_register_finalizer (res);
1205 * mono_object_isinst:
1207 * @klass: a pointer to a class
1209 * Returns: @obj if @obj is derived from @klass
1212 mono_object_isinst (MonoObject *obj, MonoClass *klass)
1224 mono_class_init (klass);
1226 if (klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
1227 if ((klass->interface_id <= oklass->max_interface_id) &&
1228 vt->interface_offsets [klass->interface_id])
1231 if (oklass == mono_defaults.transparent_proxy_class) {
1232 /* fixme: add check for IRemotingTypeInfo */
1233 oklass = ((MonoTransparentProxy *)obj)->klass;
1236 if (oklass->rank == klass->rank &&
1237 (oklass->cast_class->baseval - klass->cast_class->baseval) <=
1238 klass->cast_class->diffval)
1241 } else if ((oklass->baseval - klass->baseval) <= klass->diffval)
1249 mono_string_is_interned_lookup (MonoString *str, int insert)
1251 MonoGHashTable *ldstr_table;
1254 char *ins = g_malloc (4 + str->length * 2);
1258 /* Encode the length */
1260 mono_metadata_encode_value (2 * str->length, p, &p);
1263 mono_metadata_encode_value (bloblen + 2 * str->length, p, &p);
1264 bloblen = (p - ins) + 2 * str->length;
1266 * ins is stored in the hash table as a key and needs to have the same
1267 * representation as in the metadata: we swap the character bytes on big
1270 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
1273 char *p2 = mono_string_chars (str);
1274 for (i = 0; i < str->length; ++i) {
1281 memcpy (p, mono_string_chars (str), str->length * 2);
1283 domain = ((MonoObject *)str)->vtable->domain;
1284 ldstr_table = domain->ldstr_table;
1285 mono_domain_lock (domain);
1286 if ((res = mono_g_hash_table_lookup (ldstr_table, ins))) {
1287 mono_domain_unlock (domain);
1292 mono_g_hash_table_insert (ldstr_table, ins, str);
1293 mono_domain_unlock (domain);
1296 mono_domain_unlock (domain);
1302 mono_string_is_interned (MonoString *o)
1304 return mono_string_is_interned_lookup (o, FALSE);
1308 mono_string_intern (MonoString *str)
1310 return mono_string_is_interned_lookup (str, TRUE);
1315 * @domain: the domain where the string will be used.
1316 * @image: a metadata context
1317 * @idx: index into the user string table.
1319 * Implementation for the ldstr opcode.
1322 mono_ldstr (MonoDomain *domain, MonoImage *image, guint32 idx)
1324 const char *str, *sig;
1328 sig = str = mono_metadata_user_string (image, idx);
1330 mono_domain_lock (domain);
1331 if ((o = mono_g_hash_table_lookup (domain->ldstr_table, sig))) {
1332 mono_domain_unlock (domain);
1336 len2 = mono_metadata_decode_blob_size (str, &str);
1339 o = mono_string_new_utf16 (domain, (guint16*)str, len2);
1340 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
1343 guint16 *p2 = (guint16*)mono_string_chars (o);
1344 for (i = 0; i < len2; ++i) {
1345 *p2 = GUINT16_FROM_LE (*p2);
1350 mono_g_hash_table_insert (domain->ldstr_table, (gpointer)sig, o);
1351 mono_domain_unlock (domain);
1357 * mono_string_to_utf8:
1358 * @s: a System.String
1360 * Return the UTF8 representation for @s.
1361 * the resulting buffer nedds to be freed with g_free().
1364 mono_string_to_utf8 (MonoString *s)
1367 GError *error = NULL;
1373 return g_strdup ("");
1375 as = g_utf16_to_utf8 (mono_string_chars (s), s->length, NULL, NULL, &error);
1377 g_warning (error->message);
1383 * mono_string_to_utf16:
1386 * Return an null-terminated array of the utf-16 chars
1387 * contained in @s. The result must be freed with g_free().
1388 * This is a temporary helper until our string implementation
1389 * is reworked to always include the null terminating char.
1392 mono_string_to_utf16 (MonoString *s)
1399 as = g_malloc ((s->length * 2) + 2);
1400 as [(s->length * 2)] = '\0';
1401 as [(s->length * 2) + 1] = '\0';
1404 return (gunichar2 *)(as);
1407 memcpy (as, mono_string_chars(s), s->length * 2);
1408 return (gunichar2 *)(as);
1412 default_ex_handler (MonoException *ex)
1414 MonoObject *o = (MonoObject*)ex;
1415 g_error ("Exception %s.%s raised in C code", o->vtable->klass->name_space, o->vtable->klass->name);
1418 static MonoExceptionFunc ex_handler = default_ex_handler;
1421 mono_install_handler (MonoExceptionFunc func)
1423 ex_handler = func? func: default_ex_handler;
1427 * mono_raise_exception:
1428 * @ex: exception object
1430 * Signal the runtime that the exception @ex has been raised in unmanaged code.
1433 mono_raise_exception (MonoException *ex)
1439 mono_wait_handle_new (MonoDomain *domain, HANDLE handle)
1441 MonoWaitHandle *res;
1443 res = (MonoWaitHandle *)mono_object_new (domain, mono_defaults.waithandle_class);
1445 res->handle = handle;
1451 mono_async_result_new (MonoDomain *domain, HANDLE handle, MonoObject *state, gpointer data)
1453 MonoAsyncResult *res;
1455 res = (MonoAsyncResult *)mono_object_new (domain, mono_defaults.asyncresult_class);
1458 res->async_state = state;
1459 res->handle = (MonoObject *)mono_wait_handle_new (domain, handle);
1460 res->sync_completed = FALSE;
1461 res->completed = FALSE;
1467 mono_message_init (MonoDomain *domain,
1468 MonoMethodMessage *this,
1469 MonoReflectionMethod *method,
1470 MonoArray *out_args)
1472 MonoMethodSignature *sig = method->method->signature;
1478 this->method = method;
1480 this->args = mono_array_new (domain, mono_defaults.object_class, sig->param_count);
1481 this->arg_types = mono_array_new (domain, mono_defaults.byte_class, sig->param_count);
1483 names = g_new (char *, sig->param_count);
1484 mono_method_get_param_names (method->method, (const char **) names);
1485 this->names = mono_array_new (domain, mono_defaults.string_class, sig->param_count);
1487 for (i = 0; i < sig->param_count; i++) {
1488 name = mono_string_new (domain, names [i]);
1489 mono_array_set (this->names, gpointer, i, name);
1494 for (i = 0, j = 0; i < sig->param_count; i++) {
1496 if (sig->params [i]->byref) {
1498 gpointer arg = mono_array_get (out_args, gpointer, j);
1499 mono_array_set (this->args, gpointer, i, arg);
1503 if (sig->params [i]->attrs & PARAM_ATTRIBUTE_IN)
1509 mono_array_set (this->arg_types, guint8, i, arg_type);
1514 * mono_remoting_invoke:
1515 * @real_proxy: pointer to a RealProxy object
1516 * @msg: The MonoMethodMessage to execute
1517 * @exc: used to store exceptions
1518 * @out_args: used to store output arguments
1520 * This is used to call RealProxy::Invoke(). RealProxy::Invoke() returns an
1521 * IMessage interface and it is not trivial to extract results from there. So
1522 * we call an helper method PrivateInvoke instead of calling
1523 * RealProxy::Invoke() directly.
1525 * Returns: the result object.
1528 mono_remoting_invoke (MonoObject *real_proxy, MonoMethodMessage *msg,
1529 MonoObject **exc, MonoArray **out_args)
1531 static MonoMethod *im = NULL;
1534 /*static MonoObject *(*invoke) (gpointer, gpointer, MonoObject **, MonoArray **) = NULL;*/
1536 /* FIXME: make this domain dependent */
1541 klass = mono_defaults.real_proxy_class;
1543 for (i = 0; i < klass->method.count; ++i) {
1544 if (!strcmp ("PrivateInvoke", klass->methods [i]->name) &&
1545 klass->methods [i]->signature->param_count == 4) {
1546 im = klass->methods [i];
1554 pa [0] = real_proxy;
1559 return mono_runtime_invoke (im, NULL, pa, exc);
1563 mono_message_invoke (MonoObject *target, MonoMethodMessage *msg,
1564 MonoObject **exc, MonoArray **out_args)
1566 if (target && target->vtable->klass == mono_defaults.transparent_proxy_class) {
1568 return mono_remoting_invoke ((MonoObject *)((MonoTransparentProxy *)target)->rp,
1569 msg, exc, out_args);
1572 MonoDomain *domain = mono_domain_get ();
1573 MonoMethod *method = msg->method->method;
1574 MonoMethodSignature *sig = method->signature;
1575 int i, j, outarg_count = 0;
1577 for (i = 0; i < sig->param_count; i++) {
1578 if (sig->params [i]->byref)
1582 *out_args = mono_array_new (domain, mono_defaults.object_class, outarg_count);
1585 for (i = 0, j = 0; i < sig->param_count; i++) {
1586 if (sig->params [i]->byref) {
1588 arg = mono_array_get (msg->args, gpointer, i);
1589 mono_array_set (*out_args, gpointer, j, arg);
1594 return mono_runtime_invoke_array (method, target, msg->args, exc);
1599 mono_print_unhandled_exception (MonoObject *exc)
1601 char *message = (char *) "";
1605 gboolean free_message = FALSE;
1608 if (mono_object_isinst (exc, mono_defaults.exception_class)) {
1609 klass = exc->vtable->klass;
1611 while (klass && method == NULL) {
1612 for (i = 0; i < klass->method.count; ++i) {
1613 method = klass->methods [i];
1614 if (!strcmp ("ToString", method->name) &&
1615 method->signature->param_count == 0 &&
1616 method->flags & METHOD_ATTRIBUTE_VIRTUAL &&
1617 method->flags & METHOD_ATTRIBUTE_PUBLIC) {
1624 klass = klass->parent;
1629 str = (MonoString *) mono_runtime_invoke (method, exc, NULL, NULL);
1631 message = mono_string_to_utf8 (str);
1632 free_message = TRUE;
1637 * g_printerr ("\nUnhandled Exception: %s.%s: %s\n", exc->vtable->klass->name_space,
1638 * exc->vtable->klass->name, message);
1640 g_printerr ("\nUnhandled Exception: %s\n", message);
1647 * mono_delegate_ctor:
1648 * @this: pointer to an uninitialized delegate object
1649 * @target: target object
1650 * @addr: pointer to native code
1652 * This is used to initialize a delegate. We also insert the method_info if
1653 * we find the info with mono_jit_info_table_find().
1656 mono_delegate_ctor (MonoObject *this, MonoObject *target, gpointer addr)
1658 MonoDomain *domain = mono_domain_get ();
1659 MonoDelegate *delegate = (MonoDelegate *)this;
1660 MonoMethod *method = NULL;
1667 class = this->vtable->klass;
1669 if ((ji = mono_jit_info_table_find (domain, addr))) {
1670 method = ji->method;
1671 delegate->method_info = mono_method_get_object (domain, method, NULL);
1674 if (target && target->vtable->klass == mono_defaults.transparent_proxy_class) {
1676 method = mono_marshal_get_remoting_invoke (method);
1677 delegate->method_ptr = mono_compile_method (method);
1678 delegate->target = target;
1680 delegate->method_ptr = addr;
1681 delegate->target = target;
1686 * mono_method_call_message_new:
1688 * Translates arguments pointers into a Message.
1691 mono_method_call_message_new (MonoMethod *method, gpointer *params, MonoMethod *invoke,
1692 MonoDelegate **cb, MonoObject **state)
1694 MonoDomain *domain = mono_domain_get ();
1695 MonoMethodSignature *sig = method->signature;
1696 MonoMethodMessage *msg;
1699 msg = (MonoMethodMessage *)mono_object_new (domain, mono_defaults.mono_method_message_class);
1702 mono_message_init (domain, msg, mono_method_get_object (domain, invoke, NULL), NULL);
1703 count = sig->param_count - 2;
1705 mono_message_init (domain, msg, mono_method_get_object (domain, method, NULL), NULL);
1706 count = sig->param_count;
1709 for (i = 0; i < count; i++) {
1714 if (sig->params [i]->byref)
1715 vpos = *((gpointer *)params [i]);
1719 type = sig->params [i]->type;
1720 class = mono_class_from_mono_type (sig->params [i]);
1722 if (class->valuetype)
1723 arg = mono_value_box (domain, class, vpos);
1725 arg = *((MonoObject **)vpos);
1727 mono_array_set (msg->args, gpointer, i, arg);
1731 *cb = *((MonoDelegate **)params [i]);
1733 *state = *((MonoObject **)params [i]);
1740 * mono_method_return_message_restore:
1742 * Restore results from message based processing back to arguments pointers
1745 mono_method_return_message_restore (MonoMethod *method, gpointer *params, MonoArray *out_args)
1747 MonoMethodSignature *sig = method->signature;
1748 int i, j, type, size;
1750 for (i = 0, j = 0; i < sig->param_count; i++) {
1751 MonoType *pt = sig->params [i];
1753 size = mono_type_stack_size (pt, NULL);
1756 char *arg = mono_array_get (out_args, gpointer, j);
1760 case MONO_TYPE_VOID:
1761 g_assert_not_reached ();
1765 case MONO_TYPE_BOOLEAN:
1768 case MONO_TYPE_CHAR:
1775 case MONO_TYPE_VALUETYPE: {
1776 memcpy (*((gpointer *)params [i]), arg + sizeof (MonoObject), size);
1779 case MONO_TYPE_STRING:
1780 case MONO_TYPE_CLASS:
1781 case MONO_TYPE_ARRAY:
1782 case MONO_TYPE_SZARRAY:
1783 *((MonoObject **)params [i]) = (MonoObject *)arg;
1786 g_assert_not_reached ();
1795 * mono_load_remote_field:
1796 * @this: pointer to an object
1797 * @klass: klass of the object containing @field
1798 * @field: the field to load
1799 * @res: a storage to store the result
1801 * This method is called by the runtime on attempts to load fields of
1802 * transparent proxy objects. @this points to such TP, @klass is the class of
1803 * the object containing @field. @res is a storage location which can be
1804 * used to store the result.
1806 * Returns: an address pointing to the value of field.
1809 mono_load_remote_field (MonoObject *this, MonoClass *klass, MonoClassField *field, gpointer *res)
1811 static MonoMethod *getter = NULL;
1812 MonoDomain *domain = mono_domain_get ();
1813 MonoClass *field_class;
1814 MonoMethodMessage *msg;
1815 MonoArray *out_args;
1819 g_assert (this->vtable->klass == mono_defaults.transparent_proxy_class);
1827 for (i = 0; i < mono_defaults.object_class->method.count; ++i) {
1828 MonoMethod *cm = mono_defaults.object_class->methods [i];
1830 if (!strcmp (cm->name, "FieldGetter")) {
1838 field_class = mono_class_from_mono_type (field->type);
1840 msg = (MonoMethodMessage *)mono_object_new (domain, mono_defaults.mono_method_message_class);
1841 out_args = mono_array_new (domain, mono_defaults.object_class, 1);
1842 mono_message_init (domain, msg, mono_method_get_object (domain, getter, NULL), out_args);
1844 mono_array_set (msg->args, gpointer, 0, mono_string_new (domain, klass->name));
1845 mono_array_set (msg->args, gpointer, 1, mono_string_new (domain, field->name));
1847 mono_remoting_invoke ((MonoObject *)((MonoTransparentProxy *)this)->rp, msg, &exc, &out_args);
1849 *res = mono_array_get (out_args, MonoObject *, 0);
1851 if (field_class->valuetype) {
1852 return ((char *)*res) + sizeof (MonoObject);
1858 * mono_store_remote_field:
1859 * @this: pointer to an object
1860 * @klass: klass of the object containing @field
1861 * @field: the field to load
1862 * @val: the value/object to store
1864 * This method is called by the runtime on attempts to store fields of
1865 * transparent proxy objects. @this points to such TP, @klass is the class of
1866 * the object containing @field. @val is the new value to store in @field.
1869 mono_store_remote_field (MonoObject *this, MonoClass *klass, MonoClassField *field, gpointer val)
1871 static MonoMethod *setter = NULL;
1872 MonoDomain *domain = mono_domain_get ();
1873 MonoClass *field_class;
1874 MonoMethodMessage *msg;
1875 MonoArray *out_args;
1879 g_assert (this->vtable->klass == mono_defaults.transparent_proxy_class);
1884 for (i = 0; i < mono_defaults.object_class->method.count; ++i) {
1885 MonoMethod *cm = mono_defaults.object_class->methods [i];
1887 if (!strcmp (cm->name, "FieldSetter")) {
1895 field_class = mono_class_from_mono_type (field->type);
1897 if (field_class->valuetype)
1898 arg = mono_value_box (domain, field_class, val);
1900 arg = *((MonoObject **)val);
1903 msg = (MonoMethodMessage *)mono_object_new (domain, mono_defaults.mono_method_message_class);
1904 mono_message_init (domain, msg, mono_method_get_object (domain, setter, NULL), NULL);
1906 mono_array_set (msg->args, gpointer, 0, mono_string_new (domain, klass->name));
1907 mono_array_set (msg->args, gpointer, 1, mono_string_new (domain, field->name));
1908 mono_array_set (msg->args, gpointer, 2, arg);
1910 mono_remoting_invoke ((MonoObject *)((MonoTransparentProxy *)this)->rp, msg, &exc, &out_args);