Merge pull request #1659 from alexanderkyte/stringbuilder-referencesource
[mono.git] / mono / metadata / marshal.c
index 6eaa0775a2e5ce394970784100ec4a1243fd04d3..f688ff41b8da4eac788cfccd4bf6aa08ddbdb384 100644 (file)
@@ -628,13 +628,11 @@ mono_free_lparray (MonoArray *array, gpointer* nativeArray)
                return;
        klass = array->obj.vtable->klass;
 
-       switch (klass->element_class->byval_arg.type) {
-               case MONO_TYPE_CLASS:
-                       for(i = 0; i < array->max_length; ++i)  
-                               mono_marshal_free_ccw (mono_array_get (array, MonoObject*, i));
-                       free(nativeArray);
-               break;
-       }               
+       if (klass->element_class->byval_arg.type == MONO_TYPE_CLASS) {
+               for(i = 0; i < array->max_length; ++i)
+                       mono_marshal_free_ccw (mono_array_get (array, MonoObject*, i));
+               free(nativeArray);
+       }
 #endif
 }
 
@@ -696,49 +694,16 @@ mono_array_to_byte_byvalarray (gpointer native_arr, MonoArray *arr, guint32 elnu
        mono_array_to_byvalarray (native_arr, arr, mono_defaults.byte_class, elnum);
 }
 
-void
-mono_string_utf8_to_builder (MonoStringBuilder *sb, char *text)
-{
-       GError *error = NULL;
-       guint16 *ut;
-       glong items_written;
-       int l;
-
-       if (!sb || !text)
-               return;
-
-       l = strlen (text);
-
-       ut = g_utf8_to_utf16 (text, l, NULL, &items_written, &error);
-       
-       if (items_written > mono_stringbuilder_capacity (sb))
-               items_written = mono_stringbuilder_capacity (sb);
-       
-       if (!error) {
-               if (! sb->str || sb->str == sb->cached_str)
-                       MONO_OBJECT_SETREF (sb, str, mono_string_new_size (mono_domain_get (), items_written));
-               
-               memcpy (mono_string_chars (sb->str), ut, items_written * 2);
-               sb->length = items_written;
-               sb->cached_str = NULL;
-       } else 
-               g_error_free (error);
-
-       g_free (ut);
-}
-
-MonoStringBuilder *
-mono_string_utf8_to_builder2 (char *text)
+static MonoStringBuilder *
+mono_string_builder_new (int starting_string_length)
 {
-       int l;
-       MonoStringBuilder *sb;
        static MonoClass *string_builder_class;
        static MonoMethod *sb_ctor;
-       void *args [1];
-       MonoObject *exc;
+       static void *args [1];
+       int initial_len = starting_string_length;
 
-       if (!text)
-               return NULL;
+       if (initial_len < 0)
+               initial_len = 0;
 
        if (!string_builder_class) {
                MonoMethodDesc *desc;
@@ -749,78 +714,101 @@ mono_string_utf8_to_builder2 (char *text)
                sb_ctor = mono_method_desc_search_in_class (desc, string_builder_class);
                g_assert (sb_ctor);
                mono_method_desc_free (desc);
-       }
 
-       l = strlen (text);
+               // We make a new array in the _to_builder function, so this
+               // array will always be garbage collected.
+               args [0] = &initial_len;
+       }
 
-       sb = (MonoStringBuilder*)mono_object_new (mono_domain_get (), string_builder_class);
+       MonoStringBuilder *sb = (MonoStringBuilder*)mono_object_new (mono_domain_get (), string_builder_class);
+       MonoObject *exc;
        g_assert (sb);
-       args [0] = &l;
+
        mono_runtime_invoke (sb_ctor, sb, args, &exc);
+
+       g_assert (sb->chunkChars->max_length >= initial_len);
        g_assert (!exc);
 
