Merge pull request #2721 from ludovic-henry/fix-mono_ms_ticks
authorLudovic Henry <ludovic@xamarin.com>
Mon, 25 Apr 2016 15:22:15 +0000 (11:22 -0400)
committerLudovic Henry <ludovic@xamarin.com>
Mon, 25 Apr 2016 15:22:15 +0000 (11:22 -0400)
[runtime] Fix potential overflow when using mono_msec_ticks

1  2 
mono/io-layer/processes.c
mono/metadata/gc.c
mono/metadata/icall-def.h
mono/metadata/icall.c
mono/metadata/monitor.c
mono/metadata/threadpool-ms.c
mono/metadata/threads.c
mono/mini/debugger-agent.c
mono/utils/mono-proclib.c
mono/utils/mono-time.c

index 0157e92f5be08fc6b56f0590393d9f0030d5917f,5a9e91b4831593d9eec1f00d6d7f1b39e9bac91b..913f0b8af4b43604a528192492512caff7fac786
@@@ -6,7 -6,6 +6,7 @@@
   *
   * (C) 2002-2011 Novell, Inc.
   * Copyright 2011 Xamarin Inc
 + * Licensed under the MIT license. See LICENSE file in the project root for full license information.
   */
  
  #include <config.h>
@@@ -1287,8 -1286,7 +1287,8 @@@ GetExitCodeProcess (gpointer process, g
                        *code = STILL_ACTIVE;
                        return TRUE;
                } else {
 -                      return FALSE;
 +                      *code = -1;
 +                      return TRUE;
                }
        }
  
@@@ -2727,8 -2725,7 +2727,7 @@@ process_wait (gpointer handle, guint32 
        WapiHandle_process *process_handle;
        pid_t pid G_GNUC_UNUSED, ret;
        int status;
-       guint32 start;
-       guint32 now;
+       gint64 start, now;
        struct MonoProcess *mp;
  
        /* FIXME: We can now easily wait on processes that aren't our own children,
diff --combined mono/metadata/gc.c
index 9ab8f7dd6d674aa778d9a9f89a871ec77d1381bb,077251c7b1e7b95e0ec13895562a79111a735f90..2cff646db1771c099780ffccbf618800d049a270
@@@ -6,7 -6,6 +6,7 @@@
   * Copyright 2002-2003 Ximian, Inc (http://www.ximian.com)
   * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
   * Copyright 2012 Xamarin Inc (http://www.xamarin.com)
 + * Licensed under the MIT license. See LICENSE file in the project root for full license information.
   */
  
  #include <config.h>
@@@ -40,7 -39,6 +40,7 @@@
  #include <mono/utils/mono-threads.h>
  #include <mono/utils/atomic.h>
  #include <mono/utils/mono-coop-semaphore.h>
 +#include <mono/utils/hazard-pointer.h>
  
  #ifndef HOST_WIN32
  #include <pthread.h>
@@@ -453,8 -451,6 +453,8 @@@ mono_domain_finalize (MonoDomain *domai
                mono_gc_finalize_threadpool_threads ();
        }
  
 +      mono_profiler_appdomain_event (domain, MONO_PROFILE_END_UNLOAD);
 +
        return TRUE;
  }
  
@@@ -642,41 -638,6 +642,41 @@@ mono_gc_finalize_notify (void
        mono_coop_sem_post (&finalizer_sem);
  }
  
 +/*
 +This is the number of entries allowed in the hazard free queue before
 +we explicitly cycle the finalizer thread to trigger pumping the queue.
 +
 +It was picked empirically by running the corlib test suite in a stress
 +scenario where all hazard entries are queued.
 +
 +In this extreme scenario we double the number of times we cycle the finalizer
 +thread compared to just GC calls.
 +
 +Entries are usually in the order of 100's of bytes each, so we're limiting
 +floating garbage to be in the order of a dozen kb.
 +*/
 +static gboolean finalizer_thread_pulsed;
 +#define HAZARD_QUEUE_OVERFLOW_SIZE 20
 +
 +static void
 +hazard_free_queue_is_too_big (size_t size)
 +{
 +      if (size < HAZARD_QUEUE_OVERFLOW_SIZE)
 +              return;
 +
 +      if (finalizer_thread_pulsed || InterlockedCompareExchange (&finalizer_thread_pulsed, TRUE, FALSE))
 +              return;
 +
 +      mono_gc_finalize_notify ();
 +}
 +
 +static void
 +hazard_free_queue_pump (void)
 +{
 +      mono_thread_hazardous_try_free_all ();
 +      finalizer_thread_pulsed = FALSE;
 +}
 +
  #ifdef HAVE_BOEHM_GC
  
  static void
