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"
26 #include <mono/os/gc_wrapper.h>
29 * enable to get a good speedup: we still need to figure out
30 * how the sync structure is freed.
32 #define CREATION_SPEEDUP 0
35 mono_runtime_object_init (MonoObject *this)
38 MonoMethod *method = NULL;
39 MonoClass *klass = this->vtable->klass;
41 for (i = 0; i < klass->method.count; ++i) {
42 if (!strcmp (".ctor", klass->methods [i]->name) &&
43 klass->methods [i]->signature->param_count == 0) {
44 method = klass->methods [i];
51 mono_runtime_invoke (method, this, NULL, NULL);
56 * @klass: klass that needs to be initialized
58 * This routine calls the class constructor for @class.
61 mono_runtime_class_init (MonoClass *klass)
65 for (i = 0; i < klass->method.count; ++i) {
66 MonoMethod *method = klass->methods [i];
67 if ((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
68 (strcmp (".cctor", method->name) == 0)) {
69 mono_runtime_invoke (method, NULL, NULL, NULL);
74 /* No class constructor found */
78 default_trampoline (MonoMethod *method)
84 default_remoting_trampoline (MonoMethod *method)
86 g_error ("remoting not installed");
90 static MonoTrampoline arch_create_jit_trampoline = default_trampoline;
91 static MonoTrampoline arch_create_remoting_trampoline = default_remoting_trampoline;
94 mono_install_trampoline (MonoTrampoline func)
96 arch_create_jit_trampoline = func? func: default_trampoline;
100 mono_install_remoting_trampoline (MonoTrampoline func)
102 arch_create_remoting_trampoline = func? func: default_remoting_trampoline;
105 static MonoCompileFunc default_mono_compile_method = NULL;
108 mono_install_compile_method (MonoCompileFunc func)
110 default_mono_compile_method = func;
114 mono_compile_method (MonoMethod *method)
116 if (!default_mono_compile_method) {
117 g_error ("compile method called on uninitialized runtime");
120 return default_mono_compile_method (method);
124 #if 0 && HAVE_BOEHM_GC
126 vtable_finalizer (void *obj, void *data) {
127 g_print ("%s finalized (%p)\n", (char*)data, obj);
133 * @domain: the application domain
134 * @class: the class to initialize
136 * VTables are domain specific because we create domain specific code, and
137 * they contain the domain specific static class data.
140 mono_class_vtable (MonoDomain *domain, MonoClass *class)
144 MonoClassField *field;
146 guint32 cols [MONO_CONSTANT_SIZE];
153 vt = class->cached_vtable;
154 if (vt && vt->domain == domain)
157 /* can interfaces have static fields? */
158 if (class->flags & TYPE_ATTRIBUTE_INTERFACE)
159 g_assert_not_reached ();
161 mono_domain_lock (domain);
162 if ((vt = mono_g_hash_table_lookup (domain->class_vtable_hash, class))) {
163 mono_domain_unlock (domain);
168 mono_class_init (class);
170 mono_stats.used_class_count++;
171 mono_stats.class_vtable_size += sizeof (MonoVTable) + class->vtable_size * sizeof (gpointer);
173 vt = mono_mempool_alloc0 (domain->mp, sizeof (MonoVTable) +
174 class->vtable_size * sizeof (gpointer));
178 if (class->class_size) {
180 vt->data = GC_malloc (class->class_size + 8);
181 /*vt->data = GC_debug_malloc (class->class_size + 8, class->name, 2);*/
182 /*GC_register_finalizer (vt->data, vtable_finalizer, class->name, NULL, NULL);*/
183 mono_g_hash_table_insert (domain->static_data_hash, class, vt->data);
185 vt->data = mono_mempool_alloc0 (domain->mp, class->class_size + 8);
188 mono_stats.class_static_data_size += class->class_size + 8;
191 for (i = class->field.first; i < class->field.last; ++i) {
192 field = &class->fields [i - class->field.first];
193 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
195 if ((field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA)) {
196 MonoClass *fklass = mono_class_from_mono_type (field->type);
197 t = (char*)vt->data + field->offset;
198 g_assert (fklass->valuetype);
199 memcpy (t, field->data, mono_class_value_size (fklass, NULL));
202 if (!(field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT))
204 cindex = mono_metadata_get_constant_index (class->image, MONO_TOKEN_FIELD_DEF | (i + 1));
206 g_warning ("constant for field %s not found", field->name);
209 mono_metadata_decode_row (&class->image->tables [MONO_TABLE_CONSTANT], cindex - 1, cols, MONO_CONSTANT_SIZE);
210 p = mono_metadata_blob_heap (class->image, cols [MONO_CONSTANT_VALUE]);
211 len = mono_metadata_decode_blob_size (p, &p);
212 t = (char*)vt->data + field->offset;
213 /* should we check that the type matches? */
214 switch (cols [MONO_CONSTANT_TYPE]) {
215 case MONO_TYPE_BOOLEAN:
223 guint16 *val = (guint16*)t;
229 guint32 *val = (guint32*)t;
235 guint64 *val = (guint64*)t;
240 float *val = (float*)t;
245 double *val = (double*)t;
249 case MONO_TYPE_STRING: {
250 gpointer *val = (gpointer*)t;
251 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
252 gunichar2 *copy = g_malloc (len);
254 for (j = 0; j < len/2; j++) {
255 copy [j] = read16 (p);
258 *val = mono_string_new_utf16 (domain, copy, len/2);
261 *val = mono_string_new_utf16 (domain, (const guint16*)p, len/2);
265 case MONO_TYPE_CLASS:
266 /* nothing to do, we malloc0 the data and the value can be 0 only */
269 g_warning ("type 0x%02x should not be in constant table", cols [MONO_CONSTANT_TYPE]);
273 vt->max_interface_id = class->max_interface_id;
275 vt->interface_offsets = mono_mempool_alloc0 (domain->mp,
276 sizeof (gpointer) * (class->max_interface_id + 1));
278 /* initialize interface offsets */
279 for (k = class; k ; k = k->parent) {
280 for (i = 0; i < k->interface_count; i++) {
282 MonoClass *ic = k->interfaces [i];
283 slot = class->interface_offsets [ic->interface_id];
284 vt->interface_offsets [ic->interface_id] = &vt->vtable [slot];
288 /* initialize vtable */
289 for (i = 0; i < class->vtable_size; ++i) {
292 if ((cm = class->vtable [i]))
293 vt->vtable [i] = arch_create_jit_trampoline (cm);
296 mono_g_hash_table_insert (domain->class_vtable_hash, class, vt);
297 if (!class->cached_vtable)
298 class->cached_vtable = vt;
300 mono_domain_unlock (domain);
302 /* make sure the the parent is initialized */
304 mono_class_vtable (domain, class->parent);
306 mono_runtime_class_init (class);
312 * mono_class_proxy_vtable:
313 * @domain: the application domain
314 * @class: the class to proxy
316 * Creates a vtable for transparent proxies. It is basically
317 * a copy of the real vtable of @class, but all function pointers invoke
318 * the remoting functions, and vtable->klass points to the
319 * transparent proxy class, and not to @class.
322 mono_class_proxy_vtable (MonoDomain *domain, MonoClass *class)
324 MonoVTable *vt, *pvt;
327 if ((pvt = mono_g_hash_table_lookup (domain->proxy_vtable_hash, class)))
330 vt = mono_class_vtable (domain, class);
331 vtsize = sizeof (MonoVTable) + class->vtable_size * sizeof (gpointer);
333 mono_stats.class_vtable_size += vtsize;
335 pvt = mono_mempool_alloc (domain->mp, vtsize);
336 memcpy (pvt, vt, vtsize);
338 pvt->klass = mono_defaults.transparent_proxy_class;
340 /* initialize vtable */
341 for (i = 0; i < class->vtable_size; ++i) {
344 if ((cm = class->vtable [i]))
345 pvt->vtable [i] = arch_create_remoting_trampoline (cm);
348 mono_g_hash_table_insert (domain->proxy_vtable_hash, class, pvt);
354 * Retrieve the MonoMethod that would to be called on obj if obj is passed as
355 * the instance of a callvirt of method.
358 mono_object_get_virtual_method (MonoObject *obj, MonoMethod *method) {
364 if ((method->flags & METHOD_ATTRIBUTE_FINAL) || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL))
367 klass = mono_object_class (obj);
368 if (klass == mono_defaults.transparent_proxy_class) {
369 klass = ((MonoTransparentProxy *)obj)->klass;
374 vtable = klass->vtable;
376 if (method->klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
377 res = vtable [method->klass->interface_id + method->slot];
379 res = vtable [method->slot];
384 return mono_marshal_get_remoting_invoke (res);
390 dummy_mono_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
392 g_error ("runtime invoke called on uninitialized runtime");
396 static MonoInvokeFunc default_mono_runtime_invoke = dummy_mono_runtime_invoke;
399 mono_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
401 return default_mono_runtime_invoke (method, obj, params, exc);
405 set_value (MonoType *type, void *dest, void *value, int deref_pointer) {
408 gpointer *p = (gpointer*)dest;
415 case MONO_TYPE_BOOLEAN:
418 guint8 *p = (guint8*)dest;
419 *p = *(guint8*)value;
424 case MONO_TYPE_CHAR: {
425 guint16 *p = (guint16*)dest;
426 *p = *(guint16*)value;
429 #if SIZEOF_VOID_P == 4
435 gint32 *p = (gint32*)dest;
436 *p = *(gint32*)value;
439 #if SIZEOF_VOID_P == 8
445 gint64 *p = (gint64*)dest;
446 *p = *(gint64*)value;
450 float *p = (float*)dest;
455 double *p = (double*)dest;
456 *p = *(double*)value;
459 case MONO_TYPE_STRING:
460 case MONO_TYPE_SZARRAY:
461 case MONO_TYPE_CLASS:
462 case MONO_TYPE_OBJECT:
463 case MONO_TYPE_ARRAY:
464 case MONO_TYPE_PTR: {
465 gpointer *p = (gpointer*)dest;
466 *p = deref_pointer? *(gpointer*)value: value;
469 case MONO_TYPE_VALUETYPE:
470 if (type->data.klass->enumtype) {
471 t = type->data.klass->enum_basetype->type;
475 size = mono_class_value_size (type->data.klass, NULL);
476 memcpy (dest, value, size);
480 g_warning ("got type %x", type->type);
481 g_assert_not_reached ();
486 mono_field_set_value (MonoObject *obj, MonoClassField *field, void *value)
490 g_return_if_fail (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC));
492 dest = (char*)obj + field->offset;
493 set_value (field->type, dest, value, FALSE);
497 mono_field_static_set_value (MonoVTable *vt, MonoClassField *field, void *value)
501 g_return_if_fail (field->type->attrs & FIELD_ATTRIBUTE_STATIC);
503 dest = (char*)vt->data + field->offset;
504 set_value (field->type, dest, value, FALSE);
508 mono_field_get_value (MonoObject *obj, MonoClassField *field, void *value)
512 g_return_if_fail (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC));
514 src = (char*)obj + field->offset;
515 set_value (field->type, value, src, TRUE);
519 mono_field_static_get_value (MonoVTable *vt, MonoClassField *field, void *value)
523 g_return_if_fail (field->type->attrs & FIELD_ATTRIBUTE_STATIC);
525 src = (char*)vt->data + field->offset;
526 set_value (field->type, value, src, TRUE);
530 mono_property_set_value (MonoProperty *prop, void *obj, void **params, MonoObject **exc)
532 default_mono_runtime_invoke (prop->set, obj, params, exc);
536 mono_property_get_value (MonoProperty *prop, void *obj, void **params, MonoObject **exc)
538 return default_mono_runtime_invoke (prop->get, obj, params, exc);
543 mono_get_delegate_invoke (MonoClass *klass)
550 for (i = 0; i < klass->method.count; ++i) {
551 if (klass->methods [i]->name[0] == 'I' &&
552 !strcmp ("Invoke", klass->methods [i]->name)) {
553 im = klass->methods [i];
563 mono_runtime_delegate_invoke (MonoObject *delegate, void **params, MonoObject **exc)
567 im = mono_get_delegate_invoke (delegate->vtable->klass);
570 return mono_runtime_invoke (im, delegate, params, exc);
573 static MonoArray* main_args;
576 mono_runtime_get_main_args (void)
581 MonoMethod *mono_start_method = NULL;
584 * Execute a standard Main() method (argc/argv contains the
585 * executable name). This method also sets the command line argument value
586 * needed by System.Environment.
589 mono_runtime_run_main (MonoMethod *method, int argc, char* argv[],
593 MonoArray *args = NULL;
594 MonoDomain *domain = mono_domain_get ();
596 main_args = (MonoArray*)mono_array_new (domain, mono_defaults.string_class, argc);
597 for (i = 0; i < argc; ++i) {
598 MonoString *arg = mono_string_new (domain, argv [i]);
599 mono_array_set (main_args, gpointer, i, arg);
603 if (method->signature->param_count) {
604 args = (MonoArray*)mono_array_new (domain, mono_defaults.string_class, argc);
605 for (i = 0; i < argc; ++i) {
606 MonoString *arg = mono_string_new (domain, argv [i]);
607 mono_array_set (args, gpointer, i, arg);
610 args = (MonoArray*)mono_array_new (domain, mono_defaults.string_class, 0);
613 mono_assembly_set_main (method->klass->image->assembly);
615 mono_start_method = mono_marshal_get_runtime_invoke (method);
617 return mono_runtime_exec_main (method, args, exc);
621 * We call this function when we dectect an unhandled exception. It invokes the
622 * UnhandledException event in AppDomain or print a warning to the console
625 mono_unhandled_exception (MonoObject *exc)
627 MonoDomain *domain = mono_domain_get ();
628 MonoClassField *field;
629 MonoObject *delegate;
631 field=mono_class_get_field_from_name(mono_defaults.appdomain_class,
632 "UnhandledException");
635 if (exc->vtable->klass != mono_defaults.threadabortexception_class) {
636 delegate = *(MonoObject **)(((char *)domain->domain) + field->offset);
639 mono_print_unhandled_exception (exc);
641 MonoObject *e = NULL;
644 /* fixme: pass useful arguments */
647 mono_runtime_delegate_invoke (delegate, pa, &e);
650 g_warning ("exception inside UnhandledException handler!");
656 * Execute a standard Main() method (args doesn't contain the
660 mono_runtime_exec_main (MonoMethod *method, MonoArray *args, MonoObject **exc)
670 domain = mono_object_domain (args);
671 if (!domain->entry_assembly) {
672 domain->entry_assembly = method->klass->image->assembly;
673 ves_icall_System_AppDomainSetup_InitAppDomainSetup (domain->setup);
676 /* FIXME: check signature of method */
677 if (method->signature->ret->type == MONO_TYPE_I4) {
679 res = mono_runtime_invoke (method, NULL, pa, exc);
681 rval = *(guint32 *)((char *)res + sizeof (MonoObject));
685 mono_runtime_invoke (method, NULL, pa, exc);
696 mono_install_runtime_invoke (MonoInvokeFunc func)
698 default_mono_runtime_invoke = func ? func: dummy_mono_runtime_invoke;
702 mono_runtime_invoke_array (MonoMethod *method, void *obj, MonoArray *params,
705 MonoMethodSignature *sig = method->signature;
709 if (NULL != params) {
710 pa = alloca (sizeof (gpointer) * mono_array_length (params));
711 for (i = 0; i < mono_array_length (params); i++) {
712 if (sig->params [i]->byref) {
716 switch (sig->params [i]->type) {
719 case MONO_TYPE_BOOLEAN:
731 case MONO_TYPE_VALUETYPE:
732 pa [i] = (char *)(((gpointer *)params->vector)[i]) + sizeof (MonoObject);
734 case MONO_TYPE_STRING:
735 case MONO_TYPE_OBJECT:
736 case MONO_TYPE_CLASS:
737 case MONO_TYPE_ARRAY:
738 case MONO_TYPE_SZARRAY:
739 pa [i] = (char *)(((gpointer *)params->vector)[i]);
742 g_error ("type 0x%x not handled in ves_icall_InternalInvoke", sig->params [i]->type);
747 if (!strcmp (method->name, ".ctor") && method->klass != mono_defaults.string_class) {
749 obj = mono_object_new (mono_domain_get (), method->klass);
750 mono_runtime_invoke (method, obj, pa, exc);
753 return mono_runtime_invoke (method, obj, pa, exc);
757 * mono_object_allocate:
758 * @size: number of bytes to allocate
760 * This is a very simplistic routine until we have our GC-aware
763 * Returns: an allocated object of size @size, or NULL on failure.
766 mono_object_allocate (size_t size)
769 /* if this is changed to GC_debug_malloc(), we need to change also metadata/gc.c */
770 void *o = GC_malloc (size);
772 void *o = calloc (1, size);
775 mono_stats.new_object_count++;
783 * Frees the memory used by the object. Debugging purposes
784 * only, as we will have our GC system.
787 mono_object_free (MonoObject *o)
790 g_error ("mono_object_free called with boehm gc.");
792 MonoClass *c = o->vtable->klass;
794 memset (o, 0, c->instance_size);
801 * @klass: the class of the object that we want to create
803 * Returns: A newly created object whose definition is
804 * looked up using @klass
807 mono_object_new (MonoDomain *domain, MonoClass *klass)
809 return mono_object_new_specific (mono_class_vtable (domain, klass));
813 * mono_object_new_specific:
814 * @vtable: the vtable of the object that we want to create
816 * Returns: A newly created object with class and domain specified
820 mono_object_new_specific (MonoVTable *vtable)
824 o = mono_object_allocate (vtable->klass->instance_size);
826 if (vtable->klass->has_finalize)
827 mono_object_register_finalizer (o);
833 * mono_object_new_from_token:
834 * @image: Context where the type_token is hosted
835 * @token: a token of the type that we want to create
837 * Returns: A newly created object whose definition is
838 * looked up using @token in the @image image
841 mono_object_new_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
845 class = mono_class_get (image, token);
847 return mono_object_new (domain, class);
853 * @obj: the object to clone
855 * Returns: A newly created object who is a shallow copy of @obj
858 mono_object_clone (MonoObject *obj)
863 size = obj->vtable->klass->instance_size;
864 o = mono_object_allocate (size);
866 memcpy (o, obj, size);
868 if (obj->vtable->klass->has_finalize)
869 mono_object_register_finalizer (o);
875 * @array: the array to clone
877 * Returns: A newly created array who is a shallow copy of @array
880 mono_array_clone (MonoArray *array)
885 MonoClass *klass = array->obj.vtable->klass;
887 if (array->bounds == NULL) {
888 size = mono_array_length (array);
889 o = mono_array_new_full (((MonoObject *)array)->vtable->domain,
892 size *= mono_array_element_size (klass);
893 memcpy (o, array, sizeof (MonoArray) + size);
898 sizes = alloca (klass->rank * sizeof(guint32) * 2);
899 size = mono_array_element_size (klass);
900 for (i = 0; i < klass->rank; ++i) {
901 sizes [i] = array->bounds [i].length;
902 size *= array->bounds [i].length;
903 sizes [i + klass->rank] = array->bounds [i].lower_bound;
905 o = mono_array_new_full (((MonoObject *)array)->vtable->domain,
906 klass, sizes, sizes + klass->rank);
907 memcpy (o, array, sizeof(MonoArray) + size);
913 * mono_array_new_full:
914 * @domain: domain where the object is created
915 * @array_class: array class
916 * @lengths: lengths for each dimension in the array
917 * @lower_bounds: lower bounds for each dimension in the array (may be NULL)
919 * This routine creates a new array objects with the given dimensions,
920 * lower bounds and type.
923 mono_array_new_full (MonoDomain *domain, MonoClass *array_class,
924 guint32 *lengths, guint32 *lower_bounds)
926 guint32 byte_len, len;
929 MonoArrayBounds *bounds;
932 if (!array_class->inited)
933 mono_class_init (array_class);
935 byte_len = mono_array_element_size (array_class);
938 if (array_class->rank == 1 &&
939 (lower_bounds == NULL || lower_bounds [0] == 0)) {
944 bounds = GC_malloc (sizeof (MonoArrayBounds) * array_class->rank);
946 bounds = g_malloc0 (sizeof (MonoArrayBounds) * array_class->rank);
948 for (i = 0; i < array_class->rank; ++i) {
949 bounds [i].length = lengths [i];
954 for (i = 0; i < array_class->rank; ++i)
955 bounds [i].lower_bound = lower_bounds [i];
960 * Following three lines almost taken from mono_object_new ():
961 * they need to be kept in sync.
963 o = mono_object_allocate (sizeof (MonoArray) + byte_len);
966 o->vtable = mono_class_vtable (domain, array_class);
968 array = (MonoArray*)o;
970 array->bounds = bounds;
971 array->max_length = len;
978 * @domain: domain where the object is created
979 * @eclass: element class
980 * @n: number of array elements
982 * This routine creates a new szarray with @n elements of type @eclass.
985 mono_array_new (MonoDomain *domain, MonoClass *eclass, guint32 n)
989 ac = mono_array_class_get (&eclass->byval_arg, 1);
990 g_assert (ac != NULL);
992 return mono_array_new_specific (mono_class_vtable (domain, ac), n);
996 * mono_array_new_specific:
997 * @vtable: a vtable in the appropriate domain for an initialized class
998 * @n: number of array elements
1000 * This routine is a fast alternative to mono_array_new() for code which
1001 * can be sure about the domain it operates in.
1004 mono_array_new_specific (MonoVTable *vtable, guint32 n)
1010 byte_len = n * mono_array_element_size (vtable->klass);
1011 #if CREATION_SPEEDUP
1012 if (vtable->klass->element_class->byval_arg.type >= MONO_TYPE_BOOLEAN && vtable->klass->element_class->byval_arg.type <= MONO_TYPE_R4) {
1013 o = GC_malloc_atomic (sizeof (MonoArray) + byte_len);
1014 o->synchronisation = 0;
1015 memset (((MonoArray*)o)->vector, 0, byte_len);
1017 o = mono_object_allocate (sizeof (MonoArray) + byte_len);
1020 o = mono_object_allocate (sizeof (MonoArray) + byte_len);
1026 ao = (MonoArray *)o;
1034 * mono_string_new_utf16:
1035 * @text: a pointer to an utf16 string
1036 * @len: the length of the string
1038 * Returns: A newly created string object which contains @text.
1041 mono_string_new_utf16 (MonoDomain *domain, const guint16 *text, gint32 len)
1045 s = mono_string_new_size (domain, len);
1046 g_assert (s != NULL);
1048 memcpy (mono_string_chars (s), text, len * 2);
1054 * mono_string_new_size:
1055 * @text: a pointer to an utf16 string
1056 * @len: the length of the string
1058 * Returns: A newly created string object of @len
1061 mono_string_new_size (MonoDomain *domain, gint32 len)
1065 #if CREATION_SPEEDUP
1066 s = GC_malloc_atomic (sizeof (MonoString) + ((len + 1) * 2));
1067 s->object.synchronisation = 0;
1068 mono_string_chars (s) [len] = 0;
1070 s = (MonoString*)mono_object_allocate (sizeof (MonoString) + ((len + 1) * 2));
1075 s->object.vtable = mono_class_vtable (domain, mono_defaults.string_class);
1082 * mono_string_new_len:
1083 * @text: a pointer to an utf8 string
1084 * @length: number of bytes in @text to consider
1086 * Returns: A newly created string object which contains @text.
1089 mono_string_new_len (MonoDomain *domain, const char *text, guint length)
1091 GError *error = NULL;
1092 MonoString *o = NULL;
1094 glong items_written;
1097 ut = g_utf8_to_utf16 (text, length, NULL, &items_written, &error);
1100 o = mono_string_new_utf16 (domain, ut, items_written);
1102 g_error_free (error);
1111 * @text: a pointer to an utf8 string
1113 * Returns: A newly created string object which contains @text.
1116 mono_string_new (MonoDomain *domain, const char *text)
1118 GError *error = NULL;
1119 MonoString *o = NULL;
1121 glong items_written;
1126 ut = g_utf8_to_utf16 (text, l, NULL, &items_written, &error);
1129 o = mono_string_new_utf16 (domain, ut, items_written);
1131 g_error_free (error);
1139 * mono_string_new_wrapper:
1140 * @text: pointer to utf8 characters.
1142 * Helper function to create a string object from @text in the current domain.
1145 mono_string_new_wrapper (const char *text)
1147 MonoDomain *domain = mono_domain_get ();
1150 return mono_string_new (domain, text);
1157 * @class: the class of the value
1158 * @value: a pointer to the unboxed data
1160 * Returns: A newly created object which contains @value.
1163 mono_value_box (MonoDomain *domain, MonoClass *class, gpointer value)
1168 g_assert (class->valuetype);
1170 size = mono_class_instance_size (class);
1171 res = mono_object_allocate (size);
1172 res->vtable = mono_class_vtable (domain, class);
1174 size = size - sizeof (MonoObject);
1176 #if NO_UNALIGNED_ACCESS
1177 memcpy ((char *)res + sizeof (MonoObject), value, size);
1181 *((guint8 *) res + sizeof (MonoObject)) = *(guint8 *) value;
1184 *(guint16 *)((guint8 *) res + sizeof (MonoObject)) = *(guint16 *) value;
1187 *(guint32 *)((guint8 *) res + sizeof (MonoObject)) = *(guint32 *) value;
1190 *(guint64 *)((guint8 *) res + sizeof (MonoObject)) = *(guint64 *) value;
1193 memcpy ((char *)res + sizeof (MonoObject), value, size);
1196 if (class->has_finalize)
1197 mono_object_register_finalizer (res);
1202 * mono_object_isinst:
1204 * @klass: a pointer to a class
1206 * Returns: @obj if @obj is derived from @klass
1209 mono_object_isinst (MonoObject *obj, MonoClass *klass)
1221 mono_class_init (klass);
1223 if (klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
1224 if ((klass->interface_id <= oklass->max_interface_id) &&
1225 vt->interface_offsets [klass->interface_id])
1228 if (oklass == mono_defaults.transparent_proxy_class) {
1229 /* fixme: add check for IRemotingTypeInfo */
1230 oklass = ((MonoTransparentProxy *)obj)->klass;
1233 if (oklass->rank == klass->rank &&
1234 (oklass->cast_class->baseval - klass->cast_class->baseval) <=
1235 klass->cast_class->diffval)
1238 } else if ((oklass->baseval - klass->baseval) <= klass->diffval)
1246 mono_string_is_interned_lookup (MonoString *str, int insert)
1248 MonoGHashTable *ldstr_table;
1251 char *ins = g_malloc (4 + str->length * 2);
1255 /* Encode the length */
1257 mono_metadata_encode_value (2 * str->length, p, &p);
1260 mono_metadata_encode_value (bloblen + 2 * str->length, p, &p);
1261 bloblen = (p - ins) + 2 * str->length;
1263 * ins is stored in the hash table as a key and needs to have the same
1264 * representation as in the metadata: we swap the character bytes on big
1267 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
1270 char *p2 = mono_string_chars (str);
1271 for (i = 0; i < str->length; ++i) {
1278 memcpy (p, mono_string_chars (str), str->length * 2);
1280 domain = ((MonoObject *)str)->vtable->domain;
1281 ldstr_table = domain->ldstr_table;
1282 mono_domain_lock (domain);
1283 if ((res = mono_g_hash_table_lookup (ldstr_table, ins))) {
1284 mono_domain_unlock (domain);
1289 mono_g_hash_table_insert (ldstr_table, ins, str);
1290 mono_domain_unlock (domain);
1293 mono_domain_unlock (domain);
1299 mono_string_is_interned (MonoString *o)
1301 return mono_string_is_interned_lookup (o, FALSE);
1305 mono_string_intern (MonoString *str)
1307 return mono_string_is_interned_lookup (str, TRUE);
1312 * @domain: the domain where the string will be used.
1313 * @image: a metadata context
1314 * @idx: index into the user string table.
1316 * Implementation for the ldstr opcode.
1319 mono_ldstr (MonoDomain *domain, MonoImage *image, guint32 idx)
1321 const char *str, *sig;
1325 sig = str = mono_metadata_user_string (image, idx);
1327 mono_domain_lock (domain);
1328 if ((o = mono_g_hash_table_lookup (domain->ldstr_table, sig))) {
1329 mono_domain_unlock (domain);
1333 len2 = mono_metadata_decode_blob_size (str, &str);
1336 o = mono_string_new_utf16 (domain, (guint16*)str, len2);
1337 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
1340 guint16 *p2 = (guint16*)mono_string_chars (o);
1341 for (i = 0; i < len2; ++i) {
1342 *p2 = GUINT16_FROM_LE (*p2);
1347 mono_g_hash_table_insert (domain->ldstr_table, (gpointer)sig, o);
1348 mono_domain_unlock (domain);
1354 * mono_string_to_utf8:
1355 * @s: a System.String
1357 * Return the UTF8 representation for @s.
1358 * the resulting buffer nedds to be freed with g_free().
1361 mono_string_to_utf8 (MonoString *s)
1364 GError *error = NULL;
1370 return g_strdup ("");
1372 as = g_utf16_to_utf8 (mono_string_chars (s), s->length, NULL, NULL, &error);
1374 g_warning (error->message);
1380 * mono_string_to_utf16:
1383 * Return an null-terminated array of the utf-16 chars
1384 * contained in @s. The result must be freed with g_free().
1385 * This is a temporary helper until our string implementation
1386 * is reworked to always include the null terminating char.
1389 mono_string_to_utf16 (MonoString *s)
1396 as = g_malloc ((s->length * 2) + 2);
1397 as [(s->length * 2)] = '\0';
1398 as [(s->length * 2) + 1] = '\0';
1401 return (gunichar2 *)(as);
1404 memcpy (as, mono_string_chars(s), s->length * 2);
1405 return (gunichar2 *)(as);
1409 default_ex_handler (MonoException *ex)
1411 MonoObject *o = (MonoObject*)ex;
1412 g_error ("Exception %s.%s raised in C code", o->vtable->klass->name_space, o->vtable->klass->name);
1415 static MonoExceptionFunc ex_handler = default_ex_handler;
1418 mono_install_handler (MonoExceptionFunc func)
1420 ex_handler = func? func: default_ex_handler;
1424 * mono_raise_exception:
1425 * @ex: exception object
1427 * Signal the runtime that the exception @ex has been raised in unmanaged code.
1430 mono_raise_exception (MonoException *ex)
1436 mono_wait_handle_new (MonoDomain *domain, HANDLE handle)
1438 MonoWaitHandle *res;
1440 res = (MonoWaitHandle *)mono_object_new (domain, mono_defaults.waithandle_class);
1442 res->handle = handle;
1448 mono_async_result_new (MonoDomain *domain, HANDLE handle, MonoObject *state, gpointer data)
1450 MonoAsyncResult *res;
1452 res = (MonoAsyncResult *)mono_object_new (domain, mono_defaults.asyncresult_class);
1455 res->async_state = state;
1456 res->handle = (MonoObject *)mono_wait_handle_new (domain, handle);
1457 res->sync_completed = FALSE;
1458 res->completed = FALSE;
1464 mono_message_init (MonoDomain *domain,
1465 MonoMethodMessage *this,
1466 MonoReflectionMethod *method,
1467 MonoArray *out_args)
1469 MonoMethodSignature *sig = method->method->signature;
1475 this->method = method;
1477 this->args = mono_array_new (domain, mono_defaults.object_class, sig->param_count);
1478 this->arg_types = mono_array_new (domain, mono_defaults.byte_class, sig->param_count);
1480 names = g_new (char *, sig->param_count);
1481 mono_method_get_param_names (method->method, (const char **) names);
1482 this->names = mono_array_new (domain, mono_defaults.string_class, sig->param_count);
1484 for (i = 0; i < sig->param_count; i++) {
1485 name = mono_string_new (domain, names [i]);
1486 mono_array_set (this->names, gpointer, i, name);
1491 for (i = 0, j = 0; i < sig->param_count; i++) {
1493 if (sig->params [i]->byref) {
1495 gpointer arg = mono_array_get (out_args, gpointer, j);
1496 mono_array_set (this->args, gpointer, i, arg);
1500 if (sig->params [i]->attrs & PARAM_ATTRIBUTE_IN)
1506 mono_array_set (this->arg_types, guint8, i, arg_type);
1511 * mono_remoting_invoke:
1512 * @real_proxy: pointer to a RealProxy object
1513 * @msg: The MonoMethodMessage to execute
1514 * @exc: used to store exceptions
1515 * @out_args: used to store output arguments
1517 * This is used to call RealProxy::Invoke(). RealProxy::Invoke() returns an
1518 * IMessage interface and it is not trivial to extract results from there. So
1519 * we call an helper method PrivateInvoke instead of calling
1520 * RealProxy::Invoke() directly.
1522 * Returns: the result object.
1525 mono_remoting_invoke (MonoObject *real_proxy, MonoMethodMessage *msg,
1526 MonoObject **exc, MonoArray **out_args)
1528 static MonoMethod *im = NULL;
1531 /*static MonoObject *(*invoke) (gpointer, gpointer, MonoObject **, MonoArray **) = NULL;*/
1533 /* FIXME: make this domain dependent */
1538 klass = mono_defaults.real_proxy_class;
1540 for (i = 0; i < klass->method.count; ++i) {
1541 if (!strcmp ("PrivateInvoke", klass->methods [i]->name) &&
1542 klass->methods [i]->signature->param_count == 4) {
1543 im = klass->methods [i];
1551 pa [0] = real_proxy;
1556 return mono_runtime_invoke (im, NULL, pa, exc);
1560 mono_message_invoke (MonoObject *target, MonoMethodMessage *msg,
1561 MonoObject **exc, MonoArray **out_args)
1563 if (target && target->vtable->klass == mono_defaults.transparent_proxy_class) {
1565 return mono_remoting_invoke ((MonoObject *)((MonoTransparentProxy *)target)->rp,
1566 msg, exc, out_args);
1569 MonoDomain *domain = mono_domain_get ();
1570 MonoMethod *method = msg->method->method;
1571 MonoMethodSignature *sig = method->signature;
1572 int i, j, outarg_count = 0;
1574 for (i = 0; i < sig->param_count; i++) {
1575 if (sig->params [i]->byref)
1579 *out_args = mono_array_new (domain, mono_defaults.object_class, outarg_count);
1582 for (i = 0, j = 0; i < sig->param_count; i++) {
1583 if (sig->params [i]->byref) {
1585 arg = mono_array_get (msg->args, gpointer, i);
1586 mono_array_set (*out_args, gpointer, j, arg);
1591 return mono_runtime_invoke_array (method, target, msg->args, exc);
1596 mono_print_unhandled_exception (MonoObject *exc)
1598 char *message = (char *) "";
1602 gboolean free_message = FALSE;
1605 if (mono_object_isinst (exc, mono_defaults.exception_class)) {
1606 klass = exc->vtable->klass;
1608 while (klass && method == NULL) {
1609 for (i = 0; i < klass->method.count; ++i) {
1610 method = klass->methods [i];
1611 if (!strcmp ("ToString", method->name) &&
1612 method->signature->param_count == 0 &&
1613 method->flags & METHOD_ATTRIBUTE_VIRTUAL &&
1614 method->flags & METHOD_ATTRIBUTE_PUBLIC) {
1621 klass = klass->parent;
1626 str = (MonoString *) mono_runtime_invoke (method, exc, NULL, NULL);
1628 message = mono_string_to_utf8 (str);
1629 free_message = TRUE;
1634 * g_printerr ("\nUnhandled Exception: %s.%s: %s\n", exc->vtable->klass->name_space,
1635 * exc->vtable->klass->name, message);
1637 g_printerr ("\nUnhandled Exception: %s\n", message);
1644 * mono_delegate_ctor:
1645 * @this: pointer to an uninitialized delegate object
1646 * @target: target object
1647 * @addr: pointer to native code
1649 * This is used to initialize a delegate. We also insert the method_info if
1650 * we find the info with mono_jit_info_table_find().
1653 mono_delegate_ctor (MonoObject *this, MonoObject *target, gpointer addr)
1655 MonoDomain *domain = mono_domain_get ();
1656 MonoDelegate *delegate = (MonoDelegate *)this;
1657 MonoMethod *method = NULL;
1664 class = this->vtable->klass;
1666 if ((ji = mono_jit_info_table_find (domain, addr))) {
1667 method = ji->method;
1668 delegate->method_info = mono_method_get_object (domain, method, NULL);
1671 if (target && target->vtable->klass == mono_defaults.transparent_proxy_class) {
1673 method = mono_marshal_get_remoting_invoke (method);
1674 delegate->method_ptr = mono_compile_method (method);
1675 delegate->target = target;
1677 delegate->method_ptr = addr;
1678 delegate->target = target;
1683 * mono_method_call_message_new:
1685 * Translates arguments pointers into a Message.
1688 mono_method_call_message_new (MonoMethod *method, gpointer *params, MonoMethod *invoke,
1689 MonoDelegate **cb, MonoObject **state)
1691 MonoDomain *domain = mono_domain_get ();
1692 MonoMethodSignature *sig = method->signature;
1693 MonoMethodMessage *msg;
1696 msg = (MonoMethodMessage *)mono_object_new (domain, mono_defaults.mono_method_message_class);
1699 mono_message_init (domain, msg, mono_method_get_object (domain, invoke, NULL), NULL);
1700 count = sig->param_count - 2;
1702 mono_message_init (domain, msg, mono_method_get_object (domain, method, NULL), NULL);
1703 count = sig->param_count;
1706 for (i = 0; i < count; i++) {
1711 if (sig->params [i]->byref)
1712 vpos = *((gpointer *)params [i]);
1716 type = sig->params [i]->type;
1717 class = mono_class_from_mono_type (sig->params [i]);
1719 if (class->valuetype)
1720 arg = mono_value_box (domain, class, vpos);
1722 arg = *((MonoObject **)vpos);
1724 mono_array_set (msg->args, gpointer, i, arg);
1728 *cb = *((MonoDelegate **)params [i]);
1730 *state = *((MonoObject **)params [i]);
1737 * mono_method_return_message_restore:
1739 * Restore results from message based processing back to arguments pointers
1742 mono_method_return_message_restore (MonoMethod *method, gpointer *params, MonoArray *out_args)
1744 MonoMethodSignature *sig = method->signature;
1745 int i, j, type, size;
1747 for (i = 0, j = 0; i < sig->param_count; i++) {
1748 MonoType *pt = sig->params [i];
1750 size = mono_type_stack_size (pt, NULL);
1753 char *arg = mono_array_get (out_args, gpointer, j);
1757 case MONO_TYPE_VOID:
1758 g_assert_not_reached ();
1762 case MONO_TYPE_BOOLEAN:
1765 case MONO_TYPE_CHAR:
1772 case MONO_TYPE_VALUETYPE: {
1773 memcpy (*((gpointer *)params [i]), arg + sizeof (MonoObject), size);
1776 case MONO_TYPE_STRING:
1777 case MONO_TYPE_CLASS:
1778 case MONO_TYPE_ARRAY:
1779 case MONO_TYPE_SZARRAY:
1780 *((MonoObject **)params [i]) = (MonoObject *)arg;
1783 g_assert_not_reached ();
1792 * mono_load_remote_field:
1793 * @this: pointer to an object
1794 * @klass: klass of the object containing @field
1795 * @field: the field to load
1796 * @res: a storage to store the result
1798 * This method is called by the runtime on attempts to load fields of
1799 * transparent proxy objects. @this points to such TP, @klass is the class of
1800 * the object containing @field. @res is a storage location which can be
1801 * used to store the result.
1803 * Returns: an address pointing to the value of field.
1806 mono_load_remote_field (MonoObject *this, MonoClass *klass, MonoClassField *field, gpointer *res)
1808 static MonoMethod *getter = NULL;
1809 MonoDomain *domain = mono_domain_get ();
1810 MonoClass *field_class;
1811 MonoMethodMessage *msg;
1812 MonoArray *out_args;
1816 g_assert (this->vtable->klass == mono_defaults.transparent_proxy_class);
1824 for (i = 0; i < mono_defaults.object_class->method.count; ++i) {
1825 MonoMethod *cm = mono_defaults.object_class->methods [i];
1827 if (!strcmp (cm->name, "FieldGetter")) {
1835 field_class = mono_class_from_mono_type (field->type);
1837 msg = (MonoMethodMessage *)mono_object_new (domain, mono_defaults.mono_method_message_class);
1838 out_args = mono_array_new (domain, mono_defaults.object_class, 1);
1839 mono_message_init (domain, msg, mono_method_get_object (domain, getter, NULL), out_args);
1841 mono_array_set (msg->args, gpointer, 0, mono_string_new (domain, klass->name));
1842 mono_array_set (msg->args, gpointer, 1, mono_string_new (domain, field->name));
1844 mono_remoting_invoke ((MonoObject *)((MonoTransparentProxy *)this)->rp, msg, &exc, &out_args);
1846 *res = mono_array_get (out_args, MonoObject *, 0);
1848 if (field_class->valuetype) {
1849 return ((char *)*res) + sizeof (MonoObject);
1855 * mono_store_remote_field:
1856 * @this: pointer to an object
1857 * @klass: klass of the object containing @field
1858 * @field: the field to load
1859 * @val: the value/object to store
1861 * This method is called by the runtime on attempts to store fields of
1862 * transparent proxy objects. @this points to such TP, @klass is the class of
1863 * the object containing @field. @val is the new value to store in @field.
1866 mono_store_remote_field (MonoObject *this, MonoClass *klass, MonoClassField *field, gpointer val)
1868 static MonoMethod *setter = NULL;
1869 MonoDomain *domain = mono_domain_get ();
1870 MonoClass *field_class;
1871 MonoMethodMessage *msg;
1872 MonoArray *out_args;
1876 g_assert (this->vtable->klass == mono_defaults.transparent_proxy_class);
1881 for (i = 0; i < mono_defaults.object_class->method.count; ++i) {
1882 MonoMethod *cm = mono_defaults.object_class->methods [i];
1884 if (!strcmp (cm->name, "FieldSetter")) {
1892 field_class = mono_class_from_mono_type (field->type);
1894 if (field_class->valuetype)
1895 arg = mono_value_box (domain, field_class, val);
1897 arg = *((MonoObject **)val);
1900 msg = (MonoMethodMessage *)mono_object_new (domain, mono_defaults.mono_method_message_class);
1901 mono_message_init (domain, msg, mono_method_get_object (domain, setter, NULL), NULL);
1903 mono_array_set (msg->args, gpointer, 0, mono_string_new (domain, klass->name));
1904 mono_array_set (msg->args, gpointer, 1, mono_string_new (domain, field->name));
1905 mono_array_set (msg->args, gpointer, 2, arg);
1907 mono_remoting_invoke ((MonoObject *)((MonoTransparentProxy *)this)->rp, msg, &exc, &out_args);