Merge pull request #2869 from BrzVlad/feature-mod-union-opt
authorVlad Brezae <brezaevlad@gmail.com>
Thu, 21 Apr 2016 13:53:02 +0000 (16:53 +0300)
committerVlad Brezae <brezaevlad@gmail.com>
Thu, 21 Apr 2016 13:53:02 +0000 (16:53 +0300)
[sgen] Optimize mod union usage

254 files changed:
configure.ac
external/referencesource
man/mprof-report.1
mcs/class/Makefile
mcs/class/Mono.Security/Makefile
mcs/class/Mono.Security/Mono.Security.Authenticode/AuthenticodeDeformatter.cs
mcs/class/Mono.Security/Mono.Security.Cryptography/MD2Managed.cs
mcs/class/Mono.Security/Mono.Security.Cryptography/MD4Managed.cs
mcs/class/Mono.Security/Mono.Security.Cryptography/SHA224Managed.cs
mcs/class/Mono.Security/monotouch_Mono.Security.dll.sources
mcs/class/Mono.Security/xammac_Mono.Security.dll.sources
mcs/class/RabbitMQ.Client/Makefile.orig [deleted file]
mcs/class/System.Configuration/Makefile
mcs/class/System.Configuration/System.Configuration/InternalConfigurationHost.cs
mcs/class/System.Configuration/Test/standalone/Makefile
mcs/class/System.Configuration/Test/standalone/t48.cs [new file with mode: 0644]
mcs/class/System.Configuration/Test/standalone/t48.exe.config [new file with mode: 0644]
mcs/class/System.Configuration/Test/standalone/t48.exe.expected [new file with mode: 0644]
mcs/class/System.Deployment/Assembly/AssemblyInfo.cs [new file with mode: 0644]
mcs/class/System.Deployment/Makefile [new file with mode: 0644]
mcs/class/System.Deployment/System.Deployment.dll.sources [new file with mode: 0644]
mcs/class/System.Net.Http/CFContentStream.cs [new file with mode: 0644]
mcs/class/System.Net.Http/CFNetworkHandler.cs [new file with mode: 0644]
mcs/class/System.Net.Http/Documentation/en/index.xml
mcs/class/System.Net.Http/HttpClientEx.cs [new file with mode: 0644]
mcs/class/System.Net.Http/Makefile
mcs/class/System.Net.Http/System.Net.Http/HttpClient.android.cs [new file with mode: 0644]
mcs/class/System.Net.Http/monodroid_System.Net.Http.dll.sources [new file with mode: 0644]
mcs/class/System.Runtime.Serialization/System.Runtime.Serialization_test.dll.sources
mcs/class/System.Runtime.Serialization/Test/System.Runtime.Serialization/Exceptions.cs [new file with mode: 0644]
mcs/class/System.Web.Mobile/Assembly/AssemblyInfo.cs [new file with mode: 0644]
mcs/class/System.Web.Mobile/Makefile [new file with mode: 0644]
mcs/class/System.Web.Mobile/System.Web.Mobile.dll.sources [new file with mode: 0644]
mcs/class/System.Web.RegularExpressions/Assembly/AssemblyInfo.cs [new file with mode: 0644]
mcs/class/System.Web.RegularExpressions/Makefile [new file with mode: 0644]
mcs/class/System.Web.RegularExpressions/System.Web.RegularExpressions.dll.sources [new file with mode: 0644]
mcs/class/System.Workflow.Activities/Assembly/AssemblyInfo.cs [new file with mode: 0644]
mcs/class/System.Workflow.Activities/Makefile [new file with mode: 0644]
mcs/class/System.Workflow.Activities/System.Workflow.Activities.dll.sources [new file with mode: 0644]
mcs/class/System.Workflow.ComponentModel/Assembly/AssemblyInfo.cs [new file with mode: 0644]
mcs/class/System.Workflow.ComponentModel/Makefile [new file with mode: 0644]
mcs/class/System.Workflow.ComponentModel/System.Workflow.ComponentModel.dll.sources [new file with mode: 0644]
mcs/class/System.Workflow.Runtime/Assembly/AssemblyInfo.cs [new file with mode: 0644]
mcs/class/System.Workflow.Runtime/Makefile [new file with mode: 0644]
mcs/class/System.Workflow.Runtime/System.Workflow.Runtime.dll.sources [new file with mode: 0644]
mcs/class/System/Makefile
mcs/class/System/Mono.Net.Security/CallbackHelpers.cs
mcs/class/System/Mono.Net.Security/ChainValidationHelper.cs
mcs/class/System/Mono.Net.Security/IMonoSslStream.cs
mcs/class/System/Mono.Net.Security/IMonoTlsProvider.cs
mcs/class/System/Mono.Net.Security/LegacySslStream.cs
mcs/class/System/Mono.Net.Security/MonoDefaultTlsProvider.cs
mcs/class/System/Mono.Net.Security/MonoSslStreamImpl.cs
mcs/class/System/Mono.Net.Security/MonoSslStreamWrapper.cs
mcs/class/System/Mono.Net.Security/MonoTlsProviderImpl.cs
mcs/class/System/Mono.Net.Security/MonoTlsProviderWrapper.cs
mcs/class/System/Mono.Net.Security/MonoTlsStream.cs
mcs/class/System/Mono.Net.Security/SystemCertificateValidator.cs
mcs/class/System/ReferenceSources/SSPIWrapper.cs
mcs/class/System/System.CodeDom.Compiler/Compiler.cs
mcs/class/System/System.Configuration/AppSettingsReader.cs
mcs/class/System/System.Configuration/ApplicationSettingsBase.cs
mcs/class/System/System.Configuration/ConfigurationSettings.cs
mcs/class/System/System.Configuration/CustomizableFileSettingsProvider.cs
mcs/class/System/System.Configuration/LocalFileSettingsProvider.cs
mcs/class/System/System.Diagnostics/Process.cs
mcs/class/System/System.IO/KeventWatcher.cs
mcs/class/System/System.Net.Mail/SmtpClient.cs
mcs/class/System/System.Net.Security/LocalCertificateSelectionCallback.cs
mcs/class/System/System.Net.Security/RemoteCertificateValidationCallback.cs
mcs/class/System/System.Net.Security/SslStream.cs
mcs/class/System/System.Net/HttpConnection.cs
mcs/class/System/System.Security.Authentication.ExtendedProtection.Configuration/ConfigUtil.cs
mcs/class/System/System.Security.Cryptography.X509Certificates/OSX509Certificates.cs
mcs/class/System/System.Security.Cryptography.X509Certificates/X509Certificate2ImplMono.cs
mcs/class/System/System.Security.Cryptography.X509Certificates/X509Helper2.cs
mcs/class/System/Test/System.Net.WebSockets/ClientWebSocketTest.cs
mcs/class/corlib/CommonCrypto/.gitignore
mcs/class/corlib/CommonCrypto/CommonCryptorGenerator.cs [deleted file]
mcs/class/corlib/CommonCrypto/CommonDigestGenerator.cs [deleted file]
mcs/class/corlib/CommonCrypto/Makefile [new file with mode: 0644]
mcs/class/corlib/CommonCrypto/Makefile.include [deleted file]
mcs/class/corlib/CommonCrypto/generator.cs [deleted file]
mcs/class/corlib/Makefile
mcs/class/corlib/System.Diagnostics/StackTrace.cs
mcs/class/corlib/System.Diagnostics/StackTraceHelper.cs [deleted file]
mcs/class/corlib/System.IO/Directory.cs
mcs/class/corlib/System.IO/DirectoryInfo.cs
mcs/class/corlib/System.IO/Path.cs
mcs/class/corlib/System.Reflection.Emit/DerivedTypes.cs
mcs/class/corlib/System.Reflection/MonoMethod.cs
mcs/class/corlib/System.Runtime.InteropServices/Marshal.cs
mcs/class/corlib/System.Security.Cryptography.X509Certificates/X509CertificateImpl.cs
mcs/class/corlib/System.Security.Cryptography.X509Certificates/X509CertificateImplApple.cs
mcs/class/corlib/System.Security.Cryptography.X509Certificates/X509CertificateImplMono.cs
mcs/class/corlib/System.Threading/Monitor.cs
mcs/class/corlib/System.Threading/WaitHandle.cs
mcs/class/corlib/System/Environment.cs
mcs/class/corlib/System/Exception.cs [deleted file]
mcs/class/corlib/Test/System.IO/DirectoryTest.cs
mcs/class/corlib/Test/System.Reflection.Emit/DerivedTypesTest.cs
mcs/class/corlib/Test/System.Security.Cryptography/CspParametersTest.cs
mcs/class/corlib/Test/System.Threading/TimerTest.cs
mcs/class/corlib/Test/System/DelegateTest.cs
mcs/class/corlib/corlib.dll.sources
mcs/class/corlib/monotouch_corlib.dll.sources
mcs/class/corlib/monotouch_runtime_corlib.dll.sources
mcs/class/corlib/monotouch_tv_corlib.dll.sources
mcs/class/corlib/monotouch_watch_corlib.dll.sources
mcs/class/corlib/xammac_corlib.dll.sources
mcs/errors/cs0023-27.cs [new file with mode: 0644]
mcs/errors/cs0023-28.cs [new file with mode: 0644]
mcs/errors/cs0023-29.cs [new file with mode: 0644]
mcs/errors/cs0029-26.cs
mcs/errors/cs0266-30.cs [new file with mode: 0644]
mcs/mcs/class.cs
mcs/mcs/codegen.cs
mcs/mcs/cs-parser.jay
mcs/mcs/delegate.cs
mcs/mcs/ecore.cs
mcs/mcs/expression.cs
mcs/mcs/typespec.cs
mcs/tests/gtest-optional-37.cs [new file with mode: 0644]
mcs/tests/test-934.cs [new file with mode: 0644]
mcs/tests/test-null-operator-04.cs [new file with mode: 0644]
mcs/tests/ver-il-net_4_x.xml
mcs/tools/Makefile
mcs/tools/commoncryptogenerator/CommonCryptorGenerator.cs [new file with mode: 0644]
mcs/tools/commoncryptogenerator/CommonDigestGenerator.cs [new file with mode: 0644]
mcs/tools/commoncryptogenerator/Makefile [new file with mode: 0644]
mcs/tools/commoncryptogenerator/commoncryptogenerator.exe.sources [new file with mode: 0644]
mcs/tools/commoncryptogenerator/generator.cs [new file with mode: 0644]
mcs/tools/compiler-tester/compiler-tester.cs
mcs/tools/mono-api-html/mono-api-html.csproj
mcs/tools/mono-symbolicate/LocationProvider.cs
mcs/tools/mono-symbolicate/Makefile
mcs/tools/mono-symbolicate/mono-symbolicate.exe.sources
mcs/tools/mono-symbolicate/monosymbolicate.csproj [new file with mode: 0644]
mcs/tools/mono-symbolicate/symbolicate.cs
mono/arch/amd64/amd64-codegen.h
mono/io-layer/io.c
mono/io-layer/processes.c
mono/metadata/appdomain.c
mono/metadata/assembly.c
mono/metadata/attach.c
mono/metadata/class-internals.h
mono/metadata/class.c
mono/metadata/console-unix.c
mono/metadata/domain.c
mono/metadata/file-io.c
mono/metadata/gc.c
mono/metadata/icall-def.h
mono/metadata/icall.c
mono/metadata/locales.c
mono/metadata/marshal.c
mono/metadata/mono-perfcounters.c
mono/metadata/mono-security.c
mono/metadata/object-internals.h
mono/metadata/object.c
mono/metadata/object.h
mono/metadata/process.c
mono/metadata/profiler.c
mono/metadata/profiler.h
mono/metadata/reflection.c
mono/metadata/remoting.c
mono/metadata/sgen-bridge.c
mono/metadata/sgen-client-mono.h
mono/metadata/sgen-mono.c
mono/metadata/sgen-os-mach.c
mono/metadata/socket-io.c
mono/metadata/threadpool-ms-io-epoll.c
mono/metadata/threadpool-ms-io-kqueue.c
mono/metadata/threadpool-ms-io-poll.c
mono/metadata/threadpool-ms-io.c
mono/metadata/threadpool-ms.c
mono/metadata/threads-types.h
mono/metadata/threads.c
mono/mini/aot-compiler.c
mono/mini/aot-runtime.c
mono/mini/branch-opts.c
mono/mini/debugger-agent.c
mono/mini/decompose.c
mono/mini/driver.c
mono/mini/local-propagation.c
mono/mini/method-to-ir.c
mono/mini/mini-codegen.c
mono/mini/mini-darwin.c
mono/mini/mini-exceptions.c
mono/mini/mini-posix.c
mono/mini/mini-runtime.c
mono/mini/mini-x86.c
mono/mini/mini-x86.h
mono/mini/test_op_il_seq_point.sh
mono/profiler/Makefile.am
mono/profiler/decode.c
mono/profiler/mono-profiler-iomap.c
mono/profiler/proflog.c
mono/profiler/proflog.h
mono/sgen/sgen-descriptor.c
mono/sgen/sgen-gc.c
mono/sgen/sgen-gchandles.c
mono/sgen/sgen-marksweep.c
mono/sgen/sgen-pinning.c
mono/sgen/sgen-pinning.h
mono/sgen/sgen-protocol-def.h
mono/tests/Makefile.am
mono/tests/bug-29585.cs [new file with mode: 0644]
mono/tests/sgen-bridge-gchandle.cs [new file with mode: 0644]
mono/tests/verifier/Makefile
mono/tests/verifier/make_access_test.sh
mono/tests/verifier/make_bad_op_test.sh
mono/tests/verifier/make_bin_test.sh
mono/tests/verifier/make_boxed_genarg_test.sh
mono/tests/verifier/make_branch_test.sh
mono/tests/verifier/make_call_test.sh
mono/tests/verifier/make_cmmp_test.sh
mono/tests/verifier/make_cpobj_test.sh
mono/tests/verifier/make_cross_nested_access_test.sh
mono/tests/verifier/make_ctor_test.sh
mono/tests/verifier/make_delegate_compat_test.sh
mono/tests/verifier/make_double_nesting_test.sh
mono/tests/verifier/make_exception_overlap_test.sh
mono/tests/verifier/make_field_store_test.sh
mono/tests/verifier/make_initobj_test.sh
mono/tests/verifier/make_ldobj_test.sh
mono/tests/verifier/make_localloc_test.sh
mono/tests/verifier/make_nested_access_test.sh
mono/tests/verifier/make_obj_store_test.sh
mono/tests/verifier/make_overlapped_test.sh
mono/tests/verifier/make_stobj_test.sh
mono/tests/verifier/make_switch_test.sh
mono/tests/verifier/make_tail_call_test.sh
mono/tests/verifier/make_tests.sh
mono/tests/verifier/make_unbox_test.sh
mono/utils/lock-free-alloc.h
mono/utils/mach-support.c
mono/utils/mono-context.h
mono/utils/mono-counters.c
mono/utils/mono-counters.h
mono/utils/mono-dl-fallback.h
mono/utils/mono-error-internals.h
mono/utils/mono-os-mutex.h
mono/utils/mono-os-semaphore.h
mono/utils/mono-proclib.c
mono/utils/mono-sigcontext.h
mono/utils/mono-signal-handler.h
mono/utils/mono-threads-mach-abort-syscall.c
mono/utils/mono-threads-mach.c
mono/utils/mono-threads-posix.c
scripts/ci/run-jenkins.sh
tools/offsets-tool/.gitignore [new file with mode: 0644]
tools/offsets-tool/Makefile [new file with mode: 0644]
tools/offsets-tool/MonoAotOffsetsDumper.cs [new file with mode: 0644]
winconfig.h

index 52bd77591086353b5a9030c95f425cfe9e90687b..966bd50391504aa8e884de27ef4bbf2fe058645e 100644 (file)
@@ -1,7 +1,7 @@
 # Process this file with autoconf to produce a configure script.
 #AC_PREREQ([2.62])
 
-AC_INIT(mono, [4.5.0],
+AC_INIT(mono, [4.5.1],
         [http://bugzilla.xamarin.com/enter_bug.cgi?classification=Mono])
 
 AC_CONFIG_SRCDIR([README.md])
@@ -92,11 +92,11 @@ case "$host" in
                host_win32=yes
                mono_cv_clang=no
                if test "x$cross_compiling" = "xno"; then
-                       if test "x$host" == "x$build" -a "x$host" == "x$target"; then
+                       if test "x$host" = "x$build" -a "x$host" = "x$target"; then
                                target_win32=yes
                        fi
                else
-                       if test "x$host" == "x$target"; then
+                       if test "x$host" = "x$target"; then
                                target_win32=yes
                        fi
                fi
@@ -2451,7 +2451,7 @@ fi
 AC_ARG_ENABLE(bcl-opt, [  --disable-bcl-opt    BCL is compiled with no optimizations (allows accurate BCL debugging)], test_bcl_opt=$enableval, test_bcl_opt=yes)
 
 AC_ARG_ENABLE(perf-events, [  --enable-perf-events Enable using `perf` for profiling on Linux], test_perf_events=$enableval, test_perf_events=no)
-if test "x$test_perf_events" == "xyes"; then
+if test "x$test_perf_events" = "xyes"; then
        AC_DEFINE(ENABLE_PERF_EVENTS, 1, [Enable using `perf` for profiling on Linux])
        AC_SUBST(ENABLE_PERF_EVENTS)
 fi
@@ -2613,7 +2613,7 @@ if test "x$enable_llvm" = "xyes"; then
    AC_MSG_CHECKING(LLVM version)
    AC_MSG_RESULT($llvm_version $llvm_api_version)
    if echo $llvm_version | grep -q 'mono'; then
-         if test "x$enable_llvm_version_check" == "xyes"; then
+         if test "x$enable_llvm_version_check" = "xyes"; then
                 if test "$llvm_version" != "$expected_llvm_version"; then
                        AC_MSG_ERROR([Expected llvm version $expected_llvm_version, but llvm-config --version returned $llvm_version"])
                 fi
@@ -2648,7 +2648,7 @@ if test "x$enable_llvm" = "xyes"; then
       llvm_jit_libs=""
    fi
    LLVM_LIBS=`$LLVM_CONFIG --libs analysis core bitwriter $llvm_jit_libs`
-   if test "x$LLVM_LIBS" == "x"; then
+   if test "x$LLVM_LIBS" = "x"; then
          echo "$LLVM_CONFIG --libs failed."
          exit 1
    fi
@@ -2890,6 +2890,12 @@ case "$host" in
                AOT_SUPPORTED="yes"
                CPPFLAGS="$CPPFLAGS -D__ARM_EABI__"
                ;;
+       arm*-netbsd*-eabi*)
+               TARGET=ARM;
+               arch_target=arm;
+               ACCESS_UNALIGNED="no"
+               CPPFLAGS="$CPPFLAGS -D__ARM_EABI__"
+               ;;
 # TODO: make proper support for NaCl host.
 #        arm*-*nacl)
 #              TARGET=ARM;
@@ -3004,6 +3010,17 @@ if test "x$host" != "x$target"; then
                        ;;
                esac
                ;;
+   arm*-netbsd*-eabi*)
+               TARGET=ARM;
+               arch_target=arm;
+               AC_DEFINE(TARGET_ARM, 1, [...])
+               ACCESS_UNALIGNED="no"
+               CPPFLAGS="$CPPFLAGS -D__ARM_EABI__"
+               # Can't use tls, since it depends on the runtime detection of tls offsets
+               # in mono-compiler.h
+               with_tls=pthread
+               target_mach=no
+               ;;
    i686*-linux-*)
                TARGET=X86;
                arch_target=x86;
@@ -3265,8 +3282,10 @@ case "$host" in
        GTKX11="libgtk-x11-2.0.dylib"
        ;;
      *-*-*netbsd*)
-       LIBC="libc.so.12"
-       INTL="libintl.so.0"
+       LIBC="libc.so"
+       INTL="libintl.so"
+       SQLITE="libsqlite.so"
+       SQLITE3="libsqlite3.so"
        ;;
      *-*-kfreebsd*-gnu)
        LIBC="libc.so.0.1"
index 2f66da8d34b30473dac23f02b1a843d0717b9f1a..5b907267935346d2fe110d226bf3a62abcbd0dc6 160000 (submodule)
@@ -1 +1 @@
-Subproject commit 2f66da8d34b30473dac23f02b1a843d0717b9f1a
+Subproject commit 5b907267935346d2fe110d226bf3a62abcbd0dc6
index c166333233651b48fb029e11b1ce082876b5b6a6..af61efa37cb84a91b735581972a4f8dec8565285 100644 (file)
@@ -137,9 +137,9 @@ to the control port
 .IP \[bu] 2
 \f[I]sample[=TYPE[/FREQ]]\f[]: collect statistical samples of the
 program behaviour.
-The default is to collect a 1000 times per second the instruction
-pointer.
-This is equivalent to the value \[lq]cycles/1000\[rq] for
+The default is to collect a 100 times per second (100 Hz) the
+instruction pointer.
+This is equivalent to the value \[lq]cycles/100\[rq] for
 \f[I]TYPE\f[].
 On some systems, like with recent Linux kernels, it is possible to
 cause the sampling to happen for other events provided by the
@@ -171,6 +171,24 @@ TIMER can have the following values:
 collect \f[I]NUM\f[] frames at the most.
 The default is 8.
 .IP \[bu] 2
+\f[I]maxsamples=NUM\f[]: stop allocating reusable sample events
+once \f[I]NUM\f[] events have been allocated (a value of zero for
+all intents and purposes means unlimited). By default, the value
+of this setting is the number of CPU cores multiplied by 1000. This
+is usually a good enough value for typical desktop and mobile apps.
+If you're losing too many samples due to this default (which is
+possible in apps with an unusually high amount of threads), you
+may want to tinker with this value to find a good balance between
+sample hit rate and performance impact on the app. The way it works
+is that sample events are enqueued for reuse after they're flushed
+to the output file; if a thread gets a sampling signal but there are
+no sample events in the reuse queue and the profiler has reached the
+maximum number of sample allocations, the sample gets dropped. So a
+higher number for this setting will increase the chance that a
+thread is able to collect a sample, but also necessarily means that
+there will be more work done by the profiler. You can run Mono with
+the \f[I]--stats\f[] option to see statistics about sample events.
+.IP \[bu] 2
 \f[I]calldepth=NUM\f[]: ignore method enter/leave events when the
 call chain depth is bigger than NUM.
 .IP \[bu] 2
index 6bf570842e7757c2ba86d3e6c1a7bbe7b90ba30d..167bc4ca5cc5bc8a883aa8d145b3c9249aba47b0 100644 (file)
@@ -1,8 +1,6 @@
 thisdir = class
 
-# Note that Mono.Security and System.Security aren't listed.
-# We may have to add those if 'mcs' starts using them.
-basic_SUBDIRS := corlib System System.XML System Mono.Security System.Core 
+basic_SUBDIRS := corlib Mono.Security System System.XML System.Core 
 
 # resgen is corlib specific so we need to wait until corlib is build
 # and build it just a step before first dll needs it
@@ -10,9 +8,9 @@ resgen_dir = ../tools/resgen
 
 build_SUBDIRS :=  \
        corlib \
+       Mono.Security \
        System \
        System.XML \
-       System Mono.Security \
        Mono.Posix \
        System.Core \
        Mono.Cecil \
@@ -22,11 +20,10 @@ pcl_facade_dirs := Facades
 
 mobile_common_dirs := \
        corlib  \
+       Mono.Security \
        System  \
        System.Core     \
        System.XML      \
-       Mono.Security   \
-       System  \
        I18N            \
        System.ServiceModel.Internals   \
        SMDiagnostics   \
@@ -82,6 +79,7 @@ monotouch_tv_dirs   := $(monotouch_dirs)
 
 monotouch_runtime_dirs := \
        corlib \
+       Mono.Security \
        System \
        System.Core \
        System.XML \
@@ -92,12 +90,11 @@ monotouch_tv_runtime_dirs := $(monotouch_runtime_dirs)
 
 xammac_4_5_dirs := \
        corlib  \
+       Mono.Security \
        System  \
        Mono.Posix                      \
        System.Core     \
        System.XML      \
-       Mono.Security   \
-       System  \
        I18N            \
        System.ServiceModel.Internals   \
        SMDiagnostics   \
@@ -140,12 +137,12 @@ xammac_4_5_dirs := \
 
 net_4_x_dirs := \
        corlib                          \
+       Mono.Security \
        System                          \
        System.XML                      \
        Mono.CompilerServices.SymbolWriter \
        Mono.Posix                      \
        System.Core                     \
-       Mono.Security                   \
        System.Security                 \
        System.Configuration    \
        $(resgen_dir)                   \
@@ -272,6 +269,12 @@ net_4_x_parallel_dirs := \
        Microsoft.VisualC               \
        WebMatrix.Data \
        monodoc \
+       System.Deployment \
+       System.Web.Mobile \
+       System.Web.RegularExpressions \
+       System.Workflow.Activities \
+       System.Workflow.ComponentModel \
+       System.Workflow.Runtime \
        $(pcl_facade_dirs)
 
 xbuild_2_0_dirs := \
index 1fbfd14ec8efcff4e6514e1cac32c6d3794648a0..6d62eca583d7d32776d05e4ac5d33e1458cd8500 100644 (file)
@@ -8,6 +8,19 @@ LIB_REFS = bare/System
 LIB_MCS_FLAGS = -unsafe -nowarn:1030,3009
 TEST_MCS_FLAGS = $(LIB_MCS_FLAGS) -nowarn:169,219,618,672
 
+CC_PROFILE := $(filter monotouch% xammac, $(PROFILE))
+ifdef CC_PROFILE
+
+BUILT_SOURCES = \
+       ../corlib/CommonCrypto/SHA224Managed.g.cs \
+       ../corlib/CommonCrypto/MD2Managed.g.cs \
+       ../corlib/CommonCrypto/MD4Managed.g.cs
+
+../corlib/CommonCrypto/%.g.cs:
+       $(MAKE) -C ../corlib/CommonCrypto
+
+endif
+
 include ../../build/library.make
 
 $(build_lib): $(the_libdir_base)bare/System.dll
index 1efcec91abde0a83b6cbc5f89caae1111a368937..bca6803ee34542a6c568a0aa5bcfe2d0e3560807 100644 (file)
@@ -205,6 +205,18 @@ namespace Mono.Security.Authenticode {
                                        ha = SHA1.Create ();
                                        hash = GetHash (ha);
                                        break;
+                               case 32:
+                                       ha = SHA256.Create ();
+                                       hash = GetHash (ha);
+                                       break;
+                               case 48:
+                                       ha = SHA384.Create ();
+                                       hash = GetHash (ha);
+                                       break;
+                               case 64:
+                                       ha = SHA512.Create ();
+                                       hash = GetHash (ha);
+                                       break;
                                default:
                                        reason = 5;
                                        Close ();
@@ -402,6 +414,15 @@ namespace Mono.Security.Authenticode {
                                case 20:
                                        hashName = "SHA1";
                                        break;
+                               case 32:
+                                       hashName = "SHA256";
+                                       break;
+                               case 48:
+                                       hashName = "SHA384";
+                                       break;
+                               case 64:
+                                       hashName = "SHA512";
+                                       break;
                        }
                        HashAlgorithm ha = HashAlgorithm.Create (hashName);
                        if (!messageDigest.CompareValue (ha.ComputeHash (signature)))
index 13f0f5d8e65a639248892d5cedd5011cd4dd6aac..a428e0624b1ec82cef0e4912ff8e93588ca0aa5a 100644 (file)
@@ -27,6 +27,8 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
+#if !MONOTOUCH && !XAMMAC
+
 using System;
 
 namespace Mono.Security.Cryptography { 
@@ -195,3 +197,5 @@ namespace Mono.Security.Cryptography {
                }
        }
 }
+
+#endif
\ No newline at end of file
index eedc8b114b195cc46aa29415cbec47f46aea298f..adbd7fb876b841c88f77e7947e9ad8e158cfaba2 100644 (file)
@@ -27,6 +27,8 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
+#if !MONOTOUCH && !XAMMAC
+
 using System;
 
 namespace Mono.Security.Cryptography { 
@@ -282,3 +284,5 @@ namespace Mono.Security.Cryptography {
                }
        }
 }
+
+#endif
\ No newline at end of file
index 88d4fe59955af86f654d2a5f8ce3093d10720a63..a0da4344b9524c0d1e02264f88c828cd53b283ef 100644 (file)
@@ -29,6 +29,8 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
+#if !MONOTOUCH && !XAMMAC
+
 using System.Security.Cryptography;
 
 namespace Mono.Security.Cryptography {
@@ -256,3 +258,4 @@ namespace Mono.Security.Cryptography {
        }
 }
 
+#endif
\ No newline at end of file
index 17f56e3c4054885b5f5cf4477cef4bed1ff63c44..36918de7763e9ed1c24609f0a67e752c39967081 100644 (file)
@@ -1,6 +1,3 @@
 #include mobile_Mono.Security.dll.sources
 ../corlib/CommonCrypto/CommonCrypto.cs
 ../corlib/CommonCrypto/RC4CommonCrypto.cs
-../corlib/CommonCrypto/MD2Managed.g.cs
-../corlib/CommonCrypto/MD4Managed.g.cs
-../corlib/CommonCrypto/SHA224Managed.g.cs
index 6c1b4dbef6fda25d7d76612c984ad0776f33ee7f..698996a1d709c630c585a43f2f5ac90021c5e65a 100644 (file)
@@ -1,7 +1,4 @@
 #include monotouch_Mono.Security.dll.sources
 ../corlib/CommonCrypto/CommonCrypto.cs
 ../corlib/CommonCrypto/RC4CommonCrypto.cs
-../corlib/CommonCrypto/MD2Managed.g.cs
-../corlib/CommonCrypto/MD4Managed.g.cs
-../corlib/CommonCrypto/SHA224Managed.g.cs
 
diff --git a/mcs/class/RabbitMQ.Client/Makefile.orig b/mcs/class/RabbitMQ.Client/Makefile.orig
deleted file mode 100644 (file)
index 84182ff..0000000
+++ /dev/null
@@ -1,64 +0,0 @@
-NAME=rabbitmq-dotnet-client
-NAME_VSN=${NAME}-${RABBIT_VSN}
-
-RELEASE_DIR=releases/${NAME}/v${RABBIT_VSN}
-
-STAGE_RELEASE_DIR=charlotte:/home/rabbitmq/stage-extras/releases/${NAME}
-LIVE_RELEASE_DIR=charlotte:/home/rabbitmq/live-extras/releases/${NAME}
-
-RSYNC_CMD=rsync -irvl --delete-after
-
-TMPXMLZIP=${NAME_VSN}-tmp-xmldoc.zip
-
-ifeq "$(RABBIT_VSN)" ""
-rabbit-vsn:
-       @echo "RABBIT_VSN is not set"
-       @false
-else
-rabbit-vsn: 
-endif
-
-deploy-stage: rabbit-vsn ensure-deliverables
-       ${RSYNC_CMD} --exclude=${TMPXMLZIP} releases/${NAME}/ ${STAGE_RELEASE_DIR}
-
-deploy-live: rabbit-vsn ensure-deliverables
-       ${RSYNC_CMD} --exclude=${TMPXMLZIP} releases/${NAME}/ ${LIVE_RELEASE_DIR}
-
-ensure-deliverables: rabbit-vsn
-       file ${RELEASE_DIR}/${NAME_VSN}.zip
-       file ${RELEASE_DIR}/${NAME_VSN}-api-guide.pdf
-       file ${RELEASE_DIR}/${NAME_VSN}-user-guide.pdf
-       file ${RELEASE_DIR}/${NAME_VSN}-wcf-service-model.pdf
-       file ${RELEASE_DIR}/${NAME_VSN}-net-2.0.zip
-       file ${RELEASE_DIR}/${NAME_VSN}-net-2.0-htmldoc.zip
-       file ${RELEASE_DIR}/${NAME_VSN}-net-2.0-htmldoc
-       file ${RELEASE_DIR}/${NAME_VSN}-net-3.0-wcf.zip
-       file ${RELEASE_DIR}/${NAME_VSN}-net-3.0-wcf-htmldoc.zip
-       file ${RELEASE_DIR}/${NAME_VSN}-net-3.0-wcf-htmldoc
-
-ensure-prerequisites: rabbit-vsn
-       dpkg -p htmldoc plotutils transfig graphviz > /dev/null
-
-ensure-release-dir: rabbit-vsn
-       touch ${RELEASE_DIR}/
-
-ensure-docs: rabbit-vsn
-       file ${RELEASE_DIR}/${NAME_VSN}-net-2.0-htmldoc.zip
-       file ${RELEASE_DIR}/${TMPXMLZIP}
-
-doc: rabbit-vsn ensure-prerequisites ensure-release-dir ensure-docs
-       rm -rf build/tmpdoc build/doc
-       mkdir -p build/tmpdoc/html build/tmpdoc/xml
-       unzip -j ${RELEASE_DIR}/${NAME_VSN}-net-2.0-htmldoc.zip -d build/tmpdoc/html
-       unzip -j ${RELEASE_DIR}/${NAME_VSN}-tmp-xmldoc.zip -d build/tmpdoc/xml
-       cd docs && ./api-guide.sh && \
-         mv api-guide.pdf ../${RELEASE_DIR}/${NAME_VSN}-api-guide.pdf
-       $(MAKE) -C docs
-       mv build/doc/userguide/user-guide.pdf ${RELEASE_DIR}/${NAME_VSN}-user-guide.pdf
-       cp docs/"RabbitMQ Service Model.pdf" \
-         ${RELEASE_DIR}/${NAME_VSN}-wcf-service-model.pdf
-       cd ${RELEASE_DIR} && \
-         rm -rf ${NAME_VSN}-net-2.0-htmldoc && \
-         unzip ${NAME_VSN}-net-2.0-htmldoc.zip && \
-         rm -rf unzip ${NAME_VSN}-net-3.0-wcf-htmldoc && \
-         unzip ${NAME_VSN}-net-3.0-wcf-htmldoc.zip
index 065753050515d74addcbc04d91e84ec71296e0c9..5815830b6b9f18d4010a81939caa006ba5bd1585 100644 (file)
@@ -31,3 +31,6 @@ $(the_libdir_base)System.Security.dll:
 
 $(bare_libdir)/System.Xml.dll:
        (cd ../System.XML; $(MAKE) $@)
+
+run-test:
+       $(MAKE) -C Test/standalone
\ No newline at end of file
index e4d59f1466c2c3ba5604f17d5af8443d41d7afe9..0cf6136ae38ca111de4ffb463a475245dd7cf4b0 100644 (file)
@@ -69,6 +69,11 @@ namespace System.Configuration
                public virtual Type GetConfigType (string typeName, bool throwOnError)
                {
                        Type type = Type.GetType (typeName);
+
+                       // This code is in System.Configuration.dll, but some of the classes we might want to load here are in System.dll.
+                       if (type == null)
+                               type = Type.GetType (typeName + ",System");
+
                        if (type == null && throwOnError)
                                throw new ConfigurationErrorsException ("Type '" + typeName + "' not found.");
                        return type;
index 3a1a8a84e32c7b9c78af2e66e67e9b9541ff81e0..b203b7b9099cdafa132d38778fd1d2ce7b4a8fcb 100644 (file)
@@ -1,30 +1,37 @@
-TESTS = t1.exe t2.exe t3.exe t4.exe t5.exe t6.exe t7.exe t8.exe t9.exe t10.exe t11.exe t12.exe t15.exe t16.exe t17.exe t18.exe t19.exe t20.exe t21.exe t22.exe t23.exe t24.exe t25.exe t26.exe t27.exe t28.exe t29.exe t30.exe t31.exe t32.exe t33.exe t34.exe t35.exe t36.exe t37.exe t38.exe t39.exe t40.exe t41.exe t42.exe t43.exe t44.exe t45.exe t46.exe t47.exe
-# t13.exe t14.exe
+thisdir = class/System.Configuration/Test/standalone
+SUBDIRS = 
+include ../../../../build/rules.make
+
+TESTS = t1.exe t2.exe t3.exe t4.exe t5.exe t6.exe t7.exe t8.exe t9.exe t10.exe t11.exe t12.exe t15.exe t16.exe t17.exe t18.exe t19.exe t20.exe t21.exe t22.exe t23.exe t24.exe t25.exe t28.exe t29.exe t30.exe t31.exe t32.exe t33.exe t34.exe t35.exe t36.exe t37.exe t38.exe t39.exe t40.exe t41.exe t42.exe t43.exe t44.exe t45.exe t46.exe t47.exe t48.exe
+# t13.exe t14.exe t26.exe t27.exe
 
 check: local compare
 
 local: $(TESTS)
        @for i in $(TESTS); do \
                echo running test $$i; \
-               MONO_PATH=../../../lib/net_4_x mono --debug $$i > $$i.result; \
+               MONO_PATH="$(topdir)/class/lib/$(PROFILE)$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" $(RUNTIME) $(RUNTIME_FLAGS) $$i > $$i.result; \
        done
 
 compare:
-       @for i in $(TESTS); do \
-               echo -n "$$i: "; \
-               if diff --strip-trailing-cr $$i.expected $$i.result >/dev/null ; then echo "  OK"; else echo "  FAILED"; fi; \
-       done
+       @ECODE=0; \
+       for i in $(TESTS); do \
+               printf "$$i: "; \
+               if diff --strip-trailing-cr $$i.expected $$i.result >/dev/null ; then echo "  OK"; else echo "  FAILED"; ECODE=1; fi; \
+       done; \
+       exit $$ECODE
 
 clean:
        rm -f *.exe *.mdb *.result
 
 t36.exe : t36.cs t36-lib.cs
-       gmcs /debug -r:System.Configuration.dll -t:library t36-lib.cs
-       gmcs /debug -r:System.Configuration.dll -r:t36-lib.dll t36.cs
+       $(CSCOMPILE) -r:$(topdir)/class/lib/$(PROFILE)/System.Configuration.dll -t:library t36-lib.cs
+       $(CSCOMPILE) -r:$(topdir)/class/lib/$(PROFILE)/System.Configuration.dll -r:t36-lib.dll t36.cs
 
 t46.exe : t46.cs t46-lib.cs
-       gmcs /debug -r:System.Configuration.dll -t:library t46-lib.cs
-       gmcs /debug -r:System.Configuration.dll -r:t46-lib.dll /out:$@ Assert.cs t46.cs
+       $(CSCOMPILE) -r:$(topdir)/class/lib/$(PROFILE)/System.Configuration.dll -t:library t46-lib.cs
+       $(CSCOMPILE) -r:$(topdir)/class/lib/$(PROFILE)/System.Configuration.dll -r:t46-lib.dll /out:$@ Assert.cs t46.cs
 
 %.exe: %.cs
-       gmcs /debug /out:$@ Assert.cs $< -r:System.Configuration.dll -r:System.Web.dll -r:System.Data.dll
+       $(CSCOMPILE) /out:$@ Assert.cs $< -r:$(topdir)/class/lib/$(PROFILE)/System.Configuration.dll -r:$(topdir)/class/lib/$(PROFILE)/System.Web.dll -r:$(topdir)/class/lib/$(PROFILE)/System.Data.dll -r:$(topdir)/class/lib/$(PROFILE)/System.dll -r:$(topdir)/class/lib/$(PROFILE)/System.Xml.dll
+
diff --git a/mcs/class/System.Configuration/Test/standalone/t48.cs b/mcs/class/System.Configuration/Test/standalone/t48.cs
new file mode 100644 (file)
index 0000000..6d7bc05
--- /dev/null
@@ -0,0 +1,24 @@
+using System;
+using System.Collections;
+
+// Bugzilla #39669
+
+namespace TestConfigSection
+{
+       class Test
+       {
+               public static int Main (string[] args)
+               {
+                       Hashtable testCustomSection = (Hashtable)System.Configuration.ConfigurationManager.GetSection ("TestCustomSection");
+                       string proxyServer = (string)testCustomSection["ProxyServer"];
+
+                       if (proxyServer == null)
+                               throw new Exception("Custom section value is null");
+
+                       if (proxyServer != "server.example.com")
+                               throw new Exception("Custom section value is incorrect");
+
+                       return 0;
+               }
+       }
+}
diff --git a/mcs/class/System.Configuration/Test/standalone/t48.exe.config b/mcs/class/System.Configuration/Test/standalone/t48.exe.config
new file mode 100644 (file)
index 0000000..ebdf8a8
--- /dev/null
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="utf-8"?>
+<configuration>
+  <configSections>
+    <section name="TestCustomSection" type="System.Configuration.DictionarySectionHandler" />
+  </configSections>
+  <TestCustomSection>
+    <add key="ProxyServer" value="server.example.com" />
+    <add key="ConnectOnStart" value="false" />
+  </TestCustomSection>
+</configuration>
\ No newline at end of file
diff --git a/mcs/class/System.Configuration/Test/standalone/t48.exe.expected b/mcs/class/System.Configuration/Test/standalone/t48.exe.expected
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/mcs/class/System.Deployment/Assembly/AssemblyInfo.cs b/mcs/class/System.Deployment/Assembly/AssemblyInfo.cs
new file mode 100644 (file)
index 0000000..460e662
--- /dev/null
@@ -0,0 +1,53 @@
+//
+// AssemblyInfo.cs
+//
+// Authors:
+//     Marek Safar (marek.safar@gmail.com)
+//
+// Copyright 2016 Xamarin Inc (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Reflection;
+using System.Resources;
+using System.Security;
+using System.Security.Permissions;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about the assembly
+
+[assembly: AssemblyTitle ("System.Deployment.dll")]
+[assembly: AssemblyDescription ("System.Deployment.dll")]
+[assembly: AssemblyDefaultAlias ("System.Deployment.dll")]
+
+[assembly: AssemblyCompany (Consts.MonoCompany)]
+[assembly: AssemblyProduct (Consts.MonoProduct)]
+[assembly: AssemblyCopyright (Consts.MonoCopyright)]
+[assembly: AssemblyVersion (Consts.FxVersion)]
+[assembly: SatelliteContractVersion (Consts.FxVersion)]
+[assembly: AssemblyInformationalVersion (Consts.FxFileVersion)]
+[assembly: AssemblyFileVersion (Consts.FxFileVersion)]
+
+[assembly: CLSCompliant (true)]
+
diff --git a/mcs/class/System.Deployment/Makefile b/mcs/class/System.Deployment/Makefile
new file mode 100644 (file)
index 0000000..87b8ba7
--- /dev/null
@@ -0,0 +1,10 @@
+thisdir = class/System.Deployment
+SUBDIRS = 
+include ../../build/rules.make
+
+LIBRARY = System.Deployment.dll
+
+LIB_REFS =
+LIB_MCS_FLAGS = -delaysign -keyfile:../msfinal.pub
+
+include ../../build/library.make
diff --git a/mcs/class/System.Deployment/System.Deployment.dll.sources b/mcs/class/System.Deployment/System.Deployment.dll.sources
new file mode 100644 (file)
index 0000000..e49bef5
--- /dev/null
@@ -0,0 +1,2 @@
+../../build/common/Consts.cs
+Assembly/AssemblyInfo.cs
diff --git a/mcs/class/System.Net.Http/CFContentStream.cs b/mcs/class/System.Net.Http/CFContentStream.cs
new file mode 100644 (file)
index 0000000..270846c
--- /dev/null
@@ -0,0 +1,133 @@
+//
+// CFContentStream.cs
+//
+// Authors:
+//     Marek Safar  <marek.safar@gmail.com>
+//
+// Copyright (C) 2013 Xamarin Inc (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.Threading;
+using System.Threading.Tasks;
+using System.IO;
+using System.Net;
+
+#if XAMCORE_4_0
+using CFNetwork;
+#elif XAMCORE_2_0
+using CoreServices;
+#else
+using MonoTouch.CoreServices;
+#endif
+
+namespace System.Net.Http
+{
+       class BufferData 
+       {
+               public byte[] Buffer;
+               public int Length;
+       }
+
+       class CFContentStream : HttpContent
+       {
+               readonly CFHTTPStream http_stream;
+               BufferData data;
+               Mutex data_mutex;
+               AutoResetEvent data_event;
+               AutoResetEvent data_read_event;
+
+               // The requirements are:
+               // * We must read at least one byte from the stream every time
+               //   we get a HasBytesAvailable event.
+               // * SerializeToStreamAsync is executed on a separate thread,
+               //   so reads must somehow be synchronized with that thread.
+               //
+               // Current implementation:
+               // * We read data in ReadStreamData (on the same thread
+               //   we got the HasBytesAvailable event, i.e. inside the 
+               //   HasBytesAvailable event handler).
+               // * Data is stored in a class-level buffer.
+               // * SerializeToStreamAsync blocks while waiting for
+               //   data from ReadStreamData.
+               // * ReadStreamData will only read more data once SerializeToStreamAsync
+               //   has consumed any existing data. This means we'll be
+               //   blocking in the HasBytesAvailable event handler until
+               //   any previously read data has been processed (this prevents
+               //   any unbound memory growth).
+
+               public CFContentStream (CFHTTPStream stream)
+               {
+                       this.http_stream = stream;
+                       data = new BufferData () {
+                               Buffer = new byte [4096],
+                       };
+                       data_event = new AutoResetEvent (false);
+                       data_read_event = new AutoResetEvent (true);
+                       data_mutex = new Mutex ();
+               }
+
+               public void ReadStreamData ()
+               {
+                       data_read_event.WaitOne (); // make sure there's no pending data.
+
+                       data_mutex.WaitOne ();
+                       data.Length = (int) http_stream.Read (data.Buffer, 0, data.Buffer.Length);
+                       data_mutex.ReleaseMutex ();
+
+                       data_event.Set ();
+               }
+
+               public void Close ()
+               {
+                       data_read_event.WaitOne (); // make sure there's no pending data
+
+                       data_mutex.WaitOne ();
+                       data = null;
+                       data_mutex.ReleaseMutex ();
+
+                       data_event.Set ();
+               }
+
+               protected internal override async Task SerializeToStreamAsync (Stream stream, TransportContext context)
+               {
+                       while (data_event.WaitOne ()) {
+                               data_mutex.WaitOne ();
+                               if (data == null || data.Length <= 0) {
+                                       data_mutex.ReleaseMutex ();
+                                       data_read_event.Set ();
+                                       break;
+                               }
+
+                               await stream.WriteAsync (data.Buffer, 0, data.Length).ConfigureAwait (false);
+                               data_mutex.ReleaseMutex ();
+
+                               data_read_event.Set ();
+                       }
+               }
+
+               protected internal override bool TryComputeLength (out long length)
+               {
+                       length = 0;
+                       return false;
+               }
+       }
+}
diff --git a/mcs/class/System.Net.Http/CFNetworkHandler.cs b/mcs/class/System.Net.Http/CFNetworkHandler.cs
new file mode 100644 (file)
index 0000000..5723acb
--- /dev/null
@@ -0,0 +1,332 @@
+//
+// CFNetworkHandler.cs
+//
+// Authors:
+//     Marek Safar  <marek.safar@gmail.com>
+//
+// Copyright (C) 2013 Xamarin Inc (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.Threading;
+using System.Net.Http.Headers;
+using System.Threading.Tasks;
+using System.IO;
+using System.Collections.Generic;
+using System.Net;
+
+#if XAMCORE_4_0
+using CFNetwork;
+using CoreFoundation;
+using CF=CoreFoundation;
+#elif XAMCORE_2_0
+using CoreServices;
+using CoreFoundation;
+using CF=CoreFoundation;
+#else
+using MonoTouch.CoreServices;
+using MonoTouch.CoreFoundation;
+using CF=MonoTouch.CoreFoundation;
+#endif
+
+namespace System.Net.Http
+{
+       public class CFNetworkHandler : HttpMessageHandler
+       {
+               class StreamBucket
+               {
+                       public TaskCompletionSource<HttpResponseMessage> Response;
+                       public HttpRequestMessage Request;
+                       public CancellationTokenRegistration CancellationTokenRegistration;
+                       public CFContentStream ContentStream;
+
+                       public void Close ()
+                       {
+                               CancellationTokenRegistration.Dispose ();
+                               ContentStream.Close ();
+                       }
+               }
+
+               bool allowAutoRedirect;
+               bool sentRequest;
+               bool useSystemProxy;
+               CookieContainer cookies;
+
+               Dictionary<IntPtr, StreamBucket> streamBuckets;
+
+               public CFNetworkHandler ()
+               {
+                       allowAutoRedirect = true;
+                       streamBuckets = new Dictionary<IntPtr, StreamBucket> ();
+               }
+
+               void EnsureModifiability ()
+               {
+                       if (sentRequest)
+                               throw new InvalidOperationException (
+                                       "This instance has already started one or more requests. " +
+                                       "Properties can only be modified before sending the first request.");
+               }
+
+               public bool AllowAutoRedirect {
+                       get {
+                               return allowAutoRedirect;
+                       }
+                       set {
+                               EnsureModifiability ();
+                               allowAutoRedirect = value;
+                       }
+               }
+
+               public CookieContainer CookieContainer {
+                       get {
+                               return cookies;
+                       }
+                       set {
+                               EnsureModifiability ();
+                               cookies = value;
+                       }
+               }
+
+               public bool UseSystemProxy {
+                       get {
+                               return useSystemProxy;
+                       }
+                       set {
+                               EnsureModifiability ();
+                               useSystemProxy = value;
+                       }
+               }
+
+               // TODO: Add more properties
+
+               protected override void Dispose (bool disposing)
+               {
+                       // TODO: CloseStream remaining stream buckets if there are any
+
+                       base.Dispose (disposing);
+               }
+
+               CFHTTPMessage CreateWebRequestAsync (HttpRequestMessage request)
+               {
+                       var req = CFHTTPMessage.CreateRequest (request.RequestUri, request.Method.Method, request.Version);
+
+                       // TODO:
+/*
+                       if (wr.ProtocolVersion == HttpVersion.Version10) {
+                               wr.KeepAlive = request.Headers.ConnectionKeepAlive;
+                       } else {
+                               wr.KeepAlive = request.Headers.ConnectionClose != true;
+                       }
+
+                       if (useDefaultCredentials) {
+                               wr.UseDefaultCredentials = true;
+                       } else {
+                               wr.Credentials = credentials;
+                       }
+
+                       if (useProxy) {
+                               wr.Proxy = proxy;
+                       }
+*/
+                       if (cookies != null) {
+                               string cookieHeader = cookies.GetCookieHeader (request.RequestUri);
+                               if (cookieHeader != "")
+                                       req.SetHeaderFieldValue ("Cookie", cookieHeader);
+                       }
+
+                       foreach (var header in request.Headers) {
+                               foreach (var value in header.Value) {
+                                       req.SetHeaderFieldValue (header.Key, value);
+                               }
+                       }
+
+                       if (request.Content != null) {
+                               foreach (var header in request.Content.Headers) {
+                                       foreach (var value in header.Value) {
+                                               req.SetHeaderFieldValue (header.Key, value);
+                                       }
+                               }
+                       }
+
+                       return req;
+               }
+
+               protected internal override async Task<HttpResponseMessage> SendAsync (HttpRequestMessage request, CancellationToken cancellationToken)
+               {
+                       sentRequest = true;
+
+                       CFHTTPStream stream;
+                       using (var message = CreateWebRequestAsync (request))
+                       {
+                               if (request.Content != null) {
+                                       var data = await request.Content.ReadAsByteArrayAsync ().ConfigureAwait (false);
+                                       message.SetBody (data);
+                               }
+
+                               stream = CFHTTPStream.CreateForHTTPRequest (message);
+                       }
+
+                       if (useSystemProxy) {
+                               var proxies = CF.CFNetwork.GetSystemProxySettings ();
+                               if (proxies.HTTPEnable) {
+                                       stream.SetProxy (proxies);
+                               }
+                       }
+
+                       stream.ShouldAutoredirect = allowAutoRedirect;
+                       stream.HasBytesAvailableEvent += HandleHasBytesAvailableEvent;
+                       stream.ErrorEvent += HandleErrorEvent;
+                       stream.ClosedEvent += HandleClosedEvent;
+
+                       var response = new TaskCompletionSource<HttpResponseMessage> ();
+
+                       if (cancellationToken.IsCancellationRequested) {
+                               response.SetCanceled ();
+                               return await response.Task;
+                       }
+
+                       var bucket = new StreamBucket () {
+                               Request = request,
+                               Response = response,
+                       };
+
+                       streamBuckets.Add (stream.Handle, bucket);
+
+                       //
+                       // Always schedule stream events handling on main-loop. Due to ConfigureAwait (false) we may end up
+                       // on any thread-pool thread which may not have run-loop running
+                       //
+#if XAMCORE_2_0
+                       stream.EnableEvents (CF.CFRunLoop.Main, CF.CFRunLoop.ModeCommon);
+#else
+                       stream.EnableEvents (CF.CFRunLoop.Main, CF.CFRunLoop.CFRunLoopCommonModes);
+#endif
+
+                       stream.Open ();
+
+                       bucket.CancellationTokenRegistration = cancellationToken.Register (() => {
+                               StreamBucket bucket2;
+                               if (!streamBuckets.TryGetValue (stream.Handle, out bucket2))
+                                       return;
+
+                               bucket2.Response.TrySetCanceled ();
+                               CloseStream (stream);
+                       });
+
+                       return await response.Task;
+               }
+
+               void HandleErrorEvent (object sender, CFStream.StreamEventArgs e)
+               {
+                       var stream = (CFHTTPStream)sender;
+
+                       StreamBucket bucket;
+                       if (!streamBuckets.TryGetValue (stream.Handle, out bucket))
+                               return;
+
+                       bucket.Response.TrySetException (stream.GetError ());
+                       CloseStream (stream);
+               }
+
+               void HandleClosedEvent (object sender, CFStream.StreamEventArgs e)
+               {
+                       var stream = (CFHTTPStream)sender;
+                       CloseStream (stream);
+               }
+
+               void CloseStream (CFHTTPStream stream)
+               {
+                       StreamBucket bucket;
+                       if (streamBuckets.TryGetValue (stream.Handle, out bucket)) {
+                               bucket.Close ();
+                               streamBuckets.Remove (stream.Handle);
+                       }
+
+                       stream.Close ();
+               }
+
+               void HandleHasBytesAvailableEvent (object sender, CFStream.StreamEventArgs e)
+               {
+                       var stream = (CFHTTPStream) sender;
+
+                       StreamBucket bucket;
+                       if (!streamBuckets.TryGetValue (stream.Handle, out bucket))
+                               return;
+
+                       if (bucket.Response.Task.IsCompleted) {
+                               bucket.ContentStream.ReadStreamData ();
+                               return;
+                       }
+
+                       var header = stream.GetResponseHeader ();
+
+                       // Is this possible?
+                       if (!header.IsHeaderComplete)
+                               throw new NotImplementedException ();
+
+                       bucket.ContentStream = new CFContentStream (stream);
+                               
+                       var response_msg = new HttpResponseMessage (header.ResponseStatusCode);
+                       response_msg.RequestMessage = bucket.Request;
+                       response_msg.ReasonPhrase = header.ResponseStatusLine;
+                       response_msg.Content = bucket.ContentStream;
+
+                       var fields = header.GetAllHeaderFields ();
+                       if (fields != null) {
+                               foreach (var entry in fields) {
+                                       if (entry.Key == null)
+                                               continue;
+
+                                       var key = entry.Key.ToString ();
+                                       var value = entry.Value == null ? string.Empty : entry.Value.ToString ();
+                                       HttpHeaders item_headers;
+                                       if (HttpHeaders.GetKnownHeaderKind (key) == Headers.HttpHeaderKind.Content) {
+                                               item_headers = response_msg.Content.Headers;
+                                       } else {
+                                               item_headers = response_msg.Headers;
+
+                                               if (cookies != null && (key == "Set-Cookie" || key == "Set-Cookie2"))
+                                                       AddCookie (value, bucket.Request.RequestUri, key);
+                                       }
+
+                                       item_headers.TryAddWithoutValidation (key, value);
+                               }
+                       }
+
+                       bucket.Response.TrySetResult (response_msg);
+
+                       bucket.ContentStream.ReadStreamData ();
+               }
+
+               void AddCookie (string value, Uri uri, string header)
+               {
+                       CookieCollection cookies1 = null;
+                       try {
+                               cookies1 = cookies.CookieCutter (uri, header, value, false);
+                       } catch {
+                       }
+
+                       if (cookies1 != null && cookies1.Count != 0) 
+                               cookies.Add (cookies1);
+               }
+       }
+}
index eb70cc576c78dd095f011ab76dde239e0dc78642..08925bbaf2dec3812ae4d53b2780d9a9aec621ec 100644 (file)
@@ -56,6 +56,7 @@
   <Types>
     <Namespace Name="System.Net.Http">
       <Type Name="ByteArrayContent" Kind="Class" />
+      <Type Name="CFNetworkHandler" Kind="Class" />
       <Type Name="ClientCertificateOption" Kind="Enumeration" />
       <Type Name="DelegatingHandler" Kind="Class" />
       <Type Name="FormUrlEncodedContent" Kind="Class" />
diff --git a/mcs/class/System.Net.Http/HttpClientEx.cs b/mcs/class/System.Net.Http/HttpClientEx.cs
new file mode 100644 (file)
index 0000000..59456d6
--- /dev/null
@@ -0,0 +1,224 @@
+using System;
+using System.IO;
+using System.Net;
+#if XAMCORE_2_0
+using CoreFoundation;
+using Foundation;
+using ObjCRuntime;
+#elif MONOMAC
+using MonoMac.CoreFoundation;
+using MonoMac.Foundation;
+using MonoMac.ObjCRuntime;
+#else
+using MonoTouch.CoreFoundation;
+using MonoTouch.Foundation;
+using MonoTouch.ObjCRuntime;
+#endif
+
+#if SYSTEM_NET_HTTP && !MONOMAC
+namespace System.Net.Http {
+
+       public partial class HttpClient {
+
+               public HttpClient ()
+                       : this (GetDefaultHandler (), true)
+               {
+               }
+
+               // note: the linker will re-write this to only reference the selected handler
+               // but we want this to work "as expected" even if the application is not being linked
+               static HttpMessageHandler GetDefaultHandler ()
+               {
+                       return RuntimeOptions.GetHttpMessageHandler ();
+               }
+       }
+#else
+// due to historical reasons (around CFNetwork) Xamarin.Mac includes this inside it's profile assembly
+// and not a custom System.Net.Http assembly
+namespace Foundation {
+#endif
+
+       partial class NSUrlSessionHandler {
+
+               bool allowAutoRedirect;
+               ICredentials credentials;
+               bool sentRequest;
+
+               public bool AllowAutoRedirect {
+                       get {
+                               return allowAutoRedirect;
+                       }
+                       set {
+                               EnsureModifiability ();
+                               allowAutoRedirect = value;
+                       }
+               }
+
+               public ICredentials Credentials {
+                       get {
+                               return credentials;
+                       }
+                       set {
+                               EnsureModifiability ();
+                               credentials = value;
+                       }
+               }
+
+               internal void EnsureModifiability ()
+               {
+                       if (sentRequest)
+                               throw new InvalidOperationException (
+                                       "This instance has already started one or more requests. " +
+                                       "Properties can only be modified before sending the first request.");
+               }
+
+               // almost identical to ModernHttpClient version but it uses the constants from monotouch.dll | Xamarin.[iOS|WatchOS|TVOS].dll
+               static Exception createExceptionForNSError(NSError error)
+               {
+                       var webExceptionStatus = WebExceptionStatus.UnknownError;
+
+                       var innerException = new NSErrorException(error);
+
+                       // errors that exists in both share the same error code, so we can use a single switch/case
+                       // this also ease watchOS integration as if does not expose CFNetwork but (I would not be 
+                       // surprised if it)could return some of it's error codes
+#if MONOTOUCH_WATCH
+                       if (error.Domain == NSError.NSUrlErrorDomain) {
+#else
+                       if ((error.Domain == NSError.NSUrlErrorDomain) || (error.Domain == NSError.CFNetworkErrorDomain)) {
+#endif
+                               // Parse the enum into a web exception status or exception. Some
+                               // of these values don't necessarily translate completely to
+                               // what WebExceptionStatus supports, so made some best guesses
+                               // here.  For your reading pleasure, compare these:
+                               //
+                               // Apple docs: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/index.html#//apple_ref/doc/constant_group/URL_Loading_System_Error_Codes
+                               // .NET docs: http://msdn.microsoft.com/en-us/library/system.net.webexceptionstatus(v=vs.110).aspx
+                               switch ((NSUrlError) (long) error.Code) {
+                               case NSUrlError.Cancelled:
+                               case NSUrlError.UserCancelledAuthentication:
+#if !MONOTOUCH_WATCH
+                               case (NSUrlError) NSNetServicesStatus.CancelledError:
+#endif
+                                       // No more processing is required so just return.
+                                       return new OperationCanceledException(error.LocalizedDescription, innerException);
+                               case NSUrlError.BadURL:
+                               case NSUrlError.UnsupportedURL:
+                               case NSUrlError.CannotConnectToHost:
+                               case NSUrlError.ResourceUnavailable:
+                               case NSUrlError.NotConnectedToInternet:
+                               case NSUrlError.UserAuthenticationRequired:
+                               case NSUrlError.InternationalRoamingOff:
+                               case NSUrlError.CallIsActive:
+                               case NSUrlError.DataNotAllowed:
+#if !MONOTOUCH_WATCH
+                               case (NSUrlError) CFNetworkErrors.Socks5BadCredentials:
+                               case (NSUrlError) CFNetworkErrors.Socks5UnsupportedNegotiationMethod:
+                               case (NSUrlError) CFNetworkErrors.Socks5NoAcceptableMethod:
+                               case (NSUrlError) CFNetworkErrors.HttpAuthenticationTypeUnsupported:
+                               case (NSUrlError) CFNetworkErrors.HttpBadCredentials:
+                               case (NSUrlError) CFNetworkErrors.HttpBadURL:
+#endif
+                                       webExceptionStatus = WebExceptionStatus.ConnectFailure;
+                                       break;
+                               case NSUrlError.TimedOut:
+#if !MONOTOUCH_WATCH
+                               case (NSUrlError) CFNetworkErrors.NetServiceTimeout:
+#endif
+                                       webExceptionStatus = WebExceptionStatus.Timeout;
+                                       break;
+                               case NSUrlError.CannotFindHost:
+                               case NSUrlError.DNSLookupFailed:
+#if !MONOTOUCH_WATCH
+                               case (NSUrlError) CFNetworkErrors.HostNotFound:
+                               case (NSUrlError) CFNetworkErrors.NetServiceDnsServiceFailure:
+#endif
+                                       webExceptionStatus = WebExceptionStatus.NameResolutionFailure;
+                                       break;
+                               case NSUrlError.DataLengthExceedsMaximum:
+                                       webExceptionStatus = WebExceptionStatus.MessageLengthLimitExceeded;
+                                       break;
+                               case NSUrlError.NetworkConnectionLost:
+#if !MONOTOUCH_WATCH
+                               case (NSUrlError) CFNetworkErrors.HttpConnectionLost:
+#endif
+                                       webExceptionStatus = WebExceptionStatus.ConnectionClosed;
+                                       break;
+                               case NSUrlError.HTTPTooManyRedirects:
+                               case NSUrlError.RedirectToNonExistentLocation:
+#if !MONOTOUCH_WATCH
+                               case (NSUrlError) CFNetworkErrors.HttpRedirectionLoopDetected:
+#endif
+                                       webExceptionStatus = WebExceptionStatus.ProtocolError;
+                                       break;
+                               case NSUrlError.RequestBodyStreamExhausted:
+#if !MONOTOUCH_WATCH
+                               case (NSUrlError) CFNetworkErrors.SocksUnknownClientVersion:
+                               case (NSUrlError) CFNetworkErrors.SocksUnsupportedServerVersion:
+                               case (NSUrlError) CFNetworkErrors.HttpParseFailure:
+#endif
+                                       webExceptionStatus = WebExceptionStatus.SendFailure;
+                                       break;
+                               case NSUrlError.BadServerResponse:
+                               case NSUrlError.ZeroByteResource:
+                               case NSUrlError.CannotDecodeRawData:
+                               case NSUrlError.CannotDecodeContentData:
+                               case NSUrlError.CannotParseResponse:
+                               case NSUrlError.FileDoesNotExist:
+                               case NSUrlError.FileIsDirectory:
+                               case NSUrlError.NoPermissionsToReadFile:
+                               case NSUrlError.CannotLoadFromNetwork:
+                               case NSUrlError.CannotCreateFile:
+                               case NSUrlError.CannotOpenFile:
+                               case NSUrlError.CannotCloseFile:
+                               case NSUrlError.CannotWriteToFile:
+                               case NSUrlError.CannotRemoveFile:
+                               case NSUrlError.CannotMoveFile:
+                               case NSUrlError.DownloadDecodingFailedMidStream:
+                               case NSUrlError.DownloadDecodingFailedToComplete:
+#if !MONOTOUCH_WATCH
+                               case (NSUrlError) CFNetworkErrors.Socks4RequestFailed:
+                               case (NSUrlError) CFNetworkErrors.Socks4IdentdFailed:
+                               case (NSUrlError) CFNetworkErrors.Socks4IdConflict:
+                               case (NSUrlError) CFNetworkErrors.Socks4UnknownStatusCode:
+                               case (NSUrlError) CFNetworkErrors.Socks5BadState:
+                               case (NSUrlError) CFNetworkErrors.Socks5BadResponseAddr:
+                               case (NSUrlError) CFNetworkErrors.CannotParseCookieFile:
+                               case (NSUrlError) CFNetworkErrors.NetServiceUnknown:
+                               case (NSUrlError) CFNetworkErrors.NetServiceCollision:
+                               case (NSUrlError) CFNetworkErrors.NetServiceNotFound:
+                               case (NSUrlError) CFNetworkErrors.NetServiceInProgress:
+                               case (NSUrlError) CFNetworkErrors.NetServiceBadArgument:
+                               case (NSUrlError) CFNetworkErrors.NetServiceInvalid:
+#endif
+                                       webExceptionStatus = WebExceptionStatus.ReceiveFailure;
+                                       break;
+                               case NSUrlError.SecureConnectionFailed:
+                                       webExceptionStatus = WebExceptionStatus.SecureChannelFailure;
+                                       break;
+                               case NSUrlError.ServerCertificateHasBadDate:
+                               case NSUrlError.ServerCertificateHasUnknownRoot:
+                               case NSUrlError.ServerCertificateNotYetValid:
+                               case NSUrlError.ServerCertificateUntrusted:
+                               case NSUrlError.ClientCertificateRejected:
+                               case NSUrlError.ClientCertificateRequired:
+                                       webExceptionStatus = WebExceptionStatus.TrustFailure;
+                                       break;
+#if !MONOTOUCH_WATCH
+                               case (NSUrlError) CFNetworkErrors.HttpProxyConnectionFailure:
+                               case (NSUrlError) CFNetworkErrors.HttpBadProxyCredentials:
+                               case (NSUrlError) CFNetworkErrors.PacFileError:
+                               case (NSUrlError) CFNetworkErrors.PacFileAuth:
+                               case (NSUrlError) CFNetworkErrors.HttpsProxyConnectionFailure:
+                               case (NSUrlError) CFNetworkErrors.HttpsProxyFailureUnexpectedResponseToConnectMethod:
+                                       webExceptionStatus = WebExceptionStatus.RequestProhibitedByProxy;
+                                       break;
+#endif
+                               }
+                       } 
+
+                       // Always create a WebException so that it can be handled by the client.
+                       return new WebException(error.LocalizedDescription, innerException); //, webExceptionStatus, response: null);
+               }
+       }
+}
index bf1cbbd2799e04788e4554d8964bcdc757d54d64..9abcf2e80f62071ca0cf14a470dfaed396b3596a 100644 (file)
@@ -6,6 +6,9 @@ LIBRARY = System.Net.Http.dll
 
 LIB_REFS = System.Core System
 LIB_MCS_FLAGS = $(EXTRA_LIB_MCS_FLAGS)
+ifeq (monodroid,$(PROFILE))
+LIB_MCS_FLAGS += -d:XAMARIN_MODERN
+endif
 
 TEST_LIB_REFS = System System.Core
 TEST_MCS_FLAGS =
diff --git a/mcs/class/System.Net.Http/System.Net.Http/HttpClient.android.cs b/mcs/class/System.Net.Http/System.Net.Http/HttpClient.android.cs
new file mode 100644 (file)
index 0000000..f48b49c
--- /dev/null
@@ -0,0 +1,38 @@
+using System;
+using System.Reflection;
+
+namespace System.Net.Http {
+       public partial class HttpClient {
+
+               public HttpClient ()
+                       : this (GetDefaultHandler (), true)
+               {
+               }
+
+               static HttpMessageHandler GetDefaultHandler ()
+               {
+                       Type type = Type.GetType("Android.Runtime.AndroidEnvironment, Mono.Android");
+                       if (type == null)
+                               return GetFallback ("Invalid Mono.Android assembly? Cannot find Android.Runtime.AndroidEnvironment");
+
+                       MethodInfo method = type.GetMethod ("GetHttpMessageHandler", BindingFlags.Static | BindingFlags.NonPublic);
+                       if (method == null)
+                               return GetFallback ("Your Xamarin.Android version does not support obtaining of the custom HttpClientHandler");
+
+                       object ret = method.Invoke (null, null);
+                       if (ret == null)
+                               return GetFallback ("Xamarin.Android returned no custom HttpClientHandler");
+
+                       var handler = ret as HttpMessageHandler;
+                       if (handler == null)
+                               return GetFallback ($"{ret?.GetType()} is not a valid HttpMessageHandler");
+                       return handler;
+               }
+
+               static HttpMessageHandler GetFallback (string message)
+               {
+                       Console.WriteLine (message + ". Defaulting to System.Net.Http.HttpClientHandler");
+                       return new HttpClientHandler ();
+               }
+       }
+}
diff --git a/mcs/class/System.Net.Http/monodroid_System.Net.Http.dll.sources b/mcs/class/System.Net.Http/monodroid_System.Net.Http.dll.sources
new file mode 100644 (file)
index 0000000..acaa6a3
--- /dev/null
@@ -0,0 +1,2 @@
+#include System.Net.Http.dll.sources
+System.Net.Http/HttpClient.android.cs
index b0c9706a1dbdd42ab798bdfcf4cfebe807e8ef57..547733453e01d33328e916ef748bc572767657f9 100644 (file)
@@ -15,6 +15,7 @@ System.Runtime.Serialization/DataContractSerializerTest_NullableWithDictionary.c
 System.Runtime.Serialization/DataContractSerializerTest_InvalidCharacters.cs
 System.Runtime.Serialization/DataContractSerializerTest_ISerializable.cs
 System.Runtime.Serialization/DataContractSerializerTest.cs
+System.Runtime.Serialization/Exceptions.cs
 System.Runtime.Serialization/KnownTypeAttributeTest.cs
 System.Runtime.Serialization/XmlObjectSerializerTest.cs
 System.Runtime.Serialization/XsdDataContractExporterTest.cs
diff --git a/mcs/class/System.Runtime.Serialization/Test/System.Runtime.Serialization/Exceptions.cs b/mcs/class/System.Runtime.Serialization/Test/System.Runtime.Serialization/Exceptions.cs
new file mode 100644 (file)
index 0000000..4303c6c
--- /dev/null
@@ -0,0 +1,95 @@
+//
+// Exceptions
+//
+// Authors:
+//      Andi McClure (andi.mcclure@xamarin.com)
+//
+// Copyright 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.IO;
+using System.Runtime.Serialization;
+using System.Runtime.Serialization.Formatters.Binary;
+using NUnit.Framework;
+
+namespace MonoTests.System.Runtime.Serialization
+{
+       [TestFixture]
+       public class Exceptions
+       {
+               [Serializable]
+               public class SerializableException : Exception
+               {
+                       public string Data;
+
+                       public SerializableException (string data) {
+                               Data = data;
+
+                               SerializeObjectState += HandleSerialization;
+                       }
+
+                       private static void HandleSerialization (object exception, SafeSerializationEventArgs eventArgs) {
+                               eventArgs.AddSerializedState (new SerializableExceptionState (exception));
+                       }
+
+                       [Serializable]
+                       private class SerializableExceptionState : ISafeSerializationData {
+                               private string Data;
+
+                               public SerializableExceptionState (object _exception) {
+                                       SerializableException exception = (SerializableException)_exception;
+
+                                       Data = exception.Data;
+                               }
+
+                               public void CompleteDeserialization (object _exception) {
+                                       SerializableException exception = (SerializableException)_exception;
+                                       exception.SerializeObjectState += HandleSerialization;
+
+                                       exception.Data = Data;
+                               }
+                       }
+               }
+
+               // Effectively tests SerializeObjectState handler support on System.Exception
+               [Test]
+               public void Exception_SerializeObjectState () {
+                       SerializableException exception = new SerializableException ("success");
+                       SerializableException deserializedException;
+                       BinaryFormatter binaryFormatter = new BinaryFormatter ();
+
+                       using (MemoryStream memoryStream = new MemoryStream ())
+                       {
+                               binaryFormatter.Serialize (memoryStream, exception);
+                               memoryStream.Flush ();
+
+                               memoryStream.Seek (0, SeekOrigin.Begin);
+
+                               deserializedException = (SerializableException)binaryFormatter.Deserialize (memoryStream);
+                       }
+
+                       Assert.AreEqual ("success", deserializedException.Data);
+               }
+       }
+}
\ No newline at end of file
diff --git a/mcs/class/System.Web.Mobile/Assembly/AssemblyInfo.cs b/mcs/class/System.Web.Mobile/Assembly/AssemblyInfo.cs
new file mode 100644 (file)
index 0000000..7870e25
--- /dev/null
@@ -0,0 +1,53 @@
+//
+// AssemblyInfo.cs
+//
+// Authors:
+//     Marek Safar (marek.safar@gmail.com)
+//
+// Copyright 2016 Xamarin Inc (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Reflection;
+using System.Resources;
+using System.Security;
+using System.Security.Permissions;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about the assembly
+
+[assembly: AssemblyTitle ("System.Web.Mobile.dll")]
+[assembly: AssemblyDescription ("System.Web.Mobile.dll")]
+[assembly: AssemblyDefaultAlias ("System.Web.Mobile.dll")]
+
+[assembly: AssemblyCompany (Consts.MonoCompany)]
+[assembly: AssemblyProduct (Consts.MonoProduct)]
+[assembly: AssemblyCopyright (Consts.MonoCopyright)]
+[assembly: AssemblyVersion (Consts.FxVersion)]
+[assembly: SatelliteContractVersion (Consts.FxVersion)]
+[assembly: AssemblyInformationalVersion (Consts.FxFileVersion)]
+[assembly: AssemblyFileVersion (Consts.FxFileVersion)]
+
+[assembly: CLSCompliant (true)]
+
diff --git a/mcs/class/System.Web.Mobile/Makefile b/mcs/class/System.Web.Mobile/Makefile
new file mode 100644 (file)
index 0000000..c2c977e
--- /dev/null
@@ -0,0 +1,10 @@
+thisdir = class/System.Web.Mobile
+SUBDIRS = 
+include ../../build/rules.make
+
+LIBRARY = System.Web.Mobile.dll
+
+LIB_REFS =
+LIB_MCS_FLAGS = -delaysign -keyfile:../msfinal.pub
+
+include ../../build/library.make
diff --git a/mcs/class/System.Web.Mobile/System.Web.Mobile.dll.sources b/mcs/class/System.Web.Mobile/System.Web.Mobile.dll.sources
new file mode 100644 (file)
index 0000000..e49bef5
--- /dev/null
@@ -0,0 +1,2 @@
+../../build/common/Consts.cs
+Assembly/AssemblyInfo.cs
diff --git a/mcs/class/System.Web.RegularExpressions/Assembly/AssemblyInfo.cs b/mcs/class/System.Web.RegularExpressions/Assembly/AssemblyInfo.cs
new file mode 100644 (file)
index 0000000..ebd7f45
--- /dev/null
@@ -0,0 +1,53 @@
+//
+// AssemblyInfo.cs
+//
+// Authors:
+//     Marek Safar (marek.safar@gmail.com)
+//
+// Copyright 2016 Xamarin Inc (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Reflection;
+using System.Resources;
+using System.Security;
+using System.Security.Permissions;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about the assembly
+
+[assembly: AssemblyTitle ("System.Web.RegularExpressions.dll")]
+[assembly: AssemblyDescription ("System.Web.RegularExpressions.dll")]
+[assembly: AssemblyDefaultAlias ("System.Web.RegularExpressions.dll")]
+
+[assembly: AssemblyCompany (Consts.MonoCompany)]
+[assembly: AssemblyProduct (Consts.MonoProduct)]
+[assembly: AssemblyCopyright (Consts.MonoCopyright)]
+[assembly: AssemblyVersion (Consts.FxVersion)]
+[assembly: SatelliteContractVersion (Consts.FxVersion)]
+[assembly: AssemblyInformationalVersion (Consts.FxFileVersion)]
+[assembly: AssemblyFileVersion (Consts.FxFileVersion)]
+
+[assembly: CLSCompliant (true)]
+
diff --git a/mcs/class/System.Web.RegularExpressions/Makefile b/mcs/class/System.Web.RegularExpressions/Makefile
new file mode 100644 (file)
index 0000000..a16648c
--- /dev/null
@@ -0,0 +1,10 @@
+thisdir = class/System.Web.RegularExpressions
+SUBDIRS = 
+include ../../build/rules.make
+
+LIBRARY = System.Web.RegularExpressions.dll
+
+LIB_REFS =
+LIB_MCS_FLAGS = -delaysign -keyfile:../msfinal.pub
+
+include ../../build/library.make
diff --git a/mcs/class/System.Web.RegularExpressions/System.Web.RegularExpressions.dll.sources b/mcs/class/System.Web.RegularExpressions/System.Web.RegularExpressions.dll.sources
new file mode 100644 (file)
index 0000000..e49bef5
--- /dev/null
@@ -0,0 +1,2 @@
+../../build/common/Consts.cs
+Assembly/AssemblyInfo.cs
diff --git a/mcs/class/System.Workflow.Activities/Assembly/AssemblyInfo.cs b/mcs/class/System.Workflow.Activities/Assembly/AssemblyInfo.cs
new file mode 100644 (file)
index 0000000..5a1b6a1
--- /dev/null
@@ -0,0 +1,53 @@
+//
+// AssemblyInfo.cs
+//
+// Authors:
+//     Marek Safar (marek.safar@gmail.com)
+//
+// Copyright 2016 Xamarin Inc (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Reflection;
+using System.Resources;
+using System.Security;
+using System.Security.Permissions;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about the assembly
+
+[assembly: AssemblyTitle ("System.Workflow.Activities.dll")]
+[assembly: AssemblyDescription ("System.Workflow.Activities.dll")]
+[assembly: AssemblyDefaultAlias ("System.Workflow.Activities.dll")]
+
+[assembly: AssemblyCompany (Consts.MonoCompany)]
+[assembly: AssemblyProduct (Consts.MonoProduct)]
+[assembly: AssemblyCopyright (Consts.MonoCopyright)]
+[assembly: AssemblyVersion (Consts.FxVersion)]
+[assembly: SatelliteContractVersion (Consts.FxVersion)]
+[assembly: AssemblyInformationalVersion (Consts.FxFileVersion)]
+[assembly: AssemblyFileVersion (Consts.FxFileVersion)]
+
+[assembly: CLSCompliant (true)]
+
diff --git a/mcs/class/System.Workflow.Activities/Makefile b/mcs/class/System.Workflow.Activities/Makefile
new file mode 100644 (file)
index 0000000..bda9e38
--- /dev/null
@@ -0,0 +1,10 @@
+thisdir = class/System.Workflow.Activities
+SUBDIRS = 
+include ../../build/rules.make
+
+LIBRARY = System.Workflow.Activities.dll
+
+LIB_REFS =
+LIB_MCS_FLAGS = -delaysign -keyfile:../winfx.pub
+
+include ../../build/library.make
diff --git a/mcs/class/System.Workflow.Activities/System.Workflow.Activities.dll.sources b/mcs/class/System.Workflow.Activities/System.Workflow.Activities.dll.sources
new file mode 100644 (file)
index 0000000..e49bef5
--- /dev/null
@@ -0,0 +1,2 @@
+../../build/common/Consts.cs
+Assembly/AssemblyInfo.cs
diff --git a/mcs/class/System.Workflow.ComponentModel/Assembly/AssemblyInfo.cs b/mcs/class/System.Workflow.ComponentModel/Assembly/AssemblyInfo.cs
new file mode 100644 (file)
index 0000000..6526e77
--- /dev/null
@@ -0,0 +1,53 @@
+//
+// AssemblyInfo.cs
+//
+// Authors:
+//     Marek Safar (marek.safar@gmail.com)
+//
+// Copyright 2016 Xamarin Inc (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Reflection;
+using System.Resources;
+using System.Security;
+using System.Security.Permissions;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about the assembly
+
+[assembly: AssemblyTitle ("System.Workflow.ComponentModel.dll")]
+[assembly: AssemblyDescription ("System.Workflow.ComponentModel.dll")]
+[assembly: AssemblyDefaultAlias ("System.Workflow.ComponentModel.dll")]
+
+[assembly: AssemblyCompany (Consts.MonoCompany)]
+[assembly: AssemblyProduct (Consts.MonoProduct)]
+[assembly: AssemblyCopyright (Consts.MonoCopyright)]
+[assembly: AssemblyVersion (Consts.FxVersion)]
+[assembly: SatelliteContractVersion (Consts.FxVersion)]
+[assembly: AssemblyInformationalVersion (Consts.FxFileVersion)]
+[assembly: AssemblyFileVersion (Consts.FxFileVersion)]
+
+[assembly: CLSCompliant (true)]
+
diff --git a/mcs/class/System.Workflow.ComponentModel/Makefile b/mcs/class/System.Workflow.ComponentModel/Makefile
new file mode 100644 (file)
index 0000000..6b988f2
--- /dev/null
@@ -0,0 +1,10 @@
+thisdir = class/System.Workflow.ComponentModel
+SUBDIRS = 
+include ../../build/rules.make
+
+LIBRARY = System.Workflow.ComponentModel.dll
+
+LIB_REFS =
+LIB_MCS_FLAGS = -delaysign -keyfile:../winfx.pub
+
+include ../../build/library.make
diff --git a/mcs/class/System.Workflow.ComponentModel/System.Workflow.ComponentModel.dll.sources b/mcs/class/System.Workflow.ComponentModel/System.Workflow.ComponentModel.dll.sources
new file mode 100644 (file)
index 0000000..e49bef5
--- /dev/null
@@ -0,0 +1,2 @@
+../../build/common/Consts.cs
+Assembly/AssemblyInfo.cs
diff --git a/mcs/class/System.Workflow.Runtime/Assembly/AssemblyInfo.cs b/mcs/class/System.Workflow.Runtime/Assembly/AssemblyInfo.cs
new file mode 100644 (file)
index 0000000..d967638
--- /dev/null
@@ -0,0 +1,53 @@
+//
+// AssemblyInfo.cs
+//
+// Authors:
+//     Marek Safar (marek.safar@gmail.com)
+//
+// Copyright 2016 Xamarin Inc (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Reflection;
+using System.Resources;
+using System.Security;
+using System.Security.Permissions;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about the assembly
+
+[assembly: AssemblyTitle ("System.Workflow.Runtime.dll")]
+[assembly: AssemblyDescription ("System.Workflow.Runtime.dll")]
+[assembly: AssemblyDefaultAlias ("System.Workflow.Runtime.dll")]
+
+[assembly: AssemblyCompany (Consts.MonoCompany)]
+[assembly: AssemblyProduct (Consts.MonoProduct)]
+[assembly: AssemblyCopyright (Consts.MonoCopyright)]
+[assembly: AssemblyVersion (Consts.FxVersion)]
+[assembly: SatelliteContractVersion (Consts.FxVersion)]
+[assembly: AssemblyInformationalVersion (Consts.FxFileVersion)]
+[assembly: AssemblyFileVersion (Consts.FxFileVersion)]
+
+[assembly: CLSCompliant (true)]
+
diff --git a/mcs/class/System.Workflow.Runtime/Makefile b/mcs/class/System.Workflow.Runtime/Makefile
new file mode 100644 (file)
index 0000000..d8c4f7c
--- /dev/null
@@ -0,0 +1,10 @@
+thisdir = class/System.Workflow.Runtime
+SUBDIRS = 
+include ../../build/rules.make
+
+LIBRARY = System.Workflow.Runtime.dll
+
+LIB_REFS =
+LIB_MCS_FLAGS = -delaysign -keyfile:../winfx.pub
+
+include ../../build/library.make
diff --git a/mcs/class/System.Workflow.Runtime/System.Workflow.Runtime.dll.sources b/mcs/class/System.Workflow.Runtime/System.Workflow.Runtime.dll.sources
new file mode 100644 (file)
index 0000000..e49bef5
--- /dev/null
@@ -0,0 +1,2 @@
+../../build/common/Consts.cs
+Assembly/AssemblyInfo.cs
index 74ff995dd868b5cd03e87657edcd24cd7ae4b03b..3adbdbf3917b8b3ab8e8be7411a7b8b0dd40c82c 100644 (file)
@@ -50,7 +50,7 @@ TXT_RESOURCE_STRINGS = ../../../external/referencesource/System/System.txt
 ifdef MOBILE_PROFILE
 LIB_MCS_FLAGS += -d:INSIDE_SYSTEM -d:SECURITY_DEP
 else
-EXTERN_ALIAS_FLAGS = -d:MONO_SECURITY_ALIAS -d:MONO_X509_ALIAS
+EXTERN_ALIAS_FLAGS = -d:MONO_SECURITY_ALIAS
 endif
 
 #
@@ -59,7 +59,7 @@ endif
 ifeq (secxml/, $(intermediate))
 LOCAL_MCS_FLAGS =
 LIB_REFS += bare/System.Xml MonoSecurity=Mono.Security
-LIB_MCS_FLAGS += -d:SECURITY_DEP -d:XML_DEP -r:PrebuiltSystem=$(bare_libdir)/System.dll $(EXTERN_ALIAS_FLAGS)
+LIB_MCS_FLAGS += -d:SECURITY_DEP -d:XML_DEP $(EXTERN_ALIAS_FLAGS)
 endif
 
 #
@@ -67,7 +67,7 @@ endif
 #
 ifndef intermediate
 LIB_REFS += System.Xml MonoSecurity=Mono.Security
-LIB_MCS_FLAGS += -d:SECURITY_DEP -d:XML_DEP -r:PrebuiltSystem=$(secxml_libdir)/System.dll $(EXTERN_ALIAS_FLAGS)
+LIB_MCS_FLAGS += -d:SECURITY_DEP -d:XML_DEP $(EXTERN_ALIAS_FLAGS)
 
 ifndef MOBILE_PROFILE
 LIB_REFS += System.Configuration
index 6ae2b9f3ca8d7d2ef1cc06fc06d4ab80a73f3fda..e79c167c01ecec86236184b3a72cbe33d752d8a7 100644 (file)
@@ -26,9 +26,6 @@
 
 #if SECURITY_DEP
 
-#if MONO_X509_ALIAS
-extern alias PrebuiltSystem;
-#endif
 #if MONO_SECURITY_ALIAS
 extern alias MonoSecurity;
 #endif
@@ -38,13 +35,6 @@ using MSI = MonoSecurity::Mono.Security.Interface;
 #else
 using MSI = Mono.Security.Interface;
 #endif
-#if MONO_X509_ALIAS
-using XX509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-using XX509Chain = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509Chain;
-#else
-using XX509CertificateCollection = System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-using XX509Chain = System.Security.Cryptography.X509Certificates.X509Chain;
-#endif
 
 using System;
 using System.IO;
@@ -64,7 +54,7 @@ namespace Mono.Net.Security.Private
                        if (callback == null)
                                return null;
 
-                       return (h, c, ch, e) => callback (h, c, (X509Chain)(object)ch, (SslPolicyErrors)e);
+                       return (h, c, ch, e) => callback (h, c, ch, (SslPolicyErrors)e);
                }
 
                internal static MSI.MonoLocalCertificateSelectionCallback PublicToMono (LocalCertificateSelectionCallback callback)
@@ -72,7 +62,7 @@ namespace Mono.Net.Security.Private
                        if (callback == null)
                                return null;
 
-                       return (t, lc, rc, ai) => callback (null, t, (XX509CertificateCollection)(object)lc, rc, ai);
+                       return (t, lc, rc, ai) => callback (null, t, lc, rc, ai);
                }
 
                internal static MSI.MonoRemoteCertificateValidationCallback InternalToMono (RemoteCertValidationCallback callback)
@@ -80,7 +70,7 @@ namespace Mono.Net.Security.Private
                        if (callback == null)
                                return null;
 
-                       return (h, c, ch, e) => callback (h, c, (X509Chain)(object)ch, (SslPolicyErrors)e);
+                       return (h, c, ch, e) => callback (h, c, ch, (SslPolicyErrors)e);
                }
 
                internal static RemoteCertificateValidationCallback InternalToPublic (string hostname, RemoteCertValidationCallback callback)
@@ -96,7 +86,7 @@ namespace Mono.Net.Security.Private
                        if (callback == null)
                                return null;
 
-                       return (t, lc, rc, ai) => callback (t, (XX509CertificateCollection)(object)lc, rc, ai);
+                       return (t, lc, rc, ai) => callback (t, lc, rc, ai);
                }
 
                internal static RemoteCertificateValidationCallback MonoToPublic (MSI.MonoRemoteCertificateValidationCallback callback)
@@ -104,7 +94,7 @@ namespace Mono.Net.Security.Private
                        if (callback == null)
                                return null;
 
-                       return (t, c, ch, e) => callback (null, c, (XX509Chain)(object)ch, (MSI.MonoSslPolicyErrors)e);
+                       return (t, c, ch, e) => callback (null, c, ch, (MSI.MonoSslPolicyErrors)e);
                }
 
                internal static LocalCertificateSelectionCallback MonoToPublic (MSI.MonoLocalCertificateSelectionCallback callback)
@@ -112,7 +102,7 @@ namespace Mono.Net.Security.Private
                        if (callback == null)
                                return null;
 
-                       return (s, t, lc, rc, ai) => callback (t, (XX509CertificateCollection)(object)lc, rc, ai);
+                       return (s, t, lc, rc, ai) => callback (t, lc, rc, ai);
                }
 
                internal static RemoteCertValidationCallback MonoToInternal (MSI.MonoRemoteCertificateValidationCallback callback)
@@ -120,7 +110,7 @@ namespace Mono.Net.Security.Private
                        if (callback == null)
                                return null;
 
-                       return (h, c, ch, e) => callback (h, c, (XX509Chain)(object)ch, (MSI.MonoSslPolicyErrors)e);
+                       return (h, c, ch, e) => callback (h, c, ch, (MSI.MonoSslPolicyErrors)e);
                }
 
                internal static LocalCertSelectionCallback MonoToInternal (MSI.MonoLocalCertificateSelectionCallback callback)
@@ -128,7 +118,7 @@ namespace Mono.Net.Security.Private
                        if (callback == null)
                                return null;
 
-                       return (t, lc, rc, ai) => callback (t, (XX509CertificateCollection)(object)lc, rc, ai);
+                       return (t, lc, rc, ai) => callback (t, lc, rc, ai);
                }
 
        }
index 9a5eab25ce6f4aee6f104fb0eb41ef4479c53c2c..5d2812d2738e4c51c72af55564a3e3c95356e0c4 100644 (file)
@@ -34,9 +34,6 @@
 #if MONO_SECURITY_ALIAS
 extern alias MonoSecurity;
 #endif
-#if MONO_X509_ALIAS
-extern alias PrebuiltSystem;
-#endif
 
 #if MONO_SECURITY_ALIAS
 using MonoSecurity::Mono.Security.Interface;
@@ -47,13 +44,8 @@ using Mono.Security.Interface;
 using MSX = Mono.Security.X509;
 using Mono.Security.X509.Extensions;
 #endif
-#if MONO_X509_ALIAS
-using XX509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-using XX509Chain = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509Chain;
-#else
 using XX509CertificateCollection = System.Security.Cryptography.X509Certificates.X509CertificateCollection;
 using XX509Chain = System.Security.Cryptography.X509Certificates.X509Chain;
-#endif
 
 using System;
 using System.Net;
@@ -257,7 +249,7 @@ namespace Mono.Net.Security
                public ValidationResult ValidateCertificate (string host, bool serverMode, X509Certificate leaf, XX509Chain xchain)
                {
                        try {
-                               var chain = (X509Chain)(object)xchain;
+                               var chain = xchain;
                                var result = ValidateChain (host, serverMode, leaf, chain, null, 0);
                                if (tlsStream != null)
                                        tlsStream.CertificateValidationFailed = result == null || !result.Trusted || result.UserDenied;
@@ -326,9 +318,9 @@ namespace Mono.Net.Security
                        bool providerValidated = false;
                        if (provider != null && provider.HasCustomSystemCertificateValidator) {
                                var xerrors = (MonoSslPolicyErrors)errors;
-                               var xchain = (XX509Chain)(object)chain;
+                               var xchain = chain;
                                providerValidated = provider.InvokeSystemCertificateValidator (this, host, server, certs, wantsChain, ref xchain, out result, ref xerrors, ref status11);
-                               chain = (X509Chain)(object)xchain;
+                               chain = xchain;
                                errors = (SslPolicyErrors)xerrors;
                        } else if (wantsChain) {
                                chain = SystemCertificateValidator.CreateX509Chain (certs);
@@ -363,7 +355,7 @@ namespace Mono.Net.Security
 
                public bool InvokeSystemValidator (string targetHost, bool serverMode, XX509CertificateCollection certificates, XX509Chain xchain, ref MonoSslPolicyErrors xerrors, ref int status11)
                {
-                       X509Chain chain = (X509Chain)(object)xchain;
+                       X509Chain chain = xchain;
                        var errors = (SslPolicyErrors)xerrors;
                        var result = SystemCertificateValidator.Evaluate (settings, targetHost, certificates, chain, ref errors, ref status11);
                        xerrors = (MonoSslPolicyErrors)errors;
index 50193cc2ec19c6461764e14b83677de04c00ad1f..69daf52111386fec045981afd515d03864d37d0c 100644 (file)
 // THE SOFTWARE.
 
 #if SECURITY_DEP
-#if MONO_X509_ALIAS
-extern alias PrebuiltSystem;
-#endif
 #if MONO_SECURITY_ALIAS
 extern alias MonoSecurity;
 #endif
 
-#if MONO_X509_ALIAS
-using X509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-#endif
 #if MONO_SECURITY_ALIAS
 using MSI = MonoSecurity::Mono.Security.Interface;
 #else
index 478ed585b59c2956d8c6d0aa0fd2c115cb3405f0..50b4cd9c8c460de1aee7dd57382fe1eb0b204326 100644 (file)
 #if MONO_SECURITY_ALIAS
 extern alias MonoSecurity;
 #endif
-#if MONO_X509_ALIAS
-extern alias PrebuiltSystem;
-#endif
 
 #if MONO_SECURITY_ALIAS
 using MonoSecurity::Mono.Security.Interface;
 #else
 using Mono.Security.Interface;
 #endif
-#if MONO_X509_ALIAS
-using XX509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-#else
 using XX509CertificateCollection = System.Security.Cryptography.X509Certificates.X509CertificateCollection;
 #endif
-#endif
 
 using System;
 using System.IO;
index ab0bc51897425ca78a33ef4061ab0ffb0d78b5ad..1a6672f6c5c36f634b575715a611d14148e86c0a 100644 (file)
@@ -34,9 +34,6 @@
 
 #if SECURITY_DEP
 
-#if MONO_X509_ALIAS
-extern alias PrebuiltSystem;
-#endif
 #if MONO_SECURITY_ALIAS
 extern alias MonoSecurity;
 #endif
@@ -56,9 +53,6 @@ using MonoSecurityProtocolType = Mono.Security.Protocol.Tls.SecurityProtocolType
 using Mono.Security.Protocol.Tls;
 using Mono.Security.Interface;
 #endif
-#if MONO_X509_ALIAS
-using X509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-#endif
 
 using CipherAlgorithmType = System.Security.Authentication.CipherAlgorithmType;
 using HashAlgorithmType = System.Security.Authentication.HashAlgorithmType;
index d6f6e5296f454a65ac7ca9f27b6d3e001087e539..7ea40e1940172a2d422936d04fe51d0431956a69 100644 (file)
 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 // THE SOFTWARE.
 #if SECURITY_DEP
-#if MONO_X509_ALIAS
-extern alias PrebuiltSystem;
-#endif
 #if MONO_SECURITY_ALIAS
 extern alias MonoSecurity;
 #endif
 
-#if MONO_X509_ALIAS
-using XHttpWebRequest = PrebuiltSystem::System.Net.HttpWebRequest;
-using XSslProtocols = PrebuiltSystem::System.Security.Authentication.SslProtocols;
-using XX509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-#else
 using XHttpWebRequest = System.Net.HttpWebRequest;
 using XSslProtocols = System.Security.Authentication.SslProtocols;
 using XX509CertificateCollection = System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-#endif
 
 #if MONO_SECURITY_ALIAS
 using MonoSecurity::Mono.Security.Interface;
index dfb5c8c450ac60d1be017d770bff0d34748956da..776751537bdae8df69c5134c20ade5c097c65eb5 100644 (file)
@@ -26,9 +26,6 @@
 
 #if SECURITY_DEP
 
-#if MONO_X509_ALIAS
-extern alias PrebuiltSystem;
-#endif
 #if MONO_SECURITY_ALIAS
 extern alias MonoSecurity;
 #endif
@@ -38,27 +35,6 @@ using MSI = MonoSecurity::Mono.Security.Interface;
 #else
 using MSI = Mono.Security.Interface;
 #endif
-#if MONO_X509_ALIAS
-using XX509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-
-using XTransportContext = PrebuiltSystem::System.Net.TransportContext;
-using XAuthenticatedStream = PrebuiltSystem::System.Net.Security.AuthenticatedStream;
-
-using XCipherAlgorithmType = PrebuiltSystem::System.Security.Authentication.CipherAlgorithmType;
-using XHashAlgorithmType = PrebuiltSystem::System.Security.Authentication.HashAlgorithmType;
-using XExchangeAlgorithmType = PrebuiltSystem::System.Security.Authentication.ExchangeAlgorithmType;
-using XSslProtocols = PrebuiltSystem::System.Security.Authentication.SslProtocols;
-#else
-using XX509CertificateCollection = System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-
-using XTransportContext = System.Net.TransportContext;
-using XAuthenticatedStream = System.Net.Security.AuthenticatedStream;
-
-using XCipherAlgorithmType = System.Security.Authentication.CipherAlgorithmType;
-using XHashAlgorithmType = System.Security.Authentication.HashAlgorithmType;
-using XExchangeAlgorithmType = System.Security.Authentication.ExchangeAlgorithmType;
-using XSslProtocols = System.Security.Authentication.SslProtocols;
-#endif
 
 using System;
 using System.IO;
@@ -96,9 +72,9 @@ namespace Mono.Net.Security.Private
                        Impl.AuthenticateAsClient (targetHost);
                }
 
-               public void AuthenticateAsClient (string targetHost, XX509CertificateCollection clientCertificates, XSslProtocols enabledSslProtocols, bool checkCertificateRevocation)
+               public void AuthenticateAsClient (string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
                {
-                       Impl.AuthenticateAsClient (targetHost, clientCertificates, (SslProtocols)enabledSslProtocols, checkCertificateRevocation);
+                       Impl.AuthenticateAsClient (targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation);
                }
 
                public IAsyncResult BeginAuthenticateAsClient (string targetHost, AsyncCallback asyncCallback, object asyncState)
@@ -106,9 +82,9 @@ namespace Mono.Net.Security.Private
                        return Impl.BeginAuthenticateAsClient (targetHost, asyncCallback, asyncState);
                }
 
-               public IAsyncResult BeginAuthenticateAsClient (string targetHost, XX509CertificateCollection clientCertificates, XSslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
+               public IAsyncResult BeginAuthenticateAsClient (string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
                {
-                       return Impl.BeginAuthenticateAsClient (targetHost, clientCertificates, (SslProtocols)enabledSslProtocols, checkCertificateRevocation, asyncCallback, asyncState);
+                       return Impl.BeginAuthenticateAsClient (targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation, asyncCallback, asyncState);
                }
 
                public void EndAuthenticateAsClient (IAsyncResult asyncResult)
@@ -121,9 +97,9 @@ namespace Mono.Net.Security.Private
                        Impl.AuthenticateAsServer (serverCertificate);
                }
 
-               public void AuthenticateAsServer (X509Certificate serverCertificate, bool clientCertificateRequired, XSslProtocols enabledSslProtocols, bool checkCertificateRevocation)
+               public void AuthenticateAsServer (X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
                {
-                       Impl.AuthenticateAsServer (serverCertificate, clientCertificateRequired, (SslProtocols)enabledSslProtocols, checkCertificateRevocation);
+                       Impl.AuthenticateAsServer (serverCertificate, clientCertificateRequired, enabledSslProtocols, checkCertificateRevocation);
                }
 
                public IAsyncResult BeginAuthenticateAsServer (X509Certificate serverCertificate, AsyncCallback asyncCallback, object asyncState)
@@ -131,9 +107,9 @@ namespace Mono.Net.Security.Private
                        return Impl.BeginAuthenticateAsServer (serverCertificate, asyncCallback, asyncState);
                }
 
-               public IAsyncResult BeginAuthenticateAsServer (X509Certificate serverCertificate, bool clientCertificateRequired, XSslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
+               public IAsyncResult BeginAuthenticateAsServer (X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
                {
-                       return Impl.BeginAuthenticateAsServer (serverCertificate, clientCertificateRequired, (SslProtocols)enabledSslProtocols, checkCertificateRevocation, asyncCallback, asyncState);
+                       return Impl.BeginAuthenticateAsServer (serverCertificate, clientCertificateRequired, enabledSslProtocols, checkCertificateRevocation, asyncCallback, asyncState);
                }
 
                public void EndAuthenticateAsServer (IAsyncResult asyncResult)
@@ -146,9 +122,9 @@ namespace Mono.Net.Security.Private
                        return Impl.AuthenticateAsClientAsync (targetHost);
                }
 
-               public Task AuthenticateAsClientAsync (string targetHost, XX509CertificateCollection clientCertificates, XSslProtocols enabledSslProtocols, bool checkCertificateRevocation)
+               public Task AuthenticateAsClientAsync (string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
                {
-                       return Impl.AuthenticateAsClientAsync (targetHost, clientCertificates, (SslProtocols)enabledSslProtocols, checkCertificateRevocation);
+                       return Impl.AuthenticateAsClientAsync (targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation);
                }
 
                public Task AuthenticateAsServerAsync (X509Certificate serverCertificate)
@@ -156,9 +132,9 @@ namespace Mono.Net.Security.Private
                        return Impl.AuthenticateAsServerAsync (serverCertificate);
                }
 
-               public Task AuthenticateAsServerAsync (X509Certificate serverCertificate, bool clientCertificateRequired, XSslProtocols enabledSslProtocols, bool checkCertificateRevocation)
+               public Task AuthenticateAsServerAsync (X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
                {
-                       return Impl.AuthenticateAsServerAsync (serverCertificate, clientCertificateRequired, (SslProtocols)enabledSslProtocols, checkCertificateRevocation);
+                       return Impl.AuthenticateAsServerAsync (serverCertificate, clientCertificateRequired, enabledSslProtocols, checkCertificateRevocation);
                }
 
                public void Flush ()
@@ -201,8 +177,8 @@ namespace Mono.Net.Security.Private
                        Impl.EndWrite (asyncResult);
                }
 
-               public XTransportContext TransportContext {
-                       get { return (XTransportContext)(object)Impl.TransportContext; }
+               public TransportContext TransportContext {
+                       get { return Impl.TransportContext; }
                }
 
                public bool IsAuthenticated {
@@ -225,24 +201,24 @@ namespace Mono.Net.Security.Private
                        get { return Impl.IsServer; }
                }
 
-               public XCipherAlgorithmType CipherAlgorithm {
-                       get { return (XCipherAlgorithmType)Impl.CipherAlgorithm; }
+               public CipherAlgorithmType CipherAlgorithm {
+                       get { return Impl.CipherAlgorithm; }
                }
 
                public int CipherStrength {
                        get { return Impl.CipherStrength; }
                }
 
-               public XHashAlgorithmType HashAlgorithm {
-                       get { return (XHashAlgorithmType)Impl.HashAlgorithm; }
+               public HashAlgorithmType HashAlgorithm {
+                       get { return Impl.HashAlgorithm; }
                }
 
                public int HashStrength {
                        get { return Impl.HashStrength; }
                }
 
-               public XExchangeAlgorithmType KeyExchangeAlgorithm {
-                       get { return (XExchangeAlgorithmType)Impl.KeyExchangeAlgorithm; }
+               public ExchangeAlgorithmType KeyExchangeAlgorithm {
+                       get { return Impl.KeyExchangeAlgorithm; }
                }
 
                public int KeyExchangeStrength {
@@ -274,8 +250,8 @@ namespace Mono.Net.Security.Private
                        Impl.SetLength (value);
                }
 
-               public XAuthenticatedStream AuthenticatedStream {
-                       get { return (XAuthenticatedStream)(Stream)Impl.AuthenticatedStream; }
+               public AuthenticatedStream AuthenticatedStream {
+                       get { return Impl.AuthenticatedStream; }
                }
 
                public int ReadTimeout {
@@ -304,8 +280,8 @@ namespace Mono.Net.Security.Private
                        get { return Impl.RemoteCertificate; }
                }
 
-               public XSslProtocols SslProtocol {
-                       get { return (XSslProtocols)Impl.SslProtocol; }
+               public SslProtocols SslProtocol {
+                       get { return Impl.SslProtocol; }
                }
 
                public MSI.MonoTlsProvider Provider {
index 92f88fe1e0559344bd8ad7bfa0c5d4ebb28c87af..0cf6d394bb7da92c8b500c4c13e2a17db3511f09 100644 (file)
@@ -26,9 +26,6 @@
 
 #if SECURITY_DEP
 
-#if MONO_X509_ALIAS
-extern alias PrebuiltSystem;
-#endif
 #if MONO_SECURITY_ALIAS
 extern alias MonoSecurity;
 #endif
@@ -38,17 +35,6 @@ using MSI = MonoSecurity::Mono.Security.Interface;
 #else
 using MSI = Mono.Security.Interface;
 #endif
-#if MONO_X509_ALIAS
-using XSslProtocols = PrebuiltSystem::System.Security.Authentication.SslProtocols;
-using XX509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-#else
-using XSslProtocols = System.Security.Authentication.SslProtocols;
-using XX509CertificateCollection = System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-#endif
-
-using CipherAlgorithmType = System.Security.Authentication.CipherAlgorithmType;
-using HashAlgorithmType = System.Security.Authentication.HashAlgorithmType;
-using ExchangeAlgorithmType = System.Security.Authentication.ExchangeAlgorithmType;
 
 using System;
 using System.IO;
@@ -84,9 +70,9 @@ namespace Mono.Net.Security.Private
                        Impl.AuthenticateAsClient (targetHost);
                }
 
-               public void AuthenticateAsClient (string targetHost, XX509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
+               public void AuthenticateAsClient (string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
                {
-                       Impl.AuthenticateAsClient (targetHost, (XX509CertificateCollection)(object)clientCertificates, (XSslProtocols)enabledSslProtocols, checkCertificateRevocation);
+                       Impl.AuthenticateAsClient (targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation);
                }
 
                public IAsyncResult BeginAuthenticateAsClient (string targetHost, AsyncCallback asyncCallback, object asyncState)
@@ -94,9 +80,9 @@ namespace Mono.Net.Security.Private
                        return Impl.BeginAuthenticateAsClient (targetHost, asyncCallback, asyncState);
                }
 
-               public IAsyncResult BeginAuthenticateAsClient (string targetHost, XX509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
+               public IAsyncResult BeginAuthenticateAsClient (string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
                {
-                       return Impl.BeginAuthenticateAsClient (targetHost, (XX509CertificateCollection)(object)clientCertificates, (XSslProtocols)enabledSslProtocols, checkCertificateRevocation, asyncCallback, asyncState);
+                       return Impl.BeginAuthenticateAsClient (targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation, asyncCallback, asyncState);
                }
 
                public void EndAuthenticateAsClient (IAsyncResult asyncResult)
@@ -111,7 +97,7 @@ namespace Mono.Net.Security.Private
 
                public void AuthenticateAsServer (X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
                {
-                       Impl.AuthenticateAsServer (serverCertificate, clientCertificateRequired, (XSslProtocols)enabledSslProtocols, checkCertificateRevocation);
+                       Impl.AuthenticateAsServer (serverCertificate, clientCertificateRequired, enabledSslProtocols, checkCertificateRevocation);
                }
 
                public IAsyncResult BeginAuthenticateAsServer (X509Certificate serverCertificate, AsyncCallback asyncCallback, object asyncState)
@@ -121,7 +107,7 @@ namespace Mono.Net.Security.Private
 
                public IAsyncResult BeginAuthenticateAsServer (X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
                {
-                       return Impl.BeginAuthenticateAsServer (serverCertificate, clientCertificateRequired, (XSslProtocols)enabledSslProtocols, checkCertificateRevocation, asyncCallback, asyncState);
+                       return Impl.BeginAuthenticateAsServer (serverCertificate, clientCertificateRequired, enabledSslProtocols, checkCertificateRevocation, asyncCallback, asyncState);
                }
 
                public void EndAuthenticateAsServer (IAsyncResult asyncResult)
@@ -134,9 +120,9 @@ namespace Mono.Net.Security.Private
                        return Impl.AuthenticateAsClientAsync (targetHost);
                }
 
-               public Task AuthenticateAsClientAsync (string targetHost, XX509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
+               public Task AuthenticateAsClientAsync (string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
                {
-                       return Impl.AuthenticateAsClientAsync (targetHost, clientCertificates, (XSslProtocols)enabledSslProtocols, checkCertificateRevocation);
+                       return Impl.AuthenticateAsClientAsync (targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation);
                }
 
                public Task AuthenticateAsServerAsync (X509Certificate serverCertificate)
@@ -146,7 +132,7 @@ namespace Mono.Net.Security.Private
 
                public Task AuthenticateAsServerAsync (X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
                {
-                       return Impl.AuthenticateAsServerAsync (serverCertificate, clientCertificateRequired, (XSslProtocols)enabledSslProtocols, checkCertificateRevocation);
+                       return Impl.AuthenticateAsServerAsync (serverCertificate, clientCertificateRequired, enabledSslProtocols, checkCertificateRevocation);
                }
 
                public void Flush ()
@@ -190,7 +176,7 @@ namespace Mono.Net.Security.Private
                }
 
                public TransportContext TransportContext {
-                       get { return (TransportContext)(object)Impl.TransportContext; }
+                       get { return Impl.TransportContext; }
                }
 
                public bool IsAuthenticated {
@@ -263,7 +249,7 @@ namespace Mono.Net.Security.Private
                }
 
                public AuthenticatedStream AuthenticatedStream {
-                       get { return (AuthenticatedStream)(object)Impl.AuthenticatedStream; }
+                       get { return Impl.AuthenticatedStream; }
                }
 
                public int ReadTimeout {
index b0ae5d82c724627ca2360a856b159af606f23104..94f86ca7e747ce244abda4cc8846ce821256270b 100644 (file)
@@ -26,9 +26,6 @@
 
 #if SECURITY_DEP
 
-#if MONO_X509_ALIAS
-extern alias PrebuiltSystem;
-#endif
 #if MONO_SECURITY_ALIAS
 extern alias MonoSecurity;
 #endif
@@ -38,13 +35,6 @@ using MSI = MonoSecurity::Mono.Security.Interface;
 #else
 using MSI = Mono.Security.Interface;
 #endif
-#if MONO_X509_ALIAS
-using XHttpWebRequest = PrebuiltSystem::System.Net.HttpWebRequest;
-using XX509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-#else
-using XHttpWebRequest = System.Net.HttpWebRequest;
-using XX509CertificateCollection = System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-#endif
 
 using System;
 using System.IO;
@@ -84,13 +74,13 @@ namespace Mono.Net.Security.Private
 
                MSI.IMonoTlsContext IMonoTlsProvider.CreateTlsContext (
                        string hostname, bool serverMode, MSI.TlsProtocols protocolFlags,
-                       X509Certificate serverCertificate, XX509CertificateCollection clientCertificates,
+                       X509Certificate serverCertificate, X509CertificateCollection clientCertificates,
                        bool remoteCertRequired, bool checkCertName, bool checkCertRevocationStatus,
                        MSI.MonoEncryptionPolicy encryptionPolicy, MSI.MonoTlsSettings settings)
                {
                        return CreateTlsContextImpl (
                                hostname, serverMode, protocolFlags,
-                               serverCertificate, (X509CertificateCollection)(object)clientCertificates,
+                               serverCertificate, clientCertificates,
                                remoteCertRequired, encryptionPolicy, settings);
                }
 
@@ -102,13 +92,13 @@ namespace Mono.Net.Security.Private
 
                internal override MSI.IMonoTlsContext CreateTlsContext (
                        string hostname, bool serverMode, MSI.TlsProtocols protocolFlags,
-                       X509Certificate serverCertificate, XX509CertificateCollection clientCertificates,
+                       X509Certificate serverCertificate, X509CertificateCollection clientCertificates,
                        bool remoteCertRequired, MSI.MonoEncryptionPolicy encryptionPolicy,
                        MSI.MonoTlsSettings settings)
                {
                        return CreateTlsContextImpl (
                                hostname, serverMode, (MSI.TlsProtocols)protocolFlags,
-                               serverCertificate, (X509CertificateCollection)(object)clientCertificates,
+                               serverCertificate, clientCertificates,
                                remoteCertRequired, (MSI.MonoEncryptionPolicy)encryptionPolicy,
                                settings);
                }
index e2ec0f5a01318b9fefbdfafab0df60f45450c8a3..15283200590899b85f606eb3a2acfc9a08c6a9bb 100644 (file)
@@ -26,9 +26,6 @@
 
 #if SECURITY_DEP
 
-#if MONO_X509_ALIAS
-extern alias PrebuiltSystem;
-#endif
 #if MONO_SECURITY_ALIAS
 extern alias MonoSecurity;
 #endif
@@ -38,13 +35,6 @@ using MSI = MonoSecurity::Mono.Security.Interface;
 #else
 using MSI = Mono.Security.Interface;
 #endif
-#if MONO_X509_ALIAS
-using XHttpWebRequest = PrebuiltSystem::System.Net.HttpWebRequest;
-using XX509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-#else
-using XHttpWebRequest = System.Net.HttpWebRequest;
-using XX509CertificateCollection = System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-#endif
 
 using System;
 using System.IO;
@@ -86,13 +76,13 @@ namespace Mono.Net.Security.Private
 
                public MSI.IMonoTlsContext CreateTlsContext (
                        string hostname, bool serverMode, MSI.TlsProtocols protocolFlags,
-                       X509Certificate serverCertificate, XX509CertificateCollection clientCertificates,
+                       X509Certificate serverCertificate, X509CertificateCollection clientCertificates,
                        bool remoteCertRequired, bool checkCertName, bool checkCertRevocationStatus,
                        MSI.MonoEncryptionPolicy encryptionPolicy, MSI.MonoTlsSettings settings)
                {
                        return provider.CreateTlsContext (
                                hostname, serverMode, protocolFlags,
-                               serverCertificate, (XX509CertificateCollection)(object)clientCertificates,
+                               serverCertificate, clientCertificates,
                                remoteCertRequired, (MSI.MonoEncryptionPolicy)encryptionPolicy,
                                settings);
                }
index 96f5933dfb7ba0608ad4f5827671eb23bb390d37..58479df9fba6942c75eff0c548ec913f95f84cc0 100644 (file)
 #if MONO_SECURITY_ALIAS
 extern alias MonoSecurity;
 #endif
-#if MONO_X509_ALIAS
-extern alias PrebuiltSystem;
-#endif
 
 #if MONO_SECURITY_ALIAS
 using MonoSecurity::Mono.Security.Interface;
 #else
 using Mono.Security.Interface;
 #endif
-#if MONO_X509_ALIAS
-using XX509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-#else
 using XX509CertificateCollection = System.Security.Cryptography.X509Certificates.X509CertificateCollection;
 #endif
-#endif
 
 using System;
 using System.IO;
@@ -104,7 +97,7 @@ namespace Mono.Net.Security
 
                        try {
                                sslStream.AuthenticateAsClient (
-                                       request.Address.Host, (XX509CertificateCollection)(object)request.ClientCertificates,
+                                       request.Address.Host, request.ClientCertificates,
                                        (SslProtocols)ServicePointManager.SecurityProtocol,
                                        ServicePointManager.CheckCertificateRevocationList);
 
index 8cd1ca0b6fac8de068150a1b0e18f3342ce8a7c0..55969818a8b5d4299725c0e5f81129020d1f9366 100644 (file)
@@ -3,9 +3,6 @@
 #if MONO_SECURITY_ALIAS
 extern alias MonoSecurity;
 #endif
-#if MONO_X509_ALIAS
-extern alias PrebuiltSystem;
-#endif
 
 #if MONO_SECURITY_ALIAS
 using MonoSecurity::Mono.Security.Interface;
@@ -16,13 +13,8 @@ using Mono.Security.Interface;
 using MSX = Mono.Security.X509;
 using Mono.Security.X509.Extensions;
 #endif
-#if MONO_X509_ALIAS
-using XX509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-using XX509Chain = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509Chain;
-#else
 using XX509CertificateCollection = System.Security.Cryptography.X509Certificates.X509CertificateCollection;
 using XX509Chain = System.Security.Cryptography.X509Certificates.X509Chain;
-#endif
 
 using System;
 using System.Net;
index 629617f60312967c794b5f3a526de8eed72ed531..a0cb8d5019380a67cb9c638fcb083bcdf085cf87 100644 (file)
@@ -28,9 +28,6 @@
 #if MONO_SECURITY_ALIAS
 extern alias MonoSecurity;
 #endif
-#if MONO_X509_ALIAS
-extern alias PrebuiltSystem;
-#endif
 
 #if MONO_SECURITY_ALIAS
 using MX = MonoSecurity::Mono.Security.X509;
@@ -39,11 +36,6 @@ using MonoSecurity::Mono.Security.Interface;
 using MX = Mono.Security.X509;
 using Mono.Security.Interface;
 #endif
-#if MONO_X509_ALIAS
-using XX509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-#else
-using XX509CertificateCollection = System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-#endif
 
 using System.Runtime.InteropServices;
 using System.Security.Authentication.ExtendedProtection;
@@ -73,7 +65,7 @@ namespace System.Net.Security
 
        internal static class GlobalSSPI
        {
-               internal static SSPIInterface Create (string hostname, bool serverMode, SchProtocols protocolFlags, X509Certificate serverCertificate, XX509CertificateCollection clientCertificates,
+               internal static SSPIInterface Create (string hostname, bool serverMode, SchProtocols protocolFlags, X509Certificate serverCertificate, X509CertificateCollection clientCertificates,
                                                           bool remoteCertRequired, bool checkCertName, bool checkCertRevocationStatus, EncryptionPolicy encryptionPolicy,
                                                           LocalCertSelectionCallback certSelectionDelegate, RemoteCertValidationCallback remoteValidationCallback, SSPIConfiguration userConfig)
                {
@@ -226,7 +218,7 @@ namespace System.Net.Security
 
                internal static X509Certificate2 GetRemoteCertificate (SafeDeleteContext safeContext, out X509Certificate2Collection remoteCertificateStore)
                {
-                       XX509CertificateCollection monoCollection;
+                       X509CertificateCollection monoCollection;
                        if (safeContext == null || safeContext.IsInvalid) {
                                remoteCertificateStore = null;
                                return null;
index 2e739291d3412dce486ffaa9063cfa6711afdfd4..2abea7293f9ecff95358518babcdca29382258f9 100644 (file)
@@ -29,9 +29,6 @@
 //
 
 #if CONFIGURATION_DEP
-extern alias PrebuiltSystem;
-using TypeDescriptor = PrebuiltSystem.System.ComponentModel.TypeDescriptor;
-
 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
index 57aa6b19880683f76b923e984e4d92e4fc3d81eb..7a0bd6ef5dff7a556ba5159e668a4887b9b1acb6 100644 (file)
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if CONFIGURATION_DEP
-extern alias PrebuiltSystem;
-using NameValueCollection = PrebuiltSystem.System.Collections.Specialized.NameValueCollection;
-#endif
-
 using System.Reflection;
 using System.Collections.Specialized;
 
index 58ebcd7a5f73ee56af0dc156aee11fcd6c1df9f1..6b12f95425b8433a45d4def40764bc34067ccb2d 100644 (file)
 // Copyright (C) 2005, 2006 Novell, Inc (http://www.novell.com)
 //
 
-#if CONFIGURATION_DEP
-extern alias PrebuiltSystem;
-using NameValueCollection = PrebuiltSystem.System.Collections.Specialized.NameValueCollection;
-#endif
 #if CONFIGURATION_DEP
 using System.IO;
 using System.Xml.Serialization;
index 968532966e3d13de35882a06802f6fbbe507413c..9b2f8e9986b8768ff7ae95a95620bbb19cb9d7a1 100644 (file)
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if CONFIGURATION_DEP
-extern alias PrebuiltSystem;
-using NameValueCollection = PrebuiltSystem.System.Collections.Specialized.NameValueCollection;
-#endif
-
 using System;
 using System.Collections;
 using System.Collections.Specialized;
index 31d56ce09eb38acf77a1e3a2a9ab1466b66b1266..d74a226f1e77042ed2668b56212b96a03e6a22b8 100644 (file)
 
 #if CONFIGURATION_DEP
 
-extern alias PrebuiltSystem;
-
 using System;
 using System.Collections;
 using System.Collections.Generic;
+using System.Collections.Specialized;
 using System.Configuration;
 using System.Globalization;
 using System.IO;
@@ -42,8 +41,6 @@ using System.Security.Cryptography;
 using System.Text;
 using System.Xml;
 
-using NameValueCollection = PrebuiltSystem.System.Collections.Specialized.NameValueCollection;
-
 namespace System.Configuration
 {
        // location to store user configuration settings.
index d0ca5ab0a48b838a95eb18378f4e3209b4f89859..10664ca266bc2aef89b312b67d4e00fb82edb00e 100644 (file)
 //
 
 #if CONFIGURATION_DEP
-#if CONFIGURATION_DEP
-extern alias PrebuiltSystem;
-using NameValueCollection = PrebuiltSystem.System.Collections.Specialized.NameValueCollection;
-#endif
 
 using System;
 using System.Collections.Specialized;
index 41cf0d8c8c455930dfc4e5c8bbd84c9fa5308d74..6e929543aed5fec2f03a7c7dde270c307a54b91d 100644 (file)
@@ -74,7 +74,7 @@ namespace System.Diagnostics
 
                /* Private constructor called from other methods */
                private Process (SafeProcessHandle handle, int id) {
-                       m_processHandle = handle;
+                       SetProcessHandle (handle);
                        SetProcessId (id);
                }
 
@@ -606,13 +606,9 @@ namespace System.Diagnostics
                                throw new Win32Exception (-proc_info.pid);
                        }
 
-                       m_processHandle = new SafeProcessHandle (proc_info.process_handle, true);
-                       haveProcessHandle = true;
+                       SetProcessHandle (new SafeProcessHandle (proc_info.process_handle, true));
                        SetProcessId (proc_info.pid);
 
-                       if (watchForExit)
-                               EnsureWatchingForExit ();
-
                        return ret;
                }
 
@@ -771,8 +767,7 @@ namespace System.Diagnostics
                                }
                        }
 
-                       m_processHandle = new SafeProcessHandle (proc_info.process_handle, true);
-                       haveProcessHandle = true;
+                       SetProcessHandle (new SafeProcessHandle (proc_info.process_handle, true));
                        SetProcessId (proc_info.pid);
                        
                        if (startInfo.RedirectStandardInput) {
@@ -808,9 +803,6 @@ namespace System.Diagnostics
                                standardError = new StreamReader (new FileStream (stderr_read, FileAccess.Read, true, 8192), stderrEncoding, true);
                        }
 
-                       if (watchForExit)
-                               EnsureWatchingForExit ();
-
                        return true;
                }
 
index f17eb58d28dca262aeb2205bcaa41468a5183292..778671764ea91a8f8b9bcc563e60b0b68d9d0fdd 100644 (file)
@@ -300,11 +300,14 @@ namespace System.IO {
                        else
                                fullPathNoLastSlash = fsw.FullPath;
                                
-                       // GetFilenameFromFd() returns the *realpath* which can be different than fsw.FullPath because symlinks.
+                       // realpath() returns the *realpath* which can be different than fsw.FullPath because symlinks.
                        // If so, introduce a fixup step.
-                       int fd = open (fullPathNoLastSlash, O_EVTONLY, 0);
-                       var resolvedFullPath = GetFilenameFromFd (fd);
-                       close (fd);
+                       var sb = new StringBuilder (__DARWIN_MAXPATHLEN);
+                       if (realpath(fsw.FullPath, sb) == IntPtr.Zero) {
+                               var errMsg = String.Format ("realpath({0}) failed, error code = '{1}'", fsw.FullPath, Marshal.GetLastWin32Error ());
+                               throw new IOException (errMsg);
+                       }
+                       var resolvedFullPath = sb.ToString();
 
                        if (resolvedFullPath != fullPathNoLastSlash)
                                fixupPath = resolvedFullPath;
@@ -614,14 +617,14 @@ namespace System.IO {
                                return;
 
                        // e.Name
-                       string name = path.Substring (fullPathNoLastSlash.Length + 1); 
+                       string name = (path.Length > fullPathNoLastSlash.Length) ? path.Substring (fullPathNoLastSlash.Length + 1) : String.Empty;
 
                        // only post events that match filter pattern. check both old and new paths for renames
                        if (!fsw.Pattern.IsMatch (path) && (newPath == null || !fsw.Pattern.IsMatch (newPath)))
                                return;
                                
                        if (action == FileAction.RenamedNewName) {
-                               string newName = newPath.Substring (fullPathNoLastSlash.Length + 1);
+                               string newName = (newPath.Length > fullPathNoLastSlash.Length) ? newPath.Substring (fullPathNoLastSlash.Length + 1) : String.Empty;
                                renamed = new RenamedEventArgs (WatcherChangeTypes.Renamed, fsw.Path, newName, name);
                        }
                                
@@ -677,6 +680,9 @@ namespace System.IO {
                [DllImport ("libc", CharSet=CharSet.Auto, SetLastError=true)]
                static extern int fcntl (int file_names_by_descriptor, int cmd, StringBuilder sb);
 
+               [DllImport ("libc", CharSet=CharSet.Auto, SetLastError=true)]
+               static extern IntPtr realpath (string pathname, StringBuilder sb);
+
                [DllImport ("libc", SetLastError=true)]
                extern static int open (string path, int flags, int mode_t);
 
index 0e89b187d1a97a216d0677c1cfb612e88cfb97eb..ff881b00bcc9a6df8a457c16e23d134a2ebcef16 100644 (file)
 #if MONO_SECURITY_ALIAS
 extern alias MonoSecurity;
 #endif
-#if MONO_X509_ALIAS
-extern alias PrebuiltSystem;
-#endif
 
 #if MONO_SECURITY_ALIAS
 using MSI = MonoSecurity::Mono.Security.Interface;
 #else
 using MSI = Mono.Security.Interface;
 #endif
-#if MONO_X509_ALIAS
-using X509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-#else
-using X509CertificateCollection = System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-#endif
 using System.Security.Cryptography.X509Certificates;
 #endif
 
index 5d0d9b75471a55d28cf32dbf9157559087bae2c9..9b77646d7b1502b669d501fcd04bd3e9197c687c 100644 (file)
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 #if SECURITY_DEP && !MONO_FEATURE_NEW_TLS
-#if MONO_X509_ALIAS
-extern alias PrebuiltSystem;
-using X509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-#endif
 
 using System.Security.Cryptography.X509Certificates;
 
index 652c91e143fc6d4e18463b192fcfae99c4f9d07b..9238428b1f3841de180dc5f09f3944336a9d82d1 100644 (file)
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 #if !MONO_FEATURE_NEW_TLS
-#if MONO_X509_ALIAS
-extern alias PrebuiltSystem;
-using X509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-#endif
 
 using System.Security.Cryptography.X509Certificates;
 
index 53e6d2918577369637da3f522ced844a316bb82a..59e741722b67b820861fb63af0005b004087397c 100644 (file)
@@ -27,9 +27,6 @@
 #if !MONO_FEATURE_NEW_TLS
 #if SECURITY_DEP
 
-#if MONO_X509_ALIAS
-extern alias PrebuiltSystem;
-#endif
 #if MONO_SECURITY_ALIAS
 extern alias MonoSecurity;
 #endif
@@ -39,13 +36,6 @@ using MonoSecurity::Mono.Security.Interface;
 #else
 using Mono.Security.Interface;
 #endif
-#if MONO_X509_ALIAS
-using XSslProtocols = PrebuiltSystem::System.Security.Authentication.SslProtocols;
-using XX509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-#else
-using XSslProtocols = System.Security.Authentication.SslProtocols;
-using XX509CertificateCollection = System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-#endif
 
 using CipherAlgorithmType = System.Security.Authentication.CipherAlgorithmType;
 using HashAlgorithmType = System.Security.Authentication.HashAlgorithmType;
@@ -80,7 +70,7 @@ namespace System.Net.Security
 
        internal delegate X509Certificate LocalCertSelectionCallback (
                string targetHost,
-               XX509CertificateCollection localCertificates,
+               X509CertificateCollection localCertificates,
                X509Certificate remoteCertificate,
                string[] acceptableIssuers);
 
@@ -146,9 +136,9 @@ namespace System.Net.Security
                        Impl.AuthenticateAsClient (targetHost);
                }
 
-               public virtual void AuthenticateAsClient (string targetHost, XX509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
+               public virtual void AuthenticateAsClient (string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
                {
-                       Impl.AuthenticateAsClient (targetHost, (XX509CertificateCollection)(object)clientCertificates, (XSslProtocols)enabledSslProtocols, checkCertificateRevocation);
+                       Impl.AuthenticateAsClient (targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation);
                }
 
                // [HostProtection (ExternalThreading=true)]
@@ -158,9 +148,9 @@ namespace System.Net.Security
                }
 
                // [HostProtection (ExternalThreading=true)]
-               public virtual IAsyncResult BeginAuthenticateAsClient (string targetHost, XX509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
+               public virtual IAsyncResult BeginAuthenticateAsClient (string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
                {
-                       return Impl.BeginAuthenticateAsClient (targetHost, (XX509CertificateCollection)(object)clientCertificates, (XSslProtocols)enabledSslProtocols, checkCertificateRevocation, asyncCallback, asyncState);
+                       return Impl.BeginAuthenticateAsClient (targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation, asyncCallback, asyncState);
                }
 
                public virtual void EndAuthenticateAsClient (IAsyncResult asyncResult)
@@ -175,7 +165,7 @@ namespace System.Net.Security
 
                public virtual void AuthenticateAsServer (X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
                {
-                       Impl.AuthenticateAsServer (serverCertificate, clientCertificateRequired, (XSslProtocols)enabledSslProtocols, checkCertificateRevocation);
+                       Impl.AuthenticateAsServer (serverCertificate, clientCertificateRequired, enabledSslProtocols, checkCertificateRevocation);
                }
 
                // [HostProtection (ExternalThreading=true)]
@@ -186,7 +176,7 @@ namespace System.Net.Security
 
                public virtual IAsyncResult BeginAuthenticateAsServer (X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
                {
-                       return Impl.BeginAuthenticateAsServer (serverCertificate, clientCertificateRequired, (XSslProtocols)enabledSslProtocols, checkCertificateRevocation, asyncCallback, asyncState);
+                       return Impl.BeginAuthenticateAsServer (serverCertificate, clientCertificateRequired, enabledSslProtocols, checkCertificateRevocation, asyncCallback, asyncState);
                }
 
                public virtual void EndAuthenticateAsServer (IAsyncResult asyncResult)
@@ -206,9 +196,9 @@ namespace System.Net.Security
                        return Impl.AuthenticateAsClientAsync (targetHost);
                }
 
-               public virtual Task AuthenticateAsClientAsync (string targetHost, XX509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
+               public virtual Task AuthenticateAsClientAsync (string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
                {
-                       return Impl.AuthenticateAsClientAsync (targetHost, clientCertificates, (XSslProtocols)enabledSslProtocols, checkCertificateRevocation);
+                       return Impl.AuthenticateAsClientAsync (targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation);
                }
 
                public virtual Task AuthenticateAsServerAsync (X509Certificate serverCertificate)
@@ -218,7 +208,7 @@ namespace System.Net.Security
 
                public virtual Task AuthenticateAsServerAsync (X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
                {
-                       return Impl.AuthenticateAsServerAsync (serverCertificate, clientCertificateRequired, (XSslProtocols)enabledSslProtocols, checkCertificateRevocation);
+                       return Impl.AuthenticateAsServerAsync (serverCertificate, clientCertificateRequired, enabledSslProtocols, checkCertificateRevocation);
                }
 
                public override bool IsAuthenticated {
index 885eaf3ea3df14566dcf0a32bf21e653d1314be9..b9940eb07d89585b683f2904aa1b0fb49aa84157 100644 (file)
 #if MONO_SECURITY_ALIAS
 extern alias MonoSecurity;
 #endif
-#if MONO_X509_ALIAS
-extern alias PrebuiltSystem;
-#endif
 
 #if MONO_SECURITY_ALIAS
 using MSI = MonoSecurity::Mono.Security.Interface;
 #else
 using MSI = Mono.Security.Interface;
 #endif
-#if MONO_X509_ALIAS
-using XX509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-#else
-using XX509CertificateCollection = System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-#endif
 
 using System.IO;
 using System.Net.Sockets;
index 71eb71e31062c3b5704713a2573ef4caf2fda9c3..e0c3ed84318073bd271c8ffa07f2e9b7566554a9 100644 (file)
@@ -27,8 +27,6 @@
 //
 #if CONFIGURATION_DEP
 
-extern alias PrebuiltSystem;
-
 using System;
 using System.Collections;
 using System.Collections.Generic;
@@ -42,8 +40,6 @@ using System.Runtime.Serialization;
 using System.Text;
 using System.Xml;
 
-using TypeConverter = PrebuiltSystem::System.ComponentModel.TypeConverter;
-
 namespace System.Security.Authentication.ExtendedProtection.Configuration
 {
        internal static class ConfigUtil
index 184e586471dd30c167be16eca420d930c5c12bfb..695f5e822209a0964b0c604cdca50c421e48c52c 100644 (file)
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 #if SECURITY_DEP
-#if MONO_X509_ALIAS
-extern alias PrebuiltSystem;
-#endif
 
-#if MONO_X509_ALIAS
-using XX509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-#else
 using XX509CertificateCollection = System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-#endif
 
 using System;
 using System.Runtime.InteropServices;
@@ -101,16 +94,17 @@ namespace System.Security.Cryptography.X509Certificates {
                        }
                }
 
-               static IntPtr GetCertificate (X509Certificate certificate, out IntPtr dataPtr)
+               static IntPtr GetCertificate (X509Certificate certificate)
                {
-                       var handle = certificate.Handle;
+                       var handle = certificate.Impl.GetNativeAppleCertificate ();
                        if (handle != IntPtr.Zero) {
-                               dataPtr = IntPtr.Zero;
                                CFRetain (handle);
                                return handle;
                        }
-                       dataPtr = MakeCFData (certificate.GetRawCertData ());
-                       return SecCertificateCreateWithData (IntPtr.Zero, dataPtr);
+                       var dataPtr = MakeCFData (certificate.GetRawCertData ());
+                       handle = SecCertificateCreateWithData (IntPtr.Zero, dataPtr);
+                       CFRelease (dataPtr);
+                       return handle;
                }
                
                public static SecTrustResult TrustEvaluateSsl (XX509CertificateCollection certificates, XX509CertificateCollection anchors, string host)
@@ -129,9 +123,7 @@ namespace System.Security.Cryptography.X509Certificates {
                {
                        int certCount = certificates.Count;
                        int anchorCount = anchors != null ? anchors.Count : 0;
-                       IntPtr [] cfDataPtrs = new IntPtr [certCount];
                        IntPtr [] secCerts = new IntPtr [certCount];
-                       IntPtr [] cfDataAnchorPtrs = new IntPtr [anchorCount];
                        IntPtr [] secCertAnchors = new IntPtr [anchorCount];
                        IntPtr certArray = IntPtr.Zero;
                        IntPtr anchorArray = IntPtr.Zero;
@@ -142,13 +134,13 @@ namespace System.Security.Cryptography.X509Certificates {
 
                        try {
                                for (int i = 0; i < certCount; i++) {
-                                       secCerts [i] = GetCertificate (certificates [i], out cfDataPtrs [i]);
+                                       secCerts [i] = GetCertificate (certificates [i]);
                                        if (secCerts [i] == IntPtr.Zero)
                                                return SecTrustResult.Deny;
                                }
 
                                for (int i = 0; i < anchorCount; i++) {
-                                       secCertAnchors [i] = GetCertificate (anchors [i], out cfDataAnchorPtrs [i]);
+                                       secCertAnchors [i] = GetCertificate (anchors [i]);
                                        if (secCertAnchors [i] == IntPtr.Zero)
                                                return SecTrustResult.Deny;
                                }
@@ -170,14 +162,6 @@ namespace System.Security.Cryptography.X509Certificates {
                                code = SecTrustEvaluate (sectrust, out result);
                                return result;
                        } finally {
-                               for (int i = 0; i < certCount; i++)
-                                       if (cfDataPtrs [i] != IntPtr.Zero)
-                                               CFRelease (cfDataPtrs [i]);
-
-                               for (int i = 0; i < anchorCount; i++)
-                                       if (cfDataAnchorPtrs [i] != IntPtr.Zero)
-                                               CFRelease (cfDataAnchorPtrs [i]);
-
                                if (certArray != IntPtr.Zero)
                                        CFRelease (certArray);
 
index 87fd8a16d225230326f98043ae7f4d1de702a58a..bfb2696f97c99d3098801cd260bf07a6603c721b 100644 (file)
@@ -72,6 +72,11 @@ namespace System.Security.Cryptography.X509Certificates
                        get { return IntPtr.Zero; }
                }
 
+               public override IntPtr GetNativeAppleCertificate ()
+               {
+                       return IntPtr.Zero;
+               }
+
                internal X509Certificate2ImplMono (MX.X509Certificate cert)
                {
                        this._cert = cert;
index ffd54a737b9a8e95eb15d6b52ee7fca891f5e2da..2a9163a346f89ae143e7477b9215c67659f5e875 100644 (file)
@@ -30,9 +30,6 @@
 #if MONO_SECURITY_ALIAS
 extern alias MonoSecurity;
 #endif
-#if MONO_X509_ALIAS
-extern alias PrebuiltSystem;
-#endif
 
 #if MONO_SECURITY_ALIAS
 using MonoSecurity::Mono.Security.Interface;
@@ -59,7 +56,7 @@ namespace System.Security.Cryptography.X509Certificates
                        var provider = MonoTlsProviderFactory.GetProvider ();
                        if (provider.HasNativeCertificates) {
                                var impl = provider.GetNativeCertificate (rawData, password, keyStorageFlags);
-                               return (X509Certificate2Impl)(object)impl;
+                               return impl;
                        } else {
                                var impl = new X509Certificate2ImplMono ();
                                impl.Import (rawData, password, keyStorageFlags);
@@ -72,7 +69,7 @@ namespace System.Security.Cryptography.X509Certificates
                        var provider = MonoTlsProviderFactory.GetProvider ();
                        if (provider.HasNativeCertificates) {
                                var impl = provider.GetNativeCertificate (cert);
-                               return (X509Certificate2Impl)(object)impl;
+                               return impl;
                        }
                        var impl2 = cert.Impl as X509Certificate2Impl;
                        if (impl2 != null)
index 715c748d1f5fe0cb703014e012db8fce842f0993..0638cb720b3a57d67b0879d93f72fce0a3bda685 100644 (file)
@@ -17,7 +17,7 @@ namespace MonoTests.System.Net.WebSockets
        [TestFixture]
        public class ClientWebSocketTest
        {
-               const string EchoServerUrl = "ws://echo.websocket.org";
+               const string EchoServerUrl = "ws://corefx-net.cloudapp.net/WebSocket/EchoWebSocket.ashx";
                int Port = NetworkHelpers.FindFreePort ();
                HttpListener listener;
                ClientWebSocket socket;
index 1252b936471eb76b900e31855df7d32f96ee64d2..bd99fb05241810f064a23fdfe7198f084576344d 100644 (file)
@@ -1,2 +1 @@
 *.g.cs
-generator.exe
diff --git a/mcs/class/corlib/CommonCrypto/CommonCryptorGenerator.cs b/mcs/class/corlib/CommonCrypto/CommonCryptorGenerator.cs
deleted file mode 100644 (file)
index f177c17..0000000
+++ /dev/null
@@ -1,104 +0,0 @@
-//
-// CommonCrypto code generator for symmetric block cipher algorithms
-//
-// Authors:
-//     Sebastien Pouliot  <sebastien@xamarin.com>
-//
-// Copyright 2012 Xamarin Inc.
-//
-
-using System;
-using System.IO;
-
-namespace Xamarin {
-
-       public static class CommonCryptor {
-               
-               static public void Generate (string namespaceName, string typeName, string baseTypeName, string ccAlgorithmName, string feedbackSize = "8", string ctorInitializers = null)
-               {
-                       string template = @"// Generated file to bind CommonCrypto cipher algorithms - DO NOT EDIT
-//
-// Authors:
-//     Sebastien Pouliot  <sebastien@xamarin.com>
-//
-// Copyright 2012-2014 Xamarin Inc.
-
-using System;
-using System.Security.Cryptography;
-
-using Mono.Security.Cryptography;
-using Crimson.CommonCrypto;
-
-namespace %NAMESPACE% {
-
-       public sealed partial class %TYPE% : %BASE% {
-               
-               public %TYPE% ()
-               {
-                       FeedbackSizeValue = %FEEDBACKSIZE%;
-                       %CTOR_INIT%
-               }
-               
-               public override void GenerateIV ()
-               {
-                       IVValue = KeyBuilder.IV (BlockSizeValue >> 3);
-               }
-               
-               public override void GenerateKey ()
-               {
-                       KeyValue = KeyBuilder.Key (KeySizeValue >> 3);
-               }
-               
-               public override ICryptoTransform CreateDecryptor (byte[] rgbKey, byte[] rgbIV) 
-               {
-                       IntPtr decryptor = IntPtr.Zero;
-                       switch (Mode) {
-                       case CipherMode.CBC:
-                               decryptor = Cryptor.Create (CCOperation.Decrypt, CCAlgorithm.%CCALGORITHM%, CCOptions.None, rgbKey, rgbIV);
-                               return new FastCryptorTransform (decryptor, this, false, rgbIV);
-                       case CipherMode.ECB:
-                               decryptor = Cryptor.Create (CCOperation.Decrypt, CCAlgorithm.%CCALGORITHM%, CCOptions.ECBMode, rgbKey, rgbIV);
-                               return new FastCryptorTransform (decryptor, this, false, rgbIV);
-                       case CipherMode.CFB:
-#if MONOTOUCH || XAMMAC
-                               IntPtr encryptor = Cryptor.Create (CCOperation.Encrypt, CCAlgorithm.%CCALGORITHM%, CCOptions.ECBMode, rgbKey, rgbIV);
-                               decryptor = Cryptor.Create (CCOperation.Decrypt, CCAlgorithm.%CCALGORITHM%, CCOptions.ECBMode, rgbKey, rgbIV);
-                               return new CryptorTransform (decryptor, encryptor, this, false, rgbIV);
-#else
-                               throw new CryptographicException (""CFB is not supported by Crimson.CommonCrypto"");
-#endif
-                       default:
-                               throw new CryptographicException (String.Format (""{0} is not supported by the .NET framework"", Mode));
-                       }
-               }
-               
-               public override ICryptoTransform CreateEncryptor (byte[] rgbKey, byte[] rgbIV) 
-               {
-                       IntPtr encryptor = IntPtr.Zero;
-                       switch (Mode) {
-                       case CipherMode.CBC:
-                               encryptor = Cryptor.Create (CCOperation.Encrypt, CCAlgorithm.%CCALGORITHM%, CCOptions.None, rgbKey, rgbIV);
-                               return new FastCryptorTransform (encryptor, this, true, rgbIV);
-                       case CipherMode.ECB:
-                               encryptor = Cryptor.Create (CCOperation.Encrypt, CCAlgorithm.%CCALGORITHM%, CCOptions.ECBMode, rgbKey, rgbIV);
-                               return new FastCryptorTransform (encryptor, this, true, rgbIV);
-                       case CipherMode.CFB:
-#if MONOTOUCH || XAMMAC
-                               encryptor = Cryptor.Create (CCOperation.Encrypt, CCAlgorithm.%CCALGORITHM%, CCOptions.ECBMode, rgbKey, rgbIV);
-                               return new CryptorTransform (encryptor, IntPtr.Zero, this, true, rgbIV);
-#else
-                               throw new CryptographicException (""CFB is not supported by Crimson.CommonCrypto"");
-#endif
-                       default:
-                               throw new CryptographicException (String.Format (""{0} is not supported by the .NET framework"", Mode));
-                       }
-               }
-       }
-}";
-                       
-                       File.WriteAllText (typeName + ".g.cs", template.Replace ("%NAMESPACE%", namespaceName).
-                               Replace ("%TYPE%", typeName).Replace ("%BASE%", baseTypeName).Replace("%FEEDBACKSIZE%", feedbackSize).Replace ("%CTOR_INIT%", ctorInitializers).
-                               Replace ("%CCALGORITHM%", ccAlgorithmName.ToString ()));
-               }
-       }
-}
diff --git a/mcs/class/corlib/CommonCrypto/CommonDigestGenerator.cs b/mcs/class/corlib/CommonCrypto/CommonDigestGenerator.cs
deleted file mode 100644 (file)
index 1b729e3..0000000
+++ /dev/null
@@ -1,167 +0,0 @@
-//
-// CommonCrypto code generator for digest algorithms
-//
-// Authors:
-//     Sebastien Pouliot  <sebastien@xamarin.com>
-//
-// Copyright 2012-2014 Xamarin Inc.
-//
-
-using System;
-using System.IO;
-
-namespace Xamarin {
-
-       public static class CommonDigest {
-               
-#if !MONOTOUCH && !XAMMAC
-               // we do not add anything in MonoTouch, just replacing, so this is not needed
-               // however we can avoid a dependency on Mono.Security for Crimson.CommonCrypto.dll by including the base classes
-               static public void GenerateBaseClass (string namespaceName, string typeName, string baseTypeName, int hashSize,
-                       string visibilityStart = "", string visibilityEnd = "")
-               {
-                       string template = @"// Generated file to bind CommonCrypto/CommonDigest - DO NOT EDIT
-//
-// Authors:
-//     Sebastien Pouliot  <sebastien@xamarin.com>
-//
-// Copyright 2012-2014 Xamarin Inc.
-
-using System;
-using System.Security.Cryptography;
-using System.Runtime.InteropServices;
-
-namespace %NAMESPACE% {
-
-%VISIBILITY_START%
-       public
-%VISIBILITY_END%
-       abstract class %BASE% : HashAlgorithm {
-
-               protected %BASE% () 
-               {
-                       HashSizeValue = %HASHSIZE%; 
-               }
-
-               public static new %BASE% Create ()
-               {
-                       return Create (""%BASE%"");
-               }
-
-               public static new %BASE% Create (string hashName)
-               {
-                       object o = CryptoConfig.CreateFromName (hashName);
-                       return (%BASE%) o ?? new %TYPE% ();
-               }
-       }
-}";
-                       
-                       File.WriteAllText (baseTypeName + ".g.cs", template.Replace ("%NAMESPACE%", namespaceName).
-                               Replace ("%TYPE%", typeName).Replace ("%BASE%", baseTypeName).
-                               Replace ("%VISIBILITY_START%", visibilityStart).Replace ("%VISIBILITY_END%", visibilityEnd).
-                               Replace ("%HASHSIZE%", hashSize.ToString ()));
-               }
-#endif
-               static public void Generate (string namespaceName, string typeName, string baseTypeName, int contextSize,
-                       string visibilityStart = "", string visibilityEnd = "")
-               {
-                       string template = @"// Generated file to bind CommonCrypto/CommonDigest - DO NOT EDIT
-//
-// Authors:
-//     Sebastien Pouliot  <sebastien@xamarin.com>
-//
-// Copyright 2011-2014 Xamarin Inc.
-
-using System;
-using System.Security.Cryptography;
-using System.Runtime.InteropServices;
-
-using Mono.Security.Cryptography;
-
-namespace %NAMESPACE% {
-
-%VISIBILITY_START%
-       public
-%VISIBILITY_END%
-       sealed class %TYPE% : %BASE% {
-
-               IntPtr ctx;
-
-               [DllImport (""/usr/lib/libSystem.dylib"", EntryPoint=""CC_%BASE%_Init"")]
-               static extern int Init (/* CC_%BASE%_CTX */ IntPtr c);
-
-               [DllImport (""/usr/lib/libSystem.dylib"", EntryPoint=""CC_%BASE%_Update"")]
-               static extern int Update (/* CC_%BASE%_CTX */ IntPtr c, /* const void * */ IntPtr data, /* uint32_t */ uint len);
-
-               [DllImport (""/usr/lib/libSystem.dylib"", EntryPoint=""CC_%BASE%_Final"")]
-               static extern int Final (/* unsigned char * */ byte [] md, /* CC_%BASE%_CTX */ IntPtr c);
-
-               public %TYPE% ()
-               {
-                       ctx = IntPtr.Zero;
-               }
-
-               ~%TYPE% ()
-               {
-                       Dispose (false);
-               }
-
-               protected override void Dispose (bool disposing)
-               {
-                       if (ctx != IntPtr.Zero) {
-                               Marshal.FreeHGlobal (ctx);
-                               ctx = IntPtr.Zero;
-                       }
-                       base.Dispose (disposing);
-                       GC.SuppressFinalize (this);
-               }
-
-               public override void Initialize ()
-               {
-                       if (ctx == IntPtr.Zero)
-                               ctx = Marshal.AllocHGlobal (%CTX_SIZE%);
-                       
-                       int hr = Init (ctx);
-                       if (hr != 1)
-                               throw new CryptographicException (hr);
-               }
-
-               protected override void HashCore (byte[] data, int start, int length) 
-               {
-                       if (ctx == IntPtr.Zero)
-                               Initialize ();
-
-                       if (data.Length == 0)
-                               return;
-
-                       unsafe {
-                               fixed (byte* p = &data [0]) {
-                                       int hr = Update (ctx, (IntPtr) (p + start), (uint) length);
-                                       if (hr != 1)
-                                               throw new CryptographicException (hr);
-                               }
-                       }
-               }
-
-               protected override byte[] HashFinal () 
-               {
-                       if (ctx == IntPtr.Zero)
-                               Initialize ();
-                       
-                       byte[] data = new byte [HashSize >> 3];
-                       int hr = Final (data, ctx);
-                       if (hr != 1)
-                               throw new CryptographicException (hr);
-
-                       return data;
-               }
-       }
-}";
-                       
-                       File.WriteAllText (typeName + ".g.cs", template.Replace ("%NAMESPACE%", namespaceName).
-                               Replace ("%TYPE%", typeName).Replace ("%BASE%", baseTypeName).
-                               Replace ("%VISIBILITY_START%", visibilityStart).Replace ("%VISIBILITY_END%", visibilityEnd).
-                               Replace ("%CTX_SIZE%", contextSize.ToString ()));
-               }
-       }
-}
diff --git a/mcs/class/corlib/CommonCrypto/Makefile b/mcs/class/corlib/CommonCrypto/Makefile
new file mode 100644 (file)
index 0000000..36ea8d3
--- /dev/null
@@ -0,0 +1,8 @@
+thisdir = class/corlib/CommonCrypto
+SUBDIRS =
+include ../../../build/rules.make
+
+.NOTPARALLEL:
+all:
+       MONO_PATH="$(topdir)/class/lib/$(BUILD_TOOLS_PROFILE)$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" $(RUNTIME) $(RUNTIME_FLAGS) $(topdir)/class/lib/$(BUILD_TOOLS_PROFILE)/commoncryptogenerator.exe
+
diff --git a/mcs/class/corlib/CommonCrypto/Makefile.include b/mcs/class/corlib/CommonCrypto/Makefile.include
deleted file mode 100644 (file)
index 25e1379..0000000
+++ /dev/null
@@ -1,5 +0,0 @@
-CommonCrypto/%.g.cs: CommonCrypto/generator.exe
-       cd CommonCrypto && mono --debug generator.exe
-
-CommonCrypto/generator.exe: CommonCrypto/generator.cs CommonCrypto/CommonDigestGenerator.cs CommonCrypto/CommonCryptorGenerator.cs
-       mcs CommonCrypto/generator.cs CommonCrypto/CommonDigestGenerator.cs CommonCrypto/CommonCryptorGenerator.cs -o $@
diff --git a/mcs/class/corlib/CommonCrypto/generator.cs b/mcs/class/corlib/CommonCrypto/generator.cs
deleted file mode 100644 (file)
index a7d13c8..0000000
+++ /dev/null
@@ -1,57 +0,0 @@
-//
-// CommonCrypto Code Generator
-//
-// Authors:
-//     Sebastien Pouliot  <sebastien@xamarin.com>
-//
-// Copyright 2012 Xamarin Inc.
-//
-
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Text;
-
-namespace Xamarin {
-       
-       class Program {
-               static void Main (string [] args)
-               {
-                       // mscorlib replacements
-                       CommonDigest.Generate ("System.Security.Cryptography", "MD5CryptoServiceProvider", "MD5", 1000);
-                       CommonDigest.Generate ("System.Security.Cryptography", "SHA1CryptoServiceProvider", "SHA1", 1000);
-                       CommonDigest.Generate ("System.Security.Cryptography", "SHA1Managed", "SHA1", 1000);
-                       CommonDigest.Generate ("System.Security.Cryptography", "SHA256Managed", "SHA256", 1000);
-                       CommonDigest.Generate ("System.Security.Cryptography", "SHA384Managed", "SHA384", 1000);
-                       CommonDigest.Generate ("System.Security.Cryptography", "SHA512Managed", "SHA512", 1000);
-                       
-                       // System.Core replacements - not yet in MT profile (4.0 - functional dupes anyway)
-                       //CommonDigest.Generate ("System.Security.Cryptography", "MD5Cng", "MD5", 1000);
-                       //CommonDigest.Generate ("System.Security.Cryptography", "SHA256Cng", "SHA256", 1000);
-                       //CommonDigest.Generate ("System.Security.Cryptography", "SHA384Cng", "SHA384", 1000);
-                       //CommonDigest.Generate ("System.Security.Cryptography", "SHA512Cng", "SHA512", 1000);
-                       //CommonDigest.Generate ("System.Security.Cryptography", "SHA256CryptoServiceProvider", "SHA256", 1000);
-                       //CommonDigest.Generate ("System.Security.Cryptography", "SHA384CryptoServiceProvider", "SHA384", 1000);
-                       //CommonDigest.Generate ("System.Security.Cryptography", "SHA512CryptoServiceProvider", "SHA512", 1000);
-                       
-                       // Mono.Security replacements
-                       CommonDigest.Generate ("Mono.Security.Cryptography", "MD2Managed", "MD2", 1000, "#if !INSIDE_CORLIB", "#endif");
-                       CommonDigest.Generate ("Mono.Security.Cryptography", "MD4Managed", "MD4", 1000, "#if !INSIDE_CORLIB", "#endif");
-                       CommonDigest.Generate ("Mono.Security.Cryptography", "SHA224Managed", "SHA224", 1000);
-
-                       // mscorlib replacements
-                       CommonCryptor.Generate ("System.Security.Cryptography", "DESCryptoServiceProvider", "DES", "DES");
-                       CommonCryptor.Generate ("System.Security.Cryptography", "TripleDESCryptoServiceProvider", "TripleDES", "TripleDES");
-                       CommonCryptor.Generate ("System.Security.Cryptography", "RC2CryptoServiceProvider", "RC2", "RC2", ctorInitializers: "LegalKeySizesValue = new[] { new KeySizes(40, 128, 8) };");
-                       // Rijndael supports block sizes that are not available in AES - as such it does not use the same generated code
-                       // but has it's own version, using AES (128 bits block size) and falling back to managed (192/256 bits block size)
-
-                       // System.Core replacements
-                       CommonCryptor.Generate ("System.Security.Cryptography", "AesManaged", "Aes", "AES128", "128");
-                       CommonCryptor.Generate ("System.Security.Cryptography", "AesCryptoServiceProvider", "Aes", "AES128");
-
-                       // Mono.Security replacements
-                       // RC4 is a stream (not a block) cipher so it can not reuse the generated code
-               }
-       }
-}
\ No newline at end of file
index 95b3bc8d33703c3e3ba1bee382763bebd35f5267..3203a94e3ccab1edf51f14726503d3457264ed51 100644 (file)
@@ -1,7 +1,6 @@
 thisdir = class/corlib
 SUBDIRS =
 include ../../build/rules.make
-include CommonCrypto/Makefile.include
 export __SECURITY_BOOTSTRAP_DB=$(topdir)/class/corlib
 
 LIBRARY = corlib.dll
@@ -71,6 +70,30 @@ endif
 TEST_MCS_FLAGS += -debug -nowarn:168,219,618,672 -unsafe \
                                 -define:MONO_DATACONVERTER_STATIC_METHODS $(TEST_RESX_RESOURCES:%=-resource:%)
 
+
+CC_PROFILE := $(filter monotouch% xammac, $(PROFILE))
+ifdef CC_PROFILE
+
+BUILT_SOURCES = \
+       CommonCrypto/AesCryptoServiceProvider.g.cs \
+       CommonCrypto/MD5CryptoServiceProvider.g.cs      \
+       CommonCrypto/SHA256Managed.g.cs \
+       CommonCrypto/AesManaged.g.cs \
+       CommonCrypto/RC2CryptoServiceProvider.g.cs \
+       CommonCrypto/SHA384Managed.g.cs \
+       CommonCrypto/DESCryptoServiceProvider.g.cs \
+       CommonCrypto/SHA1CryptoServiceProvider.g.cs     \
+       CommonCrypto/SHA512Managed.g.cs \
+       CommonCrypto/MD2Managed.g.cs \
+       CommonCrypto/SHA1Managed.g.cs \
+       CommonCrypto/TripleDESCryptoServiceProvider.g.cs \
+       CommonCrypto/MD4Managed.g.cs
+
+CommonCrypto/%.g.cs:
+       $(MAKE) -C CommonCrypto
+
+endif
+
 EXTRA_DISTFILES = \
        Test/resources/MyResources.resources    \
        Test/resources/MyResources.de.resources \
@@ -166,9 +189,6 @@ EXTRA_DISTFILES += \
        $(vtsdir)/VersionTolerantSerializationTestLib/6.0/Address.cs \
        $(vtsdir)/BinarySerializationOverVersions.cs
 
-EXTRA_DISTFILES += \
-       CommonCrypto/Makefile.include
-
 #
 # Android TimeZoneInfo testing....
 #
index afa470dd5c3dbd1c4e500fec031ee5805e549959..65ca59de4f3f17defb8a2b789c20637b33d2d02b 100644 (file)
@@ -201,7 +201,7 @@ namespace System.Diagnostics {
                                        else
                                                sb.AppendFormat ("<0x{0:x5} + 0x{1:x5}> {2}", frame.GetMethodAddress (), frame.GetNativeOffset (), unknown);
                                } else {
-                                       StackTraceHelper.GetFullNameForStackTrace (sb, frame.GetMethod ());
+                                       GetFullNameForStackTrace (sb, frame.GetMethod ());
 
                                        if (frame.GetILOffset () == -1) {
                                                sb.AppendFormat (" <0x{0:x5} + 0x{1:x5}>", frame.GetMethodAddress (), frame.GetNativeOffset ());
@@ -219,6 +219,58 @@ namespace System.Diagnostics {
                        return i != 0;
                }
 
+               public static void GetFullNameForStackTrace (StringBuilder sb, MethodBase mi)
+               {
+                       var declaringType = mi.DeclaringType;
+                       if (declaringType.IsGenericType && !declaringType.IsGenericTypeDefinition)
+                               declaringType = declaringType.GetGenericTypeDefinition ();
+
+                       // Get generic definition
+                       const BindingFlags bindingflags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
+                       foreach (var m in declaringType.GetMethods (bindingflags)) {
+                               if (m.MetadataToken == mi.MetadataToken) {
+                                       mi = m;
+                                       break;
+                               }
+                       }
+
+                       sb.Append (declaringType.ToString ());
+
+                       sb.Append (".");
+                       sb.Append (mi.Name);
+
+                       if (mi.IsGenericMethod) {
+                               Type[] gen_params = mi.GetGenericArguments ();
+                               sb.Append ("[");
+                               for (int j = 0; j < gen_params.Length; j++) {
+                                       if (j > 0)
+                                               sb.Append (",");
+                                       sb.Append (gen_params [j].Name);
+                               }
+                               sb.Append ("]");
+                       }
+
+                       ParameterInfo[] p = mi.GetParameters ();
+
+                       sb.Append (" (");
+                       for (int i = 0; i < p.Length; ++i) {
+                               if (i > 0)
+                                       sb.Append (", ");
+
+                               Type pt = p[i].ParameterType;
+                               if (pt.IsGenericType && ! pt.IsGenericTypeDefinition)
+                                       pt = pt.GetGenericTypeDefinition ();
+
+                               sb.Append (pt.ToString());
+
+                               if (p [i].Name != null) {
+                                       sb.Append (" ");
+                                       sb.Append (p [i].Name);
+                               }
+                       }
+                       sb.Append (")");
+               }               
+
                public override string ToString ()
                {
                        StringBuilder sb = new StringBuilder ();
diff --git a/mcs/class/corlib/System.Diagnostics/StackTraceHelper.cs b/mcs/class/corlib/System.Diagnostics/StackTraceHelper.cs
deleted file mode 100644 (file)
index e9e0a07..0000000
+++ /dev/null
@@ -1,94 +0,0 @@
-//
-// System.Diagnostics.StackTraceHelper.cs
-//
-// Author:
-//      Marcos Henrich (marcos.henrich@xamarin.com)
-//
-// Copyright (C) Xamarin, Inc (http://www.xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-namespace System.Diagnostics {
-
-       using System.Text;
-#if INSIDE_CORLIB
-       using System.Reflection;
-#else
-       using IKVM.Reflection;
-       using IKVM.Reflection.Reader;
-       using Type = IKVM.Reflection.Type;
-#endif
-       // This class exists so tools such as mono-symbolicate can use it directly.
-       class StackTraceHelper {
-               
-               public static void GetFullNameForStackTrace (StringBuilder sb, MethodBase mi)
-               {
-                       var declaringType = mi.DeclaringType;
-                       if (declaringType.IsGenericType && !declaringType.IsGenericTypeDefinition)
-                               declaringType = declaringType.GetGenericTypeDefinition ();
-
-                       // Get generic definition
-                       var bindingflags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
-                       foreach (var m in declaringType.GetMethods (bindingflags)) {
-                               if (m.MetadataToken == mi.MetadataToken) {
-                                       mi = m;
-                                       break;
-                               }
-                       }
-
-                       sb.Append (declaringType.ToString ());
-
-                       sb.Append (".");
-                       sb.Append (mi.Name);
-
-                       if (mi.IsGenericMethod) {
-                               Type[] gen_params = mi.GetGenericArguments ();
-                               sb.Append ("[");
-                               for (int j = 0; j < gen_params.Length; j++) {
-                                       if (j > 0)
-                                               sb.Append (",");
-                                       sb.Append (gen_params [j].Name);
-                               }
-                               sb.Append ("]");
-                       }
-
-                       ParameterInfo[] p = mi.GetParameters ();
-
-                       sb.Append (" (");
-                       for (int i = 0; i < p.Length; ++i) {
-                               if (i > 0)
-                                       sb.Append (", ");
-
-                               Type pt = p[i].ParameterType;
-                               if (pt.IsGenericType && ! pt.IsGenericTypeDefinition)
-                                       pt = pt.GetGenericTypeDefinition ();
-
-                               sb.Append (pt.ToString());
-
-                               if (p [i].Name != null) {
-                                       sb.Append (" ");
-                                       sb.Append (p [i].Name);
-                               }
-                       }
-                       sb.Append (")");
-               }
-       }
-}
index f263eeb1cc9c5673811165cf436fbfb7693285ff..3c7e87a6b7ac78ad8fbe13e42343fb67337d0698 100644 (file)
@@ -96,7 +96,7 @@ namespace System.IO
                                 info.Parent.Create ();
 
                        MonoIOError error;
-                       if (!MonoIO.CreateDirectory (path, out error)) {
+                       if (!MonoIO.CreateDirectory (info.FullName, out error)) {
                                // LAMESPEC: 1.1 and 1.2alpha allow CreateDirectory on a file path.
                                // So CreateDirectory ("/tmp/somefile") will succeed if 'somefile' is
                                // not a directory. However, 1.0 will throw an exception.
index 8289c288c20ffe228d3133c28a4c4569bf05b9d1..4f74c12bf8309441d336ed37bed907003651547f 100644 (file)
@@ -62,7 +62,7 @@ namespace System.IO {
 
                        FullPath = Path.GetFullPath (path);
                        if (simpleOriginalPath)
-                               OriginalPath = Path.GetFileName (path);
+                               OriginalPath = Path.GetFileName (FullPath);
                        else
                                OriginalPath = path;
 
index 9ac0e97545427ada48cdaaadfddd1f60b0eef086..f053d51225e6e8a1db5babe82cd6507e70394c01 100644 (file)
@@ -488,7 +488,7 @@ namespace System.IO {
                                        f = new FileStream (path, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.Read,
                                                            8192, false, (FileOptions) 1);
                                } catch (IOException ex){
-                                       if (ex.hresult != MonoIO.FileAlreadyExistsHResult || count ++ > 65536)
+                                       if (ex._HResult != MonoIO.FileAlreadyExistsHResult || count ++ > 65536)
                                                throw;
                                } catch (UnauthorizedAccessException ex) {
                                        if (count ++ > 65536)
index 4d8b2ee34ba918eaaca8660fbcd515c1b552b850..b7ce6e0410a767355c9db8fcf9c9f0387ffd5f50 100644 (file)
@@ -40,120 +40,21 @@ using System.Text;
 
 namespace System.Reflection.Emit
 {
-       internal enum TypeKind : int {
-               SZARRAY = 0x1d,
-               ARRAY = 0x14
-       }
-
        [StructLayout (LayoutKind.Sequential)]
-       internal abstract class DerivedType : Type
+       abstract partial class SymbolType
        {
-               internal Type elementType;
+               internal Type m_baseType;
 
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
-               internal static extern void create_unmanaged_type (Type type);
+               static extern void create_unmanaged_type (Type type);
 
-               internal DerivedType (Type elementType)
+               internal SymbolType (Type elementType)
                {
-                       this.elementType = elementType;
+                       this.m_baseType = elementType;
                }
 
                internal abstract String FormatName (string elementName);
 
-               public override Type GetInterface (string name, bool ignoreCase)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override Type[] GetInterfaces ()
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override Type GetElementType ()
-               {
-                       return elementType;
-               }
-
-               public override EventInfo GetEvent (string name, BindingFlags bindingAttr)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override EventInfo[] GetEvents (BindingFlags bindingAttr)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override FieldInfo GetField( string name, BindingFlags bindingAttr)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override FieldInfo[] GetFields (BindingFlags bindingAttr)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override MemberInfo[] GetMembers (BindingFlags bindingAttr)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr, Binder binder,
-                                                            CallingConventions callConvention, Type[] types,
-                                                            ParameterModifier[] modifiers)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override MethodInfo[] GetMethods (BindingFlags bindingAttr)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override Type GetNestedType (string name, BindingFlags bindingAttr)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override Type[] GetNestedTypes (BindingFlags bindingAttr)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override PropertyInfo[] GetProperties (BindingFlags bindingAttr)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               protected override PropertyInfo GetPropertyImpl (string name, BindingFlags bindingAttr, Binder binder,
-                                                                Type returnType, Type[] types, ParameterModifier[] modifiers)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               protected override ConstructorInfo GetConstructorImpl (BindingFlags bindingAttr,
-                                                                      Binder binder,
-                                                                      CallingConventions callConvention,
-                                                                      Type[] types,
-                                                                      ParameterModifier[] modifiers)
-               {
-                       throw new NotSupportedException ();
-               }
-
-
-               protected override TypeAttributes GetAttributeFlagsImpl ()
-               {
-                       /*LAMEIMPL MS just return the elementType.Attributes*/
-                       return elementType.Attributes; 
-               }
-
-               protected override bool HasElementTypeImpl ()
-               {
-                       return true;
-               }
-
                protected override bool IsArrayImpl ()
                {
                        return false;
@@ -164,60 +65,11 @@ namespace System.Reflection.Emit
                        return false;
                }
 
-               protected override bool IsCOMObjectImpl ()
-               {
-                       return false;
-               }
-
                protected override bool IsPointerImpl ()
                {
                        return false;
                }
 
-               protected override bool IsPrimitiveImpl ()
-               {
-                       return false;
-               }
-
-
-               public override ConstructorInfo[] GetConstructors (BindingFlags bindingAttr)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override object InvokeMember (string name, BindingFlags invokeAttr,
-                                                    Binder binder, object target, object[] args,
-                                                    ParameterModifier[] modifiers,
-                                                    CultureInfo culture, string[] namedParameters)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override InterfaceMapping GetInterfaceMap (Type interfaceType)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override bool IsInstanceOfType (object o)
-               {
-                       return false;
-               }
-
-               public override bool IsAssignableFrom (Type c)
-               {
-                       return false;
-               }
-
-               public override bool ContainsGenericParameters {
-                       get { return elementType.ContainsGenericParameters; }
-               }
-
-               //FIXME this should be handled by System.Type
-               public override Type MakeGenericType (params Type[] typeArguments)
-               {
-                       throw new NotSupportedException ();
-               }
-
                public override Type MakeArrayType ()
                {
                        return new ArrayType (this, 0);
@@ -242,59 +94,31 @@ namespace System.Reflection.Emit
 
                public override string ToString ()
                {
-                       return FormatName (elementType.ToString ());
-               }
-
-               public override GenericParameterAttributes GenericParameterAttributes {
-                       get { throw new NotSupportedException (); }
-               }
-
-               public override StructLayoutAttribute StructLayoutAttribute {
-                       get { throw new NotSupportedException (); }
-               }
-
-               public override Assembly Assembly {
-                       get { return elementType.Assembly; }
+                       return FormatName (m_baseType.ToString ());
                }
 
                public override string AssemblyQualifiedName {
                        get {
-                               string fullName = FormatName (elementType.FullName);
+                               string fullName = FormatName (m_baseType.FullName);
                                if (fullName == null)
                                        return null;
-                               return fullName + ", " + elementType.Assembly.FullName;
+                               return fullName + ", " + m_baseType.Assembly.FullName;
                        }
                }
 
 
                public override string FullName {
                        get {
-                               return FormatName (elementType.FullName);
+                               return FormatName (m_baseType.FullName);
                        }
                }
 
                public override string Name {
                        get {
-                               return FormatName (elementType.Name);
+                               return FormatName (m_baseType.Name);
                        }
                }
-
-               public override Guid GUID {
-                       get { throw new NotSupportedException (); }
-               }
-
-               public override Module Module {
-                       get { return elementType.Module; }
-               }
        
-               public override string Namespace {
-                       get { return elementType.Namespace; }
-               }
-
-               public override RuntimeTypeHandle TypeHandle {
-                       get { throw new NotSupportedException (); }
-               }
-
                public override Type UnderlyingSystemType {
                        get {
                                create_unmanaged_type (this);
@@ -302,31 +126,15 @@ namespace System.Reflection.Emit
                        }
                }
 
-               //MemberInfo
-               public override bool IsDefined (Type attributeType, bool inherit)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override object [] GetCustomAttributes (bool inherit)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override object [] GetCustomAttributes (Type attributeType, bool inherit)
-               {
-                       throw new NotSupportedException ();
-               }
-
                internal override bool IsUserType {
                        get {
-                               return elementType.IsUserType;
+                               return m_baseType.IsUserType;
                        }
                }
        }
 
        [StructLayout (LayoutKind.Sequential)]
-       internal class ArrayType : DerivedType
+       internal class ArrayType : SymbolType
        {
                int rank;
 
@@ -342,7 +150,7 @@ namespace System.Reflection.Emit
 
                internal override Type InternalResolve ()
                {
-                       Type et = elementType.InternalResolve (); 
+                       Type et = m_baseType.InternalResolve (); 
                        if (rank == 0)
                                return et.MakeArrayType ();                     
                        return et.MakeArrayType (rank);
@@ -358,15 +166,6 @@ namespace System.Reflection.Emit
                        return (rank == 0) ? 1 : rank;
                }
 
-               public override Type BaseType {
-                       get { return typeof (System.Array); }
-               }
-
-               protected override TypeAttributes GetAttributeFlagsImpl ()
-               {
-                       return elementType.Attributes;
-               }
-
                internal override String FormatName (string elementName)
                {
                        if (elementName == null)
@@ -383,7 +182,7 @@ namespace System.Reflection.Emit
        }
 
        [StructLayout (LayoutKind.Sequential)]
-       internal class ByRefType : DerivedType
+       internal class ByRefType : SymbolType
        {
                internal ByRefType (Type elementType) : base (elementType)
                {
@@ -391,7 +190,7 @@ namespace System.Reflection.Emit
 
                internal override Type InternalResolve ()
                {
-                       return elementType.InternalResolve ().MakeByRefType (); 
+                       return m_baseType.InternalResolve ().MakeByRefType (); 
                }
 
                protected override bool IsByRefImpl ()
@@ -399,10 +198,6 @@ namespace System.Reflection.Emit
                        return true;
                }
 
-               public override Type BaseType {
-                       get { return typeof (Array); }
-               }
-
                internal override String FormatName (string elementName)
                {
                        if (elementName == null)
@@ -432,7 +227,7 @@ namespace System.Reflection.Emit
        }
 
        [StructLayout (LayoutKind.Sequential)]
-       internal class PointerType : DerivedType
+       internal class PointerType : SymbolType
        {
                internal PointerType (Type elementType) : base (elementType)
                {
@@ -440,7 +235,7 @@ namespace System.Reflection.Emit
 
                internal override Type InternalResolve ()
                {
-                       return elementType.InternalResolve ().MakePointerType (); 
+                       return m_baseType.InternalResolve ().MakePointerType (); 
                }
 
                protected override bool IsPointerImpl ()
@@ -448,10 +243,6 @@ namespace System.Reflection.Emit
                        return true;
                }
 
-               public override Type BaseType {
-                       get { return typeof(Array); }
-               }
-
                internal override String FormatName (string elementName)
                {
                        if (elementName == null)
index 544774d1786061abd71dcd490fc36a4c8e4dbf4b..1c0e73c485f4aee2d3f7e35a2b67a4d6737f5d0f 100644 (file)
@@ -751,5 +751,20 @@ namespace System.Reflection {
                public override IList<CustomAttributeData> GetCustomAttributesData () {
                        return CustomAttributeData.GetCustomAttributes (this);
                }
+
+               [MethodImplAttribute(MethodImplOptions.InternalCall)]
+               public extern int get_core_clr_security_level ();
+
+               public override bool IsSecurityTransparent {
+                       get { return get_core_clr_security_level () == 0; }
+               }
+
+               public override bool IsSecurityCritical {
+                       get { return get_core_clr_security_level () > 0; }
+               }
+
+               public override bool IsSecuritySafeCritical {
+                       get { return get_core_clr_security_level () == 1; }
+               }
        }
 }
index 8bed0815d260a9d15a98da78b35cdbbe2a62f6ba..24f15e3f980437e7877e372bf84a63afb6220ffb 100644 (file)
@@ -412,7 +412,7 @@ namespace System.Runtime.InteropServices
                        var errorInfo = new ManagedErrorInfo(e);
                        SetErrorInfo (0, errorInfo);
 
-                       return e.hresult;
+                       return e._HResult;
 #else                  
                        return -1;
 #endif
@@ -1591,7 +1591,7 @@ namespace System.Runtime.InteropServices
                                }
                        }
 
-                       if (info is ManagedErrorInfo && ((ManagedErrorInfo) info).Exception.hresult == errorCode) {
+                       if (info is ManagedErrorInfo && ((ManagedErrorInfo) info).Exception._HResult == errorCode) {
                                return ((ManagedErrorInfo) info).Exception;
                        }
 
index 7178bedaa547e5ace0afd2186a5cae5d30d5483e..548bc5d93c08ec546441419ce1a0499805b2da5b 100644 (file)
@@ -37,6 +37,11 @@ namespace System.Security.Cryptography.X509Certificates
                        get;
                }
 
+               /*
+                * This is used in System.dll's OSX509Certificates.cs
+                */
+               public abstract IntPtr GetNativeAppleCertificate ();
+
                protected void ThrowIfContextInvalid ()
                {
                        if (!IsValid)
index c1fbac195286e29110b1bbcbfd844d91a4b8be99..718aadc3f374ab1ba539160635b4c594da13b2ab 100644 (file)
@@ -26,6 +26,12 @@ namespace System.Security.Cryptography.X509Certificates
                        get { return handle; }
                }
 
+               public override IntPtr GetNativeAppleCertificate ()
+               {
+                       ThrowIfContextInvalid ();
+                       return handle;
+               }
+
                public override X509CertificateImpl Clone ()
                {
                        ThrowIfContextInvalid ();
index 056bf561ee5a31a719907724b41b6e11cf4ef5ab..fa152e97f919844f8b46992853d506f795542347 100644 (file)
@@ -34,7 +34,7 @@ using MX = Mono.Security.X509;
 
 namespace System.Security.Cryptography.X509Certificates
 {
-       class X509CertificateImplMono : X509CertificateImpl
+       sealed class X509CertificateImplMono : X509CertificateImpl
        {
                MX.X509Certificate x509;
 
@@ -51,6 +51,11 @@ namespace System.Security.Cryptography.X509Certificates
                        get { return IntPtr.Zero; }
                }
 
+               public override IntPtr GetNativeAppleCertificate ()
+               {
+                       return IntPtr.Zero;
+               }
+
                public override X509CertificateImpl Clone ()
                {
                        ThrowIfContextInvalid ();
index c5cda6920d2edc3729e325bd3228629350ef94ae..b76c35d2d88324116507e97faef0a68db4969c08 100644 (file)
@@ -159,33 +159,33 @@ namespace System.Threading
 
                public static bool Wait(object obj, int millisecondsTimeout, bool exitContext) {
                        try {
-                               if (exitContext) {
-#if MONOTOUCH
-                                       throw new NotSupportedException ("exitContext == true is not supported");
-#else
+#if !DISABLE_REMOTING
+                               if (exitContext)
                                        SynchronizationAttribute.ExitContext ();
 #endif
-                               }
                                return Wait (obj, millisecondsTimeout);
                        }
                        finally {
-                               if (exitContext) SynchronizationAttribute.EnterContext ();
+#if !DISABLE_REMOTING
+                               if (exitContext)
+                                       SynchronizationAttribute.EnterContext ();
+#endif
                        }
                }
 
                public static bool Wait(object obj, TimeSpan timeout, bool exitContext) {
                        try {
-                               if (exitContext) {
-#if MONOTOUCH
-                                       throw new NotSupportedException ("exitContext == true is not supported");
-#else
+#if !DISABLE_REMOTING
+                               if (exitContext)
                                        SynchronizationAttribute.ExitContext ();
 #endif
-                               }
                                return Wait (obj, timeout);
                        }
                        finally {
-                               if (exitContext) SynchronizationAttribute.EnterContext ();
+#if !DISABLE_REMOTING
+                               if (exitContext)
+                                       SynchronizationAttribute.EnterContext ();
+#endif
                        }
                }
 
index 019647bc0bd85170bb18b74ae176517b3f1b1ad9..f09b9fe7e551c33a006f27bf3fa1300258b73e04 100644 (file)
@@ -47,16 +47,13 @@ namespace System.Threading
 
                static int WaitMultiple(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext, bool WaitAll)
                {
-#if MONOTOUCH
-                       if (exitContext)
-                               throw new NotSupportedException ("exitContext == true is not supported");
-#endif
-
                        int release_last = -1;
 
                        try {
+#if !DISABLE_REMOTING
                                if (exitContext)
                                        SynchronizationAttribute.ExitContext ();
+#endif
 
                                for (int i = 0; i < waitHandles.Length; ++i) {
                                        try {
@@ -70,51 +67,52 @@ namespace System.Threading
                                }
 
                                if (WaitAll)
-                                       return WaitAll_internal (waitHandles, millisecondsTimeout, exitContext);
+                                       return WaitAll_internal (waitHandles, millisecondsTimeout);
                                else
-                                       return WaitAny_internal (waitHandles, millisecondsTimeout, exitContext);
+                                       return WaitAny_internal (waitHandles, millisecondsTimeout);
                        } finally {
                                for (int i = release_last; i >= 0; --i) {
                                        waitHandles [i].SafeWaitHandle.DangerousRelease ();
                                }
 
+#if !DISABLE_REMOTING
                                if (exitContext)
                                        SynchronizationAttribute.EnterContext ();
+#endif
                        }
                }
 
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
-               private static extern int WaitAll_internal(WaitHandle[] handles, int ms, bool exitContext);
+               private static extern int WaitAll_internal(WaitHandle[] handles, int ms);
 
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
-               private static extern int WaitAny_internal(WaitHandle[] handles, int ms, bool exitContext);
+               private static extern int WaitAny_internal(WaitHandle[] handles, int ms);
 
                static int WaitOneNative (SafeHandle waitableSafeHandle, uint millisecondsTimeout, bool hasThreadAffinity, bool exitContext)
                {
-#if MONOTOUCH
-                       if (exitContext)
-                               throw new NotSupportedException ("exitContext == true is not supported");
-#endif
-
                        bool release = false;
                        try {
+#if !DISABLE_REMOTING
                                if (exitContext)
                                        SynchronizationAttribute.ExitContext ();
+#endif
 
                                waitableSafeHandle.DangerousAddRef (ref release);
 
-                               return WaitOne_internal (waitableSafeHandle.DangerousGetHandle (), (int) millisecondsTimeout, exitContext);
+                               return WaitOne_internal (waitableSafeHandle.DangerousGetHandle (), (int) millisecondsTimeout);
                        } finally {
                                if (release)
                                        waitableSafeHandle.DangerousRelease ();
 
+#if !DISABLE_REMOTING
                                if (exitContext)
                                        SynchronizationAttribute.EnterContext ();
+#endif
                        }
                }
 
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
-               static extern int WaitOne_internal(IntPtr handle, int ms, bool exitContext);
+               static extern int WaitOne_internal(IntPtr handle, int ms);
 
                static int SignalAndWaitOne (SafeWaitHandle waitHandleToSignal,SafeWaitHandle waitHandleToWaitOn, int millisecondsTimeout, bool hasThreadAffinity,  bool exitContext)
                {
@@ -123,7 +121,7 @@ namespace System.Threading
                                waitHandleToSignal.DangerousAddRef (ref releaseHandleToSignal);
                                waitHandleToWaitOn.DangerousAddRef (ref releaseHandleToWaitOn);
 
-                               return SignalAndWait_Internal (waitHandleToSignal.DangerousGetHandle (), waitHandleToWaitOn.DangerousGetHandle (), millisecondsTimeout, exitContext);
+                               return SignalAndWait_Internal (waitHandleToSignal.DangerousGetHandle (), waitHandleToWaitOn.DangerousGetHandle (), millisecondsTimeout);
                        } finally {
                                if (releaseHandleToSignal)
                                        waitHandleToSignal.DangerousRelease ();
@@ -133,6 +131,6 @@ namespace System.Threading
                }
 
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
-               static extern int SignalAndWait_Internal (IntPtr toSignal, IntPtr toWaitOn, int ms, bool exitContext);
+               static extern int SignalAndWait_Internal (IntPtr toSignal, IntPtr toWaitOn, int ms);
        }
 }
index 70a4dea80df5d68f1a7de17fc2dfde0121e99606..73fef7906bb639c401e1f481c212ddd2a20d0e5c 100644 (file)
@@ -57,7 +57,7 @@ namespace System {
                 * of icalls, do not require an increment.
                 */
 #pragma warning disable 169
-               private const int mono_corlib_version = 143;
+               private const int mono_corlib_version = 146;
 #pragma warning restore 169
 
                [ComVisible (true)]
@@ -985,6 +985,19 @@ namespace System {
                {
 
                }
+
+               // Copied from referencesource Environment
+               internal static String GetStackTrace(Exception e, bool needFileInfo)
+               {
+                       System.Diagnostics.StackTrace st;
+                       if (e == null)
+                               st = new System.Diagnostics.StackTrace(needFileInfo);
+                       else
+                               st = new System.Diagnostics.StackTrace(e, needFileInfo);
+
+                       // Do not include a trailing newline for backwards compatibility
+                       return st.ToString( System.Diagnostics.StackTrace.TraceFormat.Normal );
+               }
        }
 }
 
diff --git a/mcs/class/corlib/System/Exception.cs b/mcs/class/corlib/System/Exception.cs
deleted file mode 100644 (file)
index 7b6b492..0000000
+++ /dev/null
@@ -1,336 +0,0 @@
-//
-// System.Exception.cs
-//
-// Author:
-//   Miguel de Icaza (miguel@ximian.com)
-//   Patrik Torstensson
-//
-// (C) Ximian, Inc.  http://www.ximian.com
-// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System.Collections;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Reflection;
-using System.Text;
-using System.Runtime.InteropServices;
-using System.Runtime.CompilerServices;
-using System.Runtime.Serialization;
-using System.Security.Permissions;
-
-namespace System
-{
-       [Serializable]
-       [ComVisible(true)]
-       [ComDefaultInterface (typeof (_Exception))]
-       [ClassInterface (ClassInterfaceType.None)]
-       [StructLayout (LayoutKind.Sequential)]
-#if MOBILE
-       public class Exception : ISerializable
-#else
-       public class Exception : ISerializable, _Exception
-#endif
-       {
-#pragma warning disable 169, 649
-               #region Sync with object-internals.h
-               /* Stores the IPs and the generic sharing infos
-                  (vtable/MRGCTX) of the frames. */
-               IntPtr [] trace_ips;
-               Exception inner_exception;
-               internal string _message;
-               string help_link;
-               string class_name;
-               string stack_trace;
-               // formerly known as remote_stack_trace (see #425512):
-               string _remoteStackTraceString;
-               int remote_stack_index;
-               internal int hresult = -2146233088;
-               string source;
-               IDictionary _data;
-               internal StackTrace[] captured_traces;
-               IntPtr[] native_trace_ips;
-               object dynamic_methods;
-               #endregion
-#pragma warning restore 169, 649
-
-               /* Don't add fields here, the runtime depends on the layout of subclasses */
-
-               public Exception ()
-               {
-               }
-
-               public Exception (string message)
-               {
-                       this._message = message;
-               }
-
-               protected Exception (SerializationInfo info, StreamingContext context)
-               {
-                       if (info == null)
-                               throw new ArgumentNullException ("info");
-
-                       class_name          = info.GetString ("ClassName");
-                       _message             = info.GetString ("Message");
-                       help_link           = info.GetString ("HelpURL");
-                       stack_trace         = info.GetString ("StackTraceString");
-                       _remoteStackTraceString  = info.GetString ("RemoteStackTraceString");
-                       remote_stack_index  = info.GetInt32  ("RemoteStackIndex");
-                       hresult             = info.GetInt32  ("HResult");
-                       source              = info.GetString ("Source");
-                       inner_exception     = (Exception) info.GetValue ("InnerException", typeof (Exception));
-
-                       try {
-                               _data = (IDictionary) info.GetValue ("Data", typeof (IDictionary));
-                       } catch (SerializationException) {
-                               // member did not exist in .NET 1.x
-                       }
-               }
-
-               public Exception (string message, Exception innerException)
-               {
-                       inner_exception = innerException;
-                       this._message = message;
-               }
-
-               public Exception InnerException {
-                       get { return inner_exception; }
-               }
-
-               public virtual string HelpLink {
-                       get { return help_link; }
-                       set { help_link = value; }
-               }
-
-               public int HResult {
-                       get { return hresult; }
-                       protected set { hresult = value; }
-               }
-               
-               internal void SetErrorCode(int hr)
-               {
-                       HResult = hr;
-               }
-
-               internal void SetMessage (string s)
-               {
-                       _message = s;
-               }
-
-               internal void SetStackTrace (string s)
-               {
-                       stack_trace = s;
-               }
-
-               string ClassName {
-                       get {
-                               if (class_name == null)
-                                       class_name = GetType ().ToString ();
-                               return class_name;
-                       }
-               }
-
-               public virtual string Message {
-                       get {
-                               if (_message == null)
-                                       _message = string.Format (Locale.GetText ("Exception of type '{0}' was thrown."),
-                                               ClassName);
-
-                               return _message;
-                       }
-               }
-               
-               [MonoTODO]
-               protected event EventHandler<SafeSerializationEventArgs> SerializeObjectState {
-                       add {
-                       }
-                       remove {
-                       }
-               }
-
-               public virtual string Source {
-                       get {
-                               if (source == null) {
-                                       StackTrace st = new StackTrace (this, true);
-                                       if (st.FrameCount > 0) {
-                                               StackFrame sf = st.GetFrame (0);
-                                               if (st != null) {
-                                                       MethodBase method = sf.GetMethod ();
-                                                       if (method != null) {
-                                                               source = method.DeclaringType.Assembly.UnprotectedGetName ().Name;
-                                                       }
-                                               }
-                                       }
-                               }
-
-                               // source can be null
-                               return source;
-                       }
-
-                       set {
-                               source = value;
-                       }
-               }
-
-               public virtual string StackTrace {
-                       get {
-                               if (stack_trace != null)
-                                       return stack_trace;
-
-                               if (trace_ips == null)
-                                       /* Not thrown yet */
-                                       return null;
-
-                               StackTrace st = new StackTrace (this, 0, true);
-                               return stack_trace = st.ToString ();
-                       }
-               }
-
-               public MethodBase TargetSite {
-                       get {
-                               StackTrace st = new StackTrace (this, true);
-                               if (st.FrameCount > 0)
-                                       return st.GetFrame (0).GetMethod ();
-                               
-                               return null;
-                       }
-               }
-
-               public virtual IDictionary Data {
-                       get {
-                               if (_data == null) {
-                                       // default to empty dictionary
-                                       _data = new Dictionary<object, object> ();
-                               }
-                               return _data;
-                       }
-               }
-
-               public virtual Exception GetBaseException ()
-               {
-                       Exception inner = inner_exception;
-                               
-                       while (inner != null)
-                       {
-                               if (inner.InnerException != null)
-                                       inner = inner.InnerException;
-                               else
-                                       return inner;
-                       }
-
-                       return this;
-               }
-
-               [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
-               public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
-               {
-                       if (info == null)
-                               throw new ArgumentNullException ("info");
-
-                       info.AddValue ("ClassName", ClassName);
-                       info.AddValue ("Message", _message);
-                       info.AddValue ("InnerException", inner_exception, typeof (Exception));
-                       info.AddValue ("HelpURL", help_link);
-                       info.AddValue ("StackTraceString", StackTrace);
-                       info.AddValue ("RemoteStackTraceString", _remoteStackTraceString);
-                       info.AddValue ("RemoteStackIndex", remote_stack_index);
-                       info.AddValue ("HResult", hresult);
-                       info.AddValue ("Source", Source);
-                       info.AddValue ("ExceptionMethod", null);
-                       info.AddValue ("Data", _data, typeof (IDictionary));
-               }
-
-               public override string ToString ()
-               {
-                       System.Text.StringBuilder result = new System.Text.StringBuilder (ClassName);
-                       result.Append (": ").Append (Message);
-
-                       if (null != _remoteStackTraceString)
-                               result.Append (_remoteStackTraceString);
-                               
-                       if (inner_exception != null) 
-                       {
-                               result.Append (" ---> ").Append (inner_exception.ToString ());
-                               result.Append (Environment.NewLine);
-                               result.Append (Locale.GetText ("  --- End of inner exception stack trace ---"));
-                       }
-
-                       if (StackTrace != null)
-                               result.Append (Environment.NewLine).Append (StackTrace);
-                       return result.ToString();
-               }
-
-               internal Exception FixRemotingException ()
-               {
-                       string message = (0 == remote_stack_index) ?
-                               Locale.GetText ("{0}{0}Server stack trace: {0}{1}{0}{0}Exception rethrown at [{2}]: {0}") :
-                               Locale.GetText ("{1}{0}{0}Exception rethrown at [{2}]: {0}");
-                       string tmp = String.Format (message, Environment.NewLine, StackTrace, remote_stack_index);
-
-                       _remoteStackTraceString = tmp;
-                       remote_stack_index++;
-
-                       stack_trace = null;
-
-                       return this;
-               }
-
-               // For ExceptionDispatchInfo
-               internal void RestoreExceptionDispatchInfo (System.Runtime.ExceptionServices.ExceptionDispatchInfo exceptionDispatchInfo)
-               {
-                       captured_traces = (StackTrace[]) exceptionDispatchInfo.BinaryStackTraceArray;
-                       trace_ips = null;
-                       stack_trace = null;
-               }
-
-               //
-               // The documentation states that this is available in 1.x,
-               // but it was not available (MemberRefing this would fail)
-               // and it states the signature is `override sealed', but the
-               // correct value is `newslot' 
-               //
-               public new Type GetType ()
-               {
-                       return base.GetType ();
-               }
-
-               internal enum ExceptionMessageKind
-               {
-                       ThreadAbort = 1,
-                       ThreadInterrupted = 2,
-                       OutOfMemory = 3
-               }
-
-               internal static String GetMessageFromNativeResources (ExceptionMessageKind kind)
-               {
-                       switch (kind) {
-                       case ExceptionMessageKind.ThreadAbort:
-                               return "";
-                       case ExceptionMessageKind.ThreadInterrupted:
-                               return "";
-                       case ExceptionMessageKind.OutOfMemory:
-                               return "Out of memory";
-                       }
-                       return "";
-               }
-       }
-}
index b17cfd62c55c5724bea9f608fbbb058f4382471f..8ef9dcf4680b0a486793b9eb69a4abc518cf75a1 100644 (file)
@@ -230,6 +230,17 @@ public class DirectoryTest
                }\r
        }\r
 \r
+       [Test]\r
+       public void CreateDirectoryRelativePath ()\r
+       {\r
+               var path = Path.Combine (TempFolder, "relativepath", "not_this_folder");\r
+               path = Path.Combine (path, "..");\r
+\r
+               var res = Directory.CreateDirectory (path);\r
+               Assert.AreEqual ("relativepath", res.ToString (), "#1");\r
+               Assert.IsTrue (Directory.Exists (Path.Combine (TempFolder, "relativepath")), "#2");\r
+       }\r
+\r
        [Test]\r
        public void Delete ()\r
        {\r
index fa37466a77ad7083c62be10b91be468b6d5b5bd9..122e5b65fc24e29f25e4fddb245904208ba8a4cf 100644 (file)
@@ -1586,6 +1586,7 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.IsFalse (arr.IsGenericParameter, "#8");
                        Assert.IsFalse (arr.IsGenericType, "#9");
                        Assert.IsFalse (arr.IsGenericTypeDefinition, "#10");
+                       Assert.IsTrue (arr is TypeInfo, "#11");
                }
 
                [Test]
@@ -1664,6 +1665,7 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.AreEqual ("F[]", arr.Name, "#21");
 
                        Assert.AreEqual (gparam, arr.GetElementType (), "#22");
+                       Assert.IsTrue (arr is TypeInfo, "#23");
                }
 
                [Test]
@@ -1718,6 +1720,7 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.AreEqual ("enum[]", arr.Name, "#21");
 
                        Assert.AreEqual (eb, arr.GetElementType (), "#22");
+                       Assert.IsTrue (arr is TypeInfo, "#23");
                }
 
        }
index 11e81774310f6912bbf366272d4a7334cd2db67a..6cdc052f4fb97f8b2d630733e32e5a69a9b814bc 100644 (file)
@@ -39,7 +39,7 @@ namespace MonoTests.System.Security.Cryptography {
                public void Ctor () 
                {
                        var cp = new CspParameters ();
-                       Assert.AreEqual (24, cp.ProviderType);
+                       Assert.AreEqual (1, cp.ProviderType);
                }
        }
 }
index 2ed3b6003c7a440cbfb529a6dbd78b5002aa1ed2..ce1c9793fc57daeef63df5687cbea2c505ac916d 100644 (file)
@@ -103,7 +103,7 @@ namespace MonoTests.System.Threading {
                [Test] // bug #320950
                public void TestDispose2 ()
                {
-                       Timer t = new Timer (o => Callback (o), null, 10, 10);
+                       Timer t = new Timer (o => DoNothing (o), null, 10, 10);
                        t.Dispose ();
                        t.Dispose ();
                }
index ae5a82908c861894674a758b8ba8496d5027da2a..e1d95dc93f00f563a4a7415708b3714d5a107a4f 100644 (file)
@@ -1251,7 +1251,7 @@ namespace MonoTests.System
                        }
                }
        
-               delegate int IntNoArgs ();
+               public delegate int IntNoArgs ();
 
                [Test]
                public void CreateDelegateWithAbstractMethods ()
index 357ec961ca673f784b64536658ca4dbcba9cb499..b7c1fd18db368ab5829fb39f4d834d7c78fac068 100644 (file)
@@ -100,7 +100,6 @@ System/DomainManagerInitializationFlags.cs
 System/EmptyArray.cs
 System/Environment.cs
 System/EnvironmentVariableTarget.cs
-System/Exception.cs
 System/GC.cs
 System/GCCollectionMode.cs
 System/GCNotificationStatus.cs
@@ -161,7 +160,6 @@ System.Deployment.Internal/InternalApplicationIdentityHelper.cs
 System.Diagnostics/Debugger.cs
 System.Diagnostics/StackFrame.cs
 System.Diagnostics/StackTrace.cs
-System.Diagnostics/StackTraceHelper.cs
 System.Diagnostics.Tracing/EventAttribute.cs
 System.Diagnostics.Tracing/EventCommand.cs
 System.Diagnostics.Tracing/EventSource.cs
@@ -974,6 +972,7 @@ ReferenceSources/SecurityContext.cs
 ../../../external/referencesource/mscorlib/system/entrypointnotfoundexception.cs
 ../../../external/referencesource/mscorlib/system/eventargs.cs
 ../../../external/referencesource/mscorlib/system/eventhandler.cs
+../../../external/referencesource/mscorlib/system/exception.cs
 ../../../external/referencesource/mscorlib/system/executionengineexception.cs
 ../../../external/referencesource/mscorlib/system/fieldaccessexception.cs
 ../../../external/referencesource/mscorlib/system/flagsattribute.cs
@@ -1259,6 +1258,7 @@ ReferenceSources/SecurityContext.cs
 ../../../external/referencesource/mscorlib/system/reflection/typeinfo.cs
 
 ../../../external/referencesource/mscorlib/system/reflection/emit/methodbuilder.cs
+../../../external/referencesource/mscorlib/system/reflection/emit/symboltype.cs
 
 ../../../external/referencesource/mscorlib/system/resources/__fastresourcecomparer.cs
 ../../../external/referencesource/mscorlib/system/resources/__hresults.cs
index e802a034dd64f2aa7f7a9a97dd76b0aaf3ed4294..6acc765c090d0c5e18bf7673c56328dbb30053a8 100644 (file)
@@ -3,21 +3,9 @@ CommonCrypto/CommonCrypto.cs
 CommonCrypto/CryptorTransform.cs
 CommonCrypto/FastCryptorTransform.cs
 CommonCrypto/CorlibExtras.cs
-CommonCrypto/MD5CryptoServiceProvider.g.cs
-CommonCrypto/SHA1CryptoServiceProvider.g.cs
-CommonCrypto/SHA1CryptoServiceProvider.g.cs
-CommonCrypto/SHA1Managed.g.cs
-CommonCrypto/SHA256Managed.g.cs
-CommonCrypto/SHA384Managed.g.cs
-CommonCrypto/SHA512Managed.g.cs
-CommonCrypto/TripleDESCryptoServiceProvider.g.cs
-CommonCrypto/DESCryptoServiceProvider.g.cs
-CommonCrypto/RC2CryptoServiceProvider.g.cs
 CommonCrypto/RijndaelManaged.cs
 CommonCrypto/SecRandom.cs
 CommonCrypto/RC4CommonCrypto.cs
-CommonCrypto/MD2Managed.g.cs
-CommonCrypto/MD4Managed.g.cs
 System/Environment.iOS.cs
 System/Guid.MonoTouch.cs
 System/NotSupportedException.iOS.cs
index e802a034dd64f2aa7f7a9a97dd76b0aaf3ed4294..6acc765c090d0c5e18bf7673c56328dbb30053a8 100644 (file)
@@ -3,21 +3,9 @@ CommonCrypto/CommonCrypto.cs
 CommonCrypto/CryptorTransform.cs
 CommonCrypto/FastCryptorTransform.cs
 CommonCrypto/CorlibExtras.cs
-CommonCrypto/MD5CryptoServiceProvider.g.cs
-CommonCrypto/SHA1CryptoServiceProvider.g.cs
-CommonCrypto/SHA1CryptoServiceProvider.g.cs
-CommonCrypto/SHA1Managed.g.cs
-CommonCrypto/SHA256Managed.g.cs
-CommonCrypto/SHA384Managed.g.cs
-CommonCrypto/SHA512Managed.g.cs
-CommonCrypto/TripleDESCryptoServiceProvider.g.cs
-CommonCrypto/DESCryptoServiceProvider.g.cs
-CommonCrypto/RC2CryptoServiceProvider.g.cs
 CommonCrypto/RijndaelManaged.cs
 CommonCrypto/SecRandom.cs
 CommonCrypto/RC4CommonCrypto.cs
-CommonCrypto/MD2Managed.g.cs
-CommonCrypto/MD4Managed.g.cs
 System/Environment.iOS.cs
 System/Guid.MonoTouch.cs
 System/NotSupportedException.iOS.cs
index e802a034dd64f2aa7f7a9a97dd76b0aaf3ed4294..6acc765c090d0c5e18bf7673c56328dbb30053a8 100644 (file)
@@ -3,21 +3,9 @@ CommonCrypto/CommonCrypto.cs
 CommonCrypto/CryptorTransform.cs
 CommonCrypto/FastCryptorTransform.cs
 CommonCrypto/CorlibExtras.cs
-CommonCrypto/MD5CryptoServiceProvider.g.cs
-CommonCrypto/SHA1CryptoServiceProvider.g.cs
-CommonCrypto/SHA1CryptoServiceProvider.g.cs
-CommonCrypto/SHA1Managed.g.cs
-CommonCrypto/SHA256Managed.g.cs
-CommonCrypto/SHA384Managed.g.cs
-CommonCrypto/SHA512Managed.g.cs
-CommonCrypto/TripleDESCryptoServiceProvider.g.cs
-CommonCrypto/DESCryptoServiceProvider.g.cs
-CommonCrypto/RC2CryptoServiceProvider.g.cs
 CommonCrypto/RijndaelManaged.cs
 CommonCrypto/SecRandom.cs
 CommonCrypto/RC4CommonCrypto.cs
-CommonCrypto/MD2Managed.g.cs
-CommonCrypto/MD4Managed.g.cs
 System/Environment.iOS.cs
 System/Guid.MonoTouch.cs
 System/NotSupportedException.iOS.cs
index e802a034dd64f2aa7f7a9a97dd76b0aaf3ed4294..6acc765c090d0c5e18bf7673c56328dbb30053a8 100644 (file)
@@ -3,21 +3,9 @@ CommonCrypto/CommonCrypto.cs
 CommonCrypto/CryptorTransform.cs
 CommonCrypto/FastCryptorTransform.cs
 CommonCrypto/CorlibExtras.cs
-CommonCrypto/MD5CryptoServiceProvider.g.cs
-CommonCrypto/SHA1CryptoServiceProvider.g.cs
-CommonCrypto/SHA1CryptoServiceProvider.g.cs
-CommonCrypto/SHA1Managed.g.cs
-CommonCrypto/SHA256Managed.g.cs
-CommonCrypto/SHA384Managed.g.cs
-CommonCrypto/SHA512Managed.g.cs
-CommonCrypto/TripleDESCryptoServiceProvider.g.cs
-CommonCrypto/DESCryptoServiceProvider.g.cs
-CommonCrypto/RC2CryptoServiceProvider.g.cs
 CommonCrypto/RijndaelManaged.cs
 CommonCrypto/SecRandom.cs
 CommonCrypto/RC4CommonCrypto.cs
-CommonCrypto/MD2Managed.g.cs
-CommonCrypto/MD4Managed.g.cs
 System/Environment.iOS.cs
 System/Guid.MonoTouch.cs
 System/NotSupportedException.iOS.cs
index 0dbb5163c7042ef38fd2f08e6f1fc01a3611dd6f..f321e0bc800fc1f1ecca58a541972df1fe8b7d29 100644 (file)
@@ -3,20 +3,8 @@ CommonCrypto/CommonCrypto.cs
 CommonCrypto/CryptorTransform.cs
 CommonCrypto/FastCryptorTransform.cs
 CommonCrypto/CorlibExtras.cs
-CommonCrypto/MD5CryptoServiceProvider.g.cs
-CommonCrypto/SHA1CryptoServiceProvider.g.cs
-CommonCrypto/SHA1CryptoServiceProvider.g.cs
-CommonCrypto/SHA1Managed.g.cs
-CommonCrypto/SHA256Managed.g.cs
-CommonCrypto/SHA384Managed.g.cs
-CommonCrypto/SHA512Managed.g.cs
-CommonCrypto/TripleDESCryptoServiceProvider.g.cs
-CommonCrypto/DESCryptoServiceProvider.g.cs
-CommonCrypto/RC2CryptoServiceProvider.g.cs
 CommonCrypto/RijndaelManaged.cs
 CommonCrypto/RC4CommonCrypto.cs
-CommonCrypto/MD2Managed.g.cs
-CommonCrypto/MD4Managed.g.cs
 CoreFoundation/CFHelpers.cs
 System.Security.Cryptography.X509Certificates/X509CertificateImplApple.cs
 System.Security.Cryptography.X509Certificates/X509Helper.Apple.cs
diff --git a/mcs/errors/cs0023-27.cs b/mcs/errors/cs0023-27.cs
new file mode 100644 (file)
index 0000000..068c08a
--- /dev/null
@@ -0,0 +1,13 @@
+// CS0023: The `?' operator cannot be applied to operand of type `T'
+// Line: 11
+
+class C2<T>
+{
+       C2<T> i;
+       T field;
+
+       public void Foo ()
+       {
+               var x = i?.field;
+       }
+}
\ No newline at end of file
diff --git a/mcs/errors/cs0023-28.cs b/mcs/errors/cs0023-28.cs
new file mode 100644 (file)
index 0000000..e9f7942
--- /dev/null
@@ -0,0 +1,15 @@
+// CS0023: The `?' operator cannot be applied to operand of type `T'
+// Line: 13
+
+interface IFoo<T>
+{
+       T Call ();
+}
+
+class C1
+{
+       U Foo<T, U> (IFoo<T> t)
+       {
+               return t?.Call ();
+       }
+}
diff --git a/mcs/errors/cs0023-29.cs b/mcs/errors/cs0023-29.cs
new file mode 100644 (file)
index 0000000..aea3068
--- /dev/null
@@ -0,0 +1,10 @@
+// CS0023: The `?' operator cannot be applied to operand of type `T'
+// Line: 8
+
+class X
+{
+       static void Bug<T>(System.Func<T> func)
+       {
+               var r = func?.Invoke ();
+       }
+}
\ No newline at end of file
index 723b603c5f26ed85bd85dcfc73f9826ccc440817..9fb47abf6d486d9ba4d78811a9d0e68f420f3d13 100644 (file)
@@ -1,4 +1,4 @@
-// CS0029: Cannot implicitly convert type `B [cs0029-26, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]' to `B [CS0029-26-lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=36f3ae7e947792e3]'
+// CS0029: Cannot implicitly convert type `B [cs0029-26, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null -- *PATH*/cs0029-26.cs]' to `B [CS0029-26-lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=36f3ae7e947792e3 -- *PATH*/CS0029-26-lib.dll]'
 // Line: 16
 // Compiler options: -r:R1=CS0029-26-lib.dll
 
diff --git a/mcs/errors/cs0266-30.cs b/mcs/errors/cs0266-30.cs
new file mode 100644 (file)
index 0000000..62cc53f
--- /dev/null
@@ -0,0 +1,14 @@
+// CS0266: Cannot implicitly convert type `Foo<int>.FooEvent' to `Foo<string>.FooEvent'. An explicit conversion exists (are you missing a cast?)
+// Line: 12
+
+class Foo<T> {
+       public event FooEvent Event;
+       public delegate T FooEvent();
+}
+
+class CompilerCrashTest {
+       static void Main() {
+               Foo<string> foo = new Foo<string>();
+               foo.Event += new Foo<int>.FooEvent (() => 0);
+       }
+}
index edc538e7d2ed66a09ab7b5cbd397aec15b3ac3d0..bcf7ddffa21cd928e8b8a6cbfb811c2735940f7f 100644 (file)
@@ -940,7 +940,8 @@ namespace Mono.CSharp
 
                TypeParameterSpec[] ITypeDefinition.TypeParameters {
                        get {
-                               return PartialContainer.CurrentTypeParameters.Types;
+                               var ctp = PartialContainer.CurrentTypeParameters;
+                               return ctp == null ? TypeParameterSpec.EmptyTypes : ctp.Types;
                        }
                }
 
index 1dfb747ba6a46f96ebff889b48259408c371f46a..d5ba75c12813af9d07e4b3182134f82cc3e557f9 100644 (file)
@@ -1263,10 +1263,15 @@ namespace Mono.CSharp
 
                        if (conditionalAccess) {
                                if (!ec.ConditionalAccess.Statement) {
-                                       if (ec.ConditionalAccess.Type.IsNullableType)
-                                               Nullable.LiftedNull.Create (ec.ConditionalAccess.Type, Location.Null).Emit (ec);
-                                       else
+                                       var t = ec.ConditionalAccess.Type;
+                                       if (t.IsNullableType)
+                                               Nullable.LiftedNull.Create (t, Location.Null).Emit (ec);
+                                       else {
                                                ec.EmitNull ();
+
+                                               if (t.IsGenericParameter)
+                                                       ec.Emit (OpCodes.Unbox_Any, t);
+                                       }
                                }
 
                                ec.Emit (OpCodes.Br, ec.ConditionalAccess.EndLabel);
index b0c771f7207b2eb26aa12a288bd58e11f811aae3..6783a7edbb672ef70e00d3684e3f35427ea12eab 100644 (file)
@@ -3926,7 +3926,9 @@ array_creation_expression
                if ($4 == null)
                        report.Error (1586, GetLocation ($1), "Array creation must have array size or array initializer");
 
-               $$ = new ArrayCreation ((FullNamedExpression) $2, (ComposedTypeSpecifier) $3, (ArrayInitializer) $4, GetLocation ($1));
+               $$ = new ArrayCreation ((FullNamedExpression) $2, (ComposedTypeSpecifier) $3, (ArrayInitializer) $4, GetLocation ($1)) {
+                       NoEmptyInterpolation = true
+               };
          }
        | NEW rank_specifier array_initializer
          {
index 8553856ac585229093f9edb551cd9f993ce78276..4a0e4af6fc896df171530249f820649ebb8df0d5 100644 (file)
@@ -535,7 +535,7 @@ namespace Mono.CSharp {
 
                void ResolveConditionalAccessReceiver (ResolveContext rc)
                {
-                       // LAMESPEC: Not sure why this is explicitly disalloed with very odd error message
+                       // LAMESPEC: Not sure why this is explicitly disallowed with very odd error message
                        if (!rc.HasSet (ResolveContext.Options.DontSetConditionalAccessReceiver) && method_group.HasConditionalAccess ()) {
                                Error_OperatorCannotBeApplied (rc, loc, "?", method_group.Type);
                        }
index 145f222bdcd39d2f100c230845024b4881b99258..fc99defc44e19359646b879d59bb7feb63bba902 100644 (file)
@@ -469,8 +469,13 @@ namespace Mono.CSharp {
                        return false;
                }
 
-               protected static TypeSpec LiftMemberType (ResolveContext rc, TypeSpec type)
+               protected TypeSpec LiftMemberType (ResolveContext rc, TypeSpec type)
                {
+                       var tps = type as TypeParameterSpec;
+                       if (tps != null && !(tps.IsReferenceType || tps.IsValueType)) {
+                               Error_OperatorCannotBeApplied (rc, loc, "?", type);
+                       }
+
                        return TypeSpec.IsValueType (type) && !type.IsNullableType ?
                                Nullable.NullableInfo.MakeType (rc.Module, type) :
                                type;
@@ -1332,7 +1337,7 @@ namespace Mono.CSharp {
                {
                }
 
-               public ExpressionStatement ResolveStatement (BlockContext ec)
+               public virtual ExpressionStatement ResolveStatement (BlockContext ec)
                {
                        Expression e = Resolve (ec);
                        if (e == null)
@@ -4647,7 +4652,7 @@ namespace Mono.CSharp {
                ///     false if candidate ain't better
                ///     true  if candidate is better than the current best match
                /// </remarks>
-               static bool BetterFunction (ResolveContext ec, Arguments args, MemberSpec candidate, AParametersCollection cparam, bool candidate_params,
+               bool BetterFunction (ResolveContext ec, Arguments args, MemberSpec candidate, AParametersCollection cparam, bool candidate_params,
                        MemberSpec best, AParametersCollection bparam, bool best_params)
                {
                        AParametersCollection candidate_pd = ((IParametersMember) candidate).Parameters;
@@ -4705,6 +4710,12 @@ namespace Mono.CSharp {
                                // for each argument, the conversion to 'ct' should be no worse than 
                                // the conversion to 'bt'.
                                if (result == 2) {
+                                       //
+                                       // No optional parameters tie breaking rules for delegates overload resolution
+                                       //
+                                       if ((this.restrictions & Restrictions.CovariantDelegate) != 0)
+                                               return false;
+
                                        better_at_least_one = false;
 
                                        ++j;
index 76bcdbfa0ee7bdf8109573a1e6db43c9b9797deb..aadf818066d2ad89b3d82a2b8488256753e09d9c 100644 (file)
@@ -7023,6 +7023,16 @@ namespace Mono.CSharp
                        }
                }
 
+               bool statement_resolve;
+               public override ExpressionStatement ResolveStatement (BlockContext bc)
+               {
+                       statement_resolve = true;
+                       var es = base.ResolveStatement (bc);
+                       statement_resolve = false;
+
+                       return es;
+               }
+
                protected override Expression DoResolve (ResolveContext rc)
                {
                        ResolveConditionalAccessReceiver (rc);
@@ -7111,7 +7121,7 @@ namespace Mono.CSharp
 
                        var method = mg.BestCandidate;
                        type = mg.BestCandidateReturnType;
-                       if (conditional_access_receiver)
+                       if (conditional_access_receiver && !statement_resolve)
                                type = LiftMemberType (ec, type);
 
                        if (arguments == null && method.DeclaringType.BuiltinType == BuiltinTypeSpec.Type.Object && method.Name == Destructor.MetadataName) {
@@ -7862,6 +7872,8 @@ namespace Mono.CSharp
                {
                }
 
+               public bool NoEmptyInterpolation { get; set; }
+
                public ComposedTypeSpecifier Rank {
                        get {
                                return this.rank;
@@ -8398,7 +8410,7 @@ namespace Mono.CSharp
 
                public override void Emit (EmitContext ec)
                {
-                       if (EmitOptimizedEmpty (ec))
+                       if (!NoEmptyInterpolation && EmitOptimizedEmpty (ec))
                                return;
 
                        var await_field = EmitToFieldSource (ec);
index 81894f06c762ea1d6146e2e9d99905b2d3a7f4e1..fb02370dbb32cd2317827d323637b370d01e0048 100644 (file)
@@ -547,7 +547,15 @@ namespace Mono.CSharp
 
                public string GetSignatureForErrorIncludingAssemblyName ()
                {
-                       return string.Format ("{0} [{1}]", GetSignatureForError (), MemberDefinition.DeclaringAssembly.FullName);
+                       var imported = MemberDefinition.DeclaringAssembly as ImportedAssemblyDefinition;
+
+                       var location = imported != null ?
+                               System.IO.Path.GetFullPath (imported.Location) :
+                           ((MemberCore)MemberDefinition).Location.NameFullPath;
+
+                       return string.Format ("{0} [{1} -- {2}]", GetSignatureForError (),
+                                                                 MemberDefinition.DeclaringAssembly.FullName,
+                                                                 location);
                }
 
                protected virtual string GetTypeNameSignature ()
diff --git a/mcs/tests/gtest-optional-37.cs b/mcs/tests/gtest-optional-37.cs
new file mode 100644 (file)
index 0000000..f322ff6
--- /dev/null
@@ -0,0 +1,19 @@
+using System;
+
+class Test1
+{
+       static object Foo (int arg = 1, int arg2 = 2)
+       {
+               return null;
+       }
+
+       static object Foo (object arg, object arg2)
+       {
+               return null;
+       }
+
+       public static void Main ()
+       {
+               Func<int, int, object> o = Foo;
+       }
+}
\ No newline at end of file
diff --git a/mcs/tests/test-934.cs b/mcs/tests/test-934.cs
new file mode 100644 (file)
index 0000000..ba464e3
--- /dev/null
@@ -0,0 +1,22 @@
+class X
+{
+       public static int Main ()
+       {
+               var a = new byte[] { };
+               var b = new byte[] { };
+               if (a.Equals (b))
+                       return 1;
+
+               if (ReferenceEquals (a, b))
+                       return 2;
+
+               b = new byte[0];
+               if (a.Equals (b))
+                       return 3;
+
+               if (ReferenceEquals (a, b))
+                       return 4;
+
+               return 0;
+       }
+}
\ No newline at end of file
diff --git a/mcs/tests/test-null-operator-04.cs b/mcs/tests/test-null-operator-04.cs
new file mode 100644 (file)
index 0000000..c28aa17
--- /dev/null
@@ -0,0 +1,55 @@
+using System;
+
+interface IFoo<T>
+{
+       T Call ();
+}
+
+class C1
+{
+       public void Foo<T> (IFoo<T> t) where T : class
+       {
+               t?.Call ();
+               var x = t?.Call ();
+       }
+
+       public void Foo2<T> (IFoo<T> t)
+       {
+               t?.Call ();
+       }       
+}
+
+class C2<T> where T : class
+{
+       C2<T> i;
+       T field;
+
+       public void Foo ()
+       {
+               var x = i?.field;
+       }
+}
+
+class Program
+{
+       static void Test<T>(Func<T> func) where T : struct
+       {
+               var r = func?.Invoke ();
+       }
+
+       static void Test2<T>(Func<T> func)
+       {
+               func?.Invoke ();
+       }
+
+       static void Main()
+       {
+               new C1 ().Foo<Program> (null);
+               new C1 ().Foo2<Program> (null);
+
+               new C2<string> ().Foo ();
+
+               Test (() => 1);
+               Test (() => 2);
+       }
+}
\ No newline at end of file
index 12fdee1863bbe80ec80daecb95ac2060d531a884..027fd9871ef422bf008dc6f7e66ff4196ed13027 100644 (file)
     </type>
     <type name="ExtensibleTester`1[U]">
       <method name="Void Direct()" attrs="134">
-        <size>24</size>
+        <size>25</size>
       </method>
       <method name="Void .ctor(U)" attrs="6278">
         <size>15</size>
     </type>
     <type name="TestIssue.Program">
       <method name="Int32 Main()" attrs="150">
-        <size>31</size>
+        <size>32</size>
       </method>
       <method name="Void .ctor()" attrs="6278">
         <size>7</size>
         <size>7</size>
       </method>
       <method name="Int32 Main()" attrs="150">
-        <size>36</size>
+        <size>37</size>
       </method>
       <method name="Void .ctor()" attrs="6278">
         <size>7</size>
       </method>
     </type>
   </test>
+  <test name="gtest-optional-37.cs">
+    <type name="Test1">
+      <method name="System.Object Foo(Int32, Int32)" attrs="145">
+        <size>10</size>
+      </method>
+      <method name="System.Object Foo(System.Object, System.Object)" attrs="145">
+        <size>10</size>
+      </method>
+      <method name="Void Main()" attrs="150">
+        <size>32</size>
+      </method>
+      <method name="Void .ctor()" attrs="6278">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
   <test name="gtest-partial-01.cs">
     <type name="B`1[U]">
       <method name="Void .ctor()" attrs="6278">
   <test name="test-555.cs">
     <type name="Test">
       <method name="Int32 Main()" attrs="150">
-        <size>360</size>
+        <size>361</size>
       </method>
       <method name="Void .ctor()" attrs="6278">
         <size>7</size>
       </method>
     </type>
   </test>
+  <test name="test-934.cs">
+    <type name="X">
+      <method name="Int32 Main()" attrs="150">
+        <size>106</size>
+      </method>
+      <method name="Void .ctor()" attrs="6278">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
   <test name="test-94.cs">
     <type name="Base">
       <method name="Int32 IVehicle.Start()" attrs="481">
         <size>14</size>
       </method>
       <method name="Boolean MoveNext()" attrs="486">
-        <size>167</size>
+        <size>168</size>
       </method>
       <method name="Void Dispose()" attrs="486">
         <size>15</size>
       </method>
     </type>
   </test>
+  <test name="test-null-operator-04.cs">
+    <type name="C1">
+      <method name="Void Foo[T](IFoo`1[T])" attrs="134">
+        <size>38</size>
+      </method>
+      <method name="Void Foo2[T](IFoo`1[T])" attrs="134">
+        <size>17</size>
+      </method>
+      <method name="Void .ctor()" attrs="6278">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="C2`1[T]">
+      <method name="Void Foo()" attrs="134">
+        <size>33</size>
+      </method>
+      <method name="Void .ctor()" attrs="6278">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="Program">
+      <method name="Void Test[T](System.Func`1[T])" attrs="145">
+        <size>31</size>
+      </method>
+      <method name="Void Test2[T](System.Func`1[T])" attrs="145">
+        <size>17</size>
+      </method>
+      <method name="Void Main()" attrs="145">
+        <size>102</size>
+      </method>
+      <method name="Int32 &lt;Main&gt;m__0()" attrs="145">
+        <size>9</size>
+      </method>
+      <method name="Int32 &lt;Main&gt;m__1()" attrs="145">
+        <size>9</size>
+      </method>
+      <method name="Void .ctor()" attrs="6278">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
   <test name="test-null-operator-05.cs">
     <type name="CI">
       <method name="Void set_Item(System.String, System.String)" attrs="2182">
index d95558b30831328d0943d51f4ca56f88f894aad7..693318cbea7e07fdb27df8413379a15d159e7ac0 100644 (file)
@@ -49,7 +49,7 @@ net_4_5_dirs := \
        mono-symbolicate        \
        linker-analyzer
 
-build_SUBDIRS = gacutil security culevel cil-stringreplacer
+build_SUBDIRS = gacutil security culevel cil-stringreplacer commoncryptogenerator
 net_4_5_SUBDIRS = gacutil
 net_4_5_PARALLEL_SUBDIRS = $(net_4_5_dirs)
 
diff --git a/mcs/tools/commoncryptogenerator/CommonCryptorGenerator.cs b/mcs/tools/commoncryptogenerator/CommonCryptorGenerator.cs
new file mode 100644 (file)
index 0000000..f177c17
--- /dev/null
@@ -0,0 +1,104 @@
+//
+// CommonCrypto code generator for symmetric block cipher algorithms
+//
+// Authors:
+//     Sebastien Pouliot  <sebastien@xamarin.com>
+//
+// Copyright 2012 Xamarin Inc.
+//
+
+using System;
+using System.IO;
+
+namespace Xamarin {
+
+       public static class CommonCryptor {
+               
+               static public void Generate (string namespaceName, string typeName, string baseTypeName, string ccAlgorithmName, string feedbackSize = "8", string ctorInitializers = null)
+               {
+                       string template = @"// Generated file to bind CommonCrypto cipher algorithms - DO NOT EDIT
+//
+// Authors:
+//     Sebastien Pouliot  <sebastien@xamarin.com>
+//
+// Copyright 2012-2014 Xamarin Inc.
+
+using System;
+using System.Security.Cryptography;
+
+using Mono.Security.Cryptography;
+using Crimson.CommonCrypto;
+
+namespace %NAMESPACE% {
+
+       public sealed partial class %TYPE% : %BASE% {
+               
+               public %TYPE% ()
+               {
+                       FeedbackSizeValue = %FEEDBACKSIZE%;
+                       %CTOR_INIT%
+               }
+               
+               public override void GenerateIV ()
+               {
+                       IVValue = KeyBuilder.IV (BlockSizeValue >> 3);
+               }
+               
+               public override void GenerateKey ()
+               {
+                       KeyValue = KeyBuilder.Key (KeySizeValue >> 3);
+               }
+               
+               public override ICryptoTransform CreateDecryptor (byte[] rgbKey, byte[] rgbIV) 
+               {
+                       IntPtr decryptor = IntPtr.Zero;
+                       switch (Mode) {
+                       case CipherMode.CBC:
+                               decryptor = Cryptor.Create (CCOperation.Decrypt, CCAlgorithm.%CCALGORITHM%, CCOptions.None, rgbKey, rgbIV);
+                               return new FastCryptorTransform (decryptor, this, false, rgbIV);
+                       case CipherMode.ECB:
+                               decryptor = Cryptor.Create (CCOperation.Decrypt, CCAlgorithm.%CCALGORITHM%, CCOptions.ECBMode, rgbKey, rgbIV);
+                               return new FastCryptorTransform (decryptor, this, false, rgbIV);
+                       case CipherMode.CFB:
+#if MONOTOUCH || XAMMAC
+                               IntPtr encryptor = Cryptor.Create (CCOperation.Encrypt, CCAlgorithm.%CCALGORITHM%, CCOptions.ECBMode, rgbKey, rgbIV);
+                               decryptor = Cryptor.Create (CCOperation.Decrypt, CCAlgorithm.%CCALGORITHM%, CCOptions.ECBMode, rgbKey, rgbIV);
+                               return new CryptorTransform (decryptor, encryptor, this, false, rgbIV);
+#else
+                               throw new CryptographicException (""CFB is not supported by Crimson.CommonCrypto"");
+#endif
+                       default:
+                               throw new CryptographicException (String.Format (""{0} is not supported by the .NET framework"", Mode));
+                       }
+               }
+               
+               public override ICryptoTransform CreateEncryptor (byte[] rgbKey, byte[] rgbIV) 
+               {
+                       IntPtr encryptor = IntPtr.Zero;
+                       switch (Mode) {
+                       case CipherMode.CBC:
+                               encryptor = Cryptor.Create (CCOperation.Encrypt, CCAlgorithm.%CCALGORITHM%, CCOptions.None, rgbKey, rgbIV);
+                               return new FastCryptorTransform (encryptor, this, true, rgbIV);
+                       case CipherMode.ECB:
+                               encryptor = Cryptor.Create (CCOperation.Encrypt, CCAlgorithm.%CCALGORITHM%, CCOptions.ECBMode, rgbKey, rgbIV);
+                               return new FastCryptorTransform (encryptor, this, true, rgbIV);
+                       case CipherMode.CFB:
+#if MONOTOUCH || XAMMAC
+                               encryptor = Cryptor.Create (CCOperation.Encrypt, CCAlgorithm.%CCALGORITHM%, CCOptions.ECBMode, rgbKey, rgbIV);
+                               return new CryptorTransform (encryptor, IntPtr.Zero, this, true, rgbIV);
+#else
+                               throw new CryptographicException (""CFB is not supported by Crimson.CommonCrypto"");
+#endif
+                       default:
+                               throw new CryptographicException (String.Format (""{0} is not supported by the .NET framework"", Mode));
+                       }
+               }
+       }
+}";
+                       
+                       File.WriteAllText (typeName + ".g.cs", template.Replace ("%NAMESPACE%", namespaceName).
+                               Replace ("%TYPE%", typeName).Replace ("%BASE%", baseTypeName).Replace("%FEEDBACKSIZE%", feedbackSize).Replace ("%CTOR_INIT%", ctorInitializers).
+                               Replace ("%CCALGORITHM%", ccAlgorithmName.ToString ()));
+               }
+       }
+}
diff --git a/mcs/tools/commoncryptogenerator/CommonDigestGenerator.cs b/mcs/tools/commoncryptogenerator/CommonDigestGenerator.cs
new file mode 100644 (file)
index 0000000..1b729e3
--- /dev/null
@@ -0,0 +1,167 @@
+//
+// CommonCrypto code generator for digest algorithms
+//
+// Authors:
+//     Sebastien Pouliot  <sebastien@xamarin.com>
+//
+// Copyright 2012-2014 Xamarin Inc.
+//
+
+using System;
+using System.IO;
+
+namespace Xamarin {
+
+       public static class CommonDigest {
+               
+#if !MONOTOUCH && !XAMMAC
+               // we do not add anything in MonoTouch, just replacing, so this is not needed
+               // however we can avoid a dependency on Mono.Security for Crimson.CommonCrypto.dll by including the base classes
+               static public void GenerateBaseClass (string namespaceName, string typeName, string baseTypeName, int hashSize,
+                       string visibilityStart = "", string visibilityEnd = "")
+               {
+                       string template = @"// Generated file to bind CommonCrypto/CommonDigest - DO NOT EDIT
+//
+// Authors:
+//     Sebastien Pouliot  <sebastien@xamarin.com>
+//
+// Copyright 2012-2014 Xamarin Inc.
+
+using System;
+using System.Security.Cryptography;
+using System.Runtime.InteropServices;
+
+namespace %NAMESPACE% {
+
+%VISIBILITY_START%
+       public
+%VISIBILITY_END%
+       abstract class %BASE% : HashAlgorithm {
+
+               protected %BASE% () 
+               {
+                       HashSizeValue = %HASHSIZE%; 
+               }
+
+               public static new %BASE% Create ()
+               {
+                       return Create (""%BASE%"");
+               }
+
+               public static new %BASE% Create (string hashName)
+               {
+                       object o = CryptoConfig.CreateFromName (hashName);
+                       return (%BASE%) o ?? new %TYPE% ();
+               }
+       }
+}";
+                       
+                       File.WriteAllText (baseTypeName + ".g.cs", template.Replace ("%NAMESPACE%", namespaceName).
+                               Replace ("%TYPE%", typeName).Replace ("%BASE%", baseTypeName).
+                               Replace ("%VISIBILITY_START%", visibilityStart).Replace ("%VISIBILITY_END%", visibilityEnd).
+                               Replace ("%HASHSIZE%", hashSize.ToString ()));
+               }
+#endif
+               static public void Generate (string namespaceName, string typeName, string baseTypeName, int contextSize,
+                       string visibilityStart = "", string visibilityEnd = "")
+               {
+                       string template = @"// Generated file to bind CommonCrypto/CommonDigest - DO NOT EDIT
+//
+// Authors:
+//     Sebastien Pouliot  <sebastien@xamarin.com>
+//
+// Copyright 2011-2014 Xamarin Inc.
+
+using System;
+using System.Security.Cryptography;
+using System.Runtime.InteropServices;
+
+using Mono.Security.Cryptography;
+
+namespace %NAMESPACE% {
+
+%VISIBILITY_START%
+       public
+%VISIBILITY_END%
+       sealed class %TYPE% : %BASE% {
+
+               IntPtr ctx;
+
+               [DllImport (""/usr/lib/libSystem.dylib"", EntryPoint=""CC_%BASE%_Init"")]
+               static extern int Init (/* CC_%BASE%_CTX */ IntPtr c);
+
+               [DllImport (""/usr/lib/libSystem.dylib"", EntryPoint=""CC_%BASE%_Update"")]
+               static extern int Update (/* CC_%BASE%_CTX */ IntPtr c, /* const void * */ IntPtr data, /* uint32_t */ uint len);
+
+               [DllImport (""/usr/lib/libSystem.dylib"", EntryPoint=""CC_%BASE%_Final"")]
+               static extern int Final (/* unsigned char * */ byte [] md, /* CC_%BASE%_CTX */ IntPtr c);
+
+               public %TYPE% ()
+               {
+                       ctx = IntPtr.Zero;
+               }
+
+               ~%TYPE% ()
+               {
+                       Dispose (false);
+               }
+
+               protected override void Dispose (bool disposing)
+               {
+                       if (ctx != IntPtr.Zero) {
+                               Marshal.FreeHGlobal (ctx);
+                               ctx = IntPtr.Zero;
+                       }
+                       base.Dispose (disposing);
+                       GC.SuppressFinalize (this);
+               }
+
+               public override void Initialize ()
+               {
+                       if (ctx == IntPtr.Zero)
+                               ctx = Marshal.AllocHGlobal (%CTX_SIZE%);
+                       
+                       int hr = Init (ctx);
+                       if (hr != 1)
+                               throw new CryptographicException (hr);
+               }
+
+               protected override void HashCore (byte[] data, int start, int length) 
+               {
+                       if (ctx == IntPtr.Zero)
+                               Initialize ();
+
+                       if (data.Length == 0)
+                               return;
+
+                       unsafe {
+                               fixed (byte* p = &data [0]) {
+                                       int hr = Update (ctx, (IntPtr) (p + start), (uint) length);
+                                       if (hr != 1)
+                                               throw new CryptographicException (hr);
+                               }
+                       }
+               }
+
+               protected override byte[] HashFinal () 
+               {
+                       if (ctx == IntPtr.Zero)
+                               Initialize ();
+                       
+                       byte[] data = new byte [HashSize >> 3];
+                       int hr = Final (data, ctx);
+                       if (hr != 1)
+                               throw new CryptographicException (hr);
+
+                       return data;
+               }
+       }
+}";
+                       
+                       File.WriteAllText (typeName + ".g.cs", template.Replace ("%NAMESPACE%", namespaceName).
+                               Replace ("%TYPE%", typeName).Replace ("%BASE%", baseTypeName).
+                               Replace ("%VISIBILITY_START%", visibilityStart).Replace ("%VISIBILITY_END%", visibilityEnd).
+                               Replace ("%CTX_SIZE%", contextSize.ToString ()));
+               }
+       }
+}
diff --git a/mcs/tools/commoncryptogenerator/Makefile b/mcs/tools/commoncryptogenerator/Makefile
new file mode 100644 (file)
index 0000000..64c52e4
--- /dev/null
@@ -0,0 +1,11 @@
+thisdir = tools/commoncryptogenerator
+SUBDIRS =
+include ../../build/rules.make
+
+LIB_REFS = 
+LOCAL_MCS_FLAGS =
+
+PROGRAM = commoncryptogenerator.exe
+NO_INSTALL = yes
+
+include ../../build/executable.make
diff --git a/mcs/tools/commoncryptogenerator/commoncryptogenerator.exe.sources b/mcs/tools/commoncryptogenerator/commoncryptogenerator.exe.sources
new file mode 100644 (file)
index 0000000..e2ecba4
--- /dev/null
@@ -0,0 +1,3 @@
+CommonCryptorGenerator.cs
+generator.cs
+CommonDigestGenerator.cs
diff --git a/mcs/tools/commoncryptogenerator/generator.cs b/mcs/tools/commoncryptogenerator/generator.cs
new file mode 100644 (file)
index 0000000..a7d13c8
--- /dev/null
@@ -0,0 +1,57 @@
+//
+// CommonCrypto Code Generator
+//
+// Authors:
+//     Sebastien Pouliot  <sebastien@xamarin.com>
+//
+// Copyright 2012 Xamarin Inc.
+//
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Text;
+
+namespace Xamarin {
+       
+       class Program {
+               static void Main (string [] args)
+               {
+                       // mscorlib replacements
+                       CommonDigest.Generate ("System.Security.Cryptography", "MD5CryptoServiceProvider", "MD5", 1000);
+                       CommonDigest.Generate ("System.Security.Cryptography", "SHA1CryptoServiceProvider", "SHA1", 1000);
+                       CommonDigest.Generate ("System.Security.Cryptography", "SHA1Managed", "SHA1", 1000);
+                       CommonDigest.Generate ("System.Security.Cryptography", "SHA256Managed", "SHA256", 1000);
+                       CommonDigest.Generate ("System.Security.Cryptography", "SHA384Managed", "SHA384", 1000);
+                       CommonDigest.Generate ("System.Security.Cryptography", "SHA512Managed", "SHA512", 1000);
+                       
+                       // System.Core replacements - not yet in MT profile (4.0 - functional dupes anyway)
+                       //CommonDigest.Generate ("System.Security.Cryptography", "MD5Cng", "MD5", 1000);
+                       //CommonDigest.Generate ("System.Security.Cryptography", "SHA256Cng", "SHA256", 1000);
+                       //CommonDigest.Generate ("System.Security.Cryptography", "SHA384Cng", "SHA384", 1000);
+                       //CommonDigest.Generate ("System.Security.Cryptography", "SHA512Cng", "SHA512", 1000);
+                       //CommonDigest.Generate ("System.Security.Cryptography", "SHA256CryptoServiceProvider", "SHA256", 1000);
+                       //CommonDigest.Generate ("System.Security.Cryptography", "SHA384CryptoServiceProvider", "SHA384", 1000);
+                       //CommonDigest.Generate ("System.Security.Cryptography", "SHA512CryptoServiceProvider", "SHA512", 1000);
+                       
+                       // Mono.Security replacements
+                       CommonDigest.Generate ("Mono.Security.Cryptography", "MD2Managed", "MD2", 1000, "#if !INSIDE_CORLIB", "#endif");
+                       CommonDigest.Generate ("Mono.Security.Cryptography", "MD4Managed", "MD4", 1000, "#if !INSIDE_CORLIB", "#endif");
+                       CommonDigest.Generate ("Mono.Security.Cryptography", "SHA224Managed", "SHA224", 1000);
+
+                       // mscorlib replacements
+                       CommonCryptor.Generate ("System.Security.Cryptography", "DESCryptoServiceProvider", "DES", "DES");
+                       CommonCryptor.Generate ("System.Security.Cryptography", "TripleDESCryptoServiceProvider", "TripleDES", "TripleDES");
+                       CommonCryptor.Generate ("System.Security.Cryptography", "RC2CryptoServiceProvider", "RC2", "RC2", ctorInitializers: "LegalKeySizesValue = new[] { new KeySizes(40, 128, 8) };");
+                       // Rijndael supports block sizes that are not available in AES - as such it does not use the same generated code
+                       // but has it's own version, using AES (128 bits block size) and falling back to managed (192/256 bits block size)
+
+                       // System.Core replacements
+                       CommonCryptor.Generate ("System.Security.Cryptography", "AesManaged", "Aes", "AES128", "128");
+                       CommonCryptor.Generate ("System.Security.Cryptography", "AesCryptoServiceProvider", "Aes", "AES128");
+
+                       // Mono.Security replacements
+                       // RC4 is a stream (not a block) cipher so it can not reuse the generated code
+               }
+       }
+}
\ No newline at end of file
index beafdfa555778472afda9b56e0d11d2fd3d52845..ec7e9dfc25a13881ee7e8ae8e0dec25750fc879e 100644 (file)
@@ -1440,17 +1440,15 @@ namespace TestRunner {
                static bool TryToMatchErrorMessage (string actual, string expected)
                {
                        actual = actual.Replace ("\\", "/");
-                       var path_mask_start = expected.IndexOf ("*PATH*");
+                       var path_mask_start = expected.IndexOf ("*PATH*", StringComparison.Ordinal);
                        if (path_mask_start > 0 && actual.Length > path_mask_start) {
-                               var path_mask_continue = expected.Substring (path_mask_start + 6);
-                               var expected_continue = actual.IndexOf (path_mask_continue, path_mask_start);
-                               if (expected_continue > 0) {
-                                       var path = actual.Substring (path_mask_start, expected_continue - path_mask_start);
-                                       if (actual == expected.Replace ("*PATH*", path))
-                                               return true;
-
-                                       throw new ApplicationException (expected.Replace ("*PATH*", path));
+                               var parts = expected.Split (new [] { "*PATH*" }, StringSplitOptions.None);
+                               foreach (var part in parts) {
+                                       if (!actual.Contains (part))
+                                               return false;
                                }
+
+                               return true;
                        }
 
                        return false;
index 6ac0f241ade40505cf481beed3438df489100aa6..103d817f180c918f639172c7a7afb2ea49f99c23 100644 (file)
@@ -48,7 +48,7 @@
     <Compile Include="AssemblyComparer.cs" />
     <Compile Include="ClassComparer.cs" />
     <Compile Include="ApiDiff.cs" />
-    <Compile Include="..\..\..\class\Mono.Options\Mono.Options\Options.cs">
+    <Compile Include="..\..\class\Mono.Options\Mono.Options\Options.cs">
       <Link>Options.cs</Link>
     </Compile>
     <Compile Include="ApiChange.cs" />
index 0ddfddd944dafad3f3d030cff1695636c6877cc4..01a7ceb97d9d7b328ad92007b57df1ac93bd3b80 100644 (file)
@@ -2,59 +2,62 @@ using System;
 using System.IO;
 using System.Linq;
 using System.Text;
-using IKVM.Reflection;
-using System.Diagnostics;
 using System.Collections.Generic;
-using Mono.CompilerServices.SymbolWriter;
-using System.Runtime.InteropServices;
+using Mono.Cecil;
+using Mono.Cecil.Cil;
+using Mono.Collections.Generic;
 
 namespace Symbolicate
 {
-       struct Location {
-               public string FileName;
-               public int Line;
-       }
-
        class LocationProvider {
                class AssemblyLocationProvider {
-                       Assembly assembly;
-                       MonoSymbolFile symbolFile;
+                       AssemblyDefinition assembly;
                        string seqPointDataPath;
 
-                       public AssemblyLocationProvider (Assembly assembly, MonoSymbolFile symbolFile, string seqPointDataPath)
+                       public AssemblyLocationProvider (AssemblyDefinition assembly, string seqPointDataPath)
                        {
                                this.assembly = assembly;
-                               this.symbolFile = symbolFile;
                                this.seqPointDataPath = seqPointDataPath;
                        }
 
-                       public bool TryGetLocation (string methodStr, string typeFullName, int offset, bool isOffsetIL, uint methodIndex, out Location location)
+                       public SequencePoint TryGetLocation (string typeFullName, string methodSignature, int offset, bool isOffsetIL, uint methodIndex)
                        {
-                               location = default (Location);
-                               if (symbolFile == null)
-                                       return false;
-
-                               var type = assembly.GetTypes().FirstOrDefault (t => t.FullName == typeFullName);
-                               if (type == null)
-                                       return false;
+                               if (!assembly.MainModule.HasSymbols)
+                                       return null;
+
+                               TypeDefinition type = null;
+                               var nested = typeFullName.Split ('+');
+                               var types = assembly.MainModule.Types;
+                               foreach (var ntype in nested) {
+                                       type = types.FirstOrDefault (t => t.Name == ntype);
+                                       if (type == null)
+                                               return null;
+
+                                       types = type.NestedTypes;
+                               }
 
-                               var bindingflags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
-                               var method = type.GetMethods(bindingflags).FirstOrDefault (m => GetMethodFullName (m) == methodStr);
+                               var parensStart = methodSignature.IndexOf ('(');
+                               var methodName = methodSignature.Substring (0, parensStart).TrimEnd ();
+                               var methodParameters = methodSignature.Substring (parensStart);
+                               var method = type.Methods.FirstOrDefault (m => CompareName (m, methodName) && CompareParameters (m.Parameters, methodParameters));
                                if (method == null)
-                                       return false;
+                                       return null;
 
-                               int ilOffset = (isOffsetIL)? offset : GetILOffsetFromFile (method.MetadataToken, methodIndex, offset);
+                               int ilOffset = isOffsetIL ? offset : GetILOffsetFromFile (method.MetadataToken.ToInt32 (), methodIndex, offset);
                                if (ilOffset < 0)
-                                       return false;
-
-                               var methodSymbol = symbolFile.Methods [(method.MetadataToken & 0x00ffffff) - 1];
-
-                               var lineNumbers = methodSymbol.GetLineNumberTable ().LineNumbers;
-                               var lineNumber = lineNumbers.FirstOrDefault (l => l.Offset >= ilOffset) ?? lineNumbers.Last ();
+                                       return null;
+
+                               SequencePoint sp = null;
+                               foreach (var instr in method.Body.Instructions) {
+                                       if (instr.SequencePoint != null)
+                                               sp = instr.SequencePoint;
+                                       
+                                       if (instr.Offset >= ilOffset) {
+                                               return sp;
+                                       }
+                               }
 
-                               location.FileName = symbolFile.Sources [lineNumber.File-1].FileName;
-                               location.Line = lineNumber.Row;
-                               return true;
+                               return null;
                        }
 
                        SeqPointInfo seqPointInfo;
@@ -66,17 +69,88 @@ namespace Symbolicate
                                return seqPointInfo.GetILOffset (methodToken, methodIndex, nativeOffset);
                        }
 
-                       private string GetMethodFullName (MethodBase m)
+                       static bool CompareName (MethodDefinition candidate, string expected)
+                       {
+                               if (candidate.Name == expected)
+                                       return true;
+
+                               if (!candidate.HasGenericParameters)
+                                       return false;
+                               
+                               var genStart = expected.IndexOf ('[');
+                               if (genStart < 0)
+                                       return false;
+
+                               if (candidate.Name != expected.Substring (0, genStart))
+                                       return false;
+
+                               int arity = 1;
+                               for (int pos = genStart; pos < expected.Length; ++pos) {
+                                       if (expected [pos] == ',')
+                                               ++arity;
+                               }
+
+                               return candidate.GenericParameters.Count == arity;
+                       }
+
+                       static bool CompareParameters (Collection<ParameterDefinition> candidate, string expected)
                        {
-                               StringBuilder sb = new StringBuilder ();
+                               var builder = new StringBuilder ();
+                               builder.Append ("(");
+
+                               for (int i = 0; i < candidate.Count; i++) {
+                                       var parameter = candidate [i];
+                                       if (i > 0)
+                                               builder.Append (", ");
+
+                                       if (parameter.ParameterType.IsSentinel)
+                                               builder.Append ("...,");
+
+                                       var pt = parameter.ParameterType;
+                                       if (!string.IsNullOrEmpty (pt.Namespace)) {
+                                               builder.Append (pt.Namespace);
+                                               builder.Append (".");
+                                       }
+
+                                       FormatElementType (pt, builder);
 
-                               StackTraceHelper.GetFullNameForStackTrace (sb, m);
+                                       builder.Append (" ");
+                                       builder.Append (parameter.Name);
+                               }
+
+                               builder.Append (")");
 
-                               return sb.ToString ();
+                               return builder.ToString () == expected;
+                       }
+
+                       static void FormatElementType (TypeReference tr, StringBuilder builder)
+                       {
+                               var ts = tr as TypeSpecification;
+                               if (ts != null) {
+                                       if (ts.IsByReference) {
+                                               FormatElementType (ts.ElementType, builder);
+                                               builder.Append ("&");
+                                               return;
+                                       }
+
+                                       var array = ts as ArrayType;
+                                       if (array != null) {
+                                               FormatElementType (ts.ElementType, builder);
+                                               builder.Append ("[");
+
+                                               for (int ii = 0; ii < array.Rank - 1; ++ii) {
+                                                       builder.Append (",");
+                                               }
+
+                                               builder.Append ("]");
+                                               return;
+                                       }
+                               }
+
+                               builder.Append (tr.Name);
                        }
                }
 
-               static readonly Universe ikvm_reflection = new Universe ();
                Dictionary<string, AssemblyLocationProvider> assemblies;
                HashSet<string> directories;
 
@@ -94,24 +168,19 @@ namespace Symbolicate
                        if (!File.Exists (assemblyPath))
                                throw new ArgumentException ("assemblyPath does not exist: "+ assemblyPath);
 
-                       var assembly = ikvm_reflection.LoadFile (assemblyPath);
-                       MonoSymbolFile symbolFile = null;
-
-                       var symbolPath = assemblyPath + ".mdb";
-                       if (!File.Exists (symbolPath))
-                               Debug.WriteLine (".mdb file was not found for " + assemblyPath);
-                       else
-                               symbolFile = MonoSymbolFile.ReadSymbolFile (symbolPath);
+                       var readerParameters = new ReaderParameters { ReadSymbols = true };
+                       var assembly = AssemblyDefinition.ReadAssembly (assemblyPath, readerParameters);
 
                        var seqPointDataPath = assemblyPath + ".msym";
                        if (!File.Exists (seqPointDataPath))
                                seqPointDataPath = null;
 
-                       assemblies.Add (assemblyPath, new AssemblyLocationProvider (assembly, symbolFile, seqPointDataPath));
+                       assemblies.Add (assemblyPath, new AssemblyLocationProvider (assembly, seqPointDataPath));
 
+                       // TODO: Should use AssemblyName with .net unification rules
                        directories.Add (Path.GetDirectoryName (assemblyPath));
 
-                       foreach (var assemblyRef in assembly.GetReferencedAssemblies ()) {
+                       foreach (var assemblyRef in assembly.MainModule.AssemblyReferences) {
                                string refPath = null;
                                foreach (var dir in directories) {
                                        refPath = Path.Combine (dir, assemblyRef.Name);
@@ -141,15 +210,15 @@ namespace Symbolicate
                        directories.Add (directory);
                }
 
-               public bool TryGetLocation (string method, string typeFullName, int offset, bool isOffsetIL, uint methodIndex, out Location location)
+               public SequencePoint TryGetLocation (string typeFullName, string methodSignature, int offset, bool isOffsetIL, uint methodIndex)
                {
-                       location = default (Location);
                        foreach (var assembly in assemblies.Values) {
-                               if (assembly.TryGetLocation (method, typeFullName, offset, isOffsetIL, methodIndex, out location))
-                                       return true;
+                               var loc = assembly.TryGetLocation (typeFullName, methodSignature, offset, isOffsetIL, methodIndex);
+                               if (loc != null)
+                                       return loc;
                        }
 
-                       return false;
+                       return null;
                }
        }
 }
index 57fee31f46d265e5e05e15a6bbdfd5632ed1afae..3c30921a61e18e2b3d239d3356eefda34260099f 100644 (file)
@@ -7,7 +7,7 @@ PROGRAM = mono-symbolicate.exe
 LOCAL_MCS_FLAGS = \
        /D:NO_AUTHENTICODE
 
-LIB_REFS = Mono.CompilerServices.SymbolWriter System.Xml System.Core System
+LIB_REFS = Mono.Cecil Mono.Cecil.Mdb System.Xml System.Core System
 
 include ../../build/executable.make
 
@@ -45,13 +45,13 @@ AOT_SUPPORTED = $(shell $(MONO) --aot 2>&1 | grep -q "AOT compilation is not sup
 
 test-local: all
        $(BUILD_TEST_EXE)
-       @echo "Checking $(PROGRAM) without AOT"
+       @echo "Checking $(TEST_EXE) without AOT"
        $(CHECK_DIFF)
 ifeq ($(AOT_SUPPORTED), 1)
-       @echo "Checking $(PROGRAM) with AOT"
+       @echo "Checking $(TEST_EXE) with AOT"
        @MONO_DEBUG=gen-compact-seq-points $(MONO) --aot $(TEST_EXE) > /dev/null
        $(CHECK_DIFF)
-       @echo "Checking $(PROGRAM) with AOT (using .msym)"
+       @echo "Checking $(TEST_EXE) with AOT (using .msym)"
        $(BUILD_TEST_EXE)
        @MONO_DEBUG=gen-compact-seq-points $(MONO) --aot=gen-seq-points-file $(TEST_EXE) > /dev/null
        $(CHECK_DIFF)
index 858bf2a9584a302e74674438feece12d801c80d5..5c4437ba56945b09750b3dbe362a8b1441ccd1bc 100644 (file)
@@ -1,10 +1,3 @@
 symbolicate.cs
 LocationProvider.cs
 SeqPointInfo.cs
-../../class/corlib/System.Diagnostics/StackTraceHelper.cs
-../../../external/ikvm/reflect/*.cs
-../../../external/ikvm/reflect/Impl/*.cs
-../../../external/ikvm/reflect/Emit/*.cs
-../../../external/ikvm/reflect/Metadata/*.cs
-../../../external/ikvm/reflect/Reader/*.cs
-../../../external/ikvm/reflect/Writer/*.cs
diff --git a/mcs/tools/mono-symbolicate/monosymbolicate.csproj b/mcs/tools/mono-symbolicate/monosymbolicate.csproj
new file mode 100644 (file)
index 0000000..023e181
--- /dev/null
@@ -0,0 +1,50 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
+  <PropertyGroup>\r
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
+    <Platform Condition=" '$(Platform)' == '' ">x86</Platform>\r
+    <ProjectGuid>{804E854F-E8F5-4E2B-807A-4FAF4BE99C03}</ProjectGuid>\r
+    <OutputType>Exe</OutputType>\r
+    <RootNamespace>monosymbolicate</RootNamespace>\r
+    <AssemblyName>monosymbolicate</AssemblyName>\r
+    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>\r
+    <ProductVersion>8.0.30703</ProductVersion>\r
+    <SchemaVersion>2.0</SchemaVersion>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">\r
+    <DebugSymbols>true</DebugSymbols>\r
+    <DebugType>full</DebugType>\r
+    <Optimize>false</Optimize>\r
+    <OutputPath>bin\Debug</OutputPath>\r
+    <DefineConstants>DEBUG;NO_AUTHENTICODE</DefineConstants>\r
+    <ErrorReport>prompt</ErrorReport>\r
+    <WarningLevel>4</WarningLevel>\r
+    <ExternalConsole>false</ExternalConsole>\r
+    <PlatformTarget>x86</PlatformTarget>\r
+    <Commandlineparameters></Commandlineparameters>\r
+    <ConsolePause>false</ConsolePause>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">\r
+    <Optimize>true</Optimize>\r
+    <OutputPath>bin\Release</OutputPath>\r
+    <ErrorReport>prompt</ErrorReport>\r
+    <WarningLevel>4</WarningLevel>\r
+    <ExternalConsole>true</ExternalConsole>\r
+    <PlatformTarget>x86</PlatformTarget>\r
+  </PropertyGroup>\r
+  <ItemGroup>\r
+    <Reference Include="System" />\r
+    <Reference Include="Mono.Cecil">\r
+      <HintPath>..\..\class\lib\net_4_x\Mono.Cecil.dll</HintPath>\r
+    </Reference>\r
+    <Reference Include="Mono.Cecil.Mdb">\r
+      <HintPath>..\..\class\lib\net_4_x\Mono.Cecil.Mdb.dll</HintPath>\r
+    </Reference>\r
+  </ItemGroup>\r
+  <ItemGroup>\r
+    <Compile Include="LocationProvider.cs" />\r
+    <Compile Include="SeqPointInfo.cs" />\r
+    <Compile Include="symbolicate.cs" />\r
+  </ItemGroup>\r
+  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />\r
+</Project>
\ No newline at end of file
index 4dd23e3d1bd16fea494ae918bcfd269b2532bc09..cb7aa9a46cd38ffc30d16ba877d0c7a10d20f3c7 100644 (file)
@@ -42,9 +42,9 @@ namespace Symbolicate
                        if (!match.Success)
                                return line;
 
-                       string typeFullName;
+                       string typeFullName, methodSignature;
                        var methodStr = match.Groups ["Method"].Value.Trim ();
-                       if (!TryParseMethodType (methodStr, out typeFullName))
+                       if (!ExtractSignatures (methodStr, out typeFullName, out methodSignature))
                                return line;
 
                        var isOffsetIL = !string.IsNullOrEmpty (match.Groups ["IL"].Value);
@@ -55,34 +55,37 @@ namespace Symbolicate
                        if (!string.IsNullOrEmpty (match.Groups ["MethodIndex"].Value))
                                methodIndex = uint.Parse (match.Groups ["MethodIndex"].Value, CultureInfo.InvariantCulture);
 
-                       Location location;
-                       if (!locProvider.TryGetLocation (methodStr, typeFullName, offset, isOffsetIL, methodIndex, out location))
+                       var loc = locProvider.TryGetLocation (typeFullName, methodSignature, offset, isOffsetIL, methodIndex);
+                       if (loc == null)
                                return line;
 
-                       return line.Replace ("<filename unknown>:0", string.Format ("{0}:{1}", location.FileName, location.Line));
+                       return line.Replace ("<filename unknown>:0", string.Format ("{0}:{1}", loc.Document.Url, loc.StartLine));
                }
 
-               static bool TryParseMethodType (string str, out string typeFullName)
+               static bool ExtractSignatures (string str, out string typeFullName, out string methodSignature)
                {
-                       typeFullName = null;
-
-                       var methodNameEnd = str.IndexOf ("(");
-                       if (methodNameEnd == -1)
+                       var methodNameEnd = str.IndexOf ('(');
+                       if (methodNameEnd == -1) {
+                               typeFullName = methodSignature = null;
                                return false;
+                       }
 
-                       // Remove parameters
-                       str = str.Substring (0, methodNameEnd);
-
-                       // Remove generic parameters
-                       str = Regex.Replace (str, @"\[[^\[\]]*\]", "");
-
-                       var typeNameEnd = str.LastIndexOf (".");
-                       if (methodNameEnd == -1 || typeNameEnd == -1)
+                       var typeNameEnd = str.LastIndexOf ('.', methodNameEnd);
+                       if (typeNameEnd == -1) {
+                               typeFullName = methodSignature = null;
                                return false;
+                       }
+
+                       // Adjustment for Type..ctor ()
+                       if (typeNameEnd > 0 && str [typeNameEnd - 1] == '.') {
+                               --typeNameEnd;
+                       }
 
-                       // Remove method name
                        typeFullName = str.Substring (0, typeNameEnd);
+                       // Remove generic parameters
+                       typeFullName = Regex.Replace (typeFullName, @"\[[^\[\]]*\]", "");
 
+                       methodSignature = str.Substring (typeNameEnd + 1);
                        return true;
                }
        }
index fcdf30adbfd92170b52dcd45318abe2f4ec26bed..26d73ce31c49214d27052cc77e2f929f8b436829 100644 (file)
@@ -249,6 +249,21 @@ typedef union {
                x86_reg_emit ((inst), (dreg), (reg));   \
        } while (0)
 
+#define amd64_test_reg_imm_size_body(inst,reg,imm,size) \
+       do { \
+               amd64_codegen_pre(inst); \
+               amd64_emit_rex ((inst),(size),0,0,(reg)); \
+               if ((reg) == AMD64_RAX) { \
+                       *(inst)++ = (unsigned char)0xa9; \
+               } \
+               else { \
+                       *(inst)++ = (unsigned char)0xf7;        \
+                       x86_reg_emit((inst), 0, (reg)); \
+               } \
+               x86_imm_emit32((inst), (imm));  \
+               amd64_codegen_post(inst); \
+       } while (0)
+
 #if defined(__default_codegen__)
 
 #define amd64_alu_reg_imm_size(inst,opc,reg,imm,size) \
@@ -257,6 +272,9 @@ typedef union {
 #define amd64_alu_reg_reg_size(inst,opc,dreg,reg,size) \
                amd64_alu_reg_reg_size_body((inst), (opc), (dreg), (reg), (size))
 
+#define amd64_test_reg_imm_size(inst, reg, imm, size) \
+               amd64_test_reg_imm_size_body(inst, reg, imm, size)
+
 #elif defined(__native_client_codegen__)
 /* NaCl modules may not directly update RSP or RBP other than direct copies */
 /* between them. Instead the lower 4 bytes are updated and then added to R15 */
@@ -298,6 +316,8 @@ typedef union {
 
 #define amd64_alu_reg_reg(inst,opc,dreg,reg) amd64_alu_reg_reg_size ((inst),(opc),(dreg),(reg),8)
 
+#define amd64_test_reg_imm(inst,reg,imm) amd64_test_reg_imm_size(inst,reg,imm,8)
+
 #define amd64_alu_reg_membase_size(inst,opc,reg,basereg,disp,size) \
        do { \
                amd64_codegen_pre(inst);                                                  \
@@ -1465,7 +1485,7 @@ typedef union {
 #define amd64_alu_reg8_reg8_size(inst,opc,dreg,reg,is_dreg_h,is_reg_h,size) do { amd64_codegen_pre(inst); amd64_emit_rex ((inst),(size),(dreg),0,(reg)); x86_alu_reg8_reg8((inst),(opc),((dreg)&0x7),((reg)&0x7),(is_dreg_h),(is_reg_h)); amd64_codegen_post(inst); } while (0)
 #define amd64_alu_reg_mem_size(inst,opc,reg,mem,size) do { amd64_codegen_pre(inst); amd64_emit_rex ((inst),(size),0,0,(reg)); x86_alu_reg_mem((inst),(opc),((reg)&0x7),(mem)); amd64_codegen_post(inst); } while (0)
 //#define amd64_alu_reg_membase_size(inst,opc,reg,basereg,disp,size) do { amd64_codegen_pre(inst); amd64_emit_rex ((inst),(size),(reg),0,(basereg)); x86_alu_reg_membase((inst),(opc),((reg)&0x7),((basereg)&0x7),(disp)); amd64_codegen_post(inst); } while (0)
-#define amd64_test_reg_imm_size(inst,reg,imm,size) do { amd64_codegen_pre(inst); amd64_emit_rex ((inst),(size),0,0,(reg)); x86_test_reg_imm((inst),((reg)&0x7),(imm)); amd64_codegen_post(inst); } while (0)
+//#define amd64_test_reg_imm_size(inst,reg,imm,size) do { amd64_codegen_pre(inst); amd64_emit_rex ((inst),(size),0,0,(reg)); x86_test_reg_imm((inst),((reg)&0x7),(imm)); amd64_codegen_post(inst); } while (0)
 #define amd64_test_mem_imm_size(inst,mem,imm,size) do { amd64_codegen_pre(inst); amd64_emit_rex ((inst),(size),0,0,0); x86_test_mem_imm((inst),(mem),(imm)); amd64_codegen_post(inst); } while (0)
 #define amd64_test_membase_imm_size(inst,basereg,disp,imm,size) do { amd64_codegen_pre(inst); amd64_emit_rex ((inst),(size),0,0,(basereg)); x86_test_membase_imm((inst),((basereg)&0x7),(disp),(imm)); amd64_codegen_post(inst); } while (0)
 #define amd64_test_reg_reg_size(inst,dreg,reg,size) do { amd64_codegen_pre(inst); amd64_emit_rex ((inst),(size),(dreg),0,(reg)); x86_test_reg_reg((inst),((dreg)&0x7),((reg)&0x7)); amd64_codegen_post(inst); } while (0)
@@ -1710,7 +1730,7 @@ typedef union {
 #define amd64_alu_reg8_reg8(inst,opc,dreg,reg,is_dreg_h,is_reg_h) amd64_alu_reg8_reg8_size(inst,opc,dreg,reg,is_dreg_h,is_reg_h,8)
 #define amd64_alu_reg_mem(inst,opc,reg,mem) amd64_alu_reg_mem_size(inst,opc,reg,mem,8)
 #define amd64_alu_reg_membase(inst,opc,reg,basereg,disp) amd64_alu_reg_membase_size(inst,opc,reg,basereg,disp,8)
-#define amd64_test_reg_imm(inst,reg,imm) amd64_test_reg_imm_size(inst,reg,imm,8)
+//#define amd64_test_reg_imm(inst,reg,imm) amd64_test_reg_imm_size(inst,reg,imm,8)
 #define amd64_test_mem_imm(inst,mem,imm) amd64_test_mem_imm_size(inst,mem,imm,8)
 #define amd64_test_membase_imm(inst,basereg,disp,imm) amd64_test_membase_imm_size(inst,basereg,disp,imm,8)
 #define amd64_test_reg_reg(inst,dreg,reg) amd64_test_reg_reg_size(inst,dreg,reg,8)
index 11b5f8f2fbbe28fe37584da260d8c405f8b7953a..24ec5baffb37370c346d81591ceaae514aac1845 100644 (file)
@@ -990,7 +990,14 @@ static gboolean file_setfiletime(gpointer handle,
                        SetLastError (ERROR_INVALID_PARAMETER);
                        return(FALSE);
                }
-               
+
+               if (sizeof (utbuf.actime) == 4 && ((access_ticks - 116444736000000000ULL) / 10000000) > INT_MAX) {
+                       MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: attempt to set write time that is too big for a 32bits time_t",
+                                  __func__);
+                       SetLastError (ERROR_INVALID_PARAMETER);
+                       return(FALSE);
+               }
+
                utbuf.actime=(access_ticks - 116444736000000000ULL) / 10000000;
        } else {
                utbuf.actime=statbuf.st_atime;
@@ -1008,6 +1015,12 @@ static gboolean file_setfiletime(gpointer handle,
                        SetLastError (ERROR_INVALID_PARAMETER);
                        return(FALSE);
                }
+               if (sizeof (utbuf.modtime) == 4 && ((write_ticks - 116444736000000000ULL) / 10000000) > INT_MAX) {
+                       MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: attempt to set write time that is too big for a 32bits time_t",
+                                  __func__);
+                       SetLastError (ERROR_INVALID_PARAMETER);
+                       return(FALSE);
+               }
                
                utbuf.modtime=(write_ticks - 116444736000000000ULL) / 10000000;
        } else {
index 7e46c31ba3e1564a9323022f9a0e3542b5f71fca..0157e92f5be08fc6b56f0590393d9f0030d5917f 100644 (file)
@@ -1287,7 +1287,8 @@ GetExitCodeProcess (gpointer process, guint32 *code)
                        *code = STILL_ACTIVE;
                        return TRUE;
                } else {
-                       return FALSE;
+                       *code = -1;
+                       return TRUE;
                }
        }
 
index 71bfc07952fd368df01fbf19665f8e22a7fa0121..effa46abdd1d93de67209e08d95a85a33301d450 100644 (file)
@@ -81,7 +81,7 @@
  * Changes which are already detected at runtime, like the addition
  * of icalls, do not require an increment.
  */
-#define MONO_CORLIB_VERSION 143
+#define MONO_CORLIB_VERSION 146
 
 typedef struct
 {
@@ -320,7 +320,7 @@ mono_get_corlib_version (void)
        if (! (field->type->attrs & FIELD_ATTRIBUTE_STATIC))
                return -1;
        value = mono_field_get_value_object_checked (mono_domain_get (), field, NULL, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
+       mono_error_assert_ok (&error);
        return *(gint32*)((gchar*)value + sizeof (MonoObject));
 }
 
@@ -435,13 +435,18 @@ mono_domain_create_appdomain (char *friendly_name, char *configuration_file)
 
        klass = mono_class_load_from_name (mono_defaults.corlib, "System", "AppDomainSetup");
        setup = (MonoAppDomainSetup *) mono_object_new_checked (mono_domain_get (), klass, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
+       if (!is_ok (&error))
+               goto fail;
        setup->configuration_file = configuration_file != NULL ? mono_string_new (mono_domain_get (), configuration_file) : NULL;
 
        ad = mono_domain_create_appdomain_internal (friendly_name, setup, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
+       if (!is_ok (&error))
+               goto fail;
 
        return mono_domain_from_appdomain (ad);
+fail:
+       mono_error_cleanup (&error);
+       return NULL;
 }
 
 /**
@@ -938,23 +943,20 @@ mono_domain_set_options_from_config (MonoDomain *domain)
 MonoAppDomain *
 ves_icall_System_AppDomain_createDomain (MonoString *friendly_name, MonoAppDomainSetup *setup)
 {
+       MonoError error;
+       MonoAppDomain *ad = NULL;
 #ifdef DISABLE_APPDOMAINS
-       mono_set_pending_exception (mono_get_exception_not_supported ("AppDomain creation is not supported on this runtime."));
-       return NULL;
+       mono_error_set_not_supported (&error, "AppDomain creation is not supported on this runtime.");
 #else
-       MonoError error;
        char *fname;
-       MonoAppDomain *ad;
 
        fname = mono_string_to_utf8 (friendly_name);
        ad = mono_domain_create_appdomain_internal (fname, setup, &error);
 
        g_free (fname);
-
-       mono_error_raise_exception (&error);
-
-       return ad;
 #endif
+       mono_error_set_pending_exception (&error);
+       return ad;
 }
 
 MonoArray *
@@ -987,7 +989,9 @@ ves_icall_System_AppDomain_GetAssemblies (MonoAppDomain *ad, MonoBoolean refonly
        }
        mono_domain_assemblies_unlock (domain);
 
-       res = mono_array_new (domain, mono_class_get_assembly_class (), assemblies->len);
+       res = mono_array_new_checked (domain, mono_class_get_assembly_class (), assemblies->len, &error);
+       if (!is_ok (&error))
+               goto leave;
        for (i = 0; i < assemblies->len; ++i) {
                ass = (MonoAssembly *)g_ptr_array_index (assemblies, i);
                MonoReflectionAssembly *ass_obj = mono_assembly_get_object_checked (domain, ass, &error);
@@ -1057,18 +1061,13 @@ mono_domain_assembly_postload_search (MonoAssemblyName *aname, MonoAssembly *req
 
        /* FIXME: We invoke managed code here, so there is a potential for deadlocks */
        str = mono_string_new (domain, aname_str);
+       g_free (aname_str);
        if (!str) {
-               g_free (aname_str);
                return NULL;
        }
 
        assembly = mono_try_assembly_resolve (domain, str, requesting, refonly, &error);
-       if (!mono_error_ok (&error)) {
-               g_free (aname_str);
-               mono_error_raise_exception (&error); /* FIXME don't raise here */
-       }
-
-       g_free (aname_str);
+       mono_error_cleanup (&error);
 
        if (assembly)
                return assembly->assembly;
@@ -1163,7 +1162,7 @@ mono_domain_fire_assembly_load (MonoAssembly *assembly, gpointer user_data)
        *params = ref_assembly;
 
        mono_runtime_invoke_checked (assembly_load_method, domain->domain, params, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
+       mono_error_cleanup (&error);
 }
 
 /*
@@ -2209,8 +2208,10 @@ ves_icall_System_AppDomain_ExecuteAssembly (MonoAppDomain *ad,
        if (!method)
                g_error ("No entry point method found in %s due to %s", image->name, mono_error_get_message (&error));
 
-       if (!args)
-               args = (MonoArray *) mono_array_new (ad->data, mono_defaults.string_class, 0);
+       if (!args) {
+               args = (MonoArray *) mono_array_new_checked (ad->data, mono_defaults.string_class, 0, &error);
+               mono_error_assert_ok (&error);
+       }
 
        return mono_runtime_exec_main (method, (MonoArray *)args, NULL);
 }
@@ -2309,7 +2310,7 @@ ves_icall_System_AppDomain_InternalGetProcessGuid (MonoString* newguid)
                MonoError error;
                MonoString *res = NULL;
                res = mono_string_new_utf16_checked (mono_domain_get (), process_guid, sizeof(process_guid)/2, &error);
-               mono_error_raise_exception (&error);
+               mono_error_set_pending_exception (&error);
                return res;
        }
        memcpy (process_guid, mono_string_chars(newguid), sizeof(process_guid));
@@ -2430,9 +2431,17 @@ unload_thread_main (void *arg)
        /* Have to attach to the runtime so shutdown can wait for this thread */
        /* Force it to be attached to avoid racing during shutdown. */
        thread = mono_thread_attach_full (mono_get_root_domain (), TRUE, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
+       if (!is_ok (&error)) {
+               data->failure_reason = g_strdup (mono_error_get_message (&error));
+               mono_error_cleanup (&error);
+               goto failure;
+       }
        mono_thread_set_name_internal (thread->internal_thread, mono_string_new (mono_get_root_domain (), "Domain unloader"), TRUE, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
+       if (!is_ok (&error)) {
+               data->failure_reason = g_strdup (mono_error_get_message (&error));
+               mono_error_cleanup (&error);
+               goto failure;
+       }
 
        /* 
         * FIXME: Abort our parent thread last, so we can return a failure 
index 9bc8b09e27056ca7c5aeb23a0dc1453cb15c3db0..7f2b5fdb6a62e11741c63c09f4ba5098835219de 100644 (file)
@@ -1636,7 +1636,14 @@ mono_assembly_open_full (const char *filename, MonoImageOpenStatus *status, gboo
        if (!mono_assembly_is_in_gac (fname)) {
                MonoError error;
                new_fname = mono_make_shadow_copy (fname, &error);
-               mono_error_raise_exception (&error); /* FIXME don't raise here */
+               if (!is_ok (&error)) {
+                       mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY,
+                                   "Assembly Loader shadow copy error: %s.", mono_error_get_message (&error));
+                       mono_error_cleanup (&error);
+                       *status = MONO_IMAGE_IMAGE_INVALID;
+                       g_free (fname);
+                       return NULL;
+               }
        }
        if (new_fname && new_fname != fname) {
                g_free (fname);
@@ -2597,10 +2604,12 @@ mono_assembly_load_with_partial_name (const char *name, MonoImageOpenStatus *sta
                MonoReflectionAssembly *refasm;
 
                refasm = mono_try_assembly_resolve (domain, mono_string_new (domain, name), NULL, FALSE, &error);
-               if (!mono_error_ok (&error)) {
+               if (!is_ok (&error)) {
                        g_free (fullname);
                        mono_assembly_name_free (aname);
-                       mono_error_raise_exception (&error); /* FIXME don't raise here */
+                       mono_error_cleanup (&error);
+                       if (*status == MONO_IMAGE_OK)
+                               *status = MONO_IMAGE_IMAGE_INVALID;
                }
 
                if (refasm)
index 6b65259b962b437f20e121671fb189b8486219c3..5e1605fd972295a21362b31a4be27f3d4f7d61a7 100644 (file)
@@ -302,18 +302,30 @@ mono_attach_load_agent (MonoDomain *domain, char *agent, char *args, MonoObject
                return 1;
        }
        
+       
+       main_args = (MonoArray*)mono_array_new_checked (domain, mono_defaults.string_class, (args == NULL) ? 0 : 1, &error);
+       if (main_args == NULL) {
+               g_print ("Could not allocate main method args due to %s\n", mono_error_get_message (&error));
+               mono_error_cleanup (&error);
+               g_free (agent);
+               return 1;
+       }
+
        if (args) {
-               main_args = (MonoArray*)mono_array_new (domain, mono_defaults.string_class, 1);
                mono_array_set (main_args, MonoString*, 0, mono_string_new (domain, args));
-       } else {
-               main_args = (MonoArray*)mono_array_new (domain, mono_defaults.string_class, 0);
        }
 
-       g_free (agent);
 
        pa [0] = main_args;
        mono_runtime_try_invoke (method, NULL, pa, exc, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
+       if (!is_ok (&error)) {
+               g_print ("The entry point method of assembly '%s' could not be executed due to %s\n", agent, mono_error_get_message (&error));
+               mono_error_cleanup (&error);
+               g_free (agent);
+               return 1;
+       }
+
+       g_free (agent);
 
        return 0;
 }
index bff89986c37acd3fa26b618a7b9768f6310950f9..1e7404d4e0ca4f35fa84f5ce47c475a9b3694ef0 100644 (file)
@@ -1005,7 +1005,7 @@ gpointer
 mono_lookup_dynamic_token_class (MonoImage *image, guint32 token, gboolean check_token, MonoClass **handle_class, MonoGenericContext *context, MonoError *error);
 
 gpointer
-mono_runtime_create_jump_trampoline (MonoDomain *domain, MonoMethod *method, gboolean add_sync_wrapper);
+mono_runtime_create_jump_trampoline (MonoDomain *domain, MonoMethod *method, gboolean add_sync_wrapper, MonoError *error);
 
 gpointer
 mono_runtime_create_delegate_trampoline (MonoClass *klass);
index 355d09916f80dd226ad46e488f59c7a1d8e956ef..91d31b60cc5eece43d13deef99d9933319b734b9 100644 (file)
@@ -1130,11 +1130,11 @@ mono_class_inflate_generic_method_full_checked (MonoMethod *method, MonoClass *k
        result->sre_method = FALSE;
        result->signature = NULL;
 
-       if (!context->method_inst) {
+       if (iresult->context.method_inst) {
                /* Set the generic_container of the result to the generic_container of method */
                MonoGenericContainer *generic_container = mono_method_get_generic_container (method);
 
-               if (generic_container) {
+               if (generic_container && iresult->context.method_inst == generic_container->context.method_inst) {
                        result->is_generic = 1;
                        mono_method_set_generic_container (result, generic_container);
                }
@@ -10017,6 +10017,8 @@ is_nesting_type (MonoClass *outer_klass, MonoClass *inner_klass)
        return FALSE;
 }
 
+static gboolean debug_check;
+
 MonoClass *
 mono_class_get_generic_type_definition (MonoClass *klass)
 {
@@ -10160,6 +10162,9 @@ can_access_type (MonoClass *access_klass, MonoClass *member_klass)
 {
        int access_level;
 
+       if (access_klass == member_klass)
+               return TRUE;
+
        if (access_klass->image->assembly && access_klass->image->assembly->corlib_internal)
                return TRUE;
 
@@ -10308,26 +10313,15 @@ mono_method_can_access_field (MonoMethod *method, MonoClassField *field)
 gboolean
 mono_method_can_access_method (MonoMethod *method, MonoMethod *called)
 {
-       int can = can_access_member (method->klass, called->klass, NULL, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
-       if (!can) {
-               MonoClass *nested = method->klass->nested_in;
-               while (nested) {
-                       can = can_access_member (nested, called->klass, NULL, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
-                       if (can)
-                               return TRUE;
-                       nested = nested->nested_in;
-               }
+       gboolean res = mono_method_can_access_method_full (method, called, NULL);
+       if (!res) {
+               printf ("FAILED TO VERIFY %s calling %s\n", mono_method_full_name (method, 1), mono_method_full_name (called, 1));
+               debug_check = TRUE;
+               mono_method_can_access_method_full (method, called, NULL);
+               debug_check = FALSE;
        }
-       /* 
-        * FIXME:
-        * with generics calls to explicit interface implementations can be expressed
-        * directly: the method is private, but we must allow it. This may be opening
-        * a hole or the generics code should handle this differently.
-        * Maybe just ensure the interface type is public.
-        */
-       if ((called->flags & METHOD_ATTRIBUTE_VIRTUAL) && (called->flags & METHOD_ATTRIBUTE_FINAL))
-               return TRUE;
-       return can;
+
+       return res;
 }
 
 /*
@@ -10344,10 +10338,12 @@ mono_method_can_access_method (MonoMethod *method, MonoMethod *called)
 gboolean
 mono_method_can_access_method_full (MonoMethod *method, MonoMethod *called, MonoClass *context_klass)
 {
+       if (debug_check) printf ("CHECKING %s -> %s (%p)\n", mono_method_full_name (method, 1), mono_method_full_name (called, 1), context_klass);
        MonoClass *access_class = method->klass;
        MonoClass *member_class = called->klass;
        int can = can_access_member (access_class, member_class, context_klass, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
        if (!can) {
+               if (debug_check) printf ("\tcan_access_member failed\n");
                MonoClass *nested = access_class->nested_in;
                while (nested) {
                        can = can_access_member (nested, member_class, context_klass, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
@@ -10355,13 +10351,18 @@ mono_method_can_access_method_full (MonoMethod *method, MonoMethod *called, Mono
                                break;
                        nested = nested->nested_in;
                }
+               if (!can && debug_check) printf ("\tcan_access_member nest check failed\n");
        }
 
        if (!can)
                return FALSE;
 
+       if (debug_check) printf ("\ttype checking %s(%p) -> %s(%p)\n", 
+               mono_type_get_full_name (access_class), access_class,
+               mono_type_get_full_name (member_class), member_class);
        can = can_access_type (access_class, member_class);
        if (!can) {
+               if (debug_check) printf ("\tcan_access_type check failed\n");
                MonoClass *nested = access_class->nested_in;
                while (nested) {
                        can = can_access_type (nested, member_class);
@@ -10369,6 +10370,7 @@ mono_method_can_access_method_full (MonoMethod *method, MonoMethod *called, Mono
                                break;
                        nested = nested->nested_in;
                }
+               if (!can && debug_check) printf ("\tcan_access_type nest check failed\n");
        }
 
        if (!can)
@@ -10376,8 +10378,10 @@ mono_method_can_access_method_full (MonoMethod *method, MonoMethod *called, Mono
 
        if (called->is_inflated) {
                MonoMethodInflated * infl = (MonoMethodInflated*)called;
-               if (infl->context.method_inst && !can_access_instantiation (access_class, infl->context.method_inst))
+               if (infl->context.method_inst && !can_access_instantiation (access_class, infl->context.method_inst)) {
+                       if (debug_check) printf ("\tginst check failed\n");
                        return FALSE;
+               }
        }
                
        return TRUE;
index 5c46a85a9419339be30cb6df72122ac618d40ecc..29ce37fc141bc4b8a92049e55590f10c7eef16b4 100644 (file)
@@ -445,6 +445,8 @@ set_control_chars (MonoArray *control_chars, const guchar *cc)
 MonoBoolean
 ves_icall_System_ConsoleDriver_TtySetup (MonoString *keypad, MonoString *teardown, MonoArray **control_chars, int **size)
 {
+       MonoError error;
+
        int dims;
 
        dims = terminal_get_dimensions ();
@@ -470,7 +472,10 @@ ves_icall_System_ConsoleDriver_TtySetup (MonoString *keypad, MonoString *teardow
 
        /* 17 is the number of entries set in set_control_chars() above.
         * NCCS is the total size, but, by now, we only care about those 17 values*/
-       mono_gc_wbarrier_generic_store (control_chars, (MonoObject*) mono_array_new (mono_domain_get (), mono_defaults.byte_class, 17));
+       MonoArray *control_chars_arr = mono_array_new_checked (mono_domain_get (), mono_defaults.byte_class, 17, &error);
+       if (mono_error_set_pending_exception (&error))
+               return FALSE;
+       mono_gc_wbarrier_generic_store (control_chars, (MonoObject*) control_chars_arr);
        if (tcgetattr (STDIN_FILENO, &initial_attr) == -1)
                return FALSE;
 
index da3b6930aafef0036aee4ecf3e6091fbc60dc6ca..fa2514b9814b088d8748494a51fda80edc8c2df3 100644 (file)
@@ -783,7 +783,7 @@ mono_init_internal (const char *filename, const char *exe_filename, const char *
 
        mono_assembly_load_friends (ass);
 
-       mono_defaults.handleref_class = mono_class_load_from_name (
+       mono_defaults.handleref_class = mono_class_try_load_from_name (
                mono_defaults.corlib, "System.Runtime.InteropServices", "HandleRef");
 
        mono_defaults.attribute_class = mono_class_load_from_name (
@@ -1169,12 +1169,6 @@ mono_domain_free (MonoDomain *domain, gboolean force)
        g_slist_free (domain->domain_assemblies);
        domain->domain_assemblies = NULL;
 
-       /* 
-        * Send this after the assemblies have been unloaded and the domain is still in a 
-        * usable state.
-        */
-       mono_profiler_appdomain_event (domain, MONO_PROFILE_END_UNLOAD);
-
        if (free_domain_hook)
                free_domain_hook (domain);
 
index a713e4e39f8e262080bcdaf0edfde8de0e6ada42..c10b1fee8d934b8249c8ca70b32497e0c5a174dc 100644 (file)
@@ -394,31 +394,38 @@ MonoArray *
 ves_icall_System_IO_MonoIO_GetFileSystemEntries (MonoString *path,
                                                 MonoString *path_with_pattern,
                                                 gint attrs, gint mask,
-                                                gint32 *error)
+                                                gint32 *ioerror)
 {
+       MonoError error;
        MonoDomain *domain = mono_domain_get ();
        MonoArray *result;
        int i;
        GPtrArray *names;
        
-       *error = ERROR_SUCCESS;
+       *ioerror = ERROR_SUCCESS;
 
        MONO_PREPARE_BLOCKING;
-       names = get_filesystem_entries (mono_string_chars (path), mono_string_chars (path_with_pattern), attrs, mask, error);
+       names = get_filesystem_entries (mono_string_chars (path), mono_string_chars (path_with_pattern), attrs, mask, ioerror);
        MONO_FINISH_BLOCKING;
 
        if (!names) {
                // If there's no array and no error, then return an empty array.
-               if (*error == ERROR_SUCCESS)
-                       return mono_array_new (domain, mono_defaults.string_class, 0);
+               if (*ioerror == ERROR_SUCCESS) {
+                       MonoArray *arr = mono_array_new_checked (domain, mono_defaults.string_class, 0, &error);
+                       mono_error_set_pending_exception (&error);
+                       return arr;
+               }
                return NULL;
        }
 
-       result = mono_array_new (domain, mono_defaults.string_class, names->len);
+       result = mono_array_new_checked (domain, mono_defaults.string_class, names->len, &error);
+       if (mono_error_set_pending_exception (&error))
+               goto leave;
        for (i = 0; i < names->len; i++) {
                mono_array_setref (result, i, mono_string_new (domain, (const char *)g_ptr_array_index (names, i)));
                g_free (g_ptr_array_index (names, i));
        }
+leave:
        g_ptr_array_free (names, TRUE);
        return result;
 }
@@ -1168,13 +1175,16 @@ invalid_path_chars [] = {
 MonoArray *
 ves_icall_System_IO_MonoIO_get_InvalidPathChars ()
 {
+       MonoError error;
        MonoArray *chars;
        MonoDomain *domain;
        int i, n;
 
        domain = mono_domain_get ();
        n = sizeof (invalid_path_chars) / sizeof (gunichar2);
-       chars = mono_array_new (domain, mono_defaults.char_class, n);
+       chars = mono_array_new_checked (domain, mono_defaults.char_class, n, &error);
+       if (mono_error_set_pending_exception (&error))
+               return NULL;
 
        for (i = 0; i < n; ++ i)
                mono_array_set (chars, gunichar2, i, invalid_path_chars [i]);
index bf02f2892b2e8ff3f8c0f544e2c3a08cf4dfa2b5..3871ee4b0c102ae1081e37bc15e33682915cf21a 100644 (file)
@@ -453,6 +453,8 @@ mono_domain_finalize (MonoDomain *domain, guint32 timeout)
                mono_gc_finalize_threadpool_threads ();
        }
 
+       mono_profiler_appdomain_event (domain, MONO_PROFILE_END_UNLOAD);
+
        return TRUE;
 }
 
index 6a5dc193331b7e1ee3c8a3fe641a474f6b76e52d..9c345a269cde4a0e5a36d7b234a9450695c4a004 100644 (file)
@@ -104,7 +104,7 @@ ICALL(ARGI_4, "Setup",                            mono_ArgIterator_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)
@@ -224,7 +224,7 @@ ICALL(ENUM_7, "get_value", ves_icall_System_Enum_get_value)
 
 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 )
@@ -502,9 +502,6 @@ ICALL(ASSEMB_2, "basic_init", mono_image_basic_init)
 #ifndef DISABLE_REFLECTION_EMIT
 ICALL_TYPE(CATTRB, "System.Reflection.Emit.CustomAttributeBuilder", CATTRB_1)
 ICALL(CATTRB_1, "GetBlob", ves_icall_System_Reflection_Emit_CustomAttributeBuilder_GetBlob)
-
-ICALL_TYPE(DERIVEDTYPE, "System.Reflection.Emit.DerivedType", DERIVEDTYPE_1)
-ICALL(DERIVEDTYPE_1, "create_unmanaged_type", mono_reflection_create_unmanaged_type)
 #endif
 
 ICALL_TYPE(DYNM, "System.Reflection.Emit.DynamicMethod", DYNM_1)
@@ -535,6 +532,11 @@ ICALL_TYPE(SIGH, "System.Reflection.Emit.SignatureHelper", SIGH_1)
 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", ves_icall_System_Reflection_Emit_TypeBuilder_create_generic_class)
 ICALL(TYPEB_2, "create_internal_class", mono_reflection_create_internal_class)
@@ -576,6 +578,7 @@ ICALL(MODULE_13, "get_MetadataToken", ves_icall_reflection_get_token)
 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)
index c342e592a4c21c6df409727bfff139047d0e0499..507e18becc97c3c90e66863ca7eec16026a96f1e 100644 (file)
@@ -713,6 +713,15 @@ ves_icall_System_Array_ClearInternal (MonoArray *arr, int idx, int length)
        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)
 {
@@ -1051,7 +1060,10 @@ ves_icall_System_ValueType_InternalGetHashCode (MonoObject *this_obj, MonoArray
 
        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 {
@@ -1170,7 +1182,10 @@ ves_icall_System_ValueType_Equals (MonoObject *this_obj, MonoObject *that, MonoA
 
        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;
@@ -2303,7 +2318,10 @@ ves_icall_MonoEventInfo_get_event_info (MonoReflectionMonoEvent *event, MonoEven
                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);
@@ -2409,12 +2427,17 @@ ves_icall_Type_GetInterfaces (MonoReflectionType* type)
        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;
@@ -2456,8 +2479,14 @@ ves_icall_Type_GetInterfaceMapData (MonoReflectionType *type, MonoReflectionType
 
        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);
@@ -2685,11 +2714,9 @@ ves_icall_RuntimeTypeHandle_GetArrayRank (MonoReflectionType *type)
 }
 
 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*
@@ -2706,7 +2733,9 @@ ves_icall_MonoType_GetGenericArguments (MonoReflectionType *type, MonoBoolean ru
 
        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));
 
@@ -2718,7 +2747,9 @@ ves_icall_MonoType_GetGenericArguments (MonoReflectionType *type, MonoBoolean ru
                }
        } 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);
                        if (mono_error_set_pending_exception (&error))
@@ -2875,7 +2906,9 @@ ves_icall_Type_GetGenericParameterConstraints (MonoReflectionType *type)
        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);
                if (mono_error_set_pending_exception (&error))
@@ -3100,7 +3133,9 @@ ves_icall_MonoMethod_GetGenericArguments (MonoReflectionMethod *method)
 
                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);
@@ -3115,7 +3150,9 @@ ves_icall_MonoMethod_GetGenericArguments (MonoReflectionMethod *method)
        }
 
        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);
@@ -3307,18 +3344,20 @@ ves_icall_InternalExecute (MonoReflectionMethod *method, MonoObject *this_arg, 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_checked (domain, field_klass, (char *)this_arg + field->offset, &error);
-                                               mono_error_set_pending_exception (&error);
-                                               /* fallthru to cleanup */
+                                               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;
@@ -3348,6 +3387,7 @@ ves_icall_InternalExecute (MonoReflectionMethod *method, MonoObject *this_arg, 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);
                                        MonoObject *val = (MonoObject *)mono_array_get (params, gpointer, 2);
 
@@ -3359,10 +3399,11 @@ ves_icall_InternalExecute (MonoReflectionMethod *method, MonoObject *this_arg, M
                                                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;
                                }
                                
@@ -3380,8 +3421,10 @@ ves_icall_InternalExecute (MonoReflectionMethod *method, MonoObject *this_arg, M
                        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);
@@ -3668,8 +3711,12 @@ ves_icall_System_Enum_GetEnumValuesAndNames (MonoReflectionType *type, MonoArray
        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))) {
@@ -3735,8 +3782,11 @@ ves_icall_Type_GetFields_internal (MonoReflectionType *type, MonoString *name, g
        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);
@@ -3797,7 +3847,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));
@@ -4014,7 +4066,7 @@ ves_icall_Type_GetConstructors_internal (MonoReflectionType *type, guint32 bflag
 {
        MonoDomain *domain; 
        MonoClass *startklass, *klass, *refklass;
-       MonoArray *res;
+       MonoArray *res = NULL;
        MonoMethod *method;
        MonoObject *member;
        int i, match;
@@ -4022,18 +4074,23 @@ ves_icall_Type_GetConstructors_internal (MonoReflectionType *type, guint32 bflag
        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;
@@ -4063,19 +4120,20 @@ ves_icall_Type_GetConstructors_internal (MonoReflectionType *type, guint32 bflag
                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;
@@ -4158,11 +4216,15 @@ ves_icall_Type_GetPropertiesByName (MonoReflectionType *type, MonoString *name,
 
        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) {
@@ -4234,7 +4296,9 @@ handle_parent:
        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));
 
@@ -4294,11 +4358,15 @@ ves_icall_Type_GetEvents_internal (MonoReflectionType *type, MonoString *name, g
 
        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);
@@ -4373,7 +4441,9 @@ handle_parent:
 
        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));
@@ -4420,8 +4490,11 @@ ves_icall_Type_GetNestedTypes (MonoReflectionType *type, MonoString *name, guint
        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);
 
        /*
@@ -4467,7 +4540,9 @@ ves_icall_Type_GetNestedTypes (MonoReflectionType *type, MonoString *name, guint
                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));
@@ -4781,8 +4856,11 @@ ves_icall_System_Reflection_Assembly_GetManifestModuleInternal (MonoReflectionAs
 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;
 
@@ -4838,7 +4916,10 @@ ves_icall_System_Reflection_Assembly_GetReferencedAssemblies (MonoReflectionAsse
        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 (
@@ -4896,14 +4977,26 @@ ves_icall_System_Reflection_Assembly_GetReferencedAssemblies (MonoReflectionAsse
                        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
@@ -5052,6 +5145,7 @@ ves_icall_System_Reflection_Assembly_GetManifestResourceInfoInternal (MonoReflec
 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;
@@ -5082,7 +5176,10 @@ ves_icall_System_Reflection_Assembly_GetFilesInternal (MonoReflectionAssembly *a
                        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) {
@@ -5126,7 +5223,9 @@ ves_icall_System_Reflection_Assembly_GetModulesInternal (MonoReflectionAssembly
                        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);
        if (mono_error_set_pending_exception (&error))
@@ -5454,11 +5553,15 @@ fill_reflection_assembly_name (MonoDomain *domain, MonoReflectionAssemblyName *a
                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;
        }
 
@@ -5467,8 +5570,11 @@ fill_reflection_assembly_name (MonoDomain *domain, MonoReflectionAssemblyName *a
                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;
@@ -5476,7 +5582,9 @@ fill_reflection_assembly_name (MonoDomain *domain, MonoReflectionAssemblyName *a
                        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);
        }
 }
 
@@ -5626,8 +5734,10 @@ mono_module_get_types (MonoDomain *domain, MonoImage *image, MonoArray **excepti
        } 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)) {
@@ -5691,12 +5801,16 @@ ves_icall_System_Reflection_Assembly_GetTypes (MonoReflectionAssembly *assembly,
                                        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;
@@ -5736,7 +5850,11 @@ ves_icall_System_Reflection_Assembly_GetTypes (MonoReflectionAssembly *assembly,
                MonoArray *exl = NULL;
                int j, length = g_list_length (list) + ex_count;
 
-               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);
@@ -5877,9 +5995,11 @@ ves_icall_System_Reflection_Module_InternalGetTypes (MonoReflectionModule *modul
        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);
@@ -6196,8 +6316,9 @@ ves_icall_System_Reflection_Module_ResolveMemberToken (MonoImage *image, guint32
 }
 
 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;
@@ -6205,7 +6326,7 @@ ves_icall_System_Reflection_Module_ResolveSignature (MonoImage *image, guint32 t
        const char *ptr;
        MonoArray *res;
 
-       *error = ResolveTokenError_OutOfRange;
+       *resolve_error = ResolveTokenError_OutOfRange;
 
        /* FIXME: Support other tables ? */
        if (table != MONO_TABLE_STANDALONESIG)
@@ -6222,7 +6343,9 @@ ves_icall_System_Reflection_Module_ResolveSignature (MonoImage *image, guint32 t
        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;
 }
@@ -6435,8 +6558,10 @@ ves_icall_System_Delegate_CreateDelegate_internal (MonoReflectionType *type, Mon
        } 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);
@@ -6771,10 +6896,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;
@@ -6798,7 +6933,9 @@ ves_icall_System_Environment_GetEnvironmentVariableNames (void)
        }
 
        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;
@@ -6827,6 +6964,7 @@ ves_icall_System_Environment_GetEnvironmentVariableNames (void)
        return names;
 
 #else
+       MonoError error;
        MonoArray *names;
        MonoDomain *domain;
        MonoString *str;
@@ -6838,7 +6976,9 @@ ves_icall_System_Environment_GetEnvironmentVariableNames (void)
                ++ 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) {
@@ -7001,7 +7141,10 @@ ves_icall_System_Environment_GetLogicalDrives (void)
        } 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;
@@ -7009,12 +7152,13 @@ ves_icall_System_Environment_GetLogicalDrives (void)
                while (*u16) { u16++; len ++; }
                drivestr = mono_string_new_utf16_checked (domain, dname, len, &error);
                if (mono_error_set_pending_exception (&error))
-                       return NULL;
+                       goto leave;
 
                mono_array_setref (result, ndrives++, drivestr);
                while (*dname++);
        } while (*dname);
 
+leave:
        if (ptr != buf)
                g_free (ptr);
 
@@ -7267,7 +7411,9 @@ ves_icall_System_Runtime_Activation_ActivationServices_AllocateUninitializedClas
 
        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)) {
@@ -7896,7 +8042,8 @@ type_array_from_modifiers (MonoImage *image, MonoType *type, int optional, MonoE
        }
        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)) {
index 2adadc6ed6ea52e638f47b2e74e0a03fabf3ae3f..e01f8be31d67a836e5f8c9e0b7bcffb725de557f 100644 (file)
@@ -92,11 +92,13 @@ region_name_locator (const void *a, const void *b)
 }
 
 static MonoArray*
-create_group_sizes_array (const gint *gs, gint ml)
+create_group_sizes_array (const gint *gs, gint ml, MonoError *error)
 {
        MonoArray *ret;
        int i, len = 0;
 
+       mono_error_init (error);
+
        for (i = 0; i < ml; i++) {
                if (gs [i] == -1)
                        break;
@@ -104,7 +106,8 @@ create_group_sizes_array (const gint *gs, gint ml)
        }
        
        ret = mono_array_new_cached (mono_domain_get (),
-                       mono_get_int32_class (), len);
+                                    mono_get_int32_class (), len, error);
+       return_val_if_nok (error, NULL);
 
        for(i = 0; i < len; i++)
                mono_array_set (ret, gint32, i, gs [i]);
@@ -113,18 +116,21 @@ create_group_sizes_array (const gint *gs, gint ml)
 }
 
 static MonoArray*
-create_names_array_idx (const guint16 *names, int ml)
+create_names_array_idx (const guint16 *names, int ml, MonoError *error)
 {
        MonoArray *ret;
        MonoDomain *domain;
        int i;
 
+       mono_error_init (error);
+
        if (names == NULL)
                return NULL;
 
        domain = mono_domain_get ();
 
-       ret = mono_array_new_cached (mono_domain_get (), mono_get_string_class (), ml);
+       ret = mono_array_new_cached (mono_domain_get (), mono_get_string_class (), ml, error);
+       return_val_if_nok (error, NULL);
 
        for(i = 0; i < ml; i++)
                mono_array_setref (ret, i, mono_string_new (domain, idx2string (names [i])));
@@ -133,12 +139,14 @@ create_names_array_idx (const guint16 *names, int ml)
 }
 
 static MonoArray*
-create_names_array_idx_dynamic (const guint16 *names, int ml)
+create_names_array_idx_dynamic (const guint16 *names, int ml, MonoError *error)
 {
        MonoArray *ret;
        MonoDomain *domain;
        int i, len = 0;
 
+       mono_error_init (error);
+
        if (names == NULL)
                return NULL;
 
@@ -150,7 +158,8 @@ create_names_array_idx_dynamic (const guint16 *names, int ml)
                len++;
        }
 
-       ret = mono_array_new_cached (mono_domain_get (), mono_get_string_class (), len);
+       ret = mono_array_new_cached (mono_domain_get (), mono_get_string_class (), len, error);
+       return_val_if_nok (error, NULL);
 
        for(i = 0; i < len; i++)
                mono_array_setref (ret, i, mono_string_new (domain, idx2string (names [i])));
@@ -161,6 +170,7 @@ create_names_array_idx_dynamic (const guint16 *names, int ml)
 MonoBoolean
 ves_icall_System_Globalization_CalendarData_fill_calendar_data (MonoCalendarData *this_obj, MonoString *name, gint32 calendar_index)
 {
+       MonoError error;
        MonoDomain *domain;
        const DateTimeFormatEntry *dfe;
        const CultureInfoNameEntry *ne;
@@ -181,24 +191,52 @@ ves_icall_System_Globalization_CalendarData_fill_calendar_data (MonoCalendarData
        domain = mono_domain_get ();
 
        MONO_OBJECT_SETREF (this_obj, NativeName, mono_string_new (domain, idx2string (ci->nativename)));
-       MONO_OBJECT_SETREF (this_obj, ShortDatePatterns, create_names_array_idx_dynamic (dfe->short_date_patterns,
-                       NUM_SHORT_DATE_PATTERNS));
-       MONO_OBJECT_SETREF (this_obj, YearMonthPatterns, create_names_array_idx_dynamic (dfe->year_month_patterns,
-                       NUM_YEAR_MONTH_PATTERNS));
+       MonoArray *short_date_patterns = create_names_array_idx_dynamic (dfe->short_date_patterns,
+                                                                        NUM_SHORT_DATE_PATTERNS, &error);
+       return_val_and_set_pending_if_nok (&error, FALSE);
+       MONO_OBJECT_SETREF (this_obj, ShortDatePatterns, short_date_patterns);
+       MonoArray *year_month_patterns =create_names_array_idx_dynamic (dfe->year_month_patterns,
+                                                                       NUM_YEAR_MONTH_PATTERNS, &error);
+       return_val_and_set_pending_if_nok (&error, FALSE);
+       MONO_OBJECT_SETREF (this_obj, YearMonthPatterns, year_month_patterns);
+
+       MonoArray *long_date_patterns = create_names_array_idx_dynamic (dfe->long_date_patterns,
+                                                                       NUM_LONG_DATE_PATTERNS, &error);
+       return_val_and_set_pending_if_nok (&error, FALSE);
+       MONO_OBJECT_SETREF (this_obj, LongDatePatterns, long_date_patterns);
 
-       MONO_OBJECT_SETREF (this_obj, LongDatePatterns, create_names_array_idx_dynamic (dfe->long_date_patterns,
-                       NUM_LONG_DATE_PATTERNS));
        MONO_OBJECT_SETREF (this_obj, MonthDayPattern, mono_string_new (domain, idx2string (dfe->month_day_pattern)));
 
-       MONO_OBJECT_SETREF (this_obj, DayNames, create_names_array_idx (dfe->day_names, NUM_DAYS));
-       MONO_OBJECT_SETREF (this_obj, AbbreviatedDayNames, create_names_array_idx (dfe->abbreviated_day_names, 
-                       NUM_DAYS));
-       MONO_OBJECT_SETREF (this_obj, SuperShortDayNames, create_names_array_idx (dfe->shortest_day_names, NUM_DAYS));
-       MONO_OBJECT_SETREF (this_obj, MonthNames, create_names_array_idx (dfe->month_names, NUM_MONTHS));
-       MONO_OBJECT_SETREF (this_obj, AbbreviatedMonthNames, create_names_array_idx (dfe->abbreviated_month_names,
-                       NUM_MONTHS));
-       MONO_OBJECT_SETREF (this_obj, GenitiveMonthNames, create_names_array_idx (dfe->month_genitive_names, NUM_MONTHS));
-       MONO_OBJECT_SETREF (this_obj, GenitiveAbbreviatedMonthNames, create_names_array_idx (dfe->abbreviated_month_genitive_names, NUM_MONTHS));
+       MonoArray *day_names = create_names_array_idx (dfe->day_names, NUM_DAYS, &error);
+       return_val_and_set_pending_if_nok (&error, FALSE);
+       MONO_OBJECT_SETREF (this_obj, DayNames, day_names);
+
+       MonoArray *abbr_day_names = create_names_array_idx (dfe->abbreviated_day_names, 
+                                                           NUM_DAYS, &error);
+       return_val_and_set_pending_if_nok (&error, FALSE);
+       MONO_OBJECT_SETREF (this_obj, AbbreviatedDayNames, abbr_day_names);
+
+       MonoArray *ss_day_names = create_names_array_idx (dfe->shortest_day_names, NUM_DAYS, &error);
+       return_val_and_set_pending_if_nok (&error, FALSE);
+       MONO_OBJECT_SETREF (this_obj, SuperShortDayNames, ss_day_names);
+
+       MonoArray *month_names = create_names_array_idx (dfe->month_names, NUM_MONTHS, &error);
+       return_val_and_set_pending_if_nok (&error, FALSE);
+       MONO_OBJECT_SETREF (this_obj, MonthNames, month_names);
+
+       MonoArray *abbr_mon_names = create_names_array_idx (dfe->abbreviated_month_names,
+                                                           NUM_MONTHS, &error);
+       return_val_and_set_pending_if_nok (&error, FALSE);
+       MONO_OBJECT_SETREF (this_obj, AbbreviatedMonthNames, abbr_mon_names);
+
+       
+       MonoArray *gen_month_names = create_names_array_idx (dfe->month_genitive_names, NUM_MONTHS, &error);
+       return_val_and_set_pending_if_nok (&error, FALSE);
+       MONO_OBJECT_SETREF (this_obj, GenitiveMonthNames, gen_month_names);
+
+       MonoArray *gen_abbr_mon_names = create_names_array_idx (dfe->abbreviated_month_genitive_names, NUM_MONTHS, &error);
+       return_val_and_set_pending_if_nok (&error, FALSE);
+       MONO_OBJECT_SETREF (this_obj, GenitiveAbbreviatedMonthNames, gen_abbr_mon_names);
 
        return TRUE;
 }
@@ -206,6 +244,7 @@ ves_icall_System_Globalization_CalendarData_fill_calendar_data (MonoCalendarData
 void
 ves_icall_System_Globalization_CultureData_fill_culture_data (MonoCultureData *this_obj, gint32 datetime_index)
 {
+       MonoError error;
        MonoDomain *domain;
        const DateTimeFormatEntry *dfe;
 
@@ -218,10 +257,18 @@ ves_icall_System_Globalization_CultureData_fill_culture_data (MonoCultureData *t
        MONO_OBJECT_SETREF (this_obj, AMDesignator, mono_string_new (domain, idx2string (dfe->am_designator)));
        MONO_OBJECT_SETREF (this_obj, PMDesignator, mono_string_new (domain, idx2string (dfe->pm_designator)));
        MONO_OBJECT_SETREF (this_obj, TimeSeparator, mono_string_new (domain, idx2string (dfe->time_separator)));
-       MONO_OBJECT_SETREF (this_obj, LongTimePatterns, create_names_array_idx_dynamic (dfe->long_time_patterns,
-                       NUM_LONG_TIME_PATTERNS));
-       MONO_OBJECT_SETREF (this_obj, ShortTimePatterns, create_names_array_idx_dynamic (dfe->short_time_patterns,
-                       NUM_SHORT_TIME_PATTERNS));
+
+       MonoArray *long_time_patterns = create_names_array_idx_dynamic (dfe->long_time_patterns,
+                                                                       NUM_LONG_TIME_PATTERNS, &error);
+       if (mono_error_set_pending_exception (&error))
+               return;
+       MONO_OBJECT_SETREF (this_obj, LongTimePatterns, long_time_patterns);
+
+       MonoArray *short_time_patterns = create_names_array_idx_dynamic (dfe->short_time_patterns,
+                                                                        NUM_SHORT_TIME_PATTERNS, &error);
+       if (mono_error_set_pending_exception (&error))
+               return;
+       MONO_OBJECT_SETREF (this_obj, ShortTimePatterns, short_time_patterns);
        this_obj->FirstDayOfWeek = dfe->first_day_of_week;
        this_obj->CalendarWeekRule = dfe->calendar_week_rule;
 }
@@ -229,6 +276,7 @@ ves_icall_System_Globalization_CultureData_fill_culture_data (MonoCultureData *t
 void
 ves_icall_System_Globalization_CultureData_fill_number_data (MonoNumberFormatInfo* number, gint32 number_index)
 {
+       MonoError error;
        MonoDomain *domain;
        const NumberFormatEntry *nfe;
 
@@ -243,8 +291,11 @@ ves_icall_System_Globalization_CultureData_fill_number_data (MonoNumberFormatInf
                        idx2string (nfe->currency_decimal_separator)));
        MONO_OBJECT_SETREF (number, currencyGroupSeparator, mono_string_new (domain,
                        idx2string (nfe->currency_group_separator)));
-       MONO_OBJECT_SETREF (number, currencyGroupSizes, create_group_sizes_array (nfe->currency_group_sizes,
-                       GROUP_SIZE));
+       MonoArray *currency_sizes_arr = create_group_sizes_array (nfe->currency_group_sizes,
+                                                                 GROUP_SIZE, &error);
+       if (mono_error_set_pending_exception (&error))
+               return;
+       MONO_OBJECT_SETREF (number, currencyGroupSizes, currency_sizes_arr);
        number->currencyNegativePattern = nfe->currency_negative_pattern;
        number->currencyPositivePattern = nfe->currency_positive_pattern;
        MONO_OBJECT_SETREF (number, currencySymbol, mono_string_new (domain, idx2string (nfe->currency_symbol)));
@@ -256,8 +307,11 @@ ves_icall_System_Globalization_CultureData_fill_number_data (MonoNumberFormatInf
        MONO_OBJECT_SETREF (number, numberDecimalSeparator, mono_string_new (domain,
                        idx2string (nfe->number_decimal_separator)));
        MONO_OBJECT_SETREF (number, numberGroupSeparator, mono_string_new (domain, idx2string (nfe->number_group_separator)));
-       MONO_OBJECT_SETREF (number, numberGroupSizes, create_group_sizes_array (nfe->number_group_sizes,
-                       GROUP_SIZE));
+       MonoArray *number_sizes_arr = create_group_sizes_array (nfe->number_group_sizes,
+                                                               GROUP_SIZE, &error);
+       if (mono_error_set_pending_exception (&error))
+               return;
+       MONO_OBJECT_SETREF (number, numberGroupSizes, number_sizes_arr);
        number->numberNegativePattern = nfe->number_negative_pattern;
        number->percentNegativePattern = nfe->percent_negative_pattern;
        number->percentPositivePattern = nfe->percent_positive_pattern;
@@ -269,10 +323,12 @@ ves_icall_System_Globalization_CultureData_fill_number_data (MonoNumberFormatInf
 }
 
 static MonoBoolean
-construct_culture (MonoCultureInfo *this_obj, const CultureInfoEntry *ci)
+construct_culture (MonoCultureInfo *this_obj, const CultureInfoEntry *ci, MonoError *error)
 {
        MonoDomain *domain = mono_domain_get ();
 
+       mono_error_init (error);
+
        this_obj->lcid = ci->lcid;
        MONO_OBJECT_SETREF (this_obj, name, mono_string_new (domain, idx2string (ci->name)));
        MONO_OBJECT_SETREF (this_obj, englishname, mono_string_new (domain, idx2string (ci->englishname)));
@@ -284,7 +340,10 @@ construct_culture (MonoCultureInfo *this_obj, const CultureInfoEntry *ci)
        // It's null for neutral cultures
        if (ci->territory > 0)
                MONO_OBJECT_SETREF (this_obj, territory, mono_string_new (domain, idx2string (ci->territory)));
-       MONO_OBJECT_SETREF (this_obj, native_calendar_names, create_names_array_idx (ci->native_calendar_names, NUM_CALENDARS));
+
+       MonoArray *native_calendar_names = create_names_array_idx (ci->native_calendar_names, NUM_CALENDARS, error);
+       return_val_if_nok (error, FALSE);
+       MONO_OBJECT_SETREF (this_obj, native_calendar_names, native_calendar_names);
        this_obj->parent_lcid = ci->parent_lcid;
        this_obj->datetime_index = ci->datetime_format_index;
        this_obj->number_index = ci->number_format_index;
@@ -493,19 +552,25 @@ MonoBoolean
 ves_icall_System_Globalization_CultureInfo_construct_internal_locale_from_lcid (MonoCultureInfo *this_obj,
                gint lcid)
 {
+       MonoError error;
        const CultureInfoEntry *ci;
        
        ci = culture_info_entry_from_lcid (lcid);
        if(ci == NULL)
                return FALSE;
 
-       return construct_culture (this_obj, ci);
+       if (!construct_culture (this_obj, ci, &error)) {
+               mono_error_set_pending_exception (&error);
+               return FALSE;
+       }
+       return TRUE;
 }
 
 MonoBoolean
 ves_icall_System_Globalization_CultureInfo_construct_internal_locale_from_name (MonoCultureInfo *this_obj,
                MonoString *name)
 {
+       MonoError error;
        const CultureInfoNameEntry *ne;
        char *n;
        
@@ -520,7 +585,11 @@ ves_icall_System_Globalization_CultureInfo_construct_internal_locale_from_name (
        }
        g_free (n);
 
-       return construct_culture (this_obj, &culture_entries [ne->culture_entry_index]);
+       if (!construct_culture (this_obj, &culture_entries [ne->culture_entry_index], &error)) {
+               mono_error_set_pending_exception (&error);
+               return FALSE;
+       }
+       return TRUE;
 }
 /*
 MonoBoolean
@@ -601,7 +670,9 @@ ves_icall_System_Globalization_CultureInfo_internal_get_cultures (MonoBoolean ne
        if (neutral)
                len++;
 
-       ret = mono_array_new (domain, klass, len);
+       ret = mono_array_new_checked (domain, klass, len, &error);
+       if (!is_ok (&error))
+               goto fail;
 
        if (len == 0)
                return ret;
@@ -618,7 +689,8 @@ ves_icall_System_Globalization_CultureInfo_internal_get_cultures (MonoBoolean ne
                        if (!is_ok (&error)) goto fail;
                        mono_runtime_object_init_checked ((MonoObject *) culture, &error);
                        if (!is_ok (&error)) goto fail;
-                       construct_culture (culture, ci);
+                       if (!construct_culture (culture, ci, &error))
+                               goto fail;
                        culture->use_user_override = TRUE;
                        mono_array_setref (ret, len++, culture);
                }
@@ -642,13 +714,17 @@ int ves_icall_System_Globalization_CompareInfo_internal_compare (MonoCompareInfo
 
 void ves_icall_System_Globalization_CompareInfo_assign_sortkey (MonoCompareInfo *this_obj, MonoSortKey *key, MonoString *source, gint32 options)
 {
+       MonoError error;
        MonoArray *arr;
        gint32 keylen, i;
 
        keylen=mono_string_length (source);
        
-       arr=mono_array_new (mono_domain_get (), mono_get_byte_class (),
-                           keylen);
+       arr=mono_array_new_checked (mono_domain_get (), mono_get_byte_class (),
+                                   keylen, &error);
+       if (mono_error_set_pending_exception (&error))
+               return;
+
        for(i=0; i<keylen; i++) {
                mono_array_set (arr, guint8, i, mono_string_chars (source)[i]);
        }
index 3d4e8146decc3263d8a87bbba9a445e391fcfb57..13ef2b4c486a68e9b8ca8be2303d851b22aebcf2 100644 (file)
@@ -606,9 +606,11 @@ mono_delegate_free_ftnptr (MonoDelegate *delegate)
        }
 }
 
+/* This is a JIT icall, it sets the pending exception and returns NULL on error */
 static MonoString *
 mono_string_from_byvalstr (const char *data, int max_len)
 {
+       MonoError error;
        MonoDomain *domain = mono_domain_get ();
        int len = 0;
 
@@ -618,7 +620,9 @@ mono_string_from_byvalstr (const char *data, int max_len)
        while (len < max_len - 1 && data [len])
                len++;
 
-       return mono_string_new_len (domain, data, len);
+       MonoString *result = mono_string_new_len_checked (domain, data, len, &error);
+       mono_error_set_pending_exception (&error);
+       return result;
 }
 
 /* This is a JIT icall, it sets the pending exception and return NULL on error */
@@ -1126,10 +1130,14 @@ mono_string_to_byvalwstr (gpointer dst, MonoString *src, int size)
        *((gunichar2 *) dst + len) = 0;
 }
 
+/* this is an icall, it sets the pending exception and returns NULL on error */
 static MonoString*
 mono_string_new_len_wrapper (const char *text, guint length)
 {
-       return mono_string_new_len (mono_domain_get (), text, length);
+       MonoError error;
+       MonoString *result = mono_string_new_len_checked (mono_domain_get (), text, length, &error);
+       mono_error_set_pending_exception (&error);
+       return result;
 }
 
 #ifndef DISABLE_JIT
@@ -1216,7 +1224,8 @@ guint
 mono_type_to_stind (MonoType *type)
 {
        if (type->byref)
-               return CEE_STIND_I;
+               return MONO_TYPE_IS_REFERENCE (type) ? CEE_STIND_REF : CEE_STIND_I;
+
 
 handle_enum:
        switch (type->type) {
@@ -1312,7 +1321,7 @@ emit_ptr_to_object_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv
                mono_mb_emit_ldloc (mb, 1);
                mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
                mono_mb_emit_op (mb, CEE_NEWARR, eklass);       
-               mono_mb_emit_byte (mb, CEE_STIND_I);
+               mono_mb_emit_byte (mb, CEE_STIND_REF);
 
                if (eklass->blittable) {
                        /* copy the elements */
@@ -1550,16 +1559,23 @@ emit_ptr_to_object_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv
 }
 
 static gpointer
-conv_to_icall (MonoMarshalConv conv)
+conv_to_icall (MonoMarshalConv conv, int *ind_store_type)
 {
+       int dummy;
+       if (!ind_store_type)
+               ind_store_type = &dummy;
+       *ind_store_type = CEE_STIND_I;
        switch (conv) {
        case MONO_MARSHAL_CONV_STR_LPWSTR:
                return mono_marshal_string_to_utf16;            
        case MONO_MARSHAL_CONV_LPWSTR_STR:
+               *ind_store_type = CEE_STIND_REF;
                return mono_string_from_utf16;
        case MONO_MARSHAL_CONV_LPTSTR_STR:
+               *ind_store_type = CEE_STIND_REF;
                return mono_string_new_wrapper;
        case MONO_MARSHAL_CONV_LPSTR_STR:
+               *ind_store_type = CEE_STIND_REF;
                return mono_string_new_wrapper;
        case MONO_MARSHAL_CONV_STR_LPTSTR:
 #ifdef TARGET_WIN32
@@ -1572,6 +1588,7 @@ conv_to_icall (MonoMarshalConv conv)
        case MONO_MARSHAL_CONV_STR_BSTR:
                return mono_string_to_bstr;
        case MONO_MARSHAL_CONV_BSTR_STR:
+               *ind_store_type = CEE_STIND_REF;
                return mono_string_from_bstr;
        case MONO_MARSHAL_CONV_STR_TBSTR:
        case MONO_MARSHAL_CONV_STR_ANSIBSTR:
@@ -1595,16 +1612,20 @@ conv_to_icall (MonoMarshalConv conv)
        case MONO_MARSHAL_CONV_DEL_FTN:
                return mono_delegate_to_ftnptr;
        case MONO_MARSHAL_CONV_FTN_DEL:
+               *ind_store_type = CEE_STIND_REF;
                return mono_ftnptr_to_delegate;
        case MONO_MARSHAL_CONV_LPSTR_SB:
+               *ind_store_type = CEE_STIND_REF;
                return mono_string_utf8_to_builder;
        case MONO_MARSHAL_CONV_LPTSTR_SB:
+               *ind_store_type = CEE_STIND_REF;
 #ifdef TARGET_WIN32
                return mono_string_utf16_to_builder;
 #else
                return mono_string_utf8_to_builder;
 #endif
        case MONO_MARSHAL_CONV_LPWSTR_SB:
+               *ind_store_type = CEE_STIND_REF;
                return mono_string_utf16_to_builder;
        case MONO_MARSHAL_FREE_ARRAY:
                return mono_marshal_free_array;
@@ -1623,6 +1644,7 @@ static void
 emit_object_to_ptr_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv conv, MonoMarshalSpec *mspec)
 {
        int pos;
+       int stind_op;
 
        switch (conv) {
        case MONO_MARSHAL_CONV_BOOL_I4:
@@ -1657,8 +1679,8 @@ emit_object_to_ptr_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv
                mono_mb_emit_ldloc (mb, 1);
                mono_mb_emit_ldloc (mb, 0);
                mono_mb_emit_byte (mb, CEE_LDIND_REF);
-               mono_mb_emit_icall (mb, conv_to_icall (conv));
-               mono_mb_emit_byte (mb, CEE_STIND_I);    
+               mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
+               mono_mb_emit_byte (mb, stind_op);
                break;
        }
        case MONO_MARSHAL_CONV_ARRAY_SAVEARRAY:
@@ -1667,8 +1689,8 @@ emit_object_to_ptr_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv
                mono_mb_emit_ldloc (mb, 1);
                mono_mb_emit_ldloc (mb, 0);
                mono_mb_emit_byte (mb, CEE_LDIND_REF);
-               mono_mb_emit_icall (mb, conv_to_icall (conv));
-               mono_mb_emit_byte (mb, CEE_STIND_I);    
+               mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
+               mono_mb_emit_byte (mb, stind_op);
                break;
        case MONO_MARSHAL_CONV_STR_BYVALSTR: 
        case MONO_MARSHAL_CONV_STR_BYVALWSTR: {
@@ -1678,7 +1700,7 @@ emit_object_to_ptr_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv
                mono_mb_emit_ldloc (mb, 0);     
                mono_mb_emit_byte (mb, CEE_LDIND_REF); /* src String */
                mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
-               mono_mb_emit_icall (mb, conv_to_icall (conv));
+               mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
                break;
        }
        case MONO_MARSHAL_CONV_ARRAY_BYVALARRAY: {
@@ -1940,8 +1962,9 @@ emit_struct_conv_full (MonoMethodBuilder *mb, MonoClass *klass, gboolean to_obje
                case MONO_MARSHAL_CONV_NONE: {
                        int t;
 
-                       if (ftype->byref || ftype->type == MONO_TYPE_I ||
-                           ftype->type == MONO_TYPE_U) {
+                       //XXX a byref field!?!? that's not allowed! and worse, it might miss a WB
+                       g_assert (!ftype->byref);
+                       if (ftype->type == MONO_TYPE_I || ftype->type == MONO_TYPE_U) {
                                mono_mb_emit_ldloc (mb, 1);
                                mono_mb_emit_ldloc (mb, 0);
                                mono_mb_emit_byte (mb, CEE_LDIND_I);
@@ -2964,7 +2987,8 @@ mono_delegate_end_invoke (MonoDelegate *delegate, gpointer *params)
                mono_set_pending_exception ((MonoException*)exc);
        }
 
-       mono_method_return_message_restore (method, params, out_args);
+       mono_method_return_message_restore (method, params, out_args, &error);
+       mono_error_set_pending_exception (&error);
        return res;
 }
 
@@ -5109,7 +5133,7 @@ emit_marshal_string (EmitMarshalContext *m, int argnum, MonoType *t,
                        char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
                        mono_mb_emit_exception_marshal_directive (mb, msg);
                } else {
-                       mono_mb_emit_icall (mb, conv_to_icall (conv));
+                       mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
 
                        mono_mb_emit_stloc (mb, conv_arg);
                }
@@ -5150,10 +5174,11 @@ emit_marshal_string (EmitMarshalContext *m, int argnum, MonoType *t,
                        mono_mb_emit_icall (mb, mono_string_new_len_wrapper);
                        mono_mb_emit_byte (mb, CEE_STIND_REF);
                } else if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT || !(t->attrs & PARAM_ATTRIBUTE_IN))) {
+                       int stind_op;
                        mono_mb_emit_ldarg (mb, argnum);
                        mono_mb_emit_ldloc (mb, conv_arg);
-                       mono_mb_emit_icall (mb, conv_to_icall (conv));
-                       mono_mb_emit_byte (mb, CEE_STIND_REF);
+                       mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
+                       mono_mb_emit_byte (mb, stind_op);
                        need_free = TRUE;
                }
 
@@ -5184,7 +5209,7 @@ emit_marshal_string (EmitMarshalContext *m, int argnum, MonoType *t,
                }
 
                mono_mb_emit_ldloc (mb, 0);
-               mono_mb_emit_icall (mb, conv_to_icall (conv));
+               mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
                mono_mb_emit_stloc (mb, 3);
 
                /* free the string */
@@ -5215,27 +5240,28 @@ emit_marshal_string (EmitMarshalContext *m, int argnum, MonoType *t,
                mono_mb_emit_ldarg (mb, argnum);
                if (t->byref)
                        mono_mb_emit_byte (mb, CEE_LDIND_I);
-               mono_mb_emit_icall (mb, conv_to_icall (conv));
+               mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
                mono_mb_emit_stloc (mb, conv_arg);
                break;
 
        case MARSHAL_ACTION_MANAGED_CONV_OUT:
                if (t->byref) {
                        if (conv_arg) {
+                               int stind_op;
                                mono_mb_emit_ldarg (mb, argnum);
                                mono_mb_emit_ldloc (mb, conv_arg);
-                               mono_mb_emit_icall (mb, conv_to_icall (conv));
-                               mono_mb_emit_byte (mb, CEE_STIND_I);
+                               mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
+                               mono_mb_emit_byte (mb, stind_op);
                        }
                }
                break;
 
        case MARSHAL_ACTION_MANAGED_CONV_RESULT:
-               if (conv_to_icall (conv) == mono_marshal_string_to_utf16)
+               if (conv_to_icall (conv, NULL) == mono_marshal_string_to_utf16)
                        /* We need to make a copy so the caller is able to free it */
                        mono_mb_emit_icall (mb, mono_marshal_string_to_utf16_copy);
                else
-                       mono_mb_emit_icall (mb, conv_to_icall (conv));
+                       mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
                mono_mb_emit_stloc (mb, 3);
                break;
 
@@ -5514,7 +5540,7 @@ emit_marshal_object (EmitMarshalContext *m, int argnum, MonoType *t,
                                mono_mb_emit_stloc (mb, conv_arg);
                        } else {
                                mono_mb_emit_ldarg (mb, argnum);
-                               mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_DEL_FTN));
+                               mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_DEL_FTN, NULL));
                                mono_mb_emit_stloc (mb, conv_arg);
                        }
                } else if (klass == mono_defaults.stringbuilder_class) {
@@ -5544,7 +5570,7 @@ emit_marshal_object (EmitMarshalContext *m, int argnum, MonoType *t,
                        if (t->byref)
                                mono_mb_emit_byte (mb, CEE_LDIND_I);
 
-                       mono_mb_emit_icall (mb, conv_to_icall (conv));
+                       mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
                        mono_mb_emit_stloc (mb, conv_arg);
                } else if (klass->blittable) {
                        mono_mb_emit_byte (mb, CEE_LDNULL);
@@ -5646,7 +5672,7 @@ emit_marshal_object (EmitMarshalContext *m, int argnum, MonoType *t,
                                mono_mb_emit_ldarg (mb, argnum);
                                mono_mb_emit_ldloc (mb, conv_arg);
 
-                               mono_mb_emit_icall (mb, conv_to_icall (conv));
+                               mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
                        }
 
                        if (need_free) {
@@ -5662,7 +5688,7 @@ emit_marshal_object (EmitMarshalContext *m, int argnum, MonoType *t,
                                mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
                                mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
                                mono_mb_emit_ldloc (mb, conv_arg);
-                               mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL));
+                               mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL, NULL));
                                mono_mb_emit_byte (mb, CEE_STIND_REF);
                        }
                        break;
@@ -5745,7 +5771,7 @@ emit_marshal_object (EmitMarshalContext *m, int argnum, MonoType *t,
                        mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
                        mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
                        mono_mb_emit_ldloc (mb, 0);
-                       mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL));
+                       mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL, NULL));
                        mono_mb_emit_stloc (mb, 3);
                } else {
                        /* set src */
@@ -5795,7 +5821,7 @@ emit_marshal_object (EmitMarshalContext *m, int argnum, MonoType *t,
                        mono_mb_emit_ldarg (mb, argnum);
                        if (t->byref)
                                mono_mb_emit_byte (mb, CEE_LDIND_I);
-                       mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL));
+                       mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL, NULL));
                        mono_mb_emit_stloc (mb, conv_arg);
                        break;
                }
@@ -5869,10 +5895,11 @@ emit_marshal_object (EmitMarshalContext *m, int argnum, MonoType *t,
        case MARSHAL_ACTION_MANAGED_CONV_OUT:
                if (klass->delegate) {
                        if (t->byref) {
+                               int stind_op;
                                mono_mb_emit_ldarg (mb, argnum);
                                mono_mb_emit_ldloc (mb, conv_arg);
-                               mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_DEL_FTN));
-                               mono_mb_emit_byte (mb, CEE_STIND_I);
+                               mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_DEL_FTN, &stind_op));
+                               mono_mb_emit_byte (mb, stind_op);
                                break;
                        }
                }
@@ -5931,7 +5958,7 @@ emit_marshal_object (EmitMarshalContext *m, int argnum, MonoType *t,
 
        case MARSHAL_ACTION_MANAGED_CONV_RESULT:
                if (klass->delegate) {
-                       mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_DEL_FTN));
+                       mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_DEL_FTN, NULL));
                        mono_mb_emit_stloc (mb, 3);
                        break;
                }
@@ -6148,7 +6175,7 @@ emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
                        mono_mb_emit_ldarg (mb, argnum);
                        if (t->byref)
                                mono_mb_emit_byte (mb, CEE_LDIND_I);
-                       mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_ARRAY_LPARRAY));
+                       mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_ARRAY_LPARRAY, NULL));
                        mono_mb_emit_stloc (mb, conv_arg);
                } else {
                        MonoClass *eklass;
@@ -6228,12 +6255,13 @@ emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
                        /* Emit marshalling code */
 
                        if (is_string) {
+                               int stind_op;
                                mono_mb_emit_ldloc (mb, dest_ptr);
                                mono_mb_emit_ldloc (mb, src_var);
                                mono_mb_emit_ldloc (mb, index_var);
                                mono_mb_emit_byte (mb, CEE_LDELEM_REF);
-                               mono_mb_emit_icall (mb, conv_to_icall (conv));
-                               mono_mb_emit_byte (mb, CEE_STIND_I);
+                               mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
+                               mono_mb_emit_byte (mb, stind_op);
                        } else {
                                /* set the src_ptr */
                                mono_mb_emit_ldloc (mb, src_var);
@@ -6297,7 +6325,7 @@ emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
                                mono_mb_emit_byte (mb, CEE_CONV_OVF_I);
                                mono_mb_emit_op (mb, CEE_NEWARR, klass->element_class);
                                /* Store into argument */
-                               mono_mb_emit_byte (mb, CEE_STIND_I);
+                               mono_mb_emit_byte (mb, CEE_STIND_REF);
                        }
                }
 
@@ -6357,7 +6385,7 @@ emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
                                mono_mb_emit_ldloc (mb, src_ptr);
                                mono_mb_emit_byte (mb, CEE_LDIND_I);
 
-                               mono_mb_emit_icall (mb, conv_to_icall (conv));
+                               mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
 
                                if (need_free) {
                                        /* src */
@@ -6419,7 +6447,7 @@ emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
                        if (t->byref)
                                mono_mb_emit_byte (mb, CEE_LDIND_REF);
                        mono_mb_emit_ldloc (mb, conv_arg);
-                       mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_FREE_LPARRAY));
+                       mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_FREE_LPARRAY, NULL));
                }
 
                break;
@@ -6594,7 +6622,7 @@ emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
                        mono_mb_emit_ldloc (mb, src_ptr);
                        mono_mb_emit_byte (mb, CEE_LDIND_I);
 
-                       mono_mb_emit_icall (mb, conv_to_icall (conv));
+                       mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
                        mono_mb_emit_byte (mb, CEE_STELEM_REF);
                }
                else {
@@ -6702,6 +6730,7 @@ emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
 
                /* Emit marshalling code */
                if (is_string) {
+                       int stind_op;
                        g_assert (conv != MONO_MARSHAL_CONV_INVALID);
 
                        /* dest */
@@ -6713,8 +6742,8 @@ emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
 
                        mono_mb_emit_byte (mb, CEE_LDELEM_REF);
 
-                       mono_mb_emit_icall (mb, conv_to_icall (conv));
-                       mono_mb_emit_byte (mb, CEE_STIND_I);
+                       mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
+                       mono_mb_emit_byte (mb, stind_op);
                }
                else {
                        char *msg = g_strdup ("Marshalling of non-string and non-blittable arrays to managed code is not implemented.");
@@ -6799,6 +6828,7 @@ emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
 
                /* Emit marshalling code */
                if (is_string) {
+                       int stind_op;
                        g_assert (conv != MONO_MARSHAL_CONV_INVALID);
 
                        /* dest */
@@ -6810,8 +6840,8 @@ emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
 
                        mono_mb_emit_byte (mb, CEE_LDELEM_REF);
 
-                       mono_mb_emit_icall (mb, conv_to_icall (conv));
-                       mono_mb_emit_byte (mb, CEE_STIND_I);
+                       mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
+                       mono_mb_emit_byte (mb, stind_op);
                }
                else {
                        char *msg = g_strdup ("Marshalling of non-string arrays to managed code is not implemented.");
@@ -8665,7 +8695,7 @@ mono_marshal_get_isinst_with_cache (void)
 
        // return obj
        mono_mb_patch_branch (mb, positive_cache_hit_pos);
-       mono_mb_emit_ldarg (mb, 0);
+       mono_mb_emit_ldarg (mb, obj_arg_position);
        mono_mb_emit_byte (mb, CEE_RET);
 #endif
 
@@ -10485,12 +10515,15 @@ ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi (char *ptr)
 MonoString *
 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi_len (char *ptr, gint32 len)
 {
-       if (ptr == NULL) {
-               mono_set_pending_exception (mono_get_exception_argument_null ("ptr"));
-               return NULL;
-       } else {
-               return mono_string_new_len (mono_domain_get (), ptr, len);
-       }
+       MonoError error;
+       MonoString *result = NULL;
+       mono_error_init (&error);
+       if (ptr == NULL)
+               mono_error_set_argument_null (&error, "ptr", "");
+       else
+               result = mono_string_new_len_checked (mono_domain_get (), ptr, len, &error);
+       mono_error_set_pending_exception (&error);
+       return result;
 }
 
 MonoString *
index 445df5c8334ef7931c3c373c82a5168d71d8842b..fb205e80eaff2781966cdb448262ac85e9bac19f 100644 (file)
@@ -502,7 +502,12 @@ mono_determine_physical_ram_available_size (void)
        mach_port_t host = mach_host_self();
        vm_size_t page_size;
        vm_statistics_data_t vmstat;
-       if (KERN_SUCCESS != host_statistics(host, HOST_VM_INFO, (host_info_t)&vmstat, &count)) {
+       kern_return_t ret;
+       do {
+               ret = host_statistics(host, HOST_VM_INFO, (host_info_t)&vmstat, &count);
+       } while (ret == KERN_ABORTED);
+
+       if (ret != KERN_SUCCESS) {
                g_warning ("Mono was unable to retrieve memory usage!");
                return 0;
        }
@@ -1585,16 +1590,25 @@ mono_perfcounter_instance_exists (MonoString *instance, MonoString *category, Mo
 MonoArray*
 mono_perfcounter_category_names (MonoString *machine)
 {
+       MonoError error;
        int i;
        MonoArray *res;
        MonoDomain *domain = mono_domain_get ();
        GSList *custom_categories, *tmp;
        /* no support for counters on other machines */
-       if (mono_string_compare_ascii (machine, "."))
-               return mono_array_new (domain, mono_get_string_class (), 0);
+       if (mono_string_compare_ascii (machine, ".")) {
+               res = mono_array_new_checked (domain, mono_get_string_class (), 0, &error);
+               mono_error_set_pending_exception (&error);
+               return res;
+       }
        perfctr_lock ();
        custom_categories = get_custom_categories ();
-       res = mono_array_new (domain, mono_get_string_class (), NUM_CATEGORIES + g_slist_length (custom_categories));
+       res = mono_array_new_checked (domain, mono_get_string_class (), NUM_CATEGORIES + g_slist_length (custom_categories), &error);
+       if (mono_error_set_pending_exception (&error)) {
+               perfctr_unlock ();
+               return NULL;
+       }
+
        for (i = 0; i < NUM_CATEGORIES; ++i) {
                const CategoryDesc *cdesc = &predef_categories [i];
                mono_array_setref (res, i, mono_string_new (domain, cdesc->name));
@@ -1612,17 +1626,23 @@ mono_perfcounter_category_names (MonoString *machine)
 MonoArray*
 mono_perfcounter_counter_names (MonoString *category, MonoString *machine)
 {
+       MonoError error;
        int i;
        SharedCategory *scat;
        const CategoryDesc *cdesc;
        MonoArray *res;
        MonoDomain *domain = mono_domain_get ();
        /* no support for counters on other machines */
-       if (mono_string_compare_ascii (machine, "."))
-               return mono_array_new (domain, mono_get_string_class (), 0);
+       if (mono_string_compare_ascii (machine, ".")) {
+               res =  mono_array_new_checked (domain, mono_get_string_class (), 0, &error);
+               mono_error_set_pending_exception (&error);
+               return res;
+       }
        cdesc = find_category (category);
        if (cdesc) {
-               res = mono_array_new (domain, mono_get_string_class (), cdesc [1].first_counter - cdesc->first_counter);
+               res = mono_array_new_checked (domain, mono_get_string_class (), cdesc [1].first_counter - cdesc->first_counter, &error);
+               if (mono_error_set_pending_exception (&error))
+                       return NULL;
                for (i = cdesc->first_counter; i < cdesc [1].first_counter; ++i) {
                        const CounterDesc *desc = &predef_counters [i];
                        mono_array_setref (res, i - cdesc->first_counter, mono_string_new (domain, desc->name));
@@ -1634,7 +1654,12 @@ mono_perfcounter_counter_names (MonoString *category, MonoString *machine)
        if (scat) {
                char *p = custom_category_counters (scat);
                int i;
-               res = mono_array_new (domain, mono_get_string_class (), scat->num_counters);
+               res = mono_array_new_checked (domain, mono_get_string_class (), scat->num_counters, &error);
+               if (mono_error_set_pending_exception (&error)) {
+                       perfctr_unlock ();
+                       return NULL;
+               }
+
                for (i = 0; i < scat->num_counters; ++i) {
                        mono_array_setref (res, i, mono_string_new (domain, p + 1));
                        p += 2; /* skip counter type */
@@ -1645,15 +1670,19 @@ mono_perfcounter_counter_names (MonoString *category, MonoString *machine)
                return res;
        }
        perfctr_unlock ();
-       return mono_array_new (domain, mono_get_string_class (), 0);
+       res = mono_array_new_checked (domain, mono_get_string_class (), 0, &error);
+       mono_error_set_pending_exception (&error);
+       return res;
 }
 
 static MonoArray*
-get_string_array (void **array, int count, gboolean is_process)
+get_string_array (void **array, int count, gboolean is_process, MonoError *error)
 {
        int i;
        MonoDomain *domain = mono_domain_get ();
-       MonoArray * res = mono_array_new (mono_domain_get (), mono_get_string_class (), count);
+       mono_error_init (error);
+       MonoArray * res = mono_array_new_checked (mono_domain_get (), mono_get_string_class (), count, error);
+       return_val_if_nok (error, NULL);
        for (i = 0; i < count; ++i) {
                char buf [128];
                char *p;
@@ -1672,11 +1701,13 @@ get_string_array (void **array, int count, gboolean is_process)
 }
 
 static MonoArray*
-get_string_array_of_strings (void **array, int count)
+get_string_array_of_strings (void **array, int count, MonoError *error)
 {
        int i;
        MonoDomain *domain = mono_domain_get ();
-       MonoArray * res = mono_array_new (mono_domain_get (), mono_get_string_class (), count);
+       mono_error_init (error);
+       MonoArray * res = mono_array_new_checked (mono_domain_get (), mono_get_string_class (), count, error);
+       return_val_if_nok (error, NULL);
        for (i = 0; i < count; ++i) {
                char* p = (char *)array[i];
                mono_array_setref (res, i, mono_string_new (domain, p));
@@ -1686,76 +1717,84 @@ get_string_array_of_strings (void **array, int count)
 }
 
 static MonoArray*
-get_mono_instances (void)
+get_mono_instances (MonoError *error)
 {
        int count = 64;
        int res;
        void **buf = NULL;
        MonoArray *array;
+       mono_error_init (error);
        do {
                count *= 2;
                g_free (buf);
                buf = g_new (void*, count);
                res = mono_shared_area_instances (buf, count);
        } while (res == count);
-       array = get_string_array (buf, res, TRUE);
+       array = get_string_array (buf, res, TRUE, error);
        g_free (buf);
        return array;
 }
 
 static MonoArray*
-get_cpu_instances (void)
+get_cpu_instances (MonoError *error)
 {
        void **buf = NULL;
        int i, count;
        MonoArray *array;
-
+       mono_error_init (error);
        count = mono_cpu_count () + 1; /* +1 for "_Total" */
        buf = g_new (void*, count);
        for (i = 0; i < count; ++i)
                buf [i] = GINT_TO_POINTER (i - 1); /* -1 => _Total */
-       array = get_string_array (buf, count, FALSE);
+       array = get_string_array (buf, count, FALSE, error);
        g_free (buf);
        mono_array_setref (array, 0, mono_string_new (mono_domain_get (), "_Total"));
        return array;
 }
 
 static MonoArray*
-get_processes_instances (void)
+get_processes_instances (MonoError *error)
 {
        MonoArray *array;
        int count = 0;
        void **buf = mono_process_list (&count);
+       mono_error_init (error);
        if (!buf)
-               return get_string_array (NULL, 0, FALSE);
-       array = get_string_array (buf, count, TRUE);
+               return get_string_array (NULL, 0, FALSE, error);
+       array = get_string_array (buf, count, TRUE, error);
        g_free (buf);
        return array;
 }
 
 static MonoArray*
-get_networkinterface_instances (void)
+get_networkinterface_instances (MonoError *error)
 {
        MonoArray *array;
        int count = 0;
+       mono_error_init (error);
        void **buf = mono_networkinterface_list (&count);
        if (!buf)
-               return get_string_array_of_strings (NULL, 0);
-       array = get_string_array_of_strings (buf, count);
+               return get_string_array_of_strings (NULL, 0, error);
+       array = get_string_array_of_strings (buf, count, error);
        g_strfreev ((char **) buf);
        return array;
 }
 
 static MonoArray*
-get_custom_instances (MonoString *category)
+get_custom_instances (MonoString *category, MonoError *error)
 {
        SharedCategory *scat;
+       mono_error_init (error);
        scat = find_custom_category (category);
        if (scat) {
                GSList *list = get_custom_instances_list (scat);
                GSList *tmp;
                int i = 0;
-               MonoArray *array = mono_array_new (mono_domain_get (), mono_get_string_class (), g_slist_length (list));
+               MonoArray *array = mono_array_new_checked (mono_domain_get (), mono_get_string_class (), g_slist_length (list), error);
+               if (!is_ok (error)) {
+                       g_slist_free (list);
+                       return NULL;
+               }
                for (tmp = list; tmp; tmp = tmp->next) {
                        SharedInstance *inst = (SharedInstance *)tmp->data;
                        mono_array_setref (array, i, mono_string_new (mono_domain_get (), inst->instance_name));
@@ -1764,31 +1803,46 @@ get_custom_instances (MonoString *category)
                g_slist_free (list);
                return array;
        }
-       return mono_array_new (mono_domain_get (), mono_get_string_class (), 0);
+       return mono_array_new_checked (mono_domain_get (), mono_get_string_class (), 0, error);
 }
 
 MonoArray*
 mono_perfcounter_instance_names (MonoString *category, MonoString *machine)
 {
+       MonoError error;
        const CategoryDesc* cat;
-       if (mono_string_compare_ascii (machine, "."))
-               return mono_array_new (mono_domain_get (), mono_get_string_class (), 0);
+       MonoArray *result = NULL;
+       if (mono_string_compare_ascii (machine, ".")) {
+               result = mono_array_new_checked (mono_domain_get (), mono_get_string_class (), 0, &error);
+               mono_error_set_pending_exception (&error);
+               return result;
+       }
+       
        cat = find_category (category);
-       if (!cat)
-               return get_custom_instances (category);
+       if (!cat) {
+               MonoArray *result = get_custom_instances (category, &error);
+               mono_error_set_pending_exception (&error);
+               return result;
+       }
        switch (cat->instance_type) {
        case MonoInstance:
-               return get_mono_instances ();
+               result = get_mono_instances (&error);
+               break;
        case CPUInstance:
-               return get_cpu_instances ();
+               result = get_cpu_instances (&error);
+               break;
        case ProcessInstance:
-               return get_processes_instances ();
+               result = get_processes_instances (&error);
+               break;
        case NetworkInterfaceInstance:
-               return get_networkinterface_instances ();
+               result = get_networkinterface_instances (&error);
+               break;
        case ThreadInstance:
        default:
-               return mono_array_new (mono_domain_get (), mono_get_string_class (), 0);
+               result = mono_array_new_checked (mono_domain_get (), mono_get_string_class (), 0, &error);
        }
+       mono_error_set_pending_exception (&error);
+       return result;
 }
 
 typedef struct {
index d59d624782a8d781bacbf49472ca26a457a185b8..b27da358575742b762965b76338ececeb5248327 100644 (file)
@@ -391,10 +391,10 @@ ves_icall_System_Security_Principal_WindowsIdentity_GetUserToken (MonoString *us
 MonoArray*
 ves_icall_System_Security_Principal_WindowsIdentity_GetRoles (gpointer token) 
 {
+       MonoError error;
        MonoArray *array = NULL;
        MonoDomain *domain = mono_domain_get (); 
 #ifdef HOST_WIN32
-       MonoError error;
        gint32 size = 0;
 
        GetTokenInformation (token, TokenGroups, NULL, size, (PDWORD)&size);
@@ -404,7 +404,11 @@ ves_icall_System_Security_Principal_WindowsIdentity_GetRoles (gpointer token)
                        int i=0;
                        int num = tg->GroupCount;
 
-                       array = mono_array_new (domain, mono_get_string_class (), num);
+                       array = mono_array_new_checked (domain, mono_get_string_class (), num, &error);
+                       if (mono_error_set_pending_exception (&error)) {
+                               g_free (tg);
+                               return NULL;
+                       }
 
                        for (i=0; i < num; i++) {
                                gint32 size = 0;
@@ -431,7 +435,8 @@ ves_icall_System_Security_Principal_WindowsIdentity_GetRoles (gpointer token)
 #endif
        if (!array) {
                /* return empty array of string, i.e. string [0] */
-               array = mono_array_new (domain, mono_get_string_class (), 0);
+               array = mono_array_new_checked (domain, mono_get_string_class (), 0, &error);
+               mono_error_set_pending_exception (&error);
        }
        return array;
 }
index 691d4374674c269d090daa093cc12a1770cc425e..e6fca9fba94f2d7e2762b7aae438b38705c00b62 100644 (file)
                        }; \
                        tmp_klass; })
 /* eclass should be a run-time constant */
-#define mono_array_new_cached(domain, eclass, size) ({ \
-                       MonoError __error;      \
+#define mono_array_new_cached(domain, eclass, size, error) ({  \
                        MonoVTable *__vtable = mono_class_vtable ((domain), mono_array_class_get_cached ((eclass), 1)); \
-                       MonoArray *__arr = mono_array_new_specific_checked (__vtable, (size), &__error);        \
-                       mono_error_raise_exception (&__error); /* FIXME don't raise here */     \
+                       MonoArray *__arr = mono_array_new_specific_checked (__vtable, (size), (error)); \
                        __arr; })
 
 #else
 
 #define mono_class_get_field_from_name_cached(klass,name) mono_class_get_field_from_name ((klass), (name))
 #define mono_array_class_get_cached(eclass,rank) mono_array_class_get ((eclass), (rank))
-#define mono_array_new_cached(domain, eclass, size) mono_array_new_specific (mono_class_vtable ((domain), mono_array_class_get_cached ((eclass), 1)), (size))
+#define mono_array_new_cached(domain, eclass, size, error) mono_array_new_specific_checked (mono_class_vtable ((domain), mono_array_class_get_cached ((eclass), 1)), (size), (error))
 
 #endif
 
@@ -201,23 +199,24 @@ typedef struct {
 
 struct _MonoException {
        MonoObject object;
+       MonoString *class_name;
+       MonoString *message;
+       MonoObject *_data;
+       MonoObject *inner_ex;
+       MonoString *help_link;
        /* Stores the IPs and the generic sharing infos
           (vtable/MRGCTX) of the frames. */
        MonoArray  *trace_ips;
-       MonoObject *inner_ex;
-       MonoString *message;
-       MonoString *help_link;
-       MonoString *class_name;
        MonoString *stack_trace;
        MonoString *remote_stack_trace;
        gint32      remote_stack_index;
+       /* Dynamic methods referenced by the stack trace */
+       MonoObject *dynamic_methods;
        gint32      hresult;
        MonoString *source;
-       MonoObject *_data;
+       MonoObject *serialization_manager;
        MonoObject *captured_traces;
        MonoArray  *native_trace_ips;
-       /* Dynamic methods referenced by the stack trace */
-       MonoObject *dynamic_methods;
 };
 
 typedef struct {
@@ -601,7 +600,7 @@ MonoObject *
 ves_icall_System_Runtime_Remoting_Messaging_AsyncResult_Invoke (MonoAsyncResult *ares);
 
 MonoWaitHandle *
-mono_wait_handle_new       (MonoDomain *domain, HANDLE handle);
+mono_wait_handle_new       (MonoDomain *domain, HANDLE handle, MonoError *error);
 
 HANDLE
 mono_wait_handle_get_handle (MonoWaitHandle *handle);
@@ -619,7 +618,7 @@ mono_method_call_message_new (MonoMethod *method, gpointer *params, MonoMethod *
                              MonoDelegate **cb, MonoObject **state);
 
 void
-mono_method_return_message_restore (MonoMethod *method, gpointer *params, MonoArray *out_args);
+mono_method_return_message_restore (MonoMethod *method, gpointer *params, MonoArray *out_args, MonoError *error);
 
 void
 mono_delegate_ctor_with_method (MonoObject *this_obj, MonoObject *target, gpointer addr, MonoMethod *method);
@@ -1417,7 +1416,10 @@ mono_string_to_utf8_image (MonoImage *image, MonoString *s, MonoError *error);
 
 
 MonoArray*
-mono_array_clone_in_domain (MonoDomain *domain, MonoArray *array);
+mono_array_clone_in_domain (MonoDomain *domain, MonoArray *array, MonoError *error);
+
+MonoArray*
+mono_array_clone_checked (MonoArray *array, MonoError *error);
 
 void
 mono_array_full_copy (MonoArray *src, MonoArray *dest);
@@ -1425,12 +1427,18 @@ mono_array_full_copy (MonoArray *src, MonoArray *dest);
 gboolean
 mono_array_calc_byte_len (MonoClass *klass, uintptr_t len, uintptr_t *res);
 
+MonoArray*
+mono_array_new_checked (MonoDomain *domain, MonoClass *eclass, uintptr_t n, MonoError *error);
+
 MonoArray*
 mono_array_new_full_checked (MonoDomain *domain, MonoClass *array_class, uintptr_t *lengths, intptr_t *lower_bounds, MonoError *error);
 
 MonoArray*
 mono_array_new_specific_checked (MonoVTable *vtable, uintptr_t n, MonoError *error);
 
+MonoArray*
+ves_icall_array_new (MonoDomain *domain, MonoClass *eclass, uintptr_t n);
+
 MonoArray*
 ves_icall_array_new_specific (MonoVTable *vtable, uintptr_t n);
 
@@ -1443,6 +1451,26 @@ mono_remote_class_vtable (MonoDomain *domain, MonoRemoteClass *remote_class, Mon
 
 void
 mono_upgrade_remote_class (MonoDomain *domain, MonoObject *tproxy, MonoClass *klass);
+
+void*
+mono_load_remote_field_checked (MonoObject *this_obj, MonoClass *klass, MonoClassField *field, void **res, MonoError *error);
+
+MonoObject *
+mono_load_remote_field_new_icall (MonoObject *this_obj, MonoClass *klass, MonoClassField *field);
+
+MonoObject *
+mono_load_remote_field_new_checked (MonoObject *this_obj, MonoClass *klass, MonoClassField *field, MonoError *error);
+
+gboolean
+mono_store_remote_field_checked (MonoObject *this_obj, MonoClass *klass, MonoClassField *field, void* val, MonoError *error);
+
+void
+mono_store_remote_field_new_icall (MonoObject *this_obj, MonoClass *klass, MonoClassField *field, MonoObject *arg);
+
+gboolean
+mono_store_remote_field_new_checked (MonoObject *this_obj, MonoClass *klass, MonoClassField *field, MonoObject *arg, MonoError *error);
+
+
 #endif
 
 gpointer
@@ -1543,7 +1571,7 @@ gsize*
 mono_class_compute_bitmap (MonoClass *klass, gsize *bitmap, int size, int offset, int *max_set, gboolean static_fields);
 
 MonoObject*
-mono_object_xdomain_representation (MonoObject *obj, MonoDomain *target_domain, MonoObject **exc);
+mono_object_xdomain_representation (MonoObject *obj, MonoDomain *target_domain, MonoError *error);
 
 gboolean
 mono_class_is_reflection_method_or_constructor (MonoClass *klass);
@@ -1585,6 +1613,12 @@ mono_vtable_get_static_field_data (MonoVTable *vt);
 MonoObject *
 mono_field_get_value_object_checked (MonoDomain *domain, MonoClassField *field, MonoObject *obj, MonoError *error);
 
+gboolean
+mono_property_set_value_checked (MonoProperty *prop, void *obj, void **params, MonoError *error);
+
+MonoObject*
+mono_property_get_value_checked (MonoProperty *prop, void *obj, void **params, MonoError *error);
+
 char *
 mono_string_to_utf8_ignore (MonoString *s);
 
@@ -1619,7 +1653,7 @@ gboolean
 mono_error_set_pending_exception (MonoError *error);
 
 MonoArray *
-mono_glist_to_array (GList *list, MonoClass *eclass);
+mono_glist_to_array (GList *list, MonoClass *eclass, MonoError *error);
 
 MonoObject *
 mono_object_new_checked (MonoDomain *domain, MonoClass *klass, MonoError *error);
@@ -1645,6 +1679,9 @@ mono_object_isinst_mbyref_checked   (MonoObject *obj, MonoClass *klass, MonoErro
 MonoString *
 mono_string_new_size_checked (MonoDomain *domain, gint32 len, MonoError *error);
 
+MonoString*
+mono_string_new_len_checked (MonoDomain *domain, const char *text, guint length, MonoError *error);
+
 MonoString*
 mono_string_new_checked (MonoDomain *domain, const char *text, MonoError *merror);
 
@@ -1661,6 +1698,9 @@ MonoObject*
 mono_runtime_invoke_checked (MonoMethod *method, void *obj, void **params, MonoError *error);
 
 
+MonoArray*
+mono_runtime_get_main_args_checked (MonoError *error);
+
 #endif /* __MONO_OBJECT_INTERNALS_H__ */
 
 
index dc20b4e83212449db9ba9826eb4a0be57d796369..74268ac9c1cc22d44bb1aaa1bc7ffb85552014c8 100644 (file)
@@ -53,7 +53,7 @@ static void
 get_default_field_value (MonoDomain* domain, MonoClassField *field, void *value);
 
 static MonoString*
-mono_ldstr_metadata_sig (MonoDomain *domain, const char* sig);
+mono_ldstr_metadata_sig (MonoDomain *domain, const char* sig, MonoError *error);
 
 static void
 free_main_args (void);
@@ -628,16 +628,14 @@ mono_compile_method (MonoMethod *method)
 }
 
 gpointer
-mono_runtime_create_jump_trampoline (MonoDomain *domain, MonoMethod *method, gboolean add_sync_wrapper)
+mono_runtime_create_jump_trampoline (MonoDomain *domain, MonoMethod *method, gboolean add_sync_wrapper, MonoError *error)
 {
-       MonoError error;
        gpointer res;
 
        MONO_REQ_GC_NEUTRAL_MODE;
 
-       res = callbacks.create_jump_trampoline (domain, method, add_sync_wrapper, &error);
-       if (!mono_error_ok (&error))
-               mono_error_raise_exception (&error); /* FIXME: Don't raise here */
+       mono_error_init (error);
+       res = callbacks.create_jump_trampoline (domain, method, add_sync_wrapper, error);
        return res;
 }
 
@@ -981,7 +979,7 @@ ves_icall_string_alloc (int length)
 {
        MonoError error;
        MonoString *str = mono_string_new_size_checked (mono_domain_get (), length, &error);
-       mono_error_raise_exception (&error);
+       mono_error_set_pending_exception (&error);
 
        return str;
 }
@@ -3529,6 +3527,7 @@ mono_get_constant_value_from_blob (MonoDomain* domain, MonoTypeEnum type, const
 {
        MONO_REQ_GC_UNSAFE_MODE;
 
+       MonoError error;
        int retval = 0;
        const char *p = blob;
        mono_metadata_decode_blob_size (p, &p);
@@ -3559,7 +3558,8 @@ mono_get_constant_value_from_blob (MonoDomain* domain, MonoTypeEnum type, const
                readr8 (p, (double*) value);
                break;
        case MONO_TYPE_STRING:
-               *(gpointer*) value = mono_ldstr_metadata_sig (domain, blob);
+               *(gpointer*) value = mono_ldstr_metadata_sig (domain, blob, &error);
+               mono_error_raise_exception (&error); /* FIXME don't raise here */
                break;
        case MONO_TYPE_CLASS:
                *(gpointer*) value = NULL;
@@ -3656,10 +3656,37 @@ mono_property_set_value (MonoProperty *prop, void *obj, void **params, MonoObjec
        if (exc && *exc == NULL && !mono_error_ok (&error)) {
                *exc = (MonoObject*) mono_error_convert_to_exception (&error);
        } else {
-               mono_error_raise_exception (&error); /* FIXME don't raise here */
+               mono_error_cleanup (&error);
        }
 }
 
+/**
+ * mono_property_set_value_checked:
+ * @prop: MonoProperty to set
+ * @obj: instance object on which to act
+ * @params: parameters to pass to the propery
+ * @error: set on error
+ *
+ * Invokes the property's set method with the given arguments on the
+ * object instance obj (or NULL for static properties). 
+ * 
+ * Returns: TRUE on success.  On failure returns FALSE and sets @error.
+ * If an exception is thrown, it will be caught and returned via @error.
+ */
+gboolean
+mono_property_set_value_checked (MonoProperty *prop, void *obj, void **params, MonoError *error)
+{
+       MONO_REQ_GC_UNSAFE_MODE;
+
+       MonoObject *exc;
+
+       mono_error_init (error);
+       do_runtime_invoke (prop->set, obj, params, &exc, error);
+       if (exc != NULL && is_ok (error))
+               mono_error_set_exception_instance (error, (MonoException*)exc);
+       return is_ok (error);
+}
+
 /**
  * mono_property_get_value:
  * @prop: MonoProperty to fetch
@@ -3687,12 +3714,43 @@ mono_property_get_value (MonoProperty *prop, void *obj, void **params, MonoObjec
        if (exc && *exc == NULL && !mono_error_ok (&error)) {
                *exc = (MonoObject*) mono_error_convert_to_exception (&error);
        } else {
-               mono_error_raise_exception (&error); /* FIXME don't raise here */
+               mono_error_cleanup (&error); /* FIXME don't raise here */
        }
 
        return val;
 }
 
+/**
+ * mono_property_get_value_checked:
+ * @prop: MonoProperty to fetch
+ * @obj: instance object on which to act
+ * @params: parameters to pass to the propery
+ * @error: set on error
+ *
+ * Invokes the property's get method with the given arguments on the
+ * object instance obj (or NULL for static properties). 
+ * 
+ * If an exception is thrown, you can't use the
+ * MonoObject* result from the function.  The exception will be propagated via @error.
+ *
+ * Returns: the value from invoking the get method on the property. On
+ * failure returns NULL and sets @error.
+ */
+MonoObject*
+mono_property_get_value_checked (MonoProperty *prop, void *obj, void **params, MonoError *error)
+{
+       MONO_REQ_GC_UNSAFE_MODE;
+
+       MonoObject *exc;
+       MonoObject *val = do_runtime_invoke (prop->get, obj, params, &exc, error);
+       if (exc != NULL && !is_ok (error))
+               mono_error_set_exception_instance (error, (MonoException*) exc);
+       if (!is_ok (error))
+               val = NULL;
+       return val;
+}
+
+
 /*
  * mono_nullable_init:
  * @buf: The nullable structure to initialize.
@@ -3883,12 +3941,30 @@ MonoArray*
 mono_runtime_get_main_args (void)
 {
        MONO_REQ_GC_UNSAFE_MODE;
+       MonoError error;
+       MonoArray *result = mono_runtime_get_main_args_checked (&error);
+       mono_error_assert_ok (&error);
+       return result;
+}
 
+/**
+ * mono_runtime_get_main_args:
+ * @error: set on error
+ *
+ * Returns: a MonoArray with the arguments passed to the main
+ * program. On failure returns NULL and sets @error.
+ */
+MonoArray*
+mono_runtime_get_main_args_checked (MonoError *error)
+{
        MonoArray *res;
        int i;
        MonoDomain *domain = mono_domain_get ();
 
-       res = (MonoArray*)mono_array_new (domain, mono_defaults.string_class, num_main_args);
+       mono_error_init (error);
+
+       res = (MonoArray*)mono_array_new_checked (domain, mono_defaults.string_class, num_main_args, error);
+       return_val_if_nok (error, NULL);
 
        for (i = 0; i < num_main_args; ++i)
                mono_array_setref (res, i, mono_string_new (domain, main_args [i]));
@@ -3964,6 +4040,7 @@ mono_runtime_run_main (MonoMethod *method, int argc, char* argv[],
 {
        MONO_REQ_GC_UNSAFE_MODE;
 
+       MonoError error;
        int i;
        MonoArray *args = NULL;
        MonoDomain *domain = mono_domain_get ();
@@ -4031,7 +4108,8 @@ mono_runtime_run_main (MonoMethod *method, int argc, char* argv[],
        }
 
        if (sig->param_count) {
-               args = (MonoArray*)mono_array_new (domain, mono_defaults.string_class, argc);
+               args = (MonoArray*)mono_array_new_checked (domain, mono_defaults.string_class, argc, &error);
+               mono_error_assert_ok (&error);
                for (i = 0; i < argc; ++i) {
                        /* The encodings should all work, given that
                         * we've checked all these args for the
@@ -4043,7 +4121,8 @@ mono_runtime_run_main (MonoMethod *method, int argc, char* argv[],
                        g_free (str);
                }
        } else {
-               args = (MonoArray*)mono_array_new (domain, mono_defaults.string_class, 0);
+               args = (MonoArray*)mono_array_new_checked (domain, mono_defaults.string_class, 0, &error);
+               mono_error_assert_ok (&error);
        }
        
        mono_assembly_set_main (method->klass->image->assembly);
@@ -4124,40 +4203,37 @@ deserialize_object (MonoObject *obj, gboolean *failure, MonoObject **exc)
 
 #ifndef DISABLE_REMOTING
 static MonoObject*
-make_transparent_proxy (MonoObject *obj, gboolean *failure, MonoObject **exc)
+make_transparent_proxy (MonoObject *obj, MonoError *error)
 {
        MONO_REQ_GC_UNSAFE_MODE;
 
        static MonoMethod *get_proxy_method;
 
-       MonoError error;
        MonoDomain *domain = mono_domain_get ();
        MonoRealProxy *real_proxy;
        MonoReflectionType *reflection_type;
        MonoTransparentProxy *transparent_proxy;
 
+       mono_error_init (error);
+
        if (!get_proxy_method)
                get_proxy_method = mono_class_get_method_from_name (mono_defaults.real_proxy_class, "GetTransparentProxy", 0);
 
        g_assert (mono_class_is_marshalbyref (obj->vtable->klass));
 
-       real_proxy = (MonoRealProxy*) mono_object_new_checked (domain, mono_defaults.real_proxy_class, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
-       reflection_type = mono_type_get_object_checked (domain, &obj->vtable->klass->byval_arg, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
+       real_proxy = (MonoRealProxy*) mono_object_new_checked (domain, mono_defaults.real_proxy_class, error);
+       return_val_if_nok (error, NULL);
+       reflection_type = mono_type_get_object_checked (domain, &obj->vtable->klass->byval_arg, error);
+       return_val_if_nok (error, NULL);
 
        MONO_OBJECT_SETREF (real_proxy, class_to_proxy, reflection_type);
        MONO_OBJECT_SETREF (real_proxy, unwrapped_server, obj);
 
-       *exc = NULL;
+       MonoObject *exc = NULL;
 
-       transparent_proxy = (MonoTransparentProxy*) mono_runtime_try_invoke (get_proxy_method, real_proxy, NULL, exc, &error);
-       if (*exc == NULL && !mono_error_ok (&error))
-               *exc = (MonoObject*) mono_error_convert_to_exception (&error); /* FIXME change make_transparent_proxy outarg to MonoError */
-       else
-               mono_error_cleanup (&error);
-       if (*exc)
-               *failure = TRUE;
+       transparent_proxy = (MonoTransparentProxy*) mono_runtime_try_invoke (get_proxy_method, real_proxy, NULL, &exc, error);
+       if (exc != NULL && is_ok (error))
+               mono_error_set_exception_instance (error, (MonoException*)exc);
 
        return (MonoObject*) transparent_proxy;
 }
@@ -4167,7 +4243,7 @@ make_transparent_proxy (MonoObject *obj, gboolean *failure, MonoObject **exc)
  * mono_object_xdomain_representation
  * @obj: an object
  * @target_domain: a domain
- * @exc: pointer to a MonoObject*
+ * @error: set on error.
  *
  * Creates a representation of obj in the domain target_domain.  This
  * is either a copy of obj arrived through via serialization and
@@ -4175,36 +4251,37 @@ make_transparent_proxy (MonoObject *obj, gboolean *failure, MonoObject **exc)
  * serializable or marshal by ref.  obj must not be in target_domain.
  *
  * If the object cannot be represented in target_domain, NULL is
- * returned and *exc is set to an appropriate exception.
+ * returned and @error is set appropriately.
  */
 MonoObject*
-mono_object_xdomain_representation (MonoObject *obj, MonoDomain *target_domain, MonoObject **exc)
+mono_object_xdomain_representation (MonoObject *obj, MonoDomain *target_domain, MonoError *error)
 {
        MONO_REQ_GC_UNSAFE_MODE;
 
+       mono_error_init (error);
        MonoObject *deserialized = NULL;
-       gboolean failure = FALSE;
-
-       g_assert (exc != NULL);
-       *exc = NULL;
 
 #ifndef DISABLE_REMOTING
        if (mono_class_is_marshalbyref (mono_object_class (obj))) {
-               deserialized = make_transparent_proxy (obj, &failure, exc);
+               deserialized = make_transparent_proxy (obj, error);
        } 
        else
 #endif
        {
+               gboolean failure = FALSE;
                MonoDomain *domain = mono_domain_get ();
                MonoObject *serialized;
+               MonoObject *exc = NULL;
 
                mono_domain_set_internal_with_options (mono_object_domain (obj), FALSE);
-               serialized = serialize_object (obj, &failure, exc);
+               serialized = serialize_object (obj, &failure, &exc);
                mono_domain_set_internal_with_options (target_domain, FALSE);
                if (!failure)
-                       deserialized = deserialize_object (serialized, &failure, exc);
+                       deserialized = deserialize_object (serialized, &failure, &exc);
                if (domain != target_domain)
                        mono_domain_set_internal_with_options (domain, FALSE);
+               if (failure)
+                       mono_error_set_exception_instance (error, (MonoException*)exc);
        }
 
        return deserialized;
@@ -4257,14 +4334,15 @@ call_unhandled_exception_delegate (MonoDomain *domain, MonoObject *delegate, Mon
        g_assert (domain == mono_object_domain (domain->domain));
 
        if (mono_object_domain (exc) != domain) {
-               MonoObject *serialization_exc;
+               MonoError error;
 
-               exc = mono_object_xdomain_representation (exc, domain, &serialization_exc);
+               exc = mono_object_xdomain_representation (exc, domain, &error);
                if (!exc) {
-                       if (serialization_exc) {
-                               MonoObject *dummy;
-                               exc = mono_object_xdomain_representation (serialization_exc, domain, &dummy);
-                               g_assert (exc);
+                       if (!is_ok (&error)) {
+                               MonoError inner_error;
+                               MonoException *serialization_exc = mono_error_convert_to_exception (&error);
+                               exc = mono_object_xdomain_representation ((MonoObject*)serialization_exc, domain, &inner_error);
+                               mono_error_assert_ok (&inner_error);
                        } else {
                                exc = (MonoObject*) mono_exception_from_name_msg (mono_get_corlib (),
                                                "System.Runtime.Serialization", "SerializationException",
@@ -4778,7 +4856,7 @@ mono_object_new (MonoDomain *domain, MonoClass *klass)
 
        MonoObject * result = mono_object_new_checked (domain, klass, &error);
 
-       mono_error_raise_exception (&error);
+       mono_error_cleanup (&error);
        return result;
 }
 
@@ -4791,7 +4869,7 @@ ves_icall_object_new (MonoDomain *domain, MonoClass *klass)
 
        MonoObject * result = mono_object_new_checked (domain, klass, &error);
 
-       mono_error_raise_exception (&error);
+       mono_error_set_pending_exception (&error);
        return result;
 }
 
@@ -4861,7 +4939,7 @@ mono_object_new_specific (MonoVTable *vtable)
 {
        MonoError error;
        MonoObject *o = mono_object_new_specific_checked (vtable, &error);
-       mono_error_raise_exception (&error);
+       mono_error_cleanup (&error);
 
        return o;
 }
@@ -4915,7 +4993,7 @@ ves_icall_object_new_specific (MonoVTable *vtable)
 {
        MonoError error;
        MonoObject *o = mono_object_new_specific_checked (vtable, &error);
-       mono_error_raise_exception (&error);
+       mono_error_set_pending_exception (&error);
 
        return o;
 }
@@ -4939,7 +5017,7 @@ mono_object_new_alloc_specific (MonoVTable *vtable)
 {
        MonoError error;
        MonoObject *o = mono_object_new_alloc_specific_checked (vtable, &error);
-       mono_error_raise_exception (&error);
+       mono_error_cleanup (&error);
 
        return o;
 }
@@ -4999,7 +5077,7 @@ mono_object_new_fast (MonoVTable *vtable)
 {
        MonoError error;
        MonoObject *o = mono_object_new_fast_checked (vtable, &error);
-       mono_error_raise_exception (&error);
+       mono_error_cleanup (&error);
 
        return o;
 }
@@ -5043,7 +5121,7 @@ ves_icall_object_new_fast (MonoVTable *vtable)
 {
        MonoError error;
        MonoObject *o = mono_object_new_fast_checked (vtable, &error);
-       mono_error_raise_exception (&error);
+       mono_error_set_pending_exception (&error);
 
        return o;
 }
@@ -5125,11 +5203,11 @@ mono_object_new_from_token  (MonoDomain *domain, MonoImage *image, guint32 token
        MonoClass *klass;
 
        klass = mono_class_get_checked (image, token, &error);
-       g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
+       mono_error_assert_ok (&error);
        
        result = mono_object_new_checked (domain, klass, &error);
 
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
+       mono_error_cleanup (&error);
        return result;
        
 }
@@ -5146,7 +5224,7 @@ mono_object_clone (MonoObject *obj)
 {
        MonoError error;
        MonoObject *o = mono_object_clone_checked (obj, &error);
-       mono_error_raise_exception (&error);
+       mono_error_cleanup (&error);
 
        return o;
 }
@@ -5164,7 +5242,7 @@ mono_object_clone_checked (MonoObject *obj, MonoError *error)
        size = obj->vtable->klass->instance_size;
 
        if (obj->vtable->klass->rank)
-               return (MonoObject*)mono_array_clone ((MonoArray*)obj);
+               return (MonoObject*)mono_array_clone_checked ((MonoArray*)obj, error);
 
        o = (MonoObject *)mono_gc_alloc_obj (obj->vtable, size);
 
@@ -5219,25 +5297,27 @@ mono_array_full_copy (MonoArray *src, MonoArray *dest)
  * mono_array_clone_in_domain:
  * @domain: the domain in which the array will be cloned into
  * @array: the array to clone
+ * @error: set on error
  *
  * This routine returns a copy of the array that is hosted on the
- * specified MonoDomain.
+ * specified MonoDomain.  On failure returns NULL and sets @error.
  */
 MonoArray*
-mono_array_clone_in_domain (MonoDomain *domain, MonoArray *array)
+mono_array_clone_in_domain (MonoDomain *domain, MonoArray *array, MonoError *error)
 {
        MONO_REQ_GC_UNSAFE_MODE;
 
-       MonoError error;
        MonoArray *o;
        uintptr_t size, i;
        uintptr_t *sizes;
        MonoClass *klass = array->obj.vtable->klass;
 
+       mono_error_init (error);
+
        if (array->bounds == NULL) {
                size = mono_array_length (array);
-               o = mono_array_new_full_checked (domain, klass, &size, NULL, &error);
-               mono_error_raise_exception (&error); /* FIXME don't raise here */
+               o = mono_array_new_full_checked (domain, klass, &size, NULL, error);
+               return_val_if_nok (error, NULL);
 
                size *= mono_array_element_size (klass);
 #ifdef HAVE_SGEN_GC
@@ -5262,8 +5342,8 @@ mono_array_clone_in_domain (MonoDomain *domain, MonoArray *array)
                size *= array->bounds [i].length;
                sizes [i + klass->rank] = array->bounds [i].lower_bound;
        }
-       o = mono_array_new_full_checked (domain, klass, sizes, (intptr_t*)sizes + klass->rank, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
+       o = mono_array_new_full_checked (domain, klass, sizes, (intptr_t*)sizes + klass->rank, error);
+       return_val_if_nok (error, NULL);
 #ifdef HAVE_SGEN_GC
        if (klass->element_class->valuetype) {
                if (klass->element_class->has_references)
@@ -5291,7 +5371,26 @@ mono_array_clone (MonoArray *array)
 {
        MONO_REQ_GC_UNSAFE_MODE;
 
-       return mono_array_clone_in_domain (((MonoObject *)array)->vtable->domain, array);
+       MonoError error;
+       MonoArray *result = mono_array_clone_checked (array, &error);
+       mono_error_cleanup (&error);
+       return result;
+}
+
+/**
+ * mono_array_clone_checked:
+ * @array: the array to clone
+ * @error: set on error
+ *
+ * Returns: A newly created array who is a shallow copy of @array.  On
+ * failure returns NULL and sets @error.
+ */
+MonoArray*
+mono_array_clone_checked (MonoArray *array, MonoError *error)
+{
+
+       MONO_REQ_GC_UNSAFE_MODE;
+       return mono_array_clone_in_domain (((MonoObject *)array)->vtable->domain, array, error);
 }
 
 /* helper macros to check for overflow when calculating the size of arrays */
@@ -5348,7 +5447,7 @@ mono_array_new_full (MonoDomain *domain, MonoClass *array_class, uintptr_t *leng
 {
        MonoError error;
        MonoArray *array = mono_array_new_full_checked (domain, array_class, lengths, lower_bounds, &error);
-       mono_error_raise_exception (&error);
+       mono_error_cleanup (&error);
 
        return array;
 }
@@ -5460,17 +5559,43 @@ mono_array_new (MonoDomain *domain, MonoClass *eclass, uintptr_t n)
        MONO_REQ_GC_UNSAFE_MODE;
 
        MonoError error;
+       MonoArray *result = mono_array_new_checked (domain, eclass, n, &error);
+       mono_error_cleanup (&error);
+       return result;
+}
+
+/**
+ * mono_array_new_checked:
+ * @domain: domain where the object is created
+ * @eclass: element class
+ * @n: number of array elements
+ * @error: set on error
+ *
+ * This routine creates a new szarray with @n elements of type @eclass.
+ * On failure returns NULL and sets @error.
+ */
+MonoArray *
+mono_array_new_checked (MonoDomain *domain, MonoClass *eclass, uintptr_t n, MonoError *error)
+{
        MonoClass *ac;
-       MonoArray *arr;
+
+       mono_error_init (error);
 
        ac = mono_array_class_get (eclass, 1);
        g_assert (ac);
 
-       MonoVTable *vtable = mono_class_vtable_full (domain, ac, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
+       MonoVTable *vtable = mono_class_vtable_full (domain, ac, error);
+       return_val_if_nok (error, NULL);
 
-       arr = mono_array_new_specific_checked (vtable, n, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
+       return mono_array_new_specific_checked (vtable, n, error);
+}
+
+MonoArray*
+ves_icall_array_new (MonoDomain *domain, MonoClass *eclass, uintptr_t n)
+{
+       MonoError error;
+       MonoArray *arr = mono_array_new_checked (domain, eclass, n, &error);
+       mono_error_set_pending_exception (&error);
 
        return arr;
 }
@@ -5488,7 +5613,7 @@ mono_array_new_specific (MonoVTable *vtable, uintptr_t n)
 {
        MonoError error;
        MonoArray *arr = mono_array_new_specific_checked (vtable, n, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
+       mono_error_cleanup (&error);
 
        return arr;
 }
@@ -5527,7 +5652,7 @@ ves_icall_array_new_specific (MonoVTable *vtable, uintptr_t n)
 {
        MonoError error;
        MonoArray *arr = mono_array_new_specific_checked (vtable, n, &error);
-       mono_error_raise_exception (&error);
+       mono_error_set_pending_exception (&error);
 
        return arr;
 }
@@ -5547,7 +5672,7 @@ mono_string_new_utf16 (MonoDomain *domain, const guint16 *text, gint32 len)
        MonoError error;
        MonoString *res = NULL;
        res = mono_string_new_utf16_checked (domain, text, len, &error);
-       mono_error_raise_exception (&error);
+       mono_error_cleanup (&error);
 
        return res;
 }
@@ -5581,21 +5706,22 @@ mono_string_new_utf16_checked (MonoDomain *domain, const guint16 *text, gint32 l
  * mono_string_new_utf32:
  * @text: a pointer to an utf32 string
  * @len: the length of the string
+ * @error: set on failure.
  *
- * Returns: A newly created string object which contains @text.
+ * Returns: A newly created string object which contains @text. On failure returns NULL and sets @error.
  */
-MonoString *
-mono_string_new_utf32 (MonoDomain *domain, const mono_unichar4 *text, gint32 len)
+static MonoString *
+mono_string_new_utf32_checked (MonoDomain *domain, const mono_unichar4 *text, gint32 len, MonoError *error)
 {
        MONO_REQ_GC_UNSAFE_MODE;
 
-       MonoError error;
        MonoString *s;
        mono_unichar2 *utf16_output = NULL;
        gint32 utf16_len = 0;
        GError *gerror = NULL;
        glong items_written;
        
+       mono_error_init (error);
        utf16_output = g_ucs4_to_utf16 (text, len, NULL, &items_written, &gerror);
        
        if (gerror)
@@ -5603,8 +5729,8 @@ mono_string_new_utf32 (MonoDomain *domain, const mono_unichar4 *text, gint32 len
 
        while (utf16_output [utf16_len]) utf16_len++;
        
-       s = mono_string_new_size_checked (domain, utf16_len, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
+       s = mono_string_new_size_checked (domain, utf16_len, error);
+       return_val_if_nok (error, NULL);
 
        memcpy (mono_string_chars (s), utf16_output, utf16_len * 2);
 
@@ -5613,6 +5739,22 @@ mono_string_new_utf32 (MonoDomain *domain, const mono_unichar4 *text, gint32 len
        return s;
 }
 
+/**
+ * mono_string_new_utf32:
+ * @text: a pointer to an utf32 string
+ * @len: the length of the string
+ *
+ * Returns: A newly created string object which contains @text.
+ */
+MonoString *
+mono_string_new_utf32 (MonoDomain *domain, const mono_unichar4 *text, gint32 len)
+{
+       MonoError error;
+       MonoString *result = mono_string_new_utf32_checked (domain, text, len, &error);
+       mono_error_cleanup (&error);
+       return result;
+}
+
 /**
  * mono_string_new_size:
  * @text: a pointer to an utf16 string
@@ -5625,7 +5767,7 @@ mono_string_new_size (MonoDomain *domain, gint32 len)
 {
        MonoError error;
        MonoString *str = mono_string_new_size_checked (domain, len, &error);
-       mono_error_raise_exception (&error);
+       mono_error_cleanup (&error);
 
        return str;
 }
@@ -5676,23 +5818,41 @@ mono_string_new_len (MonoDomain *domain, const char *text, guint length)
        MONO_REQ_GC_UNSAFE_MODE;
 
        MonoError error;
+       MonoString *result = mono_string_new_len_checked (domain, text, length, &error);
+       mono_error_cleanup (&error);
+       return result;
+}
+
+/**
+ * mono_string_new_len_checked:
+ * @text: a pointer to an utf8 string
+ * @length: number of bytes in @text to consider
+ * @error: set on error
+ *
+ * Returns: A newly created string object which contains @text. On
+ * failure returns NULL and sets @error.
+ */
+MonoString*
+mono_string_new_len_checked (MonoDomain *domain, const char *text, guint length, MonoError *error)
+{
+       MONO_REQ_GC_UNSAFE_MODE;
+
+       mono_error_init (error);
+
        GError *eg_error = NULL;
        MonoString *o = NULL;
-       guint16 *ut;
+       guint16 *ut = NULL;
        glong items_written;
 
-       mono_error_init (&error);
-
        ut = eg_utf8_to_utf16_with_nuls (text, length, NULL, &items_written, &eg_error);
 
        if (!eg_error)
-               o = mono_string_new_utf16_checked (domain, ut, items_written, &error);
+               o = mono_string_new_utf16_checked (domain, ut, items_written, error);
        else 
                g_error_free (eg_error);
 
        g_free (ut);
 
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
        return o;
 }
 
@@ -5747,7 +5907,6 @@ mono_string_new_checked (MonoDomain *domain, const char *text, MonoError *error)
         g_error_free (eg_error);
 
     g_free (ut);
-    mono_error_raise_exception (error);
     
 /*FIXME g_utf8_get_char, g_utf8_next_char and g_utf8_validate are not part of eglib.*/
 #if 0
@@ -6096,8 +6255,10 @@ mono_object_isinst_mbyref_checked (MonoObject *obj, MonoClass *klass, MonoError
                gpointer pa [2];
 
                im = mono_class_get_method_from_name (rpklass, "CanCastTo", -1);
-               if (!im)
-                       mono_raise_exception (mono_get_exception_not_supported ("Linked away."));
+               if (!im) {
+                       mono_error_set_not_supported (error, "Linked away.");
+                       return NULL;
+               }
                im = mono_object_get_virtual_method (rp, im);
                g_assert (im);
        
@@ -6305,7 +6466,9 @@ mono_ldstr (MonoDomain *domain, MonoImage *image, guint32 idx)
        } else {
                if (!mono_verifier_verify_string_signature (image, idx, NULL))
                        return NULL; /*FIXME we should probably be raising an exception here*/
-               return mono_ldstr_metadata_sig (domain, mono_metadata_user_string (image, idx));
+               MonoString *str = mono_ldstr_metadata_sig (domain, mono_metadata_user_string (image, idx), &error);
+               mono_error_raise_exception (&error); /* FIXME don't raise here */
+               return str;
        }
 }
 
@@ -6313,15 +6476,17 @@ mono_ldstr (MonoDomain *domain, MonoImage *image, guint32 idx)
  * mono_ldstr_metadata_sig
  * @domain: the domain for the string
  * @sig: the signature of a metadata string
+ * @error: set on error
  *
- * Returns: a MonoString for a string stored in the metadata
+ * Returns: a MonoString for a string stored in the metadata. On
+ * failure returns NULL and sets @error.
  */
 static MonoString*
-mono_ldstr_metadata_sig (MonoDomain *domain, const char* sig)
+mono_ldstr_metadata_sig (MonoDomain *domain, const char* sig, MonoError *error)
 {
        MONO_REQ_GC_UNSAFE_MODE;
 
-       MonoError error;
+       mono_error_init (error);
        const char *str = sig;
        MonoString *o, *interned;
        size_t len2;
@@ -6329,8 +6494,8 @@ mono_ldstr_metadata_sig (MonoDomain *domain, const char* sig)
        len2 = mono_metadata_decode_blob_size (str, &str);
        len2 >>= 1;
 
-       o = mono_string_new_utf16_checked (domain, (guint16*)str, len2, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
+       o = mono_string_new_utf16_checked (domain, (guint16*)str, len2, error);
+       return_val_if_nok (error, NULL);
 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
        {
                int i;
@@ -6347,8 +6512,7 @@ mono_ldstr_metadata_sig (MonoDomain *domain, const char* sig)
        if (interned)
                return interned; /* o will get garbage collected */
 
-       o = mono_string_get_pinned (o, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
+       o = mono_string_get_pinned (o, error);
        if (o) {
                ldstr_lock ();
                interned = (MonoString *)mono_g_hash_table_lookup (domain->ldstr_table, o);
@@ -6722,21 +6886,23 @@ mono_raise_exception_with_context (MonoException *ex, MonoContext *ctx)
  * mono_wait_handle_new:
  * @domain: Domain where the object will be created
  * @handle: Handle for the wait handle
+ * @error: set on error.
  *
- * Returns: A new MonoWaitHandle created in the given domain for the given handle
+ * Returns: A new MonoWaitHandle created in the given domain for the
+ * given handle.  On failure returns NULL and sets @rror.
  */
 MonoWaitHandle *
-mono_wait_handle_new (MonoDomain *domain, HANDLE handle)
+mono_wait_handle_new (MonoDomain *domain, HANDLE handle, MonoError *error)
 {
        MONO_REQ_GC_UNSAFE_MODE;
 
-       MonoError error;
        MonoWaitHandle *res;
        gpointer params [1];
        static MonoMethod *handle_set;
 
-       res = (MonoWaitHandle *)mono_object_new_checked (domain, mono_defaults.manualresetevent_class, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
+       mono_error_init (error);
+       res = (MonoWaitHandle *)mono_object_new_checked (domain, mono_defaults.manualresetevent_class, error);
+       return_val_if_nok (error, NULL);
 
        /* Even though this method is virtual, it's safe to invoke directly, since the object type matches.  */
        if (!handle_set)
@@ -6744,9 +6910,7 @@ mono_wait_handle_new (MonoDomain *domain, HANDLE handle)
 
        params [0] = &handle;
 
-       mono_runtime_invoke_checked (handle_set, res, params, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
-
+       mono_runtime_invoke_checked (handle_set, res, params, error);
        return res;
 }
 
@@ -6818,8 +6982,10 @@ mono_async_result_new (MonoDomain *domain, HANDLE handle, MonoObject *state, gpo
        res->data = (void **)data;
        MONO_OBJECT_SETREF (res, object_data, object_data);
        MONO_OBJECT_SETREF (res, async_state, state);
+       MonoWaitHandle *wait_handle = mono_wait_handle_new (domain, handle, &error);
+       mono_error_raise_exception (&error); /* FIXME don't raise here */
        if (handle != NULL)
-               MONO_OBJECT_SETREF (res, handle, (MonoObject *) mono_wait_handle_new (domain, handle));
+               MONO_OBJECT_SETREF (res, handle, (MonoObject *) wait_handle);
 
        res->sync_completed = FALSE;
        res->completed = FALSE;
@@ -6860,7 +7026,8 @@ ves_icall_System_Runtime_Remoting_Messaging_AsyncResult_Invoke (MonoAsyncResult
 
                if (ac->cb_method) {
                        mono_runtime_invoke_checked (ac->cb_method, ac->cb_target, (gpointer*) &ares, &error);
-                       mono_error_raise_exception (&error);
+                       if (mono_error_set_pending_exception (&error))
+                               return NULL;
                }
        }
 
@@ -7328,10 +7495,12 @@ mono_method_call_message_new (MonoMethod *method, gpointer *params, MonoMethod *
  * Restore results from message based processing back to arguments pointers
  */
 void
-mono_method_return_message_restore (MonoMethod *method, gpointer *params, MonoArray *out_args)
+mono_method_return_message_restore (MonoMethod *method, gpointer *params, MonoArray *out_args, MonoError *error)
 {
        MONO_REQ_GC_UNSAFE_MODE;
 
+       mono_error_init (error);
+
        MonoMethodSignature *sig = mono_method_signature (method);
        int i, j, type, size, out_len;
        
@@ -7346,8 +7515,10 @@ mono_method_return_message_restore (MonoMethod *method, gpointer *params, MonoAr
 
                if (pt->byref) {
                        char *arg;
-                       if (j >= out_len)
-                               mono_raise_exception (mono_get_exception_execution_engine ("The proxy call returned an incorrect number of output arguments"));
+                       if (j >= out_len) {
+                               mono_error_set_execution_engine (error, "The proxy call returned an incorrect number of output arguments");
+                               return;
+                       }
 
                        arg = (char *)mono_array_get (out_args, gpointer, j);
                        type = pt->type;
@@ -7394,11 +7565,36 @@ mono_method_return_message_restore (MonoMethod *method, gpointer *params, MonoAr
 gpointer
 mono_load_remote_field (MonoObject *this_obj, MonoClass *klass, MonoClassField *field, gpointer *res)
 {
-       MONO_REQ_GC_UNSAFE_MODE;
-
        MonoError error;
+       gpointer result = mono_load_remote_field_checked (this_obj, klass, field, res, &error);
+       mono_error_cleanup (&error);
+       return result;
+}
+
+/**
+ * mono_load_remote_field_checked:
+ * @this: pointer to an object
+ * @klass: klass of the object containing @field
+ * @field: the field to load
+ * @res: a storage to store the result
+ * @error: set on error
+ *
+ * This method is called by the runtime on attempts to load fields of
+ * transparent proxy objects. @this points to such TP, @klass is the class of
+ * the object containing @field. @res is a storage location which can be
+ * used to store the result.
+ *
+ * Returns: an address pointing to the value of field.  On failure returns NULL and sets @error.
+ */
+gpointer
+mono_load_remote_field_checked (MonoObject *this_obj, MonoClass *klass, MonoClassField *field, gpointer *res, MonoError *error)
+{
+       MONO_REQ_GC_UNSAFE_MODE;
 
        static MonoMethod *getter = NULL;
+
+       mono_error_init (error);
+
        MonoDomain *domain = mono_domain_get ();
        MonoTransparentProxy *tp = (MonoTransparentProxy *) this_obj;
        MonoClass *field_class;
@@ -7417,17 +7613,20 @@ mono_load_remote_field (MonoObject *this_obj, MonoClass *klass, MonoClassField *
        
        if (!getter) {
                getter = mono_class_get_method_from_name (mono_defaults.object_class, "FieldGetter", -1);
-               if (!getter)
-                       mono_raise_exception (mono_get_exception_not_supported ("Linked away."));
+               if (!getter) {
+                       mono_error_set_not_supported (error, "Linked away.");
+                       return NULL;
+               }
        }
        
        field_class = mono_class_from_mono_type (field->type);
 
-       msg = (MonoMethodMessage *)mono_object_new_checked (domain, mono_defaults.mono_method_message_class, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
-       out_args = mono_array_new (domain, mono_defaults.object_class, 1);
-       MonoReflectionMethod *rm = mono_method_get_object_checked (domain, getter, NULL, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
+       msg = (MonoMethodMessage *)mono_object_new_checked (domain, mono_defaults.mono_method_message_class, error);
+       return_val_if_nok (error, NULL);
+       out_args = mono_array_new_checked (domain, mono_defaults.object_class, 1, error);
+       return_val_if_nok (error, NULL);
+       MonoReflectionMethod *rm = mono_method_get_object_checked (domain, getter, NULL, error);
+       return_val_if_nok (error, NULL);
        mono_message_init (domain, msg, rm, out_args);
 
        full_name = mono_type_get_full_name (klass);
@@ -7435,15 +7634,18 @@ mono_load_remote_field (MonoObject *this_obj, MonoClass *klass, MonoClassField *
        mono_array_setref (msg->args, 1, mono_string_new (domain, mono_field_get_name (field)));
        g_free (full_name);
 
-       mono_remoting_invoke ((MonoObject *)(tp->rp), msg, &exc, &out_args, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
+       mono_remoting_invoke ((MonoObject *)(tp->rp), msg, &exc, &out_args, error);
+       return_val_if_nok (error, NULL);
 
-       if (exc) mono_raise_exception ((MonoException *)exc);
+       if (exc) {
+               mono_error_set_exception_instance (error, (MonoException *)exc);
+               return NULL;
+       }
 
        if (mono_array_length (out_args) == 0)
                return NULL;
 
-       *res = mono_array_get (out_args, MonoObject *, 0); /* FIXME: GC write abrrier for res */
+       mono_gc_wbarrier_generic_store (res, mono_array_get (out_args, MonoObject *, 0));
 
        if (field_class->valuetype) {
                return ((char *)*res) + sizeof (MonoObject);
@@ -7462,9 +7664,54 @@ mono_load_remote_field (MonoObject *this_obj, MonoClass *klass, MonoClassField *
 MonoObject *
 mono_load_remote_field_new (MonoObject *this_obj, MonoClass *klass, MonoClassField *field)
 {
-       MONO_REQ_GC_UNSAFE_MODE;
+       MonoError error;
+
+       MonoObject *result = mono_load_remote_field_new_checked (this_obj, klass, field, &error);
+       mono_error_cleanup (&error);
+       return result;
+}
 
+/**
+ * mono_load_remote_field_new_icall:
+ * @this: pointer to an object
+ * @klass: klass of the object containing @field
+ * @field: the field to load
+ *
+ * This method is called by the runtime on attempts to load fields of
+ * transparent proxy objects. @this points to such TP, @klass is the class of
+ * the object containing @field.
+ * 
+ * Returns: a freshly allocated object containing the value of the
+ * field.  On failure returns NULL and throws an exception.
+ */
+MonoObject *
+mono_load_remote_field_new_icall (MonoObject *this_obj, MonoClass *klass, MonoClassField *field)
+{
        MonoError error;
+       MonoObject *result = mono_load_remote_field_new_checked (this_obj, klass, field, &error);
+       mono_error_set_pending_exception (&error);
+       return result;
+}
+
+/**
+ * mono_load_remote_field_new_checked:
+ * @this: pointer to an object
+ * @klass: klass of the object containing @field
+ * @field: the field to load
+ * @error: set on error.
+ *
+ * This method is called by the runtime on attempts to load fields of
+ * transparent proxy objects. @this points to such TP, @klass is the class of
+ * the object containing @field.
+ * 
+ * Returns: a freshly allocated object containing the value of the field.  On failure returns NULL and sets @error.
+ */
+MonoObject *
+mono_load_remote_field_new_checked (MonoObject *this_obj, MonoClass *klass, MonoClassField *field, MonoError *error)
+{
+       MONO_REQ_GC_UNSAFE_MODE;
+
+       mono_error_init (error);
 
        static MonoMethod *getter = NULL;
        MonoDomain *domain = mono_domain_get ();
@@ -7482,8 +7729,8 @@ mono_load_remote_field_new (MonoObject *this_obj, MonoClass *klass, MonoClassFie
        if (mono_class_is_contextbound (tp->remote_class->proxy_class) && tp->rp->context == (MonoObject *) mono_context_get ()) {
                gpointer val;
                if (field_class->valuetype) {
-                       res = mono_object_new_checked (domain, field_class, &error);
-                       mono_error_raise_exception (&error); /* FIXME don't raise here */
+                       res = mono_object_new_checked (domain, field_class, error);
+                       return_val_if_nok (error, NULL);
                        val = ((gchar *) res) + sizeof (MonoObject);
                } else {
                        val = &res;
@@ -7494,16 +7741,19 @@ mono_load_remote_field_new (MonoObject *this_obj, MonoClass *klass, MonoClassFie
 
        if (!getter) {
                getter = mono_class_get_method_from_name (mono_defaults.object_class, "FieldGetter", -1);
-               if (!getter)
-                       mono_raise_exception (mono_get_exception_not_supported ("Linked away."));
+               if (!getter) {
+                       mono_error_set_not_supported (error, "Linked away.");
+                       return NULL;
+               }
        }
        
-       msg = (MonoMethodMessage *)mono_object_new_checked (domain, mono_defaults.mono_method_message_class, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
-       out_args = mono_array_new (domain, mono_defaults.object_class, 1);
+       msg = (MonoMethodMessage *)mono_object_new_checked (domain, mono_defaults.mono_method_message_class, error);
+       return_val_if_nok (error, NULL);
+       out_args = mono_array_new_checked (domain, mono_defaults.object_class, 1, error);
+       return_val_if_nok (error, NULL);
 
-       MonoReflectionMethod *rm = mono_method_get_object_checked (domain, getter, NULL, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
+       MonoReflectionMethod *rm = mono_method_get_object_checked (domain, getter, NULL, error);
+       return_val_if_nok (error, NULL);
        mono_message_init (domain, msg, rm, out_args);
 
        full_name = mono_type_get_full_name (klass);
@@ -7511,10 +7761,13 @@ mono_load_remote_field_new (MonoObject *this_obj, MonoClass *klass, MonoClassFie
        mono_array_setref (msg->args, 1, mono_string_new (domain, mono_field_get_name (field)));
        g_free (full_name);
 
-       mono_remoting_invoke ((MonoObject *)(tp->rp), msg, &exc, &out_args, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
+       mono_remoting_invoke ((MonoObject *)(tp->rp), msg, &exc, &out_args, error);
+       return_val_if_nok (error, NULL);
 
-       if (exc) mono_raise_exception ((MonoException *)exc);
+       if (exc) {
+               mono_error_set_exception_instance (error, (MonoException *)exc);
+               return NULL;
+       }
 
        if (mono_array_length (out_args) == 0)
                res = NULL;
@@ -7538,11 +7791,33 @@ mono_load_remote_field_new (MonoObject *this_obj, MonoClass *klass, MonoClassFie
 void
 mono_store_remote_field (MonoObject *this_obj, MonoClass *klass, MonoClassField *field, gpointer val)
 {
-       MONO_REQ_GC_UNSAFE_MODE;
-
        MonoError error;
+       (void) mono_store_remote_field_checked (this_obj, klass, field, val, &error);
+       mono_error_cleanup (&error);
+}
+
+/**
+ * mono_store_remote_field_checked:
+ * @this_obj: pointer to an object
+ * @klass: klass of the object containing @field
+ * @field: the field to load
+ * @val: the value/object to store
+ * @error: set on error
+ *
+ * This method is called by the runtime on attempts to store fields of
+ * transparent proxy objects. @this_obj points to such TP, @klass is the class of
+ * the object containing @field. @val is the new value to store in @field.
+ *
+ * Returns: on success returns TRUE, on failure returns FALSE and sets @error.
+ */
+gboolean
+mono_store_remote_field_checked (MonoObject *this_obj, MonoClass *klass, MonoClassField *field, gpointer val, MonoError *error)
+{
+       
+       MONO_REQ_GC_UNSAFE_MODE;
 
        static MonoMethod *setter = NULL;
+
        MonoDomain *domain = mono_domain_get ();
        MonoTransparentProxy *tp = (MonoTransparentProxy *) this_obj;
        MonoClass *field_class;
@@ -7552,6 +7827,8 @@ mono_store_remote_field (MonoObject *this_obj, MonoClass *klass, MonoClassField
        MonoObject *arg;
        char* full_name;
 
+       mono_error_init (error);
+
        g_assert (mono_object_is_transparent_proxy (this_obj));
 
        field_class = mono_class_from_mono_type (field->type);
@@ -7559,26 +7836,28 @@ mono_store_remote_field (MonoObject *this_obj, MonoClass *klass, MonoClassField
        if (mono_class_is_contextbound (tp->remote_class->proxy_class) && tp->rp->context == (MonoObject *) mono_context_get ()) {
                if (field_class->valuetype) mono_field_set_value (tp->rp->unwrapped_server, field, val);
                else mono_field_set_value (tp->rp->unwrapped_server, field, *((MonoObject **)val));
-               return;
+               return TRUE;
        }
 
        if (!setter) {
                setter = mono_class_get_method_from_name (mono_defaults.object_class, "FieldSetter", -1);
-               if (!setter)
-                       mono_raise_exception (mono_get_exception_not_supported ("Linked away."));
+               if (!setter) {
+                       mono_error_set_not_supported (error, "Linked away.");
+                       return FALSE;
+               }
        }
 
        if (field_class->valuetype) {
-               arg = mono_value_box_checked (domain, field_class, val, &error);
-               mono_error_raise_exception (&error); /* FIXME don't raise here */
+               arg = mono_value_box_checked (domain, field_class, val, error);
+               return_val_if_nok (error, FALSE);
        } else 
                arg = *((MonoObject **)val);
                
 
-       msg = (MonoMethodMessage *)mono_object_new_checked (domain, mono_defaults.mono_method_message_class, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
-       MonoReflectionMethod *rm = mono_method_get_object_checked (domain, setter, NULL, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
+       msg = (MonoMethodMessage *)mono_object_new_checked (domain, mono_defaults.mono_method_message_class, error);
+       return_val_if_nok (error, FALSE);
+       MonoReflectionMethod *rm = mono_method_get_object_checked (domain, setter, NULL, error);
+       return_val_if_nok (error, FALSE);
        mono_message_init (domain, msg, rm, NULL);
 
        full_name = mono_type_get_full_name (klass);
@@ -7587,10 +7866,14 @@ mono_store_remote_field (MonoObject *this_obj, MonoClass *klass, MonoClassField
        mono_array_setref (msg->args, 2, arg);
        g_free (full_name);
 
-       mono_remoting_invoke ((MonoObject *)(tp->rp), msg, &exc, &out_args, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
+       mono_remoting_invoke ((MonoObject *)(tp->rp), msg, &exc, &out_args, error);
+       return_val_if_nok (error, FALSE);
 
-       if (exc) mono_raise_exception ((MonoException *)exc);
+       if (exc) {
+               mono_error_set_exception_instance (error, (MonoException *)exc);
+               return FALSE;
+       }
+       return TRUE;
 }
 
 /**
@@ -7605,9 +7888,42 @@ mono_store_remote_field (MonoObject *this_obj, MonoClass *klass, MonoClassField
 void
 mono_store_remote_field_new (MonoObject *this_obj, MonoClass *klass, MonoClassField *field, MonoObject *arg)
 {
-       MONO_REQ_GC_UNSAFE_MODE;
+       MonoError error;
+       (void) mono_store_remote_field_new_checked (this_obj, klass, field, arg, &error);
+       mono_error_cleanup (&error);
+}
 
+/**
+ * mono_store_remote_field_new_icall:
+ * @this_obj:
+ * @klass:
+ * @field:
+ * @arg:
+ *
+ * Missing documentation
+ */
+void
+mono_store_remote_field_new_icall (MonoObject *this_obj, MonoClass *klass, MonoClassField *field, MonoObject *arg)
+{
        MonoError error;
+       (void) mono_store_remote_field_new_checked (this_obj, klass, field, arg, &error);
+       mono_error_set_pending_exception (&error);
+}
+
+/**
+ * mono_store_remote_field_new_checked:
+ * @this_obj:
+ * @klass:
+ * @field:
+ * @arg:
+ * @error:
+ *
+ * Missing documentation
+ */
+gboolean
+mono_store_remote_field_new_checked (MonoObject *this_obj, MonoClass *klass, MonoClassField *field, MonoObject *arg, MonoError *error)
+{
+       MONO_REQ_GC_UNSAFE_MODE;
 
        static MonoMethod *setter = NULL;
        MonoDomain *domain = mono_domain_get ();
@@ -7618,6 +7934,8 @@ mono_store_remote_field_new (MonoObject *this_obj, MonoClass *klass, MonoClassFi
        MonoObject *exc;
        char* full_name;
 
+       mono_error_init (error);
+
        g_assert (mono_object_is_transparent_proxy (this_obj));
 
        field_class = mono_class_from_mono_type (field->type);
@@ -7625,19 +7943,21 @@ mono_store_remote_field_new (MonoObject *this_obj, MonoClass *klass, MonoClassFi
        if (mono_class_is_contextbound (tp->remote_class->proxy_class) && tp->rp->context == (MonoObject *) mono_context_get ()) {
                if (field_class->valuetype) mono_field_set_value (tp->rp->unwrapped_server, field, ((gchar *) arg) + sizeof (MonoObject));
                else mono_field_set_value (tp->rp->unwrapped_server, field, arg);
-               return;
+               return TRUE;
        }
 
        if (!setter) {
                setter = mono_class_get_method_from_name (mono_defaults.object_class, "FieldSetter", -1);
-               if (!setter)
-                       mono_raise_exception (mono_get_exception_not_supported ("Linked away."));
+               if (!setter) {
+                       mono_error_set_not_supported (error, "Linked away.");
+                       return FALSE;
+               }
        }
 
-       msg = (MonoMethodMessage *)mono_object_new_checked (domain, mono_defaults.mono_method_message_class, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
-       MonoReflectionMethod *rm = mono_method_get_object_checked (domain, setter, NULL, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
+       msg = (MonoMethodMessage *)mono_object_new_checked (domain, mono_defaults.mono_method_message_class, error);
+       return_val_if_nok (error, FALSE);
+       MonoReflectionMethod *rm = mono_method_get_object_checked (domain, setter, NULL, error);
+       return_val_if_nok (error, FALSE);
        mono_message_init (domain, msg, rm, NULL);
 
        full_name = mono_type_get_full_name (klass);
@@ -7646,10 +7966,14 @@ mono_store_remote_field_new (MonoObject *this_obj, MonoClass *klass, MonoClassFi
        mono_array_setref (msg->args, 2, arg);
        g_free (full_name);
 
-       mono_remoting_invoke ((MonoObject *)(tp->rp), msg, &exc, &out_args, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
+       mono_remoting_invoke ((MonoObject *)(tp->rp), msg, &exc, &out_args, error);
+       return_val_if_nok (error, FALSE);
 
-       if (exc) mono_raise_exception ((MonoException *)exc);
+       if (exc) {
+               mono_error_set_exception_instance (error, (MonoException *)exc);
+               return FALSE;
+       }
+       return TRUE;
 }
 #endif
 
@@ -7743,17 +8067,19 @@ mono_array_addr_with_size (MonoArray *array, int size, uintptr_t idx)
 
 
 MonoArray *
-mono_glist_to_array (GList *list, MonoClass *eclass) 
+mono_glist_to_array (GList *list, MonoClass *eclass, MonoError *error
 {
        MonoDomain *domain = mono_domain_get ();
        MonoArray *res;
        int len, i;
 
+       mono_error_init (error);
        if (!list)
                return NULL;
 
        len = g_list_length (list);
-       res = mono_array_new (domain, eclass, len);
+       res = mono_array_new_checked (domain, eclass, len, error);
+       return_val_if_nok (error, NULL);
 
        for (i = 0; list; list = list->next, i++)
                mono_array_set (res, gpointer, i, list->data);
index 360dcd0d63188714790752d0e38c6e846496e662..99f31507451dfe415d73fa652cc3efefafcf5b9a 100644 (file)
@@ -72,29 +72,37 @@ MONO_API int            mono_string_length (MonoString *s);
 MONO_RT_EXTERNAL_ONLY MONO_API MonoObject *
 mono_object_new                    (MonoDomain *domain, MonoClass *klass);
 
+MONO_RT_EXTERNAL_ONLY
 MONO_API MonoObject *
 mono_object_new_specific    (MonoVTable *vtable);
 
 /* can be used for classes without finalizer in non-profiling mode */
+MONO_RT_EXTERNAL_ONLY
 MONO_API MonoObject *
 mono_object_new_fast       (MonoVTable *vtable);
 
+MONO_RT_EXTERNAL_ONLY
 MONO_API MonoObject *
 mono_object_new_alloc_specific (MonoVTable *vtable);
 
+MONO_RT_EXTERNAL_ONLY
 MONO_API MonoObject *
 mono_object_new_from_token  (MonoDomain *domain, MonoImage *image, uint32_t token);
 
+MONO_RT_EXTERNAL_ONLY
 MONO_API MonoArray*
 mono_array_new             (MonoDomain *domain, MonoClass *eclass, uintptr_t n);
 
+MONO_RT_EXTERNAL_ONLY
 MONO_API MonoArray*
 mono_array_new_full        (MonoDomain *domain, MonoClass *array_class,
                             uintptr_t *lengths, intptr_t *lower_bounds);
 
+MONO_RT_EXTERNAL_ONLY
 MONO_API MonoArray *
 mono_array_new_specific            (MonoVTable *vtable, uintptr_t n);
 
+MONO_RT_EXTERNAL_ONLY
 MONO_API MonoArray*
 mono_array_clone           (MonoArray *array);
 
@@ -104,9 +112,11 @@ mono_array_addr_with_size   (MonoArray *array, int size, uintptr_t idx);
 MONO_API uintptr_t
 mono_array_length           (MonoArray *array);
 
+MONO_RT_EXTERNAL_ONLY
 MONO_API MonoString*
 mono_string_new_utf16      (MonoDomain *domain, const mono_unichar2 *text, int32_t len);
 
+MONO_RT_EXTERNAL_ONLY
 MONO_API MonoString*
 mono_string_new_size       (MonoDomain *domain, int32_t len);
 
@@ -126,9 +136,11 @@ mono_string_new                (MonoDomain *domain, const char *text);
 MONO_API MonoString*
 mono_string_new_wrapper            (const char *text);
 
+MONO_RT_EXTERNAL_ONLY
 MONO_API MonoString*
 mono_string_new_len        (MonoDomain *domain, const char *text, unsigned int length);
 
+MONO_RT_EXTERNAL_ONLY
 MONO_API MonoString*
 mono_string_new_utf32      (MonoDomain *domain, const mono_unichar4 *text, int32_t len);
 
@@ -181,6 +193,7 @@ mono_object_get_class       (MonoObject *obj);
 MONO_API void*
 mono_object_unbox          (MonoObject *obj);
 
+MONO_RT_EXTERNAL_ONLY
 MONO_API MonoObject *
 mono_object_clone          (MonoObject *obj);
 
@@ -250,6 +263,7 @@ mono_runtime_invoke_array   (MonoMethod *method, void *obj, MonoArray *params,
 MONO_API void*
 mono_method_get_unmanaged_thunk (MonoMethod *method);
 
+MONO_RT_EXTERNAL_ONLY
 MONO_API MonoArray*
 mono_runtime_get_main_args  (void);
 
@@ -271,15 +285,19 @@ mono_runtime_set_main_args  (int argc, char* argv[]);
 
 /* The following functions won't be available with mono was configured with remoting disabled. */
 /*#ifndef DISABLE_REMOTING */
+MONO_RT_EXTERNAL_ONLY
 MONO_API void*
 mono_load_remote_field (MonoObject *this_obj, MonoClass *klass, MonoClassField *field, void **res);
 
+MONO_RT_EXTERNAL_ONLY
 MONO_API MonoObject *
 mono_load_remote_field_new (MonoObject *this_obj, MonoClass *klass, MonoClassField *field);
 
+MONO_RT_EXTERNAL_ONLY
 MONO_API void
 mono_store_remote_field (MonoObject *this_obj, MonoClass *klass, MonoClassField *field, void* val);
 
+MONO_RT_EXTERNAL_ONLY
 MONO_API void
 mono_store_remote_field_new (MonoObject *this_obj, MonoClass *klass, MonoClassField *field, MonoObject *arg);
 
@@ -311,9 +329,11 @@ MONO_RT_EXTERNAL_ONLY
 MONO_API MonoObject *
 mono_field_get_value_object (MonoDomain *domain, MonoClassField *field, MonoObject *obj);
 
+MONO_RT_EXTERNAL_ONLY
 MONO_API void
 mono_property_set_value (MonoProperty *prop, void *obj, void **params, MonoObject **exc);
 
+MONO_RT_EXTERNAL_ONLY
 MONO_API MonoObject*
 mono_property_get_value (MonoProperty *prop, void *obj, void **params, MonoObject **exc);
 
index 3cd38789d3cfd897fd521d25a6443f718d4f32e4..d74ca084f10e586c0521ee9d848db9c1dcf42fbf 100644 (file)
@@ -507,7 +507,9 @@ ves_icall_System_Diagnostics_Process_GetModules_internal (MonoObject *this_obj,
        }
 
        count = module_count + assembly_count; 
-       temp_arr = mono_array_new (mono_domain_get (), mono_class_get_process_module_class (), count);
+       temp_arr = mono_array_new_checked (mono_domain_get (), mono_class_get_process_module_class (), count, &error);
+       if (mono_error_set_pending_exception (&error))
+               return NULL;
 
        for (i = 0; i < module_count; i++) {
                if (GetModuleBaseName (process, mods[i], modname, MAX_PATH) &&
@@ -539,7 +541,9 @@ ves_icall_System_Diagnostics_Process_GetModules_internal (MonoObject *this_obj,
                arr = temp_arr;
        } else {
                /* shorter version of the array */
-               arr = mono_array_new (mono_domain_get (), mono_class_get_process_module_class (), num_added);
+               arr = mono_array_new_checked (mono_domain_get (), mono_class_get_process_module_class (), num_added, &error);
+               if (mono_error_set_pending_exception (&error))
+                       return NULL;
 
                for (i = 0; i < num_added; i++)
                        mono_array_setref (arr, i, mono_array_get (temp_arr, MonoObject*, i));
@@ -850,6 +854,7 @@ MonoArray *
 ves_icall_System_Diagnostics_Process_GetProcesses_internal (void)
 {
 #if !defined(HOST_WIN32)
+       MonoError error;
        MonoArray *procs;
        gpointer *pidarray;
        int i, count;
@@ -859,7 +864,11 @@ ves_icall_System_Diagnostics_Process_GetProcesses_internal (void)
                mono_set_pending_exception (mono_get_exception_not_supported ("This system does not support EnumProcesses"));
                return NULL;
        }
-       procs = mono_array_new (mono_domain_get (), mono_get_int32_class (), count);
+       procs = mono_array_new_checked (mono_domain_get (), mono_get_int32_class (), count, &error);
+       if (mono_error_set_pending_exception (&error)) {
+               g_free (pidarray);
+               return NULL;
+       }
        if (sizeof (guint32) == sizeof (gpointer)) {
                memcpy (mono_array_addr (procs, guint32, 0), pidarray, count * sizeof (gint32));
        } else {
@@ -870,6 +879,7 @@ ves_icall_System_Diagnostics_Process_GetProcesses_internal (void)
 
        return procs;
 #else
+       MonoError error;
        MonoArray *procs;
        gboolean ret;
        DWORD needed;
@@ -897,7 +907,12 @@ ves_icall_System_Diagnostics_Process_GetProcesses_internal (void)
        } while (TRUE);
 
        count = needed / sizeof (guint32);
-       procs = mono_array_new (mono_domain_get (), mono_get_int32_class (), count);
+       procs = mono_array_new_checked (mono_domain_get (), mono_get_int32_class (), count, &error);
+       if (mono_error_set_pending_exception (&error)) {
+               g_free (pids);
+               return NULL;
+       }
+
        memcpy (mono_array_addr (procs, guint32, 0), pids, needed);
        g_free (pids);
        pids = NULL;
index bb8579e7ad904bc4ebf04bbde85ce61ddf6e9a74..4920694b731f928265424c78bfa730b5238bd7aa 100644 (file)
@@ -283,7 +283,7 @@ mono_profiler_install_monitor  (MonoProfileMonitorFunc callback)
 }
 
 static MonoProfileSamplingMode sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
-static int64_t sampling_frequency = 1000; //1ms
+static int64_t sampling_frequency = 100; // Hz
 
 /**
  * mono_profiler_set_statistical_mode:
@@ -298,10 +298,10 @@ static int64_t sampling_frequency = 1000; //1ms
  * Said that, when using statistical sampling, always assume variable rate sampling as all sort of external factors can interfere.
  */
 void
-mono_profiler_set_statistical_mode (MonoProfileSamplingMode mode, int64_t sampling_frequency_is_us)
+mono_profiler_set_statistical_mode (MonoProfileSamplingMode mode, int64_t sampling_frequency_hz)
 {
        sampling_mode = mode;
-       sampling_frequency = sampling_frequency_is_us;
+       sampling_frequency = sampling_frequency_hz;
 }
 
 void 
@@ -1147,7 +1147,15 @@ load_embedded_profiler (const char *desc, const char *name)
        MonoDl *pmodule = NULL;
        gboolean result;
 
-       pmodule = mono_dl_open (NULL, MONO_DL_LAZY, &err);
+       /*
+        * Some profilers (such as ours) may need to call back into the runtime
+        * from their sampling callback (which is called in async-signal context).
+        * They need to be able to know that all references back to the runtime
+        * have been resolved; otherwise, calling runtime functions may result in
+        * invoking the dynamic linker which is not async-signal-safe. Passing
+        * MONO_DL_EAGER will ask the dynamic linker to resolve everything upfront.
+        */
+       pmodule = mono_dl_open (NULL, MONO_DL_EAGER, &err);
        if (!pmodule) {
                g_warning ("Could not open main executable (%s)", err);
                g_free (err);
@@ -1175,7 +1183,7 @@ load_profiler_from_directory (const char *directory, const char *libname, const
        iter = NULL;
        err = NULL;
        while ((path = mono_dl_build_path (directory, libname, &iter))) {
-               pmodule = mono_dl_open (path, MONO_DL_LAZY, &err);
+               pmodule = mono_dl_open (path, MONO_DL_EAGER, &err);
                mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT, "Attempting to load profiler: %s, %ssuccessful, err: %s", path, pmodule?"":"not ", err);
                g_free (path);
                g_free (err);
@@ -1190,7 +1198,7 @@ static gboolean
 load_profiler_from_mono_installation (const char *libname, const char *desc)
 {
        char *err = NULL;
-       MonoDl *pmodule = mono_dl_open_runtime_lib (libname, MONO_DL_LAZY, &err);
+       MonoDl *pmodule = mono_dl_open_runtime_lib (libname, MONO_DL_EAGER, &err);
        mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT, "Attempting to load profiler from runtime libs: %s, %ssuccessful, err: %s", libname, pmodule?"":"not ", err);
        g_free (err);
        if (pmodule)
index 17128a1cb5a79d950d70cc90c6a73337fae24b0b..b793548ef8fbd98782f7975b1b08ffd0d0a3634d 100644 (file)
@@ -214,7 +214,7 @@ typedef enum {
        MONO_PROFILER_STAT_MODE_REAL = 1,
 } MonoProfileSamplingMode;
 
-MONO_API void mono_profiler_set_statistical_mode (MonoProfileSamplingMode mode, int64_t sampling_frequency_is_us);
+MONO_API void mono_profiler_set_statistical_mode (MonoProfileSamplingMode mode, int64_t sampling_frequency_hz);
 
 MONO_END_DECLS
 
index 61a8a597d407c0722d61299cc1f83d1980b0435c..5488e7df3d8432c5e3e05ba91dd931624867290d 100644 (file)
@@ -7868,11 +7868,17 @@ mono_method_body_get_object_checked (MonoDomain *domain, MonoMethod *method, Mon
        ret->init_locals = header->init_locals;
        ret->max_stack = header->max_stack;
        ret->local_var_sig_token = local_var_sig_token;
-       MONO_OBJECT_SETREF (ret, il, mono_array_new_cached (domain, mono_defaults.byte_class, header->code_size));
+       MonoArray *il_arr = mono_array_new_cached (domain, mono_defaults.byte_class, header->code_size, error);
+       if (!is_ok (error))
+               goto fail;
+       MONO_OBJECT_SETREF (ret, il, il_arr);
        memcpy (mono_array_addr (ret->il, guint8, 0), header->code, header->code_size);
 
        /* Locals */
-       MONO_OBJECT_SETREF (ret, locals, mono_array_new_cached (domain, mono_class_get_local_variable_info_class (), header->num_locals));
+       MonoArray *locals_arr = mono_array_new_cached (domain, mono_class_get_local_variable_info_class (), header->num_locals, error);
+       if (!is_ok (error))
+               goto fail;
+       MONO_OBJECT_SETREF (ret, locals, locals_arr);
        for (i = 0; i < header->num_locals; ++i) {
                MonoReflectionLocalVariableInfo *info = (MonoReflectionLocalVariableInfo*)mono_object_new_checked (domain, mono_class_get_local_variable_info_class (), error);
                if (!is_ok (error))
@@ -7890,7 +7896,10 @@ mono_method_body_get_object_checked (MonoDomain *domain, MonoMethod *method, Mon
        }
 
        /* Exceptions */
-       MONO_OBJECT_SETREF (ret, clauses, mono_array_new_cached (domain, mono_class_get_exception_handling_clause_class (), header->num_clauses));
+       MonoArray *exn_clauses = mono_array_new_cached (domain, mono_class_get_exception_handling_clause_class (), header->num_clauses, error);
+       if (!is_ok (error))
+               goto fail;
+       MONO_OBJECT_SETREF (ret, clauses, exn_clauses);
        for (i = 0; i < header->num_clauses; ++i) {
                MonoReflectionExceptionHandlingClause *info = (MonoReflectionExceptionHandlingClause*)mono_object_new_checked (domain, mono_class_get_exception_handling_clause_class (), error);
                if (!is_ok (error))
@@ -9057,7 +9066,7 @@ handle_enum:
                }
                slen = mono_metadata_decode_value (p, &p);
                *end = p + slen;
-               return mono_string_new_len (mono_domain_get (), p, slen);
+               return mono_string_new_len_checked (mono_domain_get (), p, slen, error);
        case MONO_TYPE_CLASS: {
                MonoReflectionType *rt;
                char *n;
@@ -9165,7 +9174,8 @@ handle_type:
                        *end = p;
                        return NULL;
                }
-               arr = mono_array_new (mono_domain_get(), tklass, alen);
+               arr = mono_array_new_checked (mono_domain_get(), tklass, alen, error);
+               return_val_if_nok (error, NULL);
                basetype = tklass->byval_arg.type;
                if (basetype == MONO_TYPE_VALUETYPE && tklass->enumtype)
                        basetype = mono_class_enum_basetype (tklass)->type;
@@ -9531,9 +9541,13 @@ create_custom_attr (MonoImage *image, MonoMethod *method, const guchar *data, gu
                        }
 
 
-                       mono_property_set_value (prop, attr, pparams, NULL);
+                       mono_property_set_value_checked (prop, attr, pparams, error);
                        if (!type_is_reference (prop_type))
                                g_free (pparams [0]);
+                       if (!is_ok (error)) {
+                               g_free (name);
+                               goto fail;
+                       }
                }
                g_free (name);
        }
@@ -9587,8 +9601,9 @@ mono_reflection_create_custom_attr_data_args (MonoImage *image, MonoMethod *meth
        if (len < 2 || read16 (p) != 0x0001) /* Prolog */
                return;
 
-       typedargs = mono_array_new (domain, mono_get_object_class (), mono_method_signature (method)->param_count);
-       
+       typedargs = mono_array_new_checked (domain, mono_get_object_class (), mono_method_signature (method)->param_count, error);
+       return_if_nok (error);
+
        /* skip prolog */
        p += 2;
        for (i = 0; i < mono_method_signature (method)->param_count; ++i) {
@@ -9601,7 +9616,8 @@ mono_reflection_create_custom_attr_data_args (MonoImage *image, MonoMethod *meth
 
        named = p;
        num_named = read16 (named);
-       namedargs = mono_array_new (domain, mono_get_object_class (), num_named);
+       namedargs = mono_array_new_checked (domain, mono_get_object_class (), num_named, error);
+       return_if_nok (error);
        named += 2;
        attrklass = method->klass;
 
@@ -9820,7 +9836,8 @@ mono_custom_attrs_construct_by_type (MonoCustomAttrInfo *cinfo, MonoClass *attr_
                        n ++;
        }
 
-       result = mono_array_new_cached (mono_domain_get (), mono_defaults.attribute_class, n);
+       result = mono_array_new_cached (mono_domain_get (), mono_defaults.attribute_class, n, error);
+       return_val_if_nok (error, NULL);
        n = 0;
        for (i = 0; i < cinfo->num_attrs; ++i) {
                if (!cinfo->attrs [i].ctor) {
@@ -9858,7 +9875,8 @@ mono_custom_attrs_data_construct (MonoCustomAttrInfo *cinfo, MonoError *error)
        int i;
        
        mono_error_init (error);
-       result = mono_array_new (mono_domain_get (), mono_defaults.customattribute_data_class, cinfo->num_attrs);
+       result = mono_array_new_checked (mono_domain_get (), mono_defaults.customattribute_data_class, cinfo->num_attrs, error);
+       return_val_if_nok (error, NULL);
        for (i = 0; i < cinfo->num_attrs; ++i) {
                attr = create_custom_attr_data (cinfo->image, &cinfo->attrs [i], error);
                return_val_if_nok (error, NULL);
@@ -10455,7 +10473,7 @@ mono_reflection_get_custom_attrs_by_type (MonoObject *obj, MonoClass *attr_klass
                if (!result)
                        return NULL;
        } else {
-               result = mono_array_new_cached (mono_domain_get (), mono_defaults.attribute_class, 0);
+               result = mono_array_new_cached (mono_domain_get (), mono_defaults.attribute_class, 0, error);
        }
 
        return result;
@@ -10519,8 +10537,8 @@ mono_reflection_get_custom_attrs_data_checked (MonoObject *obj, MonoError *error
                if (!cinfo->cached)
                        mono_custom_attrs_free (cinfo);
                return_val_if_nok (error, NULL);
-       } else
-               result = mono_array_new (mono_domain_get (), mono_defaults.customattribute_data_class, 0);
+       } else 
+               result = mono_array_new_checked (mono_domain_get (), mono_defaults.customattribute_data_class, 0, error);
 
        return result;
 }
@@ -11390,7 +11408,9 @@ mono_reflection_get_custom_attrs_blob_checked (MonoReflectionAssembly *assembly,
 
        g_assert (p - buffer <= buflen);
        buflen = p - buffer;
-       result = mono_array_new (mono_domain_get (), mono_defaults.byte_class, buflen);
+       result = mono_array_new_checked (mono_domain_get (), mono_defaults.byte_class, buflen, error);
+       if (!is_ok (error))
+               goto leave;
        p = mono_array_addr (result, char, 0);
        memcpy (p, buffer, buflen);
 leave:
@@ -13479,7 +13499,8 @@ reflection_sighelper_get_signature_local (MonoReflectionSigHelper *sig, MonoErro
        }
 
        buflen = buf.p - buf.buf;
-       result = mono_array_new (mono_domain_get (), mono_defaults.byte_class, buflen);
+       result = mono_array_new_checked (mono_domain_get (), mono_defaults.byte_class, buflen, error);
+       if (!is_ok (error)) goto fail;
        memcpy (mono_array_addr (result, char, 0), buf.buf, buflen);
        sigbuffer_free (&buf);
        return result;
@@ -13522,7 +13543,8 @@ reflection_sighelper_get_signature_field (MonoReflectionSigHelper *sig, MonoErro
        }
 
        buflen = buf.p - buf.buf;
-       result = mono_array_new (mono_domain_get (), mono_defaults.byte_class, buflen);
+       result = mono_array_new_checked (mono_domain_get (), mono_defaults.byte_class, buflen, error);
+       if (!is_ok (error)) goto fail;
        memcpy (mono_array_addr (result, char, 0), buf.buf, buflen);
        sigbuffer_free (&buf);
 
index 6555cdec7a0d49f1e7da05a0cd841ca99bf47139..2b1a9d6b1949a31bf130d234779c79b43eee4102 100644 (file)
@@ -194,6 +194,9 @@ mono_remoting_marshal_init (void)
                register_icall (mono_marshal_xdomain_copy_out_value, "mono_marshal_xdomain_copy_out_value", "void object object", FALSE);
                register_icall (mono_remoting_wrapper, "mono_remoting_wrapper", "object ptr ptr", FALSE);
                register_icall (mono_upgrade_remote_class_wrapper, "mono_upgrade_remote_class_wrapper", "void object object", FALSE);
+               /* mono_load_remote_field_new_icall registered  by mini-runtime.c */
+               /* mono_store_remote_field_new_icall registered  by mini-runtime.c */
+
        }
 
        icalls_registered = TRUE;
@@ -376,7 +379,8 @@ mono_remoting_wrapper (MonoMethod *method, gpointer *params)
                                        /* runtime_invoke expects a boxed instance */
                                        if (mono_class_is_nullable (mono_class_from_mono_type (sig->params [i]))) {
                                                mparams[i] = mono_nullable_box ((guint8 *)params [i], klass, &error);
-                                               mono_error_raise_exception (&error); /* FIXME don't raise here */
+                                               if (!is_ok (&error))
+                                                       goto fail;
                                        } else
                                                mparams[i] = params [i];
                                }
@@ -386,7 +390,8 @@ mono_remoting_wrapper (MonoMethod *method, gpointer *params)
                }
 
                res = mono_runtime_invoke_checked (method, method->klass->valuetype? mono_object_unbox ((MonoObject*)this_obj): this_obj, mparams, &error);
-               mono_error_raise_exception (&error); /* FIXME don't raise here */
+               if (!is_ok (&error))
+                       goto fail;
 
                return res;
        }
@@ -394,16 +399,31 @@ mono_remoting_wrapper (MonoMethod *method, gpointer *params)
        msg = mono_method_call_message_new (method, params, NULL, NULL, NULL);
 
        res = mono_remoting_invoke ((MonoObject *)this_obj->rp, msg, &exc, &out_args, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
+       if (!is_ok (&error))
+               goto fail;
 
-       if (exc)
-               mono_raise_exception ((MonoException *)exc);
+       if (exc) {
+               mono_error_init (&error);
+               mono_error_set_exception_instance (&error, (MonoException *)exc);
+               goto fail;
+       }
 
-       mono_method_return_message_restore (method, params, out_args);
+       mono_method_return_message_restore (method, params, out_args, &error);
+       if (!is_ok (&error)) goto fail;
 
        return res;
+fail:
+       /* This icall will be called from managed code, and more over
+        * from a protected wrapper so interruptions such as pending
+        * exceptions will not be honored.  (See
+        * is_running_protected_wrapper () in threads.c and
+        * mono_marshal_get_remoting_invoke () in remoting.c)
+        */
+       mono_error_raise_exception (&error);
+       return NULL;
 } 
 
+
 MonoMethod *
 mono_marshal_get_remoting_invoke (MonoMethod *method)
 {
@@ -451,6 +471,11 @@ mono_marshal_get_remoting_invoke (MonoMethod *method)
        mono_mb_emit_ptr (mb, method);
        mono_mb_emit_ldloc (mb, params_var);
        mono_mb_emit_icall (mb, mono_remoting_wrapper);
+       // FIXME: this interrupt checkpoint code is a no-op since 'mb'
+       //  is a MONO_WRAPPER_REMOTING_INVOKE, and
+       //  mono_thread_interruption_checkpoint_request (FALSE)
+       //  considers such wrappers "protected" and always returns
+       //  NULL as if there's no pending interruption.
        mono_marshal_emit_thread_interrupt_checkpoint (mb);
 
        if (sig->ret->type == MONO_TYPE_VOID) {
@@ -534,8 +559,10 @@ mono_marshal_set_domain_by_id (gint32 id, MonoBoolean push)
        MonoDomain *current_domain = mono_domain_get ();
        MonoDomain *domain = mono_domain_get_by_id (id);
 
-       if (!domain || !mono_domain_set (domain, FALSE))        
-               mono_raise_exception (mono_get_exception_appdomain_unloaded ());
+       if (!domain || !mono_domain_set (domain, FALSE)) {
+               mono_set_pending_exception (mono_get_exception_appdomain_unloaded ());
+               return 0;
+       }
 
        if (push)
                mono_thread_push_appdomain_ref (domain);
@@ -1285,7 +1312,7 @@ mono_marshal_get_remoting_invoke_with_check (MonoMethod *method)
 MonoMethod *
 mono_marshal_get_ldfld_remote_wrapper (MonoClass *klass)
 {
-       MonoMethodSignature *sig, *csig;
+       MonoMethodSignature *sig;
        MonoMethodBuilder *mb;
        MonoMethod *res;
        static MonoMethod* cached = NULL;
@@ -1312,15 +1339,7 @@ mono_marshal_get_ldfld_remote_wrapper (MonoClass *klass)
        mono_mb_emit_ldarg (mb, 1);
        mono_mb_emit_ldarg (mb, 2);
 
-       csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
-       csig->params [0] = &mono_defaults.object_class->byval_arg;
-       csig->params [1] = &mono_defaults.int_class->byval_arg;
-       csig->params [2] = &mono_defaults.int_class->byval_arg;
-       csig->ret = &mono_defaults.object_class->byval_arg;
-       csig->pinvoke = 1;
-
-       mono_mb_emit_native_call (mb, csig, mono_load_remote_field_new);
-       mono_marshal_emit_thread_interrupt_checkpoint (mb);
+       mono_mb_emit_icall (mb, mono_load_remote_field_new_icall);
 
        mono_mb_emit_byte (mb, CEE_RET);
 #endif
@@ -1643,7 +1662,7 @@ mono_marshal_get_ldflda_wrapper (MonoType *type)
 MonoMethod *
 mono_marshal_get_stfld_remote_wrapper (MonoClass *klass)
 {
-       MonoMethodSignature *sig, *csig;
+       MonoMethodSignature *sig;
        MonoMethodBuilder *mb;
        MonoMethod *res;
        static MonoMethod *cached = NULL;
@@ -1672,16 +1691,7 @@ mono_marshal_get_stfld_remote_wrapper (MonoClass *klass)
        mono_mb_emit_ldarg (mb, 2);
        mono_mb_emit_ldarg (mb, 3);
 
-       csig = mono_metadata_signature_alloc (mono_defaults.corlib, 4);
-       csig->params [0] = &mono_defaults.object_class->byval_arg;
-       csig->params [1] = &mono_defaults.int_class->byval_arg;
-       csig->params [2] = &mono_defaults.int_class->byval_arg;
-       csig->params [3] = &mono_defaults.object_class->byval_arg;
-       csig->ret = &mono_defaults.void_class->byval_arg;
-       csig->pinvoke = 1;
-
-       mono_mb_emit_native_call (mb, csig, mono_store_remote_field_new);
-       mono_marshal_emit_thread_interrupt_checkpoint (mb);
+       mono_mb_emit_icall (mb, mono_store_remote_field_new_icall);
 
        mono_mb_emit_byte (mb, CEE_RET);
 #endif
@@ -2028,7 +2038,9 @@ mono_marshal_xdomain_copy_value (MonoObject *val)
                MonoArray *acopy;
                MonoXDomainMarshalType mt = mono_get_xdomain_marshal_type (&(mono_object_class (val)->element_class->byval_arg));
                if (mt == MONO_MARSHAL_SERIALIZE) return NULL;
-               acopy = mono_array_clone_in_domain (domain, (MonoArray *) val);
+               acopy = mono_array_clone_in_domain (domain, (MonoArray *) val, &error);
+               mono_error_raise_exception (&error); /* FIXME don't raise here */
+
                if (mt == MONO_MARSHAL_COPY) {
                        int i, len = mono_array_length (acopy);
                        for (i = 0; i < len; i++) {
index 3b0487c9243afe496a0f5d842a592cdf5e7dd459..74630b2c973afd4027dae0aac1c84b2515fe747f 100644 (file)
@@ -526,6 +526,30 @@ bridge_test_cross_reference2 (int num_sccs, MonoGCBridgeSCC **sccs, int num_xref
                sccs [i]->is_alive = TRUE;
 }
 
+/* This bridge keeps all peers with __test > 0 */
+static void
+bridge_test_positive_status (int num_sccs, MonoGCBridgeSCC **sccs, int num_xrefs, MonoGCBridgeXRef *xrefs)
+{
+       int i;
+
+       if (!mono_bridge_test_field) {
+               mono_bridge_test_field = mono_class_get_field_from_name (mono_object_get_class (sccs[0]->objs [0]), "__test");
+               g_assert (mono_bridge_test_field);
+       }
+
+       /*We mark all objects in a scc with live objects as reachable by scc*/
+       for (i = 0; i < num_sccs; ++i) {
+               int j;
+               for (j = 0; j < sccs [i]->num_objs; ++j) {
+                       if (test_scc (sccs [i], j)) {
+                               sccs [i]->is_alive = TRUE;
+                               break;
+                       }
+               }
+       }
+}
+
+
 static void
 register_test_bridge_callbacks (const char *bridge_class_name)
 {
@@ -533,9 +557,21 @@ register_test_bridge_callbacks (const char *bridge_class_name)
        callbacks.bridge_version = SGEN_BRIDGE_VERSION;
        callbacks.bridge_class_kind = bridge_test_bridge_class_kind;
        callbacks.is_bridge_object = bridge_test_is_bridge_object;
-       callbacks.cross_references = bridge_class_name[0] == '2' ? bridge_test_cross_reference2 : bridge_test_cross_reference;
+
+       switch (bridge_class_name [0]) {
+       case '2':
+               bridge_class = bridge_class_name + 1;
+               callbacks.cross_references = bridge_test_cross_reference2;
+               break;
+       case '3':
+               bridge_class = bridge_class_name + 1;
+               callbacks.cross_references = bridge_test_positive_status;
+               break;
+       default:
+               bridge_class = bridge_class_name;
+               callbacks.cross_references = bridge_test_cross_reference;
+       }
        mono_gc_register_bridge_callbacks (&callbacks);
-       bridge_class = bridge_class_name + (bridge_class_name[0] == '2' ? 1 : 0);
 }
 
 gboolean
index 54630c6ee033853a8ac63065b70eb7cfa1f3a100..e9f9b1a81a7a5ddeaad89a7ae0ddac596f328fcc 100644 (file)
@@ -689,6 +689,11 @@ sgen_client_binary_protocol_evacuating_blocks (size_t block_size)
 {
 }
 
+static void G_GNUC_UNUSED
+sgen_client_binary_protocol_concurrent_sweep_end (long long timestamp)
+{
+}
+
 int sgen_thread_handshake (BOOL suspend);
 gboolean sgen_suspend_thread (SgenThreadInfo *info);
 gboolean sgen_resume_thread (SgenThreadInfo *info);
index 0ffea956f7fce324006748046e72fe2a828cdb0a..bbd97e955df2a69003dafb75b8333c0bb505859b 100644 (file)
@@ -1242,16 +1242,14 @@ create_allocator (int atype, gboolean slowpath)
                g_assert_not_reached ();
        }
 
-       if (atype != ATYPE_SMALL) {
-               /* size += ALLOC_ALIGN - 1; */
-               mono_mb_emit_ldloc (mb, size_var);
-               mono_mb_emit_icon (mb, SGEN_ALLOC_ALIGN - 1);
-               mono_mb_emit_byte (mb, CEE_ADD);
-               /* size &= ~(ALLOC_ALIGN - 1); */
-               mono_mb_emit_icon (mb, ~(SGEN_ALLOC_ALIGN - 1));
-               mono_mb_emit_byte (mb, CEE_AND);
-               mono_mb_emit_stloc (mb, size_var);
-       }
+       /* size += ALLOC_ALIGN - 1; */
+       mono_mb_emit_ldloc (mb, size_var);
+       mono_mb_emit_icon (mb, SGEN_ALLOC_ALIGN - 1);
+       mono_mb_emit_byte (mb, CEE_ADD);
+       /* size &= ~(ALLOC_ALIGN - 1); */
+       mono_mb_emit_icon (mb, ~(SGEN_ALLOC_ALIGN - 1));
+       mono_mb_emit_byte (mb, CEE_AND);
+       mono_mb_emit_stloc (mb, size_var);
 
        /* if (size > MAX_SMALL_OBJ_SIZE) goto slowpath */
        if (atype != ATYPE_SMALL) {
@@ -1350,14 +1348,6 @@ create_allocator (int atype, gboolean slowpath)
                mono_mb_emit_byte (mb, MONO_CEE_ADD);
                mono_mb_emit_ldarg (mb, 1);
                mono_mb_emit_byte (mb, MONO_CEE_STIND_I4);
-               /* s->chars [len] = 0; */
-               mono_mb_emit_ldloc (mb, p_var);
-               mono_mb_emit_ldloc (mb, size_var);
-               mono_mb_emit_icon (mb, 2);
-               mono_mb_emit_byte (mb, MONO_CEE_SUB);
-               mono_mb_emit_byte (mb, MONO_CEE_ADD);
-               mono_mb_emit_icon (mb, 0);
-               mono_mb_emit_byte (mb, MONO_CEE_STIND_I2);
        }
 
        /*
index 10ac567111ec81b022d058662e3dbde0ec612375..1c45e375af5dffb372cc6b0338189ecee7e96d82 100644 (file)
 gboolean
 sgen_resume_thread (SgenThreadInfo *info)
 {
-       return thread_resume (info->client_info.info.native_handle) == KERN_SUCCESS;
+       kern_return_t ret;
+       do {
+               ret = thread_resume (info->client_info.info.native_handle);
+       } while (ret == KERN_ABORTED);
+       return ret == KERN_SUCCESS;
 }
 
 gboolean
@@ -51,11 +55,15 @@ sgen_suspend_thread (SgenThreadInfo *info)
        state = (thread_state_t) alloca (mono_mach_arch_get_thread_state_size ());
        mctx = (mcontext_t) alloca (mono_mach_arch_get_mcontext_size ());
 
-       ret = thread_suspend (info->client_info.info.native_handle);
+       do {
+               ret = thread_suspend (info->client_info.info.native_handle);
+       } while (ret == KERN_ABORTED);
        if (ret != KERN_SUCCESS)
                return FALSE;
 
-       ret = mono_mach_arch_get_thread_state (info->client_info.info.native_handle, state, &num_state);
+       do {
+               ret = mono_mach_arch_get_thread_state (info->client_info.info.native_handle, state, &num_state);
+       } while (ret == KERN_ABORTED);
        if (ret != KERN_SUCCESS)
                return FALSE;
 
@@ -117,7 +125,9 @@ sgen_thread_handshake (BOOL suspend)
                        if (!sgen_suspend_thread (info))
                                continue;
                } else {
-                       ret = thread_resume (info->client_info.info.native_handle);
+                       do {
+                               ret = thread_resume (info->client_info.info.native_handle);
+                       } while (ret == KERN_ABORTED);
                        if (ret != KERN_SUCCESS)
                                continue;
                }
index 4bf721f9a06faeaeaa5d90fb7fef7093106b78a1..6c3e0cf22875f07ffd8d1a3f6a77b4c61e396f3e 100644 (file)
@@ -847,7 +847,8 @@ create_object_from_sockaddr (struct sockaddr *saddr, int sa_size, gint32 *werror
         * the length of the entire sockaddr_in/in6, including
         * sizeof (unsigned short) of the family */
        /* We can't really avoid the +2 as all code below depends on this size - INCLUDING unix domain sockets.*/
-       data = mono_array_new_cached (domain, mono_get_byte_class (), sa_size + 2);
+       data = mono_array_new_cached (domain, mono_get_byte_class (), sa_size + 2, error);
+       return_val_if_nok (error, NULL);
 
        /* The data buffer is laid out as follows:
         * bytes 0 and 1 are the address family
@@ -1924,12 +1925,9 @@ ves_icall_System_Net_Sockets_Socket_Select_internal (MonoArray **sockets, gint32
 }
 
 static MonoObject*
-int_to_object (MonoDomain *domain, int val)
+int_to_object (MonoDomain *domain, int val, MonoError *error)
 {
-       MonoError error;
-       MonoObject *result = mono_value_box_checked (domain, mono_get_int32_class (), &val, &error);
-       mono_error_raise_exception (&error); /* FIXME don't raise here */
-       return result;
+       return mono_value_box_checked (domain, mono_get_int32_class (), &val, error);
 }
 
 void
@@ -1976,7 +1974,8 @@ ves_icall_System_Net_Sockets_Socket_GetSocketOption_obj_internal (SOCKET sock, g
                return;
        }
        if (ret == -2) {
-               *obj_val = int_to_object (domain, 0);
+               *obj_val = int_to_object (domain, 0, &error);
+               mono_error_set_pending_exception (&error);
                return;
        }
 
@@ -2037,11 +2036,13 @@ ves_icall_System_Net_Sockets_Socket_GetSocketOption_obj_internal (SOCKET sock, g
                break;
        case SocketOptionName_DontLinger:
                /* construct a bool int in val - true if linger is off */
-               obj = int_to_object (domain, !linger.l_onoff);
+               obj = int_to_object (domain, !linger.l_onoff, &error);
+               mono_error_set_pending_exception (&error);
                break;
        case SocketOptionName_SendTimeout:
        case SocketOptionName_ReceiveTimeout:
-               obj = int_to_object (domain, time_ms);
+               obj = int_to_object (domain, time_ms, &error);
+               mono_error_set_pending_exception (&error);
                break;
 
 #ifdef SO_PEERCRED
@@ -2087,7 +2088,8 @@ ves_icall_System_Net_Sockets_Socket_GetSocketOption_obj_internal (SOCKET sock, g
                if (level == SocketOptionLevel_Socket && name == SocketOptionName_ExclusiveAddressUse)
                        val = val ? 0 : 1;
 #endif
-               obj = int_to_object (domain, val);
+               obj = int_to_object (domain, val, &error);
+               mono_error_set_pending_exception (&error);
        }
 
        *obj_val = obj;
@@ -2480,7 +2482,7 @@ ves_icall_System_Net_Sockets_Socket_IOControl_internal (SOCKET sock, gint32 code
 }
 
 static gboolean 
-addrinfo_to_IPHostEntry(MonoAddressInfo *info, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list, gboolean add_local_ips)
+addrinfo_to_IPHostEntry (MonoAddressInfo *info, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list, gboolean add_local_ips, MonoError *error)
 {
        gint32 count, i;
        MonoAddressEntry *ai = NULL;
@@ -2491,14 +2493,19 @@ addrinfo_to_IPHostEntry(MonoAddressInfo *info, MonoString **h_name, MonoArray **
        int addr_index;
        MonoDomain *domain = mono_domain_get ();
 
+       mono_error_init (error);
        addr_index = 0;
-       *h_aliases = mono_array_new (domain, mono_get_string_class (), 0);
+       *h_aliases = mono_array_new_checked (domain, mono_get_string_class (), 0, error);
+       return_val_if_nok (error, FALSE);
        if (add_local_ips) {
                local_in = (struct in_addr *) mono_get_local_interfaces (AF_INET, &nlocal_in);
                local_in6 = (struct in6_addr *) mono_get_local_interfaces (AF_INET6, &nlocal_in6);
                if (nlocal_in || nlocal_in6) {
                        char addr [INET6_ADDRSTRLEN];
-                       *h_addr_list = mono_array_new (domain, mono_get_string_class (), nlocal_in + nlocal_in6);
+                       *h_addr_list = mono_array_new_checked (domain, mono_get_string_class (), nlocal_in + nlocal_in6, error);
+                       if (!is_ok (error))
+                               goto leave;
+                       
                        if (nlocal_in) {
                                MonoString *addr_string;
                                int i;
@@ -2529,11 +2536,12 @@ addrinfo_to_IPHostEntry(MonoAddressInfo *info, MonoString **h_name, MonoArray **
                                }
                        }
 
+               leave:
                        g_free (local_in);
                        g_free (local_in6);
                        if (info)
                                mono_free_address_info (info);
-                       return TRUE;
+                       return is_ok (error);;
                }
 
                g_free (local_in);
@@ -2546,7 +2554,9 @@ addrinfo_to_IPHostEntry(MonoAddressInfo *info, MonoString **h_name, MonoArray **
                count++;
        }
 
-       *h_addr_list = mono_array_new (domain, mono_get_string_class (), count);
+       *h_addr_list = mono_array_new_checked (domain, mono_get_string_class (), count, error);
+       if (!is_ok (error))
+               goto leave2;
 
        for (ai = info->entries, i = 0; ai != NULL; ai = ai->next) {
                MonoAddress maddr;
@@ -2576,10 +2586,11 @@ addrinfo_to_IPHostEntry(MonoAddressInfo *info, MonoString **h_name, MonoArray **
                addr_index++;
        }
 
+leave2:
        if (info)
                mono_free_address_info (info);
 
-       return TRUE;
+       return is_ok (error);
 }
 
 static int
@@ -2640,8 +2651,11 @@ ves_icall_System_Net_Dns_GetHostByName_internal (MonoString *host, MonoString **
 
        g_free(hostname);
 
-       if (add_info_ok)
-               return addrinfo_to_IPHostEntry (info, h_name, h_aliases, h_addr_list, add_local_ips);
+       if (add_info_ok) {
+               MonoBoolean result = addrinfo_to_IPHostEntry (info, h_name, h_aliases, h_addr_list, add_local_ips, &error);
+               mono_error_set_pending_exception (&error);
+               return result;
+       }
        return FALSE;
 }
 
@@ -2706,7 +2720,9 @@ ves_icall_System_Net_Dns_GetHostByAddr_internal (MonoString *addr, MonoString **
        if (mono_get_address_info (hostname, 0, hint | MONO_HINT_CANONICAL_NAME | MONO_HINT_CONFIGURED_ONLY, &info) != 0)
                return FALSE;
 
-       return addrinfo_to_IPHostEntry (info, h_name, h_aliases, h_addr_list, FALSE);
+       MonoBoolean result = addrinfo_to_IPHostEntry (info, h_name, h_aliases, h_addr_list, FALSE, &error);
+       mono_error_set_pending_exception (&error);
+       return result;
 }
 
 MonoBoolean
index bf619214c8557f19a08553296a81a69719ee3d1c..462fa98df8143115552eeb48bc32c6e21813a529 100644 (file)
@@ -47,13 +47,6 @@ epoll_init (gint wakeup_pipe_fd)
        return TRUE;
 }
 
-static void
-epoll_cleanup (void)
-{
-       g_free (epoll_events);
-       close (epoll_fd);
-}
-
 static void
 epoll_register_fd (gint fd, gint events, gboolean is_new)
 {
@@ -127,7 +120,6 @@ epoll_event_wait (void (*callback) (gint fd, gint events, gpointer user_data), g
 
 static ThreadPoolIOBackend backend_epoll = {
        .init = epoll_init,
-       .cleanup = epoll_cleanup,
        .register_fd = epoll_register_fd,
        .remove_fd = epoll_remove_fd,
        .event_wait = epoll_event_wait,
index 093d3399dc947736f20140470c3ef08cfa306aa0..e162c3cc9be24eec2bc8dfe1558449bedb9ac314 100644 (file)
@@ -43,13 +43,6 @@ kqueue_init (gint wakeup_pipe_fd)
        return TRUE;
 }
 
-static void
-kqueue_cleanup (void)
-{
-       g_free (kqueue_events);
-       close (kqueue_fd);
-}
-
 static void
 kqueue_register_fd (gint fd, gint events, gboolean is_new)
 {
@@ -124,7 +117,6 @@ kqueue_event_wait (void (*callback) (gint fd, gint events, gpointer user_data),
 
 static ThreadPoolIOBackend backend_kqueue = {
        .init = kqueue_init,
-       .cleanup = kqueue_cleanup,
        .register_fd = kqueue_register_fd,
        .remove_fd = kqueue_remove_fd,
        .event_wait = kqueue_event_wait,
index 4adae56791b40af7ffab900966b10c267a908000..4d4cceb090269f97b4f53ecad27601c128da93a6 100644 (file)
@@ -28,12 +28,6 @@ poll_init (gint wakeup_pipe_fd)
        return TRUE;
 }
 
-static void
-poll_cleanup (void)
-{
-       g_free (poll_fds);
-}
-
 static void
 poll_register_fd (gint fd, gint events, gboolean is_new)
 {
@@ -236,7 +230,6 @@ poll_event_wait (void (*callback) (gint fd, gint events, gpointer user_data), gp
 
 static ThreadPoolIOBackend backend_poll = {
        .init = poll_init,
-       .cleanup = poll_cleanup,
        .register_fd = poll_register_fd,
        .remove_fd = poll_remove_fd,
        .event_wait = poll_event_wait,
index b479fb1bd35a20946061e8a5c812a2fa716afc81..2851c7547b8b859f8b296c56cba264bf842ca4c7 100644 (file)
@@ -32,7 +32,6 @@
 
 typedef struct {
        gboolean (*init) (gint wakeup_pipe_fd);
-       void     (*cleanup) (void);
        void     (*register_fd) (gint fd, gint events, gboolean is_new);
        void     (*remove_fd) (gint fd);
        gint     (*event_wait) (void (*callback) (gint fd, gint events, gpointer user_data), gpointer user_data);
@@ -551,24 +550,6 @@ cleanup (void)
        selector_thread_wakeup ();
        while (io_selector_running)
                mono_thread_info_usleep (1000);
-
-       mono_coop_mutex_destroy (&threadpool_io->updates_lock);
-       mono_coop_cond_destroy (&threadpool_io->updates_cond);
-
-       threadpool_io->backend.cleanup ();
-
-#if !defined(HOST_WIN32)
-       close (threadpool_io->wakeup_pipes [0]);
-       close (threadpool_io->wakeup_pipes [1]);
-#else
-       closesocket (threadpool_io->wakeup_pipes [0]);
-       closesocket (threadpool_io->wakeup_pipes [1]);
-#endif
-
-       g_assert (threadpool_io);
-       g_free (threadpool_io);
-       threadpool_io = NULL;
-       g_assert (!threadpool_io);
 }
 
 void
index 14ebdf648ceb2ff052f46f2115b62b87830ded6a..abcc9fd747942fd34b85f58442c804c449119d9a 100644 (file)
@@ -1361,6 +1361,7 @@ mono_threadpool_ms_begin_invoke (MonoDomain *domain, MonoObject *target, MonoMet
 MonoObject *
 mono_threadpool_ms_end_invoke (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
 {
+       MonoError error;
        MonoAsyncCall *ac;
 
        g_assert (exc);
@@ -1390,7 +1391,9 @@ mono_threadpool_ms_end_invoke (MonoAsyncResult *ares, MonoArray **out_args, Mono
                } 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;
index f767247435aa25f7ebe39c62836cf651692fa93e..7e740b72b53dfadb97736debbc8ef1807e1c87f7 100644 (file)
@@ -96,10 +96,10 @@ gboolean ves_icall_System_Threading_Events_ResetEvent_internal (HANDLE handle);
 void ves_icall_System_Threading_Events_CloseEvent_internal (HANDLE handle);
 HANDLE ves_icall_System_Threading_Events_OpenEvent_internal (MonoString *name, gint32 rights, gint32 *error);
 
-gint32 ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext);
-gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms, gboolean exitContext);
-gint32 ves_icall_System_Threading_WaitHandle_WaitOne_internal(HANDLE handle, gint32 ms, gboolean exitContext);
-gint32 ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (HANDLE toSignal, HANDLE toWait, gint32 ms, gboolean exitContext);
+gint32 ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_handles, gint32 ms);
+gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_handles, gint32 ms);
+gint32 ves_icall_System_Threading_WaitHandle_WaitOne_internal(HANDLE handle, gint32 ms);
+gint32 ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (HANDLE toSignal, HANDLE toWait, gint32 ms);
 
 MonoArray* ves_icall_System_Threading_Thread_ByteArrayToRootDomain (MonoArray *arr);
 MonoArray* ves_icall_System_Threading_Thread_ByteArrayToCurrentDomain (MonoArray *arr);
index 856f0abf8797153ac0049e640442c89ba8097713..a7fd6491a226ccac6081cceea0fb6a313d510890 100644 (file)
@@ -455,7 +455,7 @@ static void thread_cleanup (MonoInternalThread *thread)
        mono_release_type_locks (thread);
 
        /* Can happen when we attach the profiler helper thread in order to heapshot. */
-       if (!mono_thread_info_lookup (thread->tid)->tools_thread)
+       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 ()) {
@@ -730,7 +730,7 @@ static guint32 WINAPI start_wrapper_internal(void *data)
        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 (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 */
@@ -1442,17 +1442,18 @@ ves_icall_System_Threading_Thread_SetPriority (MonoThread *this_obj, int priorit
 /* 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;
 }
@@ -1460,13 +1461,19 @@ byte_array_to_domain (MonoArray *arr, MonoDomain *domain)
 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 *
@@ -1600,8 +1607,7 @@ mono_wait_uninterrupted (MonoInternalThread *thread, gboolean multiple, guint32
        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;
@@ -1634,11 +1640,11 @@ gint32 ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_ha
 
        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;
@@ -1681,12 +1687,12 @@ gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_ha
                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 ();
@@ -1705,11 +1711,12 @@ gint32 ves_icall_System_Threading_WaitHandle_WaitOne_internal(HANDLE handle, gin
        
        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 ();
@@ -1727,7 +1734,8 @@ ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal (HANDLE toSignal, H
        
        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)
@@ -2270,8 +2278,9 @@ mono_thread_internal_reset_abort (MonoInternalThread *thread)
 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)
@@ -2284,12 +2293,14 @@ ves_icall_System_Threading_Thread_GetAbortExceptionState (MonoThread *this_obj)
        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;
        }
@@ -3526,8 +3537,12 @@ mono_threads_get_thread_dump (MonoArray **out_threads, MonoArray **out_stack_fra
        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];
@@ -3546,7 +3561,9 @@ mono_threads_get_thread_dump (MonoArray **out_threads, MonoArray **out_stack_fra
 
                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) {
index f65b3a6ee68a58a0b22aae2c31695b1d46471843..0217ba5b29cc92e9e8c223b86a9a72570a0c850f 100644 (file)
@@ -10463,8 +10463,10 @@ mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
        }
 
 #if defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
-       acfg->opts |= MONO_OPT_GSHAREDVT;
-       opts |= MONO_OPT_GSHAREDVT;
+       if (acfg->aot_opts.llvm_only || mono_aot_mode_is_full (&acfg->aot_opts)) {
+               acfg->opts |= MONO_OPT_GSHAREDVT;
+               opts |= MONO_OPT_GSHAREDVT;
+       }
 #endif
 
        if (opts & MONO_OPT_GSHAREDVT)
index 2d789a2f1767d43ecfcbce86822b9ad78132ea56..d3f3cf2e952c82b946e69b7a834082609d318d2e 100644 (file)
@@ -5222,7 +5222,9 @@ get_new_trampoline_from_page (int tramp_type)
                /* allocate two contiguous pages of memory: the first page will contain the data (like a local constant pool)
                 * while the second will contain the trampolines.
                 */
-               ret = vm_allocate (mach_task_self (), &addr, psize * 2, VM_FLAGS_ANYWHERE);
+               do {
+                       ret = vm_allocate (mach_task_self (), &addr, psize * 2, VM_FLAGS_ANYWHERE);
+               } while (ret == KERN_ABORTED);
                if (ret != KERN_SUCCESS) {
                        g_error ("Cannot allocate memory for trampolines: %d", ret);
                        break;
index 7b2bedd56470c901f27cba63a015a2309c382c16..ca8289b81c8313619b3f5c3e5fec193c4a503298 100644 (file)
@@ -249,7 +249,8 @@ mono_replace_ins (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *ins, MonoInst
                bb->has_array_access |= first_bb->has_array_access;
 
                /* Delete the links between the original bb and its successors */
-               tmp_bblocks = bb->out_bb;
+               tmp_bblocks = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoBasicBlock*) * bb->out_count);
+               memcpy (tmp_bblocks, bb->out_bb, sizeof (MonoBasicBlock*) * bb->out_count);
                count = bb->out_count;
                for (i = 0; i < count; ++i)
                        mono_unlink_bblock (cfg, bb, tmp_bblocks [i]);
index c7e18a0f0d9af49c4a515e255662d5781568a4e1..5b05e57c90e39af906a32a24d9f876a0e900d337 100644 (file)
@@ -9255,6 +9255,7 @@ string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
 static ErrorCode
 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
 {
+       MonoError error;
        int objid;
        ErrorCode err;
        MonoObject *obj;
@@ -9332,7 +9333,11 @@ object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
 
                                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
index 10a5bdfd5b40a943f3a0b627cd4cb91265ff7121..45849a824337eb2fd5dd7bb8d9eae312640afd27 100644 (file)
@@ -933,6 +933,8 @@ mono_decompose_long_opts (MonoCompile *cfg)
                                MONO_EMIT_NEW_BIALU_IMM (cfg, OP_XOR_IMM, MONO_LVREG_LS (tree->dreg), MONO_LVREG_LS (tree->sreg1), tree->inst_ls_word);
                                MONO_EMIT_NEW_BIALU_IMM (cfg, OP_XOR_IMM, MONO_LVREG_MS (tree->dreg), MONO_LVREG_MS (tree->sreg1), tree->inst_ms_word);
                                break;
+#ifdef TARGET_POWERPC
+/* FIXME This is normally handled in cprop. Proper fix or remove if no longer needed. */
                        case OP_LSHR_UN_IMM:
                                if (tree->inst_c1 == 32) {
 
@@ -941,20 +943,12 @@ mono_decompose_long_opts (MonoCompile *cfg)
                                         * later apply the speedup to the left shift as well
                                         * See BUG# 57957.
                                         */
-                                       /* FIXME: Move this to the strength reduction pass */
                                        /* just move the upper half to the lower and zero the high word */
                                        MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, MONO_LVREG_LS (tree->dreg), MONO_LVREG_MS (tree->sreg1));
                                        MONO_EMIT_NEW_ICONST (cfg, MONO_LVREG_MS (tree->dreg), 0);
                                }
                                break;
-                       case OP_LSHL_IMM:
-                               if (tree->inst_c1 == 32) {
-                                       /* just move the lower half to the upper and zero the lower word */
-                                       MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, MONO_LVREG_MS (tree->dreg), MONO_LVREG_LS (tree->sreg1));
-                                       MONO_EMIT_NEW_ICONST (cfg, MONO_LVREG_LS (tree->dreg), 0);
-                               }
-                               break;
-
+#endif
                        case OP_LCOMPARE: {
                                MonoInst *next = mono_inst_next (tree, FILTER_IL_SEQ_POINT);
 
@@ -1526,7 +1520,7 @@ mono_decompose_array_access_opts (MonoCompile *cfg)
                                                MONO_INST_NEW (cfg, iargs [2], OP_MOVE);
                                                iargs [2]->dreg = ins->sreg1;
 
-                                               dest = mono_emit_jit_icall (cfg, mono_array_new, iargs);
+                                               dest = mono_emit_jit_icall (cfg, ves_icall_array_new, iargs);
                                                dest->dreg = ins->dreg;
                                        } else {
                                                MonoClass *array_class = mono_array_class_get (ins->inst_newa_class, 1);
index dd5800be728affba67579b0669a00558cdf9e00f..5e6e71e26adecaf495bf6e37ae05a5477906aea2 100644 (file)
@@ -1140,7 +1140,7 @@ load_agent (MonoDomain *domain, char *desc)
 
        method = mono_get_method_checked (image, entry, NULL, NULL, &error);
        if (method == NULL){
-               g_print ("The entry point method of assembly '%s' could not be loaded due to %s\n", agent, &error);
+               g_print ("The entry point method of assembly '%s' could not be loaded due to %s\n", agent, mono_error_get_message (&error));
                mono_error_cleanup (&error);
                g_free (agent);
                return 1;
@@ -1149,12 +1149,19 @@ load_agent (MonoDomain *domain, char *desc)
        mono_thread_set_main (mono_thread_current ());
 
        if (args) {
-               main_args = (MonoArray*)mono_array_new (domain, mono_defaults.string_class, 1);
-               mono_array_set (main_args, MonoString*, 0, mono_string_new (domain, args));
+               main_args = (MonoArray*)mono_array_new_checked (domain, mono_defaults.string_class, 1, &error);
+               if (main_args)
+                       mono_array_set (main_args, MonoString*, 0, mono_string_new (domain, args));
        } else {
-               main_args = (MonoArray*)mono_array_new (domain, mono_defaults.string_class, 0);
+               main_args = (MonoArray*)mono_array_new_checked (domain, mono_defaults.string_class, 0, &error);
        }
-
+       if (!main_args) {
+               g_print ("Could not allocate array for main args of assembly '%s' due to %s\n", agent, mono_error_get_message (&error));
+               mono_error_cleanup (&error);
+               g_free (agent);
+               return 1;
+       }
+       
        g_free (agent);
 
        pa [0] = main_args;
@@ -1982,7 +1989,7 @@ mono_main (int argc, char* argv[])
 
        if (enable_profile) {
                mono_profiler_load (profile_options);
-               mono_profiler_thread_name (mono_native_thread_id_get (), "Main");
+               mono_profiler_thread_name (MONO_NATIVE_THREAD_ID_TO_UINT (mono_native_thread_id_get ()), "Main");
        }
 
        mono_attach_parse_options (attach_options);
index f23c5ff3bb9e5c1278220b19656c554e6f85d527..32cd496f30f19b43817bfef49cfe95f27a2d5a08 100644 (file)
@@ -181,6 +181,69 @@ mono_strength_reduction_ins (MonoCompile *cfg, MonoInst *ins, const char **spec)
 #endif
                break;
        }
+#if SIZEOF_REGISTER == 4
+       case OP_LSHR_IMM: {
+               if (ins->inst_c1 == 32) {
+                       MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, MONO_LVREG_LS (ins->dreg), MONO_LVREG_MS (ins->sreg1));
+                       MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHR_IMM, MONO_LVREG_MS (ins->dreg), MONO_LVREG_MS (ins->sreg1), 31);
+               } else if (ins->inst_c1 == 0) {
+                       MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, MONO_LVREG_LS (ins->dreg), MONO_LVREG_LS (ins->sreg1));
+                       MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, MONO_LVREG_MS (ins->dreg), MONO_LVREG_MS (ins->sreg1));
+               } else if (ins->inst_c1 > 32) {
+                       MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHR_IMM, MONO_LVREG_LS (ins->dreg), MONO_LVREG_MS (ins->sreg1), ins->inst_c1 - 32);
+                       MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHR_IMM, MONO_LVREG_MS (ins->dreg), MONO_LVREG_MS (ins->sreg1), 31);
+               } else {
+                       guint32 tmpreg = alloc_ireg (cfg);
+                       MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHL_IMM, tmpreg, MONO_LVREG_MS (ins->sreg1), 32 - ins->inst_c1);
+                       MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHR_IMM, MONO_LVREG_MS (ins->dreg), MONO_LVREG_MS (ins->sreg1), ins->inst_c1);
+                       MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHR_UN_IMM, MONO_LVREG_LS (ins->dreg), MONO_LVREG_LS (ins->sreg1), ins->inst_c1);
+                       MONO_EMIT_NEW_BIALU (cfg, OP_IOR, MONO_LVREG_LS (ins->dreg), MONO_LVREG_LS (ins->dreg), tmpreg);
+                       allocated_vregs = TRUE;
+               }
+               break;
+       }
+       case OP_LSHR_UN_IMM: {
+               if (ins->inst_c1 == 32) {
+                       MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, MONO_LVREG_LS (ins->dreg), MONO_LVREG_MS (ins->sreg1));
+                       MONO_EMIT_NEW_ICONST (cfg, MONO_LVREG_MS (ins->dreg), 0);
+               } else if (ins->inst_c1 == 0) {
+                       MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, MONO_LVREG_LS (ins->dreg), MONO_LVREG_LS (ins->sreg1));
+                       MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, MONO_LVREG_MS (ins->dreg), MONO_LVREG_MS (ins->sreg1));
+               } else if (ins->inst_c1 > 32) {
+                       MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHR_UN_IMM, MONO_LVREG_LS (ins->dreg), MONO_LVREG_MS (ins->sreg1), ins->inst_c1 - 32);
+                       MONO_EMIT_NEW_ICONST (cfg, MONO_LVREG_MS (ins->dreg), 0);
+               } else {
+                       guint32 tmpreg = alloc_ireg (cfg);
+                       MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHL_IMM, tmpreg, MONO_LVREG_MS (ins->sreg1), 32 - ins->inst_c1);
+                       MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHR_UN_IMM, MONO_LVREG_MS (ins->dreg), MONO_LVREG_MS (ins->sreg1), ins->inst_c1);
+                       MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHR_UN_IMM, MONO_LVREG_LS (ins->dreg), MONO_LVREG_LS (ins->sreg1), ins->inst_c1);
+                       MONO_EMIT_NEW_BIALU (cfg, OP_IOR, MONO_LVREG_LS (ins->dreg), MONO_LVREG_LS (ins->dreg), tmpreg);
+                       allocated_vregs = TRUE;
+               }
+               break;
+       }
+       case OP_LSHL_IMM: {
+               if (ins->inst_c1 == 32) {
+                       /* just move the lower half to the upper and zero the lower word */
+                       MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, MONO_LVREG_MS (ins->dreg), MONO_LVREG_LS (ins->sreg1));
+                       MONO_EMIT_NEW_ICONST (cfg, MONO_LVREG_LS (ins->dreg), 0);
+               } else if (ins->inst_c1 == 0) {
+                       MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, MONO_LVREG_LS (ins->dreg), MONO_LVREG_LS (ins->sreg1));
+                       MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, MONO_LVREG_MS (ins->dreg), MONO_LVREG_MS (ins->sreg1));
+               } else if (ins->inst_c1 > 32) {
+                       MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHL_IMM, MONO_LVREG_MS (ins->dreg), MONO_LVREG_LS (ins->sreg1), ins->inst_c1 - 32);
+                       MONO_EMIT_NEW_ICONST (cfg, MONO_LVREG_LS (ins->dreg), 0);
+               } else {
+                       guint32 tmpreg = alloc_ireg (cfg);
+                       MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHR_UN_IMM, tmpreg, MONO_LVREG_LS (ins->sreg1), 32 - ins->inst_c1);
+                       MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHL_IMM, MONO_LVREG_MS (ins->dreg), MONO_LVREG_MS (ins->sreg1), ins->inst_c1);
+                       MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHL_IMM, MONO_LVREG_LS (ins->dreg), MONO_LVREG_LS (ins->sreg1), ins->inst_c1);
+                       MONO_EMIT_NEW_BIALU (cfg, OP_IOR, MONO_LVREG_MS (ins->dreg), MONO_LVREG_MS (ins->dreg), tmpreg);
+                       allocated_vregs = TRUE;
+               }
+               break;
+       }
+#endif
 
        default:
                break;
index 587d08254e5f2143e2555a1d3bc579ddb2bb42e5..8e6ffa8dbac0d62df121c2d96d0082607b974e21 100644 (file)
@@ -4230,7 +4230,7 @@ handle_alloc (MonoCompile *cfg, MonoClass *klass, gboolean for_box, int context_
                                if (size < sizeof (MonoObject))
                                        g_error ("Invalid size %d for class %s", size, mono_type_get_full_name (klass));
 
-                               EMIT_NEW_ICONST (cfg, iargs [1], mono_gc_get_aligned_size_for_allocator (size));
+                               EMIT_NEW_ICONST (cfg, iargs [1], size);
                        }
                        return mono_emit_method_call (cfg, managed_alloc, iargs, NULL);
                }
@@ -4267,7 +4267,7 @@ handle_alloc (MonoCompile *cfg, MonoClass *klass, gboolean for_box, int context_
                                g_error ("Invalid size %d for class %s", size, mono_type_get_full_name (klass));
 
                        EMIT_NEW_VTABLECONST (cfg, iargs [0], vtable);
-                       EMIT_NEW_ICONST (cfg, iargs [1], mono_gc_get_aligned_size_for_allocator (size));
+                       EMIT_NEW_ICONST (cfg, iargs [1], size);
                        return mono_emit_method_call (cfg, managed_alloc, iargs, NULL);
                }
                alloc_ftn = mono_class_get_allocation_ftn (vtable, for_box, &pass_lw);
@@ -11869,7 +11869,7 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
                                        EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
                                        iargs [2] = sp [0];
 
-                                       ins = mono_emit_jit_icall (cfg, mono_array_new, iargs);
+                                       ins = mono_emit_jit_icall (cfg, ves_icall_array_new, iargs);
                                } else {
                                        /* Decompose later since it is needed by abcrem */
                                        MonoClass *array_type = mono_array_class_get (klass, 1);
index db26f1b5c523fb34ec53fe186b302ffbcbd4c2d3..5e5c27a53f6d21701ec85ced4cfc39c5b5132406 100644 (file)
@@ -722,6 +722,36 @@ mono_print_ins_index_strbuf (int i, MonoInst *ins)
        case OP_SEQ_POINT:
                g_string_append_printf (sbuf, " il: 0x%x%s", (int)ins->inst_imm, ins->flags & MONO_INST_NONEMPTY_STACK ? ", nonempty-stack" : "");
                break;
+       case OP_COND_EXC_EQ:
+       case OP_COND_EXC_GE:
+       case OP_COND_EXC_GT:
+       case OP_COND_EXC_LE:
+       case OP_COND_EXC_LT:
+       case OP_COND_EXC_NE_UN:
+       case OP_COND_EXC_GE_UN:
+       case OP_COND_EXC_GT_UN:
+       case OP_COND_EXC_LE_UN:
+       case OP_COND_EXC_LT_UN:
+       case OP_COND_EXC_OV:
+       case OP_COND_EXC_NO:
+       case OP_COND_EXC_C:
+       case OP_COND_EXC_NC:
+       case OP_COND_EXC_IEQ:
+       case OP_COND_EXC_IGE:
+       case OP_COND_EXC_IGT:
+       case OP_COND_EXC_ILE:
+       case OP_COND_EXC_ILT:
+       case OP_COND_EXC_INE_UN:
+       case OP_COND_EXC_IGE_UN:
+       case OP_COND_EXC_IGT_UN:
+       case OP_COND_EXC_ILE_UN:
+       case OP_COND_EXC_ILT_UN:
+       case OP_COND_EXC_IOV:
+       case OP_COND_EXC_INO:
+       case OP_COND_EXC_IC:
+       case OP_COND_EXC_INC:
+               g_string_append_printf (sbuf, " %s", ins->inst_p1);
+               break;
        default:
                break;
        }
index 4f8fbcf65853f668acdb0cc1be9140ae552f395a..a52f5eb80d06aef3137d018ac67b0940961f8460 100644 (file)
 #include <dlfcn.h>
 #include <AvailabilityMacros.h>
 
-#if defined (TARGET_OSX) && (MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_5)
-#define NEEDS_EXCEPTION_THREAD
-#endif
-
-#ifdef NEEDS_EXCEPTION_THREAD
-
-/*
- * This code disables the CrashReporter of MacOS X by installing
- * a dummy Mach exception handler.
- */
-
-/*
- * http://darwinsource.opendarwin.org/10.4.3/xnu-792.6.22/osfmk/man/exc_server.html
- */
-extern boolean_t exc_server (mach_msg_header_t *request_msg, mach_msg_header_t *reply_msg);
-
-/*
- * The exception message
- */
-typedef struct {
-       mach_msg_base_t msg;  /* common mach message header */
-       char payload [1024];  /* opaque */
-} mach_exception_msg_t;
-
-/* The exception port */
-static mach_port_t mach_exception_port = VM_MAP_NULL;
-
-kern_return_t
-catch_exception_raise (
-       mach_port_t exception_port,
-       mach_port_t thread,
-       mach_port_t task,
-       exception_type_t exception,
-       exception_data_t code,
-       mach_msg_type_number_t code_count);
-
-/*
- * Implicitly called by exc_server. Must be public.
- *
- * http://darwinsource.opendarwin.org/10.4.3/xnu-792.6.22/osfmk/man/catch_exception_raise.html
- */
-kern_return_t
-catch_exception_raise (
-       mach_port_t exception_port,
-       mach_port_t thread,
-       mach_port_t task,
-       exception_type_t exception,
-       exception_data_t code,
-       mach_msg_type_number_t code_count)
-{
-       /* consume the exception */
-       return KERN_FAILURE;
-}
-
-/*
- * Exception thread handler.
- */
-static
-void *
-mach_exception_thread (void *arg)
-{
-       for (;;) {
-               mach_exception_msg_t request;
-               mach_exception_msg_t reply;
-               mach_msg_return_t result;
-
-               /* receive from "mach_exception_port" */
-               result = mach_msg (&request.msg.header,
-                                  MACH_RCV_MSG | MACH_RCV_LARGE,
-                                  0,
-                                  sizeof (request),
-                                  mach_exception_port,
-                                  MACH_MSG_TIMEOUT_NONE,
-                                  MACH_PORT_NULL);
-
-               g_assert (result == MACH_MSG_SUCCESS);
-
-               /* dispatch to catch_exception_raise () */
-               exc_server (&request.msg.header, &reply.msg.header);
-
-               /* send back to sender */
-               result = mach_msg (&reply.msg.header,
-                                  MACH_SEND_MSG,
-                                  reply.msg.header.msgh_size,
-                                  0,
-                                  MACH_PORT_NULL,
-                                  MACH_MSG_TIMEOUT_NONE,
-                                  MACH_PORT_NULL);
-
-               /*
-               If we try to abort the thread while delivering an exception. The port will be gone since the kernel
-               setup a send once port to deliver the resume message and thread_abort will consume it.
-               */
-               g_assert (result == MACH_MSG_SUCCESS || result == MACH_SEND_INVALID_DEST);
-       }
-       return NULL;
-}
-
-static void
-macosx_register_exception_handler (void)
-{
-       mach_port_t task;
-       pthread_attr_t attr;
-       pthread_t thread;
-
-       if (mach_exception_port != VM_MAP_NULL)
-               return;
-
-       task = mach_task_self ();
-
-       /* create the "mach_exception_port" with send & receive rights */
-       g_assert (mach_port_allocate (task, MACH_PORT_RIGHT_RECEIVE,
-                                     &mach_exception_port) == KERN_SUCCESS);
-       g_assert (mach_port_insert_right (task, mach_exception_port, mach_exception_port,
-                                         MACH_MSG_TYPE_MAKE_SEND) == KERN_SUCCESS);
-
-       /* create the exception handler thread */
-       g_assert (!pthread_attr_init (&attr));
-       g_assert (!pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED));
-       g_assert (!pthread_create (&thread, &attr, mach_exception_thread, NULL));
-       pthread_attr_destroy (&attr);
-
-       /*
-        * register "mach_exception_port" as a receiver for the
-        * EXC_BAD_ACCESS exception
-        *
-        * http://darwinsource.opendarwin.org/10.4.3/xnu-792.6.22/osfmk/man/task_set_exception_ports.html
-        */
-       g_assert (task_set_exception_ports (task, EXC_MASK_BAD_ACCESS,
-                                           mach_exception_port,
-                                           EXCEPTION_DEFAULT,
-                                           MACHINE_THREAD_STATE) == KERN_SUCCESS);
-
-       mono_gc_register_mach_exception_thread (thread);
-}
-
-#endif
-
 /* This is #define'd by Boehm GC to _GC_dlopen. */
 #undef dlopen
 
@@ -215,9 +77,6 @@ void* dlopen(const char* path, int mode);
 void
 mono_runtime_install_handlers (void)
 {
-#ifdef NEEDS_EXCEPTION_THREAD
-       macosx_register_exception_handler ();
-#endif
        mono_runtime_posix_install_handlers ();
 
        /* Snow Leopard has a horrible bug: http://openradar.appspot.com/7209349
@@ -326,7 +185,9 @@ mono_thread_state_init_from_handle (MonoThreadUnwindState *tctx, MonoThreadInfo
        state = (thread_state_t) alloca (mono_mach_arch_get_thread_state_size ());
        mctx = (mcontext_t) alloca (mono_mach_arch_get_mcontext_size ());
 
-       ret = mono_mach_arch_get_thread_state (info->native_handle, state, &num_state);
+       do {
+               ret = mono_mach_arch_get_thread_state (info->native_handle, state, &num_state);
+       } while (ret == KERN_ABORTED);
        if (ret != KERN_SUCCESS)
                return FALSE;
 
index 479aed2f41ab71ae43f465101c120d87934a2162..a4d15fa4849100f30054a6e2324dc540937f0aa9 100644 (file)
@@ -709,12 +709,16 @@ ves_icall_get_trace (MonoException *exc, gint32 skip, MonoBoolean need_file_info
 
        if (ta == NULL) {
                /* Exception is not thrown yet */
-               return mono_array_new (domain, mono_defaults.stack_frame_class, 0);
+               res = mono_array_new_checked (domain, mono_defaults.stack_frame_class, 0, &error);
+               mono_error_set_pending_exception (&error);
+               return res;
        }
 
        len = mono_array_length (ta) >> 1;
 
-       res = mono_array_new (domain, mono_defaults.stack_frame_class, len > skip ? len - skip : 0);
+       res = mono_array_new_checked (domain, mono_defaults.stack_frame_class, len > skip ? len - skip : 0, &error);
+       if (mono_error_set_pending_exception (&error))
+               return NULL;
 
        for (i = skip; i < len; i++) {
                MonoJitInfo *ji;
@@ -1278,8 +1282,9 @@ wrap_non_exception_throws (MonoMethod *m)
 
 #define MAX_UNMANAGED_BACKTRACE 128
 static MonoArray*
-build_native_trace (void)
+build_native_trace (MonoError *error)
 {
+       mono_error_init (error);
 /* This puppy only makes sense on mobile, IOW, ARM. */
 #if defined (HAVE_BACKTRACE_SYMBOLS) && defined (TARGET_ARM)
        MonoArray *res;
@@ -1289,7 +1294,8 @@ build_native_trace (void)
 
        if (!size)
                return NULL;
-       res = mono_array_new (mono_domain_get (), mono_defaults.int_class, size);
+       res = mono_array_new_checked (mono_domain_get (), mono_defaults.int_class, size, error);
+       return_val_if_nok (error, NULL);
 
        for (i = 0; i < size; i++)
                mono_array_set (res, gpointer, i, native_trace [i]);
@@ -1304,8 +1310,12 @@ setup_stack_trace (MonoException *mono_ex, GSList *dynamic_methods, MonoArray *i
 {
        if (mono_ex && !initial_trace_ips) {
                *trace_ips = g_list_reverse (*trace_ips);
-               MONO_OBJECT_SETREF (mono_ex, trace_ips, mono_glist_to_array (*trace_ips, mono_defaults.int_class));
-               MONO_OBJECT_SETREF (mono_ex, native_trace_ips, build_native_trace ());
+               MonoError error;
+               MonoArray *ips_arr = mono_glist_to_array (*trace_ips, mono_defaults.int_class, &error);
+               mono_error_assert_ok (&error);
+               MONO_OBJECT_SETREF (mono_ex, trace_ips, ips_arr);
+               MONO_OBJECT_SETREF (mono_ex, native_trace_ips, build_native_trace (&error));
+               mono_error_assert_ok (&error);
                if (dynamic_methods) {
                        /* These methods could go away anytime, so save a reference to them in the exception object */
                        GSList *l;
@@ -2910,7 +2920,9 @@ throw_exception (MonoObject *ex, gboolean rethrow)
                        trace = g_list_append (trace, l->data);
                        trace = g_list_append (trace, NULL);
                }
-               MONO_OBJECT_SETREF (mono_ex, trace_ips, mono_glist_to_array (trace, mono_defaults.int_class));
+               MonoArray *ips_arr = mono_glist_to_array (trace, mono_defaults.int_class, &error);
+               mono_error_assert_ok (&error);
+               MONO_OBJECT_SETREF (mono_ex, trace_ips, ips_arr);
                g_list_free (l);
                g_list_free (trace);
 #endif
@@ -2967,6 +2979,7 @@ mono_llvm_resume_exception (void)
 MonoObject *
 mono_llvm_load_exception (void)
 {
+               MonoError error;
        MonoJitTlsData *jit_tls = mono_get_jit_tls ();
 
        MonoException *mono_ex = (MonoException*)mono_gchandle_get_target (jit_tls->thrown_exc);
@@ -2990,14 +3003,18 @@ mono_llvm_load_exception (void)
                // FIXME: Does this work correctly for rethrows?
                // We may be discarding useful information
                // when this gets GC'ed
-               MONO_OBJECT_SETREF (mono_ex, trace_ips, mono_glist_to_array (trace_ips, mono_defaults.int_class));
+               MonoArray *ips_arr = mono_glist_to_array (trace_ips, mono_defaults.int_class, &error);
+               mono_error_assert_ok (&error);
+               MONO_OBJECT_SETREF (mono_ex, trace_ips, ips_arr);
                g_list_free (trace_ips);
 
                // FIXME:
                //MONO_OBJECT_SETREF (mono_ex, stack_trace, ves_icall_System_Exception_get_trace (mono_ex));
        } else {
-               MONO_OBJECT_SETREF (mono_ex, trace_ips, mono_array_new (mono_domain_get (), mono_defaults.int_class, 0));
-               MONO_OBJECT_SETREF (mono_ex, stack_trace, mono_array_new (mono_domain_get (), mono_defaults.stack_frame_class, 0));
+               MONO_OBJECT_SETREF (mono_ex, trace_ips, mono_array_new_checked (mono_domain_get (), mono_defaults.int_class, 0, &error));
+               mono_error_assert_ok (&error);
+               MONO_OBJECT_SETREF (mono_ex, stack_trace, mono_array_new_checked (mono_domain_get (), mono_defaults.stack_frame_class, 0, &error));
+               mono_error_assert_ok (&error);
        }
 
        return &mono_ex->object;
index d5787acf13b6dff1e2468d5002302a1aca978a16..95b45b56afb55485e6fef0845395d5e4638f6177 100644 (file)
@@ -322,18 +322,41 @@ per_thread_profiler_hit (void *ctx)
        }
 }
 
+static MonoNativeThreadId sampling_thread;
+
+static gint32 profiler_signals_sent;
+static gint32 profiler_signals_received;
+static gint32 profiler_signals_accepted;
+static gint32 profiler_interrupt_signals_received;
+
 MONO_SIG_HANDLER_FUNC (static, profiler_signal_handler)
 {
        int old_errno = errno;
        int hp_save_index;
        MONO_SIG_HANDLER_GET_CONTEXT;
 
+       /* See the comment in mono_runtime_shutdown_stat_profiler (). */
+       if (mono_native_thread_id_get () == sampling_thread) {
+#ifdef HAVE_CLOCK_NANOSLEEP
+               if (mono_profiler_get_sampling_mode () == MONO_PROFILER_STAT_MODE_PROCESS) {
+                       InterlockedIncrement (&profiler_interrupt_signals_received);
+                       return;
+               }
+#endif
+
+               g_error ("%s: Unexpected profiler signal received by the sampler thread", __func__);
+       }
+
+       InterlockedIncrement (&profiler_signals_received);
+
        if (mono_thread_info_get_small_id () == -1)
                return; //an non-attached thread got the signal
 
        if (!mono_domain_get () || !mono_native_tls_get_value (mono_jit_tls_id))
                return; //thread in the process of dettaching
 
+       InterlockedIncrement (&profiler_signals_accepted);
+
        hp_save_index = mono_hazard_pointer_save_for_signal_handler ();
 
        mono_thread_info_set_is_async_context (TRUE);
@@ -508,6 +531,8 @@ mono_runtime_cleanup_handlers (void)
 
 #ifdef HAVE_PROFILER_SIGNAL
 
+static volatile gint32 sampling_thread_running;
+
 #ifdef PLATFORM_MACOSX
 
 static clock_serv_t sampling_clock_service;
@@ -517,7 +542,11 @@ clock_init (void)
 {
        kern_return_t ret;
 
-       if ((ret = host_get_clock_service (mach_host_self (), SYSTEM_CLOCK, &sampling_clock_service)) != KERN_SUCCESS)
+       do {
+               ret = host_get_clock_service (mach_host_self (), SYSTEM_CLOCK, &sampling_clock_service);
+       } while (ret == KERN_ABORTED);
+
+       if (ret != KERN_SUCCESS)
                g_error ("%s: host_get_clock_service () returned %d", __func__, ret);
 }
 
@@ -526,7 +555,11 @@ clock_cleanup (void)
 {
        kern_return_t ret;
 
-       if ((ret = mach_port_deallocate (mach_task_self (), sampling_clock_service)) != KERN_SUCCESS)
+       do {
+               ret = mach_port_deallocate (mach_task_self (), sampling_clock_service);
+       } while (ret == KERN_ABORTED);
+
+       if (ret != KERN_SUCCESS)
                g_error ("%s: mach_port_deallocate () returned %d", __func__, ret);
 }
 
@@ -536,7 +569,11 @@ clock_get_time_ns (void)
        kern_return_t ret;
        mach_timespec_t mach_ts;
 
-       if ((ret = clock_get_time (sampling_clock_service, &mach_ts)) != KERN_SUCCESS)
+       do {
+               ret = clock_get_time (sampling_clock_service, &mach_ts);
+       } while (ret == KERN_ABORTED);
+
+       if (ret != KERN_SUCCESS)
                g_error ("%s: clock_get_time () returned %d", __func__, ret);
 
        return ((guint64) mach_ts.tv_sec * 1000000000) + (guint64) mach_ts.tv_nsec;
@@ -556,7 +593,7 @@ clock_sleep_ns_abs (guint64 ns_abs)
 
                if (ret != KERN_SUCCESS && ret != KERN_ABORTED)
                        g_error ("%s: clock_sleep () returned %d", __func__, ret);
-       } while (ret == KERN_ABORTED);
+       } while (ret == KERN_ABORTED && InterlockedRead (&sampling_thread_running));
 }
 
 #else
@@ -613,7 +650,7 @@ clock_sleep_ns_abs (guint64 ns_abs)
 
                if (ret != 0 && ret != EINTR)
                        g_error ("%s: clock_nanosleep () returned %d", __func__, ret);
-       } while (ret == EINTR);
+       } while (ret == EINTR && InterlockedRead (&sampling_thread_running));
 #else
        int ret;
        gint64 diff;
@@ -654,15 +691,14 @@ clock_sleep_ns_abs (guint64 ns_abs)
 
                if ((ret = nanosleep (&req, NULL)) == -1 && errno != EINTR)
                        g_error ("%s: nanosleep () returned -1, errno = %d", __func__, errno);
-       } while (ret == -1);
+       } while (ret == -1 && InterlockedRead (&sampling_thread_running));
 #endif
 }
 
 #endif
 
 static int profiler_signal;
-static MonoNativeThreadId sampling_thread;
-static volatile gint32 sampling_thread_running;
+static volatile gint32 sampling_thread_exiting;
 
 static mono_native_thread_return_t
 sampling_thread_func (void *data)
@@ -705,11 +741,14 @@ sampling_thread_func (void *data)
                        g_assert (mono_thread_info_get_tid (info) != mono_native_thread_id_get ());
 
                        mono_threads_pthread_kill (info, profiler_signal);
+                       InterlockedIncrement (&profiler_signals_sent);
                } FOREACH_THREAD_SAFE_END
 
                clock_sleep_ns_abs (sleep);
        }
 
+       InterlockedWrite (&sampling_thread_exiting, 1);
+
        clock_cleanup ();
 
        pthread_setschedparam (pthread_self (), old_policy, &old_sched);
@@ -723,6 +762,41 @@ void
 mono_runtime_shutdown_stat_profiler (void)
 {
        InterlockedWrite (&sampling_thread_running, 0);
+
+#ifdef HAVE_CLOCK_NANOSLEEP
+       /*
+        * There is a slight problem when we're using CLOCK_PROCESS_CPUTIME_ID: If
+        * we're shutting down and there's largely no activity in the process other
+        * than waiting for the sampler thread to shut down, it can take upwards of
+        * 20 seconds (depending on a lot of factors) for us to shut down because
+        * the sleep progresses very slowly as a result of the low CPU activity.
+        *
+        * We fix this by repeatedly sending the profiler signal to the sampler
+        * thread in order to interrupt the sleep. clock_sleep_ns_abs () will check
+        * sampling_thread_running upon an interrupt and return immediately if it's
+        * zero. profiler_signal_handler () has a special case to ignore the signal
+        * for the sampler thread.
+        *
+        * We do not need to do this on platforms where we use a regular sleep
+        * based on a monotonic clock. The sleep will return in a reasonable amount
+        * of time in those cases.
+        */
+       if (mono_profiler_get_sampling_mode () == MONO_PROFILER_STAT_MODE_PROCESS) {
+               MonoThreadInfo *info;
+
+               // Did it shut down already?
+               if ((info = mono_thread_info_lookup (sampling_thread))) {
+                       while (!InterlockedRead (&sampling_thread_exiting)) {
+                               mono_threads_pthread_kill (info, profiler_signal);
+                               mono_thread_info_usleep (10 * 1000 /* 10ms */);
+                       }
+
+                       // Make sure info can be freed.
+                       mono_hazard_pointer_clear (mono_hazard_pointer_get (), 1);
+               }
+       }
+#endif
+
        pthread_join (sampling_thread, NULL);
 
        /*
@@ -742,12 +816,16 @@ mono_runtime_setup_stat_profiler (void)
         * tends to result in awful delivery rates when the application is heavily
         * loaded.
         *
+        * We avoid real-time signals on Android as they're super broken in certain
+        * API levels (too small sigset_t, nonsensical SIGRTMIN/SIGRTMAX values,
+        * etc).
+        *
         * TODO: On Mac, we should explore using the Mach thread suspend/resume
         * functions and doing the stack walk from the sampling thread. This would
         * get us a 100% sampling rate. However, this may interfere with the GC's
         * STW logic. Could perhaps be solved by taking the suspend lock.
         */
-#if defined (USE_POSIX_BACKEND) && defined (SIGRTMIN)
+#if defined (USE_POSIX_BACKEND) && defined (SIGRTMIN) && !defined (PLATFORM_ANDROID)
        /* Just take the first real-time signal we can get. */
        profiler_signal = mono_threads_posix_signal_search_alternative (-1);
 #else
@@ -756,6 +834,11 @@ mono_runtime_setup_stat_profiler (void)
 
        add_signal_handler (profiler_signal, profiler_signal_handler, SA_RESTART);
 
+       mono_counters_register ("Sampling signals sent", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &profiler_signals_sent);
+       mono_counters_register ("Sampling signals received", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &profiler_signals_received);
+       mono_counters_register ("Sampling signals accepted", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &profiler_signals_accepted);
+       mono_counters_register ("Shutdown signals received", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &profiler_interrupt_signals_received);
+
        InterlockedWrite (&sampling_thread_running, 1);
        mono_native_thread_create (&sampling_thread, sampling_thread_func, NULL);
 }
index 795bab9e41d319ebb23ec690c14ee6cf6c288980..2c0750bfc72ca13e24597e8a2c98fcadcb0f58cd 100644 (file)
@@ -1112,8 +1112,6 @@ mono_thread_attach_cb (intptr_t tid, gpointer stack_start)
        thread = mono_thread_info_current_unchecked ();
        if (thread)
                thread->jit_data = jit_tls;
-       if (mono_profiler_get_events () & MONO_PROFILE_STATISTICAL)
-               mono_runtime_setup_stat_profiler ();
 
        mono_arch_cpu_init ();
 }
@@ -3397,7 +3395,7 @@ register_jit_stats (void)
        mono_counters_register ("Methods from AOT", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_aot);
        mono_counters_register ("Methods JITted using mono JIT", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_without_llvm);
        mono_counters_register ("Methods JITted using LLVM", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_with_llvm);
-       mono_counters_register ("JIT/method-to-IR (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_method_to_ir);
+       mono_counters_register ("JIT/method_to_ir (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_method_to_ir);
        mono_counters_register ("JIT/liveness_handle_exception_clauses (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_liveness_handle_exception_clauses);
        mono_counters_register ("JIT/handle_out_of_line_bblock (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_handle_out_of_line_bblock);
        mono_counters_register ("JIT/decompose_long_opts (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_decompose_long_opts);
@@ -3840,6 +3838,9 @@ mini_init (const char *filename, const char *runtime_version)
        mono_thread_attach (domain);
 #endif
 
+       if (mono_profiler_get_events () & MONO_PROFILE_STATISTICAL)
+               mono_runtime_setup_stat_profiler ();
+
        mono_profiler_runtime_initialized ();
 
        MONO_VES_INIT_END ();
@@ -3900,8 +3901,8 @@ register_icalls (void)
        register_icall (mono_thread_interruption_checkpoint, "mono_thread_interruption_checkpoint", "object", FALSE);
        register_icall (mono_thread_force_interruption_checkpoint_noraise, "mono_thread_force_interruption_checkpoint_noraise", "object", FALSE);
 #ifndef DISABLE_REMOTING
-       register_icall (mono_load_remote_field_new, "mono_load_remote_field_new", "object object ptr ptr", FALSE);
-       register_icall (mono_store_remote_field_new, "mono_store_remote_field_new", "void object ptr ptr object", FALSE);
+       register_icall (mono_load_remote_field_new_icall, "mono_load_remote_field_new_icall", "object object ptr ptr", FALSE);
+       register_icall (mono_store_remote_field_new_icall, "mono_store_remote_field_new_icall", "void object ptr ptr object", FALSE);
 #endif
 
 #if defined(__native_client__) || defined(__native_client_codegen__)
@@ -4050,7 +4051,7 @@ register_icalls (void)
        register_icall (mono_helper_stelem_ref_check, "mono_helper_stelem_ref_check", "void object object", FALSE);
        register_icall (ves_icall_object_new, "ves_icall_object_new", "object ptr ptr", FALSE);
        register_icall (ves_icall_object_new_specific, "ves_icall_object_new_specific", "object ptr", FALSE);
-       register_icall (mono_array_new, "mono_array_new", "object ptr ptr int32", FALSE);
+       register_icall (ves_icall_array_new, "ves_icall_array_new", "object ptr ptr int32", FALSE);
        register_icall (ves_icall_array_new_specific, "ves_icall_array_new_specific", "object ptr int32", FALSE);
        register_icall (ves_icall_runtime_class_init, "ves_icall_runtime_class_init", "void ptr", FALSE);
        register_icall (mono_ldftn, "mono_ldftn", "ptr ptr", FALSE);
index 5e9204611d7bf37760b7aae0a19dcb1057196085..6f2685dce80d67d586da67b8058f69e8f53d66a8 100644 (file)
@@ -1010,7 +1010,9 @@ mono_arch_allocate_vars (MonoCompile *cfg)
        header = cfg->header;
        sig = mono_method_signature (cfg->method);
 
-       cinfo = get_call_info (cfg->mempool, sig);
+       if (!cfg->arch.cinfo)
+               cfg->arch.cinfo = get_call_info (cfg->mempool, sig);
+       cinfo = (CallInfo *)cfg->arch.cinfo;
 
        cfg->frame_reg = X86_EBP;
        offset = 0;
@@ -1140,8 +1142,8 @@ mono_arch_allocate_vars (MonoCompile *cfg)
                if (inst->opcode != OP_REGVAR) {
                        inst->opcode = OP_REGOFFSET;
                        inst->inst_basereg = X86_EBP;
+                       inst->inst_offset = ainfo->offset + ARGS_OFFSET;
                }
-               inst->inst_offset = ainfo->offset + ARGS_OFFSET;
        }
 
        cfg->stack_offset = offset;
@@ -1156,7 +1158,10 @@ mono_arch_create_vars (MonoCompile *cfg)
 
        sig = mono_method_signature (cfg->method);
 
-       cinfo = get_call_info (cfg->mempool, sig);
+       if (!cfg->arch.cinfo)
+               cfg->arch.cinfo = get_call_info (cfg->mempool, sig);
+       cinfo = (CallInfo *)cfg->arch.cinfo;
+
        sig_ret = mini_get_underlying_type (sig->ret);
 
        if (cinfo->ret.storage == ArgValuetypeInReg)
@@ -5128,6 +5133,8 @@ mono_arch_emit_prolog (MonoCompile *cfg)
        MonoBasicBlock *bb;
        MonoMethodSignature *sig;
        MonoInst *inst;
+       CallInfo *cinfo;
+       ArgInfo *ainfo;
        int alloc_size, pos, max_offset, i, cfa_offset;
        guint8 *code;
        gboolean need_stack_frame;
@@ -5387,11 +5394,14 @@ mono_arch_emit_prolog (MonoCompile *cfg)
        sig = mono_method_signature (method);
        pos = 0;
 
+       cinfo = (CallInfo *)cfg->arch.cinfo;
+
        for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
                inst = cfg->args [pos];
+               ainfo = &cinfo->args [pos];
                if (inst->opcode == OP_REGVAR) {
                        g_assert (need_stack_frame);
-                       x86_mov_reg_membase (code, inst->dreg, X86_EBP, inst->inst_offset, 4);
+                       x86_mov_reg_membase (code, inst->dreg, X86_EBP, ainfo->offset + ARGS_OFFSET, 4);
                        if (cfg->verbose_level > 2)
                                g_print ("Argument %d assigned to register %s\n", pos, mono_arch_regname (inst->dreg));
                }
@@ -5513,7 +5523,7 @@ mono_arch_emit_epilog (MonoCompile *cfg)
        }
 
        /* Load returned vtypes into registers if needed */
-       cinfo = get_call_info (cfg->mempool, sig);
+       cinfo = (CallInfo *)cfg->arch.cinfo;
        if (cinfo->ret.storage == ArgValuetypeInReg) {
                for (quad = 0; quad < 2; quad ++) {
                        switch (cinfo->ret.pair_storage [quad]) {
index 969b679f29bbfdd161bd5a77c6c68cf7d6900cbc..0ca2bdcec44d54524c13b56004e93c1149bb4c8c 100644 (file)
@@ -165,6 +165,7 @@ typedef struct {
        gboolean need_stack_frame_inited;
        gboolean need_stack_frame;
        int sp_fp_offset, param_area_size;
+       gpointer cinfo;
        gpointer ss_tramp_var;
        gpointer bp_tramp_var;
 } MonoCompileArch;
index eb42a0279c1faf464a2b0840c7a8b611d95a4a2b..45d32b99c05e54b64969afac9b9c51d6047a07b8 100755 (executable)
@@ -6,7 +6,12 @@ USE_AOT=$2
 TMP_FILE_PREFIX=$(basename $0).tmp
 BASEDIR=$(dirname $0)
 
-MONO_PATH=$BASEDIR/../../mcs/class/lib/net_4_x:$BASEDIR
+case "$(uname -s)" in
+       CYGWIN*) PLATFORM_PATH_SEPARATOR=';';;
+       *) PLATFORM_PATH_SEPARATOR=':';;
+esac
+
+MONO_PATH=$BASEDIR/../../mcs/class/lib/net_4_x$PLATFORM_PATH_SEPARATOR$BASEDIR
 RUNTIME=$BASEDIR/../../runtime/mono-wrapper
 
 trap "rm -rf ${TMP_FILE_PREFIX}*" EXIT
@@ -16,7 +21,7 @@ tmp_file () {
 }
 
 clean_aot () {
-       rm -rf *.exe.so *.exe.dylib *.exe.dylib.dSYM
+       rm -rf *.exe.so *.exe.dylib *.exe.dylib.dSYM *.exe.dll
 }
 
 # The test compares the generated native code size between a compilation with and without seq points.
@@ -42,15 +47,19 @@ get_method () {
 }
 
 diff_methods () {
-       TMP_FILE=$(tmp_file)
-       echo "$(MONO_DEBUG=single-imm-size get_methods $1 $2 $3 $4)" >$TMP_FILE
-       diff <(cat $TMP_FILE) <(echo "$(MONO_DEBUG=gen-compact-seq-points,single-imm-size get_methods $1 $2 $3 $4)")
+       TMP_FILE1=$(tmp_file)
+       TMP_FILE2=$(tmp_file)
+       echo "$(MONO_DEBUG=single-imm-size get_methods $1 $2 $3 $4)" >$TMP_FILE1
+       echo "$(MONO_DEBUG=gen-compact-seq-points,single-imm-size get_methods $1 $2 $3 $4)" >$TMP_FILE2
+       diff $TMP_FILE1 $TMP_FILE2
 }
 
 diff_method () {
-       TMP_FILE=$(tmp_file)
-       echo "$(MONO_DEBUG=single-imm-size get_method $1 $2 $3 $4 $5)" >$TMP_FILE
-       sdiff -w 150 <(cat $TMP_FILE) <(echo "$(MONO_DEBUG=gen-compact-seq-points,single-imm-size get_method $1 $2 $3 $4 $5 | grep -Ev il_seq_point)")
+       TMP_FILE1=$(tmp_file)
+       TMP_FILE2=$(tmp_file)
+       echo "$(MONO_DEBUG=single-imm-size get_method $1 $2 $3 $4 $5)" >$TMP_FILE1
+       echo "$(MONO_DEBUG=gen-compact-seq-points,single-imm-size get_method $1 $2 $3 $4 $5 | grep -Ev il_seq_point)" >$TMP_FILE2
+       sdiff -w 150 $TMP_FILE1 $TMP_FILE2
 }
 
 get_method_name () {
index 39cf237bf87a15ac51d69d4da8c1eee9f47cc52d..6ae3d2556e90c46cd2cba6631b4c60cb4814d5f1 100644 (file)
@@ -61,21 +61,21 @@ LIBMONO=$(top_builddir)/mono/mini/libmonosgen-$(API_VER).la
 endif
 
 libmono_profiler_aot_la_SOURCES = mono-profiler-aot.c
-libmono_profiler_aot_la_LIBADD = $(LIBMONO) $(GLIB_LIBS) $(LIBICONV)
+libmono_profiler_aot_la_LIBADD = $(GLIB_LIBS) $(LIBICONV)
 if BITCODE
 libmono_profiler_aot_la_LDFLAGS = -no-undefined
 endif
 libmono_profiler_iomap_la_SOURCES = mono-profiler-iomap.c
-libmono_profiler_iomap_la_LIBADD = $(LIBMONO) $(GLIB_LIBS) $(LIBICONV)
+libmono_profiler_iomap_la_LIBADD = $(GLIB_LIBS) $(LIBICONV)
 if BITCODE
 libmono_profiler_iomap_la_LDFLAGS = -no-undefined
 endif
 libmono_profiler_log_la_SOURCES = proflog.c
-libmono_profiler_log_la_LIBADD = $(LIBMONO) $(GLIB_LIBS) $(Z_LIBS)
+libmono_profiler_log_la_LIBADD = $(GLIB_LIBS) $(Z_LIBS)
 if HAVE_VTUNE
 libmono_profiler_vtune_la_SOURCES = mono-profiler-vtune.c
 libmono_profiler_vtune_la_CFLAGS = $(VTUNE_CFLAGS)
-libmono_profiler_vtune_la_LIBADD = $(VTUNE_LIBS) $(LIBMONO) $(GLIB_LIBS) $(LIBICONV)
+libmono_profiler_vtune_la_LIBADD = $(VTUNE_LIBS) $(GLIB_LIBS) $(LIBICONV)
 endif
 
 # The log profile uses eglib functions, so it needs to be linked against
index 10eaba51c6ce6d7bce0d68888f4666b44bf9c18c..e8d53afea686ed76588370c99fe74beac2c0718b 100644 (file)
@@ -354,6 +354,7 @@ section_name (int section)
        case MONO_COUNTER_SECURITY: return "Mono Security";
        case MONO_COUNTER_RUNTIME: return "Mono Runtime";
        case MONO_COUNTER_SYSTEM: return "Mono System";
+       case MONO_COUNTER_PROFILER: return "Mono Profiler";
        default: return "<unknown>";
        }
 }
index 445e1bf1f893cab64898eed096e0c072ea009b1e..e658bf9777b6b78e81c6851a74b41a6fc44ec53a 100644 (file)
@@ -18,6 +18,7 @@
 #include <mono/metadata/metadata-internals.h>
 #include <mono/metadata/class.h>
 #include <mono/metadata/class-internals.h>
+#include <mono/metadata/object-internals.h>
 #include <mono/metadata/image.h>
 #include <mono/metadata/mono-debug.h>
 #include <mono/metadata/debug-helpers.h>
@@ -185,6 +186,7 @@ static inline guint32 calc_strings_hash (const gchar *str1, const gchar *str2, g
 
 static inline void print_report (const gchar *format, ...)
 {
+       MonoError error;
        MonoClass *klass;
        MonoProperty *prop;
        MonoString *str;
@@ -199,7 +201,8 @@ static inline void print_report (const gchar *format, ...)
        klass = mono_class_load_from_name (mono_get_corlib (), "System", "Environment");
        mono_class_init (klass);
        prop = mono_class_get_property_from_name (klass, "StackTrace");
-       str = (MonoString*)mono_property_get_value (prop, NULL, NULL, NULL);
+       str = (MonoString*)mono_property_get_value_checked (prop, NULL, NULL, &error);
+       mono_error_assert_ok (&error);
        stack_trace = mono_string_to_utf8 (str);
 
        fprintf (stdout, "-= Stack Trace =-\n%s\n\n", stack_trace);
index 47002dd5b5b6b75b9d98efe86c63016a930149ea..23605903f4350f01b1a6c982b077a56648aae204 100644 (file)
 #include <mono/metadata/tabledefs.h>
 #include <mono/utils/atomic.h>
 #include <mono/utils/mono-membar.h>
+#include <mono/utils/mono-mmap.h>
 #include <mono/utils/mono-counters.h>
 #include <mono/utils/mono-os-mutex.h>
 #include <mono/utils/mono-conc-hashtable.h>
+#include <mono/utils/lock-free-alloc.h>
 #include <mono/utils/lock-free-queue.h>
 #include <stdlib.h>
 #include <string.h>
@@ -122,6 +124,24 @@ static int do_counters = 0;
 static int do_coverage = 0;
 static gboolean debug_coverage = FALSE;
 static MonoProfileSamplingMode sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
+static int max_allocated_sample_hits;
+
+static gint32 sample_hits;
+static gint32 sample_flushes;
+static gint32 sample_allocations;
+static gint32 buffer_allocations;
+static gint32 thread_starts;
+static gint32 thread_ends;
+static gint32 domain_loads;
+static gint32 domain_unloads;
+static gint32 context_loads;
+static gint32 context_unloads;
+static gint32 assembly_loads;
+static gint32 assembly_unloads;
+static gint32 image_loads;
+static gint32 image_unloads;
+static gint32 class_loads;
+static gint32 class_unloads;
 
 typedef struct _LogBuffer LogBuffer;
 
@@ -454,41 +474,6 @@ ign_res (int G_GNUC_UNUSED unused, ...)
 #define ENTER_LOG(lb,str) if ((lb)->locked) {ign_res (write(2, str, strlen(str))); ign_res (write(2, "\n", 1));return;} else {(lb)->locked++;}
 #define EXIT_LOG(lb) (lb)->locked--;
 
-// Shared queue of sample snapshots taken at signal time.
-// The queue is written into by signal handlers for all threads;
-// the helper thread later unqueues and writes into its own LogBuffer.
-typedef struct _StatBuffer StatBuffer;
-struct _StatBuffer {
-       // Next (older) StatBuffer in processing queue
-       StatBuffer *next;
-
-       // Bytes allocated for this StatBuffer
-       uintptr_t size;
-
-       // Start of currently unused space in buffer
-       uintptr_t *cursor;
-
-       // Pointer to start-of-structure-plus-size (for convenience)
-       uintptr_t *buf_end;
-
-       // Start of data in buffer.
-       // Data consists of a series of sample packets consisting of:
-       // 1 ptrword: Metadata
-       //    Low 8 bits: COUNT, the count of native stack frames in this sample (currently always 1)
-       //    Next 8 bits: MBT_COUNT, the count of managed stacks in this sample
-       //    Next 8 bits: TYPE. See "sampling sources" enum in proflog.h. Usually SAMPLE_CYCLES (1)
-       // 1 ptrword: Thread ID
-       // 1 ptrword: Timestamp
-       // COUNT ptrwords: Native stack frames
-       //   Each word is an IP (first is IP where the signal did the interruption)
-       // MBT_COUNT * 4 ptrwords: Managed stack frames (AsyncFrameInfo, repacked)
-       //    Word 1: MonoMethod ptr
-       //    Word 2: MonoDomain ptr
-       //    Word 3: Base address of method
-       //    Word 4: Offset within method
-       uintptr_t buf [1];
-};
-
 typedef struct _BinaryObject BinaryObject;
 
 struct _BinaryObject {
@@ -498,7 +483,6 @@ struct _BinaryObject {
 };
 
 struct _MonoProfiler {
-       StatBuffer *stat_buffers;
        FILE* file;
 #if defined (HAVE_SYS_ZLIB)
        gzFile gzfile;
@@ -512,15 +496,21 @@ struct _MonoProfiler {
 #ifndef HOST_WIN32
        pthread_t helper_thread;
        pthread_t writer_thread;
+       pthread_t dumper_thread;
 #endif
        volatile gint32 run_writer_thread;
        MonoLockFreeQueue writer_queue;
        MonoSemType writer_queue_sem;
        MonoConcurrentHashTable *method_table;
        mono_mutex_t method_table_mutex;
+       volatile gint32 run_dumper_thread;
+       MonoLockFreeQueue dumper_queue;
+       MonoSemType dumper_queue_sem;
+       MonoLockFreeAllocSizeClass sample_size_class;
+       MonoLockFreeAllocator sample_allocator;
+       MonoLockFreeQueue sample_reuse_queue;
        BinaryObject *binary_objects;
        GPtrArray *coverage_filters;
-       GPtrArray *sorted_sample_events;
 };
 
 typedef struct _WriterQueueEntry WriterQueueEntry;
@@ -572,20 +562,13 @@ pstrdup (const char *s)
        return p;
 }
 
-static StatBuffer*
-create_stat_buffer (void)
-{
-       StatBuffer* buf = (StatBuffer *)alloc_buffer (BUFFER_SIZE);
-       buf->size = BUFFER_SIZE;
-       buf->buf_end = (uintptr_t*)((unsigned char*)buf + buf->size);
-       buf->cursor = buf->buf;
-       return buf;
-}
-
 static LogBuffer*
 create_buffer (void)
 {
        LogBuffer* buf = (LogBuffer *)alloc_buffer (BUFFER_SIZE);
+
+       InterlockedIncrement (&buffer_allocations);
+
        buf->size = BUFFER_SIZE;
        buf->time_base = current_time ();
        buf->last_time = buf->time_base;
@@ -1099,13 +1082,16 @@ gc_resize (MonoProfiler *profiler, int64_t new_size) {
        EXIT_LOG (logbuffer);
 }
 
+// If you alter MAX_FRAMES, you may need to alter SAMPLE_BLOCK_SIZE too.
 #define MAX_FRAMES 32
+
 typedef struct {
        int count;
        MonoMethod* methods [MAX_FRAMES];
        int32_t il_offsets [MAX_FRAMES];
        int32_t native_offsets [MAX_FRAMES];
 } FrameData;
+
 static int num_frames = MAX_FRAMES;
 
 static mono_bool
@@ -1364,6 +1350,8 @@ image_loaded (MonoProfiler *prof, MonoImage *image, int result)
        if (logbuffer->next)
                safe_send (prof, logbuffer);
        process_requests (prof);
+
+       InterlockedIncrement (&image_loads);
 }
 
 static void
@@ -1395,6 +1383,8 @@ image_unloaded (MonoProfiler *prof, MonoImage *image)
                safe_send (prof, logbuffer);
 
        process_requests (prof);
+
+       InterlockedIncrement (&image_unloads);
 }
 
 static void
@@ -1431,6 +1421,8 @@ assembly_loaded (MonoProfiler *prof, MonoAssembly *assembly, int result)
                safe_send (prof, logbuffer);
 
        process_requests (prof);
+
+       InterlockedIncrement (&assembly_loads);
 }
 
 static void
@@ -1464,6 +1456,8 @@ assembly_unloaded (MonoProfiler *prof, MonoAssembly *assembly)
                safe_send (prof, logbuffer);
 
        process_requests (prof);
+
+       InterlockedIncrement (&assembly_unloads);
 }
 
 static void
@@ -1510,6 +1504,8 @@ class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
        if (logbuffer->next)
                safe_send (prof, logbuffer);
        process_requests (prof);
+
+       InterlockedIncrement (&class_loads);
 }
 
 static void
@@ -1555,6 +1551,8 @@ class_unloaded (MonoProfiler *prof, MonoClass *klass)
                safe_send (prof, logbuffer);
 
        process_requests (prof);
+
+       InterlockedIncrement (&class_unloads);
 }
 
 #ifndef DISABLE_HELPER_THREAD
@@ -1795,6 +1793,8 @@ thread_start (MonoProfiler *prof, uintptr_t tid)
                safe_send (prof, logbuffer);
 
        process_requests (prof);
+
+       InterlockedIncrement (&thread_starts);
 }
 
 static void
@@ -1825,6 +1825,8 @@ thread_end (MonoProfiler *prof, uintptr_t tid)
 
        TLS_SET (tlsbuffer, NULL);
        TLS_SET (tlsmethodlist, NULL);
+
+       InterlockedIncrement (&thread_ends);
 }
 
 static void
@@ -1854,6 +1856,8 @@ domain_loaded (MonoProfiler *prof, MonoDomain *domain, int result)
                safe_send (prof, logbuffer);
 
        process_requests (prof);
+
+       InterlockedIncrement (&domain_loads);
 }
 
 static void
@@ -1880,6 +1884,8 @@ domain_unloaded (MonoProfiler *prof, MonoDomain *domain)
                safe_send (prof, logbuffer);
 
        process_requests (prof);
+
+       InterlockedIncrement (&domain_unloads);
 }
 
 static void
@@ -1938,6 +1944,8 @@ context_loaded (MonoProfiler *prof, MonoAppContext *context)
                safe_send (prof, logbuffer);
 
        process_requests (prof);
+
+       InterlockedIncrement (&context_loads);
 }
 
 static void
@@ -1966,6 +1974,8 @@ context_unloaded (MonoProfiler *prof, MonoAppContext *context)
                safe_send (prof, logbuffer);
 
        process_requests (prof);
+
+       InterlockedIncrement (&context_unloads);
 }
 
 static void
@@ -2007,101 +2017,102 @@ typedef struct {
 } AsyncFrameInfo;
 
 typedef struct {
+       MonoLockFreeQueueNode node;
+       MonoProfiler *prof;
+       uint64_t elapsed;
+       uintptr_t tid;
+       void *ip;
        int count;
-       AsyncFrameInfo *data;
-} AsyncFrameData;
+       AsyncFrameInfo frames [MONO_ZERO_LEN_ARRAY];
+} SampleHit;
 
 static mono_bool
 async_walk_stack (MonoMethod *method, MonoDomain *domain, void *base_address, int offset, void *data)
 {
-       AsyncFrameData *frame = (AsyncFrameData *)data;
-       if (frame->count < num_frames) {
-               frame->data [frame->count].method = method;
-               frame->data [frame->count].domain = domain;
-               frame->data [frame->count].base_address = base_address;
-               frame->data [frame->count].offset = offset;
-               // printf ("In %d at %p (dom %p) (native: %p)\n", frame->count, method, domain, base_address);
-               frame->count++;
+       SampleHit *sample = (SampleHit *) data;
+
+       if (sample->count < num_frames) {
+               int i = sample->count;
+
+               sample->frames [i].method = method;
+               sample->frames [i].domain = domain;
+               sample->frames [i].base_address = base_address;
+               sample->frames [i].offset = offset;
+
+               sample->count++;
        }
-       return frame->count == num_frames;
+
+       return sample->count == num_frames;
 }
 
-/*
-(type | frame count), tid, time, ip, [method, domain, base address, offset] * frames
-*/
-#define SAMPLE_EVENT_SIZE_IN_SLOTS(FRAMES) (4 + (FRAMES) * 4)
+#define SAMPLE_SLOT_SIZE(FRAMES) (sizeof (SampleHit) + sizeof (AsyncFrameInfo) * (FRAMES - MONO_ZERO_LEN_ARRAY))
+#define SAMPLE_BLOCK_SIZE (mono_pagesize ())
+
+static void
+enqueue_sample_hit (gpointer p)
+{
+       SampleHit *sample = p;
+
+       mono_lock_free_queue_node_unpoison (&sample->node);
+       mono_lock_free_queue_enqueue (&sample->prof->dumper_queue, &sample->node);
+       mono_os_sem_post (&sample->prof->dumper_queue_sem);
+
+       InterlockedIncrement (&sample_flushes);
+}
 
 static void
 mono_sample_hit (MonoProfiler *profiler, unsigned char *ip, void *context)
 {
-       StatBuffer *sbuf;
-       AsyncFrameInfo frames [num_frames];
-       AsyncFrameData bt_data = { 0, &frames [0]};
-       uint64_t now;
-       uintptr_t *data, *new_data, *old_data;
-       uintptr_t elapsed;
-       int timedout = 0;
-       int i;
+       /*
+        * Please note: We rely on the runtime loading the profiler with
+        * MONO_DL_EAGER (RTLD_NOW) so that references to runtime functions within
+        * this function (and its siblings) are resolved when the profiler is
+        * loaded. Otherwise, we would potentially invoke the dynamic linker when
+        * invoking runtime functions, which is not async-signal-safe.
+        */
+
        if (in_shutdown)
                return;
-       now = current_time ();
 
-       mono_stack_walk_async_safe (&async_walk_stack, context, &bt_data);
+       InterlockedIncrement (&sample_hits);
+
+       uint64_t now = current_time ();
+
+       SampleHit *sample = (SampleHit *) mono_lock_free_queue_dequeue (&profiler->sample_reuse_queue);
+
+       if (!sample) {
+               /*
+                * If we're out of reusable sample events and we're not allowed to
+                * allocate more, we have no choice but to drop the event.
+                */
+               if (InterlockedRead (&sample_allocations) >= max_allocated_sample_hits)
+                       return;
+
+               sample = mono_lock_free_alloc (&profiler->sample_allocator);
+               sample->prof = profiler;
+               mono_lock_free_queue_node_init (&sample->node, TRUE);
+
+               InterlockedIncrement (&sample_allocations);
+       }
+
+       sample->count = 0;
+       mono_stack_walk_async_safe (&async_walk_stack, context, sample);
+
+       uintptr_t elapsed = (now - profiler->startup_time) / 10000;
+
+       sample->elapsed = elapsed;
+       sample->tid = thread_id ();
+       sample->ip = ip;
 
-       elapsed = (now - profiler->startup_time) / 10000;
        if (do_debug) {
                int len;
                char buf [256];
-               snprintf (buf, sizeof (buf), "hit at %p in thread %p after %llu ms\n", ip, (void*)thread_id (), (unsigned long long int)elapsed/100);
+               snprintf (buf, sizeof (buf), "hit at %p in thread %p after %llu ms\n", ip, (void *) thread_id (), (unsigned long long int) elapsed / 100);
                len = strlen (buf);
                ign_res (write (2, buf, len));
        }
-       sbuf = profiler->stat_buffers;
-       if (!sbuf)
-               return;
-       /* flush the buffer at 1 second intervals */
-       if (sbuf->cursor > sbuf->buf && (elapsed - sbuf->buf [2]) > 100000) {
-               timedout = 1;
-       }
-       /* overflow: 400 slots is a big enough number to reduce the chance of losing this event if many
-        * threads hit this same spot at the same time
-        */
-       if (timedout || (sbuf->cursor + 400 >= sbuf->buf_end)) {
-               StatBuffer *oldsb, *foundsb;
-               sbuf = create_stat_buffer ();
-               do {
-                       oldsb = profiler->stat_buffers;
-                       sbuf->next = oldsb;
-                       foundsb = (StatBuffer *)InterlockedCompareExchangePointer ((void * volatile*)&profiler->stat_buffers, sbuf, oldsb);
-               } while (foundsb != oldsb);
-               if (do_debug)
-                       ign_res (write (2, "overflow\n", 9));
-               /* notify the helper thread */
-               if (sbuf->next->next) {
-                       char c = 0;
-                       ign_res (write (profiler->pipes [1], &c, 1));
-                       if (do_debug)
-                               ign_res (write (2, "notify\n", 7));
-               }
-       }
-       do {
-               old_data = sbuf->cursor;
-               new_data = old_data + SAMPLE_EVENT_SIZE_IN_SLOTS (bt_data.count);
-               if (new_data > sbuf->buf_end)
-                       return; /* Not enough room in buf to hold this event-- lost event */
-               data = (uintptr_t *)InterlockedCompareExchangePointer ((void * volatile*)&sbuf->cursor, new_data, old_data);
-       } while (data != old_data);
-
-       old_data [0] = 1 | (sample_type << 16) | (bt_data.count << 8);
-       old_data [1] = thread_id ();
-       old_data [2] = elapsed;
-       old_data [3] = (uintptr_t)ip;
-       for (i = 0; i < bt_data.count; ++i) {
-               old_data [4 + 4 * i + 0] = (uintptr_t)frames [i].method;
-               old_data [4 + 4 * i + 1] = (uintptr_t)frames [i].domain;
-               old_data [4 + 4 * i + 2] = (uintptr_t)frames [i].base_address;
-               old_data [4 + 4 * i + 3] = (uintptr_t)frames [i].offset;
-       }
+
+       mono_thread_hazardous_try_free (sample, enqueue_sample_hit);
 }
 
 static uintptr_t *code_pages = 0;
@@ -2441,111 +2452,6 @@ dump_unmanaged_coderefs (MonoProfiler *prof)
        }
 }
 
-static gint
-compare_sample_events (gconstpointer a, gconstpointer b)
-{
-       uintptr_t tid1 = (*(uintptr_t **) a) [1];
-       uintptr_t tid2 = (*(uintptr_t **) b) [1];
-
-       return tid1 > tid2 ? 1 :
-              tid1 < tid2 ? -1 :
-              0;
-}
-
-static void
-dump_sample_hits (MonoProfiler *prof, StatBuffer *sbuf)
-{
-       LogBuffer *logbuffer;
-       if (!sbuf)
-               return;
-       if (sbuf->next) {
-               dump_sample_hits (prof, sbuf->next);
-               free_buffer (sbuf->next, sbuf->next->size);
-               sbuf->next = NULL;
-       }
-
-       g_ptr_array_set_size (prof->sorted_sample_events, 0);
-
-       for (uintptr_t *sample = sbuf->buf; sample < sbuf->cursor;) {
-               int count = sample [0] & 0xff;
-               int mbt_count = (sample [0] & 0xff00) >> 8;
-
-               if (sample + SAMPLE_EVENT_SIZE_IN_SLOTS (mbt_count) > sbuf->cursor)
-                       break;
-
-               g_ptr_array_add (prof->sorted_sample_events, sample);
-
-               sample += count + 3 + 4 * mbt_count;
-       }
-
-       g_ptr_array_sort (prof->sorted_sample_events, compare_sample_events);
-
-       for (guint sidx = 0; sidx < prof->sorted_sample_events->len; sidx++) {
-               uintptr_t *sample = (uintptr_t *)g_ptr_array_index (prof->sorted_sample_events, sidx);
-               int count = sample [0] & 0xff;
-               int mbt_count = (sample [0] & 0xff00) >> 8;
-               int type = sample [0] >> 16;
-               uintptr_t *managed_sample_base = sample + count + 3;
-               uintptr_t thread_id = sample [1];
-
-               for (int i = 0; i < mbt_count; ++i) {
-                       MonoMethod *method = (MonoMethod*)managed_sample_base [i * 4 + 0];
-                       MonoDomain *domain = (MonoDomain*)managed_sample_base [i * 4 + 1];
-                       void *address = (void*)managed_sample_base [i * 4 + 2];
-
-                       if (!method) {
-                               g_assert (domain);
-                               MonoJitInfo *ji = mono_jit_info_table_find (domain, (char *)address);
-
-                               if (ji)
-                                       managed_sample_base [i * 4 + 0] = (uintptr_t)mono_jit_info_get_method (ji);
-                       }
-               }
-
-               logbuffer = ensure_logbuf (
-                       EVENT_SIZE /* event */ +
-                       LEB128_SIZE /* type */ +
-                       LEB128_SIZE /* time */ +
-                       LEB128_SIZE /* tid */ +
-                       LEB128_SIZE /* count */ +
-                       count * (
-                               LEB128_SIZE /* ip */
-                       ) +
-                       LEB128_SIZE /* managed count */ +
-                       mbt_count * (
-                               LEB128_SIZE /* method */ +
-                               LEB128_SIZE /* il offset */ +
-                               LEB128_SIZE /* native offset */
-                       )
-               );
-               emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
-               emit_value (logbuffer, type);
-               emit_uvalue (logbuffer, prof->startup_time + (uint64_t)sample [2] * (uint64_t)10000);
-               emit_ptr (logbuffer, (void *) thread_id);
-               emit_value (logbuffer, count);
-               for (int i = 0; i < count; ++i) {
-                       emit_ptr (logbuffer, (void*)sample [i + 3]);
-                       add_code_pointer (sample [i + 3]);
-               }
-
-               sample += count + 3;
-               /* new in data version 6 */
-               emit_uvalue (logbuffer, mbt_count);
-               for (int i = 0; i < mbt_count; ++i) {
-                       MonoMethod *method = (MonoMethod *) sample [i * 4 + 0];
-                       uintptr_t native_offset = sample [i * 4 + 3];
-
-                       emit_method (prof, logbuffer, method);
-                       emit_svalue (logbuffer, 0); /* il offset will always be 0 from now on */
-                       emit_svalue (logbuffer, native_offset);
-               }
-       }
-
-       dump_unmanaged_coderefs (prof);
-}
-
-#if USE_PERF_EVENTS
-
 static int
 mono_cpu_count (void)
 {
@@ -2624,6 +2530,8 @@ mono_cpu_count (void)
        return 1;
 }
 
+#if USE_PERF_EVENTS
+
 typedef struct {
        int perf_fd;
        unsigned int prev_pos;
@@ -3949,6 +3857,21 @@ unref_coverage_assemblies (gpointer key, gpointer value, gpointer userdata)
        mono_assembly_close (assembly);
 }
 
+static void
+free_sample_hit (gpointer p)
+{
+       mono_lock_free_free (p, SAMPLE_BLOCK_SIZE);
+}
+
+static void
+cleanup_reusable_samples (MonoProfiler *prof)
+{
+       SampleHit *sample;
+
+       while ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&prof->sample_reuse_queue)))
+               mono_thread_hazardous_try_free (sample, free_sample_hit);
+}
+
 static void
 log_shutdown (MonoProfiler *prof)
 {
@@ -3974,20 +3897,24 @@ log_shutdown (MonoProfiler *prof)
        }
 #endif
 
-       g_ptr_array_free (prof->sorted_sample_events, TRUE);
-
        if (TLS_GET (LogBuffer, tlsbuffer))
                send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
 
        TLS_SET (tlsbuffer, NULL);
        TLS_SET (tlsmethodlist, NULL);
 
+       InterlockedWrite (&prof->run_dumper_thread, 0);
+       mono_os_sem_post (&prof->dumper_queue_sem);
+       pthread_join (prof->dumper_thread, &res);
+       mono_os_sem_destroy (&prof->dumper_queue_sem);
+
        InterlockedWrite (&prof->run_writer_thread, 0);
        mono_os_sem_post (&prof->writer_queue_sem);
        pthread_join (prof->writer_thread, &res);
-
        mono_os_sem_destroy (&prof->writer_queue_sem);
 
+       cleanup_reusable_samples (prof);
+
 #if defined (HAVE_SYS_ZLIB)
        if (prof->gzfile)
                gzclose (prof->gzfile);
@@ -4141,25 +4068,7 @@ helper_thread (void* arg)
 
                if (FD_ISSET (prof->pipes [0], &rfds)) {
                        char c;
-                       int r = read (prof->pipes [0], &c, 1);
-                       if (r == 1 && c == 0) {
-                               StatBuffer *sbufbase = prof->stat_buffers;
-                               StatBuffer *sbuf;
-                               if (!sbufbase->next)
-                                       continue;
-                               sbuf = sbufbase->next->next;
-                               sbufbase->next->next = NULL;
-                               if (do_debug)
-                                       fprintf (stderr, "stat buffer dump\n");
-                               if (sbuf) {
-                                       dump_sample_hits (prof, sbuf);
-                                       free_buffer (sbuf, sbuf->size);
-                                       safe_send_threadless (prof, ensure_logbuf (0));
-                               }
-                               continue;
-                       }
-                       /* time to shut down */
-                       dump_sample_hits (prof, prof->stat_buffers);
+                       read (prof->pipes [0], &c, 1);
                        if (thread)
                                mono_thread_detach (thread);
                        if (do_debug)
@@ -4391,6 +4300,117 @@ start_writer_thread (MonoProfiler* prof)
        return !pthread_create (&prof->writer_thread, NULL, writer_thread, prof);
 }
 
+static void
+reuse_sample_hit (gpointer p)
+{
+       SampleHit *sample = p;
+
+       mono_lock_free_queue_node_unpoison (&sample->node);
+       mono_lock_free_queue_enqueue (&sample->prof->sample_reuse_queue, &sample->node);
+}
+
+static gboolean
+handle_dumper_queue_entry (MonoProfiler *prof)
+{
+       SampleHit *sample;
+
+       if ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&prof->dumper_queue))) {
+               for (int i = 0; i < sample->count; ++i) {
+                       MonoMethod *method = sample->frames [i].method;
+                       MonoDomain *domain = sample->frames [i].domain;
+                       void *address = sample->frames [i].base_address;
+
+                       if (!method) {
+                               g_assert (domain);
+                               g_assert (address);
+
+                               MonoJitInfo *ji = mono_jit_info_table_find (domain, (char *) address);
+
+                               if (ji)
+                                       sample->frames [i].method = mono_jit_info_get_method (ji);
+                       }
+               }
+
+               LogBuffer *logbuffer = ensure_logbuf (
+                       EVENT_SIZE /* event */ +
+                       LEB128_SIZE /* type */ +
+                       LEB128_SIZE /* time */ +
+                       LEB128_SIZE /* tid */ +
+                       LEB128_SIZE /* count */ +
+                       1 * (
+                               LEB128_SIZE /* ip */
+                       ) +
+                       LEB128_SIZE /* managed count */ +
+                       sample->count * (
+                               LEB128_SIZE /* method */ +
+                               LEB128_SIZE /* il offset */ +
+                               LEB128_SIZE /* native offset */
+                       )
+               );
+
+               emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
+               emit_value (logbuffer, sample_type);
+               emit_uvalue (logbuffer, prof->startup_time + sample->elapsed * 10000);
+               emit_ptr (logbuffer, (void *) sample->tid);
+               emit_value (logbuffer, 1);
+
+               // TODO: Actual native unwinding.
+               for (int i = 0; i < 1; ++i) {
+                       emit_ptr (logbuffer, sample->ip);
+                       add_code_pointer ((uintptr_t) sample->ip);
+               }
+
+               /* new in data version 6 */
+               emit_uvalue (logbuffer, sample->count);
+
+               for (int i = 0; i < sample->count; ++i) {
+                       emit_method (prof, logbuffer, sample->frames [i].method);
+                       emit_svalue (logbuffer, 0); /* il offset will always be 0 from now on */
+                       emit_svalue (logbuffer, sample->frames [i].offset);
+               }
+
+               mono_thread_hazardous_try_free (sample, reuse_sample_hit);
+
+               dump_unmanaged_coderefs (prof);
+
+               if (logbuffer->next)
+                       safe_send_threadless (prof, logbuffer);
+       }
+
+       return FALSE;
+}
+
+static void *
+dumper_thread (void *arg)
+{
+       MonoProfiler *prof = (MonoProfiler *)arg;
+
+       mono_threads_attach_tools_thread ();
+       mono_thread_info_set_name (mono_native_thread_id_get (), "Profiler dumper");
+
+       while (InterlockedRead (&prof->run_dumper_thread)) {
+               mono_os_sem_wait (&prof->dumper_queue_sem, MONO_SEM_FLAGS_NONE);
+               handle_dumper_queue_entry (prof);
+       }
+
+       /* Drain any remaining entries on shutdown. */
+       while (handle_dumper_queue_entry (prof));
+
+       safe_send_threadless (prof, ensure_logbuf (0));
+
+       mono_thread_info_detach ();
+
+       return NULL;
+}
+
+static int
+start_dumper_thread (MonoProfiler* prof)
+{
+       InterlockedWrite (&prof->run_dumper_thread, 1);
+
+       return !pthread_create (&prof->dumper_thread, NULL, dumper_thread, prof);
+}
+
 static void
 runtime_initialized (MonoProfiler *profiler)
 {
@@ -4402,6 +4422,7 @@ runtime_initialized (MonoProfiler *profiler)
 #endif
 
        start_writer_thread (profiler);
+       start_dumper_thread (profiler);
 
        InterlockedWrite (&runtime_inited, 1);
 #ifndef DISABLE_HELPER_THREAD
@@ -4469,14 +4490,23 @@ create_profiler (const char *filename, GPtrArray *filters)
        }
 #endif
        if (do_mono_sample) {
-               prof->stat_buffers = create_stat_buffer ();
                need_helper_thread = 1;
        }
        if (do_counters && !need_helper_thread) {
                need_helper_thread = 1;
        }
 
-       prof->sorted_sample_events = g_ptr_array_sized_new (BUFFER_SIZE / SAMPLE_EVENT_SIZE_IN_SLOTS (0));
+       /*
+        * If you hit this assert while increasing MAX_FRAMES, you need to increase
+        * SAMPLE_BLOCK_SIZE as well.
+        */
+       g_assert (SAMPLE_SLOT_SIZE (MAX_FRAMES) * 2 < LOCK_FREE_ALLOC_SB_USABLE_SIZE (SAMPLE_BLOCK_SIZE));
+
+       // FIXME: We should free this stuff too.
+       mono_lock_free_allocator_init_size_class (&prof->sample_size_class, SAMPLE_SLOT_SIZE (num_frames), SAMPLE_BLOCK_SIZE);
+       mono_lock_free_allocator_init_allocator (&prof->sample_allocator, &prof->sample_size_class);
+
+       mono_lock_free_queue_init (&prof->sample_reuse_queue);
 
 #ifdef DISABLE_HELPER_THREAD
        if (hs_mode_ondemand)
@@ -4490,6 +4520,9 @@ create_profiler (const char *filename, GPtrArray *filters)
        mono_lock_free_queue_init (&prof->writer_queue);
        mono_os_sem_init (&prof->writer_queue_sem, 0);
 
+       mono_lock_free_queue_init (&prof->dumper_queue);
+       mono_os_sem_init (&prof->dumper_queue_sem, 0);
+
        mono_os_mutex_init (&prof->method_table_mutex);
        prof->method_table = mono_conc_hashtable_new (NULL, NULL);
 
@@ -4513,7 +4546,7 @@ usage (int do_exit)
        printf ("\theapshot[=MODE]      record heap shot info (by default at each major collection)\n");
        printf ("\t                     MODE: every XXms milliseconds, every YYgc collections, ondemand\n");
        printf ("\tcounters             sample counters every 1s\n");
-       printf ("\tsample[=TYPE]        use statistical sampling mode (by default cycles/1000)\n");
+       printf ("\tsample[=TYPE]        use statistical sampling mode (by default cycles/100)\n");
        printf ("\t                     TYPE: cycles,instr,cacherefs,cachemiss,branches,branchmiss\n");
        printf ("\t                     TYPE can be followed by /FREQUENCY\n");
        printf ("\ttime=fast            use a faster (but more inaccurate) timer\n");
@@ -4598,7 +4631,7 @@ set_sample_mode (char* val, int allow_empty)
 #endif
        if (allow_empty && !val) {
                sample_type = SAMPLE_CYCLES;
-               sample_freq = 1000;
+               sample_freq = 100;
                return;
        }
        if (strcmp (val, "mono") == 0) {
@@ -4625,7 +4658,7 @@ set_sample_mode (char* val, int allow_empty)
        } else if (*maybe_freq != 0) {
                usage (1);
        } else {
-               sample_freq = 1000;
+               sample_freq = 100;
        }
        free (val);
 }
@@ -4694,6 +4727,25 @@ mono_profiler_startup (const char *desc)
                MONO_PROFILE_INS_COVERAGE|MONO_PROFILE_APPDOMAIN_EVENTS|MONO_PROFILE_CONTEXT_EVENTS|
                MONO_PROFILE_ASSEMBLY_EVENTS;
 
+       max_allocated_sample_hits = mono_cpu_count () * 1000;
+
+       mono_counters_register ("Sample hits", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &sample_hits);
+       mono_counters_register ("Sample flushes", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &sample_flushes);
+       mono_counters_register ("Sample events allocated", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &sample_allocations);
+       mono_counters_register ("Log buffers allocated", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &buffer_allocations);
+       mono_counters_register ("Thread start events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &thread_starts);
+       mono_counters_register ("Thread stop events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &thread_ends);
+       mono_counters_register ("Domain load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &domain_loads);
+       mono_counters_register ("Domain unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &domain_unloads);
+       mono_counters_register ("Context load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &context_loads);
+       mono_counters_register ("Context unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &context_unloads);
+       mono_counters_register ("Assembly load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &assembly_loads);
+       mono_counters_register ("Assembly unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &assembly_unloads);
+       mono_counters_register ("Image load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &image_loads);
+       mono_counters_register ("Image unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &image_unloads);
+       mono_counters_register ("Class load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &class_loads);
+       mono_counters_register ("Class unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &class_unloads);
+
        p = desc;
        if (strncmp (p, "log", 3))
                usage (1);
@@ -4796,6 +4848,14 @@ mono_profiler_startup (const char *desc)
                        notraces = num_frames == 0;
                        continue;
                }
+               if ((opt = match_option (p, "maxsamples", &val)) != p) {
+                       char *end;
+                       max_allocated_sample_hits = strtoul (val, &end, 10);
+                       if (!max_allocated_sample_hits)
+                               max_allocated_sample_hits = G_MAXINT32;
+                       free (val);
+                       continue;
+               }
                if ((opt = match_option (p, "calldepth", &val)) != p) {
                        char *end;
                        max_call_depth = strtoul (val, &end, 10);
@@ -4872,6 +4932,7 @@ mono_profiler_startup (const char *desc)
        prof = create_profiler (filename, filters);
        if (!prof)
                return;
+
        init_thread ();
 
        mono_profiler_install (prof, log_shutdown);
@@ -4879,11 +4940,11 @@ mono_profiler_startup (const char *desc)
        mono_profiler_install_allocation (gc_alloc);
        mono_profiler_install_gc_moves (gc_moves);
        mono_profiler_install_gc_roots (gc_handle, gc_roots);
-       mono_profiler_install_appdomain (NULL, domain_loaded, NULL, domain_unloaded);
+       mono_profiler_install_appdomain (NULL, domain_loaded, domain_unloaded, NULL);
        mono_profiler_install_appdomain_name (domain_name);
        mono_profiler_install_context (context_loaded, context_unloaded);
-       mono_profiler_install_class (NULL, class_loaded, NULL, class_unloaded);
-       mono_profiler_install_module (NULL, image_loaded, NULL, image_unloaded);
+       mono_profiler_install_class (NULL, class_loaded, class_unloaded, NULL);
+       mono_profiler_install_module (NULL, image_loaded, image_unloaded, NULL);
        mono_profiler_install_assembly (NULL, assembly_loaded, assembly_unloaded, NULL);
        mono_profiler_install_thread (thread_start, thread_end);
        mono_profiler_install_thread_name (thread_name);
@@ -4898,7 +4959,7 @@ mono_profiler_startup (const char *desc)
 
        if (do_mono_sample && sample_type == SAMPLE_CYCLES && !only_counters) {
                events |= MONO_PROFILE_STATISTICAL;
-               mono_profiler_set_statistical_mode (sampling_mode, 1000000 / sample_freq);
+               mono_profiler_set_statistical_mode (sampling_mode, sample_freq);
                mono_profiler_install_statistical (mono_sample_hit);
        }
 
index 1fbad58d9e737a734761ae09dbd2861b3b44814a..ecb0e43b82334160ce788b255733b12902fce6ae 100644 (file)
@@ -5,7 +5,7 @@
 #define LOG_HEADER_ID 0x4D505A01
 #define LOG_VERSION_MAJOR 0
 #define LOG_VERSION_MINOR 4
-#define LOG_DATA_VERSION 11
+#define LOG_DATA_VERSION 12
 /*
  * Changes in data versions:
  * version 2: added offsets in heap walk
@@ -26,6 +26,7 @@
                removed TYPE_LOAD_ERR flag (profiler never generated it, now removed from the format itself)
                added TYPE_GC_HANDLE_{CREATED,DESTROYED}_BT
                TYPE_JIT events are no longer guaranteed to have code start/size info (can be zero)
+ * version 12: added MONO_COUNTER_PROFILER
  */
 
 enum {
index 852a4a63329d2fdd134ebfb7c5e762fdd901c000..6ddea6d621301348aa2035c5f227994d8f695631 100644 (file)
@@ -186,7 +186,7 @@ mono_gc_make_descr_for_array (int vector, gsize *elem_bitmap, int numbits, size_
                }
                /* Note: we also handle structs with just ref fields */
                if (num_set * sizeof (gpointer) == elem_size) {
-                       return desc | VECTOR_SUBTYPE_REFS | ((gssize)(-1) << 16);
+                       return desc | VECTOR_SUBTYPE_REFS | ((gsize)(-1) << 16);
                }
                /* FIXME: try run-len first */
                /* Note: we can't skip the object header here, because it's not present */
index e6b8d672dce53fbb73037cc2c4dbfe39bca1a9a7..5ec907371f38451a493b5de735ff26c44620c6cf 100644 (file)
@@ -696,6 +696,8 @@ pin_objects_from_nursery_pin_queue (gboolean do_scan_objects, ScanCopyContext ct
                        definitely_pinned [count] = obj_to_pin;
                        count++;
                }
+               if (concurrent_collection_in_progress)
+                       sgen_pinning_register_pinned_in_nursery (obj_to_pin);
 
        next_pin_queue_entry:
                last = addr;
@@ -1411,6 +1413,8 @@ job_mod_union_preclean (void *worker_data_untyped, SgenThreadPoolJob *job)
 
        major_collector.scan_card_table (CARDTABLE_SCAN_MOD_UNION_PRECLEAN, ctx);
        sgen_los_scan_card_table (CARDTABLE_SCAN_MOD_UNION_PRECLEAN, ctx);
+
+       sgen_scan_pin_queue_objects (ctx);
 }
 
 static void
@@ -3008,6 +3012,7 @@ sgen_gc_init (void)
 
        alloc_nursery ();
 
+       sgen_pinning_init ();
        sgen_cement_init (cement_enabled);
 
        if ((env = g_getenv (MONO_GC_DEBUG_NAME))) {
index 223116861a66974e1139928cbb335f127254da88..6fc24a2151a8e4b464f94cb5724afe32af392a6e 100644 (file)
@@ -477,7 +477,7 @@ null_link_if (gpointer hidden, GCHandleType handle_type, int max_generation, gpo
                return hidden;
 
        if (closure->predicate (obj, closure->data))
-               return NULL;
+               return MONO_GC_HANDLE_METADATA_POINTER (sgen_client_default_metadata (), GC_HANDLE_TYPE_IS_WEAK (handle_type));
 
        return hidden;
 }
index 2bbfaff19c66074962f0f2389b190a44d040ff80..4c63191ad447d0ea5c9fb76bf44f9eba3ee19b46 100644 (file)
@@ -162,7 +162,7 @@ static int fast_block_obj_size_indexes [MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES];
 static gboolean *evacuate_block_obj_sizes;
 static float evacuation_threshold = 0.666f;
 
-static gboolean lazy_sweep = FALSE;
+static gboolean lazy_sweep = TRUE;
 
 enum {
        SWEEP_STATE_SWEPT,
@@ -810,6 +810,7 @@ set_sweep_state (int new_, int expected)
 static gboolean ensure_block_is_checked_for_sweeping (guint32 block_index, gboolean wait, gboolean *have_checked);
 
 static SgenThreadPoolJob * volatile sweep_job;
+static SgenThreadPoolJob * volatile sweep_blocks_job;
 
 static void
 major_finish_sweep_checking (void)
@@ -1578,6 +1579,20 @@ ensure_block_is_checked_for_sweeping (guint32 block_index, gboolean wait, gboole
        return !!tagged_block;
 }
 
+static void
+sweep_blocks_job_func (void *thread_data_untyped, SgenThreadPoolJob *job)
+{
+       volatile gpointer *slot;
+
+       SGEN_ARRAY_LIST_FOREACH_SLOT (&allocated_blocks, slot) {
+               sweep_block (BLOCK_UNTAG (*slot));
+       } SGEN_ARRAY_LIST_END_FOREACH_SLOT;
+
+       mono_memory_write_barrier ();
+
+       sweep_blocks_job = NULL;
+}
+
 static void
 sweep_job_func (void *thread_data_untyped, SgenThreadPoolJob *job)
 {
@@ -1619,6 +1634,16 @@ sweep_job_func (void *thread_data_untyped, SgenThreadPoolJob *job)
 
        sgen_array_list_remove_nulls (&allocated_blocks);
 
+       /*
+        * Concurrently sweep all the blocks to reduce workload during minor
+        * pauses where we need certain blocks to be swept. At the start of
+        * the next major we need all blocks to be swept anyway.
+        */
+       if (concurrent_sweep && lazy_sweep) {
+               sweep_blocks_job = sgen_thread_pool_job_alloc ("sweep_blocks", sweep_blocks_job_func, sizeof (SgenThreadPoolJob));
+               sgen_thread_pool_job_enqueue (sweep_blocks_job);
+       }
+
        sweep_finish ();
 
        sweep_job = NULL;
@@ -1645,6 +1670,8 @@ sweep_finish (void)
        sgen_memgov_major_post_sweep ();
 
        set_sweep_state (SWEEP_STATE_SWEPT, SWEEP_STATE_COMPACTING);
+       if (concurrent_sweep)
+               binary_protocol_concurrent_sweep_end (sgen_timestamp ());
 }
 
 static void
@@ -1864,12 +1891,22 @@ major_start_major_collection (void)
                sgen_evacuation_freelist_blocks (&free_block_lists [MS_BLOCK_FLAG_REFS][i], i);
        }
 
-       if (lazy_sweep)
-               binary_protocol_sweep_begin (GENERATION_OLD, TRUE);
+       if (lazy_sweep && concurrent_sweep) {
+               /*
+                * sweep_blocks_job is created before sweep_finish, which we wait for above
+                * (major_finish_sweep_checking). After the end of sweep, if we don't have
+                * sweep_blocks_job set, it means that it has already been run.
+                */
+               SgenThreadPoolJob *job = sweep_blocks_job;
+               if (job)
+                       sgen_thread_pool_job_wait (job);
+       }
 
+       if (lazy_sweep && !concurrent_sweep)
+               binary_protocol_sweep_begin (GENERATION_OLD, TRUE);
        /* Sweep all unswept blocks and set them to MARKING */
        FOREACH_BLOCK_NO_LOCK (block) {
-               if (lazy_sweep)
+               if (lazy_sweep && !concurrent_sweep)
                        sweep_block (block);
                SGEN_ASSERT (0, block->state == BLOCK_STATE_SWEPT, "All blocks must be swept when we're pinning.");
                set_block_state (block, BLOCK_STATE_MARKING, BLOCK_STATE_SWEPT);
@@ -1881,8 +1918,7 @@ major_start_major_collection (void)
                if (evacuate_block_obj_sizes [block->obj_size_index] && !block->free_list)
                        block->is_to_space = TRUE;
        } END_FOREACH_BLOCK_NO_LOCK;
-
-       if (lazy_sweep)
+       if (lazy_sweep && !concurrent_sweep)
                binary_protocol_sweep_end (GENERATION_OLD, TRUE);
 
        set_sweep_state (SWEEP_STATE_NEED_SWEEPING, SWEEP_STATE_SWEPT);
index eedd1f0343a93e720cac0838ec29ff70e8bd773e..cfe3db1acd0167bd08d1c7e285b6313736460ec3 100644 (file)
 
 static SgenPointerQueue pin_queue;
 static size_t last_num_pinned = 0;
+/*
+ * While we hold the pin_queue_mutex, all objects in pin_queue_objs will
+ * stay pinned, which means they can't move, therefore they can be scanned.
+ */
+static SgenPointerQueue pin_queue_objs;
+static MonoCoopMutex pin_queue_mutex;
 
 #define PIN_HASH_SIZE 1024
 static void *pin_hash_filter [PIN_HASH_SIZE];
 
+void
+sgen_pinning_init (void)
+{
+       mono_coop_mutex_init (&pin_queue_mutex);
+}
+
 void
 sgen_init_pinning (void)
 {
+       mono_coop_mutex_lock (&pin_queue_mutex);
        memset (pin_hash_filter, 0, sizeof (pin_hash_filter));
        pin_queue.mem_type = INTERNAL_MEM_PIN_QUEUE;
+       sgen_pointer_queue_clear (&pin_queue_objs);
 }
 
 void
@@ -37,6 +51,27 @@ sgen_finish_pinning (void)
 {
        last_num_pinned = pin_queue.next_slot;
        sgen_pointer_queue_clear (&pin_queue);
+       mono_coop_mutex_unlock (&pin_queue_mutex);
+}
+
+void
+sgen_pinning_register_pinned_in_nursery (GCObject *obj)
+{
+       sgen_pointer_queue_add (&pin_queue_objs, obj);
+}
+
+void
+sgen_scan_pin_queue_objects (ScanCopyContext ctx)
+{
+       int i;
+       ScanObjectFunc scan_func = ctx.ops->scan_object;
+
+       mono_coop_mutex_lock (&pin_queue_mutex);
+       for (i = 0; i < pin_queue_objs.next_slot; ++i) {
+               GCObject *obj = (GCObject *)pin_queue_objs.data [i];
+               scan_func (obj, sgen_obj_get_descriptor_safe (obj), ctx.queue);
+       }
+       mono_coop_mutex_unlock (&pin_queue_mutex);
 }
 
 void
index 00eb20dd819830f40a45a620981e812426673df2..2ae2594fa85e1c762898e60d43e6caafaf0ed40a 100644 (file)
@@ -18,10 +18,13 @@ enum {
        PIN_TYPE_MAX
 };
 
+void sgen_pinning_init (void);
 void sgen_pin_stage_ptr (void *ptr);
 void sgen_optimize_pin_queue (void);
 void sgen_init_pinning (void);
 void sgen_finish_pinning (void);
+void sgen_pinning_register_pinned_in_nursery (GCObject *obj);
+void sgen_scan_pin_queue_objects (ScanCopyContext ctx);
 void sgen_pin_queue_clear_discarded_entries (GCMemSection *section, size_t max_pin_slot);
 size_t sgen_get_pinned_count (void);
 void sgen_pinning_setup_section (GCMemSection *section);
index 8a190ef6f494df314fa590d74a0022af78f28294..3ab36e3bf660f380b9b21cf554f0e659899eb520 100644 (file)
@@ -435,6 +435,13 @@ MATCH_INDEX (BINARY_PROTOCOL_MATCH)
 IS_VTABLE_MATCH (FALSE)
 END_PROTOCOL_ENTRY
 
+BEGIN_PROTOCOL_ENTRY1 (binary_protocol_concurrent_sweep_end, TYPE_LONGLONG, timestamp)
+DEFAULT_PRINT ()
+IS_ALWAYS_MATCH (TRUE)
+MATCH_INDEX (BINARY_PROTOCOL_MATCH)
+IS_VTABLE_MATCH (FALSE)
+END_PROTOCOL_ENTRY
+
 #undef BEGIN_PROTOCOL_ENTRY0
 #undef BEGIN_PROTOCOL_ENTRY1
 #undef BEGIN_PROTOCOL_ENTRY2
index 965b148ec74a6989ce25b6817e334af0b3f0f36a..86a740ca0579e5dc75f60f5025acf3b457ca0959 100644 (file)
@@ -435,7 +435,8 @@ BASE_TEST_CS_SRC=           \
        pinvoke_ppcs.cs \
        pinvoke_ppci.cs \
        pinvoke_ppcf.cs \
-       pinvoke_ppcd.cs
+       pinvoke_ppcd.cs \
+       bug-29585.cs
 
 TEST_CS_SRC_DIST=      \
        $(BASE_TEST_CS_SRC)     \
@@ -963,7 +964,7 @@ debug-casts:
        @$(MCS) -r:TestDriver.dll $(srcdir)/debug-casts.cs
        @$(RUNTIME) --debug=casts debug-casts.exe
 
-EXTRA_DIST += sgen-bridge.cs sgen-descriptors.cs sgen-gshared-vtype.cs sgen-bridge-major-fragmentation.cs sgen-domain-unload.cs sgen-weakref-stress.cs sgen-cementing-stress.cs sgen-case-23400.cs     finalizer-wait.cs critical-finalizers.cs sgen-domain-unload-2.cs sgen-suspend.cs sgen-new-threads-dont-join-stw.cs sgen-bridge-xref.cs bug-17590.cs sgen-toggleref.cs
+EXTRA_DIST += sgen-bridge.cs sgen-descriptors.cs sgen-gshared-vtype.cs sgen-bridge-major-fragmentation.cs sgen-domain-unload.cs sgen-weakref-stress.cs sgen-cementing-stress.cs sgen-case-23400.cs     finalizer-wait.cs critical-finalizers.cs sgen-domain-unload-2.cs sgen-suspend.cs sgen-new-threads-dont-join-stw.cs sgen-bridge-xref.cs bug-17590.cs sgen-toggleref.cs sgen-bridge-gchandle.cs
 
 
 sgen-tests:
@@ -1104,6 +1105,38 @@ sgen-bridge2-tests-plain-tarjan-bridge: $(SGEN_BRIDGE2_TESTS) test-runner.exe
 sgen-bridge2-tests-ms-split-tarjan-bridge: $(SGEN_BRIDGE2_TESTS) test-runner.exe
        MONO_ENV_OPTIONS="--gc=sgen" MONO_GC_DEBUG="bridge=2Bridge" MONO_GC_PARAMS="bridge-implementation=tarjan,minor=split" $(RUNTIME) ./test-runner.exe --testsuite-name $@ --timeout 900 $(SGEN_BRIDGE2_TESTS)
 
+
+SGEN_BRIDGE3_TESTS=    \
+       sgen-bridge-gchandle.exe
+
+sgen-bridge3-tests: $(SGEN_BRIDGE3_TESTS)
+       $(MAKE) sgen-bridge3-tests-plain
+       $(MAKE) sgen-bridge3-tests-ms-conc
+       $(MAKE) sgen-bridge3-tests-ms-split
+       $(MAKE) sgen-bridge3-tests-plain-new-bridge
+       $(MAKE) sgen-bridge3-tests-ms-conc-new-bridge
+       $(MAKE) sgen-bridge3-tests-ms-split-new-bridge
+       $(MAKE) sgen-bridge3-tests-plain-tarjan-bridge
+       $(MAKE) sgen-bridge3-tests-ms-split-tarjan-bridge
+
+sgen-bridge3-tests-plain: $(SGEN_bridge3_TESTS) test-runner.exe
+       MONO_ENV_OPTIONS="--gc=sgen" MONO_GC_DEBUG="bridge=3Bridge" MONO_GC_PARAMS="" $(RUNTIME) ./test-runner.exe --testsuite-name $@ --timeout 900 $(SGEN_BRIDGE3_TESTS)
+sgen-bridge3-tests-ms-conc: $(SGEN_BRIDGE3_TESTS) test-runner.exe
+       MONO_ENV_OPTIONS="--gc=sgen" MONO_GC_DEBUG="bridge=3Bridge" MONO_GC_PARAMS="major=marksweep-conc" $(RUNTIME) ./test-runner.exe --testsuite-name $@ --timeout 900 $(SGEN_BRIDGE3_TESTS)
+sgen-bridge3-tests-ms-split: $(SGEN_BRIDGE3_TESTS) test-runner.exe
+       MONO_ENV_OPTIONS="--gc=sgen" MONO_GC_DEBUG="bridge=3Bridge" MONO_GC_PARAMS="minor=split" $(RUNTIME) ./test-runner.exe --testsuite-name $@ --timeout 900 $(SGEN_BRIDGE3_TESTS)
+sgen-bridge3-tests-plain-new-bridge: $(SGEN_BRIDGE3_TESTS) test-runner.exe
+       MONO_ENV_OPTIONS="--gc=sgen" MONO_GC_DEBUG="bridge=3Bridge" MONO_GC_PARAMS="bridge-implementation=new" $(RUNTIME) ./test-runner.exe --testsuite-name $@ --timeout 900 $(SGEN_BRIDGE3_TESTS)
+sgen-bridge3-tests-ms-conc-new-bridge: $(SGEN_BRIDGE3_TESTS) test-runner.exe
+       MONO_ENV_OPTIONS="--gc=sgen" MONO_GC_DEBUG="bridge=3Bridge" MONO_GC_PARAMS="bridge-implementation=new,major=marksweep-conc" $(RUNTIME) ./test-runner.exe --testsuite-name $@ --timeout 900 $(SGEN_BRIDGE3_TESTS)
+sgen-bridge3-tests-ms-split-new-bridge: $(SGEN_BRIDGE3_TESTS) test-runner.exe
+       MONO_ENV_OPTIONS="--gc=sgen" MONO_GC_DEBUG="bridge=3Bridge" MONO_GC_PARAMS="bridge-implementation=new,minor=split" $(RUNTIME) ./test-runner.exe --testsuite-name $@ --timeout 900 $(SGEN_BRIDGE3_TESTS)
+sgen-bridge3-tests-plain-tarjan-bridge: $(SGEN_BRIDGE3_TESTS) test-runner.exe
+       MONO_ENV_OPTIONS="--gc=sgen" MONO_GC_DEBUG="bridge=3Bridge" MONO_GC_PARAMS="bridge-implementation=tarjan" $(RUNTIME) ./test-runner.exe --testsuite-name $@ --timeout 900 $(SGEN_BRIDGE3_TESTS)
+sgen-bridge3-tests-ms-split-tarjan-bridge: $(SGEN_BRIDGE3_TESTS) test-runner.exe
+       MONO_ENV_OPTIONS="--gc=sgen" MONO_GC_DEBUG="bridge=3Bridge" MONO_GC_PARAMS="bridge-implementation=tarjan,minor=split" $(RUNTIME) ./test-runner.exe --testsuite-name $@ --timeout 900 $(SGEN_BRIDGE3_TESTS)
+
+
 AOT_CONFIGURATIONS=    \
        "|regular"      \
        "--gc=boehm|boehm"
diff --git a/mono/tests/bug-29585.cs b/mono/tests/bug-29585.cs
new file mode 100644 (file)
index 0000000..a1289fa
--- /dev/null
@@ -0,0 +1,54 @@
+namespace TestCase
+{
+    using System;
+    using System.Linq;
+    using System.Reflection;
+
+
+    public class MainClass
+    {
+        public static int Main()
+        {
+            return new GenericDerived<Param>().FindMethod();
+        }
+    }
+
+
+    interface Param
+    {
+    }
+
+
+    class GenericDerived<T> :
+        Abstract<GenericDerived<T>>
+    {
+        public int FindMethod()
+        {
+            return FindGenericMethod<T>();
+        }
+    }
+
+
+    abstract class Abstract<TDerived>
+        where TDerived : Abstract<TDerived>
+    {
+        protected virtual int FindGenericMethod<T>()
+        {
+            var method = typeof(TDerived)
+                .GetMethods(BindingFlags.Instance | BindingFlags.NonPublic)
+                .FirstOrDefault(x => x.Name == "FindGenericMethod" && x.IsGenericMethod);
+
+            Console.WriteLine("TDerived = {0}", typeof(TDerived));
+            Console.WriteLine("method = {0}", method);
+            Console.WriteLine("method.DeclaringType = {0}", method.DeclaringType);
+            Console.WriteLine("method.IsGenericMethod = {0}", method.IsGenericMethod);
+            Console.WriteLine("method.IsGenericMethodDefinition = {0}", method.IsGenericMethodDefinition);
+                       
+                       if (!method.IsGenericMethod)
+                               return 1;
+                       if (!method.IsGenericMethodDefinition)
+                               return 2;
+                       return 0;
+        }
+    }
+}
\ No newline at end of file
diff --git a/mono/tests/sgen-bridge-gchandle.cs b/mono/tests/sgen-bridge-gchandle.cs
new file mode 100644 (file)
index 0000000..c9a7064
--- /dev/null
@@ -0,0 +1,78 @@
+using System;
+using System.Collections;
+using System.Threading;
+using System.Runtime.InteropServices;
+
+
+public class Bridge {
+       public int __test;
+       public string id;
+       
+       ~Bridge () {
+               try {Console.WriteLine ("bridge {0} gone", id);} catch (Exception) {}
+       }
+}
+
+
+/*
+Test scenario:
+       Alloc a bridge and create a gc handle to it
+       Get it collected.
+       Create another one and see it steal the handle of the previous one.
+
+
+*/
+class Driver {
+       public static GCHandle weak_track_handle;
+       public static GCHandle weak_track_handle2;
+
+       static void CreateFirstBridge () {
+               Bridge b = new Bridge() {
+                       __test = 0,
+                       id = "first",
+               };
+               weak_track_handle = GCHandle.Alloc (b, GCHandleType.WeakTrackResurrection);
+       }
+
+       static void CreateSecondBridge () {
+               Bridge b = new Bridge() {
+                       __test = 1,
+                       id = "second",
+               };
+               weak_track_handle2 = GCHandle.Alloc (b, GCHandleType.WeakTrackResurrection);
+       }
+
+       static void DumpHandle (GCHandle h, string name) {
+               Console.WriteLine ("{0}:{1:X} alloc:{2} hasValue:{2}", name, (IntPtr)h, h.IsAllocated, h.Target == null);
+       }
+
+       static int Main () {
+               var t = new Thread (CreateFirstBridge);
+               t.Start ();
+               t.Join ();
+
+               GC.Collect ();
+               GC.WaitForPendingFinalizers ();
+               Console.WriteLine ("GC DONE");
+
+               DumpHandle (weak_track_handle, "weak-track1");
+
+               t = new Thread (CreateSecondBridge);
+               t.Start ();
+               t.Join ();
+
+               GC.Collect ();
+               GC.WaitForPendingFinalizers ();
+               Console.WriteLine ("GC DONE");
+               DumpHandle (weak_track_handle, "weak-track1");
+               DumpHandle (weak_track_handle2, "weak-track2");
+               Console.WriteLine ("DONE");
+
+               if ((IntPtr)weak_track_handle == (IntPtr)weak_track_handle2) {
+                       Console.WriteLine ("FIRST HANDLE GOT DEALLOCATED!");
+                       return 1;
+               }
+
+               return 0;
+       }
+}
index c170df2714ec8499ac96e8391aaa2f1b8a583a01..b61302fec3a7ab135a8e1d1c19702d42ba60f44e 100644 (file)
@@ -1,19 +1,19 @@
 
 %.exe: %.cil
-       ilasm2 -out:$@ $<
+       ilasm -out:$@ $<
 
 BatchCompiler.exe: BatchCompiler.cs
-       gmcs -r:../../../mcs/class/lib/net_2_0/ilasm.exe BatchCompiler.cs
+       mcs -r:../../../mcs/class/lib/net_4_x/ilasm.exe BatchCompiler.cs
 
 test_lib.dll: test_lib.cs
-       gmcs test_lib.cs -target:library
+       mcs test_lib.cs -target:library
 
 compile-stamp: generate-stamp BatchCompiler.exe test_lib.dll
        for i in *.cs; do \
                EXE="`echo $$i | cut -d. -f1`.exe"; \
                DLL="`echo $$i | cut -d. -f1`.dll"; \
                if ! [ -f $$EXE ] && ! [ -f $$DLL ]; then \
-                       gmcs /unsafe $$i; \
+                       mcs /unsafe $$i; \
                fi \
        done 
        #MONO_PATH=../../../mcs/class/lib/net_2_0/ mono BatchCompiler.exe
@@ -42,7 +42,7 @@ run-test: compile-stamp
                then \
                        RES=3; \
                fi; \
-               if [ "$$FIRST" == "unverifiable" ] || [ "$FIRST" == "typeunverifiable" ]; \
+               if [ "$$FIRST" == "unverifiable" ] || [ "$$FIRST" == "typeunverifiable" ]; \
                then \
                        RES=2; \
                fi; \
@@ -56,37 +56,37 @@ run-test: compile-stamp
                fi; \
                if [ "$$FIRST" == "strict" ]; \
                then \
-                       #in strict more it must fail under strict check and pass under non-strict check \
+                       echo "#in strict more it must fail under strict check and pass under non-strict check" >/dev/null; \
                        ../../metadata/pedump --verify partial-md,error,warn,cls,code $$TEST.exe >/dev/null 2>/dev/null; \
                        R1=$$?; \
                        ../../metadata/pedump --verify partial-md,error,warn,cls,code,non-strict $$TEST.exe >/dev/null 2>/dev/null; \
                        R2=$$?; \
                        if [ $$R1 != 2 ] && [ $$R1 != 3 ]; then \
                                echo "$$TEST is strict but did not fail under strict check, got $${R1} but expected 2 or 3"; \
-                       fi \
-                       #non-strict result \
+                       fi; \
+                       echo "#non-strict result" >/dev/null; \
                        if [ $$R2 != 0 ]; then \
                                echo "$$TEST is strict but did not pass under non-strict check, got $${R2} but expected 0"; \
-                       fi \
+                       fi; \
                elif [ "$$FIRST" == "typeunverifiable" ]; then \
-                       #in type unverifiable more it must fail under verifiable mode but it's ok under valid mode \
+                       echo "#in type unverifiable more it must fail under verifiable mode but it's ok under valid mode" >/dev/null; \
                        ../../metadata/pedump --verify partial-md,error,warn,cls,code $$TEST.exe  >/dev/null 2>/dev/null; \
                        R1=$$?; \
                        ../../metadata/pedump --verify partial-md,error,warn,cls,code,valid-only $$TEST.exe  >/dev/null 2>/dev/null; \
                        R2=$$?; \
                        if [ $$R1 != 3 ]; then \
                                echo "$$TEST is type unverifiable but did not fail under verifiable check, got $${R1} but expected 3"; \
-                       fi \
-                       #type unverifiable result \
+                       fi; \
+                       echo "#type unverifiable result" >/dev/null; \
                        if [ $$R2 != 0 ]; then \
                                echo "$$TEST is type unverifiable but did not pass under non-strict check, got $${R2} but expected 0"; \
-                       fi \
+                       fi; \
                elif [ $$RES != 99 ]; then \
                        ../../metadata/pedump --verify partial-md,error,warn,cls,code $$TEST.exe >/dev/null 2>/dev/null; \
                        R=$$?; \
                        if [ $$R != $$RES ]; then \
                                echo "$$TEST failed expected $$RES but got $$R"; \
-                       fi \
+                       fi; \
                fi; \
        done
 
index bbbf83024848d1e285df2c10417a0125de7f4df8..72be8020ee54eb6d2d34905f68915604e0f0b700 100755 (executable)
@@ -13,7 +13,7 @@ TEST_MEMBER_ACCESS=$5
 TEST_EXTENDS=$6
 TEST_USE_SUB_CLASS=$7
 
-if [ "$TEST_EXTENDS" == "yes" ]; then
+if [ "$TEST_EXTENDS" = "yes" ]; then
        TEST_EXTENDS="extends Class"
        TEST_SUPER_TYPE="Class"
 else
@@ -21,7 +21,7 @@ else
        TEST_SUPER_TYPE="object"
 fi
 
-if [ "$TEST_USE_SUB_CLASS" == "yes" ]; then
+if [ "$TEST_USE_SUB_CLASS" = "yes" ]; then
        TEST_VAR_TYPE="ExampleClass"
 else
        TEST_VAR_TYPE="Class"
@@ -87,4 +87,4 @@ $SED -e "s/SUPER_TYPE/${TEST_SUPER_TYPE}/g" -e "s/VALIDITY/${TEST_VALIDITY}/g" -
                ret
        }
 }
-//EOF
\ No newline at end of file
+//EOF
index 73b79622f5b77461de8f3b3764aa7f87a692368e..4356497ea37651a6a257db532d0607c03b1017e5 100755 (executable)
@@ -11,7 +11,7 @@ TEST_BYTE_0=$3
 TEST_BYTE_1=$4
 
 
-if [ "$TEST_BYTE_1" == "" ] ; then
+if [ "x$TEST_BYTE_1" = "x" ] ; then
        TEST_BYTE_1="0";
 fi
 
index 5ebbbb99416c577541df95516d369ae1137f9e3c..019b453beb181e8a35fb69838eae9bca94dd06c3 100755 (executable)
@@ -12,7 +12,7 @@ TEST_TYPE2=$5
 TEST_INIT_EXP=$6
 TEST_INIT_VAL=$7
 
-if [ "$TEST_INIT_VAL" == "yes" ]; then
+if [ "$TEST_INIT_VAL" = "yes" ]; then
        TEST_INIT="$TEST_INIT_EXP\n\t\stloc.1"
 else
        TEST_INIT=""
@@ -50,4 +50,4 @@ $SED -e "s/INIT/${TEST_INIT}/g" -e "s/VALIDITY/${TEST_VALIDITY}/g" -e "s/TYPE1/$
        ldc.i4.0
        ret
 }
-//EOF
\ No newline at end of file
+//EOF
index 9522718a1c712f2e2d3417a8c7e756ca6a72c702..32428322b688a18ebd061db69c66814d75aa8634 100755 (executable)
@@ -11,7 +11,7 @@ TEST_OP=$3
 TEST_BEFORE_OP=$4
 TEST_CONSTRAINT_TYPE=$5
 
-if [ "$TEST_CONSTRAINT_TYPE" == "" ]; then
+if [ "x$TEST_CONSTRAINT_TYPE" = "x" ]; then
        TEST_CONSTRAINT_TYPE="IFace";
 fi
 
index 5ae54d3cafff22dcadeadfb4ba441fd7bc11e0e5..9ea87a414cfec29ca8edbf1d2964a82ff7eb7bde 100755 (executable)
@@ -11,7 +11,7 @@ TEST_POS=$3
 TEST_OP=$4
 TEST_FIN=$5
 
-if [ "$TEST_FIN" == "" ]; then
+if [ "x$TEST_FIN" = "x" ]; then
        TEST_FIN="finally";
 fi
 
index 884333b2accd748873009ebb8d6765c31824e362..08605a0f9cf29fca1648d502bb1e73b3d6839df4 100755 (executable)
@@ -12,7 +12,7 @@ TEST_LOAD_ARGS=$4
 TEST_INSTANCE_METHOD=$5
 TEST_EXTRA_STUFF=$6
 
-if [ "$TEST_INSTANCE_METHOD" == "instance" ]; then
+if [ "$TEST_INSTANCE_METHOD" = "instance" ]; then
        MEMBER_TEST_OP=$TEST_OP
        MEMBER_TEST_LOAD_ARGS=$TEST_LOAD_ARGS
        MEMBER_TEST_EXTRA_STUFF=$6
index 9e8894a709eb9ce5637d6cb040e5c37b59ad7e90..2687f0dfe687b95c2adf7b5a67b38d5de4cb7c9b 100755 (executable)
@@ -14,7 +14,7 @@ TEST_BEFORE_OP=$6
 
 echo $TEST_OP | grep unbox > /dev/null;
 
-if [ "$?" == "0" ]; then
+if [ $? -eq 0 ]; then
        TEST_CODE="
        ldloc.0
        box $TEST_TYPE";
index 008d485bedfb405f73a80212d3b7e52366041a33..5110b563ff63b3ca8c0b4f0cf2afcf2bf49c57e1 100755 (executable)
@@ -15,7 +15,7 @@ TEST_EXTRA_OPS=$6
 ZZ=`echo $TEST_TYPE1 | grep "\&"`
 T1_REF=$?
 
-if [ "$T1_REF" == "0" ]; then
+if [ $T1_REF -eq 0 ]; then
        T1_NO_REF=`echo $TEST_TYPE1 | cut -d '\' -f 1`
        INIT_LOCS=", $T1_NO_REF V_2"
        INIT_IL="ldloca.s 2\n\tstloc.0"
@@ -24,9 +24,9 @@ fi
 ZZ=`echo $TEST_TYPE2 | grep "\&"`
 T2_REF=$?
 
-if [ "$T2_REF" == "0" ]; then
+if [ $T2_REF -eq 0 ]; then
        T2_NO_REF=`echo $TEST_TYPE2 | cut -d '\' -f 1`
-       if [ "$T1_REF" == "0" ]; then
+       if [ $T1_REF -eq 0 ]; then
                INIT_LOCS="$INIT_LOCS , $T2_NO_REF V_3"
                INIT_IL="$INIT_IL \n\tldloca.s 3\n\tstloc.1"
        else
index e34c2fbe360238f2b8b8f28bf086f67327a50fee..b94b7e960bf38c25add04f1ed2177ab46c1e9c6e 100755 (executable)
@@ -14,7 +14,7 @@ TEST_EXTENDS=$6
 TEST_LOAD_BASE=$7
 
 
-if [ "$TEST_EXTENDS" == "yes" ]; then
+if [ "$TEST_EXTENDS" = "yes" ]; then
        TEST_EXTENDS="extends Owner\/Nested"
        TEST_CONSTRUCTOR="call instance void Owner\/Nested::.ctor()"
 else
@@ -22,7 +22,7 @@ else
        TEST_CONSTRUCTOR="call instance void object::.ctor()"
 fi
 
-if [ "$TEST_LOAD_BASE" == "yes" ]; then
+if [ "$TEST_LOAD_BASE" = "yes" ]; then
        TEST_LOAD_REF="ldarg.0"
 else
        TEST_LOAD_REF="call class Owner\/Nested Owner::Create ()"
index 81febde0c3046a92dd2316c866233f8d3b756ff8..6325f6167971059efb0444b3b09071e0ca490f70 100755 (executable)
@@ -13,7 +13,7 @@ TEST_TARGET_TYPE=$4
 TARGET_TYPE="Test"
 TEST_OTHER_CODE="call instance void TestClass::'.ctor'()"
 
-if [ "$TEST_TARGET_TYPE" == "other" ]; then
+if [ "$TEST_TARGET_TYPE" = "other" ]; then
        TARGET_TYPE="TestSubClass"
        TEST_OTHER_CODE=$TEST_CODE
        TEST_CODE=""
index a12b82c373a3279f9c89a3ed90403f7ee7f0d48c..31b8581fbe7f68025fde4127eb10511e796ab093 100755 (executable)
@@ -26,7 +26,7 @@ fi
 RET_2_LOCAL="$TEST_RET_TYPE2"
 RET_2_OP="ldloc 0"
 
-if [ "$TEST_RET_TYPE2" == "void" ]; then
+if [ "$TEST_RET_TYPE2" = "void" ]; then
        RET_2_LOCAL="int32"
        RET_2_OP="nop"
 fi
@@ -47,7 +47,7 @@ MANAGED_METHOD="
        }
 "
 
-if [ "$TEST_USE_NATIVE" == "pinvoke" ]; then
+if [ "$TEST_USE_NATIVE" = "pinvoke" ]; then
        LDFTN="ldftn $TCONV_2 ${TEST_RET_TYPE2} Driver::NativeMethod(${TEST_PARAM_TYPE2})"
        CALLVIRT="nop"
        MANAGED_METHOD=""
index 68bc551cf9fef66fbd3d9c291fb70dec22dc6daf..f6271e2fb9599ab7706dca36622187cf145fd1fc 100755 (executable)
@@ -16,7 +16,7 @@ TEST_NESTED_EXTENDS=$8
 TEST_LOAD_BASE=$9
 
 
-if [ "$TEST_BASE_EXTENDS" == "yes" ]; then
+if [ "$TEST_BASE_EXTENDS" = "yes" ]; then
        TEST_BASE_EXTENDS="extends Root"
        TEST_BASE_CONSTRUCTOR="call instance void Root::.ctor()"
 else
@@ -24,7 +24,7 @@ else
        TEST_BASE_CONSTRUCTOR="call instance void object::.ctor()"
 fi
 
-if [ "$TEST_NESTED_EXTENDS" == "yes" ]; then
+if [ "$TEST_NESTED_EXTENDS" = "yes" ]; then
        TEST_NESTED_EXTENDS="extends Root\/Nested"
        TEST_NESTED_CONSTRUCTOR="call instance void Root\/Nested::.ctor()"
 else
@@ -32,7 +32,7 @@ else
        TEST_NESTED_CONSTRUCTOR="call instance void object::.ctor()"
 fi
 
-if [ "$TEST_LOAD_BASE" == "yes" ]; then
+if [ "$TEST_LOAD_BASE" = "yes" ]; then
        TEST_LOAD_REF="ldarg.0"
 else
        TEST_LOAD_REF="call class Root\/Nested Root::Create ()"
index 284fadfd7e6d81c92e8bfb7c4ef7dc0887bbe103..0647eed5b19b73bad74a5401a8d7469b508a0dc7 100755 (executable)
@@ -12,7 +12,7 @@ TEST_BLOCK_2=$4
 TEST_WITH_FILTER_BLOCK=$5
 TEST_WITH_FINALLY_BLOCK=$6
 
-if [ "$TEST_WITH_FILTER_BLOCK" == "yes" ]; then
+if [ "$TEST_WITH_FILTER_BLOCK" = "yes" ]; then
        FILTER_BLOCK="
 FILTER_BLOCK_3:
        nop
@@ -35,7 +35,7 @@ else
        FILTER_BLOCK="";
 fi
 
-if [ "$TEST_WITH_FINALLY_BLOCK" == "yes" ]; then
+if [ "$TEST_WITH_FINALLY_BLOCK" = "yes" ]; then
        FINALLY_BLOCK="
 FINALLY_BLOCK_1:
        nop
index a50a5f4385c692cdc1fdf7068b681172c4cb40c9..8d72117ffc2918268a9c31695a832234e63e1f5f 100755 (executable)
@@ -11,7 +11,7 @@ TEST_OP=$3
 TEST_TYPE1=$4
 TEST_TYPE2=$5
 TEST_EMIT_CSTOR=$6
-if [ "${TEST_EMIT_CSTOR}" == "yes" ]; then
+if [ "${TEST_EMIT_CSTOR}" = "yes" ]; then
        TEST_CSTOR="newobj instance void ${TEST_TYPE2}::.ctor()";
 else
        TEST_CSTOR="ldloc.0";
index 3382ff99d6e279d332f4f7e4e5b312ca3a35330d..5b1e064afaa1862cffca7723282e622fcd79131f 100755 (executable)
@@ -14,7 +14,7 @@ ZZ=`echo $TEST_TYPE1 | grep "\&"`
 T1_REF=$?
 
 LOCAL_INIT="";
-if [ "$T1_REF" == "0" ]; then
+if [ $T1_REF -eq 0 ]; then
        T1_NO_REF=`echo $TEST_TYPE1 | cut -d '\' -f 1`
        INIT_LOCS=", $T1_NO_REF V_0"
        INIT_IL="ldloca.s 1\n\tstloc.0"
index c314cf297020215183136ba7073d23d29d2d9091..4a2f84a1ed6bd0796a57d3071e6bc7127ebf404d 100755 (executable)
@@ -13,7 +13,7 @@ ZZ=`echo $TEST_TYPE1 | grep "\&"`
 T1_REF=$?
 
 LOCAL_INIT="";
-if [ "$T1_REF" == "0" ]; then
+if [ $T1_REF -eq 0 ]; then
        T1_NO_REF=`echo $TEST_TYPE1 | cut -d '\' -f 1`
        INIT_LOCS=", $T1_NO_REF V_0"
        INIT_IL="ldloca.s 1\n\tstloc.0"
index 8a5016a7fd1d9b05af28ec1c5f38dd24f09d037c..e53849cf18cdf7ef5c216834689978a169786f81 100755 (executable)
@@ -16,14 +16,14 @@ TRY_END="
                leave END
        }"
 
-if [ "$TEST_BLOCK" == "catch" ]; then
+if [ "$TEST_BLOCK" = "catch" ]; then
        TRY_MIDDLE="
                leave END
        } catch [mscorlib]System.NullReferenceException {"
        TRY_END="
                leave END
        }"
-elif [ "$TEST_BLOCK" == "filter" ]; then
+elif [ "$TEST_BLOCK" = "filter" ]; then
        TRY_MIDDLE="
                leave END
        } filter {"
@@ -34,7 +34,7 @@ elif [ "$TEST_BLOCK" == "filter" ]; then
        } {
                leave END
        }"
-elif [ "$TEST_BLOCK" == "handler" ]; then
+elif [ "$TEST_BLOCK" = "handler" ]; then
        TRY_MIDDLE="
                leave END
        } filter {
@@ -45,14 +45,14 @@ elif [ "$TEST_BLOCK" == "handler" ]; then
        TRY_END="
                leave END
        }"
-elif [ "$TEST_BLOCK" == "finally" ]; then
+elif [ "$TEST_BLOCK" = "finally" ]; then
        TRY_MIDDLE="
                leave END
        } finally {"
        TRY_END="
                endfinally
        }"
-elif [ "$TEST_BLOCK" == "fault" ]; then
+elif [ "$TEST_BLOCK" = "fault" ]; then
        TRY_MIDDLE="
                leave END
        } fault {"
index d096e85256619db690df7a107f9561fe4fbc7fe1..5fd41668a68d9a3de2ddd20729a57698a6822095 100755 (executable)
@@ -12,7 +12,7 @@ TEST_CLASS_ACCESS=$4
 TEST_MEMBER_ACCESS=$5
 TEST_EXTENDS=$6
 
-if [ "$TEST_EXTENDS" == "yes" ]; then
+if [ "$TEST_EXTENDS" = "yes" ]; then
        TEST_EXTENDS="extends Owner"
        TEST_CONSTRUCTOR="call instance void Owner::.ctor()"
 else
@@ -108,4 +108,4 @@ $SED -e "s/VALIDITY/${TEST_VALIDITY}/g" -e "s/OPCODE/${TEST_OP}/g" -e "s/CONSTRU
        ldc.i4.0
        ret
 }
-//EOF
\ No newline at end of file
+//EOF
index f0d53366c87aead38e91afaadbbe1f8353553b04..6390c65695cdd7145260c10e6adae930871ced95 100755 (executable)
@@ -18,7 +18,7 @@ echo $TEST_FILE
 TEST_TYPE1=`echo $TEST_TYPE1 | $SED -s 's/&/\\\&/'`
 TEST_TYPE2=`echo $TEST_TYPE2 | $SED -s 's/&/\\\&/'`
 
-if [ "$TEST_CREATE_FIELD" == "no" ]; then
+if [ "$TEST_CREATE_FIELD" = "no" ]; then
        CLASS_FIELDS="";
 else
        CLASS_FIELDS=".field public ${TEST_TYPE1} fld\n .field public static ${TEST_TYPE1} sfld";
index baa46d38ae6d56e4973925cadeb8f8089763783c..239e27dc3b94c1fc0637879f4b3a655bbc46f86c 100755 (executable)
@@ -12,7 +12,7 @@ TEST_POS_1=$4
 TEST_POS_2=$5
 TEST_TYPE_0=$6
 
-if [ "$TEST_TYPE_0" == "" ] ; then
+if [ "x$TEST_TYPE_0" = "x" ] ; then
        TEST_TYPE_0="int32";
 fi
 
index 1bf078b35dd01625e2ca7b2c5a77be047a346a5e..d1859623b24e494a819f8769bf3e8fb7998d4b4f 100755 (executable)
@@ -16,7 +16,7 @@ ZZ=`echo $TEST_TYPE2 | grep "\&"`
 T2_REF=$?
 
 LOCAL_INIT="";
-if [ "$T2_REF" == "0" ]; then
+if [ $T2_REF -eq 0 ]; then
        T2_NO_REF=`echo $TEST_TYPE2 | cut -d '\' -f 1`
        INIT_LOCS=", $T2_NO_REF V_2"
        INIT_IL="ldloca.s 2\n\tstloc.1"
index 1767aa4816631a4d8c28061df434dab841a41e45..face162ef8ee56ef18209a364c00119c1f8c2f43 100755 (executable)
@@ -12,7 +12,7 @@ TEST_EXTRA=$4
 TEST_OP=$5
 TEST_FIN=$6
 
-if [ "$TEST_FIN" == "" ]; then
+if [ "x$TEST_FIN" = "x" ]; then
        TEST_FIN="finally";
 fi
 
index de58fa79f35f1a48a4231b067adf06ebb88a9061..82bdccdf81dedc4cb923d7e986e153440d03388d 100755 (executable)
@@ -12,7 +12,7 @@ TEST_LOAD_OP=$4
 TEST_TYPE=$5
 TEST_RET_TYPE=$6
 
-if [ "$TEST_RET_TYPE" == "" ]; then
+if [ "x$TEST_RET_TYPE" = "x" ]; then
        TEST_RET_TYPE="void"
 else
        LD_RET_CODE="ldloc.0"
index 270c2677b865aa6ed8f5c8ef218186c33b2ba785..25dd54a92576e995e679a27356d15ee6c9f19bea 100755 (executable)
@@ -25,7 +25,7 @@ done
 I=1
 for OP in add div mul rem sub
 do
-  if [ "$OP" == "div" ] || [ "$OP" == "rem" ]; then
+  if [ "$OP" = "div" ] || [ "$OP" = "rem" ]; then
        INIT="yes";
   else
        INIT="no";
@@ -92,7 +92,7 @@ done
 I=1
 for OP in div mul rem
 do
-  if [ "$OP" == "div" ] || [ "$OP" == "div" ]; then
+  if [ "$OP" = "div" ] || [ "$OP" = "div" ]; then
        INIT="yes";
   else
        INIT="no";
@@ -112,7 +112,7 @@ done
 I=1
 for OP in div mul rem add
 do
-  if [ "$OP" == "div" ] || [ "$OP" == "div" ]; then
+  if [ "$OP" = "div" ] || [ "$OP" = "div" ]; then
        INIT="yes";
   else
        INIT="no";
@@ -503,9 +503,9 @@ function fix () {
                A=$1;
        fi
 
-       if [ "$A" == "bool&" ]; then
+       if [ "$A" = "bool&" ]; then
                A="int8&";
-       elif [ "$A" == "char&" ]; then
+       elif [ "$A" = "char&" ]; then
                A="int16&";
        fi
 
@@ -522,11 +522,11 @@ do
                do
                        TA="$(fix $TYPE1)"
                        TB="$(fix $TYPE2)"
-                       if [ "$TA" == "$TB" ]; then
+                       if [ "$TA" = "$TB" ]; then
                                ./make_store_test.sh ref_coercion_${I} valid "$OP" "$TYPE1" "$TYPE2"
-                       elif [ "$TA" == "int32&" ] && [ "$TB" == "int&" ]; then
+                       elif [ "$TA" = "int32&" ] && [ "$TB" = "int&" ]; then
                                ./make_store_test.sh ref_coercion_${I} valid "$OP" "$TYPE1" "$TYPE2"
-                       elif [ "$TA" == "int&" ] && [ "$TB" == "int32&" ]; then
+                       elif [ "$TA" = "int&" ] && [ "$TB" = "int32&" ]; then
                                ./make_store_test.sh ref_coercion_${I} valid "$OP" "$TYPE1" "$TYPE2"
                        else
                                ./make_store_test.sh ref_coercion_${I} unverifiable "$OP" "$TYPE1" "$TYPE2"
@@ -545,7 +545,7 @@ do
                do
                        TA="$(fix $TYPE1)"
                        TB="$(fix $TYPE2)"
-                       if [ "$TA" == "$TB" ]; then
+                       if [ "$TA" = "$TB" ]; then
                                ./make_store_test.sh ref_coercion_${I} valid "$OP" "$TYPE1" "$TYPE2"
                        else
                                ./make_store_test.sh ref_coercion_${I} unverifiable "$OP" "$TYPE1" "$TYPE2"
@@ -561,7 +561,7 @@ do
        do
                for TYPE2 in 'class ClassA&' 'class ClassB&' 'class InterfaceA&' 'class InterfaceB&' 'class ValueType&'
                do
-                       if [ "$TYPE1" == "$TYPE2" ]; then
+                       if [ "$TYPE1" = "$TYPE2" ]; then
                                ./make_store_test.sh ref_coercion_${I} valid "$OP" "$TYPE1" "$TYPE2"
                        else
                                ./make_store_test.sh ref_coercion_${I} unverifiable "$OP" "$TYPE1" "$TYPE2"
@@ -791,17 +791,17 @@ do
        ZZ=`echo $TYPE2 | grep "*";`
        T2_PTR=$?
        
-    if (($T1_PTR == 0  ||  $T2_PTR == 0)); then
+    if [ $T1_PTR -eq 0 ] || [ $T2_PTR -eq 0 ]; then
                ./make_stack_merge_test.sh stack_merge_${I} unverifiable "$TYPE1" "$TYPE2"
-    elif [ "$TYPE1" == "$TYPE2" ]; then
+    elif [ "$TYPE1" = "$TYPE2" ]; then
                ./make_stack_merge_test.sh stack_merge_${I} valid "$TYPE1" "$TYPE2"
-       elif [ "$TYPE1" == "int32" ] && [ "$TYPE2" == "native int" ]; then
+       elif [ "$TYPE1" = "int32" ] && [ "$TYPE2" = "native int" ]; then
                ./make_stack_merge_test.sh stack_merge_${I} valid "$TYPE1" "$TYPE2"
-       elif [ "$TYPE1" == "native int" ] && [ "$TYPE2" == "int32" ]; then
+       elif [ "$TYPE1" = "native int" ] && [ "$TYPE2" = "int32" ]; then
                ./make_stack_merge_test.sh stack_merge_${I} valid "$TYPE1" "$TYPE2"
-       elif [ "$TYPE1" == "int32&" ] && [ "$TYPE2" == "native int&" ]; then
+       elif [ "$TYPE1" = "int32&" ] && [ "$TYPE2" = "native int&" ]; then
                ./make_stack_merge_test.sh stack_merge_${I} valid "$TYPE1" "$TYPE2"
-       elif [ "$TYPE1" == "native int&" ] && [ "$TYPE2" == "int32&" ]; then
+       elif [ "$TYPE1" = "native int&" ] && [ "$TYPE2" = "int32&" ]; then
                ./make_stack_merge_test.sh stack_merge_${I} valid "$TYPE1" "$TYPE2"
        else
                ./make_stack_merge_test.sh stack_merge_${I} unverifiable "$TYPE1" "$TYPE2"
@@ -1335,7 +1335,7 @@ do
        MAX_PARAM_RESULT="unverifiable"
        POPS="pop\npop\npop\npop\npop\npop\npop\npop\n"
        
-       if [ "$OP" == "ldloc" ]; then
+       if [ "$OP" = "ldloc" ]; then
                MAX_PARAM_RESULT="invalid"
 
                LOCALS_1=$ARGS_1
@@ -1892,7 +1892,7 @@ function create_nesting_test_same_result () {
       do
         for LOAD in yes no
         do
-          if ! ( [ "$NESTED" == "no" ] && [ "$LOAD" == "yes" ] ) ; then
+          if ! ( [ "$NESTED" = "no" ] && [ "$LOAD" = "yes" ] ) ; then
             ./make_double_nesting_test.sh double_nesting_access_check_${K}_$I $2 "$OP" $3 $4 $5 "$BASE" "$NESTED" "$LOAD"
             K=`expr $K + 1`
           fi
@@ -1910,9 +1910,9 @@ function create_nesting_test_only_first_ok () {
       do
         for LOAD in yes no
         do
-          if ! ( [ "$NESTED" == "no" ] && [ "$LOAD" == "yes" ] ) ; then
+          if ! ( [ "$NESTED" = "no" ] && [ "$LOAD" = "yes" ] ) ; then
               EXPECT=unverifiable
-           if [ "$FIRST" == "$K" ]; then
+           if [ "$FIRST" = "$K" ]; then
               EXPECT=valid
            fi
            ./make_double_nesting_test.sh double_nesting_access_check_${K}_$I $EXPECT "$OP" $2 $3 $4 "$BASE" "$NESTED" "$LOAD"
@@ -2065,7 +2065,7 @@ function create_nesting_test_strips_result_static () {
     for NESTED in yes no
       do
         EXPECT=unverifiable
-        if [ "$NESTED" == "yes" ]; then
+        if [ "$NESTED" = "yes" ]; then
           EXPECT=valid
         fi
         ./make_double_nesting_test.sh double_nesting_access_check_${K}_$I $EXPECT "$OP" $2 $3 $4 "$BASE" "$NESTED" yes
@@ -2188,9 +2188,9 @@ function fix_ldobj () {
                A=$1;
        fi
 
-       if [ "$A" == "bool" ]; then
+       if [ "$A" = "bool" ]; then
                A="int8";
-       elif [ "$A" == "char" ]; then
+       elif [ "$A" = "char" ]; then
                A="int16";
        fi
 
@@ -2207,7 +2207,7 @@ do
        do
                TYPE1="$(fix_ldobj $T1)"
                TYPE2="$(fix_ldobj $T2)"
-               if [ "$TYPE1" == "$TYPE2" ] ; then
+               if [ "$TYPE1" = "$TYPE2" ] ; then
                        ./make_ldobj_test.sh ldobj_${I} valid "${T1}\&" "${T2}"
                else
                        ./make_ldobj_test.sh ldobj_${I} unverifiable "${T1}\&" "${T2}"
@@ -2564,7 +2564,7 @@ I=1
 for TYPE1 in "int8" "bool" "int16" "char" "int32" "int64" "float64" "native int" "object" "string" "class Class" "valuetype MyStruct"  "int32[]" "int32[,]" "int32*" "method int32 *(int32)"  "class Template\`1<object>"
 do
        ./make_store_indirect_test.sh indirect_store_bad_addr_r4_${I} unverifiable "stind.r4" "${TYPE1}\&" "float32"
-       if [ "$TYPE1" == "float64" ]; then
+       if [ "$TYPE1" = "float64" ]; then
                ./make_store_indirect_test.sh indirect_store_good_val_r4_${I} valid "stind.r4" "float32\&" "${TYPE1}"
        else
                ./make_store_indirect_test.sh indirect_store_bad_val_r4_${I} unverifiable "stind.r4" "float32\&" "${TYPE1}"
@@ -2577,7 +2577,7 @@ I=1
 for TYPE1 in "int8" "bool" "int16" "char" "int32" "int64" "float32" "native int" "object" "string" "class Class" "valuetype MyStruct"  "int32[]" "int32[,]" "int32*" "method int32 *(int32)"  "class Template\`1<object>"
 do
        ./make_store_indirect_test.sh indirect_store_bad_addr_r8_${I} unverifiable "stind.r8" "${TYPE1}\&" "float64"
-       if [ "$TYPE1" == "float32" ]; then
+       if [ "$TYPE1" = "float32" ]; then
                ./make_store_indirect_test.sh indirect_store_good_val_r8_${I} valid "stind.r8" "float64\&" "${TYPE1}";
        else
                ./make_store_indirect_test.sh indirect_store_bad_val_r8_${I} unverifiable "stind.r8" "float64\&" "${TYPE1}";
@@ -3223,30 +3223,34 @@ done
 
 # Exception block branch tests (see 2.19)
 
-for I in {1..2};
+I=1; while [ $I -le 2 ]
 do
        ./make_rethrow_test.sh rethrow_from_catch_${I} invalid ${I}
+       I=$((I + 1))
 done
 
-for I in {3..10};
+I=3; while [ $I -le 10 ]
 do
        ./make_rethrow_test.sh rethrow_from_catch_${I} valid ${I}
+       I=$((I + 1))
 done
 
 
 
 # endfinally / endfault
 
-for I in {1..7};
+I=1; while [ $I -le 7 ]
 do
        ./make_endfinally_test.sh endfinally_block_${I} invalid finally ${I}
        ./make_endfinally_test.sh endfault_block_${I} invalid fault ${I}
+       I=$((I + 1))
 done
 
-for I in {8..9};
+I=8; while [ $I -le 9 ]
 do
        ./make_endfinally_test.sh endfinally_block_${I} valid finally ${I}
        ./make_endfinally_test.sh endfault_block_${I} valid fault ${I}
+       I=$((I + 1))
 done
 
 #stack can have stuff and endfinally or endfault will just empty it
@@ -3268,7 +3272,7 @@ done
 ./make_endfilter_test.sh endfilter_inside_protected_block_3 invalid 3 "ldc.i4.1\n\t\tendfilter"
 ./make_endfilter_test.sh endfilter_inside_protected_block_5 strict 5 "ldc.i4.1\n\t\tendfilter"
 
-for I in {2,4,6};
+for I in 2 4 6;
 do
        ./make_endfilter_test.sh endfilter_inside_protected_block_${I} unverifiable ${I} "ldc.i4.1\n\t\tendfilter"
 done
@@ -3302,9 +3306,9 @@ EXTRA="ldloc.0\n\tbrfalse END"
 ./make_leave_test.sh "filter_block_test_1" valid "1" "leave END" "$EXTRA"
 
 #but not ok to leave finally or filter
-for I in {2..3};
-do
+I=2; while [ $I -le 3 ]; do
        ./make_leave_test.sh "filter_block_test_${I}" unverifiable "${I}" "leave END" "${EXTRA}_${I}"
+       I=$((I + 1))
 done
 
 #neither is to branch to invalid regions of code
@@ -3314,24 +3318,27 @@ done
 
 # br.X
 #valid tests
-for I in {1..6}; do
+I=1; while [ $I -le 6 ]; do
        ./make_branch_test.sh branch_inside_same_block_${I} valid ${I} "br BLOCK_${I}";
        ./make_branch_test.sh branch_inside_same_block_${I}_s valid ${I} "br.s BLOCK_${I}";
+       I=$((I + 1))
 done
 
 #branching outside of the protected block
-for I in {2..6}; do
+I=2; while [ $I -le 6 ]; do
        ./make_branch_test.sh branch_outside_protected_block_${I} unverifiable ${I} "br END";
+       I=$((I + 1))
 done
 
 #branching to a protected block from the outside
-for I in {2..6}; do
-       if [ "$I" == "4" ]; then
+I=2; while [ $I -le 6 ]; do
+       if [ $I -eq 4 ]; then
                ./make_branch_test.sh branch_inside_protected_block_from_outside_${I}_finally invalid 1 "br BLOCK_${I}" "finally";
                ./make_branch_test.sh branch_inside_protected_block_from_outside_${I}_fault invalid 1 "br BLOCK_${I}" "fault";
        else
                ./make_branch_test.sh branch_inside_protected_block_from_outside_${I} unverifiable 1 "br BLOCK_${I}";
        fi
+       I=$((I + 1))
 done
 
 
@@ -3349,25 +3356,28 @@ done
 #TODO test the encoding of the switch table
 # switch
 #valid tests
-for I in {1..6}; do
+I=1; while [ $I -le 6 ]; do
        ./make_switch_test.sh switch_inside_same_block_${I} valid ${I} "ldloc.0" "switch (BLOCK_${I}, BLOCK_${I}_B)";
+       I=$((I + 1))
 done
 
 ./make_switch_test.sh switch_with_native_int_on_stack valid 1 "ldloc.1" "switch (BLOCK_1, BLOCK_1_B)";
 
 #branching outside of the protected block
-for I in {2..6}; do
+I=2; while [ $I -le 6 ]; do
        ./make_switch_test.sh switch_outside_protected_block_${I} unverifiable ${I} "ldloc.0" "switch (END, BLOCK_1, BLOCK_1_B)";
+       I=$((I + 1))
 done
 
 #branching to a protected block from the outside
-for I in {2..6}; do
-       if [ "$I" == "4" ]; then
+I=2; while [ $I -le 6 ]; do
+       if [ $I -eq 4 ]; then
                ./make_switch_test.sh switch_inside_protected_block_from_outside_${I}_finally invalid 1 "ldloc.0" "switch (BLOCK_${I}, BLOCK_${I}_B)" "finally";
                ./make_switch_test.sh switch_inside_protected_block_from_outside_${I}_fault invalid 1 "ldloc.0" "switch (BLOCK_${I}, BLOCK_${I}_B)" "fault";
        else
                ./make_switch_test.sh switch_inside_protected_block_from_outside_${I} unverifiable 1 "ldloc.0" "switch (BLOCK_${I}, BLOCK_${I}_B)";
        fi
+       I=$((I + 1))
 done
 
 #TODO branching out of range (FIX ilasm first)
@@ -4893,33 +4903,38 @@ done
 ./make_overlapped_test.sh ref_only_overlapping_5 invalid 0 0 8 int32
 
 #invalid opcodes
-for I in {166..178}
+I=166; while [ $I -le 178 ]
 do
        ./make_bad_op_test.sh bad_op_$I invalid $I
+       I=$((I + 1))
 done
 
 
-for I in {187..193}
+I=187; while [ $I -le 193 ]
 do
        ./make_bad_op_test.sh bad_op_$I invalid $I
+       I=$((I + 1))
 done
 
-for I in {196..207}
+I=196; while [ $I -le 207 ]
 do
        ./make_bad_op_test.sh bad_op_$I invalid $I
+       I=$((I + 1))
 done
 
-for I in {225..253}
+I=225; while [ $I -le 253 ]
 do
        ./make_bad_op_test.sh bad_op_$I invalid $I
+       I=$((I + 1))
 done
 
 ./make_bad_op_test.sh bad_op_xff invalid 255
 
 
-for I in {35..255}
+I=35; while [ $I -le 255 ]
 do
        ./make_bad_op_test.sh bad_op_with_prefix_$I invalid 0xFE $I
+       I=$((I + 1))
 done
 
 
@@ -5148,5 +5163,3 @@ done
 
 ./make_generic_argument_constraints_test.sh type_mixed_3 valid "" "(IfaceA)"
 ./make_generic_argument_constraints_test.sh type_mixed_4 valid "" "class (IfaceA)"
-
-
index b71063657cbc3083f621f7d0d5cddd78c7348391..744e931a2a9ad8a213c411c8de4509647c75d7d4 100755 (executable)
@@ -12,7 +12,7 @@ TEST_TYPE2=$4
 TEST_POST_OP=$5
 TEST_NO_BOX=$6
 TEST_BOX="box ${TEST_TYPE1}";
-if [ "${TEST_NO_BOX}" == "yes" ]; then
+if [ "x${TEST_NO_BOX}" = "xyes" ]; then
        TEST_BOX="";
 fi
 
index 9cbfdec5e9955a1cea60a1960b3d8473ddaf5167..f0420b492ec1bc39ee043f826f85bd933996ea0f 100644 (file)
@@ -47,12 +47,12 @@ typedef struct {
 #define LOCK_FREE_ALLOC_SB_HEADER_SIZE                         (sizeof (MonoLockFreeAllocator))
 #define LOCK_FREE_ALLOC_SB_USABLE_SIZE(block_size)     ((block_size) - LOCK_FREE_ALLOC_SB_HEADER_SIZE)
 
-void mono_lock_free_allocator_init_size_class (MonoLockFreeAllocSizeClass *sc, unsigned int slot_size, unsigned int block_size);
-void mono_lock_free_allocator_init_allocator (MonoLockFreeAllocator *heap, MonoLockFreeAllocSizeClass *sc);
+MONO_API void mono_lock_free_allocator_init_size_class (MonoLockFreeAllocSizeClass *sc, unsigned int slot_size, unsigned int block_size);
+MONO_API void mono_lock_free_allocator_init_allocator (MonoLockFreeAllocator *heap, MonoLockFreeAllocSizeClass *sc);
 
-gpointer mono_lock_free_alloc (MonoLockFreeAllocator *heap);
-void mono_lock_free_free (gpointer ptr, size_t block_size);
+MONO_API gpointer mono_lock_free_alloc (MonoLockFreeAllocator *heap);
+MONO_API void mono_lock_free_free (gpointer ptr, size_t block_size);
 
-gboolean mono_lock_free_allocator_check_consistency (MonoLockFreeAllocator *heap);
+MONO_API gboolean mono_lock_free_allocator_check_consistency (MonoLockFreeAllocator *heap);
 
 #endif
index 19e745f630c0c54eb46f030dfb5c3e62e7b7de20..314b30d972c2b18c065f33f6978a050b64bb10f0 100644 (file)
@@ -27,7 +27,7 @@ mono_mach_get_threads (thread_act_array_t *threads, guint32 *count)
 
        do {
                ret = task_threads (current_task (), threads, count);
-       } while (ret != KERN_SUCCESS);
+       } while (ret == KERN_ABORTED);
 
        return ret;
 }
index c1159ca723a684d75ed193a6be933b2d9b193fca..374171cf6747b828f5e85b5e649cc07fd08a6a8e 100644 (file)
@@ -31,7 +31,7 @@
 /*HACK, move this to an eventual mono-signal.c*/
 #if defined( __linux__) || defined(__sun) || defined(__APPLE__) || defined(__NetBSD__) || \
        defined(__FreeBSD__) || defined(__OpenBSD__)
-#ifdef HAVE_SIGACTION
+#if defined(HAVE_SIGACTION) || defined(__APPLE__)  // the __APPLE__ check is required for the tvos simulator, which has ucontext_t but not sigaction
 #define MONO_SIGNAL_USE_UCONTEXT_T 1
 #endif
 #endif
@@ -152,7 +152,7 @@ typedef struct {
 
 #if !defined( HOST_WIN32 ) && !defined(__native_client__) && !defined(__native_client_codegen__)
 
-#ifdef HAVE_SIGACTION
+#if defined(HAVE_SIGACTION) || defined(__APPLE__)  // the __APPLE__ check is required for the tvos simulator, which has ucontext_t but not sigaction
 #define MONO_SIGNAL_USE_UCONTEXT_T 1
 #endif
 
index e0260f8ac848c0e79a6039c39cff0015c873b370..2ca19a8b3d645fca66230e58f15d4b0e2b9cccf2 100644 (file)
@@ -561,7 +561,7 @@ dump_counter (MonoCounter *counter, FILE *outfile) {
 }
 
 static const char
-section_names [][10] = {
+section_names [][12] = {
        "JIT",
        "GC",
        "Metadata",
@@ -569,6 +569,8 @@ section_names [][10] = {
        "Security",
        "Runtime",
        "System",
+       "", // MONO_COUNTER_PERFCOUNTERS - not used.
+       "Profiler",
 };
 
 static void
index a8e6928dfbe84d036be48f0ef52e79987a24a97c..20be122e58288ccbd62cdcb25ab464080e9604d1 100644 (file)
@@ -26,6 +26,7 @@ enum {
        MONO_COUNTER_RUNTIME  = 1 << 13,
        MONO_COUNTER_SYSTEM   = 1 << 14,
        MONO_COUNTER_PERFCOUNTERS = 1 << 15,
+       MONO_COUNTER_PROFILER = 1 << 16,
        MONO_COUNTER_LAST_SECTION,
 
        /* Unit, bits 24-27 (4 bits) */
index 97b13c6c189b5d4707234e5de28797e82228b016..6e4b81eaf791a12b6c2191d1a767a1bbb0d29957 100644 (file)
@@ -6,6 +6,7 @@
 MONO_BEGIN_DECLS
 
 enum {
+       MONO_DL_EAGER = 0,
        MONO_DL_LAZY  = 1,
        MONO_DL_LOCAL = 2,
        MONO_DL_MASK  = 3
index 71498c0d99b4e2e8148f5c73658aba7b934c2f0a..63607a8fb89eb962ba99887b2941a5963cd6a7ed 100644 (file)
@@ -42,6 +42,11 @@ typedef struct {
 #define return_if_nok(error) do { if (!is_ok ((error))) return; } while (0)
 #define return_val_if_nok(error,val) do { if (!is_ok ((error))) return (val); } while (0)
 
+/* Only use this in icalls */
+#define return_val_and_set_pending_if_nok(error,value) \
+       if (mono_error_set_pending_exception ((error))) \
+               return (value);
+
 void
 mono_error_assert_ok_pos (MonoError *error, const char* filename, int lineno) MONO_LLVM_INTERNAL;
 
index 8f7f70307c7072e7fd47ecd46c9fd94430aa92dd..1317b0b462d385037b2347d881a954dfc201785d 100644 (file)
@@ -210,6 +210,11 @@ WINBASEAPI WINBOOL WINAPI InitOnceBeginInitialize(LPINIT_ONCE lpInitOnce, DWORD
 WINBASEAPI WINBOOL WINAPI InitOnceComplete(LPINIT_ONCE lpInitOnce, DWORD dwFlags, LPVOID lpContext);
 WINBASEAPI WINBOOL WINAPI InitOnceExecuteOnce(PINIT_ONCE InitOnce, PINIT_ONCE_FN InitFn, PVOID Parameter, LPVOID *Context);
 
+/* https://msdn.microsoft.com/en-us/library/windows/desktop/ms683477(v=vs.85).aspx */
+WINBASEAPI BOOL WINAPI InitializeCriticalSectionEx(LPCRITICAL_SECTION lpCriticalSection, DWORD dwSpinCount, DWORD Flags);
+
+#define CRITICAL_SECTION_NO_DEBUG_INFO 0x01000000
+
 #endif /* defined __MINGW32__ && !defined __MINGW64_VERSION_MAJOR && (_WIN32_WINNT >= 0x0600) */
 
 typedef CRITICAL_SECTION mono_mutex_t;
@@ -218,14 +223,14 @@ typedef CONDITION_VARIABLE mono_cond_t;
 static inline int
 mono_os_mutex_init (mono_mutex_t *mutex)
 {
-       InitializeCriticalSection (mutex);
+       InitializeCriticalSectionEx (mutex, 0, CRITICAL_SECTION_NO_DEBUG_INFO);
        return 0;
 }
 
 static inline int
 mono_os_mutex_init_recursive (mono_mutex_t *mutex)
 {
-       InitializeCriticalSection (mutex);
+       InitializeCriticalSectionEx (mutex, 0, CRITICAL_SECTION_NO_DEBUG_INFO);
        return 0;
 }
 
index 7ab1b9df7876d24e2bf88fe0858c177491512bcf..16e3d463b8b7377ab0dfb6ec22b8adcc15b76f66 100644 (file)
@@ -131,10 +131,13 @@ static inline int
 mono_os_sem_post (MonoSemType *sem)
 {
        int res;
-
+retry:
        res = semaphore_signal (*sem);
        g_assert (res != KERN_INVALID_ARGUMENT);
 
+       if (res == KERN_ABORTED)
+               goto retry;
+
        return res != KERN_SUCCESS ? -1 : 0;
 }
 
index c53af96454a79e84a98239ad450d0e9f8658154d..7a4a02e39a3f7fea5ca4a441251215d75d406bf8 100644 (file)
@@ -27,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
@@ -355,22 +356,35 @@ get_process_stat_item (int pid, int pos, int sum, MonoProcessError *error)
        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);
@@ -381,7 +395,11 @@ get_process_stat_item (int pid, int pos, int sum, MonoProcessError *error)
                
                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;
@@ -494,16 +512,25 @@ get_pid_status_item (int pid, const char *item, MonoProcessError *error, int mul
        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);
index 15106129b7212e85ba809c4a9a13b16332e0d18e..3c2f79b58c37e99ac92e90325b6f603118182aaa 100644 (file)
@@ -201,6 +201,10 @@ typedef struct ucontext {
        #define UCONTEXT_REG_RSI(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs [_REG_RSI])
        #define UCONTEXT_REG_RDI(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs [_REG_RDI])
        #define UCONTEXT_REG_RIP(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs [_REG_RIP])
+       #define UCONTEXT_REG_R8(ctx)  (((ucontext_t*)(ctx))->uc_mcontext.__gregs [_REG_R8])
+       #define UCONTEXT_REG_R9(ctx)  (((ucontext_t*)(ctx))->uc_mcontext.__gregs [_REG_R9])
+       #define UCONTEXT_REG_R10(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs [_REG_R10])
+       #define UCONTEXT_REG_R11(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs [_REG_R11])
        #define UCONTEXT_REG_R12(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs [_REG_R12])
        #define UCONTEXT_REG_R13(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs [_REG_R13])
        #define UCONTEXT_REG_R14(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs [_REG_R14])
@@ -351,6 +355,27 @@ typedef struct ucontext {
        #define UCONTEXT_REG_R11(ctx) (((arm_ucontext*)(ctx))->sig_ctx.arm_fp)
        #define UCONTEXT_REG_R12(ctx) (((arm_ucontext*)(ctx))->sig_ctx.arm_ip)
        #define UCONTEXT_REG_CPSR(ctx) (((arm_ucontext*)(ctx))->sig_ctx.arm_cpsr)
+#elif defined(__NetBSD__)
+       typedef ucontext_t arm_ucontext;
+
+       #define UCONTEXT_REG_PC(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs[_REG_PC])
+       #define UCONTEXT_REG_SP(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs[_REG_SP])
+       #define UCONTEXT_REG_LR(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs[_REG_LR])
+       #define UCONTEXT_REG_R0(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs[_REG_R0])
+       #define UCONTEXT_REG_R1(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs[_REG_R1])
+       #define UCONTEXT_REG_R2(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs[_REG_R2])
+       #define UCONTEXT_REG_R3(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs[_REG_R3])
+       #define UCONTEXT_REG_R4(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs[_REG_R4])
+       #define UCONTEXT_REG_R5(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs[_REG_R5])
+       #define UCONTEXT_REG_R6(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs[_REG_R6])
+       #define UCONTEXT_REG_R7(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs[_REG_R7])
+       #define UCONTEXT_REG_R8(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs[_REG_R8])
+       #define UCONTEXT_REG_R9(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs[_REG_R9])
+       #define UCONTEXT_REG_R10(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs[_REG_R10])
+       #define UCONTEXT_REG_R11(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs[_REG_R11])
+       #define UCONTEXT_REG_R12(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs[_REG_R12])
+       #define UCONTEXT_REG_CPSR(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs[_REG_CPSR])
+       #define UCONTEXT_REG_VFPREGS(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs[_REG_VFPREGS])
 #endif
 
 #elif defined(TARGET_ARM64)
index 9e0b072a1a5e7b6659f2c9f8f83a3e0618a6db6d..68fa0ad5f62312b1e11de46d1b92e073f9eeab03 100644 (file)
                              "mov r0, r0\n\t"                          \
                              "mov r0, r0\n\t"                          \
                              "mov r0, r0\n\t"                          \
-                             "mov r0, r0\n\t");                        \
-               asm volatile (                                          \
-                             "bx %0"                                   \
-                             : : "r" (__krait_ ## name));              \
+                             "mov r0, r0\n\t"                          \
+                                 "b __krait_" # name                   \
+                                 "\n\t");                                              \
        }       \
-       static void __krait_ ## name arglist
+       static __attribute__((used)) void __krait_ ## name arglist
 #endif
 
-
 /* Don't use this */
 #ifndef MONO_SIGNAL_HANDLER_FUNC
 #define MONO_SIGNAL_HANDLER_FUNC(access, name, arglist) access void name arglist
index 056a88f150a1cd72b8b5a1fb9d771ae8495c8845..559d2fa63c94525e4c36384bb02213e3ac3155a4 100644 (file)
@@ -49,11 +49,16 @@ mono_threads_core_abort_syscall (MonoThreadInfo *info)
 {
        kern_return_t ret;
 
-       ret = thread_suspend (info->native_handle);
+       do {
+               ret = thread_suspend (info->native_handle);
+       } while (ret == KERN_ABORTED);
+
        if (ret != KERN_SUCCESS)
                return;
 
-       ret = thread_abort_safely (info->native_handle);
+       do {
+               ret = thread_abort_safely (info->native_handle);
+       } while (ret == KERN_ABORTED);
 
        /*
         * We are doing thread_abort when thread_abort_safely returns KERN_SUCCESS because
@@ -66,7 +71,11 @@ mono_threads_core_abort_syscall (MonoThreadInfo *info)
        if (ret == KERN_SUCCESS)
                ret = thread_abort (info->native_handle);
 
-       g_assert (thread_resume (info->native_handle) == KERN_SUCCESS);
+       do {
+               ret = thread_resume (info->native_handle);
+       } while (ret == KERN_ABORTED);
+
+       g_assert (ret == KERN_SUCCESS);
 }
 
 gboolean
index 6f2ddfa78af52357be210b50a2a43c3a73526b52..6c2b07e468f5686872fb4a9db872be7f30dacdd2 100644 (file)
@@ -60,7 +60,11 @@ mono_threads_core_begin_async_suspend (MonoThreadInfo *info, gboolean interrupt_
 
        g_assert (info);
 
-       ret = thread_suspend (info->native_handle);
+
+       do {
+               ret = thread_suspend (info->native_handle);
+       } while (ret == KERN_ABORTED);
+
        THREADS_SUSPEND_DEBUG ("SUSPEND %p -> %d\n", (void*)info->native_handle, ret);
        if (ret != KERN_SUCCESS)
                return FALSE;
@@ -68,7 +72,10 @@ mono_threads_core_begin_async_suspend (MonoThreadInfo *info, gboolean interrupt_
        /* We're in the middle of a self-suspend, resume and register */
        if (!mono_threads_transition_finish_async_suspend (info)) {
                mono_threads_add_to_pending_operation_set (info);
-               g_assert (thread_resume (info->native_handle) == KERN_SUCCESS);
+               do {
+                       ret = thread_resume (info->native_handle);
+               } while (ret == KERN_ABORTED);
+               g_assert (ret == KERN_SUCCESS);
                THREADS_SUSPEND_DEBUG ("FAILSAFE RESUME/1 %p -> %d\n", (void*)info->native_handle, 0);
                //XXX interrupt_kernel doesn't make sense in this case as the target is not in a syscall
                return TRUE;
@@ -81,7 +88,10 @@ mono_threads_core_begin_async_suspend (MonoThreadInfo *info, gboolean interrupt_
                        thread_abort (info->native_handle);
        } else {
                mono_threads_transition_async_suspend_compensation (info);
-               g_assert (thread_resume (info->native_handle) == KERN_SUCCESS);
+               do {
+                       ret = thread_resume (info->native_handle);
+               } while (ret == KERN_ABORTED);
+               g_assert (ret == KERN_SUCCESS);
                THREADS_SUSPEND_DEBUG ("FAILSAFE RESUME/2 %p -> %d\n", (void*)info->native_handle, 0);
        }
        return res;
@@ -112,7 +122,10 @@ mono_threads_core_begin_async_resume (MonoThreadInfo *info)
                state = (thread_state_t) alloca (mono_mach_arch_get_thread_state_size ());
                mctx = (mcontext_t) alloca (mono_mach_arch_get_mcontext_size ());
 
-               ret = mono_mach_arch_get_thread_state (info->native_handle, state, &num_state);
+               do {
+                       ret = mono_mach_arch_get_thread_state (info->native_handle, state, &num_state);
+               } while (ret == KERN_ABORTED);
+
                if (ret != KERN_SUCCESS)
                        return FALSE;
 
@@ -122,12 +135,17 @@ mono_threads_core_begin_async_resume (MonoThreadInfo *info)
 
                mono_mach_arch_mcontext_to_thread_state (mctx, state);
 
-               ret = mono_mach_arch_set_thread_state (info->native_handle, state, num_state);
+               do {
+                       ret = mono_mach_arch_set_thread_state (info->native_handle, state, num_state);
+               } while (ret == KERN_ABORTED);
+
                if (ret != KERN_SUCCESS)
                        return FALSE;
        }
 
-       ret = thread_resume (info->native_handle);
+       do {
+               ret = thread_resume (info->native_handle);
+       } while (ret == KERN_ABORTED);
        THREADS_SUSPEND_DEBUG ("RESUME %p -> %d\n", (void*)info->native_handle, ret);
 
        return ret == KERN_SUCCESS;
index 7fe86b96273e80ded338c90b945f0dd256646806..395fdb5bdab19dacdf2de564c7e8fa534cd9b936 100644 (file)
@@ -296,6 +296,16 @@ mono_threads_core_set_name (MonoNativeThreadId tid, const char *name)
                n [62] = '\0';
                pthread_setname_np (n);
        }
+#elif defined (__NetBSD__)
+       if (!name) {
+               pthread_setname_np (tid, "%s", (void*)"");
+       } else {
+               char n [PTHREAD_MAX_NAMELEN_NP];
+
+               strncpy (n, name, PTHREAD_MAX_NAMELEN_NP);
+               n [PTHREAD_MAX_NAMELEN_NP - 1] = '\0';
+               pthread_setname_np (tid, "%s", (void*)n);
+       }
 #elif defined (HAVE_PTHREAD_SETNAME_NP)
        if (!name) {
                pthread_setname_np (tid, "");
index 7e999c540bf90dfba14b4919b15239ca685b8a39..81945bfc56e397dffa4f02476da4351f7c5b4024 100755 (executable)
@@ -15,6 +15,12 @@ if [[ ${label} != w* ]] && [[ ${label} != 'debian-ppc64el' ]] && [[ ${label} !=
     # only enable the mobile profiles and mobile_static on the main architectures
 fi
 
+if [ -x "/usr/bin/dpkg-architecture" ];
+       then
+       EXTRA_CONF_FLAGS="$EXTRA_CONF_FLAGS --host=`/usr/bin/dpkg-architecture -qDEB_HOST_GNU_TYPE`"
+       #force build arch = dpkg arch, sometimes misdetected
+fi
+
 ${TESTCMD} --label=configure --timeout=60m --fatal ./autogen.sh $EXTRA_CONF_FLAGS
 if [[ ${label} == w* ]];
     then
diff --git a/tools/offsets-tool/.gitignore b/tools/offsets-tool/.gitignore
new file mode 100644 (file)
index 0000000..61a0f8d
--- /dev/null
@@ -0,0 +1,5 @@
+.stamp-clone
+CppSharp
+*.exe
+*.h
+*.exe.mdb
diff --git a/tools/offsets-tool/Makefile b/tools/offsets-tool/Makefile
new file mode 100644 (file)
index 0000000..6486362
--- /dev/null
@@ -0,0 +1,39 @@
+CPPSHARP_DIR = CppSharp
+
+CPPSHARP_REFS = -r:$(CPPSHARP_DIR)/CppSharp.dll \
+       -r:$(CPPSHARP_DIR)/CppSharp.AST.dll \
+       -r:$(CPPSHARP_DIR)/CppSharp.Parser.CSharp.dll \
+       -r:$(CPPSHARP_DIR)/CppSharp.Generator.dll
+
+SRC_ROOT = ../..
+
+MONO_OPTIONS_SRC = $(SRC_ROOT)/mcs/class/Mono.Options/Mono.Options/Options.cs
+
+.stamp-clone:
+       @if [ ! -d $(CPPSHARP_DIR) ]; then \
+               git clone git@github.com:xamarin/CppSharpBinaries.git $(CPPSHARP_DIR); \
+               touch $@; \
+       fi
+
+MonoAotOffsetsDumper.exe: .stamp-clone MonoAotOffsetsDumper.cs $(MONO_OPTIONS_SRC)
+       mcs MonoAotOffsetsDumper.cs /debug /nowarn:0436 $(MONO_OPTIONS_SRC) $(CPPSHARP_REFS)
+
+.PHONY: clean
+clean:
+       rm MonoAotOffsetsDumper.exe
+
+dump: MonoAotOffsetsDumper.exe 
+       MONO_PATH=$(CPPSHARP_DIR) mono MonoAotOffsetsDumper.exe
+
+update:
+       @if [ -f object-offsets.h ]; then rm object-offsets.h; fi;
+       @for f in *.h; do \
+               echo "Processing $$f.."; \
+               echo "#include \"$$f\"" >> object-offsets1.h; \
+       done
+       @cp *.h ../mono/metadata
+
+gen-proj:
+       $(CPPSHARP_DIR)/premake5 vs2012
+
+all: MonoAotOffsetsDumper.exe
\ No newline at end of file
diff --git a/tools/offsets-tool/MonoAotOffsetsDumper.cs b/tools/offsets-tool/MonoAotOffsetsDumper.cs
new file mode 100644 (file)
index 0000000..a5320ba
--- /dev/null
@@ -0,0 +1,822 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text.RegularExpressions;
+using CppSharp.AST;
+using CppSharp.AST.Extensions;
+using CppSharp.Parser;
+
+namespace CppSharp
+{
+    /**
+     * This tool dumps the offsets of structures used in the Mono VM needed
+     * by the AOT compiler for cross-compiling code to target platforms
+     * different than the host the compiler is being invoked on.
+     * 
+     * It takes two arguments: the path to your clone of the Mono repo and
+     * the path to the root of Android NDK.
+     */
+    static class MonoAotOffsetsDumper
+    {
+        static string MonoDir = @"";
+
+        static List<string> Abis = new List<string> ();
+        static string OutputDir;
+
+        static string MonodroidDir = @"";
+        static string MaccoreDir = @"";
+
+        public enum TargetPlatform
+        {
+            Android,
+            iOS,
+            WatchOS,
+        }
+
+        public class Target
+        {
+            public Target()
+            {
+                Defines = new List<string>();
+                Arguments = new List<string>();
+            }
+
+            public Target(Target target)
+            {
+                Platform = target.Platform;
+                Triple = target.Triple;
+                Build = target.Build;
+                Defines = target.Defines;
+                Arguments = target.Arguments;
+            }
+
+            public TargetPlatform Platform;
+            public string Triple;
+            public string Build;            
+            public List<string> Defines;
+            public List<string> Arguments;
+        };
+
+        public static List<Target> Targets = new List<Target>();
+
+        public static IEnumerable<Target> AndroidTargets
+        {
+            get { return Targets.Where ((t) => t.Platform == TargetPlatform.Android); }
+        }
+
+        public static IEnumerable<Target> DarwinTargets
+        {
+            get
+            {
+                return Targets.Where ((t) => t.Platform == TargetPlatform.iOS ||
+                    t.Platform == TargetPlatform.WatchOS);
+            }
+        }
+
+        public static IEnumerable<Target> iOSTargets
+        {
+            get
+            {
+                return Targets.Where ((t) => t.Platform == TargetPlatform.iOS);
+            }
+        }
+
+        public static void SetupAndroidTargets()
+        {
+            Targets.Add (new Target {
+                Platform = TargetPlatform.Android,
+                Triple = "i686-none-linux-android",
+                Build = "mono-x86",
+                Defines = { "TARGET_X86" }
+            });
+
+            Targets.Add (new Target {
+                Platform = TargetPlatform.Android,
+                Triple = "x86_64-none-linux-android",
+                Build = "mono-x86_64",
+                Defines = { "TARGET_AMD64" }
+            });            
+
+            Targets.Add (new Target {
+                Platform = TargetPlatform.Android,
+                Triple = "armv5-none-linux-androideabi",
+                Build = "mono-armv6",
+                Defines = { "TARGET_ARM", "ARM_FPU_VFP", "HAVE_ARMV5" }
+            });
+
+            Targets.Add (new Target {
+                Platform = TargetPlatform.Android,
+                Triple = "armv7-none-linux-androideabi",
+                Build = "mono-armv7",                    
+                Defines = { "TARGET_ARM", "ARM_FPU_VFP", "HAVE_ARMV5", "HAVE_ARMV6",
+                    "HAVE_ARMV7"
+                }
+            });
+
+            Targets.Add (new Target {
+                Platform = TargetPlatform.Android,
+                Triple = "aarch64-v8a-linux-android",
+                Build = "mono-aarch64",                    
+                Defines = { "TARGET_ARM64" }
+            });            
+
+            /*Targets.Add(new Target {
+                    Platform = TargetPlatform.Android,
+                    Triple = "mipsel-none-linux-android",
+                    Build = "mono-mips",
+                    Defines = { "TARGET_MIPS", "__mips__" }
+                });*/
+
+            foreach (var target in AndroidTargets)
+                target.Defines.AddRange (new string[] { "PLATFORM_ANDROID",
+                    "TARGET_ANDROID", "MONO_CROSS_COMPILE", "USE_MONO_CTX"
+                });
+        }
+
+        public static void SetupiOSTargets()
+        {
+            Targets.Add(new Target {
+                Platform = TargetPlatform.iOS,
+                Triple = "arm-apple-darwin10",
+                Build = "target7",
+                Defines = { "TARGET_ARM", "ARM_FPU_VFP", "HAVE_ARMV5" }
+            });
+
+            Targets.Add(new Target {
+                Platform = TargetPlatform.iOS,
+                Triple = "aarch64-apple-darwin10",
+                Build = "target64",                    
+                Defines = { "TARGET_ARM64" }
+            });
+
+            foreach (var target in iOSTargets) {
+                target.Defines.AddRange (new string[] { "PLATFORM_DARWIN",
+                    "TARGET_IOS", "TARGET_MACH", "MONO_CROSS_COMPILE", "USE_MONO_CTX",
+                    "_XOPEN_SOURCE"
+                });
+            }
+
+            Targets.Add(new Target {
+                Platform = TargetPlatform.WatchOS,
+                Triple = "armv7k-apple-darwin",
+                Build = "targetwatch",
+                Defines = { "TARGET_ARM", "ARM_FPU_VFP", "HAVE_ARMV5" }
+            });
+
+            foreach (var target in DarwinTargets) {
+                target.Defines.AddRange (new string[] { "PLATFORM_DARWIN",
+                    "TARGET_IOS", "TARGET_MACH", "MONO_CROSS_COMPILE", "USE_MONO_CTX",
+                    "_XOPEN_SOURCE"
+                });
+            }
+        }
+
+        static bool GetParentSubDirectoryPath(string parent, out string subdir)
+        {
+            var directory = Directory.GetParent(Directory.GetCurrentDirectory());
+
+            while (directory != null) {
+                var path = Path.Combine(directory.FullName, parent);
+
+                if (Directory.Exists (path)) {
+                    subdir = path;
+                    return true;
+                }
+
+                directory = directory.Parent;
+            }
+
+            subdir = null;
+            return false;
+        }
+
+        public static void Main(string[] args)
+        {
+            ParseCommandLineArgs(args);
+
+            string monodroidDir;
+            if (!Directory.Exists (MonodroidDir) &&
+                GetParentSubDirectoryPath ("monodroid", out monodroidDir)) {
+                MonodroidDir = Path.Combine (monodroidDir);
+            }
+
+            if (Directory.Exists (MonodroidDir))
+                SetupAndroidTargets();
+
+            string maccoreDir;
+            if (!Directory.Exists (MaccoreDir) &&
+                GetParentSubDirectoryPath ("maccore", out maccoreDir)) {
+                MaccoreDir = Path.Combine (maccoreDir);
+            }
+
+            if (Directory.Exists(MaccoreDir))
+                SetupiOSTargets();
+
+            foreach (var target in Targets)
+             {
+                if (Abis.Any() && !Abis.Any (target.Triple.Contains))
+                    continue;
+                
+                Console.WriteLine();
+                Console.WriteLine("Processing triple: {0}", target.Triple);
+
+                var options = new DriverOptions();
+
+                var log = new TextDiagnosticPrinter();
+                var driver = new Driver(options, log);
+
+                Setup(driver, target);
+                driver.Setup();
+
+                BuildParseOptions(driver, target);
+                if (!driver.ParseCode())
+                    return;
+
+                Dump(driver.ASTContext, driver.TargetInfo, target);
+            }
+        }
+
+        static void BuildParseOptions(Driver driver, Target target)
+        {
+            foreach (var header in driver.Options.Headers)
+            {
+                var source = driver.Project.AddFile(header);
+                source.Options = driver.BuildParseOptions(source);
+
+                if (header.Contains ("mini"))
+                    continue;
+
+                source.Options.addDefines ("HAVE_SGEN_GC");
+                source.Options.addDefines ("HAVE_MOVING_COLLECTOR");
+            }
+        }
+
+        static string GetAndroidNdkPath()
+        {
+            // Find the Android NDK's path from Monodroid's config.
+            var configFile = Path.Combine(MonodroidDir, "env.config");
+            if (!File.Exists(configFile))
+                throw new Exception("Expected a valid Monodroid environment config file at " + configFile);
+
+            var config = File.ReadAllText(configFile);
+            var match = Regex.Match(config, @"ANDROID_NDK_PATH\s*:=\s(.*)");
+            return match.Groups[1].Value.Trim();
+        }
+
+        static void ParseCommandLineArgs(string[] args)
+        {
+            var showHelp = false;
+
+            var options = new Mono.Options.OptionSet () {
+                { "abi=", "ABI triple to generate", v => Abis.Add(v) },
+                { "o|out=", "output directory", v => OutputDir = v },
+                { "maccore=", "include directory", v => MaccoreDir = v },
+                { "monodroid=", "include directory", v => MonodroidDir = v },
+                { "mono=", "include directory", v => MonoDir = v },
+                { "h|help",  "show this message and exit",  v => showHelp = v != null },
+            };
+
+            try {
+                options.Parse (args);
+            }
+            catch (Mono.Options.OptionException e) {
+                Console.WriteLine (e.Message);
+                Environment.Exit(0);
+            }
+
+            if (showHelp)
+            {
+                // Print usage and exit.
+                Console.WriteLine("{0} [--abi=triple] [--out=dir] "
+                    + "[--monodroid/maccore=dir] [--mono=dir]",
+                    AppDomain.CurrentDomain.FriendlyName);
+                Environment.Exit(0);
+            }
+        }
+
+        static void Setup(Driver driver, Target target)
+        {
+            var options = driver.Options;
+            options.DryRun = true;
+            options.Verbose = false;
+            options.LibraryName = "Mono";
+            options.MicrosoftMode = false;
+            options.addArguments("-xc");
+            options.addArguments("-std=gnu99");
+            options.addDefines("CPPSHARP");
+
+            foreach (var define in target.Defines)
+                options.addDefines(define);
+
+            SetupToolchainPaths(driver, target);
+
+            SetupMono(options, target);
+        }
+
+        static void SetupMono(DriverOptions options, Target target)
+        {
+            string targetPath;
+            switch (target.Platform) {
+            case TargetPlatform.Android:
+                targetPath = Path.Combine (MonodroidDir, "builds");
+                break;
+            case TargetPlatform.WatchOS:
+            case TargetPlatform.iOS:
+                targetPath = Path.Combine (MaccoreDir, "builds");
+                break;
+            default:
+                throw new ArgumentOutOfRangeException ();
+            }
+
+            if (!Directory.Exists (MonoDir)) {
+                MonoDir = Path.GetFullPath (Path.Combine (targetPath, "../../mono"));
+            }
+
+            var targetBuild = Path.Combine(targetPath, target.Build);
+
+            if (!Directory.Exists(targetBuild))
+                throw new Exception(string.Format("Could not find the target build directory: {0}", targetBuild));
+
+            var includeDirs = new[]
+            {
+                targetBuild,
+                Path.Combine(targetBuild, "eglib", "src"),
+                MonoDir,
+                Path.Combine(MonoDir, "mono"),
+                Path.Combine(MonoDir, "mono", "mini"),
+                Path.Combine(MonoDir, "eglib", "src")
+            };
+
+            foreach (var inc in includeDirs)
+                options.addIncludeDirs(inc);
+
+            var filesToParse = new[]
+            {
+                Path.Combine(MonoDir, "mono", "metadata", "metadata-cross-helpers.c"),
+                Path.Combine(MonoDir, "mono", "mini", "mini-cross-helpers.c"),
+            };
+
+            foreach (var file in filesToParse)
+                options.Headers.Add(file);
+        }
+
+        static void SetupMSVC(Driver driver, string triple)
+        {
+            var options = driver.Options;
+
+            options.Abi = Parser.AST.CppAbi.Microsoft;
+            options.MicrosoftMode = true;
+
+            var systemIncludeDirs = new[]
+            {
+                @"C:\Program Files (x86)\Windows Kits\8.1\Include\um",
+                @"C:\Program Files (x86)\Windows Kits\8.1\Include\shared"
+            };
+
+            foreach (var inc in systemIncludeDirs)
+                options.addSystemIncludeDirs(inc);
+
+            options.addDefines("HOST_WIN32");
+        }
+
+        static void SetupToolchainPaths(Driver driver, Target target)
+        {
+            switch (target.Platform) {
+            case TargetPlatform.Android:
+                SetupAndroidNDK(driver, target);
+                break;
+            case TargetPlatform.iOS:
+            case TargetPlatform.WatchOS:
+                SetupXcode(driver, target);
+                break;
+            default:
+                throw new ArgumentOutOfRangeException ();
+            }
+        }        
+
+        static string GetArchFromTriple(string triple)
+        {
+            if (triple.Contains("mips"))
+                return "mips";
+
+            if (triple.Contains("arm64") || triple.Contains("aarch64"))
+                return "arm64";
+
+            if (triple.Contains("arm"))
+                return "arm";
+
+            if (triple.Contains("i686"))
+                return "x86";
+
+            if (triple.Contains("x86_64"))
+                return "x86_64";
+
+            throw  new Exception("Unknown architecture from triple: " + triple);
+        }
+
+        static string GetXcodeToolchainPath()
+        {
+            var toolchains = Directory.EnumerateDirectories("/Applications", "Xcode*")
+                .ToList();
+            toolchains.Sort();
+
+            var toolchainPath = toolchains.LastOrDefault();
+            if (toolchainPath == null)
+                throw new Exception("Could not find a valid Xcode SDK");
+
+            return toolchainPath;
+        }
+
+        static string GetXcodeBuiltinIncludesFolder()
+        {
+            var toolchainPath = GetXcodeToolchainPath();
+
+            var toolchains = Directory.EnumerateDirectories(Path.Combine(toolchainPath,
+                "Contents/Developer/Toolchains")).ToList();
+            toolchains.Sort();
+
+            toolchainPath = toolchains.LastOrDefault();
+            if (toolchainPath == null)
+                throw new Exception("Could not find a valid Xcode toolchain");
+
+            var includePaths = Directory.EnumerateDirectories(Path.Combine(toolchainPath,
+                "usr/lib/clang")).ToList();
+            var includePath = includePaths.LastOrDefault();
+
+            if (includePath == null)
+                throw new Exception("Could not find a valid Clang include folder");
+
+            return Path.Combine(includePath, "include");
+        }
+
+        static string GetXcodeiOSIncludesFolder()
+        {
+            var toolchainPath = GetXcodeToolchainPath();
+
+            var sdkPaths = Directory.EnumerateDirectories(Path.Combine(toolchainPath,
+                "Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs")).ToList();
+            var sdkPath = sdkPaths.LastOrDefault();
+
+            if (sdkPath == null)
+                throw new Exception("Could not find a valid iPhone SDK");
+
+            return Path.Combine(sdkPath, "usr/include");
+        }
+
+        static string GetXcodeWatchOSIncludesFolder()
+        {
+            var toolchainPath = GetXcodeToolchainPath();
+
+            var sdkPaths = Directory.EnumerateDirectories(Path.Combine(toolchainPath,
+                "Contents/Developer/Platforms/WatchOS.platform/Developer/SDKs")).ToList();
+            var sdkPath = sdkPaths.LastOrDefault();
+
+            if (sdkPath == null)
+                throw new Exception("Could not find a valid WatchOS SDK");
+
+            return Path.Combine(sdkPath, "usr/include");
+        }
+
+        static void SetupXcode(Driver driver, Target target)
+        {
+            var options = driver.Options;
+
+            var builtinsPath = GetXcodeBuiltinIncludesFolder();
+            string includePath;
+
+            switch (target.Platform) {
+            case TargetPlatform.iOS:
+                includePath = GetXcodeiOSIncludesFolder();
+                break;
+            case TargetPlatform.WatchOS:
+                includePath = GetXcodeWatchOSIncludesFolder();
+                break;
+            default:
+                throw new ArgumentOutOfRangeException ();
+            }
+
+            options.addSystemIncludeDirs(builtinsPath);
+            options.addSystemIncludeDirs(includePath);
+
+            options.NoBuiltinIncludes = true;
+            options.NoStandardIncludes = true;
+            options.TargetTriple = target.Triple;
+        }
+
+        static string GetAndroidHostToolchainPath()
+        {
+            var androidNdkPath = GetAndroidNdkPath ();
+            var toolchains = Directory.EnumerateDirectories(
+                Path.Combine(androidNdkPath, "toolchains"), "llvm*").ToList();
+            toolchains.Sort();
+
+            var toolchainPath = toolchains.LastOrDefault();
+            if (toolchainPath == null)
+                throw new Exception("Could not find a valid NDK host toolchain");
+
+            toolchains = Directory.EnumerateDirectories(Path.Combine(toolchainPath,
+                "prebuilt")).ToList();
+            toolchains.Sort();
+
+            toolchainPath = toolchains.LastOrDefault();
+            if (toolchainPath == null)
+                throw new Exception("Could not find a valid NDK host toolchain");
+
+            return toolchainPath;
+        }
+
+        static string GetAndroidBuiltinIncludesFolder()
+        {
+            var toolchainPath = GetAndroidHostToolchainPath();
+
+            string clangToolchainPath = Path.Combine(toolchainPath, "lib64", "clang");
+            if (!Directory.Exists (clangToolchainPath))
+                clangToolchainPath = Path.Combine(toolchainPath, "lib", "clang");
+
+            string includePath = null;
+            if (Directory.Exists (clangToolchainPath)) {
+                var includePaths = Directory.EnumerateDirectories(clangToolchainPath).ToList();
+                includePath = includePaths.LastOrDefault();
+            }
+            if (includePath == null)
+                throw new Exception("Could not find a valid Clang include folder");
+
+            return Path.Combine(includePath, "include");
+        }
+
+        static void SetupAndroidNDK(Driver driver, Target target)
+        {
+            var options = driver.Options;
+
+            var builtinsPath = GetAndroidBuiltinIncludesFolder();
+            options.addSystemIncludeDirs(builtinsPath);
+
+            var androidNdkRoot = GetAndroidNdkPath ();
+            const int androidNdkApiLevel = 21;
+
+            var toolchainPath = Path.Combine(androidNdkRoot, "platforms",
+                "android-" + androidNdkApiLevel, "arch-" + GetArchFromTriple(target.Triple),
+                "usr", "include");
+            options.addSystemIncludeDirs(toolchainPath);
+
+            options.NoBuiltinIncludes = true;
+            options.NoStandardIncludes = true;
+            options.TargetTriple = target.Triple;
+        }
+
+        static uint GetTypeAlign(ParserTargetInfo target, ParserIntType type)
+        {
+            switch (type)
+            {
+                case ParserIntType.SignedChar:
+                case ParserIntType.UnsignedChar:
+                    return target.CharAlign;
+                case ParserIntType.SignedShort:
+                case ParserIntType.UnsignedShort:
+                    return target.ShortAlign;
+                case ParserIntType.SignedInt:
+                case ParserIntType.UnsignedInt:
+                    return target.IntAlign;
+                case ParserIntType.SignedLong:
+                case ParserIntType.UnsignedLong:
+                    return target.LongAlign;
+                case ParserIntType.SignedLongLong:
+                case ParserIntType.UnsignedLongLong:
+                    return target.LongLongAlign;
+                default:
+                    throw new Exception("Type has no alignment");
+            }
+        }
+
+        static uint GetTypeSize(ParserTargetInfo target, ParserIntType type)
+        {
+            switch (type)
+            {
+                case ParserIntType.SignedChar:
+                case ParserIntType.UnsignedChar:
+                    return target.CharWidth;
+                case ParserIntType.SignedShort:
+                case ParserIntType.UnsignedShort:
+                    return target.ShortWidth;
+                case ParserIntType.SignedInt:
+                case ParserIntType.UnsignedInt:
+                    return target.IntWidth;
+                case ParserIntType.SignedLong:
+                case ParserIntType.UnsignedLong:
+                    return target.LongWidth;
+                case ParserIntType.SignedLongLong:
+                case ParserIntType.UnsignedLongLong:
+                    return target.LongLongWidth;
+                default:
+                    throw new Exception("Type has no size");
+            }
+        }
+
+        static string GetTargetPlatformDefine(TargetPlatform target)
+        {
+            switch (target) {
+            case TargetPlatform.Android:
+                return "TARGET_ANDROID";
+            case TargetPlatform.iOS:
+                return "TARGET_IOS";
+            case TargetPlatform.WatchOS:
+                return "TARGET_WATCHOS";
+            default:
+                throw new ArgumentOutOfRangeException ();
+            }
+        }
+
+        static void Dump(ASTContext ctx, ParserTargetInfo targetInfo, Target target)
+        {
+            var targetFile = target.Triple;
+
+                       if (!string.IsNullOrEmpty (OutputDir))
+                               targetFile = Path.Combine (OutputDir, targetFile);
+
+            targetFile += ".h";
+
+            using (var writer = new StreamWriter(targetFile))
+            //using (var writer = Console.Out)
+            {
+                writer.WriteLine("#ifndef USED_CROSS_COMPILER_OFFSETS");
+                writer.WriteLine("#ifdef {0}", target.Defines[0]);
+                writer.WriteLine ("#ifdef {0}", GetTargetPlatformDefine (target.Platform));
+                writer.WriteLine("#ifndef HAVE_BOEHM_GC");
+                writer.WriteLine("#define HAS_CROSS_COMPILER_OFFSETS");
+                writer.WriteLine("#if defined (USE_CROSS_COMPILE_OFFSETS) || defined (MONO_CROSS_COMPILE)");
+                writer.WriteLine("#if !defined (DISABLE_METADATA_OFFSETS)");
+                writer.WriteLine("#define USED_CROSS_COMPILER_OFFSETS");
+
+                DumpAligns(writer, targetInfo);
+                DumpSizes(writer, targetInfo);
+                DumpMetadataOffsets(writer, ctx, target);
+
+                writer.WriteLine("#endif //disable metadata check");
+
+                DumpJITOffsets(writer, ctx);
+
+                writer.WriteLine("#endif //cross compiler checks");
+                writer.WriteLine("#endif //gc check");
+                writer.WriteLine("#endif //os check");
+                writer.WriteLine("#endif //arch check");
+                writer.WriteLine("#endif //USED_CROSS_COMPILER_OFFSETS check");
+            }
+
+            Console.WriteLine("Generated offsets file: {0}", targetFile);
+        }
+
+        static void DumpAligns(TextWriter writer, ParserTargetInfo target)
+        {
+            var aligns = new[]
+            {
+                new { Name = "gint8", Align = target.CharAlign},
+                new { Name = "gint16", Align = target.ShortAlign},
+                new { Name = "gint32", Align = target.IntAlign},
+                new { Name = "gint64", Align = GetTypeAlign(target, target.Int64Type)},
+                new { Name = "float", Align = target.FloatAlign},
+                new { Name = "double", Align = target.DoubleAlign},
+                new { Name = "gpointer", Align = GetTypeAlign(target, target.IntPtrType)},
+            };
+
+            // Write the alignment info for the basic types.
+            foreach (var align in aligns)
+                writer.WriteLine("DECL_ALIGN2({0},{1})", align.Name, align.Align / 8);
+        }
+
+        static void DumpSizes(TextWriter writer, ParserTargetInfo target)
+        {
+            var sizes = new[]
+            {
+                new { Name = "gint8", Size = target.CharWidth},
+                new { Name = "gint16", Size = target.ShortWidth},
+                new { Name = "gint32", Size = target.IntWidth},
+                new { Name = "gint64", Size = GetTypeSize(target, target.Int64Type)},
+                new { Name = "float", Size = target.FloatWidth},
+                new { Name = "double", Size = target.DoubleWidth},
+                new { Name = "gpointer", Size = GetTypeSize(target, target.IntPtrType)},
+            };
+
+            // Write the size info for the basic types.
+            foreach (var size in sizes)
+                writer.WriteLine("DECL_SIZE2({0},{1})", size.Name, size.Size / 8);
+        }
+
+        static Class GetClassFromTypedef(ITypedDecl typedef)
+        {
+            var type = typedef.Type.Desugar() as TagType;
+            if (type == null)
+                return null;
+
+            var @class = type.Declaration as Class;
+
+            return @class.IsIncomplete ?
+                (@class.CompleteDeclaration as Class) : @class; 
+        }
+
+        static void DumpClasses(TextWriter writer, ASTContext ctx, IEnumerable<string> types,
+            bool optional = false)
+        {
+            foreach (var @struct in types)
+            {
+                var @class = ctx.FindCompleteClass(@struct);
+                if (@class == null)
+                    @class = ctx.FindCompleteClass("_" + @struct);
+
+                if (@class == null)
+                {
+                    var typedef = ctx.FindTypedef(@struct).FirstOrDefault(
+                        decl => !decl.IsIncomplete);
+
+                    if (typedef != null)
+                        @class = GetClassFromTypedef(typedef);
+                }
+
+                if (@class == null && optional)
+                    continue;
+
+                if (@class == null)
+                    throw new Exception("Expected to find struct definition for " + @struct);
+
+                DumpStruct(writer, @class);
+            }
+        }
+
+        static void DumpMetadataOffsets(TextWriter writer, ASTContext ctx, Target target)
+        {
+            var types = new List<string>
+            {
+                "MonoObject",
+                "MonoClass",
+                "MonoVTable",
+                "MonoDelegate",
+                "MonoInternalThread",
+                "MonoMulticastDelegate",
+                "MonoTransparentProxy",
+                "MonoRealProxy",
+                "MonoRemoteClass",
+                "MonoArray",
+                "MonoArrayBounds",
+                "MonoSafeHandle",
+                "MonoHandleRef",
+                "MonoComInteropProxy",
+                "MonoString",
+                "MonoException",
+                "MonoTypedRef",
+                "MonoThreadsSync",
+                "SgenThreadInfo"
+            };
+
+            DumpClasses(writer, ctx, types);
+        }
+
+        static void DumpJITOffsets(TextWriter writer, ASTContext ctx)
+        {
+            writer.WriteLine("#ifndef DISABLE_JIT_OFFSETS");
+            writer.WriteLine("#define USED_CROSS_COMPILER_OFFSETS");
+
+            var types = new[]
+            {
+                "MonoLMF",
+                "MonoMethodRuntimeGenericContext",
+                "MonoJitTlsData",
+                "MonoGSharedVtMethodRuntimeInfo",
+                "MonoContinuation",
+                "MonoContext",
+                "MonoDelegateTrampInfo",
+            };
+
+            DumpClasses(writer, ctx, types);
+
+            var optionalTypes = new[]
+            {
+                "GSharedVtCallInfo",
+                "SeqPointInfo",
+                "DynCallArgs", 
+                "MonoLMFTramp",
+            };            
+
+            DumpClasses(writer, ctx, optionalTypes, optional: true);
+
+            writer.WriteLine("#endif //disable jit check");
+        }
+
+        static void DumpStruct(TextWriter writer, Class @class)
+        {
+            var name = @class.Name;
+                       if (name.StartsWith ("_", StringComparison.Ordinal))
+                               name = name.Substring (1);
+
+            foreach (var field in @class.Fields)
+            {
+                if (field.IsBitField) continue;
+
+                if (name == "SgenThreadInfo" && field.Name == "regs")
+                    continue;
+
+                writer.WriteLine("DECL_OFFSET2({0},{1},{2})", name, field.Name,
+                    field.Offset / 8);
+            }
+        }
+    }
+}
index 1a9a35eb18ae5136db406fb8c8770e462c39d4e3..2a49fea8b19401abb058883d9ad6fe8b3a2b6d86 100644 (file)
  /* Have signal */
 #define HAVE_SIGNAL 1
 
+ /* Define to 1 if you have the <signal.h> header file. */
+#define HAVE_SIGNAL_H 1
+
 /* Have signbit */
 /* #undef HAVE_SIGNBIT */