@@@ -750,15 -711,8 +750,15 @@@ finalize_domain_objects (DomainFinaliza
  static guint32
  finalizer_thread (gpointer unused)
  {
 +      MonoError error;
 +      mono_thread_set_name_internal (mono_thread_internal_current (), mono_string_new (mono_get_root_domain (), "Finalizer"), FALSE, &error);
 +      mono_error_assert_ok (&error);
 +
        gboolean wait = TRUE;
  
 +      /* Register a hazard free queue pump callback */
 +      mono_hazard_pointer_install_free_queue_size_callback (hazard_free_queue_is_too_big);
 +
        while (!finished) {
                /* Wait to be notified that there's at least one
                 * finaliser to run
  
                reference_queue_proccess_all ();
  
 +              hazard_free_queue_pump ();
 +
                /* Avoid posting the pending done event until there are pending finalizers */
                if (mono_coop_sem_timedwait (&finalizer_sem, 0, MONO_SEM_FLAGS_NONE) == 0) {
                        /* Don't wait again at the start of the loop */
@@@ -828,9 -780,8 +828,9 @@@ stati
  void
  mono_gc_init_finalizer_thread (void)
  {
 -      gc_thread = mono_thread_create_internal (mono_domain_get (), finalizer_thread, NULL, FALSE, 0);
 -      ves_icall_System_Threading_Thread_SetName_internal (gc_thread, mono_string_new (mono_domain_get (), "Finalizer"));
 +      MonoError error;
 +      gc_thread = mono_thread_create_internal (mono_domain_get (), finalizer_thread, NULL, FALSE, 0, &error);
 +      mono_error_assert_ok (&error);
  }
  
  void
@@@ -876,14 -827,14 +876,14 @@@ mono_gc_cleanup (void
                finished = TRUE;
                if (mono_thread_internal_current () != gc_thread) {
                        gboolean timed_out = FALSE;
-                       guint32 start_ticks = mono_msec_ticks ();
-                       guint32 end_ticks = start_ticks + 2000;
+                       gint64 start_ticks = mono_msec_ticks ();
+                       gint64 end_ticks = start_ticks + 2000;
  
                        mono_gc_finalize_notify ();
                        /* Finishing the finalizer thread, so wait a little bit... */
                        /* MS seems to wait for about 2 seconds */
                        while (!finalizer_thread_exited) {
-                               guint32 current_ticks = mono_msec_ticks ();
+                               gint64 current_ticks = mono_msec_ticks ();
                                guint32 timeout;
  
                                if (current_ticks >= end_ticks)
index 9c345a269cde4a0e5a36d7b234a9450695c4a004,6f82e40d54868e976179b1c19ae63009d8b06e88..b74631fd9420a19a216568a45eb1d0c00380a785
@@@ -104,7 -104,7 +104,7 @@@ ICALL(ARGI_4, "Setup"
  
  ICALL_TYPE(ARRAY, "System.Array", ARRAY_1)
  ICALL(ARRAY_1, "ClearInternal",    ves_icall_System_Array_ClearInternal)
 -ICALL(ARRAY_2, "Clone",            mono_array_clone)
 +ICALL(ARRAY_2, "Clone",            ves_icall_System_Array_Clone)
  ICALL(ARRAY_3, "CreateInstanceImpl",   ves_icall_System_Array_CreateInstanceImpl)
  ICALL(ARRAY_14, "CreateInstanceImpl64",   ves_icall_System_Array_CreateInstanceImpl64)
  ICALL(ARRAY_4, "FastCopy",         ves_icall_System_Array_FastCopy)
@@@ -210,6 -210,9 +210,6 @@@ ICALL(PROCESS_10, "ProcessName_internal
  ICALL(PROCESS_13, "ShellExecuteEx_internal(System.Diagnostics.ProcessStartInfo,System.Diagnostics.Process/ProcInfo&)", ves_icall_System_Diagnostics_Process_ShellExecuteEx_internal)
  #endif /* !DISABLE_PROCESS_HANDLING */
  
 -ICALL_TYPE(SFRAME, "System.Diagnostics.StackFrame", SFRAME_1)
 -ICALL(SFRAME_1, "GetILOffsetFromFile", ves_icall_System_StackFrame_GetILOffsetFromFile)
 -
  ICALL_TYPE(STOPWATCH, "System.Diagnostics.Stopwatch", STOPWATCH_1)
  ICALL(STOPWATCH_1, "GetTimestamp", mono_100ns_ticks)
  
@@@ -224,7 -227,7 +224,7 @@@ ICALL(ENUM_7, "get_value", ves_icall_Sy
  
  ICALL_TYPE(ENV, "System.Environment", ENV_1)
  ICALL(ENV_1, "Exit", ves_icall_System_Environment_Exit)
 -ICALL(ENV_2, "GetCommandLineArgs", mono_runtime_get_main_args)
 +ICALL(ENV_2, "GetCommandLineArgs", ves_icall_System_Environment_GetCoomandLineArgs)
  ICALL(ENV_3, "GetEnvironmentVariableNames", ves_icall_System_Environment_GetEnvironmentVariableNames)
  ICALL(ENV_31, "GetIs64BitOperatingSystem", ves_icall_System_Environment_GetIs64BitOperatingSystem)
  ICALL(ENV_4, "GetLogicalDrivesInternal", ves_icall_System_Environment_GetLogicalDrives )
@@@ -239,7 -242,7 +239,7 @@@ ICALL(ENV_10, "get_HasShutdownStarted"
  ICALL(ENV_11, "get_MachineName", ves_icall_System_Environment_get_MachineName)
  ICALL(ENV_13, "get_Platform", ves_icall_System_Environment_get_Platform)
  ICALL(ENV_14, "get_ProcessorCount", mono_cpu_count)
- ICALL(ENV_15, "get_TickCount", mono_msec_ticks)
+ ICALL(ENV_15, "get_TickCount", ves_icall_System_Environment_get_TickCount)
  ICALL(ENV_16, "get_UserName", ves_icall_System_Environment_get_UserName)
  ICALL(ENV_16m, "internalBroadcastSettingChange", ves_icall_System_Environment_BroadcastSettingChange)
  ICALL(ENV_17, "internalGetEnvironmentVariable", ves_icall_System_Environment_GetEnvironmentVariable)
@@@ -493,15 -496,18 +493,15 @@@ ICALL(ASSEMN_1, "ParseName", ves_icall_
  ICALL(ASSEMN_2, "get_public_token", mono_digest_get_public_token)
  
  ICALL_TYPE(CATTR_DATA, "System.Reflection.CustomAttributeData", CATTR_DATA_1)
 -ICALL(CATTR_DATA_1, "ResolveArgumentsInternal", mono_reflection_resolve_custom_attribute_data)
 +ICALL(CATTR_DATA_1, "ResolveArgumentsInternal", ves_icall_System_Reflection_CustomAttributeData_ResolveArgumentsInternal)
  
  ICALL_TYPE(ASSEMB, "System.Reflection.Emit.AssemblyBuilder", ASSEMB_1)
  ICALL(ASSEMB_1, "InternalAddModule", ves_icall_System_Reflection_Emit_AssemblyBuilder_InternalAddModule)
  ICALL(ASSEMB_2, "basic_init", mono_image_basic_init)
  
 -ICALL_TYPE(CATTRB, "System.Reflection.Emit.CustomAttributeBuilder", CATTRB_1)
 -ICALL(CATTRB_1, "GetBlob", mono_reflection_get_custom_attrs_blob)
 -
  #ifndef DISABLE_REFLECTION_EMIT
 -ICALL_TYPE(DERIVEDTYPE, "System.Reflection.Emit.DerivedType", DERIVEDTYPE_1)
 -ICALL(DERIVEDTYPE_1, "create_unmanaged_type", mono_reflection_create_unmanaged_type)
 +ICALL_TYPE(CATTRB, "System.Reflection.Emit.CustomAttributeBuilder", CATTRB_1)
 +ICALL(CATTRB_1, "GetBlob", ves_icall_System_Reflection_Emit_CustomAttributeBuilder_GetBlob)
  #endif
  
  ICALL_TYPE(DYNM, "System.Reflection.Emit.DynamicMethod", DYNM_1)
@@@ -532,13 -538,8 +532,13 @@@ ICALL_TYPE(SIGH, "System.Reflection.Emi
  ICALL(SIGH_1, "get_signature_field", mono_reflection_sighelper_get_signature_field)
  ICALL(SIGH_2, "get_signature_local", mono_reflection_sighelper_get_signature_local)
  
 +#ifndef DISABLE_REFLECTION_EMIT
 +ICALL_TYPE(SYMBOLTYPE, "System.Reflection.Emit.SymbolType", SYMBOLTYPE_1)
 +ICALL(SYMBOLTYPE_1, "create_unmanaged_type", mono_reflection_create_unmanaged_type)
 +#endif
 +
  ICALL_TYPE(TYPEB, "System.Reflection.Emit.TypeBuilder", TYPEB_1)
 -ICALL(TYPEB_1, "create_generic_class", mono_reflection_create_generic_class)
 +ICALL(TYPEB_1, "create_generic_class", ves_icall_System_Reflection_Emit_TypeBuilder_create_generic_class)
  ICALL(TYPEB_2, "create_internal_class", mono_reflection_create_internal_class)
  ICALL(TYPEB_3, "create_runtime_class", mono_reflection_create_runtime_class)
  ICALL(TYPEB_4, "get_IsGenericParameter", ves_icall_TypeBuilder_get_IsGenericParameter)
@@@ -578,7 -579,6 +578,7 @@@ ICALL(MODULE_13, "get_MetadataToken", v
  ICALL_TYPE(MCMETH, "System.Reflection.MonoCMethod", MCMETH_1)
  ICALL(MCMETH_1, "GetGenericMethodDefinition_impl", ves_icall_MonoMethod_GetGenericMethodDefinition)
  ICALL(MCMETH_2, "InternalInvoke", ves_icall_InternalInvoke)
 +ICALL(MCMETH_3, "get_core_clr_security_level", ves_icall_MonoMethod_get_core_clr_security_level)
  
  ICALL_TYPE(MEVIN, "System.Reflection.MonoEventInfo", MEVIN_1)
  ICALL(MEVIN_1, "get_event_info", ves_icall_MonoEventInfo_get_event_info)
diff --combined mono/metadata/icall.c
index 285905fb9b8b8369f009526ea213975274c8ff3c,49bd4482155f96b6d9149f7c51a2a77a54fb2fba..e22c730342dc4a3bc8eadcb4932aa9722ad5cc93
@@@ -11,7 -11,6 +11,7 @@@
   * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
   * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
   * Copyright 2011-2015 Xamarin Inc (http://www.xamarin.com).
 + * Licensed under the MIT license. See LICENSE file in the project root for full license information.
   */
  
  #include <config.h>
@@@ -139,23 -138,19 +139,23 @@@ mono_class_init_checked (MonoClass *kla
  ICALL_EXPORT MonoObject *
  ves_icall_System_Array_GetValueImpl (MonoArray *arr, guint32 pos)
  {
 +      MonoError error;
        MonoClass *ac;
        gint32 esize;
        gpointer *ea;
 +      MonoObject *result = NULL;
  
        ac = (MonoClass *)arr->obj.vtable->klass;
  
        esize = mono_array_element_size (ac);
        ea = (gpointer*)((char*)arr->vector + (pos * esize));
  
 -      if (ac->element_class->valuetype)
 -              return mono_value_box (arr->obj.vtable->domain, ac->element_class, ea);
 -      else
 -              return (MonoObject *)*ea;
 +      if (ac->element_class->valuetype) {
 +              result = mono_value_box_checked (arr->obj.vtable->domain, ac->element_class, ea, &error);
 +              mono_error_set_pending_exception (&error);
 +      } else
 +              result = (MonoObject *)*ea;
 +      return result;
  }
  
  ICALL_EXPORT MonoObject *
@@@ -208,7 -203,6 +208,7 @@@ ves_icall_System_Array_GetValue (MonoAr
  ICALL_EXPORT void
  ves_icall_System_Array_SetValueImpl (MonoArray *arr, MonoObject *value, guint32 pos)
  {
 +      MonoError error;
        MonoClass *ac, *vc, *ec;
        gint32 esize, vsize;
        gpointer *ea, *va;
        gint64 i64 = 0;
        gdouble r64 = 0;
  
 +      mono_error_init (&error);
 +
        if (value)
                vc = value->vtable->klass;
        else
        }
  
        if (!ec->valuetype) {
 -              if (!mono_object_isinst (value, ec))
 +              gboolean castOk = (NULL != mono_object_isinst_checked (value, ec, &error));
 +              if (mono_error_set_pending_exception (&error))
 +                      return;
 +              if (!castOk)
                        INVALID_CAST;
                mono_gc_wbarrier_set_arrayref (arr, ea, (MonoObject*)value);
                return;
        }
  
 -      if (mono_object_isinst (value, ec)) {
 +      if (mono_object_isinst_checked (value, ec, &error)) {
                if (ec->has_references)
                        mono_value_copy (ea, (char*)value + sizeof (MonoObject), ec);
                else
                        mono_gc_memmove_atomic (ea, (char *)value + sizeof (MonoObject), esize);
                return;
        }
 +      if (mono_error_set_pending_exception (&error))
 +              return;
  
        if (!vc->valuetype)
                INVALID_CAST;
@@@ -565,8 -552,7 +565,8 @@@ ves_icall_System_Array_CreateInstanceIm
  
        klass = mono_class_from_mono_type (type->type);
        mono_class_init_checked (klass, &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
  
        if (bounds && (mono_array_length (bounds) == 1) && (mono_array_get (bounds, gint32, 0) != 0))
                /* vectors are not the same as one dimensional arrays with no-zero bounds */
@@@ -617,8 -603,7 +617,8 @@@ ves_icall_System_Array_CreateInstanceIm
  
        klass = mono_class_from_mono_type (type->type);
        mono_class_init_checked (klass, &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
  
        if (bounds && (mono_array_length (bounds) == 1) && (mono_array_get (bounds, gint64, 0) != 0))
                /* vectors are not the same as one dimensional arrays with no-zero bounds */
@@@ -713,15 -698,6 +713,15 @@@ ves_icall_System_Array_ClearInternal (M
        mono_gc_bzero_atomic (mono_array_addr_with_size_fast (arr, sz, idx), length * sz);
  }
  
 +ICALL_EXPORT MonoArray*
 +ves_icall_System_Array_Clone (MonoArray *arr)
 +{
 +      MonoError error;
 +      MonoArray *result = mono_array_clone_checked (arr, &error);
 +      mono_error_set_pending_exception (&error);
 +      return result;
 +}
 +
  ICALL_EXPORT gboolean
  ves_icall_System_Array_FastCopy (MonoArray *source, int source_idx, MonoArray* dest, int dest_idx, int length)
  {
@@@ -1060,10 -1036,7 +1060,10 @@@ ves_icall_System_ValueType_InternalGetH
  
        if (values) {
                int i;
 -              mono_gc_wbarrier_generic_store (fields, (MonoObject*) mono_array_new (mono_domain_get (), mono_defaults.object_class, count));
 +              MonoArray *fields_arr = mono_array_new_checked (mono_domain_get (), mono_defaults.object_class, count, &error);
 +              if (mono_error_set_pending_exception (&error))
 +                      return 0;
 +              mono_gc_wbarrier_generic_store (fields, (MonoObject*) fields_arr);
                for (i = 0; i < count; ++i)
                        mono_array_setref (*fields, i, values [i]);
        } else {
@@@ -1182,10 -1155,7 +1182,10 @@@ ves_icall_System_ValueType_Equals (Mono
  
        if (values) {
                int i;
 -              mono_gc_wbarrier_generic_store (fields, (MonoObject*) mono_array_new (mono_domain_get (), mono_defaults.object_class, count));
 +              MonoArray *fields_arr = mono_array_new_checked (mono_domain_get (), mono_defaults.object_class, count, &error);
 +              if (mono_error_set_pending_exception (&error))
 +                      return FALSE;
 +              mono_gc_wbarrier_generic_store (fields, (MonoObject*) fields_arr);
                for (i = 0; i < count; ++i)
                        mono_array_setref_fast (*fields, i, values [i]);
                return FALSE;
@@@ -1206,7 -1176,8 +1206,7 @@@ ves_icall_System_Object_GetType (MonoOb
  #endif
                ret = mono_type_get_object_checked (mono_object_domain (obj), &obj->vtable->klass->byval_arg, &error);
  
 -      mono_error_raise_exception (&error);
 -
 +      mono_error_set_pending_exception (&error);
        return ret;
  }
  
@@@ -1224,7 -1195,7 +1224,7 @@@ ves_icall_ModuleBuilder_getToken (MonoR
        
        MonoError error;
        gint32 result = mono_image_create_token (mb->dynamic_image, obj, create_open_instance, TRUE, &error);
 -      mono_error_raise_exception (&error);
 +      mono_error_set_pending_exception (&error);
        return result;
  }
  
@@@ -1238,7 -1209,7 +1238,7 @@@ ves_icall_ModuleBuilder_getMethodToken 
        MonoError error;
        gint32 result = mono_image_create_method_token (
                mb->dynamic_image, (MonoObject *) method, opt_param_types, &error);
 -      mono_error_raise_exception (&error);
 +      mono_error_set_pending_exception (&error);
        return result;
  }
  
@@@ -1247,15 -1218,15 +1247,15 @@@ ves_icall_ModuleBuilder_WriteToFile (Mo
  {
        MonoError error;
        mono_image_create_pefile (mb, file, &error);
 -      mono_error_raise_exception (&error);
 +      mono_error_set_pending_exception (&error);
  }
  
  ICALL_EXPORT void
  ves_icall_ModuleBuilder_build_metadata (MonoReflectionModuleBuilder *mb)
  {
        MonoError error;
 -      if (!mono_image_build_metadata (mb, &error))
 -              mono_error_raise_exception (&error);
 +      mono_image_build_metadata (mb, &error);
 +      mono_error_set_pending_exception (&error);
  }
  
  ICALL_EXPORT void
@@@ -1285,34 -1256,8 +1285,34 @@@ ves_icall_System_Reflection_Emit_Assemb
        return result;
  }
  
 +/**
 + * ves_icall_System_Reflection_Emit_TypeBuilder_create_generic_class:
 + * @tb: a TypeBuilder object
 + *
 + * (icall)
 + * Creates the generic class after all generic parameters have been added.
 + */
 +ICALL_EXPORT void
 +ves_icall_System_Reflection_Emit_TypeBuilder_create_generic_class (MonoReflectionTypeBuilder *tb)
 +{
 +      MonoError error;
 +      (void) mono_reflection_create_generic_class (tb, &error);
 +      mono_error_set_pending_exception (&error);
 +}
 +
 +#ifndef DISABLE_REFLECTION_EMIT
 +ICALL_EXPORT MonoArray*
 +ves_icall_System_Reflection_Emit_CustomAttributeBuilder_GetBlob (MonoReflectionAssembly *assembly, MonoObject *ctor, MonoArray *ctorArgs, MonoArray *properties, MonoArray *propValues, MonoArray *fields, MonoArray* fieldValues)
 +{
 +      MonoError error;
 +      MonoArray *result = mono_reflection_get_custom_attrs_blob_checked (assembly, ctor, ctorArgs, properties, propValues, fields, fieldValues, &error);
 +      mono_error_set_pending_exception (&error);
 +      return result;
 +}
 +#endif
 +
  static gboolean
 -get_caller (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
 +get_executing (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
  {
        MonoMethod **dest = (MonoMethod **)data;
  
        if (!managed)
                return FALSE;
  
 -      if (m == *dest) {
 -              *dest = NULL;
 -              return FALSE;
 -      }
        if (!(*dest)) {
 +              if (!strcmp (m->klass->name_space, "System.Reflection"))
 +                      return FALSE;
                *dest = m;
                return TRUE;
        }
  }
  
  static gboolean
 -get_executing (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
 +get_caller_no_reflection (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
  {
        MonoMethod **dest = (MonoMethod **)data;
  
        if (!managed)
                return FALSE;
  
 +      if (m->wrapper_type != MONO_WRAPPER_NONE)
 +              return FALSE;
 +
 +      if (m == *dest) {
 +              *dest = NULL;
 +              return FALSE;
 +      }
 +
 +      if (m->klass->image == mono_defaults.corlib && !strcmp (m->klass->name_space, "System.Reflection"))
 +              return FALSE;
 +
        if (!(*dest)) {
 -              if (!strcmp (m->klass->name_space, "System.Reflection"))
 -                      return FALSE;
                *dest = m;
                return TRUE;
        }
  }
  
  static gboolean
 -get_caller_no_reflection (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
 +get_caller_no_system_or_reflection (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
  {
        MonoMethod **dest = (MonoMethod **)data;
  
        if (m->wrapper_type != MONO_WRAPPER_NONE)
                return FALSE;
  
 -      if (m->klass->image == mono_defaults.corlib && !strcmp (m->klass->name_space, "System.Reflection"))
 -              return FALSE;
 -
        if (m == *dest) {
                *dest = NULL;
                return FALSE;
        }
 +
 +      if (m->klass->image == mono_defaults.corlib && ((!strcmp (m->klass->name_space, "System.Reflection"))
 +                                                                                                      || (!strcmp (m->klass->name_space, "System"))))
 +              return FALSE;
 +
        if (!(*dest)) {
                *dest = m;
                return TRUE;
@@@ -1392,7 -1328,6 +1392,7 @@@ type_from_parsed_name (MonoTypeNamePars
        MonoType *type = NULL;
        MonoAssembly *assembly = NULL;
        gboolean type_resolve = FALSE;
 +      MonoImage *rootimage = NULL;
  
        mono_error_init (error);
  
         */
        m = mono_method_get_last_managed ();
        dest = m;
 -
 -      mono_stack_walk_no_il (get_caller_no_reflection, &dest);
 -      if (!dest)
 -              dest = m;
 +      if (m && m->klass->image != mono_defaults.corlib) {
 +              /* Happens with inlining */
 +      } else {
 +              /* Ugly hack: type_from_parsed_name is called from
 +               * System.Type.internal_from_name, which is called most
 +               * directly from System.Type.GetType(string,bool,bool) but
 +               * also indirectly from places such as
 +               * System.Type.GetType(string,func,func) (via
 +               * System.TypeNameParser.GetType and System.TypeSpec.Resolve)
 +               * so we need to skip over all of those to find the true caller.
 +               *
 +               * It would be nice if we had stack marks.
 +               */
 +              mono_stack_walk_no_il (get_caller_no_system_or_reflection, &dest);
 +              if (!dest)
 +                      dest = m;
 +      }
  
        /*
         * FIXME: mono_method_get_last_managed() sometimes returns NULL, thus
        if (dest) {
                assembly = dest->klass->image->assembly;
                type_resolve = TRUE;
 +              rootimage = assembly->image;
        } else {
                g_warning (G_STRLOC);
        }
        if (info->assembly.name)
                assembly = mono_assembly_load (&info->assembly, assembly ? assembly->basedir : NULL, NULL);
  
 -
        if (assembly) {
                /* When loading from the current assembly, AppDomain.TypeResolve will not be called yet */
 -              type = mono_reflection_get_type_checked (assembly->image, info, ignoreCase, &type_resolve, error);
 +              type = mono_reflection_get_type_checked (rootimage, assembly->image, info, ignoreCase, &type_resolve, error);
                return_val_if_nok (error, NULL);
        }
  
 +      // XXXX - aleksey -
 +      //  Say we're looking for System.Generic.Dict<int, Local>
 +      //  we FAIL the get type above, because S.G.Dict isn't in assembly->image.  So we drop down here.
 +      //  but then we FAIL AGAIN because now we pass null as the image and the rootimage and everything
 +      //  is messed up when we go to construct the Local as the type arg...
 +      //
 +      // By contrast, if we started with Mine<System.Generic.Dict<int, Local>> we'd go in with assembly->image
 +      // as the root and then even the detour into generics would still not screw us when we went to load Local.
        if (!info->assembly.name && !type) {
                /* try mscorlib */
 -              type = mono_reflection_get_type_checked (NULL, info, ignoreCase, &type_resolve, error);
 +              type = mono_reflection_get_type_checked (rootimage, NULL, info, ignoreCase, &type_resolve, error);
                return_val_if_nok (error, NULL);
        }
        if (assembly && !type && type_resolve) {
                type_resolve = FALSE; /* This will invoke TypeResolve if not done in the first 'if' */
 -              type = mono_reflection_get_type_checked (assembly->image, info, ignoreCase, &type_resolve, error);
 +              type = mono_reflection_get_type_checked (rootimage, assembly->image, info, ignoreCase, &type_resolve, error);
                return_val_if_nok (error, NULL);
        }
  
@@@ -1487,12 -1401,10 +1487,12 @@@ ves_icall_System_Type_internal_from_nam
        /* mono_reflection_parse_type() mangles the string */
        if (!parsedOk) {
                mono_reflection_free_type_info (&info);
 -              g_free (str);
                if (throwOnError) {
 -                      mono_set_pending_exception (mono_get_exception_argument("typeName", "failed parse"));
 +                      mono_error_init (&error);
 +                      mono_error_set_argument (&error, "typeName", "failed parse: %s", str);
 +                      mono_error_set_pending_exception (&error);
                }
 +              g_free (str);
                return NULL;
        }
  
                if (throwOnError)
                        e = mono_get_exception_type_load (name, NULL);
  
 -              mono_loader_clear_error ();
                if (e) {
                        mono_set_pending_exception (e);
                        return NULL;
@@@ -1533,7 -1446,7 +1533,7 @@@ ves_icall_System_Type_internal_from_han
        MonoDomain *domain = mono_domain_get (); 
  
        ret = mono_type_get_object_checked (domain, handle, &error);
 -      mono_error_raise_exception (&error);
 +      mono_error_set_pending_exception (&error);
  
        return ret;
  }
@@@ -1704,13 -1617,8 +1704,13 @@@ ves_icall_RuntimeTypeHandle_IsInstanceO
        MonoError error;
        MonoClass *klass = mono_class_from_mono_type (type->type);
        mono_class_init_checked (klass, &error);
 -      mono_error_raise_exception (&error);
 -      return mono_object_isinst (obj, klass) != NULL;
 +      if (!is_ok (&error)) {
 +              mono_error_set_pending_exception (&error);
 +              return FALSE;
 +      }
 +      guint32 result = (mono_object_isinst_checked (obj, klass, &error) != NULL);
 +      mono_error_set_pending_exception (&error);
 +      return result;
  }
  
  ICALL_EXPORT guint32
@@@ -1785,7 -1693,7 +1785,7 @@@ ves_icall_System_Reflection_FieldInfo_i
        }
  
        MonoReflectionField *result = mono_field_get_object_checked (mono_domain_get (), klass, handle, &error);
 -      mono_error_raise_exception (&error);
 +      mono_error_set_pending_exception (&error);
        return result;
  }
  
@@@ -1802,7 -1710,7 +1802,7 @@@ ves_icall_System_Reflection_FieldInfo_G
        }
  
        res = type_array_from_modifiers (field->field->parent->image, type, optional, &error);
 -      mono_error_raise_exception (&error);
 +      mono_error_set_pending_exception (&error);
        return res;
  }
  
@@@ -1915,7 -1823,7 +1915,7 @@@ ves_icall_MonoField_GetParentType (Mono
        parent = declaring? field->field->parent: field->klass;
  
        ret = mono_type_get_object_checked (mono_object_domain (field), &parent->byval_arg, &error);
 -      mono_error_raise_exception (&error);
 +      mono_error_set_pending_exception (&error);
  
        return ret;
  
@@@ -1935,11 -1843,8 +1935,11 @@@ ves_icall_MonoField_GetValueInternal (M
                return NULL;
        }
  
 -      if (mono_security_core_clr_enabled ())
 -              mono_security_core_clr_ensure_reflection_access_field (cf);
 +      if (mono_security_core_clr_enabled () &&
 +          !mono_security_core_clr_ensure_reflection_access_field (cf, &error)) {
 +              mono_error_set_pending_exception (&error);
 +              return NULL;
 +      }
  
        MonoObject * result = mono_field_get_value_object_checked (domain, cf, obj, &error);
        mono_error_set_pending_exception (&error);
@@@ -1960,11 -1865,8 +1960,11 @@@ ves_icall_MonoField_SetValueInternal (M
                return;
        }
  
 -      if (mono_security_core_clr_enabled ())
 -              mono_security_core_clr_ensure_reflection_access_field (cf);
 +      if (mono_security_core_clr_enabled () &&
 +          !mono_security_core_clr_ensure_reflection_access_field (cf, &error)) {
 +              mono_error_set_pending_exception (&error);
 +              return;
 +      }
  
        type = mono_field_get_type_checked (cf, &error);
        if (!mono_error_ok (&error)) {
@@@ -2209,15 -2111,13 +2209,15 @@@ ves_icall_MonoPropertyInfo_get_property
  
        if ((req_info & PInfo_ReflectedType) != 0) {
                rt = mono_type_get_object_checked (domain, &property->klass->byval_arg, &error);
 -              mono_error_raise_exception (&error);
 +              if (mono_error_set_pending_exception (&error))
 +                      return;
  
                MONO_STRUCT_SETREF (info, parent, rt);
        }
        if ((req_info & PInfo_DeclaringType) != 0) {
                rt = mono_type_get_object_checked (domain, &pproperty->parent->byval_arg, &error);
 -              mono_error_raise_exception (&error);
 +              if (mono_error_set_pending_exception (&error))
 +                      return;
  
                MONO_STRUCT_SETREF (info, declaring_type, rt);
        }
                    (((pproperty->get->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) != METHOD_ATTRIBUTE_PRIVATE) ||
                     pproperty->get->klass == property->klass)) {
                        rm = mono_method_get_object_checked (domain, pproperty->get, property->klass, &error);
 -                      mono_error_raise_exception (&error);
 +                      if (mono_error_set_pending_exception (&error))
 +                              return;
                } else {
                        rm = NULL;
                }
                    (((pproperty->set->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) != METHOD_ATTRIBUTE_PRIVATE) ||
                     pproperty->set->klass == property->klass)) {
                        rm =  mono_method_get_object_checked (domain, pproperty->set, property->klass, &error);
 -                      mono_error_raise_exception (&error);
 +                      if (mono_error_set_pending_exception (&error))
 +                              return;
                } else {
                        rm = NULL;
                }
@@@ -2269,14 -2167,12 +2269,14 @@@ ves_icall_MonoEventInfo_get_event_info 
        MonoDomain *domain = mono_object_domain (event); 
  
        rt = mono_type_get_object_checked (domain, &event->klass->byval_arg, &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return;
  
        MONO_STRUCT_SETREF (info, reflected_type, rt);
  
        rt = mono_type_get_object_checked (domain, &event->event->parent->byval_arg, &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return;
  
        MONO_STRUCT_SETREF (info, declaring_type, rt);
  
  
        if (event->event->add) {
                rm = mono_method_get_object_checked (domain, event->event->add, NULL, &error);
 -              mono_error_raise_exception (&error);
 +              if (mono_error_set_pending_exception (&error))
 +                      return;
        } else {
                rm = NULL;
        }
  
        if (event->event->remove) {
                rm = mono_method_get_object_checked (domain, event->event->remove, NULL, &error);
 -              mono_error_raise_exception (&error);
 +              if (mono_error_set_pending_exception (&error))
 +                      return;
        } else {
                rm = NULL;
        }
  
        if (event->event->raise) {
                rm = mono_method_get_object_checked (domain, event->event->raise, NULL, &error);
 -              mono_error_raise_exception (&error);
 +              if (mono_error_set_pending_exception (&error))
 +                      return;
        } else {
                rm = NULL;
        }
                int i, n = 0;
                while (event->event->other [n])
                        n++;
 -              MONO_STRUCT_SETREF (info, other_methods, mono_array_new (domain, mono_defaults.method_info_class, n));
 +              MonoArray *info_arr = mono_array_new_checked (domain, mono_defaults.method_info_class, n, &error);
 +              if (mono_error_set_pending_exception (&error))
 +                      return;
 +              MONO_STRUCT_SETREF (info, other_methods, info_arr);
  
                for (i = 0; i < n; i++) {
                        rm = mono_method_get_object_checked (domain, event->event->other [i], NULL, &error);
 -                      mono_error_raise_exception (&error);
 +                      if (mono_error_set_pending_exception (&error))
 +                              return;
                        mono_array_setref (info->other_methods, i, rm);
                }
        }               
@@@ -2427,17 -2316,12 +2427,17 @@@ ves_icall_Type_GetInterfaces (MonoRefle
        len = g_hash_table_size (iface_hash);
        if (len == 0) {
                g_hash_table_destroy (iface_hash);
 -              if (!data.domain->empty_types)
 -                      data.domain->empty_types = mono_array_new_cached (data.domain, mono_defaults.monotype_class, 0);
 +              if (!data.domain->empty_types) {
 +                      data.domain->empty_types = mono_array_new_cached (data.domain, mono_defaults.monotype_class, 0, &error);
 +                      if (!is_ok (&error))
 +                              goto fail;
 +              }
                return data.domain->empty_types;
        }
  
 -      data.iface_array = mono_array_new_cached (data.domain, mono_defaults.monotype_class, len);
 +      data.iface_array = mono_array_new_cached (data.domain, mono_defaults.monotype_class, len, &error);
 +      if (!is_ok (&error))
 +              goto fail;
        g_hash_table_foreach (iface_hash, fill_iface_array, &data);
        if (!mono_error_ok (&error))
                goto fail;
@@@ -2465,11 -2349,9 +2465,11 @@@ ves_icall_Type_GetInterfaceMapData (Mon
        MonoError error;
  
        mono_class_init_checked (klass, &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return;
        mono_class_init_checked (iclass, &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return;
  
        mono_class_setup_vtable (klass);
  
  
        len = mono_class_num_methods (iclass);
        domain = mono_object_domain (type);
 -      mono_gc_wbarrier_generic_store (targets, (MonoObject*) mono_array_new (domain, mono_defaults.method_info_class, len));
 -      mono_gc_wbarrier_generic_store (methods, (MonoObject*) mono_array_new (domain, mono_defaults.method_info_class, len));
 +      MonoArray *targets_arr = mono_array_new_checked (domain, mono_defaults.method_info_class, len, &error);
 +      if (mono_error_set_pending_exception (&error))
 +              return;
 +      mono_gc_wbarrier_generic_store (targets, (MonoObject*) targets_arr);
 +      MonoArray *methods_arr = mono_array_new_checked (domain, mono_defaults.method_info_class, len, &error);
 +      if (mono_error_set_pending_exception (&error))
 +              return;
 +      mono_gc_wbarrier_generic_store (methods, (MonoObject*) methods_arr);
        iter = NULL;
        while ((method = mono_class_get_methods (iclass, &iter))) {
                member = mono_method_get_object_checked (domain, method, iclass, &error);
 -              mono_error_raise_exception (&error);
 +              if (mono_error_set_pending_exception (&error))
 +                      return;
                mono_array_setref (*methods, i, member);
                member = mono_method_get_object_checked (domain, klass->vtable [i + ioffset], klass, &error);
 -              mono_error_raise_exception (&error);
 +              if (mono_error_set_pending_exception (&error))
 +                      return;
                mono_array_setref (*targets, i, member);
                
                i ++;
@@@ -2509,8 -2383,7 +2509,8 @@@ ves_icall_Type_GetPacking (MonoReflecti
        MonoClass *klass = mono_class_from_mono_type (type->type);
  
        mono_class_init_checked (klass, &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return;
  
        if (image_is_dynamic (klass->image)) {
                MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)type;
@@@ -2530,15 -2403,14 +2530,15 @@@ ves_icall_RuntimeTypeHandle_GetElementT
  
        if (!type->type->byref && type->type->type == MONO_TYPE_SZARRAY) {
                ret = mono_type_get_object_checked (mono_object_domain (type), &type->type->data.klass->byval_arg, &error);
 -              mono_error_raise_exception (&error);
 -
 +              mono_error_set_pending_exception (&error);
                return ret;
        }
  
        klass = mono_class_from_mono_type (type->type);
        mono_class_init_checked (klass, &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
 +
  
        // GetElementType should only return a type for:
        // Array Pointer PassedByRef
        else
                return NULL;
  
 -      mono_error_raise_exception (&error);
 +      mono_error_set_pending_exception (&error);
  
        return ret;
  }
@@@ -2570,7 -2442,7 +2570,7 @@@ ves_icall_RuntimeTypeHandle_GetBaseTyp
                return NULL;
  
        ret = mono_type_get_object_checked (mono_object_domain (type), &klass->parent->byval_arg, &error);
 -      mono_error_raise_exception (&error);
 +      mono_error_set_pending_exception (&error);
  
        return ret;
  }
@@@ -2599,8 -2471,7 +2599,8 @@@ ves_icall_RuntimeTypeHandle_IsComObjec
        MonoError error;
        MonoClass *klass = mono_class_from_mono_type (type->type);
        mono_class_init_checked (klass, &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return FALSE;
  
        return mono_class_is_com_object (klass);
  }
@@@ -2621,7 -2492,8 +2621,7 @@@ ves_icall_RuntimeTypeHandle_GetModule (
        MonoReflectionModule *result = NULL;
        MonoClass *klass = mono_class_from_mono_type (type->type);
        result = mono_module_get_object_checked (mono_object_domain (type), klass->image, &error);
 -      if (!mono_error_ok (&error))
 -              mono_error_set_pending_exception (&error);
 +      mono_error_set_pending_exception (&error);
        return result;
  }
  
@@@ -2632,7 -2504,8 +2632,7 @@@ ves_icall_RuntimeTypeHandle_GetAssembl
        MonoDomain *domain = mono_domain_get (); 
        MonoClass *klass = mono_class_from_mono_type (type->type);
        MonoReflectionAssembly *result = mono_assembly_get_object_checked (domain, klass->image->assembly, &error);
 -      if (!result)
 -              mono_error_set_pending_exception (&error);
 +      mono_error_set_pending_exception (&error);
        return result;
  }
  
@@@ -2660,7 -2533,7 +2660,7 @@@ ves_icall_MonoType_get_DeclaringType (M
                return NULL;
  
        ret = mono_type_get_object_checked (domain, &klass->byval_arg, &error);
 -      mono_error_raise_exception (&error);
 +      mono_error_set_pending_exception (&error);
  
        return ret;
  }
@@@ -2714,9 -2587,11 +2714,9 @@@ ves_icall_RuntimeTypeHandle_GetArrayRan
  }
  
  static MonoArray*
 -create_type_array (MonoDomain *domain, MonoBoolean runtimeTypeArray, int count)
 +create_type_array (MonoDomain *domain, MonoBoolean runtimeTypeArray, int count, MonoError *error)
  {
 -      MonoArray *res;
 -      res = mono_array_new (domain, runtimeTypeArray ? mono_defaults.runtimetype_class : mono_defaults.systemtype_class, count);
 -      return res;
 +      return mono_array_new_checked (domain, runtimeTypeArray ? mono_defaults.runtimetype_class : mono_defaults.systemtype_class, count, error);
  }
  
  ICALL_EXPORT MonoArray*
@@@ -2733,27 -2608,21 +2733,27 @@@ ves_icall_MonoType_GetGenericArguments 
  
        if (klass->generic_container) {
                MonoGenericContainer *container = klass->generic_container;
 -              res = create_type_array (domain, runtimeTypeArray, container->type_argc);
 +              res = create_type_array (domain, runtimeTypeArray, container->type_argc, &error);
 +              if (mono_error_set_pending_exception (&error))
 +                      return NULL;
                for (i = 0; i < container->type_argc; ++i) {
                        pklass = mono_class_from_generic_parameter_internal (mono_generic_container_get_param (container, i));
  
                        rt = mono_type_get_object_checked (domain, &pklass->byval_arg, &error);
 -                      mono_error_raise_exception (&error);
 +                      if (mono_error_set_pending_exception (&error))
 +                              return NULL;
  
                        mono_array_setref (res, i, rt);
                }
        } else if (klass->generic_class) {
                MonoGenericInst *inst = klass->generic_class->context.class_inst;
 -              res = create_type_array (domain, runtimeTypeArray, inst->type_argc);
 +              res = create_type_array (domain, runtimeTypeArray, inst->type_argc, &error);
 +              if (mono_error_set_pending_exception (&error))
 +                      return NULL;
                for (i = 0; i < inst->type_argc; ++i) {
                        rt = mono_type_get_object_checked (domain, inst->type_argv [i], &error);
 -                      mono_error_raise_exception (&error);
 +                      if (mono_error_set_pending_exception (&error))
 +                              return NULL;
  
                        mono_array_setref (res, i, rt);
                }
@@@ -2803,7 -2672,7 +2803,7 @@@ ves_icall_RuntimeTypeHandle_GetGenericT
                        return (MonoReflectionType *)tb;
                else {
                        ret = mono_type_get_object_checked (mono_object_domain (type), &generic_class->byval_arg, &error);
 -                      mono_error_raise_exception (&error);
 +                      mono_error_set_pending_exception (&error);
  
                        return ret;
                }
@@@ -2822,8 -2691,7 +2822,8 @@@ ves_icall_Type_MakeGenericType (MonoRef
  
        g_assert (IS_MONOTYPE (type));
        mono_class_init_checked (mono_class_from_mono_type (type->type), &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
  
        count = mono_array_length (type_array);
        types = g_new0 (MonoType *, count);
                types [i] = t->type;
        }
  
 -      geninst = mono_reflection_bind_generic_parameters (type, count, types);
 +      geninst = mono_reflection_bind_generic_parameters (type, count, types, &error);
        g_free (types);
 -      if (!geninst)
 +      if (!geninst) {
 +              mono_error_set_pending_exception (&error);
                return NULL;
 +      }
  
        klass = mono_class_from_mono_type (geninst);
  
        }
  
        ret = mono_type_get_object_checked (mono_object_domain (type), geninst, &error);
 -      mono_error_raise_exception (&error);
 +      mono_error_set_pending_exception (&error);
  
        return ret;
  }
@@@ -2906,13 -2772,10 +2906,13 @@@ ves_icall_Type_GetGenericParameterConst
        for (count = 0, ptr = param_info->constraints; ptr && *ptr; ptr++, count++)
                ;
  
 -      res = mono_array_new (domain, mono_defaults.monotype_class, count);
 +      res = mono_array_new_checked (domain, mono_defaults.monotype_class, count, &error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
        for (i = 0; i < count; i++) {
                rt = mono_type_get_object_checked (domain, &param_info->constraints [i]->byval_arg, &error);
 -              mono_error_raise_exception (&error);
 +              if (mono_error_set_pending_exception (&error))
 +                      return NULL;
  
                mono_array_setref (res, i, rt);
        }
@@@ -2955,15 -2818,13 +2955,15 @@@ ves_icall_MonoType_GetCorrespondingInfl
  
        klass = mono_class_from_mono_type (type->type);
        mono_class_init_checked (klass, &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
  
        iter = NULL;
        while ((method = mono_class_get_methods (klass, &iter))) {
                  if (method->token == generic->method->token) {
                        ret = mono_method_get_object_checked (domain, method, klass, &error);
 -                      mono_error_raise_exception (&error);
 +                      if (mono_error_set_pending_exception (&error))
 +                              return NULL;
                }
          }
  
@@@ -3133,14 -2994,11 +3133,14 @@@ ves_icall_MonoMethod_GetGenericArgument
  
                if (inst) {
                        count = inst->type_argc;
 -                      res = mono_array_new (domain, mono_defaults.systemtype_class, count);
 +                      res = mono_array_new_checked (domain, mono_defaults.systemtype_class, count, &error);
 +                      if (mono_error_set_pending_exception (&error))
 +                              return NULL;
  
                        for (i = 0; i < count; i++) {
                                rt = mono_type_get_object_checked (domain, inst->type_argv [i], &error);
 -                              mono_error_raise_exception (&error);
 +                              if (mono_error_set_pending_exception (&error))
 +                                      return NULL;
  
                                mono_array_setref (res, i, rt);
                        }
        }
  
        count = mono_method_signature (method->method)->generic_param_count;
 -      res = mono_array_new (domain, mono_defaults.systemtype_class, count);
 +      res = mono_array_new_checked (domain, mono_defaults.systemtype_class, count, &error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
  
        for (i = 0; i < count; i++) {
                MonoGenericContainer *container = mono_method_get_generic_container (method->method);
                MonoClass *pklass = mono_class_from_generic_parameter_internal (param);
  
                rt = mono_type_get_object_checked (domain, &pklass->byval_arg, &error);
 -              mono_error_raise_exception (&error);
 +              if (mono_error_set_pending_exception (&error))
 +                      return NULL;
  
                mono_array_setref (res, i, rt);
        }
@@@ -3186,11 -3041,8 +3186,11 @@@ ves_icall_InternalInvoke (MonoReflectio
  
        *exc = NULL;
  
 -      if (mono_security_core_clr_enabled ())
 -              mono_security_core_clr_ensure_reflection_access_method (m);
 +      if (mono_security_core_clr_enabled () &&
 +          !mono_security_core_clr_ensure_reflection_access_method (m, &error)) {
 +              mono_error_set_pending_exception (&error);
 +              return NULL;
 +      }
  
        if (!(m->flags & METHOD_ATTRIBUTE_STATIC)) {
                if (!mono_class_vtable_full (mono_object_domain (method), m->klass, &error)) {
                }
  
                if (this_arg) {
 -                      if (!mono_object_isinst (this_arg, m->klass)) {
 +                      if (!mono_object_isinst_checked (this_arg, m->klass, &error)) {
 +                              if (!is_ok (&error)) {
 +                                      mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_error_convert_to_exception (&error));
 +                                      return NULL;
 +                              }
                                char *this_name = mono_type_get_full_name (mono_object_get_class (this_arg));
                                char *target_name = mono_type_get_full_name (m->klass);
                                char *msg = g_strdup_printf ("Object of type '%s' doesn't match target type '%s'", this_name, target_name);
  ICALL_EXPORT MonoObject *
  ves_icall_InternalExecute (MonoReflectionMethod *method, MonoObject *this_arg, MonoArray *params, MonoArray **outArgs) 
  {
 +      MonoError error;
        MonoDomain *domain = mono_object_domain (method); 
        MonoMethod *m = method->method;
        MonoMethodSignature *sig = mono_method_signature (m);
                        do {
                                MonoClassField* field = mono_class_get_field_from_name (k, str);
                                if (field) {
 +                                      g_free (str);
                                        MonoClass *field_klass =  mono_class_from_mono_type (field->type);
 -                                      if (field_klass->valuetype)
 -                                              result = mono_value_box (domain, field_klass, (char *)this_arg + field->offset);
 -                                      else 
 +                                      if (field_klass->valuetype) {
 +                                              result = mono_value_box_checked (domain, field_klass, (char *)this_arg + field->offset, &error);
 +                                              if (mono_error_set_pending_exception (&error))
 +                                                      return NULL;
 +                                      } else 
                                                result = (MonoObject *)*((gpointer *)((char *)this_arg + field->offset));
                                
 -                                      out_args = mono_array_new (domain, mono_defaults.object_class, 1);
 +                                      out_args = mono_array_new_checked (domain, mono_defaults.object_class, 1, &error);
 +                                      if (mono_error_set_pending_exception (&error))
 +                                              return NULL;
                                        mono_gc_wbarrier_generic_store (outArgs, (MonoObject*) out_args);
                                        mono_array_setref (out_args, 0, result);
 -                                      g_free (str);
                                        return NULL;
                                }
                                k = k->parent;
                        do {
                                MonoClassField* field = mono_class_get_field_from_name (k, str);
                                if (field) {
 +                                      g_free (str);
                                        MonoClass *field_klass =  mono_class_from_mono_type (field->type);
                                        MonoObject *val = (MonoObject *)mono_array_get (params, gpointer, 2);
  
                                                mono_gc_wbarrier_set_field (this_arg, (char*)this_arg + field->offset, val);
                                        }
                                
 -                                      out_args = mono_array_new (domain, mono_defaults.object_class, 0);
 +                                      out_args = mono_array_new_checked (domain, mono_defaults.object_class, 0, &error);
 +                                      if (mono_error_set_pending_exception (&error))
 +                                              return NULL;
                                        mono_gc_wbarrier_generic_store (outArgs, (MonoObject*) out_args);
  
 -                                      g_free (str);
                                        return NULL;
                                }
                                
                        outarg_count++;
        }
  
 -      out_args = mono_array_new (domain, mono_defaults.object_class, outarg_count);
 -      
 +      out_args = mono_array_new_checked (domain, mono_defaults.object_class, outarg_count, &error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
 +
        /* handle constructors only for objects already allocated */
        if (!strcmp (method->method->name, ".ctor"))
                g_assert (this_arg);
@@@ -3486,8 -3325,7 +3486,8 @@@ write_enum_value (char *mem, int type, 
                break;
        }
        case MONO_TYPE_U2:
 -      case MONO_TYPE_I2: {
 +      case MONO_TYPE_I2:
 +      case MONO_TYPE_CHAR: {
                guint16 *p = (guint16 *)mem;
                *p = value;
                break;
@@@ -3523,14 -3361,12 +3523,14 @@@ ves_icall_System_Enum_ToObject (MonoRef
        enumc = mono_class_from_mono_type (enumType->type);
  
        mono_class_init_checked (enumc, &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
  
        etype = mono_class_enum_basetype (enumc);
  
        res = mono_object_new_checked (domain, enumc, &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
        write_enum_value ((char *)res + sizeof (MonoObject), etype->type, value);
  
        return res;
@@@ -3565,8 -3401,7 +3565,8 @@@ ves_icall_System_Enum_get_value (MonoOb
        
        enumc = mono_class_from_mono_type (mono_class_enum_basetype (eobj->vtable->klass));
        res = mono_object_new_checked (mono_object_domain (eobj), enumc, &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
        dst = (char *)res + sizeof (MonoObject);
        src = (char *)eobj + sizeof (MonoObject);
        size = mono_class_value_size (enumc, NULL);
@@@ -3586,8 -3421,7 +3586,8 @@@ ves_icall_System_Enum_get_underlying_ty
  
        klass = mono_class_from_mono_type (type->type);
        mono_class_init_checked (klass, &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
  
        etype = mono_class_enum_basetype (klass);
        if (!etype) {
        }
  
        ret = mono_type_get_object_checked (mono_object_domain (type), etype, &error);
 -      mono_error_raise_exception (&error);
 +      mono_error_set_pending_exception (&error);
  
        return ret;
  }
@@@ -3700,9 -3534,7 +3700,9 @@@ ves_icall_System_Enum_GetEnumValuesAndN
        gboolean sorted = TRUE;
  
        mono_class_init_checked (enumc, &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return FALSE;
 +
  
        if (!enumc->enumtype) {
                mono_set_pending_exception (mono_get_exception_argument ("enumType", "Type provided must be an Enum."));
        base_type = mono_class_enum_basetype (enumc)->type;
  
        nvalues = mono_class_num_fields (enumc) ? mono_class_num_fields (enumc) - 1 : 0;
 -      *names = mono_array_new (domain, mono_defaults.string_class, nvalues);
 -      *values = mono_array_new (domain, mono_defaults.uint64_class, nvalues);
 +      *names = mono_array_new_checked (domain, mono_defaults.string_class, nvalues, &error);
 +      if (mono_error_set_pending_exception (&error))
 +              return FALSE;
 +      *values = mono_array_new_checked (domain, mono_defaults.uint64_class, nvalues, &error);
 +      if (mono_error_set_pending_exception (&error))
 +              return FALSE;
  
        iter = NULL;
        while ((field = mono_class_get_fields (enumc, &iter))) {
@@@ -3783,11 -3611,8 +3783,11 @@@ ves_icall_Type_GetFields_internal (Mono
        MonoPtrArray tmp_array;
  
        domain = ((MonoObject *)type)->vtable->domain;
 -      if (type->type->byref)
 -              return mono_array_new (domain, mono_defaults.field_info_class, 0);
 +      if (type->type->byref) {
 +              MonoArray *result = mono_array_new_checked (domain, mono_defaults.field_info_class, 0, &error);
 +              mono_error_set_pending_exception (&error);
 +              return result;
 +      }
  
        klass = startklass = mono_class_from_mono_type (type->type);
        refklass = mono_class_from_mono_type (reftype->type);
@@@ -3848,9 -3673,7 +3848,9 @@@ handle_parent
        if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
                goto handle_parent;
  
 -      res = mono_array_new_cached (domain, mono_defaults.field_info_class, mono_ptr_array_size (tmp_array));
 +      res = mono_array_new_cached (domain, mono_defaults.field_info_class, mono_ptr_array_size (tmp_array), &error);
 +      if (!is_ok (&error))
 +              goto fail;
  
        for (i = 0; i < mono_ptr_array_size (tmp_array); ++i)
                mono_array_setref (res, i, mono_ptr_array_get (tmp_array, i));
        return res;
  fail:
        mono_ptr_array_destroy (tmp_array);
 -      mono_error_raise_exception (&error);
 -      g_assert_not_reached ();
 +      mono_error_set_pending_exception (&error);
 +      return NULL;
  }
  
  static gboolean
@@@ -3905,7 -3728,8 +3905,7 @@@ mono_class_get_methods_by_name (MonoCla
        /* An optimization for calls made from Delegate:CreateDelegate () */
        if (klass->delegate && name && !strcmp (name, "Invoke") && (bflags == (BFLAGS_Public | BFLAGS_Static | BFLAGS_Instance))) {
                method = mono_get_delegate_invoke (klass);
 -              if (mono_loader_get_last_error ())
 -                      goto loader_error;
 +              g_assert (method);
  
                g_ptr_array_add (array, method);
                return array;
  
        mono_class_setup_methods (klass);
        mono_class_setup_vtable (klass);
 -      if (mono_class_has_failure (klass) || mono_loader_get_last_error ())
 +      if (mono_class_has_failure (klass))
                goto loader_error;
  
        if (is_generic_parameter (&klass->byval_arg))
  handle_parent:
        mono_class_setup_methods (klass);
        mono_class_setup_vtable (klass);
 -      if (mono_class_has_failure (klass) || mono_loader_get_last_error ())
 +      if (mono_class_has_failure (klass))
                goto loader_error;              
  
        iter = NULL;
@@@ -3989,7 -3813,8 +3989,7 @@@ loader_error
        if (mono_class_has_failure (klass)) {
                *ex = mono_class_get_exception_for_failure (klass);
        } else {
 -              *ex = mono_loader_error_prepare_exception (mono_loader_get_last_error ());
 -              mono_loader_clear_error ();
 +              *ex = mono_get_exception_execution_engine ("Unknown error");
        }
        return NULL;
  }
@@@ -4067,7 -3892,7 +4067,7 @@@ ves_icall_Type_GetConstructors_interna
  {
        MonoDomain *domain; 
        MonoClass *startklass, *klass, *refklass;
 -      MonoArray *res;
 +      MonoArray *res = NULL;
        MonoMethod *method;
        MonoObject *member;
        int i, match;
        MonoPtrArray tmp_array;
        MonoError error;
        
 +      domain = ((MonoObject *)type)->vtable->domain;
 +      if (type->type->byref) {
 +              res = mono_array_new_cached (domain, mono_defaults.method_info_class, 0, &error);
 +              mono_error_set_pending_exception (&error);
 +              return res;
 +      }
 +
        mono_ptr_array_init (tmp_array, 4, MONO_ROOT_SOURCE_REFLECTION, "temporary reflection constructors list"); /*FIXME, guestimating*/
  
 -      domain = ((MonoObject *)type)->vtable->domain;
 -      if (type->type->byref)
 -              return mono_array_new_cached (domain, mono_defaults.method_info_class, 0);
 +
        klass = startklass = mono_class_from_mono_type (type->type);
        refklass = mono_class_from_mono_type (reftype->type);
  
        mono_class_setup_methods (klass);
        if (mono_class_has_failure (klass)) {
                mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
 -              return NULL;
 +              goto leave;
        }
  
        iter = NULL;
                if (!match)
                        continue;
                member = (MonoObject*)mono_method_get_object_checked (domain, method, refklass, &error);
 -              if (!mono_error_ok (&error)) {
 -                      mono_error_set_pending_exception (&error);
 -                      return NULL;
 -              }
 +              if (mono_error_set_pending_exception (&error))
 +                      goto leave;
  
                mono_ptr_array_append (tmp_array, member);
        }
  
 -      res = mono_array_new_cached (domain, mono_class_get_constructor_info_class (), mono_ptr_array_size (tmp_array));
 +      res = mono_array_new_cached (domain, mono_class_get_constructor_info_class (), mono_ptr_array_size (tmp_array), &error);
 +      if (mono_error_set_pending_exception (&error))
 +              goto leave;
  
        for (i = 0; i < mono_ptr_array_size (tmp_array); ++i)
                mono_array_setref (res, i, mono_ptr_array_get (tmp_array, i));
  
 +leave:
        mono_ptr_array_destroy (tmp_array);
  
        return res;
@@@ -4217,15 -4036,11 +4217,15 @@@ ves_icall_Type_GetPropertiesByName (Mon
  
        mono_error_init (&error);
        
 +      domain = ((MonoObject *)type)->vtable->domain;
 +      if (type->type->byref) {
 +              res = mono_array_new_cached (domain, mono_class_get_property_info_class (), 0, &error);
 +              mono_error_set_pending_exception (&error);
 +              return res;
 +      }
 +
        mono_ptr_array_init (tmp_array, 8, MONO_ROOT_SOURCE_REFLECTION, "temporary reflection properties list"); /*This the average for ASP.NET types*/
  
 -      domain = ((MonoObject *)type)->vtable->domain;
 -      if (type->type->byref)
 -              return mono_array_new_cached (domain, mono_class_get_property_info_class (), 0);
        klass = startklass = mono_class_from_mono_type (type->type);
  
        if (name != NULL) {
  handle_parent:
        mono_class_setup_methods (klass);
        mono_class_setup_vtable (klass);
 -      if (mono_class_has_failure (klass) || mono_loader_get_last_error ())
 +      if (mono_class_has_failure (klass))
                goto loader_error;
  
        iter = NULL;
        g_hash_table_destroy (properties);
        g_free (propname);
  
 -      res = mono_array_new_cached (domain, mono_class_get_property_info_class (), mono_ptr_array_size (tmp_array));
 +      res = mono_array_new_cached (domain, mono_class_get_property_info_class (), mono_ptr_array_size (tmp_array), &error);
 +      if (!is_ok (&error))
 +              goto failure;
        for (i = 0; i < mono_ptr_array_size (tmp_array); ++i)
                mono_array_setref (res, i, mono_ptr_array_get (tmp_array, i));
  
  loader_error:
        if (mono_class_has_failure (klass)) {
                mono_error_set_exception_instance (&error, mono_class_get_exception_for_failure (klass));
 -      } else {
 -              mono_error_set_from_loader_error (&error);
 -              mono_loader_clear_error ();
        }
  
  failure:
@@@ -4359,22 -4175,18 +4359,22 @@@ ves_icall_Type_GetEvents_internal (Mono
  
        mono_error_init (&error);
        
 +      domain = mono_object_domain (type);
 +      if (type->type->byref) {
 +              res = mono_array_new_cached (domain, mono_class_get_event_info_class (), 0, &error);
 +              mono_error_set_pending_exception (&error);
 +              return res;
 +      }
 +
        mono_ptr_array_init (tmp_array, 4, MONO_ROOT_SOURCE_REFLECTION, "temporary reflection events list");
  
 -      domain = mono_object_domain (type);
 -      if (type->type->byref)
 -              return mono_array_new_cached (domain, mono_class_get_event_info_class (), 0);
        klass = startklass = mono_class_from_mono_type (type->type);
  
        events = g_hash_table_new (event_hash, (GEqualFunc)event_equal);
  handle_parent:
        mono_class_setup_methods (klass);
        mono_class_setup_vtable (klass);
 -      if (mono_class_has_failure (klass) || mono_loader_get_last_error ())
 +      if (mono_class_has_failure (klass))
                goto loader_error;
  
        iter = NULL;
  
        g_hash_table_destroy (events);
  
 -      res = mono_array_new_cached (domain, mono_class_get_event_info_class (), mono_ptr_array_size (tmp_array));
 +      res = mono_array_new_cached (domain, mono_class_get_event_info_class (), mono_ptr_array_size (tmp_array), &error);
 +      if (!is_ok (&error))
 +              goto failure;
  
        for (i = 0; i < mono_ptr_array_size (tmp_array); ++i)
                mono_array_setref (res, i, mono_ptr_array_get (tmp_array, i));
  loader_error:
        if (mono_class_has_failure (klass)) {
                mono_error_set_exception_instance (&error, mono_class_get_exception_for_failure (klass));
 -      } else {
 -              mono_error_set_from_loader_error (&error);
 -              mono_loader_clear_error ();
        }
  
  failure:
@@@ -4481,21 -4294,16 +4481,21 @@@ ves_icall_Type_GetNestedTypes (MonoRefl
        MonoReflectionType *rt;
        MonoDomain *domain; 
        MonoClass *klass;
 -      MonoArray *res;
 +      MonoArray *res = NULL;
        int i, match;
        MonoClass *nested;
        gpointer iter;
        char *str = NULL;
        MonoPtrArray tmp_array;
  
 +      mono_error_init (&error);
 +
        domain = ((MonoObject *)type)->vtable->domain;
 -      if (type->type->byref)
 -              return mono_array_new (domain, mono_defaults.monotype_class, 0);
 +      if (type->type->byref) {
 +              MonoArray *result = mono_array_new_cached (domain, mono_defaults.monotype_class, 0, &error);
 +              mono_error_set_pending_exception (&error);
 +              return result;
 +      }
        klass = mono_class_from_mono_type (type->type);
  
        /*
                }
  
                rt = mono_type_get_object_checked (domain, &nested->byval_arg, &error);
 -              mono_error_raise_exception (&error);
 +              if (!is_ok (&error))
 +                      goto leave;
  
                mono_ptr_array_append (tmp_array, (MonoObject*) rt);
        }
  
 -      res = mono_array_new_cached (domain, mono_defaults.monotype_class, mono_ptr_array_size (tmp_array));
 +      res = mono_array_new_cached (domain, mono_defaults.monotype_class, mono_ptr_array_size (tmp_array), &error);
 +      if (!is_ok (&error))
 +              goto leave;
  
        for (i = 0; i < mono_ptr_array_size (tmp_array); ++i)
                mono_array_setref (res, i, mono_ptr_array_get (tmp_array, i));
  
 +leave:
        mono_ptr_array_destroy (tmp_array);
  
 -      if (!str)
 -              g_free (str);
 +      g_free (str);
  
 +      mono_error_set_pending_exception (&error);
        return res;
  }
  
@@@ -4598,7 -4402,7 +4598,7 @@@ ves_icall_System_Reflection_Assembly_In
  
        if (module != NULL) {
                if (module->image) {
 -                      type = mono_reflection_get_type_checked (module->image, &info, ignoreCase, &type_resolve, &error);
 +                      type = mono_reflection_get_type_checked (module->image, module->image, &info, ignoreCase, &type_resolve, &error);
                        if (!is_ok (&error)) {
                                g_free (str);
                                mono_reflection_free_type_info (&info);
                        if (abuilder->modules) {
                                for (i = 0; i < mono_array_length (abuilder->modules); ++i) {
                                        MonoReflectionModuleBuilder *mb = mono_array_get (abuilder->modules, MonoReflectionModuleBuilder*, i);
 -                                      type = mono_reflection_get_type_checked (&mb->dynamic_image->image, &info, ignoreCase, &type_resolve, &error);
 +                                      type = mono_reflection_get_type_checked (&mb->dynamic_image->image, &mb->dynamic_image->image, &info, ignoreCase, &type_resolve, &error);
                                        if (!is_ok (&error)) {
                                                g_free (str);
                                                mono_reflection_free_type_info (&info);
                        if (!type && abuilder->loaded_modules) {
                                for (i = 0; i < mono_array_length (abuilder->loaded_modules); ++i) {
                                        MonoReflectionModule *mod = mono_array_get (abuilder->loaded_modules, MonoReflectionModule*, i);
 -                                      type = mono_reflection_get_type_checked (mod->image, &info, ignoreCase, &type_resolve, &error);
 +                                      type = mono_reflection_get_type_checked (mod->image, mod->image, &info, ignoreCase, &type_resolve, &error);
                                        if (!is_ok (&error)) {
                                                g_free (str);
                                                mono_reflection_free_type_info (&info);
                        }
                }
                else {
 -                      type = mono_reflection_get_type_checked (assembly->assembly->image, &info, ignoreCase, &type_resolve, &error);
 +                      type = mono_reflection_get_type_checked (assembly->assembly->image, assembly->assembly->image, &info, ignoreCase, &type_resolve, &error);
                        if (!is_ok (&error)) {
                                g_free (str);
                                mono_reflection_free_type_info (&info);
                if (throwOnError)
                        e = mono_get_exception_type_load (name, NULL);
  
 -              if (mono_loader_get_last_error () && mono_defaults.generic_ilist_class)
 -                      e = mono_loader_error_prepare_exception (mono_loader_get_last_error ());
 -
 -              mono_loader_clear_error ();
 -
                if (e != NULL)
                        mono_set_pending_exception (e);
                return NULL;
 -      } else if (mono_loader_get_last_error ()) {
 -              if (throwOnError) {
 -                      mono_set_pending_exception (mono_loader_error_prepare_exception (mono_loader_get_last_error ()));
 -                      return NULL;
 -              }
 -              mono_loader_clear_error ();
        }
  
        if (type->type == MONO_TYPE_CLASS) {
                if (throwOnError && mono_class_has_failure (klass)) {
                        /* report SecurityException (or others) that occured when loading the assembly */
                        MonoException *exc = mono_class_get_exception_for_failure (klass);
 -                      mono_loader_clear_error ();
                        mono_set_pending_exception (exc);
                        return NULL;
                }
@@@ -4857,11 -4673,8 +4857,11 @@@ ves_icall_System_Reflection_Assembly_Ge
  ICALL_EXPORT MonoArray*
  ves_icall_System_Reflection_Assembly_GetManifestResourceNames (MonoReflectionAssembly *assembly) 
  {
 +      MonoError error;
        MonoTableInfo *table = &assembly->assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
 -      MonoArray *result = mono_array_new (mono_object_domain (assembly), mono_defaults.string_class, table->rows);
 +      MonoArray *result = mono_array_new_checked (mono_object_domain (assembly), mono_defaults.string_class, table->rows, &error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
        int i;
        const char *val;
  
@@@ -4917,10 -4730,7 +4917,10 @@@ ves_icall_System_Reflection_Assembly_Ge
        t = &assembly->assembly->image->tables [MONO_TABLE_ASSEMBLYREF];
        count = t->rows;
  
 -      result = mono_array_new (domain, mono_class_get_assembly_name_class (), count);
 +      result = mono_array_new_checked (domain, mono_class_get_assembly_name_class (), count, &error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
 +
  
        if (count > 0 && !create_culture) {
                MonoMethodDesc *desc = mono_method_desc_new (
  
                aname = (MonoReflectionAssemblyName *) mono_object_new_checked (
                        domain, mono_class_get_assembly_name_class (), &error);
 -              mono_error_raise_exception (&error);
 +              if (mono_error_set_pending_exception (&error))
 +                      return NULL;
  
                MONO_OBJECT_SETREF (aname, name, mono_string_new (domain, mono_metadata_string_heap (image, cols [MONO_ASSEMBLYREF_NAME])));
  
                aname->hashalg = ASSEMBLY_HASH_SHA1; /* SHA1 (default) */
  
                version = create_version (domain, aname->major, aname->minor, aname->build, aname->revision, &error);
 -              mono_error_raise_exception (&error);
 +              if (mono_error_set_pending_exception (&error))
 +                      return NULL;
  
                MONO_OBJECT_SETREF (aname, version, version);
  
                        args [1] = &assembly_ref;
  
                        o = mono_runtime_invoke_checked (create_culture, NULL, args, &error);
 -                      mono_error_raise_exception (&error);
 +                      if (mono_error_set_pending_exception (&error))
 +                              return NULL;
  
                        MONO_OBJECT_SETREF (aname, cultureInfo, o);
                }
                        if ((cols [MONO_ASSEMBLYREF_FLAGS] & ASSEMBLYREF_FULL_PUBLIC_KEY_FLAG)) {
                                /* public key token isn't copied - the class library will 
                                automatically generate it from the public key if required */
 -                              MONO_OBJECT_SETREF (aname, publicKey, mono_array_new (domain, mono_defaults.byte_class, pkey_len));
 -                              memcpy (mono_array_addr (aname->publicKey, guint8, 0), pkey_ptr, pkey_len);
 +                              MonoArray *pkey = mono_array_new_checked (domain, mono_defaults.byte_class, pkey_len, &error);
 +                              if (mono_error_set_pending_exception (&error))
 +                                      return NULL;
 +
 +                              MONO_OBJECT_SETREF (aname, publicKey, pkey);
 +                              memcpy (mono_array_addr (pkey, guint8, 0), pkey_ptr, pkey_len);
                        } else {
 -                              MONO_OBJECT_SETREF (aname, keyToken, mono_array_new (domain, mono_defaults.byte_class, pkey_len));
 -                              memcpy (mono_array_addr (aname->keyToken, guint8, 0), pkey_ptr, pkey_len);
 +                              MonoArray *keyToken = mono_array_new_checked (domain, mono_defaults.byte_class, pkey_len, &error);
 +                              if (mono_error_set_pending_exception (&error))
 +                                      return NULL;
 +
 +                              MONO_OBJECT_SETREF (aname, keyToken, keyToken);
 +                              memcpy (mono_array_addr (keyToken, guint8, 0), pkey_ptr, pkey_len);
                        }
                } else {
 -                      MONO_OBJECT_SETREF (aname, keyToken, mono_array_new (domain, mono_defaults.byte_class, 0));
 +                      MonoArray *keyToken = mono_array_new_checked (domain, mono_defaults.byte_class, 0, &error);
 +                      if (mono_error_set_pending_exception (&error))
 +                              return NULL;
 +
 +                      MONO_OBJECT_SETREF (aname, keyToken, keyToken);
                }
                
                /* note: this function doesn't return the codebase on purpose (i.e. it can
@@@ -5065,8 -4860,7 +5065,8 @@@ ves_icall_System_Reflection_Assembly_Ge
  
        
        MonoReflectionModule *rm = mono_module_get_object_checked (mono_domain_get (), module, &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
        mono_gc_wbarrier_generic_store (ref_module, (MonoObject*) rm);
  
        return (void*)mono_image_get_resource (module, cols [MONO_MANIFEST_OFFSET], (guint32*)size);
@@@ -5146,7 -4940,6 +5146,7 @@@ ves_icall_System_Reflection_Assembly_Ge
  ICALL_EXPORT MonoObject*
  ves_icall_System_Reflection_Assembly_GetFilesInternal (MonoReflectionAssembly *assembly, MonoString *name, MonoBoolean resource_modules) 
  {
 +      MonoError error;
        MonoTableInfo *table = &assembly->assembly->image->tables [MONO_TABLE_FILE];
        MonoArray *result = NULL;
        int i, count;
                        count ++;
        }
  
 -      result = mono_array_new (mono_object_domain (assembly), mono_defaults.string_class, count);
 +      result = mono_array_new_checked (mono_object_domain (assembly), mono_defaults.string_class, count, &error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
 +
  
        count = 0;
        for (i = 0; i < table->rows; ++i) {
@@@ -5224,21 -5014,16 +5224,21 @@@ ves_icall_System_Reflection_Assembly_Ge
                        real_module_count ++;
  
        klass = mono_class_get_module_class ();
 -      res = mono_array_new (domain, klass, 1 + real_module_count + file_count);
 +      res = mono_array_new_checked (domain, klass, 1 + real_module_count + file_count, &error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
  
        MonoReflectionModule *image_obj = mono_module_get_object_checked (domain, image, &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
 +
        mono_array_setref (res, 0, image_obj);
        j = 1;
        for (i = 0; i < module_count; ++i)
                if (modules [i]) {
                        MonoReflectionModule *rm = mono_module_get_object_checked (domain, modules[i], &error);
 -                      mono_error_raise_exception (&error);
 +                      if (mono_error_set_pending_exception (&error))
 +                              return NULL;
                        mono_array_setref (res, j, rm);
                        ++j;
                }
                mono_metadata_decode_row (table, i, cols, MONO_FILE_SIZE);
                if (cols [MONO_FILE_FLAGS] && FILE_CONTAINS_NO_METADATA) {
                        MonoReflectionModule *rm = mono_module_file_get_object_checked (domain, image, i, &error);
 -                      mono_error_raise_exception (&error);
 +                      if (mono_error_set_pending_exception (&error))
 +                              return NULL;
                        mono_array_setref (res, j, rm);
                }
                else {
                                return NULL;
                        }
                        MonoReflectionModule *rm = mono_module_get_object_checked (domain, m, &error);
 -                      mono_error_raise_exception (&error);
 +                      if (mono_error_set_pending_exception (&error))
 +                              return NULL;
                        mono_array_setref (res, j, rm);
                }
        }
@@@ -5285,7 -5068,7 +5285,7 @@@ ves_icall_GetCurrentMethod (void
                m = ((MonoMethodInflated*)m)->declaring;
  
        res = mono_method_get_object_checked (mono_domain_get (), m, NULL, &error);
 -      mono_error_raise_exception (&error);
 +      mono_error_set_pending_exception (&error);
        return res;
  }
  
@@@ -5345,7 -5128,7 +5345,7 @@@ ves_icall_System_Reflection_MethodBase_
        } else
                klass = method->klass;
        res = mono_method_get_object_checked (mono_domain_get (), method, klass, &error);
 -      mono_error_raise_exception (&error);
 +      mono_error_set_pending_exception (&error);
        return res;
  }
  
@@@ -5452,7 -5235,7 +5452,7 @@@ vell_icall_MonoType_get_core_clr_securi
        MonoClass *klass = mono_class_from_mono_type (rfield->type);
  
        mono_class_init_checked (klass, &error);
 -      mono_error_raise_exception (&error);
 +      mono_error_set_pending_exception (&error);
        return mono_security_core_clr_class_level (klass);
  }
  
@@@ -5554,15 -5337,11 +5554,15 @@@ fill_reflection_assembly_name (MonoDoma
                pkey_ptr = (char*)name->public_key;
                pkey_len = mono_metadata_decode_blob_size (pkey_ptr, &pkey_ptr);
  
 -              MONO_OBJECT_SETREF (aname, publicKey, mono_array_new (domain, mono_defaults.byte_class, pkey_len));
 +              MonoArray *pkey = mono_array_new_checked (domain, mono_defaults.byte_class, pkey_len, error);
 +              return_if_nok (error);
 +              MONO_OBJECT_SETREF (aname, publicKey, pkey);
                memcpy (mono_array_addr (aname->publicKey, guint8, 0), pkey_ptr, pkey_len);
                aname->flags |= ASSEMBLYREF_FULL_PUBLIC_KEY_FLAG;
        } else if (default_publickey) {
 -              MONO_OBJECT_SETREF (aname, publicKey, mono_array_new (domain, mono_defaults.byte_class, 0));
 +              MonoArray *pkey = mono_array_new_checked (domain, mono_defaults.byte_class, 0, error);
 +              return_if_nok (error);
 +              MONO_OBJECT_SETREF (aname, publicKey, pkey);
                aname->flags |= ASSEMBLYREF_FULL_PUBLIC_KEY_FLAG;
        }
  
                int i, j;
                char *p;
  
 -              MONO_OBJECT_SETREF (aname, keyToken, mono_array_new (domain, mono_defaults.byte_class, 8));
 -              p = mono_array_addr (aname->keyToken, char, 0);
 +              MonoArray *keyToken = mono_array_new_checked (domain, mono_defaults.byte_class, 8, error);
 +              return_if_nok (error);
 +              
 +              MONO_OBJECT_SETREF (aname, keyToken, keyToken);
 +              p = mono_array_addr (keyToken, char, 0);
  
                for (i = 0, j = 0; i < 8; i++) {
                        *p = g_ascii_xdigit_value (name->public_key_token [j++]) << 4;
                        p++;
                }
        } else if (default_token) {
 -              MONO_OBJECT_SETREF (aname, keyToken, mono_array_new (domain, mono_defaults.byte_class, 0));
 +              MonoArray *keyToken = mono_array_new_checked (domain, mono_defaults.byte_class, 0, error);
 +              return_if_nok (error);
 +              MONO_OBJECT_SETREF (aname, keyToken, keyToken);
        }
  }
  
@@@ -5735,14 -5509,14 +5735,14 @@@ mono_module_get_types (MonoDomain *doma
        } else {
                count = tdef->rows - 1;
        }
 -      res = mono_array_new (domain, mono_defaults.monotype_class, count);
 -      *exceptions = mono_array_new (domain, mono_defaults.exception_class, count);
 +      res = mono_array_new_checked (domain, mono_defaults.monotype_class, count, error);
 +      return_val_if_nok (error, NULL);
 +      *exceptions = mono_array_new_checked (domain, mono_defaults.exception_class, count, error);
 +      return_val_if_nok (error, NULL);
        count = 0;
        for (i = 1; i < tdef->rows; ++i) {
                if (!exportedOnly || mono_module_type_is_visible (tdef, image, i + 1)) {
                        klass = mono_class_get_checked (image, (i + 1) | MONO_TOKEN_TYPE_DEF, error);
 -                      mono_loader_assert_no_error (); /* Plug any leaks */
 -                      mono_error_assert_ok (error);
                        
                        if (klass) {
                                rt = mono_type_get_object_checked (domain, &klass->byval_arg, error);
@@@ -5778,8 -5552,7 +5778,8 @@@ ves_icall_System_Reflection_Assembly_Ge
        image = assembly->assembly->image;
        table = &image->tables [MONO_TABLE_FILE];
        res = mono_module_get_types (domain, image, &exceptions, exportedOnly, &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
  
        /* Append data from all modules in the assembly */
        for (i = 0; i < table->rows; ++i) {
                                MonoArray *res2;
  
                                res2 = mono_module_get_types (domain, loaded_image, &ex2, exportedOnly, &error);
 -                              mono_error_raise_exception (&error);
 +                              if (mono_error_set_pending_exception (&error))
 +                                      return NULL;
 +
  
                                /* Append the new types to the end of the array */
                                if (mono_array_length (res2) > 0) {
                                        len1 = mono_array_length (res);
                                        len2 = mono_array_length (res2);
  
 -                                      res3 = mono_array_new (domain, mono_defaults.monotype_class, len1 + len2);
 +                                      res3 = mono_array_new_checked (domain, mono_defaults.monotype_class, len1 + len2, &error);
 +                                      if (mono_error_set_pending_exception (&error))
 +                                              return NULL;
                                        mono_array_memcpy_refs (res3, 0, res, 0, len1);
                                        mono_array_memcpy_refs (res3, len1, res2, 0, len2);
                                        res = res3;
  
 -                                      ex3 = mono_array_new (domain, mono_defaults.monotype_class, len1 + len2);
 +                                      ex3 = mono_array_new_checked (domain, mono_defaults.monotype_class, len1 + len2, &error);
 +                                      if (mono_error_set_pending_exception (&error))
 +                                              return NULL;
                                        mono_array_memcpy_refs (ex3, 0, exceptions, 0, len1);
                                        mono_array_memcpy_refs (ex3, len1, ex2, 0, len2);
                                        exceptions = ex3;
                MonoArray *exl = NULL;
                int j, length = g_list_length (list) + ex_count;
  
 -              mono_loader_clear_error ();
 -
 -              exl = mono_array_new (domain, mono_defaults.exception_class, length);
 +              exl = mono_array_new_checked (domain, mono_defaults.exception_class, length, &error);
 +              if (mono_error_set_pending_exception (&error)) {
 +                      g_list_free (list);
 +                      return NULL;
 +              }
                /* Types for which mono_class_get_checked () succeeded */
                for (i = 0, tmp = list; tmp; i++, tmp = tmp->next) {
                        MonoException *exc = mono_class_get_exception_for_failure ((MonoClass *)tmp->data);
                        mono_error_set_pending_exception (&error);
                        return NULL;
                }
 -              mono_loader_clear_error ();
                mono_set_pending_exception (exc);
                return NULL;
        }
@@@ -5996,16 -5762,13 +5996,16 @@@ ves_icall_System_Reflection_Module_Inte
        MonoArray *exceptions;
        int i;
  
 -      if (!module->image)
 -              return mono_array_new (mono_object_domain (module), mono_defaults.monotype_class, 0);
 -      else {
 +      if (!module->image) {
 +              MonoArray *arr = mono_array_new_checked (mono_object_domain (module), mono_defaults.monotype_class, 0, &error);
 +              mono_error_set_pending_exception (&error);
 +              return arr;
 +      } else {
                MonoArray *res;
  
                res = mono_module_get_types (mono_object_domain (module), module->image, &exceptions, FALSE, &error);
 -              mono_error_raise_exception (&error);
 +              if (mono_error_set_pending_exception (&error))
 +                      return NULL;
  
                for (i = 0; i < mono_array_length (exceptions); ++i) {
                        MonoException *ex = mono_array_get (exceptions, MonoException *, i);
@@@ -6029,13 -5792,10 +6029,13 @@@ mono_memberref_is_method (MonoImage *im
                mono_metadata_decode_blob_size (sig, &sig);
                return (*sig != 0x6);
        } else {
 +              MonoError error;
                MonoClass *handle_class;
  
 -              if (!mono_lookup_dynamic_token_class (image, token, FALSE, &handle_class, NULL))
 +              if (!mono_lookup_dynamic_token_class (image, token, FALSE, &handle_class, NULL, &error)) {
 +                      mono_error_cleanup (&error); /* just probing, ignore error */
                        return FALSE;
 +              }
  
                return mono_defaults.methodhandle_class == handle_class;
        }
@@@ -6076,14 -5836,12 +6076,14 @@@ ves_icall_System_Reflection_Module_Reso
  
        if (image_is_dynamic (image)) {
                if ((table == MONO_TABLE_TYPEDEF) || (table == MONO_TABLE_TYPEREF)) {
 -                      klass = (MonoClass *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL);
 +                      klass = (MonoClass *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL, &error);
 +                      mono_error_cleanup (&error);
                        return klass ? &klass->byval_arg : NULL;
                }
  
                init_generic_context_from_args (&context, type_args, method_args);
 -              klass = (MonoClass *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, &context);
 +              klass = (MonoClass *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, &context, &error);
 +              mono_error_cleanup (&error);
                return klass ? &klass->byval_arg : NULL;
        }
  
@@@ -6126,11 -5884,8 +6126,11 @@@ ves_icall_System_Reflection_Module_Reso
        }
  
        if (image_is_dynamic (image)) {
 -              if (table == MONO_TABLE_METHOD)
 -                      return (MonoMethod *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL);
 +              if (table == MONO_TABLE_METHOD) {
 +                      method = (MonoMethod *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL, &error);
 +                      mono_error_cleanup (&error);
 +                      return method;
 +              }
  
                if ((table == MONO_TABLE_MEMBERREF) && !(mono_memberref_is_method (image, token))) {
                        *resolve_error = ResolveTokenError_BadTable;
                }
  
                init_generic_context_from_args (&context, type_args, method_args);
 -              return (MonoMethod *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, &context);
 +              method = (MonoMethod *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, &context, &error);
 +              mono_error_cleanup (&error);
 +              return method;
        }
  
        if ((index <= 0) || (index > image->tables [table].rows)) {
  }
  
  ICALL_EXPORT MonoString*
 -ves_icall_System_Reflection_Module_ResolveStringToken (MonoImage *image, guint32 token, MonoResolveTokenError *error)
 +ves_icall_System_Reflection_Module_ResolveStringToken (MonoImage *image, guint32 token, MonoResolveTokenError *resolve_error)
  {
 +      MonoError error;
        int index = mono_metadata_token_index (token);
  
 -      *error = ResolveTokenError_Other;
 +      *resolve_error = ResolveTokenError_Other;
  
        /* Validate token */
        if (mono_metadata_token_code (token) != MONO_TOKEN_STRING) {
 -              *error = ResolveTokenError_BadTable;
 +              *resolve_error = ResolveTokenError_BadTable;
                return NULL;
        }
  
 -      if (image_is_dynamic (image))
 -              return (MonoString *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL);
 +      if (image_is_dynamic (image)) {
 +              MonoString * result = (MonoString *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL, &error);
 +              mono_error_cleanup (&error);
 +              return result;
 +      }
  
        if ((index <= 0) || (index >= image->heap_us.size)) {
 -              *error = ResolveTokenError_OutOfRange;
 +              *resolve_error = ResolveTokenError_OutOfRange;
                return NULL;
        }
  
@@@ -6208,11 -5957,8 +6208,11 @@@ ves_icall_System_Reflection_Module_Reso
        }
  
        if (image_is_dynamic (image)) {
 -              if (table == MONO_TABLE_FIELD)
 -                      return (MonoClassField *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL);
 +              if (table == MONO_TABLE_FIELD) {
 +                      field = (MonoClassField *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL, &error);
 +                      mono_error_cleanup (&error);
 +                      return field;
 +              }
  
                if (mono_memberref_is_method (image, token)) {
                        *resolve_error = ResolveTokenError_BadTable;
                }
  
                init_generic_context_from_args (&context, type_args, method_args);
 -              return (MonoClassField *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, &context);
 +              field = (MonoClassField *)mono_lookup_dynamic_token_class (image, token, FALSE, NULL, &context, &error);
 +              mono_error_cleanup (&error);
 +              return field;
        }
  
        if ((index <= 0) || (index > image->tables [table].rows)) {
@@@ -6258,7 -6002,7 +6258,7 @@@ ves_icall_System_Reflection_Module_Reso
                MonoType *t = ves_icall_System_Reflection_Module_ResolveTypeToken (image, token, type_args, method_args, error);
                if (t) {
                        ret = (MonoObject*) mono_type_get_object_checked (mono_domain_get (), t, &merror);
 -                      mono_error_raise_exception (&merror);
 +                      mono_error_set_pending_exception (&merror);
  
                        return ret;
                }
                MonoMethod *m = ves_icall_System_Reflection_Module_ResolveMethodToken (image, token, type_args, method_args, error);
                if (m) {
                        ret = (MonoObject*)mono_method_get_object_checked (mono_domain_get (), m, m->klass, &merror);
 -                      mono_error_raise_exception (&merror);
 +                      mono_error_set_pending_exception (&merror);
  
                        return ret;
                } else
                MonoClassField *f = ves_icall_System_Reflection_Module_ResolveFieldToken (image, token, type_args, method_args, error);
                if (f) {
                        ret =(MonoObject*)mono_field_get_object_checked (mono_domain_get (), f->parent, f, &merror);
 -                      mono_error_raise_exception (&merror);
 +                      mono_error_set_pending_exception (&merror);
                        return ret;
                }
                else
                        MonoMethod *m = ves_icall_System_Reflection_Module_ResolveMethodToken (image, token, type_args, method_args, error);
                        if (m) {
                                ret = (MonoObject*)mono_method_get_object_checked (mono_domain_get (), m, m->klass, &merror);
 -                              mono_error_raise_exception (&merror);
 +                              mono_error_set_pending_exception (&merror);
  
                                return ret;
                        } else
                        MonoClassField *f = ves_icall_System_Reflection_Module_ResolveFieldToken (image, token, type_args, method_args, error);
                        if (f) {
                                ret = (MonoObject*)mono_field_get_object_checked (mono_domain_get (), f->parent, f, &merror);
 -                              mono_error_raise_exception (&merror);
 +                              mono_error_set_pending_exception (&merror);
                                return ret;
                        }
                        else
  }
  
  ICALL_EXPORT MonoArray*
 -ves_icall_System_Reflection_Module_ResolveSignature (MonoImage *image, guint32 token, MonoResolveTokenError *error)
 +ves_icall_System_Reflection_Module_ResolveSignature (MonoImage *image, guint32 token, MonoResolveTokenError *resolve_error)
  {
 +      MonoError error;
        int table = mono_metadata_token_table (token);
        int idx = mono_metadata_token_index (token);
        MonoTableInfo *tables = image->tables;
        const char *ptr;
        MonoArray *res;
  
 -      *error = ResolveTokenError_OutOfRange;
 +      *resolve_error = ResolveTokenError_OutOfRange;
  
        /* FIXME: Support other tables ? */
        if (table != MONO_TABLE_STANDALONESIG)
        ptr = mono_metadata_blob_heap (image, sig);
        len = mono_metadata_decode_blob_size (ptr, &ptr);
  
 -      res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, len);
 +      res = mono_array_new_checked (mono_domain_get (), mono_defaults.byte_class, len, &error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
        memcpy (mono_array_addr (res, guint8, 0), ptr, len);
        return res;
  }
@@@ -6377,7 -6118,7 +6377,7 @@@ ves_icall_ModuleBuilder_create_modified
                        g_free (str);
  
                        ret = mono_type_get_object_checked (mono_object_domain (tb), &klass->this_arg, &error);
 -                      mono_error_raise_exception (&error);
 +                      mono_error_set_pending_exception (&error);
  
                        return ret;
                case '*':
        g_free (str);
  
        ret = mono_type_get_object_checked (mono_object_domain (tb), &klass->byval_arg, &error);
 -      mono_error_raise_exception (&error);
 +      mono_error_set_pending_exception (&error);
  
        return ret;
  }
@@@ -6458,7 -6199,7 +6458,7 @@@ ves_icall_Type_make_array_type (MonoRef
  
        klass = mono_class_from_mono_type (type->type);
        check_for_invalid_type (klass, &error);
 -      mono_error_raise_exception (&error);
 +      mono_error_set_pending_exception (&error);
  
        if (rank == 0) //single dimentional array
                aklass = mono_array_class_get (klass, 1);
                aklass = mono_bounded_array_class_get (klass, rank, TRUE);
  
        ret = mono_type_get_object_checked (mono_object_domain (type), &aklass->byval_arg, &error);
 -      mono_error_raise_exception (&error);
 +      mono_error_set_pending_exception (&error);
  
        return ret;
  }
@@@ -6480,15 -6221,12 +6480,15 @@@ ves_icall_Type_make_byref_type (MonoRef
  
        klass = mono_class_from_mono_type (type->type);
        mono_class_init_checked (klass, &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
 +
        check_for_invalid_type (klass, &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
  
        ret = mono_type_get_object_checked (mono_object_domain (type), &klass->this_arg, &error);
 -      mono_error_raise_exception (&error);
 +      mono_error_set_pending_exception (&error);
  
        return ret;
  }
@@@ -6502,16 -6240,14 +6502,16 @@@ ves_icall_Type_MakePointerType (MonoRef
  
        klass = mono_class_from_mono_type (type->type);
        mono_class_init_checked (klass, &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
        check_for_invalid_type (klass, &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
  
        pklass = mono_ptr_class_get (type->type);
  
        ret = mono_type_get_object_checked (mono_object_domain (type), &pklass->byval_arg, &error);
 -      mono_error_raise_exception (&error);
 +      mono_error_set_pending_exception (&error);
  
        return ret;
  }
@@@ -6527,31 -6263,17 +6527,31 @@@ ves_icall_System_Delegate_CreateDelegat
        MonoMethod *method = info->method;
  
        mono_class_init_checked (delegate_class, &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
  
 -      mono_assert (delegate_class->parent == mono_defaults.multicastdelegate_class);
 +      if (!(delegate_class->parent == mono_defaults.multicastdelegate_class)) {
 +              /* FIXME improve this exception message */
 +              mono_error_set_execution_engine (&error, "file %s: line %d (%s): assertion failed: (%s)", __FILE__, __LINE__,
 +                                               __func__,
 +                                               "delegate_class->parent == mono_defaults.multicastdelegate_class");
 +              mono_error_set_pending_exception (&error);
 +              return NULL;
 +      }
  
        if (mono_security_core_clr_enabled ()) {
 -              if (!mono_security_core_clr_ensure_delegate_creation (method, throwOnBindFailure))
 +              if (!mono_security_core_clr_ensure_delegate_creation (method, &error)) {
 +                      if (throwOnBindFailure)
 +                              mono_error_set_pending_exception (&error);
 +                      else
 +                              mono_error_cleanup (&error);
                        return NULL;
 +              }
        }
  
        delegate = mono_object_new_checked (mono_object_domain (type), delegate_class, &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
  
        if (method_is_dynamic (method)) {
                /* Creating a trampoline would leak memory */
        } else {
                if (target && method->flags & METHOD_ATTRIBUTE_VIRTUAL && method->klass != mono_object_class (target))
                        method = mono_object_get_virtual_method (target, method);
 -              func = mono_create_ftnptr (mono_domain_get (),
 -                      mono_runtime_create_jump_trampoline (mono_domain_get (), method, TRUE));
 +              gpointer trampoline = mono_runtime_create_jump_trampoline (mono_domain_get (), method, TRUE, &error);
 +              if (mono_error_set_pending_exception (&error))
 +                      return NULL;
 +              func = mono_create_ftnptr (mono_domain_get (), trampoline);
        }
  
        mono_delegate_ctor_with_method (delegate, target, func, method);
@@@ -6579,9 -6299,7 +6579,9 @@@ ves_icall_System_Delegate_AllocDelegate
        g_assert (mono_class_has_parent (mono_object_class (delegate), mono_defaults.multicastdelegate_class));
  
        ret = (MonoMulticastDelegate*) mono_object_new_checked (mono_object_domain (delegate), mono_object_class (delegate), &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
 +
        ret->delegate.invoke_impl = mono_runtime_create_delegate_trampoline (mono_object_class (delegate));
  
        return ret;
@@@ -6593,7 -6311,7 +6593,7 @@@ ves_icall_System_Delegate_GetVirtualMet
        MonoReflectionMethod *ret = NULL;
        MonoError error;
        ret = mono_method_get_object_checked (mono_domain_get (), mono_object_get_virtual_method (delegate->target, delegate->method), mono_object_class (delegate->target), &error);
 -      mono_error_raise_exception (&error);
 +      mono_error_set_pending_exception (&error);
        return ret;
  }
  
@@@ -6703,9 -6421,7 +6703,9 @@@ ves_icall_Remoting_RealProxy_GetTranspa
        MonoClass *klass;
  
        res = mono_object_new_checked (domain, mono_defaults.transparent_proxy_class, &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
 +
        tp = (MonoTransparentProxy*) res;
        
        MONO_OBJECT_SETREF (tp, rp, rp);
                return NULL;
        }
  
 -      tp->custom_type_info = (mono_object_isinst (this_obj, mono_defaults.iremotingtypeinfo_class) != NULL);
 +      tp->custom_type_info = (mono_object_isinst_checked (this_obj, mono_defaults.iremotingtypeinfo_class, &error) != NULL);
 +      if (!is_ok (&error)) {
 +              mono_error_set_pending_exception (&error);
 +              return NULL;
 +      }
        tp->remote_class = mono_remote_class (domain, class_name, klass, &error);
        if (!is_ok (&error)) {
                mono_error_set_pending_exception (&error);
@@@ -6739,7 -6451,7 +6739,7 @@@ ves_icall_Remoting_RealProxy_InternalGe
  {
        MonoError error;
        MonoReflectionType *ret = mono_type_get_object_checked (mono_object_domain (tp), &tp->remote_class->proxy_class->byval_arg, &error);
 -      mono_error_raise_exception (&error);
 +      mono_error_set_pending_exception (&error);
  
        return ret;
  }
@@@ -6770,7 -6482,7 +6770,7 @@@ ves_icall_System_Environment_get_Machin
        if (GetComputerName (buf, (PDWORD) &len)) {
                MonoError error;
                result = mono_string_new_utf16_checked (mono_domain_get (), buf, len, &error);
 -              mono_error_raise_exception (&error);
 +              mono_error_set_pending_exception (&error);
        }
  
        g_free (buf);
@@@ -6897,20 -6609,10 +6897,20 @@@ char **environ
  #endif
  #endif
  
 +ICALL_EXPORT MonoArray *
 +ves_icall_System_Environment_GetCoomandLineArgs (void)
 +{
 +      MonoError error;
 +      MonoArray *result = mono_runtime_get_main_args_checked (&error);
 +      mono_error_set_pending_exception (&error);
 +      return result;
 +}
 +
  ICALL_EXPORT MonoArray *
  ves_icall_System_Environment_GetEnvironmentVariableNames (void)
  {
  #ifdef HOST_WIN32
 +      MonoError error;
        MonoArray *names;
        MonoDomain *domain;
        MonoString *str;
        }
  
        domain = mono_domain_get ();
 -      names = mono_array_new (domain, mono_defaults.string_class, n);
 +      names = mono_array_new_checked (domain, mono_defaults.string_class, n, &error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
  
        if (env_strings) {
                n = 0;
                                g_assert(equal_str);
                                MonoError error;
                                str = mono_string_new_utf16_checked (domain, env_string, equal_str-env_string, &error);
 -                              mono_error_raise_exception (&error);
 +                              if (mono_error_set_pending_exception (&error))
 +                                      return NULL;
 +
                                mono_array_setref (names, n, str);
                                n++;
                        }
        return names;
  
  #else
 +      MonoError error;
        MonoArray *names;
        MonoDomain *domain;
        MonoString *str;
                ++ n;
  
        domain = mono_domain_get ();
 -      names = mono_array_new (domain, mono_defaults.string_class, n);
 +      names = mono_array_new_checked (domain, mono_defaults.string_class, n, &error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
  
        n = 0;
        for (e = environ; *e != 0; ++ e) {
@@@ -7097,7 -6792,7 +7097,7 @@@ ves_icall_System_Environment_GetWindows
                        ++ len;
                MonoError error;
                MonoString *res = mono_string_new_utf16_checked (mono_domain_get (), path, len, &error);
 -              mono_error_raise_exception (&error);
 +              mono_error_set_pending_exception (&error);
                return res;
        }
  #else
@@@ -7142,24 -6837,18 +7142,24 @@@ ves_icall_System_Environment_GetLogical
        } while (*dname);
  
        dname = ptr;
 -      result = mono_array_new (domain, mono_defaults.string_class, ndrives);
 +      result = mono_array_new_checked (domain, mono_defaults.string_class, ndrives, &error);
 +      if (mono_error_set_pending_exception (&error))
 +              goto leave;
 +
        ndrives = 0;
        do {
                len = 0;
                u16 = dname;
                while (*u16) { u16++; len ++; }
                drivestr = mono_string_new_utf16_checked (domain, dname, len, &error);
 -              mono_error_raise_exception (&error);
 +              if (mono_error_set_pending_exception (&error))
 +                      goto leave;
 +
                mono_array_setref (result, ndrives++, drivestr);
                while (*dname++);
        } while (*dname);
  
 +leave:
        if (ptr != buf)
                g_free (ptr);
  
@@@ -7278,6 -6967,14 +7278,14 @@@ ves_icall_System_Environment_BroadcastS
  #endif
  }
  
+ ICALL_EXPORT
+ gint32
+ ves_icall_System_Environment_get_TickCount (void)
+ {
+       /* this will overflow after ~24 days */
+       return (gint32) (mono_msec_boottime () & 0xffffffff);
+ }
  ICALL_EXPORT gint32
  ves_icall_System_Runtime_Versioning_VersioningHelper_GetRuntimeId (void)
  {
@@@ -7323,8 -7020,7 +7331,8 @@@ ves_icall_Remoting_RemotingServices_Get
        method = rmethod->method;
        klass = mono_class_from_mono_type (rtype->type);
        mono_class_init_checked (klass, &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
  
        if (MONO_CLASS_IS_INTERFACE (klass))
                return NULL;
                return NULL;
  
        ret = mono_method_get_object_checked (mono_domain_get (), res, NULL, &error);
 -      mono_error_raise_exception (&error);
 +      mono_error_set_pending_exception (&error);
        return ret;
  }
  
@@@ -7402,8 -7098,7 +7410,8 @@@ ves_icall_System_Runtime_Activation_Act
        domain = mono_object_domain (type);
        klass = mono_class_from_mono_type (type->type);
        mono_class_init_checked (klass, &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
  
        if (MONO_CLASS_IS_INTERFACE (klass) || (klass->flags & TYPE_ATTRIBUTE_ABSTRACT)) {
                mono_set_pending_exception (mono_get_exception_argument ("type", "Type cannot be instantiated"));
  
        if (klass->rank >= 1) {
                g_assert (klass->rank == 1);
 -              return (MonoObject *) mono_array_new (domain, klass->element_class, 0);
 +              ret = (MonoObject *) mono_array_new_checked (domain, klass->element_class, 0, &error);
 +              mono_error_set_pending_exception (&error);
 +              return ret;
        } else {
                MonoVTable *vtable = mono_class_vtable_full (domain, klass, &error);
                if (!is_ok (&error)) {
@@@ -7649,15 -7342,14 +7657,15 @@@ ves_icall_System_Activator_CreateInstan
        domain = mono_object_domain (type);
        klass = mono_class_from_mono_type (type->type);
        mono_class_init_checked (klass, &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return NULL;
  
        if (mono_class_is_nullable (klass))
                /* No arguments -> null */
                return NULL;
  
        result = mono_object_new_checked (domain, klass, &error);
 -      mono_error_raise_exception (&error);
 +      mono_error_set_pending_exception (&error);
        return result;
  }
  
@@@ -7718,6 -7410,7 +7726,6 @@@ ves_icall_MonoMethod_get_base_method (M
                        */
                        MonoGenericContext *parent_inst = NULL;
                        if (mono_class_is_open_constructed_type (mono_class_get_type (parent))) {
 -                              MonoError error;
                                parent = mono_class_inflate_generic_class_checked (parent, generic_inst, &error);
                                if (!mono_error_ok (&error)) {
                                        mono_error_set_pending_exception (&error);
                return m;
  
        ret = mono_method_get_object_checked (mono_domain_get (), result, NULL, &error);
 -      mono_error_raise_exception (&error);
 +      mono_error_set_pending_exception (&error);
        return ret;
  }
  
@@@ -7909,16 -7602,12 +7917,16 @@@ mono_ArgIterator_IntGetNextArgType (Mon
  ICALL_EXPORT MonoObject*
  mono_TypedReference_ToObject (MonoTypedRef* tref)
  {
 +      MonoError error;
 +      MonoObject *result = NULL;
        if (MONO_TYPE_IS_REFERENCE (tref->type)) {
                MonoObject** objp = (MonoObject **)tref->value;
                return *objp;
        }
  
 -      return mono_value_box (mono_domain_get (), tref->klass, tref->value);
 +      result = mono_value_box_checked (mono_domain_get (), tref->klass, tref->value, &error);
 +      mono_error_set_pending_exception (&error);
 +      return result;
  }
  
  ICALL_EXPORT MonoTypedRef
@@@ -7986,7 -7675,7 +7994,7 @@@ ves_icall_System_Runtime_InteropService
        MonoError error;
  
        prelink_method (method->method, &error);
 -      mono_error_raise_exception (&error);
 +      mono_error_set_pending_exception (&error);
  }
  
  ICALL_EXPORT void
@@@ -7998,13 -7687,11 +8006,13 @@@ ves_icall_System_Runtime_InteropService
        gpointer iter = NULL;
  
        mono_class_init_checked (klass, &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return;
  
        while ((m = mono_class_get_methods (klass, &iter))) {
                prelink_method (m, &error);
 -              mono_error_raise_exception (&error);
 +              if (mono_error_set_pending_exception (&error))
 +                      return;
        }
  }
  
@@@ -8043,8 -7730,7 +8051,8 @@@ type_array_from_modifiers (MonoImage *i
        }
        if (!count)
                return NULL;
 -      res = mono_array_new (mono_domain_get (), mono_defaults.systemtype_class, count);
 +      res = mono_array_new_checked (mono_domain_get (), mono_defaults.systemtype_class, count, error);
 +      return_val_if_nok (error, NULL);
        count = 0;
        for (i = 0; i < type->num_mods; ++i) {
                if ((optional && !type->modifiers [i].required) || (!optional && type->modifiers [i].required)) {
@@@ -8100,7 -7786,7 +8108,7 @@@ ves_icall_ParameterInfo_GetTypeModifier
                type = sig->params [pos];
  
        res = type_array_from_modifiers (image, type, optional, &error);
 -      mono_error_raise_exception (&error);
 +      mono_error_set_pending_exception (&error);
        return res;
  }
  
@@@ -8129,7 -7815,7 +8137,7 @@@ ves_icall_MonoPropertyInfo_GetTypeModif
        if (!type)
                return NULL;
        res = type_array_from_modifiers (image, type, optional, &error);
 -      mono_error_raise_exception (&error);
 +      mono_error_set_pending_exception (&error);
        return res;
  }
  
@@@ -8192,8 -7878,7 +8200,8 @@@ custom_attrs_defined_internal (MonoObje
        gboolean found;
  
        mono_class_init_checked (attr_class, &error);
 -      mono_error_raise_exception (&error);
 +      if (mono_error_set_pending_exception (&error))
 +              return FALSE;
  
        cinfo = mono_reflection_get_custom_attrs_info_checked (obj, &error);
        if (!is_ok (&error)) {
@@@ -8217,8 -7902,7 +8225,8 @@@ custom_attrs_get_by_type (MonoObject *o
  
        if (attr_class) {
                mono_class_init_checked (attr_class, &error);
 -              mono_error_raise_exception (&error);
 +              if (mono_error_set_pending_exception (&error))
 +                      return NULL;
        }
  
        res = mono_reflection_get_custom_attrs_by_type (obj, attr_class, &error);
                return NULL;
        }
  
 -      if (mono_loader_get_last_error ()) {
 -              mono_set_pending_exception (mono_loader_error_prepare_exception (mono_loader_get_last_error ()));
 -              return NULL;
 -      } else {
 -              return res;
 -      }
 +      return res;
  }
  
  ICALL_EXPORT MonoArray*
@@@ -8268,13 -7957,26 +8276,13 @@@ ves_icall_System_ComponentModel_Win32Ex
                message = mono_string_new (mono_domain_get (), "Error looking up error string");
        } else {
                message = mono_string_new_utf16_checked (mono_domain_get (), buf, ret, &error);
 -              mono_error_raise_exception (&error);
 +              if (mono_error_set_pending_exception (&error))
 +                      return NULL;
        }
        
        return message;
  }
  
 -ICALL_EXPORT int
 -ves_icall_System_StackFrame_GetILOffsetFromFile (MonoString *path, guint32 method_token, guint32 method_index, int native_offset)
 -{
 -      guint32 il_offset;
 -      char *path_str = mono_string_to_utf8 (path);
 -
 -      if (!mono_seq_point_data_get_il_offset (path_str, method_token, method_index, native_offset, &il_offset))
 -              il_offset = -1;
 -
 -      g_free (path_str);
 -
 -      return il_offset;
 -}
 -
  ICALL_EXPORT gpointer
  ves_icall_Microsoft_Win32_NativeMethods_GetCurrentProcess (void)
  {
diff --combined mono/metadata/monitor.c
index 45c13be4e0f780ed511c327c5c9925ff97626e36,fc7f7b18810ca84844177bc7fd22668f850263fd..510d1c18bcd31b3fcd86556f7ee0cea21b4fe0ef
@@@ -6,7 -6,6 +6,7 @@@
   *
   * Copyright 2003 Ximian, Inc (http://www.ximian.com)
   * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
 + * Licensed under the MIT license. See LICENSE file in the project root for full license information.
   */
  
  #include <config.h>
@@@ -743,7 -742,7 +743,7 @@@ mono_monitor_try_enter_inflated (MonoOb
        LockWord lw;
        MonoThreadsSync *mon;
        HANDLE sem;
-       guint32 then = 0, now, delta;
+       gint64 then = 0, now, delta;
        guint32 waitms;
        guint32 ret;
        guint32 new_status, old_status, tmp_status;
@@@ -900,14 -899,9 +900,9 @@@ retry_contended
                if (!mono_thread_test_state (mono_thread_internal_current (), (MonoThreadState)(ThreadState_StopRequested | ThreadState_SuspendRequested | ThreadState_AbortRequested))) {
                        if (ms != INFINITE) {
                                now = mono_msec_ticks ();
-                               if (now < then) {
-                                       LOCK_DEBUG (g_message ("%s: wrapped around! now=0x%x then=0x%x", __func__, now, then));
  
-                                       now += (0xffffffff - then);
-                                       then = 0;
-                                       LOCK_DEBUG (g_message ("%s: wrap rejig: now=0x%x then=0x%x delta=0x%x", __func__, now, then, now-then));
-                               }
+                               /* it should not overflow before ~30k years */
+                               g_assert (now >= then);
  
                                delta = now - then;
                                if (delta >= ms) {
index 6151395688005d2ba455d7684bfec5f3bdb67d8c,ba3d3efd39370d493c5671c8f1a818677164b9ef..69ade32e593ef5fc5db50665d5924f1069595dcb
@@@ -5,7 -5,6 +5,7 @@@
   *    Ludovic Henry (ludovic.henry@xamarin.com)
   *
   * Copyright 2015 Xamarin, Inc (http://www.xamarin.com)
 + * Licensed under the MIT license. See LICENSE file in the project root for full license information.
   */
  
  //
@@@ -140,10 -139,10 +140,10 @@@ typedef struct 
        MonoCoopMutex worker_creation_lock;
  
        gint32 heuristic_completions;
-       guint32 heuristic_sample_start;
-       guint32 heuristic_last_dequeue; // ms
-       guint32 heuristic_last_adjustment; // ms
-       guint32 heuristic_adjustment_interval; // ms
+       gint64 heuristic_sample_start;
+       gint64 heuristic_last_dequeue; // ms
+       gint64 heuristic_last_adjustment; // ms
+       gint64 heuristic_adjustment_interval; // ms
        ThreadPoolHillClimbing heuristic_hill_climbing;
        MonoCoopMutex heuristic_lock;
  
@@@ -345,16 -344,16 +345,16 @@@ cleanup (void
        mono_coop_mutex_unlock (&threadpool->active_threads_lock);
  }
  
 -void
 -mono_threadpool_ms_enqueue_work_item (MonoDomain *domain, MonoObject *work_item)
 +gboolean
 +mono_threadpool_ms_enqueue_work_item (MonoDomain *domain, MonoObject *work_item, MonoError *error)
  {
        static MonoClass *threadpool_class = NULL;
        static MonoMethod *unsafe_queue_custom_work_item_method = NULL;
 -      MonoError error;
        MonoDomain *current_domain;
        MonoBoolean f;
        gpointer args [2];
  
 +      mono_error_init (error);
        g_assert (work_item);
  
        if (!threadpool_class)
  
        current_domain = mono_domain_get ();
        if (current_domain == domain) {
 -              mono_runtime_invoke_checked (unsafe_queue_custom_work_item_method, NULL, args, &error);
 -              mono_error_raise_exception (&error); /* FIXME don't raise here */
 +              mono_runtime_invoke_checked (unsafe_queue_custom_work_item_method, NULL, args, error);
 +              return_val_if_nok (error, FALSE);
        } else {
                mono_thread_push_appdomain_ref (domain);
                if (mono_domain_set (domain, FALSE)) {
 -                      mono_runtime_invoke_checked (unsafe_queue_custom_work_item_method, NULL, args, &error);
 -                      mono_error_raise_exception (&error); /* FIXME don't raise here */
 +                      mono_runtime_invoke_checked (unsafe_queue_custom_work_item_method, NULL, args, error);
 +                      if (!is_ok (error)) {
 +                              mono_thread_pop_appdomain_ref ();
 +                              return FALSE;
 +                      }
                        mono_domain_set (current_domain, TRUE);
                }
                mono_thread_pop_appdomain_ref ();
        }
 +      return TRUE;
  }
  
  /* LOCKING: threadpool->domains_lock must be held */
@@@ -529,7 -524,7 +529,7 @@@ worker_park (void
                if (interrupted)
                        goto done;
  
 -              if (mono_coop_cond_timedwait (&threadpool->parked_threads_cond, &threadpool->active_threads_lock, rand_next ((void **)rand_handle, 5 * 1000, 60 * 1000)) != 0)
 +              if (mono_coop_cond_timedwait (&threadpool->parked_threads_cond, &threadpool->active_threads_lock, rand_next (&rand_handle, 5 * 1000, 60 * 1000)) != 0)
                        timeout = TRUE;
  
                mono_thread_info_uninstall_interrupt (&interrupted);
@@@ -592,8 -587,7 +592,8 @@@ worker_thread (gpointer data
        thread = mono_thread_internal_current ();
        g_assert (thread);
  
 -      mono_thread_set_name_internal (thread, mono_string_new (mono_domain_get (), "Threadpool worker"), FALSE);
 +      mono_thread_set_name_internal (thread, mono_string_new (mono_get_root_domain (), "Threadpool worker"), FALSE, &error);
 +      mono_error_assert_ok (&error);
  
        mono_coop_mutex_lock (&threadpool->active_threads_lock);
        g_ptr_array_add (threadpool->working_threads, thread);
@@@ -742,8 -736,7 +742,8 @@@ worker_try_create (void
                counter._.active ++;
        });
  
 -      if ((thread = mono_thread_create_internal (mono_get_root_domain (), worker_thread, NULL, TRUE, 0)) != NULL) {
 +      MonoError error;
 +      if ((thread = mono_thread_create_internal (mono_get_root_domain (), worker_thread, NULL, TRUE, 0, &error)) != NULL) {
                threadpool->worker_creation_current_count += 1;
  
                mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker, created %p, now = %d count = %d", mono_native_thread_id_get (), thread->tid, now, threadpool->worker_creation_current_count);
                return TRUE;
        }
  
 -      mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker, failed: could not create thread", mono_native_thread_id_get ());
 +      mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker, failed: could not create thread due to %s", mono_native_thread_id_get (), mono_error_get_message (&error));
 +      mono_error_cleanup (&error);
  
        COUNTER_ATOMIC (counter, {
                counter._.working --;
@@@ -855,7 -847,7 +855,7 @@@ monitor_should_keep_running (void
  static gboolean
  monitor_sufficient_delay_since_last_dequeue (void)
  {
-       guint32 threshold;
+       gint64 threshold;
  
        g_assert (threadpool);
  
@@@ -893,7 -885,7 +893,7 @@@ monitor_thread (void
                mono_gc_set_skip_thread (TRUE);
  
                do {
-                       guint32 ts;
+                       gint64 ts;
                        gboolean alerted = FALSE;
  
                        if (mono_runtime_is_shutting_down ())
  static void
  monitor_ensure_running (void)
  {
 +      MonoError error;
        for (;;) {
                switch (monitor_status) {
                case MONITOR_STATUS_REQUESTED:
                        if (mono_runtime_is_shutting_down ())
                                return;
                        if (InterlockedCompareExchange (&monitor_status, MONITOR_STATUS_REQUESTED, MONITOR_STATUS_NOT_RUNNING) == MONITOR_STATUS_NOT_RUNNING) {
 -                              if (!mono_thread_create_internal (mono_get_root_domain (), monitor_thread, NULL, TRUE, SMALL_STACK))
 +                              if (!mono_thread_create_internal (mono_get_root_domain (), monitor_thread, NULL, TRUE, SMALL_STACK, &error)) {
                                        monitor_status = MONITOR_STATUS_NOT_RUNNING;
 +                                      mono_error_cleanup (&error);
 +                              }
                                return;
                        }
                        break;
@@@ -1052,7 -1041,7 +1052,7 @@@ hill_climbing_get_wave_component (gdoub
  }
  
  static gint16
- hill_climbing_update (gint16 current_thread_count, guint32 sample_duration, gint32 completions, guint32 *adjustment_interval)
+ hill_climbing_update (gint16 current_thread_count, guint32 sample_duration, gint32 completions, gint64 *adjustment_interval)
  {
        ThreadPoolHillClimbing *hc;
        ThreadPoolHeuristicStateTransition transition;
@@@ -1292,8 -1281,8 +1292,8 @@@ heuristic_adjust (void
  
        if (mono_coop_mutex_trylock (&threadpool->heuristic_lock) == 0) {
                gint32 completions = InterlockedExchange (&threadpool->heuristic_completions, 0);
-               guint32 sample_end = mono_msec_ticks ();
-               guint32 sample_duration = sample_end - threadpool->heuristic_sample_start;
+               gint64 sample_end = mono_msec_ticks ();
+               gint64 sample_duration = sample_end - threadpool->heuristic_sample_start;
  
                if (sample_duration >= threadpool->heuristic_adjustment_interval / 2) {
                        ThreadPoolCounter counter;
@@@ -1325,9 -1314,10 +1325,9 @@@ mono_threadpool_ms_cleanup (void
  }
  
  MonoAsyncResult *
 -mono_threadpool_ms_begin_invoke (MonoDomain *domain, MonoObject *target, MonoMethod *method, gpointer *params)
 +mono_threadpool_ms_begin_invoke (MonoDomain *domain, MonoObject *target, MonoMethod *method, gpointer *params, MonoError *error)
  {
        static MonoClass *async_call_klass = NULL;
 -      MonoError error;
        MonoMethodMessage *message;
        MonoAsyncResult *async_result;
        MonoAsyncCall *async_call;
  
        mono_lazy_initialize (&status, initialize);
  
 +      mono_error_init (error);
 +
        message = mono_method_call_message_new (method, params, mono_get_delegate_invoke (method->klass), (params != NULL) ? (&async_callback) : NULL, (params != NULL) ? (&state) : NULL);
  
 -      async_call = (MonoAsyncCall*) mono_object_new_checked (domain, async_call_klass, &error);
 -      mono_error_raise_exception (&error); /* FIXME don't raise here */
 +      async_call = (MonoAsyncCall*) mono_object_new_checked (domain, async_call_klass, error);
 +      return_val_if_nok (error, NULL);
  
        MONO_OBJECT_SETREF (async_call, msg, message);
        MONO_OBJECT_SETREF (async_call, state, state);
        async_result = mono_async_result_new (domain, NULL, async_call->state, NULL, (MonoObject*) async_call);
        MONO_OBJECT_SETREF (async_result, async_delegate, target);
  
 -      mono_threadpool_ms_enqueue_work_item (domain, (MonoObject*) async_result);
 +      mono_threadpool_ms_enqueue_work_item (domain, (MonoObject*) async_result, error);
 +      return_val_if_nok (error, NULL);
  
        return async_result;
  }
  MonoObject *
  mono_threadpool_ms_end_invoke (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
  {
 +      MonoError error;
        MonoAsyncCall *ac;
  
        g_assert (exc);
                } else {
                        wait_event = CreateEvent (NULL, TRUE, FALSE, NULL);
                        g_assert(wait_event);
 -                      MONO_OBJECT_SETREF (ares, handle, (MonoObject*) mono_wait_handle_new (mono_object_domain (ares), wait_event));
 +                      MonoWaitHandle *wait_handle = mono_wait_handle_new (mono_object_domain (ares), wait_event, &error);
 +                      mono_error_raise_exception (&error); /* FIXME don't raise here */
 +                      MONO_OBJECT_SETREF (ares, handle, (MonoObject*) wait_handle);
                }
                mono_monitor_exit ((MonoObject*) ares);
                MONO_PREPARE_BLOCKING;
@@@ -1418,7 -1402,7 +1418,7 @@@ gboolea
  mono_threadpool_ms_remove_domain_jobs (MonoDomain *domain, int timeout)
  {
        gboolean res = TRUE;
-       guint32 start;
+       gint64 end;
        gpointer sem;
  
        g_assert (domain);
        g_assert (mono_domain_is_unloading (domain));
  
        if (timeout != -1)
-               start = mono_msec_ticks ();
+               end = mono_msec_ticks () + timeout;
  
  #ifndef DISABLE_SOCKETS
        mono_threadpool_ms_io_remove_domain_jobs (domain);
        if (timeout != -1) {
-               timeout -= mono_msec_ticks () - start;
-               if (timeout < 0)
+               if (mono_msec_ticks () > end)
                        return FALSE;
        }
  #endif
        mono_memory_write_barrier ();
  
        while (domain->threadpool_jobs) {
-               MONO_PREPARE_BLOCKING;
-               WaitForSingleObject (sem, timeout);
-               MONO_FINISH_BLOCKING;
+               gint64 now;
                if (timeout != -1) {
-                       timeout -= mono_msec_ticks () - start;
-                       if (timeout <= 0) {
+                       now = mono_msec_ticks ();
+                       if (now > end) {
                                res = FALSE;
                                break;
                        }
                }
+               MONO_PREPARE_BLOCKING;
+               WaitForSingleObject (sem, timeout != -1 ? end - now : timeout);
+               MONO_FINISH_BLOCKING;
        }
  
        domain->cleanup_semaphore = NULL;
@@@ -1599,9 -1585,7 +1601,9 @@@ voi
  ves_icall_System_Threading_ThreadPool_ReportThreadStatus (MonoBoolean is_working)
  {
        // TODO
 -      mono_raise_exception (mono_get_exception_not_implemented (NULL));
 +      MonoError error;
 +      mono_error_set_not_implemented (&error, "");
 +      mono_error_set_pending_exception (&error);
  }
  
  MonoBoolean
@@@ -1614,9 -1598,7 +1616,9 @@@ MonoBoolean G_GNUC_UNUSE
  ves_icall_System_Threading_ThreadPool_PostQueuedCompletionStatus (MonoNativeOverlapped *native_overlapped)
  {
        /* This copy the behavior of the current Mono implementation */
 -      mono_raise_exception (mono_get_exception_not_implemented (NULL));
 +      MonoError error;
 +      mono_error_set_not_implemented (&error, "");
 +      mono_error_set_pending_exception (&error);
        return FALSE;
  }
  
diff --combined mono/metadata/threads.c
index b842edbc08f4aef1eabe5deeb5be0f5d93ce4fce,d53f160758820a990d96a8906650537544365912..34f3be0d4887eb48835f6381a8e12e1598e16a6f
@@@ -9,7 -9,6 +9,7 @@@
   * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
   * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
   * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
 + * Licensed under the MIT license. See LICENSE file in the project root for full license information.
   */
  
  #include <config.h>
@@@ -454,9 -453,7 +454,9 @@@ static void thread_cleanup (MonoInterna
        }
        mono_release_type_locks (thread);
  
 -      mono_profiler_thread_end (thread->tid);
 +      /* Can happen when we attach the profiler helper thread in order to heapshot. */
 +      if (!mono_thread_info_lookup (MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid))->tools_thread)
 +              mono_profiler_thread_end (thread->tid);
  
        if (thread == mono_thread_internal_current ()) {
                /*
@@@ -618,25 -615,23 +618,25 @@@ create_internal_thread (MonoError *erro
        return thread;
  }
  
 -static void
 -init_root_domain_thread (MonoInternalThread *thread, MonoThread *candidate)
 +static gboolean
 +init_root_domain_thread (MonoInternalThread *thread, MonoThread *candidate, MonoError *error)
  {
 -      MonoError error;
        MonoDomain *domain = mono_get_root_domain ();
  
 +      mono_error_init (error);
        if (!candidate || candidate->obj.vtable->domain != domain) {
 -              candidate = new_thread_with_internal (domain, thread, &error);
 -              mono_error_raise_exception (&error); /* FIXME don't raise here */
 +              candidate = new_thread_with_internal (domain, thread, error);
 +              return_val_if_nok (error, FALSE);
        }
        set_current_thread_for_domain (domain, thread, candidate);
        g_assert (!thread->root_domain_thread);
        MONO_OBJECT_SETREF (thread, root_domain_thread, candidate);
 +      return TRUE;
  }
  
  static guint32 WINAPI start_wrapper_internal(void *data)
  {
 +      MonoError error;
        MonoThreadInfo *info;
        StartInfo *start_info = (StartInfo *)data;
        guint32 (*start_func)(void *);
        /* We have to do this here because mono_thread_new_init()
           requires that root_domain_thread is set up. */
        thread_adjust_static_data (internal);
 -      init_root_domain_thread (internal, start_info->obj);
 +      init_root_domain_thread (internal, start_info->obj, &error);
 +      mono_error_raise_exception (&error); /* FIXME don't raise here */
  
        /* This MUST be called before any managed code can be
         * executed, as it calls the callback function that (for the
        if (internal->name && (internal->flags & MONO_THREAD_FLAG_NAME_SET)) {
                char *tname = g_utf16_to_utf8 (internal->name, internal->name_len, NULL, NULL, NULL);
                mono_profiler_thread_name (internal->tid, tname);
 +              mono_thread_info_set_name (MONO_UINT_TO_NATIVE_THREAD_ID (internal->tid), tname);
                g_free (tname);
        }
        /* start_func is set only for unmanaged start functions */
@@@ -793,7 -786,7 +793,7 @@@ static guint32 WINAPI start_wrapper(voi
   */
  static gboolean
  create_thread (MonoThread *thread, MonoInternalThread *internal, StartInfo *start_info, gboolean threadpool_thread, guint32 stack_size,
 -                         gboolean throw_on_failure)
 +                         MonoError *error)
  {
        HANDLE thread_handle;
        MonoNativeThreadId tid;
         */
        mono_threads_join_threads ();
  
 +      mono_error_init (error);
 +
        mono_threads_lock ();
        if (shutting_down) {
                g_free (start_info);
                                                                                                stack_size, create_flags, &tid);
  
        if (thread_handle == NULL) {
 -              /* The thread couldn't be created, so throw an exception */
 +              /* The thread couldn't be created, so set an exception */
                mono_threads_lock ();
                mono_g_hash_table_remove (threads_starting_up, thread);
                mono_threads_unlock ();
                g_free (start_info);
 -              if (throw_on_failure)
 -                      mono_raise_exception (mono_get_exception_execution_engine ("Couldn't create thread"));
 -              else
 -                      g_warning ("%s: CreateThread error 0x%x", __func__, GetLastError ());
 +              mono_error_set_execution_engine (error, "Couldn't create thread. Error 0x%x", GetLastError());
                return FALSE;
        }
        THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
@@@ -915,20 -909,19 +915,20 @@@ guint32 mono_threads_get_default_stacks
   *   ARG should not be a GC reference.
   */
  MonoInternalThread*
 -mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, gboolean threadpool_thread, guint32 stack_size)
 +mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, gboolean threadpool_thread, guint32 stack_size, MonoError *error)
  {
 -      MonoError error;
        MonoThread *thread;
        MonoInternalThread *internal;
        StartInfo *start_info;
        gboolean res;
  
 -      thread = create_thread_object (domain, &error);
 -      mono_error_raise_exception (&error); /* FIXME don't raise here */
 +      mono_error_init (error);
  
 -      internal = create_internal_thread (&error);
 -      mono_error_raise_exception (&error); /* FIXME don't raise here */
 +      thread = create_thread_object (domain, error);
 +      return_val_if_nok (error, NULL);
 +
 +      internal = create_internal_thread (error);
 +      return_val_if_nok (error, NULL);
  
        MONO_OBJECT_SETREF (thread, internal_thread, internal);
  
        start_info->obj = thread;
        start_info->start_arg = arg;
  
 -      res = create_thread (thread, internal, start_info, threadpool_thread, stack_size, TRUE);
 -      if (!res)
 -              return NULL;
 +      res = create_thread (thread, internal, start_info, threadpool_thread, stack_size, error);
 +      return_val_if_nok (error, NULL);
  
        /* Check that the managed and unmanaged layout of MonoInternalThread matches */
  #ifndef MONO_CROSS_COMPILE
  void
  mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
  {
 -      mono_thread_create_internal (domain, func, arg, FALSE, 0);
 +      MonoError error;
 +      if (!mono_thread_create_checked (domain, func, arg, &error))
 +              mono_error_cleanup (&error);
 +}
 +
 +gboolean
 +mono_thread_create_checked (MonoDomain *domain, gpointer func, gpointer arg, MonoError *error)
 +{
 +      return (NULL != mono_thread_create_internal (domain, func, arg, FALSE, 0, error));
  }
  
  MonoThread *
@@@ -1032,9 -1018,7 +1032,9 @@@ mono_thread_attach_full (MonoDomain *do
  
        thread_adjust_static_data (thread);
  
 -      init_root_domain_thread (thread, current_thread);
 +      init_root_domain_thread (thread, current_thread, error);
 +      return_val_if_nok (error, NULL);
 +
        if (domain != mono_get_root_domain ())
                set_current_thread_for_domain (domain, thread, current_thread);
  
                        mono_thread_attach_cb (MONO_NATIVE_THREAD_ID_TO_UINT (tid), staddr + stsize);
        }
  
 -      // FIXME: Need a separate callback
 -      mono_profiler_thread_start (MONO_NATIVE_THREAD_ID_TO_UINT (tid));
 +      /* Can happen when we attach the profiler helper thread in order to heapshot. */
 +      if (!info->tools_thread)
 +              // FIXME: Need a separate callback
 +              mono_profiler_thread_start (MONO_NATIVE_THREAD_ID_TO_UINT (tid));
  
        return current_thread;
  }
@@@ -1140,7 -1122,6 +1140,7 @@@ HANDL
  ves_icall_System_Threading_Thread_Thread_internal (MonoThread *this_obj,
                                                                                                   MonoObject *start)
  {
 +      MonoError error;
        StartInfo *start_info;
        MonoInternalThread *internal;
        gboolean res;
        start_info->obj = this_obj;
        g_assert (this_obj->obj.vtable->domain == mono_domain_get ());
  
 -      res = create_thread (this_obj, internal, start_info, FALSE, 0, FALSE);
 +      res = create_thread (this_obj, internal, start_info, FALSE, 0, &error);
        if (!res) {
 +              mono_error_cleanup (&error);
                UNLOCK_THREAD (internal);
                return NULL;
        }
@@@ -1364,16 -1344,14 +1364,16 @@@ ves_icall_System_Threading_Thread_GetNa
  }
  
  void 
 -mono_thread_set_name_internal (MonoInternalThread *this_obj, MonoString *name, gboolean managed)
 +mono_thread_set_name_internal (MonoInternalThread *this_obj, MonoString *name, gboolean managed, MonoError *error)
  {
        LOCK_THREAD (this_obj);
  
 +      mono_error_init (error);
 +
        if ((this_obj->flags & MONO_THREAD_FLAG_NAME_SET) && !this_obj->threadpool_thread) {
                UNLOCK_THREAD (this_obj);
                
 -              mono_raise_exception (mono_get_exception_invalid_operation ("Thread.Name can only be set once."));
 +              mono_error_set_invalid_operation (error, "Thread.Name can only be set once.");
                return;
        }
        if (this_obj->name) {
  void 
  ves_icall_System_Threading_Thread_SetName_internal (MonoInternalThread *this_obj, MonoString *name)
  {
 -      mono_thread_set_name_internal (this_obj, name, TRUE);
 +      MonoError error;
 +      mono_thread_set_name_internal (this_obj, name, TRUE, &error);
 +      mono_error_set_pending_exception (&error);
  }
  
  /*
@@@ -1448,18 -1424,17 +1448,18 @@@ ves_icall_System_Threading_Thread_SetPr
  /* If the array is already in the requested domain, we just return it,
     otherwise we return a copy in that domain. */
  static MonoArray*
 -byte_array_to_domain (MonoArray *arr, MonoDomain *domain)
 +byte_array_to_domain (MonoArray *arr, MonoDomain *domain, MonoError *error)
  {
        MonoArray *copy;
  
 +      mono_error_init (error);
        if (!arr)
                return NULL;
  
        if (mono_object_domain (arr) == domain)
                return arr;
  
 -      copy = mono_array_new (domain, mono_defaults.byte_class, arr->max_length);
 +      copy = mono_array_new_checked (domain, mono_defaults.byte_class, arr->max_length, error);
        memmove (mono_array_addr (copy, guint8, 0), mono_array_addr (arr, guint8, 0), arr->max_length);
        return copy;
  }
  MonoArray*
  ves_icall_System_Threading_Thread_ByteArrayToRootDomain (MonoArray *arr)
  {
 -      return byte_array_to_domain (arr, mono_get_root_domain ());
 +      MonoError error;
 +      MonoArray *result = byte_array_to_domain (arr, mono_get_root_domain (), &error);
 +      mono_error_set_pending_exception (&error);
 +      return result;
  }
  
  MonoArray*
  ves_icall_System_Threading_Thread_ByteArrayToCurrentDomain (MonoArray *arr)
  {
 -      return byte_array_to_domain (arr, mono_domain_get ());
 +      MonoError error;
 +      MonoArray *result = byte_array_to_domain (arr, mono_domain_get (), &error);
 +      mono_error_set_pending_exception (&error);
 +      return result;
  }
  
  MonoThread *
@@@ -1613,7 -1582,8 +1613,7 @@@ mono_wait_uninterrupted (MonoInternalTh
        return ret;
  }
  
 -/* FIXME: exitContext isnt documented */
 -gint32 ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
 +gint32 ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms)
  {
        HANDLE *handles;
        guint32 numhandles;
  
        g_free(handles);
  
 -      return ret;
 +      /* WAIT_FAILED in waithandle.cs is different from WAIT_FAILED in Win32 API */
 +      return ret == WAIT_FAILED ? 0x7fffffff : ret;
  }
  
 -/* FIXME: exitContext isnt documented */
 -gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext)
 +gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms)
  {
        HANDLE handles [MAXIMUM_WAIT_OBJECTS];
        uintptr_t numhandles;
                return ret - WAIT_ABANDONED_0;
        }
        else {
 -              return ret;
 +              /* WAIT_FAILED in waithandle.cs is different from WAIT_FAILED in Win32 API */
 +              return ret == WAIT_FAILED ? 0x7fffffff : ret;
        }
  }
  
 -/* FIXME: exitContext isnt documented */
 -gint32 ves_icall_System_Threading_WaitHandle_WaitOne_internal(HANDLE handle, gint32 ms, gboolean exitContext)
 +gint32 ves_icall_System_Threading_WaitHandle_WaitOne_internal(HANDLE handle, gint32 ms)
  {
        guint32 ret;
        MonoInternalThread *thread = mono_thread_internal_current ();
        
        mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
        
 -      return ret;
 +      /* WAIT_FAILED in waithandle.cs is different from WAIT_FAILED in Win32 API */
 +      return ret == WAIT_FAILED ? 0x7fffffff : ret;
  }
  
  gint32
 -ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (HANDLE toSignal, HANDLE toWait, gint32 ms, gboolean exitContext)
 +ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (HANDLE toSignal, HANDLE toWait, gint32 ms)
  {
        guint32 ret;
        MonoInternalThread *thread = mono_thread_internal_current ();
        
        mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
  
 -      return ret;
 +      /* WAIT_FAILED in waithandle.cs is different from WAIT_FAILED in Win32 API */
 +      return ret == WAIT_FAILED ? 0x7fffffff : ret;
  }
  
  HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
@@@ -2284,9 -2252,8 +2284,9 @@@ mono_thread_internal_reset_abort (MonoI
  MonoObject*
  ves_icall_System_Threading_Thread_GetAbortExceptionState (MonoThread *this_obj)
  {
 +      MonoError error;
        MonoInternalThread *thread = this_obj->internal_thread;
 -      MonoObject *state, *deserialized = NULL, *exc;
 +      MonoObject *state, *deserialized = NULL;
        MonoDomain *domain;
  
        if (!thread->abort_state_handle)
        if (mono_object_domain (state) == domain)
                return state;
  
 -      deserialized = mono_object_xdomain_representation (state, domain, &exc);
 +      deserialized = mono_object_xdomain_representation (state, domain, &error);
  
        if (!deserialized) {
                MonoException *invalid_op_exc = mono_get_exception_invalid_operation ("Thread.ExceptionState cannot access an ExceptionState from a different AppDomain");
 -              if (exc)
 +              if (!is_ok (&error)) {
 +                      MonoObject *exc = (MonoObject*)mono_error_convert_to_exception (&error);
                        MONO_OBJECT_SETREF (invalid_op_exc, inner_ex, exc);
 +              }
                mono_set_pending_exception (invalid_op_exc);
                return NULL;
        }
@@@ -3543,12 -3508,8 +3543,12 @@@ mono_threads_get_thread_dump (MonoArra
        ud.frames = g_new0 (MonoStackFrameInfo, 256);
        ud.max_frames = 256;
  
 -      *out_threads = mono_array_new (domain, mono_defaults.thread_class, nthreads);
 -      *out_stack_frames = mono_array_new (domain, mono_defaults.array_class, nthreads);
 +      *out_threads = mono_array_new_checked (domain, mono_defaults.thread_class, nthreads, &error);
 +      if (!is_ok (&error))
 +              goto leave;
 +      *out_stack_frames = mono_array_new_checked (domain, mono_defaults.array_class, nthreads, &error);
 +      if (!is_ok (&error))
 +              goto leave;
  
        for (tindex = 0; tindex < nthreads; ++tindex) {
                MonoInternalThread *thread = thread_array [tindex];
  
                mono_array_setref_fast (*out_threads, tindex, mono_thread_current_for_thread (thread));
  
 -              thread_frames = mono_array_new (domain, mono_defaults.stack_frame_class, ud.nframes);
 +              thread_frames = mono_array_new_checked (domain, mono_defaults.stack_frame_class, ud.nframes, &error);
 +              if (!is_ok (&error))
 +                      goto leave;
                mono_array_setref_fast (*out_stack_frames, tindex, thread_frames);
  
                for (i = 0; i < ud.nframes; ++i) {
@@@ -3790,7 -3749,7 +3790,7 @@@ mono_threads_abort_appdomain_threads (M
  #endif
  
        abort_appdomain_data user_data;
-       guint32 start_time;
+       gint64 start_time;
        int orig_timeout = timeout;
        int i;
  
index 5b05e57c90e39af906a32a24d9f876a0e900d337,e9bdc72ad4607f2a3cb80ece48c7bdbb583e0d7e..8c4d16aa4f27b4a3fb88d33e64e4e858d048365e
@@@ -6,7 -6,6 +6,7 @@@
   *
   * Copyright 2009-2010 Novell, Inc.
   * Copyright 2011 Xamarin Inc.
 + * Licensed under the MIT license. See LICENSE file in the project root for full license information.
   */
  
  #include <config.h>
@@@ -1120,8 -1119,8 +1120,8 @@@ socket_transport_recv (void *buf, int l
        int total = 0;
        int fd = conn_fd;
        int flags = 0;
-       static gint32 last_keepalive;
-       gint32 msecs;
+       static gint64 last_keepalive;
+       gint64 msecs;
  
        MONO_PREPARE_BLOCKING;
  
@@@ -6032,7 -6031,6 +6032,7 @@@ decode_value_internal (MonoType *t, in
                        } else if (type == VALUE_TYPE_ID_NULL) {
                                *(MonoObject**)addr = NULL;
                        } else if (type == MONO_TYPE_VALUETYPE) {
 +                              MonoError error;
                                guint8 *buf2;
                                gboolean is_enum;
                                MonoClass *klass;
                                        g_free (vtype_buf);
                                        return err;
                                }
 -                              *(MonoObject**)addr = mono_value_box (d, klass, vtype_buf);
 +                              *(MonoObject**)addr = mono_value_box_checked (d, klass, vtype_buf, &error);
 +                              mono_error_cleanup (&error);
                                g_free (vtype_buf);
                        } else {
                                char *name = mono_type_full_name (t);
  static ErrorCode
  decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
  {
 +      MonoError error;
        ErrorCode err;
        int type = decode_byte (buf, &buf, limit);
  
                                g_free (nullable_buf);
                                return err;
                        }
 -                      mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
 +                      MonoObject *boxed = mono_value_box_checked (domain, mono_class_from_mono_type (targ), nullable_buf, &error);
 +                      if (!is_ok (&error)) {
 +                              mono_error_cleanup (&error);
 +                              return ERR_INVALID_OBJECT;
 +                      }
 +                      mono_nullable_init (addr, boxed, mono_class_from_mono_type (t));
                        g_free (nullable_buf);
                        *endbuf = buf;
                        return ERR_NONE;
@@@ -7258,7 -7249,7 +7258,7 @@@ vm_commands (int command, int id, guint
                                        MonoError error;
                                        type_resolve = TRUE;
                                        /* FIXME really okay to call while holding locks? */
 -                                      t = mono_reflection_get_type_checked (ass->image, &info, ignore_case, &type_resolve, &error);
 +                                      t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignore_case, &type_resolve, &error);
                                        mono_error_cleanup (&error); 
                                        if (t) {
                                                g_ptr_array_add (res_classes, mono_type_get_class (t));
@@@ -7692,7 -7683,7 +7692,7 @@@ assembly_commands (int command, guint8 
                } else {
                        if (info.assembly.name)
                                NOT_IMPLEMENTED;
 -                      t = mono_reflection_get_type_checked (ass->image, &info, ignorecase, &type_resolve, &error);
 +                      t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignorecase, &type_resolve, &error);
                        if (!is_ok (&error)) {
                                mono_error_cleanup (&error); /* FIXME don't swallow the error */
                                mono_reflection_free_type_info (&info);
@@@ -9255,7 -9246,6 +9255,7 @@@ string_commands (int command, guint8 *p
  static ErrorCode
  object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
  {
 +      MonoError error;
        int objid;
        ErrorCode err;
        MonoObject *obj;
  
                                if (remote_obj) {
  #ifndef DISABLE_REMOTING
 -                                      field_value = mono_load_remote_field(obj, obj_type, f, &field_storage);
 +                                      field_value = mono_load_remote_field_checked(obj, obj_type, f, &field_storage, &error);
 +                                      if (!is_ok (&error)) {
 +                                              mono_error_cleanup (&error); /* FIXME report the error */
 +                                              return ERR_INVALID_OBJECT;
 +                                      }
  #else
                                        g_assert_not_reached ();
  #endif
@@@ -9680,7 -9666,6 +9680,7 @@@ wait_for_attach (void
  static guint32 WINAPI
  debugger_thread (void *arg)
  {
 +      MonoError error;
        int res, len, id, flags, command = 0;
        CommandSet command_set = (CommandSet)0;
        guint8 header [HEADER_LENGTH];
        debugger_thread_id = mono_native_thread_id_get ();
  
        attach_cookie = mono_jit_thread_attach (mono_get_root_domain (), &attach_dummy);
 +      MonoInternalThread *thread = mono_thread_internal_current ();
 +      mono_thread_set_name_internal (thread, mono_string_new (mono_get_root_domain (), "Debugger agent"), TRUE, &error);
 +      mono_error_assert_ok (&error);
  
 -      mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
 +      thread->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
  
        mono_set_is_debugger_attached (TRUE);
        
index 7a4a02e39a3f7fea5ca4a441251215d75d406bf8,9b8585a392afdda7bca558220f32fb24d81dbcf5..efd732d6d56b7592b9de709a4d34c352e42baf8f
@@@ -1,7 -1,6 +1,7 @@@
  /*
   * Copyright 2008-2011 Novell Inc
   * Copyright 2011 Xamarin Inc
 + * Licensed under the MIT license. See LICENSE file in the project root for full license information.
   */
  
  #include "config.h"
@@@ -27,7 -26,6 +27,7 @@@
  #if defined(_POSIX_VERSION)
  #include <sys/errno.h>
  #include <sys/param.h>
 +#include <errno.h>
  #ifdef HAVE_SYS_TYPES_H
  #include <sys/types.h>
  #endif
@@@ -325,7 -323,7 +325,7 @@@ mono_process_get_times (gpointer pid, g
                if (*start_time == 0) {
                        static guint64 boot_time = 0;
                        if (!boot_time)
-                               boot_time = mono_100ns_datetime () - ((guint64)mono_msec_ticks ()) * 10000;
+                               boot_time = mono_100ns_datetime () - mono_msec_boottime () * 10000;
  
                        *start_time = boot_time + mono_process_get_data (pid, MONO_PROCESS_ELAPSED);
                }
@@@ -356,35 -354,22 +356,35 @@@ get_process_stat_item (int pid, int pos
        mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT, th_count;
        thread_array_t th_array;
        size_t i;
 +      kern_return_t ret;
  
        if (pid == getpid ()) {
                /* task_for_pid () doesn't work on ios, even for the current process */
                task = mach_task_self ();
        } else {
 -              if (task_for_pid (mach_task_self (), pid, &task) != KERN_SUCCESS)
 +              do {
 +                      ret = task_for_pid (mach_task_self (), pid, &task);
 +              } while (ret == KERN_ABORTED);
 +
 +              if (ret != KERN_SUCCESS)
                        RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
        }
  
 -      if (task_info (task, TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count) != KERN_SUCCESS) {
 +      do {
 +              ret = task_info (task, TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count);
 +      } while (ret == KERN_ABORTED);
 +
 +      if (ret != KERN_SUCCESS) {
                if (pid != getpid ())
                        mach_port_deallocate (mach_task_self (), task);
                RET_ERROR (MONO_PROCESS_ERROR_OTHER);
        }
 +
 +      do {
 +              ret = task_threads (task, &th_array, &th_count);
 +      } while (ret == KERN_ABORTED);
        
 -      if (task_threads(task, &th_array, &th_count) != KERN_SUCCESS) {
 +      if (ret  != KERN_SUCCESS) {
                if (pid != getpid ())
                        mach_port_deallocate (mach_task_self (), task);
                RET_ERROR (MONO_PROCESS_ERROR_OTHER);
                
                struct thread_basic_info th_info;
                mach_msg_type_number_t th_info_count = THREAD_BASIC_INFO_COUNT;
 -              if (thread_info(th_array[i], THREAD_BASIC_INFO, (thread_info_t)&th_info, &th_info_count) == KERN_SUCCESS) {
 +              do {
 +                      ret = thread_info(th_array[i], THREAD_BASIC_INFO, (thread_info_t)&th_info, &th_info_count);
 +              } while (ret == KERN_ABORTED);
 +
 +              if (ret == KERN_SUCCESS) {
                        thread_user_time = th_info.user_time.seconds + th_info.user_time.microseconds / 1e6;
                        thread_system_time = th_info.system_time.seconds + th_info.system_time.microseconds / 1e6;
                        //thread_percent = (double)th_info.cpu_usage / TH_USAGE_SCALE;
@@@ -512,25 -493,16 +512,25 @@@ get_pid_status_item (int pid, const cha
        task_t task;
        struct task_basic_info t_info;
        mach_msg_type_number_t th_count = TASK_BASIC_INFO_COUNT;
 +      kern_return_t mach_ret;
  
        if (pid == getpid ()) {
                /* task_for_pid () doesn't work on ios, even for the current process */
                task = mach_task_self ();
        } else {
 -              if (task_for_pid (mach_task_self (), pid, &task) != KERN_SUCCESS)
 +              do {
 +                      mach_ret = task_for_pid (mach_task_self (), pid, &task);
 +              } while (mach_ret == KERN_ABORTED);
 +
 +              if (mach_ret != KERN_SUCCESS)
                        RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
        }
 -      
 -      if (task_info (task, TASK_BASIC_INFO, (task_info_t)&t_info, &th_count) != KERN_SUCCESS) {
 +
 +      do {
 +              mach_ret = task_info (task, TASK_BASIC_INFO, (task_info_t)&t_info, &th_count);
 +      } while (mach_ret == KERN_ABORTED);
 +
 +      if (mach_ret != KERN_SUCCESS) {
                if (pid != getpid ())
                        mach_port_deallocate (mach_task_self (), task);
                RET_ERROR (MONO_PROCESS_ERROR_OTHER);
diff --combined mono/utils/mono-time.c
index 5f0168ebb7475b94886d44a002331d2aa1184842,c93130bbdd63994d9c5905c7598ac1b1c6b6b331..5a34f440353e0d8ff72b83443b42412b7d5dda0a
@@@ -2,7 -2,6 +2,7 @@@
   * Time utility functions.
   * Author: Paolo Molaro (<lupus@ximian.com>)
   * Copyright (C) 2008 Novell, Inc.
 + * Licensed under the MIT license. See LICENSE file in the project root for full license information.
   */
  
  #include <config.h>
  #include <utils/mono-time.h>
  
  
- #define MTICKS_PER_SEC 10000000
+ #define MTICKS_PER_SEC (10 * 1000 * 1000)
+ gint64
+ mono_msec_ticks (void)
+ {
+       return mono_100ns_ticks () / 10 / 1000;
+ }
  
  #ifdef HOST_WIN32
  #include <windows.h>
  
- guint32
- mono_msec_ticks (void)
+ #ifndef _MSC_VER
+ /* we get "error: implicit declaration of function 'GetTickCount64'" */
+ ULONGLONG GetTickCount64(void);
+ #endif
+ gint64
+ mono_msec_boottime (void)
  {
        /* GetTickCount () is reportedly monotonic */
-       return GetTickCount ();
+       return GetTickCount64 ();
  }
  
  /* Returns the number of 100ns ticks from unspecified time: this should be monotonic */
@@@ -114,8 -124,8 +125,8 @@@ get_boot_time (void
  }
  
  /* Returns the number of milliseconds from boot time: this should be monotonic */
- guint32
- mono_msec_ticks (void)
+ gint64
+ mono_msec_boottime (void)
  {
        static gint64 boot_time = 0;
        gint64 now;
                boot_time = get_boot_time ();
        now = mono_100ns_ticks ();
        /*printf ("now: %llu (boot: %llu) ticks: %llu\n", (gint64)now, (gint64)boot_time, (gint64)(now - boot_time));*/
+       g_assert (now > boot_time);
        return (now - boot_time)/10000;
  }