-       mono_string_utf8_to_builder (sb, text);
+       return sb;
+}
+
+static void
+mono_string_utf16_to_builder_copy (MonoStringBuilder *sb, gunichar2 *text, size_t string_len)
+{
+       gunichar2 *charDst = (gunichar2 *)sb->chunkChars->vector;
+       gunichar2 *charSrc = (gunichar2 *)text;
+       memcpy (charDst, charSrc, sizeof (gunichar2) * string_len);
+
+       sb->chunkLength = string_len;
+
+       return;
+}
+
+MonoStringBuilder *
+mono_string_utf16_to_builder2 (gunichar2 *text)
+{
+       if (!text)
+               return NULL;
+
+       int len;
+       for (len = 0; text [len] != 0; ++len);
+
+       MonoStringBuilder *sb = mono_string_builder_new (len);
+       mono_string_utf16_to_builder (sb, text);
 
        return sb;
 }
 
-/*
- * FIXME: This routine does not seem to do what it seems to do
- * the @text is never copied into the string builder
- */
 void
-mono_string_utf16_to_builder (MonoStringBuilder *sb, gunichar2 *text)
+mono_string_utf8_to_builder (MonoStringBuilder *sb, char *text)
 {
-       guint32 len;
-
        if (!sb || !text)
                return;
 
-       g_assert (mono_string_chars (sb->str) == text);
+       int len = strlen (text);
+       if (len > mono_string_builder_capacity (sb))
+               len = mono_string_builder_capacity (sb);
 
-       for (len = 0; text [len] != 0; ++len)
-               ;
+       GError *error = NULL;
+       glong copied;
+       gunichar2* ut = g_utf8_to_utf16 (text, len, NULL, &copied, &error);
 
-       sb->length = len;
+       if (!error) {
+               MONO_OBJECT_SETREF (sb, chunkPrevious, NULL);
+               mono_string_utf16_to_builder_copy (sb, ut, copied);
+       } else
+               g_error_free (error);
+
+       g_free (ut);
 }
 
 MonoStringBuilder *
-mono_string_utf16_to_builder2 (gunichar2 *text)
+mono_string_utf8_to_builder2 (char *text)
 {
-       int len;
-       MonoStringBuilder *sb;
-       static MonoClass *string_builder_class;
-       static MonoMethod *sb_ctor;
-       void *args [1];
-       MonoObject *exc;
-
        if (!text)
                return NULL;
 
-       if (!string_builder_class) {
-               MonoMethodDesc *desc;
+       int len = strlen (text);
+       MonoStringBuilder *sb = mono_string_builder_new (len);
+       mono_string_utf8_to_builder (sb, text);
 
-               string_builder_class = mono_class_from_name (mono_defaults.corlib, "System.Text", "StringBuilder");
-               g_assert (string_builder_class);
-               desc = mono_method_desc_new (":.ctor(int)", FALSE);
-               sb_ctor = mono_method_desc_search_in_class (desc, string_builder_class);
-               g_assert (sb_ctor);
-               mono_method_desc_free (desc);
-       }
+       return sb;
+}
 
-       for (len = 0; text [len] != 0; ++len)
-               ;
 
-       sb = (MonoStringBuilder*)mono_object_new (mono_domain_get (), string_builder_class);
-       g_assert (sb);
-       args [0] = &len;
-       mono_runtime_invoke (sb_ctor, sb, args, &exc);
-       g_assert (!exc);
+void
+mono_string_utf16_to_builder (MonoStringBuilder *sb, gunichar2 *text)
+{
+       if (!sb || !text)
+               return;
 
-       sb->length = len;
-       memcpy (mono_string_chars (sb->str), text, len * 2);
+       guint32 len;
+       for (len = 0; text [len] != 0; ++len);
+       
+       if (len > mono_string_builder_capacity (sb))
+               len = mono_string_builder_capacity (sb);
 
-       return sb;
+       mono_string_utf16_to_builder_copy (sb, text, len);
 }
 
 /**
@@ -833,35 +821,38 @@ mono_string_utf16_to_builder2 (gunichar2 *text)
  *
  * The return value must be released with g_free.
  */
