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 dummy_mono_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
356 g_error ("runtime invoke called on uninitialized runtime");
360 static MonoInvokeFunc default_mono_runtime_invoke = dummy_mono_runtime_invoke;
363 mono_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
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 ? func: dummy_mono_runtime_invoke;
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:
693 case MONO_TYPE_VALUETYPE:
694 pa [i] = (char *)(((gpointer *)params->vector)[i]) + sizeof (MonoObject);
696 case MONO_TYPE_STRING:
697 case MONO_TYPE_OBJECT:
698 case MONO_TYPE_CLASS:
699 case MONO_TYPE_ARRAY:
700 case MONO_TYPE_SZARRAY:
701 pa [i] = (char *)(((gpointer *)params->vector)[i]);
704 g_error ("type 0x%x not handled in ves_icall_InternalInvoke", sig->params [i]->type);
709 if (!strcmp (method->name, ".ctor") && method->klass != mono_defaults.string_class) {
711 obj = mono_object_new (mono_domain_get (), method->klass);
712 mono_runtime_invoke (method, obj, pa, exc);
715 return mono_runtime_invoke (method, obj, pa, exc);
719 * mono_object_allocate:
720 * @size: number of bytes to allocate
722 * This is a very simplistic routine until we have our GC-aware
725 * Returns: an allocated object of size @size, or NULL on failure.
728 mono_object_allocate (size_t size)
731 /* if this is changed to GC_debug_malloc(), we need to change also metadata/gc.c */
732 void *o = GC_malloc (size);
734 void *o = calloc (1, size);
737 mono_stats.new_object_count++;
745 * Frees the memory used by the object. Debugging purposes
746 * only, as we will have our GC system.
749 mono_object_free (MonoObject *o)
752 g_error ("mono_object_free called with boehm gc.");
754 MonoClass *c = o->vtable->klass;
756 memset (o, 0, c->instance_size);
763 * @klass: the class of the object that we want to create
765 * Returns: A newly created object whose definition is
766 * looked up using @klass
769 mono_object_new (MonoDomain *domain, MonoClass *klass)
771 return mono_object_new_specific (mono_class_vtable (domain, klass));
775 * mono_object_new_specific:
776 * @vtable: the vtable of the object that we want to create
778 * Returns: A newly created object with class and domain specified
782 mono_object_new_specific (MonoVTable *vtable)
786 o = mono_object_allocate (vtable->klass->instance_size);
788 if (vtable->klass->has_finalize)
789 mono_object_register_finalizer (o);
795 * mono_object_new_from_token:
796 * @image: Context where the type_token is hosted
797 * @token: a token of the type that we want to create
799 * Returns: A newly created object whose definition is
800 * looked up using @token in the @image image
803 mono_object_new_from_token (MonoDomain *domain, MonoImage *image, guint32 token)
807 class = mono_class_get (image, token);
809 return mono_object_new (domain, class);
815 * @obj: the object to clone
817 * Returns: A newly created object who is a shallow copy of @obj
820 mono_object_clone (MonoObject *obj)
825 size = obj->vtable->klass->instance_size;
826 o = mono_object_allocate (size);
828 memcpy (o, obj, size);
830 if (obj->vtable->klass->has_finalize)
831 mono_object_register_finalizer (o);
837 * @array: the array to clone
839 * Returns: A newly created array who is a shallow copy of @array
842 mono_array_clone (MonoArray *array)
847 MonoClass *klass = array->obj.vtable->klass;
849 if (array->bounds == NULL) {
850 size = mono_array_length (array);
851 o = mono_array_new_full (((MonoObject *)array)->vtable->domain,
854 size *= mono_array_element_size (klass);
855 memcpy (o, array, sizeof (MonoArray) + size);
860 sizes = alloca (klass->rank * sizeof(guint32) * 2);
861 size = mono_array_element_size (klass);
862 for (i = 0; i < klass->rank; ++i) {
863 sizes [i] = array->bounds [i].length;
864 size *= array->bounds [i].length;
865 sizes [i + klass->rank] = array->bounds [i].lower_bound;
867 o = mono_array_new_full (((MonoObject *)array)->vtable->domain,
868 klass, sizes, sizes + klass->rank);
869 memcpy (o, array, sizeof(MonoArray) + size);
875 * mono_array_new_full:
876 * @domain: domain where the object is created
877 * @array_class: array class
878 * @lengths: lengths for each dimension in the array
879 * @lower_bounds: lower bounds for each dimension in the array (may be NULL)
881 * This routine creates a new array objects with the given dimensions,
882 * lower bounds and type.
885 mono_array_new_full (MonoDomain *domain, MonoClass *array_class,
886 guint32 *lengths, guint32 *lower_bounds)
888 guint32 byte_len, len;
891 MonoArrayBounds *bounds;
894 if (!array_class->inited)
895 mono_class_init (array_class);
897 byte_len = mono_array_element_size (array_class);
900 if (array_class->rank == 1 &&
901 (lower_bounds == NULL || lower_bounds [0] == 0)) {
906 bounds = GC_malloc (sizeof (MonoArrayBounds) * array_class->rank);
908 bounds = g_malloc0 (sizeof (MonoArrayBounds) * array_class->rank);
910 for (i = 0; i < array_class->rank; ++i) {
911 bounds [i].length = lengths [i];
916 for (i = 0; i < array_class->rank; ++i)
917 bounds [i].lower_bound = lower_bounds [i];
922 * Following three lines almost taken from mono_object_new ():
923 * they need to be kept in sync.
925 o = mono_object_allocate (sizeof (MonoArray) + byte_len);
928 o->vtable = mono_class_vtable (domain, array_class);
930 array = (MonoArray*)o;
932 array->bounds = bounds;
933 array->max_length = len;
940 * @domain: domain where the object is created
941 * @eclass: element class
942 * @n: number of array elements
944 * This routine creates a new szarray with @n elements of type @eclass.
947 mono_array_new (MonoDomain *domain, MonoClass *eclass, guint32 n)
951 ac = mono_array_class_get (&eclass->byval_arg, 1);
952 g_assert (ac != NULL);
954 return mono_array_new_specific (mono_class_vtable (domain, ac), n);
958 * mono_array_new_specific:
959 * @vtable: a vtable in the appropriate domain for an initialized class
960 * @n: number of array elements
962 * This routine is a fast alternative to mono_array_new() for code which
963 * can be sure about the domain it operates in.
966 mono_array_new_specific (MonoVTable *vtable, guint32 n)
972 byte_len = n * mono_array_element_size (vtable->klass);
974 if (vtable->klass->element_class->byval_arg.type >= MONO_TYPE_BOOLEAN && vtable->klass->element_class->byval_arg.type <= MONO_TYPE_R4) {
975 o = GC_malloc_atomic (sizeof (MonoArray) + byte_len);
976 o->synchronisation = 0;
977 memset (((MonoArray*)o)->vector, 0, byte_len);
979 o = mono_object_allocate (sizeof (MonoArray) + byte_len);
982 o = mono_object_allocate (sizeof (MonoArray) + byte_len);
996 * mono_string_new_utf16:
997 * @text: a pointer to an utf16 string
998 * @len: the length of the string
1000 * Returns: A newly created string object which contains @text.
1003 mono_string_new_utf16 (MonoDomain *domain, const guint16 *text, gint32 len)
1007 s = mono_string_new_size (domain, len);
1008 g_assert (s != NULL);
1010 memcpy (mono_string_chars (s), text, len * 2);
1016 * mono_string_new_size:
1017 * @text: a pointer to an utf16 string
1018 * @len: the length of the string
1020 * Returns: A newly created string object of @len
1023 mono_string_new_size (MonoDomain *domain, gint32 len)
1027 #if CREATION_SPEEDUP
1028 s = GC_malloc_atomic (sizeof (MonoString) + ((len + 1) * 2));
1029 s->object.synchronisation = 0;
1030 mono_string_chars (s) [len] = 0;
1032 s = (MonoString*)mono_object_allocate (sizeof (MonoString) + ((len + 1) * 2));
1037 s->object.vtable = mono_class_vtable (domain, mono_defaults.string_class);
1044 * mono_string_new_len:
1045 * @text: a pointer to an utf8 string
1046 * @length: number of bytes in @text to consider
1048 * Returns: A newly created string object which contains @text.
1051 mono_string_new_len (MonoDomain *domain, const char *text, guint length)
1053 GError *error = NULL;
1054 MonoString *o = NULL;
1056 glong items_written;
1059 ut = g_utf8_to_utf16 (text, length, NULL, &items_written, &error);
1062 o = mono_string_new_utf16 (domain, ut, items_written);
1064 g_error_free (error);
1073 * @text: a pointer to an utf8 string
1075 * Returns: A newly created string object which contains @text.
1078 mono_string_new (MonoDomain *domain, const char *text)
1080 GError *error = NULL;
1081 MonoString *o = NULL;
1083 glong items_written;
1088 ut = g_utf8_to_utf16 (text, l, NULL, &items_written, &error);
1091 o = mono_string_new_utf16 (domain, ut, items_written);
1093 g_error_free (error);
1101 * mono_string_new_wrapper:
1102 * @text: pointer to utf8 characters.
1104 * Helper function to create a string object from @text in the current domain.
1107 mono_string_new_wrapper (const char *text)
1109 MonoDomain *domain = mono_domain_get ();
1112 return mono_string_new (domain, text);
1119 * @class: the class of the value
1120 * @value: a pointer to the unboxed data
1122 * Returns: A newly created object which contains @value.
1125 mono_value_box (MonoDomain *domain, MonoClass *class, gpointer value)
1130 g_assert (class->valuetype);
1132 size = mono_class_instance_size (class);
1133 res = mono_object_allocate (size);
1134 res->vtable = mono_class_vtable (domain, class);
1136 size = size - sizeof (MonoObject);
1138 #if NO_UNALIGNED_ACCESS
1139 memcpy ((char *)res + sizeof (MonoObject), value, size);
1143 *((guint8 *) res + sizeof (MonoObject)) = *(guint8 *) value;
1146 *(guint16 *)((guint8 *) res + sizeof (MonoObject)) = *(guint16 *) value;
1149 *(guint32 *)((guint8 *) res + sizeof (MonoObject)) = *(guint32 *) value;
1152 *(guint64 *)((guint8 *) res + sizeof (MonoObject)) = *(guint64 *) value;
1155 memcpy ((char *)res + sizeof (MonoObject), value, size);
1158 if (class->has_finalize)
1159 mono_object_register_finalizer (res);
1164 * mono_object_isinst:
1166 * @klass: a pointer to a class
1168 * Returns: @obj if @obj is derived from @klass
1171 mono_object_isinst (MonoObject *obj, MonoClass *klass)
1183 mono_class_init (klass);
1185 if (klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
1186 if ((klass->interface_id <= oklass->max_interface_id) &&
1187 vt->interface_offsets [klass->interface_id])
1190 if (oklass == mono_defaults.transparent_proxy_class) {
1191 /* fixme: add check for IRemotingTypeInfo */
1192 oklass = ((MonoTransparentProxy *)obj)->klass;
1195 if (oklass->rank == klass->rank &&
1196 (oklass->element_class->baseval - klass->element_class->baseval) <=
1197 klass->element_class->diffval)
1200 } else if ((oklass->baseval - klass->baseval) <= klass->diffval)
1208 mono_string_is_interned_lookup (MonoString *str, int insert)
1210 MonoGHashTable *ldstr_table;
1213 char *ins = g_malloc (4 + str->length * 2);
1217 /* Encode the length */
1219 mono_metadata_encode_value (2 * str->length, p, &p);
1222 mono_metadata_encode_value (bloblen + 2 * str->length, p, &p);
1223 bloblen = (p - ins) + 2 * str->length;
1225 * ins is stored in the hash table as a key and needs to have the same
1226 * representation as in the metadata: we swap the character bytes on big
1229 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
1232 char *p2 = mono_string_chars (str);
1233 for (i = 0; i < str->length; ++i) {
1240 memcpy (p, mono_string_chars (str), str->length * 2);
1242 domain = ((MonoObject *)str)->vtable->domain;
1243 ldstr_table = domain->ldstr_table;
1244 mono_domain_lock (domain);
1245 if ((res = mono_g_hash_table_lookup (ldstr_table, ins))) {
1246 mono_domain_unlock (domain);
1251 mono_g_hash_table_insert (ldstr_table, ins, str);
1252 mono_domain_unlock (domain);
1255 mono_domain_unlock (domain);
1261 mono_string_is_interned (MonoString *o)
1263 return mono_string_is_interned_lookup (o, FALSE);
1267 mono_string_intern (MonoString *str)
1269 return mono_string_is_interned_lookup (str, TRUE);
1274 * @domain: the domain where the string will be used.
1275 * @image: a metadata context
1276 * @idx: index into the user string table.
1278 * Implementation for the ldstr opcode.
1281 mono_ldstr (MonoDomain *domain, MonoImage *image, guint32 idx)
1283 const char *str, *sig;
1287 sig = str = mono_metadata_user_string (image, idx);
1289 mono_domain_lock (domain);
1290 if ((o = mono_g_hash_table_lookup (domain->ldstr_table, sig))) {
1291 mono_domain_unlock (domain);
1295 len2 = mono_metadata_decode_blob_size (str, &str);
1298 o = mono_string_new_utf16 (domain, (guint16*)str, len2);
1299 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
1302 guint16 *p2 = (guint16*)mono_string_chars (o);
1303 for (i = 0; i < len2; ++i) {
1304 *p2 = GUINT16_FROM_LE (*p2);
1309 mono_g_hash_table_insert (domain->ldstr_table, (gpointer)sig, o);
1310 mono_domain_unlock (domain);
1316 * mono_string_to_utf8:
1317 * @s: a System.String
1319 * Return the UTF8 representation for @s.
1320 * the resulting buffer nedds to be freed with g_free().
1323 mono_string_to_utf8 (MonoString *s)
1326 GError *error = NULL;
1332 return g_strdup ("");
1334 as = g_utf16_to_utf8 (mono_string_chars (s), s->length, NULL, NULL, &error);
1336 g_warning (error->message);
1342 * mono_string_to_utf16:
1345 * Return an null-terminated array of the utf-16 chars
1346 * contained in @s. The result must be freed with g_free().
1347 * This is a temporary helper until our string implementation
1348 * is reworked to always include the null terminating char.
1351 mono_string_to_utf16 (MonoString *s)
1358 as = g_malloc ((s->length * 2) + 2);
1359 as [(s->length * 2)] = '\0';
1360 as [(s->length * 2) + 1] = '\0';
1363 return (gunichar2 *)(as);
1366 memcpy (as, mono_string_chars(s), s->length * 2);
1367 return (gunichar2 *)(as);
1371 default_ex_handler (MonoException *ex)
1373 MonoObject *o = (MonoObject*)ex;
1374 g_error ("Exception %s.%s raised in C code", o->vtable->klass->name_space, o->vtable->klass->name);
1377 static MonoExceptionFunc ex_handler = default_ex_handler;
1380 mono_install_handler (MonoExceptionFunc func)
1382 ex_handler = func? func: default_ex_handler;
1386 * mono_raise_exception:
1387 * @ex: exception object
1389 * Signal the runtime that the exception @ex has been raised in unmanaged code.
1392 mono_raise_exception (MonoException *ex)
1398 mono_wait_handle_new (MonoDomain *domain, HANDLE handle)
1400 MonoWaitHandle *res;
1402 res = (MonoWaitHandle *)mono_object_new (domain, mono_defaults.waithandle_class);
1404 res->handle = handle;
1410 mono_async_result_new (MonoDomain *domain, HANDLE handle, MonoObject *state, gpointer data)
1412 MonoAsyncResult *res;
1414 res = (MonoAsyncResult *)mono_object_new (domain, mono_defaults.asyncresult_class);
1417 res->async_state = state;
1418 res->handle = (MonoObject *)mono_wait_handle_new (domain, handle);
1419 res->sync_completed = FALSE;
1420 res->completed = FALSE;
1426 mono_message_init (MonoDomain *domain,
1427 MonoMethodMessage *this,
1428 MonoReflectionMethod *method,
1429 MonoArray *out_args)
1431 MonoMethodSignature *sig = method->method->signature;
1437 this->method = method;
1439 this->args = mono_array_new (domain, mono_defaults.object_class, sig->param_count);
1440 this->arg_types = mono_array_new (domain, mono_defaults.byte_class, sig->param_count);
1442 names = g_new (char *, sig->param_count);
1443 mono_method_get_param_names (method->method, (const char **) names);
1444 this->names = mono_array_new (domain, mono_defaults.string_class, sig->param_count);
1446 for (i = 0; i < sig->param_count; i++) {
1447 name = mono_string_new (domain, names [i]);
1448 mono_array_set (this->names, gpointer, i, name);
1453 for (i = 0, j = 0; i < sig->param_count; i++) {
1455 if (sig->params [i]->byref) {
1457 gpointer arg = mono_array_get (out_args, gpointer, j);
1458 mono_array_set (this->args, gpointer, i, arg);
1462 if (sig->params [i]->attrs & PARAM_ATTRIBUTE_IN)
1468 mono_array_set (this->arg_types, guint8, i, arg_type);
1473 * mono_remoting_invoke:
1474 * @real_proxy: pointer to a RealProxy object
1475 * @msg: The MonoMethodMessage to execute
1476 * @exc: used to store exceptions
1477 * @out_args: used to store output arguments
1479 * This is used to call RealProxy::Invoke(). RealProxy::Invoke() returns an
1480 * IMessage interface and it is not trivial to extract results from there. So
1481 * we call an helper method PrivateInvoke instead of calling
1482 * RealProxy::Invoke() directly.
1484 * Returns: the result object.
1487 mono_remoting_invoke (MonoObject *real_proxy, MonoMethodMessage *msg,
1488 MonoObject **exc, MonoArray **out_args)
1490 static MonoMethod *im = NULL;
1493 /*static MonoObject *(*invoke) (gpointer, gpointer, MonoObject **, MonoArray **) = NULL;*/
1495 /* FIXME: make this domain dependent */
1500 klass = mono_defaults.real_proxy_class;
1502 for (i = 0; i < klass->method.count; ++i) {
1503 if (!strcmp ("PrivateInvoke", klass->methods [i]->name) &&
1504 klass->methods [i]->signature->param_count == 4) {
1505 im = klass->methods [i];
1513 pa [0] = real_proxy;
1518 return mono_runtime_invoke (im, NULL, pa, exc);
1522 mono_message_invoke (MonoObject *target, MonoMethodMessage *msg,
1523 MonoObject **exc, MonoArray **out_args)
1525 if (target && target->vtable->klass == mono_defaults.transparent_proxy_class) {
1527 return mono_remoting_invoke ((MonoObject *)((MonoTransparentProxy *)target)->rp,
1528 msg, exc, out_args);
1531 MonoDomain *domain = mono_domain_get ();
1532 MonoMethod *method = msg->method->method;
1533 MonoMethodSignature *sig = method->signature;
1534 int i, j, outarg_count = 0;
1536 for (i = 0; i < sig->param_count; i++) {
1537 if (sig->params [i]->byref)
1541 *out_args = mono_array_new (domain, mono_defaults.object_class, outarg_count);
1544 for (i = 0, j = 0; i < sig->param_count; i++) {
1545 if (sig->params [i]->byref) {
1547 arg = mono_array_get (msg->args, gpointer, i);
1548 mono_array_set (*out_args, gpointer, j, arg);
1553 return mono_runtime_invoke_array (method, target, msg->args, exc);
1558 mono_print_unhandled_exception (MonoObject *exc)
1560 char *message = (char *) "";
1564 gboolean free_message = FALSE;
1567 if (mono_object_isinst (exc, mono_defaults.exception_class)) {
1568 klass = exc->vtable->klass;
1570 while (klass && method == NULL) {
1571 for (i = 0; i < klass->method.count; ++i) {
1572 method = klass->methods [i];
1573 if (!strcmp ("ToString", method->name) &&
1574 method->signature->param_count == 0 &&
1575 method->flags & METHOD_ATTRIBUTE_VIRTUAL &&
1576 method->flags & METHOD_ATTRIBUTE_PUBLIC) {
1583 klass = klass->parent;
1588 str = (MonoString *) mono_runtime_invoke (method, exc, NULL, NULL);
1590 message = mono_string_to_utf8 (str);
1591 free_message = TRUE;
1596 * g_printerr ("\nUnhandled Exception: %s.%s: %s\n", exc->vtable->klass->name_space,
1597 * exc->vtable->klass->name, message);
1599 g_printerr ("\nUnhandled Exception: %s\n", message);
1606 * mono_delegate_ctor:
1607 * @this: pointer to an uninitialized delegate object
1608 * @target: target object
1609 * @addr: pointer to native code
1611 * This is used to initialize a delegate. We also insert the method_info if
1612 * we find the info with mono_jit_info_table_find().
1615 mono_delegate_ctor (MonoObject *this, MonoObject *target, gpointer addr)
1617 MonoDomain *domain = mono_domain_get ();
1618 MonoDelegate *delegate = (MonoDelegate *)this;
1619 MonoMethod *method = NULL;
1626 class = this->vtable->klass;
1628 if ((ji = mono_jit_info_table_find (domain, addr))) {
1629 method = ji->method;
1630 delegate->method_info = mono_method_get_object (domain, method, NULL);
1633 if (target && target->vtable->klass == mono_defaults.transparent_proxy_class) {
1635 method = mono_marshal_get_remoting_invoke (method);
1636 delegate->method_ptr = mono_compile_method (method);
1637 delegate->target = target;
1639 delegate->method_ptr = addr;
1640 delegate->target = target;
1645 * mono_method_call_message_new:
1647 * Translates arguments pointers into a Message.
1650 mono_method_call_message_new (MonoMethod *method, gpointer *params, MonoMethod *invoke,
1651 MonoDelegate **cb, MonoObject **state)
1653 MonoDomain *domain = mono_domain_get ();
1654 MonoMethodSignature *sig = method->signature;
1655 MonoMethodMessage *msg;
1658 msg = (MonoMethodMessage *)mono_object_new (domain, mono_defaults.mono_method_message_class);
1661 mono_message_init (domain, msg, mono_method_get_object (domain, invoke, NULL), NULL);
1662 count = sig->param_count - 2;
1664 mono_message_init (domain, msg, mono_method_get_object (domain, method, NULL), NULL);
1665 count = sig->param_count;
1668 for (i = 0; i < count; i++) {
1673 if (sig->params [i]->byref)
1674 vpos = *((gpointer *)params [i]);
1678 type = sig->params [i]->type;
1679 class = mono_class_from_mono_type (sig->params [i]);
1681 if (class->valuetype)
1682 arg = mono_value_box (domain, class, vpos);
1684 arg = *((MonoObject **)vpos);
1686 mono_array_set (msg->args, gpointer, i, arg);
1690 *cb = *((MonoDelegate **)params [i]);
1692 *state = *((MonoObject **)params [i]);
1699 * mono_method_return_message_restore:
1701 * Restore results from message based processing back to arguments pointers
1704 mono_method_return_message_restore (MonoMethod *method, gpointer *params, MonoArray *out_args)
1706 MonoMethodSignature *sig = method->signature;
1707 int i, j, type, size;
1709 for (i = 0, j = 0; i < sig->param_count; i++) {
1710 MonoType *pt = sig->params [i];
1712 size = mono_type_stack_size (pt, NULL);
1715 char *arg = mono_array_get (out_args, gpointer, j);
1719 case MONO_TYPE_VOID:
1720 g_assert_not_reached ();
1724 case MONO_TYPE_BOOLEAN:
1727 case MONO_TYPE_CHAR:
1734 case MONO_TYPE_VALUETYPE: {
1735 memcpy (*((gpointer *)params [i]), arg + sizeof (MonoObject), size);
1738 case MONO_TYPE_STRING:
1739 case MONO_TYPE_CLASS:
1740 case MONO_TYPE_ARRAY:
1741 case MONO_TYPE_SZARRAY:
1742 *((MonoObject **)params [i]) = (MonoObject *)arg;
1745 g_assert_not_reached ();
1754 * mono_load_remote_field:
1755 * @this: pointer to an object
1756 * @klass: klass of the object containing @field
1757 * @field: the field to load
1758 * @res: a storage to store the result
1760 * This method is called by the runtime on attempts to load fields of
1761 * transparent proxy objects. @this points to such TP, @klass is the class of
1762 * the object containing @field. @res is a storage location which can be
1763 * used to store the result.
1765 * Returns: an address pointing to the value of field.
1768 mono_load_remote_field (MonoObject *this, MonoClass *klass, MonoClassField *field, gpointer *res)
1770 static MonoMethod *getter = NULL;
1771 MonoDomain *domain = mono_domain_get ();
1772 MonoClass *field_class;
1773 MonoMethodMessage *msg;
1774 MonoArray *out_args;
1778 g_assert (this->vtable->klass == mono_defaults.transparent_proxy_class);
1786 for (i = 0; i < mono_defaults.object_class->method.count; ++i) {
1787 MonoMethod *cm = mono_defaults.object_class->methods [i];
1789 if (!strcmp (cm->name, "FieldGetter")) {
1797 field_class = mono_class_from_mono_type (field->type);
1799 msg = (MonoMethodMessage *)mono_object_new (domain, mono_defaults.mono_method_message_class);
1800 out_args = mono_array_new (domain, mono_defaults.object_class, 1);
1801 mono_message_init (domain, msg, mono_method_get_object (domain, getter, NULL), out_args);
1803 mono_array_set (msg->args, gpointer, 0, mono_string_new (domain, klass->name));
1804 mono_array_set (msg->args, gpointer, 1, mono_string_new (domain, field->name));
1806 mono_remoting_invoke ((MonoObject *)((MonoTransparentProxy *)this)->rp, msg, &exc, &out_args);
1808 *res = mono_array_get (out_args, MonoObject *, 0);
1810 if (field_class->valuetype) {
1811 return ((char *)*res) + sizeof (MonoObject);
1817 * mono_store_remote_field:
1818 * @this: pointer to an object
1819 * @klass: klass of the object containing @field
1820 * @field: the field to load
1821 * @val: the value/object to store
1823 * This method is called by the runtime on attempts to store fields of
1824 * transparent proxy objects. @this points to such TP, @klass is the class of
1825 * the object containing @field. @val is the new value to store in @field.
1828 mono_store_remote_field (MonoObject *this, MonoClass *klass, MonoClassField *field, gpointer val)
1830 static MonoMethod *setter = NULL;
1831 MonoDomain *domain = mono_domain_get ();
1832 MonoClass *field_class;
1833 MonoMethodMessage *msg;
1834 MonoArray *out_args;
1838 g_assert (this->vtable->klass == mono_defaults.transparent_proxy_class);
1843 for (i = 0; i < mono_defaults.object_class->method.count; ++i) {
1844 MonoMethod *cm = mono_defaults.object_class->methods [i];
1846 if (!strcmp (cm->name, "FieldSetter")) {
1854 field_class = mono_class_from_mono_type (field->type);
1856 if (field_class->valuetype)
1857 arg = mono_value_box (domain, field_class, val);
1859 arg = *((MonoObject **)val);
1862 msg = (MonoMethodMessage *)mono_object_new (domain, mono_defaults.mono_method_message_class);
1863 mono_message_init (domain, msg, mono_method_get_object (domain, setter, NULL), NULL);
1865 mono_array_set (msg->args, gpointer, 0, mono_string_new (domain, klass->name));
1866 mono_array_set (msg->args, gpointer, 1, mono_string_new (domain, field->name));
1867 mono_array_set (msg->args, gpointer, 2, arg);
1869 mono_remoting_invoke ((MonoObject *)((MonoTransparentProxy *)this)->rp, msg, &exc, &out_args);