-gpointer
+gchar*
 mono_string_builder_to_utf8 (MonoStringBuilder *sb)
 {
        GError *error = NULL;
-       gchar *tmp, *res = NULL;
 
        if (!sb)
                return NULL;
 
-       if ((sb->str == sb->cached_str) && (sb->str->length == 0)) {
-               /* 
-                * The sb could have been allocated with the default capacity and be empty.
-                * we need to alloc a buffer of the default capacity in this case.
-                */
-               MONO_OBJECT_SETREF (sb, str, mono_string_new_size (mono_domain_get (), 16));
-               sb->cached_str = NULL;
-       }
 
-       tmp = g_utf16_to_utf8 (mono_string_chars (sb->str), sb->length, NULL, NULL, &error);
+       gunichar2 *str_utf16 = mono_string_builder_to_utf16 (sb);
+
+       guint str_len = mono_string_builder_string_length (sb);
+
+       gchar *tmp = g_utf16_to_utf8 (str_utf16, str_len, NULL, NULL, &error);
+
        if (error) {
                g_error_free (error);
+               g_free (str_utf16);
                mono_raise_exception (mono_get_exception_execution_engine ("Failed to convert StringBuilder from utf16 to utf8"));
+               return NULL;
        } else {
-               res = mono_marshal_alloc (mono_stringbuilder_capacity (sb) + 1);
-               memcpy (res, tmp, sb->length + 1);
+               guint len = mono_string_builder_capacity (sb) + 1;
+               gchar *res = mono_marshal_alloc (len * sizeof (gchar));
+               g_assert (str_len < len);
+               memcpy (res, tmp, str_len * sizeof (gchar));
+               res[str_len] = '\0';
+
+
+               g_free (str_utf16);
                g_free (tmp);
+               return res;
        }
-
-       return res;
 }
 
 /**
@@ -874,35 +865,43 @@ mono_string_builder_to_utf8 (MonoStringBuilder *sb)
  *
  * The return value must not be freed.
  */
-gpointer
+gunichar2*
 mono_string_builder_to_utf16 (MonoStringBuilder *sb)
 {
        if (!sb)
                return NULL;
 
-       g_assert (sb->str);
+       g_assert (sb->chunkChars);
 
-       /*
-        * The stringbuilder might not have ownership of this string. If this is
-        * the case, we must duplicate the string, so that we don't munge immutable
-        * strings
-        */
-       if (sb->str == sb->cached_str) {
-               /* 
-                * The sb could have been allocated with the default capacity and be empty.
-                * we need to alloc a buffer of the default capacity in this case.
-                */
-               if (sb->str->length == 0)
-                       MONO_OBJECT_SETREF (sb, str, mono_string_new_size (mono_domain_get (), 16));
-               else
-                       MONO_OBJECT_SETREF (sb, str, mono_string_new_utf16 (mono_domain_get (), mono_string_chars (sb->str), mono_stringbuilder_capacity (sb)));
-               sb->cached_str = NULL;
-       }
-       
-       if (sb->length == 0)
-               *(mono_string_chars (sb->str)) = '\0';
+       guint len = mono_string_builder_capacity (sb);
+
+       if (len == 0)
+               len = 1;
+
+       gunichar2 *str = mono_marshal_alloc ((len + 1) * sizeof (gunichar2));
+       str[len] = '\0';
+
+       if (len == 0)
+               return str;
+
+       MonoStringBuilder* chunk = sb;
+       do {
+               if (chunk->chunkLength > 0) {
+                       // Check that we will not overrun our boundaries.
+                       gunichar2 *source = (gunichar2 *)chunk->chunkChars->vector;
 
-       return mono_string_chars (sb->str);
+                       if (chunk->chunkLength <= len) {
+                               memcpy (str + chunk->chunkOffset, source, chunk->chunkLength * sizeof(gunichar2));
+                       } else {
+                               g_error ("A chunk in the StringBuilder had a length longer than expected from the offset.");
+                       }
+
+                       len -= chunk->chunkLength;
+               }
+               chunk = chunk->chunkPrevious;
+       } while (chunk != NULL);
+
+       return str;
 }
 
 static gpointer
@@ -1708,27 +1707,8 @@ emit_object_to_ptr_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv
 #endif /* DISABLE_COM */
 
        case MONO_MARSHAL_CONV_SAFEHANDLE: {
-               int dar_release_slot, pos;
+               int pos;
                
-               dar_release_slot = mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
-
-               /*
-                * The following is ifdefed-out, because I have no way of doing the
-                * DangerousRelease when destroying the structure
-                */
-#if 0
-               /* set release = false */
-               mono_mb_emit_icon (mb, 0);
-               mono_mb_emit_stloc (mb, dar_release_slot);
-               if (!sh_dangerous_add_ref)
-                       init_safe_handle ();
-
-               /* safehandle.DangerousAddRef (ref release) */
-               mono_mb_emit_ldloc (mb, 0); /* the source */
-               mono_mb_emit_byte (mb, CEE_LDIND_I);
-               mono_mb_emit_ldloc_addr (mb, dar_release_slot);
-               mono_mb_emit_managed_call (mb, sh_dangerous_add_ref, NULL);
-#endif
                mono_mb_emit_ldloc (mb, 0);
                mono_mb_emit_byte (mb, CEE_LDIND_I);
                pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
@@ -2012,7 +1992,8 @@ emit_thread_interrupt_checkpoint_call (MonoMethodBuilder *mb, gpointer checkpoin
 {
        int pos_noabort, pos_noex;
 
-       mono_mb_emit_ptr (mb, (gpointer) mono_thread_interruption_request_flag ());
+       mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
+       mono_mb_emit_byte (mb, CEE_MONO_LDPTR_INT_REQ_FLAG);
        mono_mb_emit_byte (mb, CEE_LDIND_U4);
        pos_noabort = mono_mb_emit_branch (mb, CEE_BRFALSE);
 
@@ -2326,7 +2307,6 @@ static gboolean
 mono_marshal_need_free (MonoType *t, MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec)
 {
        MonoMarshalNative encoding;
-       MonoMarshalConv conv;
 
        switch (t->type) {
        case MONO_TYPE_VALUETYPE:
@@ -2336,7 +2316,7 @@ mono_marshal_need_free (MonoType *t, MonoMethodPInvoke *piinfo, MonoMarshalSpec
        case MONO_TYPE_CLASS:
                if (t->data.klass == mono_defaults.stringbuilder_class) {
                        gboolean need_free;
-                       conv = mono_marshal_get_ptr_to_stringbuilder_conv (piinfo, spec, &need_free);
+                       mono_marshal_get_ptr_to_stringbuilder_conv (piinfo, spec, &need_free);
                        return need_free;
                }
                return FALSE;
@@ -2592,10 +2572,8 @@ check_generic_wrapper_cache (GHashTable *cache, MonoMethod *orig_method, gpointe
        MonoMethod *res;
        MonoMethod *inst, *def;
        MonoGenericContext *ctx;
-       MonoMethod *def_method;
 
        g_assert (orig_method->is_inflated);
-       def_method = ((MonoMethodInflated*)orig_method)->declaring;
        ctx = mono_method_get_context (orig_method);
 
        /*
@@ -6163,7 +6141,7 @@ emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
        case MARSHAL_ACTION_MANAGED_CONV_IN: {
                MonoClass *eklass;
                guint32 label1, label2, label3;
-               int index_var, src_ptr, loc, esize, param_num, num_elem;
+               int index_var, src_ptr, esize, param_num, num_elem;
                MonoMarshalConv conv;
                gboolean is_string = FALSE;
                
@@ -6224,7 +6202,6 @@ emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
                else
                        esize = mono_class_native_size (eklass, NULL);
                src_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
-               loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
 
                mono_mb_emit_byte (mb, CEE_LDNULL);
                mono_mb_emit_stloc (mb, conv_arg);
@@ -6341,7 +6318,7 @@ emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
        case MARSHAL_ACTION_MANAGED_CONV_OUT: {
                MonoClass *eklass;
                guint32 label1, label2, label3;
-               int index_var, dest_ptr, loc, esize, param_num, num_elem;
+               int index_var, dest_ptr, esize, param_num, num_elem;
                MonoMarshalConv conv;
                gboolean is_string = FALSE;
 
@@ -6389,7 +6366,6 @@ emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
                        esize = mono_class_native_size (eklass, NULL);
 
                dest_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
-               loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
 
                /* Check null */
                mono_mb_emit_ldloc (mb, conv_arg);
@@ -6936,8 +6912,9 @@ emit_marshal (EmitMarshalContext *m, int argnum, MonoType *t,
                        return emit_marshal_vtype (m, argnum, t, spec, conv_arg, conv_arg_type, action);
                else
                        return emit_marshal_object (m, argnum, t, spec, conv_arg, conv_arg_type, action);
+       default:
+               return conv_arg;
        }
-       return conv_arg;
 }
 
 #ifndef DISABLE_JIT
@@ -7154,6 +7131,8 @@ mono_marshal_emit_native_wrapper (MonoImage *image, MonoMethodBuilder *mb, MonoM
                case MONO_TYPE_BOOLEAN:
                        emit_marshal (&m, argnum, t, spec, tmp_locals [i], NULL, MARSHAL_ACTION_CONV_OUT);
                        break;
+               default:
+                       break;
                }
        }
 
@@ -7705,6 +7684,8 @@ mono_marshal_emit_managed_wrapper (MonoMethodBuilder *mb, MonoMethodSignature *i
                        case MONO_TYPE_BOOLEAN:
                                emit_marshal (m, i, t, mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
                                break;
+                       default:
+                               break;
                        }
                }
                else if (invoke_sig->params [i]->attrs & PARAM_ATTRIBUTE_OUT) {
@@ -7870,8 +7851,6 @@ mono_marshal_get_managed_wrapper (MonoMethod *method, MonoClass *delegate_klass,
                        gint32 call_conv;
                        gint32 charset = 0;
                        MonoBoolean set_last_error = 0;
-                       MonoBoolean best_fit_mapping = 0;
-                       MonoBoolean throw_on_unmappable = 0;
                        MonoError error;
 
                        mono_reflection_create_custom_attr_data_args (mono_defaults.corlib, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
@@ -7894,9 +7873,9 @@ mono_marshal_get_managed_wrapper (MonoMethod *method, MonoClass *delegate_klass,
                                } else if (!strcmp (narg->field->name, "SetLastError")) {
                                        set_last_error = *(MonoBoolean*)mono_object_unbox (o);
                                } else if (!strcmp (narg->field->name, "BestFitMapping")) {
-                                       best_fit_mapping = *(MonoBoolean*)mono_object_unbox (o);
+                                       // best_fit_mapping = *(MonoBoolean*)mono_object_unbox (o);
                                } else if (!strcmp (narg->field->name, "ThrowOnUnmappableChar")) {
-                                       throw_on_unmappable = *(MonoBoolean*)mono_object_unbox (o);
+                                       // throw_on_unmappable = *(MonoBoolean*)mono_object_unbox (o);
                                } else {
                                        g_assert_not_reached ();
                                }
@@ -8165,7 +8144,7 @@ mono_marshal_get_isinst_with_cache (void)
        mono_mb_emit_ldloc (mb, 1);
        mono_mb_emit_byte (mb, CEE_LDC_I4);
        mono_mb_emit_i4 (mb, ~0x1);
-       mono_mb_emit_byte (mb, CEE_CONV_U);
+       mono_mb_emit_byte (mb, CEE_CONV_I);
        mono_mb_emit_byte (mb, CEE_AND);
        mono_mb_emit_ldloc (mb, 0);
        /*if ((cached_vtable & ~0x1)== obj_vtable)*/
@@ -8589,11 +8568,9 @@ mono_marshal_get_synchronized_inner_wrapper (MonoMethod *method)
        MonoMethodSignature *sig;
        MonoMethod *res;
        MonoGenericContext *ctx = NULL;
-       MonoMethod *orig_method = NULL;
        MonoGenericContainer *container = NULL;
 
        if (method->is_inflated && !mono_method_get_context (method)->method_inst) {
-               orig_method = method;
                ctx = &((MonoMethodInflated*)method)->context;
                method = ((MonoMethodInflated*)method)->declaring;
                container = mono_method_get_generic_container (method);
@@ -10258,7 +10235,6 @@ mono_struct_delete_old (MonoClass *klass, char *ptr)
        info = mono_marshal_load_type_info (klass);
 
        for (i = 0; i < info->num_fields; i++) {
-               MonoMarshalNative ntype;
                MonoMarshalConv conv;
                MonoType *ftype = info->fields [i].field->type;
                char *cpos;
@@ -10266,8 +10242,8 @@ mono_struct_delete_old (MonoClass *klass, char *ptr)
                if (ftype->attrs & FIELD_ATTRIBUTE_STATIC)
                        continue;
 
-               ntype = mono_type_to_unmanaged (ftype, info->fields [i].mspec, TRUE, 
-                                               klass->unicode, &conv);
+               mono_type_to_unmanaged (ftype, info->fields [i].mspec, TRUE, 
+                               klass->unicode, &conv);
                        
                cpos = ptr + info->fields [i].offset;
 
@@ -10371,11 +10347,20 @@ ves_icall_System_Runtime_InteropServices_Marshal_FreeHGlobal (void *ptr)
 void*
 ves_icall_System_Runtime_InteropServices_Marshal_AllocCoTaskMem (int size)
 {
+       void *res;
+
 #ifdef HOST_WIN32
-       return CoTaskMemAlloc (size);
+       res = CoTaskMemAlloc (size);
 #else
-       return g_try_malloc ((gulong)size);
+       if ((gulong)size == 0)
+               /* This returns a valid pointer for size 0 on MS.NET */
+               size = 4;
+
+       res = g_try_malloc ((gulong)size);
 #endif
+       if (!res)
+               mono_gc_out_of_memory ((gulong)size);
+       return res;
 }
 
 void
@@ -10391,11 +10376,16 @@ ves_icall_System_Runtime_InteropServices_Marshal_FreeCoTaskMem (void *ptr)
 gpointer
 ves_icall_System_Runtime_InteropServices_Marshal_ReAllocCoTaskMem (gpointer ptr, int size)
 {
+       void *res;
+
 #ifdef HOST_WIN32
-       return CoTaskMemRealloc (ptr, size);
+       res = CoTaskMemRealloc (ptr, size);
 #else
-       return g_try_realloc (ptr, (gulong)size);
+       res = g_try_realloc (ptr, (gulong)size);
 #endif
+       if (!res)
+               mono_gc_out_of_memory ((gulong)size);
+       return res;
 }
 
 void*
@@ -10861,10 +10851,10 @@ mono_marshal_asany (MonoObject *o, MonoMarshalNative string_encoding, int param_
 
                return res;
        }
+       default:
+               break;
        }
-
        mono_raise_exception (mono_get_exception_argument ("", "No PInvoke conversion exists for value passed to Object-typed parameter."));
-
        return NULL;
 }