Merge pull request #3716 from vargaz/unbox-stobj-null
authorRodrigo Kumpera <kumpera@users.noreply.github.com>
Thu, 13 Oct 2016 18:00:58 +0000 (14:00 -0400)
committerGitHub <noreply@github.com>
Thu, 13 Oct 2016 18:00:58 +0000 (14:00 -0400)
[jit] Add a small optimization for unbox.any+stobj called with a null…

283 files changed:
.gitmodules
configure.ac
external/corefx [new submodule]
external/ikvm
man/mono.1
mcs/class/Makefile
mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/PredefinedPropertyFunctionsTest.cs
mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/TargetTest.cs
mcs/class/Microsoft.Build.Engine/Test/various/Properties.cs
mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/AssignTargetPathTest.cs
mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/CopyTest.cs
mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/WriteLinesToFileTest.cs
mcs/class/Microsoft.Build/Test/Microsoft.Build.Evaluation/ProjectItemTest.cs
mcs/class/Microsoft.Build/Test/Microsoft.Build.Execution/BuildSubmissionTest.cs
mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsProvider.cs
mcs/class/Mono.Data.Sqlite/Mono.Data.Sqlite_2.0/SQLiteConvert.cs
mcs/class/Mono.Data.Sqlite/Mono.Data.Sqlite_test.dll.sources
mcs/class/Mono.Data.Sqlite/Test/Bug27864.cs
mcs/class/Mono.Data.Sqlite/Test/SqliteTests.cs [new file with mode: 0644]
mcs/class/System.Core/System.Security.Cryptography/CngAlgorithm.cs [deleted file]
mcs/class/System.Core/System.Security.Cryptography/CngAlgorithmGroup.cs [deleted file]
mcs/class/System.Core/System.Security.Cryptography/CngExportPolicies.cs [deleted file]
mcs/class/System.Core/System.Security.Cryptography/CngKeyCreationOptions.cs [deleted file]
mcs/class/System.Core/System.Security.Cryptography/CngKeyCreationParameters.cs [deleted file]
mcs/class/System.Core/System.Security.Cryptography/CngKeyOpenOptions.cs [deleted file]
mcs/class/System.Core/System.Security.Cryptography/CngKeyUsages.cs [deleted file]
mcs/class/System.Core/System.Security.Cryptography/CngProperty.cs [deleted file]
mcs/class/System.Core/System.Security.Cryptography/CngPropertyCollection.cs [deleted file]
mcs/class/System.Core/System.Security.Cryptography/CngPropertyOptions.cs [deleted file]
mcs/class/System.Core/System.Security.Cryptography/CngProvider.cs [deleted file]
mcs/class/System.Core/System.Security.Cryptography/CngUIPolicy.cs [deleted file]
mcs/class/System.Core/System.Security.Cryptography/CngUIProtectionLevels.cs [deleted file]
mcs/class/System.Core/System.Security.Cryptography/ECDiffieHellmanKeyDerivationFunction.cs [deleted file]
mcs/class/System.Core/System.Security.Cryptography/ECKeyXmlFormat.cs [deleted file]
mcs/class/System.Data/System.Data.SqlClient/SqlConnection.cs
mcs/class/System.Net.Http/System.Net.Http.Headers/ContentRangeHeaderValue.cs
mcs/class/System.Net.Http/System.Net.Http/HttpClientHandler.cs
mcs/class/System.Net.Http/Test/System.Net.Http.Headers/ContentRangeHeaderValueTest.cs
mcs/class/System.ServiceModel.Web/Test/System.ServiceModel.Web/WebOperationContextTest.cs
mcs/class/System.ServiceModel/Test/System.ServiceModel.Dispatcher/DispatchOperationTest.cs
mcs/class/System.Web/System.Web.dll.sources
mcs/class/System.Web/Test/System.Web.UI.WebControls.Adapters/HideDisabledControlAdapterTest.cs [changed mode: 0644->0755]
mcs/class/System.Web/Test/System.Web.UI.WebControls.Adapters/MenuAdapterTest.cs [changed mode: 0644->0755]
mcs/class/System.Web/Test/System.Web.UI.WebControls.Adapters/WebControlAdapterTest.cs [changed mode: 0644->0755]
mcs/class/System.Web/Test/System.Web.UI.WebControls/WizardTest.cs [changed mode: 0644->0755]
mcs/class/System.Windows.Forms/System.Windows.Forms.dll.sources
mcs/class/System/Mono.Btls/MonoBtlsContext.cs
mcs/class/System/Mono.Btls/MonoBtlsKey.cs
mcs/class/System/Mono.Btls/MonoBtlsPkcs12.cs
mcs/class/System/Mono.Btls/MonoBtlsProvider.cs
mcs/class/System/Mono.Btls/MonoBtlsUtils.cs
mcs/class/System/Mono.Btls/MonoBtlsX509.cs
mcs/class/System/Mono.Btls/MonoBtlsX509Crl.cs
mcs/class/System/Mono.Btls/MonoBtlsX509Name.cs
mcs/class/System/Mono.Btls/MonoBtlsX509Revoked.cs
mcs/class/System/Mono.Btls/MonoBtlsX509VerifyParam.cs
mcs/class/System/Mono.Btls/X509CertificateImplBtls.cs
mcs/class/System/Mono.Net.Security/MonoTlsProviderFactory.Droid.cs
mcs/class/System/Mono.Net.Security/MonoTlsProviderFactory.cs
mcs/class/System/Mono.Net.Security/MonoTlsStream.cs
mcs/class/System/ReferenceSources/Logging.cs
mcs/class/System/ReferenceSources/SettingsSectionInternal.cs
mcs/class/System/System.Net.Sockets/SendPacketsElement.cs [deleted file]
mcs/class/System/System.Net.Sockets/Socket.cs
mcs/class/System/System.Net.Sockets/SocketAsyncEventArgs.cs
mcs/class/System/System.Net.Sockets/SocketAsyncOperation.cs [deleted file]
mcs/class/System/System.Net.Sockets/TcpClient.cs [deleted file]
mcs/class/System/System.Net.Sockets/TcpListener.cs [deleted file]
mcs/class/System/System.Net.Sockets/UdpClient.cs [deleted file]
mcs/class/System/System.Net/Dns.cs
mcs/class/System/System.Net/FtpWebRequest.cs
mcs/class/System/System.Net/WebConnection.cs
mcs/class/System/System.Security.Cryptography.X509Certificates/X500DistinguishedName.cs
mcs/class/System/System.Security.Cryptography.X509Certificates/X509Certificate2.cs
mcs/class/System/System.Security.Cryptography.X509Certificates/X509Certificate2Impl.cs
mcs/class/System/System.Security.Cryptography.X509Certificates/X509Certificate2ImplMono.cs
mcs/class/System/System.Security.Cryptography.X509Certificates/X509Chain.cs
mcs/class/System/System.Security.Cryptography.X509Certificates/X509Helper2.cs
mcs/class/System/System.dll.sources
mcs/class/System/System/MonoExeLocator.cs [deleted file]
mcs/class/System/System/MonoToolsLocator.cs [new file with mode: 0755]
mcs/class/System/Test/System.Net.Sockets/SocketAsyncEventArgsTest.cs
mcs/class/System/Test/System.Net.Sockets/TcpClientTest.cs
mcs/class/System/Test/System.Net.Sockets/UdpClientTest.cs
mcs/class/System/Test/System.Net/FtpWebRequestTest.cs
mcs/class/System/Test/System/UriTest3.cs
mcs/class/System/mobile_System.dll.sources
mcs/class/System/monotouch_watch_System.dll.exclude.sources
mcs/class/WindowsBase/System.IO.Packaging/Package.cs [changed mode: 0644->0755]
mcs/class/WindowsBase/Test/System.Windows/RectTest.cs
mcs/class/WindowsBase/WindowsBase.dll.sources
mcs/class/WindowsBase/ZipSharp/IOFunctions.cs
mcs/class/WindowsBase/ZipSharp/NativeUnzip.cs
mcs/class/WindowsBase/ZipSharp/NativeVersion.cs [new file with mode: 0755]
mcs/class/WindowsBase/ZipSharp/NativeZip.cs
mcs/class/WindowsBase/ZipSharp/UnzipArchive.cs
mcs/class/WindowsBase/ZipSharp/UnzipFileInfo.cs
mcs/class/WindowsBase/ZipSharp/UnzipReadStream.cs
mcs/class/WindowsBase/ZipSharp/ZipArchive.cs
mcs/class/WindowsBase/ZipSharp/ZipFileInfo.cs
mcs/class/WindowsBase/ZipSharp/ZipStream.cs
mcs/class/corlib/CommonCrypto/SecRandom.cs
mcs/class/corlib/Makefile
mcs/class/corlib/System.Globalization/CultureInfo.cs
mcs/class/corlib/System.Reflection.Emit/TypeBuilder.cs
mcs/class/corlib/System.Runtime.Remoting/RemotingConfiguration.cs
mcs/class/corlib/System.Security.Cryptography/CryptoConfig.fullaot.cs
mcs/class/corlib/System.Security.Cryptography/RNGCryptoServiceProvider.cs
mcs/class/corlib/System/AppDomain.cs
mcs/class/corlib/System/Environment.cs
mcs/class/corlib/Test/System.Reflection.Emit/TypeBuilderTest.cs
mcs/class/corlib/Test/System.Runtime.CompilerServices/RuntimeHelpersTest.cs
mcs/class/corlib/Test/System/TypeTest.cs
mcs/class/corlib/corefx/SR.cs [new file with mode: 0644]
mcs/class/corlib/corlib.dll.sources
mcs/class/referencesource/System/compmod/system/codedom/CodeNamespace.cs
mcs/class/referencesource/System/compmod/system/codedom/CodePropertyReferenceExpression.cs
mcs/class/referencesource/System/compmod/system/componentmodel/LicFileLicenseProvider.cs
mcs/class/referencesource/System/compmod/system/componentmodel/ReflectEventDescriptor.cs
mcs/class/referencesource/System/compmod/system/componentmodel/ReflectPropertyDescriptor.cs
mcs/class/referencesource/System/compmod/system/componentmodel/TypeConverter.cs
mcs/class/referencesource/System/net/System/Net/Sockets/Socket.cs
mcs/class/referencesource/System/net/System/Net/WebRequest.cs
mcs/class/referencesource/System/net/System/Net/connectionpool.cs
mcs/class/referencesource/System/net/System/Net/filewebrequest.cs
mcs/class/referencesource/System/net/System/Net/webclient.cs
mcs/class/referencesource/System/net/System/UriExt.cs
mcs/class/referencesource/System/regex/system/text/regularexpressions/RegexCompiler.cs
mcs/class/referencesource/System/services/monitoring/system/diagnosticts/AsyncStreamReader.cs
mcs/class/referencesource/System/services/monitoring/system/diagnosticts/Process.cs
mcs/class/referencesource/mscorlib/system/globalization/compareinfo.cs
mcs/class/referencesource/mscorlib/system/runtime/interopservices/runtimeenvironment.cs
mcs/class/referencesource/mscorlib/system/security/cryptography/rc2cryptoserviceprovider.cs
mcs/class/referencesource/mscorlib/system/security/cryptography/rfc2898derivebytes.cs
mcs/class/test-helpers/SocketResponder.cs
mcs/mcs/cs-tokenizer.cs
mcs/mcs/ikvm.cs
mcs/tests/test-interpolation-05.cs
mcs/tests/ver-il-net_4_x.xml
mcs/tools/btls/btls-cert-sync.cs
mcs/tools/commoncryptogenerator/CommonCryptorGenerator.cs
mcs/tools/commoncryptogenerator/generator.cs
mcs/tools/linker/Mono.Linker.Steps/MarkStep.cs
mcs/tools/mdoc/Makefile
mcs/tools/mono-symbolicate/Makefile
mcs/tools/security/cert-sync.cs
mono/btls/Makefile.am
mono/btls/btls-x509-name.c
mono/btls/btls-x509-name.h
mono/btls/btls-x509.c
mono/io-layer/processes.c
mono/metadata/Makefile.am
mono/metadata/appdomain.c
mono/metadata/assembly.c
mono/metadata/assembly.h
mono/metadata/attach.c
mono/metadata/boehm-gc.c
mono/metadata/class-internals.h
mono/metadata/class.c
mono/metadata/console-win32-internals.h [new file with mode: 0644]
mono/metadata/console-win32-uwp.c [new file with mode: 0644]
mono/metadata/console-win32.c
mono/metadata/coree-internals.h [new file with mode: 0644]
mono/metadata/coree-windows-uwp.c [new file with mode: 0644]
mono/metadata/coree.c
mono/metadata/domain-internals.h
mono/metadata/domain.c
mono/metadata/exception.c
mono/metadata/file-io-internals.h [new file with mode: 0644]
mono/metadata/file-io-windows-internals.h [new file with mode: 0644]
mono/metadata/file-io-windows-uwp.c [new file with mode: 0644]
mono/metadata/file-io-windows.c [new file with mode: 0644]
mono/metadata/file-io.c
mono/metadata/icall-def.h
mono/metadata/icall-internals.h [new file with mode: 0644]
mono/metadata/icall-windows-internals.h [new file with mode: 0644]
mono/metadata/icall-windows-uwp.c [new file with mode: 0644]
mono/metadata/icall-windows.c [new file with mode: 0644]
mono/metadata/icall.c
mono/metadata/lock-tracer.c
mono/metadata/marshal-internals.h [new file with mode: 0644]
mono/metadata/marshal-windows-internals.h [new file with mode: 0644]
mono/metadata/marshal-windows-uwp.c [new file with mode: 0644]
mono/metadata/marshal-windows.c [new file with mode: 0644]
mono/metadata/marshal.c
mono/metadata/mempool.c
mono/metadata/mono-config-dirs.c
mono/metadata/mono-config-dirs.h
mono/metadata/mono-config.c
mono/metadata/mono-security-windows-internals.h [new file with mode: 0644]
mono/metadata/mono-security-windows-uwp.c [new file with mode: 0644]
mono/metadata/mono-security-windows.c [new file with mode: 0644]
mono/metadata/mono-security.c
mono/metadata/null-gc.c
mono/metadata/object.c
mono/metadata/process-internals.h [new file with mode: 0644]
mono/metadata/process-windows-internals.h [new file with mode: 0644]
mono/metadata/process-windows-uwp.c [new file with mode: 0644]
mono/metadata/process-windows.c [new file with mode: 0644]
mono/metadata/process.c
mono/metadata/reflection.c
mono/metadata/remoting.c
mono/metadata/security-core-clr.c
mono/metadata/sgen-os-coop.c
mono/metadata/socket-io-windows-internals.h [new file with mode: 0644]
mono/metadata/socket-io-windows.c [new file with mode: 0644]
mono/metadata/socket-io.c
mono/metadata/socket-io.h
mono/metadata/sre.c
mono/metadata/threads.c
mono/metadata/w32semaphore-win32.c
mono/mini/Makefile.am.in
mono/mini/aot-compiler.c
mono/mini/debugger-agent.c
mono/mini/driver.c
mono/mini/exceptions-amd64.c
mono/mini/generics.cs
mono/mini/gshared.cs
mono/mini/local-propagation.c
mono/mini/method-to-ir.c
mono/mini/mini-exceptions.c
mono/mini/mini-llvm.c
mono/mini/mini-mips.c
mono/mini/mini-mips.h
mono/mini/mini-windows-uwp.c [new file with mode: 0644]
mono/mini/mini-windows.c
mono/mini/mini-windows.h [new file with mode: 0644]
mono/mini/mini.c
mono/mini/mini.h
mono/mini/tramp-amd64.c
mono/profiler/mono-profiler-log.c
mono/sgen/gc-internal-agnostic.h
mono/sgen/sgen-gc.c
mono/sgen/sgen-internal.c
mono/tests/Makefile.am
mono/tests/libtest.c
mono/tests/pinvoke2.cs
mono/utils/Makefile.am
mono/utils/atomic.c
mono/utils/mono-compiler.h
mono/utils/mono-context.h
mono/utils/mono-dl-windows-uwp.c [new file with mode: 0644]
mono/utils/mono-dl-windows.c
mono/utils/mono-dl-windows.h [new file with mode: 0644]
mono/utils/mono-error-internals.h
mono/utils/mono-error.c
mono/utils/mono-error.h
mono/utils/mono-io-portability.c
mono/utils/mono-log-common.c
mono/utils/mono-log-windows.c
mono/utils/mono-logger.c
mono/utils/mono-mmap-internals.h
mono/utils/mono-mmap-windows-uwp.c [new file with mode: 0644]
mono/utils/mono-mmap-windows.c [new file with mode: 0644]
mono/utils/mono-mmap-windows.h [new file with mode: 0644]
mono/utils/mono-mmap.c
mono/utils/mono-proclib-windows-uwp.c [new file with mode: 0644]
mono/utils/mono-proclib-windows.c [new file with mode: 0644]
mono/utils/mono-proclib-windows.h [new file with mode: 0644]
mono/utils/mono-proclib.c
mono/utils/mono-rand-windows-uwp.c [new file with mode: 0644]
mono/utils/mono-rand-windows.c [new file with mode: 0644]
mono/utils/mono-rand-windows.h [new file with mode: 0644]
mono/utils/mono-rand.c
mono/utils/mono-threads-posix.c
mono/utils/mono-threads-windows-abort-syscall.c
mono/utils/mono-threads-windows.c
mono/utils/mono-threads.c
mono/utils/mono-threads.h
mono/utils/networking-missing.c
msvc/libmono-static.vcxproj
msvc/libmono-static.vcxproj.filters
msvc/libmonoruntime.vcxproj
msvc/libmonoruntime.vcxproj.filters
msvc/libmonoutils.vcxproj
msvc/libmonoutils.vcxproj.filters
msvc/monoposixhelper.def
msvc/monoposixhelper.vcxproj
msvc/monoposixhelper.vcxproj.filters
msvc/pedump.vcxproj
msvc/pedump.vcxproj.filters
scripts/Makefile.am
scripts/ci/run-test-default.sh

index 6d87209417eec370475d4ece03cc108c5ea06dd4..1c8f76e0107dae1e948de7280f293bcd110ef7b1 100644 (file)
@@ -43,3 +43,6 @@
        path = external/boringssl
        url = git://github.com/mono/boringssl.git
        branch = mono
+[submodule "external/corefx"]
+       path = external/corefx
+       url = git://github.com/mono/corefx.git
index f79f320c00987585a5cbd6f560ac52708b967cf2..491e142eb5056354f8b63eaf4e4f3ad67afe6090 100644 (file)
@@ -68,7 +68,11 @@ AC_SUBST(libmono_cflags)
 AC_SUBST(libmono_ldflags)
 
 # Variable to have relocatable .pc files (lib, or lib64)
-reloc_libdir=`basename ${libdir}`
+# realpath isn't always available, and requires that all but the tip of the provided
+# path exists. Fall back to the old behaviour, but realpath allows depth >1
+# e.g. Debian puts Mono in /usr/bin and libs in /usr/lib/x86_64-linux-gnu/ which is
+# too deep for the old method to work
+reloc_libdir=`realpath --relative-to=${prefix} ${libdir} 2> /dev/null || basename ${libdir}`
 AC_SUBST(reloc_libdir)
 
 # Set to yes if Unix sockets cannot be created in an anonymous namespace
@@ -3915,7 +3919,7 @@ dnl **************
 dnl ***  Btls  ***
 dnl **************
 
-AC_ARG_ENABLE(btls, [  --disable-blts             Disable the BoringTls provider], enable_btls=$enableval, enable_btls=$BTLS_SUPPORTED)
+AC_ARG_ENABLE(btls, [  --disable-btls             Disable the BoringTls provider], enable_btls=$enableval, enable_btls=$BTLS_SUPPORTED)
 AC_ARG_WITH(btls_android_ndk, [  --with-btls-android-ndk        Android NDK for BoringTls])
 
 AM_CONDITIONAL(BTLS, test x$enable_btls = xyes)
diff --git a/external/corefx b/external/corefx
new file mode 160000 (submodule)
index 0000000..b1aa1d9
--- /dev/null
@@ -0,0 +1 @@
+Subproject commit b1aa1d92ca33d0cb8ffbac9b6ff73b284db6bbf1
index 9f44f259bf5059df6c8019948ea75313bd09a9fb..367864ef810859ae3ce652864233b35f2dd5fdbe 160000 (submodule)
@@ -1 +1 @@
-Subproject commit 9f44f259bf5059df6c8019948ea75313bd09a9fb
+Subproject commit 367864ef810859ae3ce652864233b35f2dd5fdbe
index c4589ea70c7243f74525d5669f342c983f24f39b..08a93ac91823901085ca08edf8daa9d6b08b2363 100644 (file)
@@ -332,6 +332,12 @@ Currently this merely ensures that you are running either the
 \fBMONO_ENV_OPTIONS\fR environment variable to force all of your child
 processes to use one particular kind of GC with the Mono runtime.
 .TP
+\fB--gc-debug=[options]\fR
+Command line equivalent of the \fBMONO_GC_DEBUG\fR environment variable.
+.TP
+\fB--gc-params=[options]\fR
+Command line equivalent of the \fBMONO_GC_PARAMS\fR environment variable.
+.TP
 \fB--arch=32\fR, \fB--arch=64\fR
 (Mac OS X only): Selects the bitness of the Mono binary used, if
 available. If the binary used is already for the selected bitness, nothing
index f8f0b0a9396c0061111da1316a13812edea6936a..45d9d4b4c832a289bd4571791ea34eb9a15cd67a 100644 (file)
@@ -344,6 +344,7 @@ DISTFILES = \
        MicrosoftAjaxLibrary/License.htm        \
        test-helpers/NetworkHelpers.cs  \
        test-helpers/SocketResponder.cs \
+       lib/$(monolite_dir)/basic.exe   \
        $(monolite_files)
 
 .PHONY: all-local $(STD_TARGETS:=-local)
@@ -376,11 +377,13 @@ $(monolite_files): | lib/$(monolite_dir)/Facades
 $(monolite_files): lib/$(monolite_dir)/%: lib/build/%
        cp -p $< $@
 
+lib/$(monolite_dir)/basic.exe:
+       cp -p lib/basic/basic.exe lib/$(monolite_dir)
+
 $(build_files:%=lib/build/%):
        cd $(topdir) && $(MAKE) profile-do--build--all NO_DIR_CHECK=1 SKIP_AOT=1
 
-dist-monolite: $(monolite_files)
-       cp -p lib/basic/basic.exe lib/$(monolite_dir)
+dist-monolite: $(monolite_files) lib/$(monolite_dir)/basic.exe
 
 dist-default: dist-monolite
 
index 1a4e4317421d460b5a13cc638b1514cddf5db232..2398184df6d706fb5fc9aefc0d9bfb3f4c8c4666 100644 (file)
@@ -24,6 +24,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
 using System;
+using System.IO;
 using Microsoft.Build.BuildEngine;
 using NUnit.Framework;
 
@@ -61,6 +62,11 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
                                </Project>
                        ";
 
+                       if (Path.DirectorySeparatorChar == '\\') {
+                               documentString = documentString.Replace ("/home", "c:/home");
+                               documentString = documentString.Replace ("/tmp", "c:/tmp");
+                       }
+
                        var engine = new Engine (Consts.BinPath);
                        var project = engine.CreateNewProject ();
                        project.LoadXml (documentString);
index 6c7919e6ae7db4d7c36cc02ad79cc4ceebc10ab3..459bb66e6d5cd3cde9d2007433d0e8aaecb1a480 100644 (file)
@@ -40,6 +40,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
        [TestFixture]
        public class TargetTest {
                
+               static bool isMono = Type.GetType ("Mono.Runtime", false) != null;
                Engine                  engine;
                Project                 project;
                
@@ -351,16 +352,16 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
 
                bool Build (string projectXml, ILogger logger)
                {
-                       if (Environment.OSVersion.Platform == PlatformID.Win32NT) {
+                       if (!isMono) {
                                var reader = new StringReader (projectXml);
                                var xml = XmlReader.Create (reader);
-                               return BuildOnWindows (xml, logger);
+                               return BuildOnDotNet (xml, logger);
                        } else {
-                               return BuildOnLinux (projectXml, logger);
+                               return BuildOnMono (projectXml, logger);
                        }
                }
 
-               bool BuildOnWindows (XmlReader reader, ILogger logger)
+               bool BuildOnDotNet (XmlReader reader, ILogger logger)
                {
                        var type = Type.GetType ("Microsoft.Build.Evaluation.ProjectCollection, Microsoft.Build, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
 
@@ -376,7 +377,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
                        return ret;
                }
 
-               bool BuildOnLinux (string projectXml, ILogger logger)
+               bool BuildOnMono (string projectXml, ILogger logger)
                {
                        var engine = new Engine (Consts.BinPath);
                        var project = engine.CreateNewProject ();
index 54f1c8a94cc2c935c49a573869ba9799aa6568df..144a6d72ea2e134bcfd4cdd96369be9b377fc66c 100644 (file)
@@ -129,6 +129,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine.Various {
                }
 
                [Test]
+               [SetCulture ("en-us")]
                public void AllowedFrameworkMembers ()
                {
                        string documentString = @"
@@ -202,6 +203,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine.Various {
                }
 
                [Test]
+               [SetCulture ("en-us")]
                public void MSBuildPropertyFunctions ()
                {
                        string documentString = @"
index 43917b03e340b8917fac8248808ced3b00b13c5c..19649dadf86b904503eeaa8835d2a4dcca5fa1c9 100755 (executable)
@@ -158,11 +158,11 @@ namespace MonoTests.Microsoft.Build.Tasks
                        Assert.AreEqual(files.Length, include.Count, id + "2");
 
                        for (int i = 0; i < files.Length; i++) {
-                               Assert.AreEqual (files [i], include [i].FinalItemSpec, id + "3, file #" + i);
+                               Assert.AreEqual (files [i], include [i].FinalItemSpec.Replace ("\\", "/"), id + "3, file #" + i);
                                Assert.IsTrue (include[i].HasMetadata ("TargetPath"), id + "4, file #" + i + ", TargetPath metadata missing");
                                Assert.AreEqual (assignedFiles [i], include[i].GetMetadata("TargetPath"), id + "5, file #" + i);
                                Assert.IsTrue (include [i].HasMetadata ("Child"), id + "6, file #" + i + ", Child metadata missing");
-                               Assert.AreEqual ("C" + files [i], include [i].GetMetadata ("Child"), id + "7, file #" + i + ", Child metadata value incorrect");
+                               Assert.AreEqual ("C" + files [i], include [i].GetMetadata ("Child").Replace ("\\", "/"), id + "7, file #" + i + ", Child metadata value incorrect");
                        }
                }
 
index ad7ca03ba5a6ebb9b3fcb611f695492d0a673a3e..dab6adaf7a3aac4ff02f42ee0c16ca3f43590a5f 100644 (file)
@@ -301,7 +301,11 @@ namespace MonoTests.Microsoft.Build.Tasks {
                                Assert.Fail ("Build failed");
                        }
                        Assert.IsTrue (File.Exists (target_file), "A2");
-                       Assert.AreEqual (FileAttributes.Normal, File.GetAttributes (target_file), "A3");                                        
+                       if (Environment.OSVersion.Platform == PlatformID.Unix)
+                               Assert.AreEqual (FileAttributes.Normal, File.GetAttributes (target_file), "A3");
+                       else
+                               // On Windows the Archive attribute will be set, not the Normal attribute.
+                               Assert.AreEqual (FileAttributes.Archive, File.GetAttributes (target_file), "A3");
                }
 
                [Test]
@@ -349,7 +353,12 @@ namespace MonoTests.Microsoft.Build.Tasks {
                                Assert.Fail ("Build failed " + sb.ToString ());
                        }
                        Assert.IsTrue (File.Exists (target_file), "A2");
-                       Assert.AreEqual (FileAttributes.Normal, File.GetAttributes (target_file), "A3");                                        
+                       var target_file_attrs = File.GetAttributes (target_file);
+                       if (Environment.OSVersion.Platform == PlatformID.Unix)
+                               Assert.AreEqual (FileAttributes.Normal, File.GetAttributes (target_file), "A3");
+                       else
+                               // On Windows the Archive attribute will be set, not the Normal attribute.
+                               Assert.AreEqual (FileAttributes.Archive, File.GetAttributes (target_file), "A3");
                }
 
                [Test]
index 3342c003e8bf890d8df77900cb32aee9f6d3eb0f..41c8d8e4f103a7bebdd6737de846e8f57b4654c4 100755 (executable)
@@ -115,6 +115,9 @@ namespace MonoTests.Microsoft.Build.Tasks {
                [Test]
                public void TestLineWithEscapedQuote ()
                {
+                       if (Environment.OSVersion.Platform != PlatformID.Unix) {
+                               Assert.Ignore ("Throws \"Illegal characters in path\" on Windows since \" is not a legal Windows path character");
+                       }
                        string[] lines = new string[] { "%22abc test%22 123 %22def%22" };
                        CreateProjectAndCheck (full_filepath, lines, false, true, delegate () {
                                CheckFileExists (full_filepath, true);
index 61973b7ceb48f80a4f2b7c64eac02b7f11934e25..f3b3524ba81277d944e710e63f7c0760c31786ba 100644 (file)
@@ -90,7 +90,7 @@ namespace MonoTests.Microsoft.Build.Evaluation
                {
                        string project_xml = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
   <ItemGroup>
-    <Foo Include='Test/ProjectItemTestTemporary/parent/dir*/a*.cs;Test/ProjectItemTestTemporary/x.cs' />
+    <Foo Include='" + "Test/ProjectItemTestTemporary/parent/dir*/a*.cs;Test/ProjectItemTestTemporary/x.cs".Replace ('/', Path.DirectorySeparatorChar) + @"' />
   </ItemGroup>
 </Project>";
                        try {
@@ -106,7 +106,7 @@ namespace MonoTests.Microsoft.Build.Evaluation
                {
                        string project_xml = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
   <ItemGroup>
-    <Foo Include='Test/ProjectItemTestTemporary/parent/**/a*.cs;Test/ProjectItemTestTemporary/x.cs' />
+    <Foo Include='" + "Test/ProjectItemTestTemporary/parent/**/a*.cs;Test/ProjectItemTestTemporary/x.cs".Replace ('/', Path.DirectorySeparatorChar) + @"' />
   </ItemGroup>
 </Project>";
                        try {
@@ -127,23 +127,23 @@ namespace MonoTests.Microsoft.Build.Evaluation
                        // sort is needed because they are only sorted by ItemType.
                        var items = proj.Items.OrderBy (p => p.EvaluatedInclude).ToArray ();
                        Assert.AreEqual (5, items.Length, "#1");
-                       Assert.AreEqual (string.Format ("Test/ProjectItemTestTemporary/parent/dir1{0}a.cs", Path.DirectorySeparatorChar), items [0].EvaluatedInclude, "#2");
+                       Assert.AreEqual ("Test/ProjectItemTestTemporary/parent/dir1/a.cs", items [0].EvaluatedInclude.Replace (Path.DirectorySeparatorChar, '/'), "#2");
                        Assert.AreEqual ("a", items [0].GetMetadataValue ("Filename"), "#3");
                        if (hasRecursiveDir)
                                Assert.AreEqual ("dir1" + sep, items [0].GetMetadataValue ("RecursiveDir"), "#3.2");
-                       Assert.AreEqual (string.Format ("Test/ProjectItemTestTemporary/parent/dir1{0}a1.cs", Path.DirectorySeparatorChar), items [1].EvaluatedInclude, "#4");
+                       Assert.AreEqual ("Test/ProjectItemTestTemporary/parent/dir1/a1.cs", items [1].EvaluatedInclude.Replace (Path.DirectorySeparatorChar, '/'), "#4");
                        Assert.AreEqual ("a1", items [1].GetMetadataValue ("Filename"), "#5");
                        if (hasRecursiveDir)
                                Assert.AreEqual ("dir1" + sep, items [1].GetMetadataValue ("RecursiveDir"), "#5.2");
-                       Assert.AreEqual (string.Format ("Test/ProjectItemTestTemporary/parent/dir2{0}a.cs", Path.DirectorySeparatorChar), items [2].EvaluatedInclude, "#6");
+                       Assert.AreEqual ("Test/ProjectItemTestTemporary/parent/dir2/a.cs", items [2].EvaluatedInclude.Replace (Path.DirectorySeparatorChar, '/'), "#6");
                        Assert.AreEqual ("a", items [2].GetMetadataValue ("Filename"), "#7");
                        if (hasRecursiveDir)
                                Assert.AreEqual ("dir2" + sep, items [2].GetMetadataValue ("RecursiveDir"), "#7.2");
-                       Assert.AreEqual (string.Format ("Test/ProjectItemTestTemporary/parent/dir2{0}a2.cs", Path.DirectorySeparatorChar), items [3].EvaluatedInclude, "#8");
+                       Assert.AreEqual ("Test/ProjectItemTestTemporary/parent/dir2/a2.cs", items [3].EvaluatedInclude.Replace (Path.DirectorySeparatorChar, '/'), "#8");
                        Assert.AreEqual ("a2", items [3].GetMetadataValue ("Filename"), "#9");
                        if (hasRecursiveDir)
                                Assert.AreEqual ("dir2" + sep, items [3].GetMetadataValue ("RecursiveDir"), "#9.2");
-                       Assert.AreEqual ("Test/ProjectItemTestTemporary/x.cs", items [4].EvaluatedInclude, "#10");
+                       Assert.AreEqual ("Test/ProjectItemTestTemporary/x.cs", items [4].EvaluatedInclude.Replace (Path.DirectorySeparatorChar, '/'), "#10");
                        for (int i = 0; i < items.Length; i++)
                                Assert.AreEqual (xitem, items [i].Xml, "#11:" + i);
                }
index 9723191bf164f6643724dcc990d59e609bf35003..f14bcd864ac75839762a8220b18f9fb9090fc187 100644 (file)
@@ -108,7 +108,8 @@ namespace MonoTests.Microsoft.Build.Execution
                        Assert.IsTrue (sub.BuildResult.OverallResult == BuildResultCode.Success, "#1");
                        DateTime endBuildDone = DateTime.Now;
                        Assert.IsTrue (endBuildDone - beforeExec >= TimeSpan.FromSeconds (1), "#2");
-                       Assert.IsTrue (endBuildDone > waitDone, "#3");
+                       Assert.IsTrue (waitDone >= beforeExec, "#3");
+                       Assert.IsTrue (endBuildDone >= waitDone, "#4");
                }
                
                [Test]
index 6a8d81062531fd737211a192a19de4775eeb18ea..0959dd0b61243891a25165932c892fc62e319cea 100644 (file)
@@ -26,6 +26,7 @@
 using System;
 using Mono.Security.Interface;
 using System.Security.Cryptography.X509Certificates;
+using MNS = Mono.Net.Security;
 
 namespace Mono.Btls.Interface
 {
@@ -33,7 +34,7 @@ namespace Mono.Btls.Interface
        {
                public static bool IsSupported ()
                {
-                       return MonoBtlsProvider.IsSupported ();
+                       return MNS.MonoTlsProviderFactory.IsBtlsSupported ();
                }
 
                public static MonoTlsProvider GetProvider ()
index 7f35914d241f72792d3667671bf8add783dd3dca..45b2db176875cbf3a4dc9fc0811ae180b64a71d3 100644 (file)
@@ -221,7 +221,7 @@ namespace Mono.Data.Sqlite
         case SQLiteDateFormats.UnixEpoch:\r
           return ((long)(dateValue.Subtract(UnixEpoch).Ticks / TimeSpan.TicksPerSecond)).ToString();\r
         default:\r
-          return dateValue.ToString(_datetimeFormats[7], CultureInfo.InvariantCulture);\r
+          return dateValue.ToString(_datetimeFormats[5], CultureInfo.InvariantCulture);\r
       }\r
     }\r
 \r
index 0a02896ef8ddaa01b2ebec83459d4cfeadc88807..643c40a86da80e8ac3d3afd94d1d04c4cf43d7f2 100644 (file)
@@ -6,4 +6,4 @@ SqliteExceptionUnitTests.cs
 SqliteParameterUnitTests.cs
 SqliteFunctionTests.cs
 Bug27864.cs
-
+SqliteTests.cs
index d64d3055b999b36e07e8ba66aeed04a5aba275c0..b381e1fde72bbdc7d29dd4ffdb482cb863bd5a9c 100644 (file)
@@ -9,7 +9,6 @@
 // Copyright 2015 Xamarin Inc.
 //
 
-#if MONOTOUCH
 using System;
 using System.Data;
 using System.IO;
@@ -96,13 +95,14 @@ namespace MonoTests.Mono.Data.Sqlite {
                                        }
                                }
                        } catch (SqliteException ex) {
+#if MONOTOUCH
                                // Expected Exception from iOS 8.2 (broken) to 9.0 (fixed)
                                if (BCL.Tests.TestRuntime.CheckSystemVersion (8,2) && !BCL.Tests.TestRuntime.CheckSystemVersion (9,0)) 
                                        Assert.That (ex.Message.Contains ("no such column: com.Name"));
                                else
-                                       throw new AssertionException ("Unexpected Sqlite Error", ex); // This should not happen
+                                       throw;
+#endif
                        }
                }
        }
 }
-#endif
\ No newline at end of file
diff --git a/mcs/class/Mono.Data.Sqlite/Test/SqliteTests.cs b/mcs/class/Mono.Data.Sqlite/Test/SqliteTests.cs
new file mode 100644 (file)
index 0000000..1533945
--- /dev/null
@@ -0,0 +1,102 @@
+//
+// SqliteTests.cs
+//
+// Authors:
+//     Marek Safar  <marek.safar@gmail.com>
+//
+// Copyright (C) 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.Data;
+using System.IO;
+using System.Text;
+using Mono.Data.Sqlite;
+using NUnit.Framework;
+
+namespace MonoTests.Mono.Data.Sqlite
+{
+       [TestFixture]
+       public class SqliteTests
+       {
+               string _databasePath;
+
+               [SetUp]
+               public void Setup ()
+               {
+                       var dataFolder = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), "SqlTest");
+
+                       _databasePath = Path.Combine (dataFolder, "database.db");
+
+                       if (!Directory.Exists (dataFolder)) {
+                               Directory.CreateDirectory (dataFolder);
+                       }
+
+                       File.Delete (_databasePath);
+               }
+
+               [TearDown]
+               public void TearDown ()
+               {
+                       try {
+                               File.Delete (_databasePath);
+                       } catch {
+                       }
+               }
+
+               [Test]
+               public void DateTimeConvert ()
+               {
+                       var dateTime = new DateTime (2016, 9, 15, 12, 1, 53);
+                       var guid = Guid.NewGuid ();
+
+                       using (var connection = new SqliteConnection ("Data Source=" + _databasePath)) {
+                               connection.Open ();
+
+                               var sqlCreate = "CREATE TABLE TestTable (ID uniqueidentifier PRIMARY KEY, Modified datetime)";
+                               using (var cmd = new SqliteCommand (sqlCreate, connection)) {
+                                       cmd.ExecuteNonQuery ();
+                               }
+
+                               var sqlInsert = "INSERT INTO TestTable (ID, Modified) VALUES (@id, @mod)";
+                               using (var cmd = new SqliteCommand (sqlInsert, connection)) {
+                                       cmd.Parameters.Add (new SqliteParameter ("@id", guid));
+                                       cmd.Parameters.Add (new SqliteParameter ("@mod", dateTime));
+                                       cmd.ExecuteNonQuery ();
+                               }
+                       }
+
+                       using (var connection = new SqliteConnection ("Data Source=" + _databasePath)) {
+                               connection.Open ();
+
+                               var sqlSelect = "SELECT * from TestTable";
+                               using (var cmd = new SqliteCommand (sqlSelect, connection))
+                               using (var reader = cmd.ExecuteReader ()) {
+                                       while (reader.Read ()) {
+                                               Assert.AreEqual (guid, reader.GetGuid (0), "#1");
+                                               Assert.AreEqual (dateTime, reader.GetDateTime (1), "#2");
+                                       }
+                               }
+                       }
+               }
+       }
+}
diff --git a/mcs/class/System.Core/System.Security.Cryptography/CngAlgorithm.cs b/mcs/class/System.Core/System.Security.Cryptography/CngAlgorithm.cs
deleted file mode 100644 (file)
index ea87b30..0000000
+++ /dev/null
@@ -1,192 +0,0 @@
-//
-// System.Security.Cryptography.CngAlgorithm
-//
-// Authors:
-//     Sebastien Pouliot  <sebastien@ximian.com>
-//
-// Copyright (C) 2008 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;
-
-namespace System.Security.Cryptography {
-
-       // note: CNG stands for "Cryptography API: Next Generation"
-
-       [Serializable]
-       public sealed class CngAlgorithm : IEquatable<CngAlgorithm> {
-
-               private string m_algorithm;
-
-               public CngAlgorithm (string algorithm)
-               {
-                       if (algorithm == null)
-                               throw new ArgumentNullException ("algorithm");
-                       if (algorithm.Length == 0)
-                               throw new ArgumentException ("algorithm");
-
-                       m_algorithm = algorithm;
-               }
-
-               public string Algorithm {
-                       get { return m_algorithm; }
-               }
-
-               public bool Equals (CngAlgorithm other)
-               {
-                       if (other == null)
-                               return false;
-                       return m_algorithm == other.m_algorithm;
-               }
-
-               public override bool Equals (object obj)
-               {
-                       return Equals (obj as CngAlgorithm);
-               }
-
-               public override int GetHashCode ()
-               {
-                       return m_algorithm.GetHashCode ();
-               }
-
-               public override string ToString ()
-               {
-                       return m_algorithm;
-               }
-
-               // static
-
-               static CngAlgorithm dh256;
-               static CngAlgorithm dh384;
-               static CngAlgorithm dh521;
-               static CngAlgorithm dsa256;
-               static CngAlgorithm dsa384;
-               static CngAlgorithm dsa521;
-               static CngAlgorithm md5;
-               static CngAlgorithm sha1;
-               static CngAlgorithm sha256;
-               static CngAlgorithm sha384;
-               static CngAlgorithm sha512;
-
-               public static CngAlgorithm ECDiffieHellmanP256 {
-                       get {
-                               if (dh256 == null)
-                                       dh256 = new CngAlgorithm ("ECDH_P256");
-                               return dh256;
-                       }
-               }
-
-               public static CngAlgorithm ECDiffieHellmanP384 {
-                       get {
-                               if (dh384 == null)
-                                       dh384 = new CngAlgorithm ("ECDH_P384");
-                               return dh384;
-                       }
-               }
-
-               public static CngAlgorithm ECDiffieHellmanP521 {
-                       get {
-                               if (dh521 == null)
-                                       dh521 = new CngAlgorithm ("ECDH_P521");
-                               return dh521;
-                       }
-               }
-
-               public static CngAlgorithm ECDsaP256 {
-                       get {
-                               if (dsa256 == null)
-                                       dsa256 = new CngAlgorithm ("ECDSA_P256");
-                               return dsa256;
-                       }
-               }
-
-               public static CngAlgorithm ECDsaP384 {
-                       get {
-                               if (dsa384 == null)
-                                       dsa384 = new CngAlgorithm ("ECDSA_P384");
-                               return dsa384;
-                       }
-               }
-
-               public static CngAlgorithm ECDsaP521 {
-                       get {
-                               if (dsa521 == null)
-                                       dsa521 = new CngAlgorithm ("ECDSA_P521");
-                               return dsa521;
-                       }
-               }
-
-               public static CngAlgorithm MD5 {
-                       get {
-                               if (md5 == null)
-                                       md5 = new CngAlgorithm ("MD5");
-                               return md5;
-                       }
-               }
-
-               public static CngAlgorithm Sha1 {
-                       get {
-                               if (sha1 == null)
-                                       sha1 = new CngAlgorithm ("SHA1");
-                               return sha1;
-                       }
-               }
-
-               public static CngAlgorithm Sha256 {
-                       get {
-                               if (sha256 == null)
-                                       sha256 = new CngAlgorithm ("SHA256");
-                               return sha256;
-                       }
-               }
-
-               public static CngAlgorithm Sha384 {
-                       get {
-                               if (sha384 == null)
-                                       sha384 = new CngAlgorithm ("SHA384");
-                               return sha384;
-                       }
-               }
-
-               public static CngAlgorithm Sha512 {
-                       get {
-                               if (sha512 == null)
-                                       sha512 = new CngAlgorithm ("SHA512");
-                               return sha512;
-                       }
-               }
-
-               public static bool operator == (CngAlgorithm left, CngAlgorithm right)
-               {
-                       if ((object)left == null)
-                               return ((object)right == null);
-                       return left.Equals (right);
-               }
-
-               public static bool operator != (CngAlgorithm left, CngAlgorithm right)
-               {
-                       if ((object)left == null)
-                               return ((object)right != null);
-                       return !left.Equals (right);
-               }
-       }
-}
diff --git a/mcs/class/System.Core/System.Security.Cryptography/CngAlgorithmGroup.cs b/mcs/class/System.Core/System.Security.Cryptography/CngAlgorithmGroup.cs
deleted file mode 100644 (file)
index fa43965..0000000
+++ /dev/null
@@ -1,138 +0,0 @@
-//
-// System.Security.Cryptography.CngAlgorithmGroup
-//
-// Authors:
-//     Sebastien Pouliot  <sebastien@ximian.com>
-//
-// Copyright (C) 2008 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;
-
-namespace System.Security.Cryptography {
-
-       // note: CNG stands for "Cryptography API: Next Generation"
-
-       [Serializable]
-       public sealed class CngAlgorithmGroup : IEquatable<CngAlgorithmGroup> {
-
-               private string m_algorithmGroup;
-
-               public CngAlgorithmGroup (string algorithmGroup)
-               {
-                       if (algorithmGroup == null)
-                               throw new ArgumentNullException ("algorithmGroup");
-                       if (algorithmGroup.Length == 0)
-                               throw new ArgumentException ("algorithmGroup");
-
-                       m_algorithmGroup = algorithmGroup;
-               }
-
-               public string AlgorithmGroup {
-                       get { return m_algorithmGroup; }
-               }
-
-               public bool Equals (CngAlgorithmGroup other)
-               {
-                       if (other == null)
-                               return false;
-                       return m_algorithmGroup == other.m_algorithmGroup;
-               }
-
-               public override bool Equals (object obj)
-               {
-                       return Equals (obj as CngAlgorithmGroup);
-               }
-
-               public override int GetHashCode ()
-               {
-                       return m_algorithmGroup.GetHashCode ();
-               }
-
-               public override string ToString ()
-               {
-                       return m_algorithmGroup;
-               }
-
-               // static
-
-               private static CngAlgorithmGroup dh;
-               private static CngAlgorithmGroup dsa;
-               private static CngAlgorithmGroup ecdh;
-               private static CngAlgorithmGroup ecdsa;
-               private static CngAlgorithmGroup rsa;
-
-               public static CngAlgorithmGroup DiffieHellman {
-                       get {
-                               if (dh == null)
-                                       dh = new CngAlgorithmGroup ("DH");
-                               return dh;
-                       }
-               }
-
-               public static CngAlgorithmGroup Dsa {
-                       get {
-                               if (dsa == null)
-                                       dsa = new CngAlgorithmGroup ("DSA");
-                               return dsa;
-                       }
-               }
-
-               public static CngAlgorithmGroup ECDiffieHellman {
-                       get {
-                               if (ecdh == null)
-                                       ecdh = new CngAlgorithmGroup ("ECDH");
-                               return ecdh;
-                       }
-               }
-
-               public static CngAlgorithmGroup ECDsa {
-                       get {
-                               if (ecdsa == null)
-                                       ecdsa = new CngAlgorithmGroup ("ECDSA");
-                               return ecdsa;
-                       }
-               }
-
-               public static CngAlgorithmGroup Rsa {
-                       get {
-                               if (rsa == null)
-                                       rsa = new CngAlgorithmGroup ("RSA");
-                               return rsa;
-                       }
-               }
-
-               public static bool operator == (CngAlgorithmGroup left, CngAlgorithmGroup right)
-               {
-                       if ((object)left == null)
-                               return ((object)right == null);
-                       return left.Equals (right);
-               }
-
-               public static bool operator != (CngAlgorithmGroup left, CngAlgorithmGroup right)
-               {
-                       if ((object)left == null)
-                               return ((object)right != null);
-                       return !left.Equals (right);
-               }
-       }
-}
diff --git a/mcs/class/System.Core/System.Security.Cryptography/CngExportPolicies.cs b/mcs/class/System.Core/System.Security.Cryptography/CngExportPolicies.cs
deleted file mode 100644 (file)
index 90a1aa5..0000000
+++ /dev/null
@@ -1,40 +0,0 @@
-//
-// System.Security.Cryptography.CngExportPolicies
-//
-// Copyright (C) 2011 Juho Vähä-Herttua
-//
-// 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;
-
-namespace System.Security.Cryptography {
-
-       // note: CNG stands for "Cryptography API: Next Generation"
-
-       [Flags]
-       public enum CngExportPolicies {
-               None,
-               AllowExport,
-               AllowPlaintextExport,
-               AllowArchiving,
-               AllowPlaintextArchiving
-       }
-}
diff --git a/mcs/class/System.Core/System.Security.Cryptography/CngKeyCreationOptions.cs b/mcs/class/System.Core/System.Security.Cryptography/CngKeyCreationOptions.cs
deleted file mode 100644 (file)
index da28e7b..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-//
-// System.Security.Cryptography.CngKeyCreationOptions
-//
-// Copyright (C) 2011 Juho Vähä-Herttua
-//
-// 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;
-
-namespace System.Security.Cryptography {
-
-       // note: CNG stands for "Cryptography API: Next Generation"
-
-       [Flags]
-       public enum CngKeyCreationOptions {
-               None                 = 0x00,
-               MachineKey           = 0x20,
-               OverwriteExistingKey = 0x80
-       }
-}
diff --git a/mcs/class/System.Core/System.Security.Cryptography/CngKeyCreationParameters.cs b/mcs/class/System.Core/System.Security.Cryptography/CngKeyCreationParameters.cs
deleted file mode 100644 (file)
index 8963324..0000000
+++ /dev/null
@@ -1,92 +0,0 @@
-//
-// System.Security.Cryptography.CngKeyCreationParameters
-//
-// Copyright (C) 2011 Juho Vähä-Herttua
-//
-// 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;
-
-namespace System.Security.Cryptography {
-
-       // note: CNG stands for "Cryptography API: Next Generation"
-
-       public class CngKeyCreationParameters {
-               private Nullable<CngExportPolicies> exportPolicy;
-               private CngKeyCreationOptions keyCreationOptions;
-               private Nullable<CngKeyUsages> keyUsage;
-               private CngPropertyCollection parameters;
-               private IntPtr parentWindowHandle;
-               private CngProvider provider;
-               private CngUIPolicy uiPolicy;
-
-               public CngKeyCreationParameters ()
-               {
-                       parameters = new CngPropertyCollection ();
-                       provider = CngProvider.MicrosoftSoftwareKeyStorageProvider;
-               }
-
-               public Nullable<CngExportPolicies> ExportPolicy
-               {
-                       get { return exportPolicy; }
-                       set { exportPolicy = value; }
-               }
-
-               public CngKeyCreationOptions KeyCreationOptions
-               {
-                       get { return keyCreationOptions; }
-                       set { keyCreationOptions = value; }
-               }
-
-               public Nullable<CngKeyUsages> KeyUsage
-               {
-                       get { return keyUsage; }
-                       set { keyUsage = value; }
-               }
-
-               public CngPropertyCollection Parameters
-               {
-                       get { return parameters; }
-               }
-
-               public IntPtr ParentWindowHandle
-               {
-                       get { return parentWindowHandle; }
-                       set { parentWindowHandle = value; }
-               }
-
-               public CngProvider Provider
-               {
-                       get { return provider; }
-                       set {
-                               if (value == null)
-                                       throw new ArgumentNullException ("value");
-                               provider = value;
-                       }
-               }
-
-               public CngUIPolicy UIPolicy
-               {
-                       get { return uiPolicy; }
-                       set { uiPolicy = value; }
-               }
-       }
-}
diff --git a/mcs/class/System.Core/System.Security.Cryptography/CngKeyOpenOptions.cs b/mcs/class/System.Core/System.Security.Cryptography/CngKeyOpenOptions.cs
deleted file mode 100644 (file)
index dcc3289..0000000
+++ /dev/null
@@ -1,39 +0,0 @@
-//
-// System.Security.Cryptography.CngKeyOpenOptions
-//
-// Copyright (C) 2011 Juho Vähä-Herttua
-//
-// 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;
-
-namespace System.Security.Cryptography {
-
-       // note: CNG stands for "Cryptography API: Next Generation"
-
-       [Flags]
-       public enum CngKeyOpenOptions {
-               None       = 0x00,
-               UserKey    = 0x00,
-               MachineKey = 0x20,
-               Silent     = 0x40
-       }
-}
diff --git a/mcs/class/System.Core/System.Security.Cryptography/CngKeyUsages.cs b/mcs/class/System.Core/System.Security.Cryptography/CngKeyUsages.cs
deleted file mode 100644 (file)
index 35f1d43..0000000
+++ /dev/null
@@ -1,40 +0,0 @@
-//
-// System.Security.Cryptography.CngKeyUsages
-//
-// Copyright (C) 2011 Juho Vähä-Herttua
-//
-// 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;
-
-namespace System.Security.Cryptography {
-
-       // note: CNG stands for "Cryptography API: Next Generation"
-
-       [Flags]
-       public enum CngKeyUsages {
-               None,
-               Decryption,
-               Signing,
-               KeyAgreement,
-               AllUsages = 0xffffff
-       }
-}
diff --git a/mcs/class/System.Core/System.Security.Cryptography/CngProperty.cs b/mcs/class/System.Core/System.Security.Cryptography/CngProperty.cs
deleted file mode 100644 (file)
index f0948bb..0000000
+++ /dev/null
@@ -1,115 +0,0 @@
-//
-// System.Security.Cryptography.CngProperty
-//
-// Copyright (C) 2011 Juho Vähä-Herttua
-//
-// 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;
-
-namespace System.Security.Cryptography {
-
-       // note: CNG stands for "Cryptography API: Next Generation"
-
-       public struct CngProperty : IEquatable<CngProperty> {
-               private string name;
-               private byte[] val;
-               private CngPropertyOptions opts;
-
-               public CngProperty(string name, byte[] value, CngPropertyOptions options)
-               {
-                       if (name == null)
-                               throw new ArgumentNullException("name");
-
-                       this.name = name;
-                       this.val = (value != null) ? (byte[]) value.Clone () : null;
-                       this.opts = options;
-               }
-
-               public string Name {
-                       get { return name; }
-               }
-
-               public CngPropertyOptions Options {
-                       get { return opts; }
-               }
-
-               public byte[] GetValue ()
-               {
-                       if (val == null)
-                               return null;
-                       return (byte[]) val.Clone ();
-               }
-
-               public bool Equals (CngProperty other)
-               {
-                       if (this.name != other.name || this.opts != other.opts)
-                               return false;
-                       if (this.val == null && other.val == null)
-                               return true;
-                       if (this.val == null || other.val == null)
-                               return false;
-                       if (this.val.Length != other.val.Length)
-                               return false;
-
-                       for (int i=0; i<val.Length; i++) {
-                               if (this.val[i] != other.val[i])
-                                       return false;
-                       }
-                       return true;
-               }
-
-               public override bool Equals (object obj)
-               {
-                       if (obj == null)
-                               return false;
-                       if (!(obj is CngProperty))
-                               return false;
-                       return Equals ((CngProperty) obj);
-               }
-
-               public override int GetHashCode ()
-               {
-                       int ret = name.GetHashCode () ^ opts.GetHashCode ();
-                       if (val == null)
-                               return ret;
-
-                       for (int i=0; i<val.Length; i++) {
-                               // Handle each 4 bytes of byte array as a little-endian
-                               // integer and XOR it with the resulting hash code value
-                               ret ^= val[i] << 8*(i % 4);
-                       }
-                       return ret;
-               }
-
-               // static
-
-               public static bool operator == (CngProperty left, CngProperty right)
-               {
-                       return left.Equals (right);
-               }
-
-               public static bool operator != (CngProperty left, CngProperty right)
-               {
-                       return !left.Equals (right);
-               }
-       }
-}
diff --git a/mcs/class/System.Core/System.Security.Cryptography/CngPropertyCollection.cs b/mcs/class/System.Core/System.Security.Cryptography/CngPropertyCollection.cs
deleted file mode 100644 (file)
index afc5269..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-//
-// System.Security.Cryptography.CngPropertyCollection
-//
-// Copyright (C) 2011 Juho Vähä-Herttua
-//
-// 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.Collections.ObjectModel;
-
-namespace System.Security.Cryptography {
-
-       // note: CNG stands for "Cryptography API: Next Generation"
-
-       public sealed class CngPropertyCollection : Collection<CngProperty> {
-               public CngPropertyCollection ()
-               {
-               }
-       }
-}
diff --git a/mcs/class/System.Core/System.Security.Cryptography/CngPropertyOptions.cs b/mcs/class/System.Core/System.Security.Cryptography/CngPropertyOptions.cs
deleted file mode 100644 (file)
index 336d26a..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-//
-// System.Security.Cryptography.CngPropertyOptions
-//
-// Copyright (C) 2011 Juho Vähä-Herttua
-//
-// 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;
-
-namespace System.Security.Cryptography {
-
-       // note: CNG stands for "Cryptography API: Next Generation"
-
-       [Flags]
-       public enum CngPropertyOptions {
-               None           = 0x00 << 24,
-               CustomProperty = 0x40 << 24,
-               Persist        = 0x80 << 24
-       }
-}
diff --git a/mcs/class/System.Core/System.Security.Cryptography/CngProvider.cs b/mcs/class/System.Core/System.Security.Cryptography/CngProvider.cs
deleted file mode 100644 (file)
index 8c868a7..0000000
+++ /dev/null
@@ -1,112 +0,0 @@
-//
-// System.Security.Cryptography.CngProvider
-//
-// Authors:
-//      Sebastien Pouliot  <sebastien@ximian.com>
-//
-// Copyright (C) 2008 Novell, Inc (http://www.novell.com)
-// Copyright (C) 2011 Juho Vähä-Herttua
-//
-// 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;
-
-namespace System.Security.Cryptography {
-
-       // note: CNG stands for "Cryptography API: Next Generation"
-
-       [Serializable]
-       public sealed class CngProvider : IEquatable<CngProvider> {
-
-               private string m_Provider;
-
-               public CngProvider (string provider)
-               {
-                       if (provider == null)
-                               throw new ArgumentNullException ("provider");
-                       if (provider.Length == 0)
-                               throw new ArgumentException ("provider");
-
-                       m_Provider = provider;
-               }
-
-               public string Provider {
-                       get { return m_Provider; }
-               }
-
-               public bool Equals (CngProvider other)
-               {
-                       if (other == null)
-                               return false;
-                       return m_Provider == other.m_Provider;
-               }
-
-               public override bool Equals (object obj)
-               {
-                       return Equals (obj as CngProvider);
-               }
-
-               public override int GetHashCode ()
-               {
-                       return m_Provider.GetHashCode ();
-               }
-
-               public override string ToString ()
-               {
-                       return m_Provider;
-               }
-
-               // static
-
-               private static CngProvider microsoftSmartCardKeyStorageProvider;
-               private static CngProvider microsoftSoftwareKeyStorageProvider;
-
-               public static CngProvider MicrosoftSmartCardKeyStorageProvider {
-                       get {
-                               if (microsoftSmartCardKeyStorageProvider == null)
-                                       microsoftSmartCardKeyStorageProvider = new CngProvider ("Microsoft Smart Card Key Storage Provider");
-                               return microsoftSmartCardKeyStorageProvider;
-                       }
-               }
-
-               public static CngProvider MicrosoftSoftwareKeyStorageProvider {
-                       get {
-                               if (microsoftSoftwareKeyStorageProvider == null)
-                                       microsoftSoftwareKeyStorageProvider = new CngProvider ("Microsoft Software Key Storage Provider");
-                               return microsoftSoftwareKeyStorageProvider;
-                       }
-               }
-
-               public static bool operator == (CngProvider left, CngProvider right)
-               {
-                       if ((object)left == null)
-                               return ((object)right == null);
-                       return left.Equals (right);
-               }
-
-               public static bool operator != (CngProvider left, CngProvider right)
-               {
-                       if ((object)left == null)
-                               return ((object)right != null);
-                       return !left.Equals (right);
-               }
-       }
-}
diff --git a/mcs/class/System.Core/System.Security.Cryptography/CngUIPolicy.cs b/mcs/class/System.Core/System.Security.Cryptography/CngUIPolicy.cs
deleted file mode 100644 (file)
index 4e0c36c..0000000
+++ /dev/null
@@ -1,98 +0,0 @@
-//
-// System.Security.Cryptography.CngUIPolicy
-//
-// Copyright (C) 2011 Juho Vähä-Herttua
-//
-// 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;
-
-namespace System.Security.Cryptography {
-
-       // note: CNG stands for "Cryptography API: Next Generation"
-
-       public sealed class CngUIPolicy {
-               private CngUIProtectionLevels level;
-               private string name;
-               private string desc;
-               private string context;
-               private string title;
-
-               public CngUIPolicy (CngUIProtectionLevels protectionLevel)
-                       : this (protectionLevel, null)
-               {
-               }
-
-               public CngUIPolicy (CngUIProtectionLevels protectionLevel,
-                                   string friendlyName)
-                       : this (protectionLevel, friendlyName, null)
-               {
-               }
-
-               public CngUIPolicy (CngUIProtectionLevels protectionLevel,
-                                   string friendlyName,
-                                   string description)
-                       : this (protectionLevel, friendlyName, description, null)
-               {
-               }
-
-               public CngUIPolicy (CngUIProtectionLevels protectionLevel,
-                                   string friendlyName,
-                                   string description,
-                                   string useContext)
-                       : this (protectionLevel, friendlyName, description, useContext, null)
-               {
-               }
-
-               public CngUIPolicy (CngUIProtectionLevels protectionLevel,
-                                   string friendlyName,
-                                   string description,
-                                   string useContext,
-                                   string creationTitle)
-               {
-                       level = protectionLevel;
-                       name = friendlyName;
-                       desc = description;
-                       context = useContext;
-                       title = creationTitle;
-               }
-
-               public CngUIProtectionLevels ProtectionLevel {
-                       get { return level; }
-               }
-
-               public string FriendlyName {
-                       get { return name; }
-               }
-
-               public string Description {
-                       get { return desc; }
-               }
-
-               public string UseContext {
-                       get { return context; }
-               }
-
-               public string CreationTitle {
-                       get { return title; }
-               }
-       }
-}
diff --git a/mcs/class/System.Core/System.Security.Cryptography/CngUIProtectionLevels.cs b/mcs/class/System.Core/System.Security.Cryptography/CngUIProtectionLevels.cs
deleted file mode 100644 (file)
index 22f4178..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-//
-// System.Security.Cryptography.CngUIProtectionLevels
-//
-// Copyright (C) 2011 Juho Vähä-Herttua
-//
-// 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;
-
-namespace System.Security.Cryptography {
-
-       // note: CNG stands for "Cryptography API: Next Generation"
-
-       [Flags]
-       public enum CngUIProtectionLevels {
-               None,
-               ProtectKey,
-               ForceHighProtection
-       }
-}
diff --git a/mcs/class/System.Core/System.Security.Cryptography/ECDiffieHellmanKeyDerivationFunction.cs b/mcs/class/System.Core/System.Security.Cryptography/ECDiffieHellmanKeyDerivationFunction.cs
deleted file mode 100644 (file)
index a2a9880..0000000
+++ /dev/null
@@ -1,35 +0,0 @@
-//
-// System.Security.Cryptography.ECDiffieHellmanKeyDerivationFunction
-//
-// Copyright (C) 2011 Juho Vähä-Herttua
-//
-// 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;
-
-namespace System.Security.Cryptography {
-
-       public enum ECDiffieHellmanKeyDerivationFunction {
-               Hash,
-               Hmac,
-               Tls
-       }
-}
diff --git a/mcs/class/System.Core/System.Security.Cryptography/ECKeyXmlFormat.cs b/mcs/class/System.Core/System.Security.Cryptography/ECKeyXmlFormat.cs
deleted file mode 100644 (file)
index 3ed2910..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-//
-// System.Security.Cryptography.ECKeyXmlFormat
-//
-// Copyright (C) 2011 Juho Vähä-Herttua
-//
-// 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;
-
-namespace System.Security.Cryptography {
-
-       public enum ECKeyXmlFormat {
-               Rfc4050
-       }
-}
index 415f5832e863fbb51dd0606f4129b71a03c3f3ef..f7248acb6bcc5dd554bf5b75c6c64609d52a1261 100644 (file)
@@ -930,7 +930,11 @@ namespace System.Data.SqlClient
 
                                if (Client.Available <= 0)
                                        return -1; // Error
-                               IPEndPoint endpoint = new IPEndPoint (Dns.GetHostEntry ("localhost").AddressList [0], 0);
+
+                               IPEndPoint endpoint = CreateLocalEndpoint ();
+                               if (endpoint == null)
+                                       return -1;
+
                                Byte [] rawrs;
 
                                rawrs = Receive (ref endpoint);
@@ -955,6 +959,16 @@ namespace System.Data.SqlClient
 
                                return SqlServerTcpPort;
                        }
+
+                       IPEndPoint CreateLocalEndpoint ()
+                       {
+                               foreach (var addr in Dns.GetHostEntry ("localhost").AddressList) {
+                                       if (addr.AddressFamily == Client.AddressFamily)
+                                               return new IPEndPoint (addr, 0);
+                               }
+
+                               return null;
+                       }
                }
 
                struct ColumnInfo
index ee2dbe74b67855bf0c9bf4a7210aea2df3b02c46..e90cc29f822a82c5b405de37c856f78a33a1850b 100644 (file)
@@ -147,7 +147,7 @@ namespace System.Net.Http.Headers
                        if (t != Token.Type.Token)
                                return false;
 
-                       int nvalue;
+                       long nvalue;
                        if (!lexer.IsStarStringValue (t)) {
                                if (!lexer.TryGetNumericValue (t, out nvalue)) {
                                        var s = lexer.GetStringValue (t);
@@ -158,12 +158,12 @@ namespace System.Net.Http.Headers
                                        if (sep.Length != 2)
                                                return false;
 
-                                       if (!int.TryParse (sep[0], NumberStyles.None, CultureInfo.InvariantCulture, out nvalue))
+                                       if (!long.TryParse (sep[0], NumberStyles.None, CultureInfo.InvariantCulture, out nvalue))
                                                return false;
 
                                        value.From = nvalue;
 
-                                       if (!int.TryParse (sep[1], NumberStyles.None, CultureInfo.InvariantCulture, out nvalue))
+                                       if (!long.TryParse (sep[1], NumberStyles.None, CultureInfo.InvariantCulture, out nvalue))
                                                return false;
 
                                        value.To = nvalue;
index 78f2fafcc83284e5e87abfbcbfb13e4935abbd1a..a3335ea5506ffe67aafedba5773301d48b9cee77 100644 (file)
@@ -380,7 +380,9 @@ namespace System.Net.Http
                                }
                        } catch (WebException we) {
                                if (we.Status != WebExceptionStatus.RequestCanceled)
-                                       throw;
+                                       throw new HttpRequestException ("An error occurred while sending the request", we);
+                       } catch (System.IO.IOException ex) {
+                               throw new HttpRequestException ("An error occurred while sending the request", ex);
                        }
 
                        if (cancellationToken.IsCancellationRequested) {
index 62b740c33cd5b9ba2ee05a5ab7741938037be95a..7522def2d7b2999527d732a93cc3006bac2b0d24 100644 (file)
@@ -101,6 +101,12 @@ namespace MonoTests.System.Net.Http.Headers
                        Assert.IsNull (res.To, "#22");
                        Assert.IsNull (res.Length, "#23");
                        Assert.AreEqual ("by */*", res.ToString (), "#24");
+
+                       res = ContentRangeHeaderValue.Parse("bytes  199999999999999999 - 999999999999999999/ 9223372036854775807");
+                       Assert.AreEqual (199999999999999999, res.From, "#31");
+                       Assert.AreEqual (999999999999999999, res.To, "#32");
+                       Assert.AreEqual (9223372036854775807, res.Length, "#33");
+                       Assert.AreEqual ("bytes 199999999999999999-999999999999999999/9223372036854775807", res.ToString (), "#34");
                }
 
                [Test]
index f25171f793f2c5b909b603bc30be8f6d48af81a5..909ae4f9cf04cc9c2cd483dfbe4d5e906e94e0bc 100644 (file)
@@ -48,7 +48,7 @@ namespace MonoTests.System.ServiceModel.Web
        public class WebOperationContextTest
        {
 // MonoTouch does not support dynamic proxy code generation.
-#if !MONOTOUCH
+#if !MONOTOUCH && !MOBILE_STATIC
                [Test]
 #endif
                public void Current ()
index 641a95852ee198c0bfd2d652495f9de556f8c91a..f7d30c63c3466ab403f9033814f6cfcc12eaa892 100644 (file)
@@ -105,23 +105,53 @@ namespace MonoTests.System.ServiceModel.Dispatcher
                                        Assert.AreEqual (5, p.ErrorCode, "#2");
                                        Assert.AreEqual ("foobarerror", p.Text, "#3");
                                }
+                       } finally {
+                               host.Close ();
+                       }
+               }
+
+               [Test]
+               public void FaultContractInfos_2 ()
+               {
+                       var host = new ServiceHost (typeof (TestFaultContract));
+                       int port = NetworkHelpers.FindFreePort ();
+                       host.Description.Behaviors.Find<ServiceDebugBehavior> ().IncludeExceptionDetailInFaults = false;
+                       host.AddServiceEndpoint (typeof (ITestFaultContract), new BasicHttpBinding (), new Uri ("http://localhost:" + port));
+                       host.Open ();
+                       try {
+                               var cf = new ChannelFactory<ITestFaultContract> (new BasicHttpBinding (), new EndpointAddress ("http://localhost:" + port));
+                               var cli = cf.CreateChannel ();
 
                                try {
                                        cli.Run ("deriveddata");
                                        Assert.Fail ("#4");
-                               } catch (Exception ex) {
+                               } catch (FaultException ex) {
                                        // The type must be explicitly listed in the [FaultContract],
                                        // it is not allowed to use a subclass of the exception data type.
-                                       Assert.AreEqual (typeof (FaultException), ex.GetType (), "#5");
                                }
+                       } finally {
+                               host.Close ();
+                       }
+               }
 
+               [Test]
+               public void FaultContractInfos_3 ()
+               {
+                       var host = new ServiceHost (typeof (TestFaultContract));
+                       int port = NetworkHelpers.FindFreePort ();
+                       host.Description.Behaviors.Find<ServiceDebugBehavior> ().IncludeExceptionDetailInFaults = false;
+                       host.AddServiceEndpoint (typeof (ITestFaultContract), new BasicHttpBinding (), new Uri ("http://localhost:" + port));
+                       host.Open ();
+                       try {
+                               var cf = new ChannelFactory<ITestFaultContract> (new BasicHttpBinding (), new EndpointAddress ("http://localhost:" + port));
+                               var cli = cf.CreateChannel ();
+                               
                                try {
                                        cli.Run ("derivedexception");
                                        Assert.Fail ("#6");
-                               } catch (Exception ex) {
+                               } catch (FaultException<PrivateAffairError> ex) {
                                        // However, it is allowed to derive from FaultException<T>, provided
                                        // that T is explicitly listed in [FaultContract].  Bug #7177.
-                                       Assert.AreEqual (typeof (FaultException<PrivateAffairError>), ex.GetType (), "#7");
                                }
                        } finally {
                                host.Close ();
index 09a2639d7355a6ccf51210dff4d46f49aac5124d..46f3627f416fa5f5342ba4ef05c35b8a56e65ba1 100644 (file)
@@ -2,7 +2,7 @@ Assembly/AssemblyInfo.cs
 ../../build/common/Consts.cs
 ../../build/common/Locale.cs
 ../../build/common/MonoTODOAttribute.cs
-../System/System/MonoExeLocator.cs
+../System/System/MonoToolsLocator.cs
 ../System.Windows.Forms/System.Resources/AssemblyNamesTypeResolutionService.cs
 ../System.Windows.Forms/System.Resources/ByteArrayFromResXHandler.cs
 ../System.Windows.Forms/System.Resources/ResXNullRef.cs
old mode 100644 (file)
new mode 100755 (executable)
index 0e1bb04..5e07845
@@ -57,7 +57,7 @@ namespace MonoTests.System.Web.UI.WebControls.Adapters
                        sw = new StringWriter();
                        w = new HtmlTextWriter(sw);
                        a.Render (w);
-                       Assert.AreEqual ("RenderBeginTag\nRenderContents\nRenderEndTag\n", sw.ToString(), "Render #1");
+                       Assert.AreEqual ("RenderBeginTag\nRenderContents\nRenderEndTag\n", sw.ToString().Replace ("\r", ""), "Render #1");
                        
                        
                        sw = new StringWriter();
old mode 100644 (file)
new mode 100755 (executable)
index fe1cb73..a40764b
@@ -91,21 +91,21 @@ namespace MonoTests.System.Web.UI.WebControls.Adapters
                public void RenderBeginTag ()
                {
                        a.RenderBeginTag (w);
-                       Assert.AreEqual ("RenderBeginTag\n", sw.ToString (), "RenderBeginTag #1");
+                       Assert.AreEqual ("RenderBeginTag\n", sw.ToString ().Replace ("\r", ""), "RenderBeginTag #1");
                }
 
                [Test]
                public void RenderContentsTag ()
                {
                        a.RenderContents (w);
-                       Assert.AreEqual ("RenderContents\n", sw.ToString (), "RenderContents #1");
+                       Assert.AreEqual ("RenderContents\n", sw.ToString ().Replace ("\r", ""), "RenderContents #1");
                }
 
                [Test]
                public void RenderEndTag ()
                {
                        a.RenderEndTag (w);
-                       Assert.AreEqual ("RenderEndTag\n", sw.ToString (), "RenderEndTag #1");
+                       Assert.AreEqual ("RenderEndTag\n", sw.ToString ().Replace ("\r", ""), "RenderEndTag #1");
                }
 
                [Test]
old mode 100644 (file)
new mode 100755 (executable)
index 12b2d0f..85f5040
@@ -63,28 +63,28 @@ namespace MonoTests.System.Web.UI.WebControls.Adapters
                public void RenderBeginTag ()
                {
                        a.RenderBeginTag (w);
-                       Assert.AreEqual ("RenderBeginTag\n", sw.ToString (), "RenderBeginTag #1");
+                       Assert.AreEqual ("RenderBeginTag\n", sw.ToString ().Replace ("\r", ""), "RenderBeginTag #1");
                }
 
                [Test]
                public void RenderContentsTag ()
                {
                        a.RenderContents (w);
-                       Assert.AreEqual ("RenderContents\n", sw.ToString (), "RenderContents #1");
+                       Assert.AreEqual ("RenderContents\n", sw.ToString ().Replace ("\r", ""), "RenderContents #1");
                }
 
                [Test]
                public void RenderEndTag ()
                {
                        a.RenderEndTag (w);
-                       Assert.AreEqual ("RenderEndTag\n", sw.ToString (), "RenderEndTag #1");
+                       Assert.AreEqual ("RenderEndTag\n", sw.ToString ().Replace ("\r", ""), "RenderEndTag #1");
                }
 
                [Test]
                public void Render ()
                {
                        a.Render (w);
-                       Assert.AreEqual ("RenderBeginTag\nRenderContents\nRenderEndTag\n", sw.ToString (), "Render #1");
+                       Assert.AreEqual ("RenderBeginTag\nRenderContents\nRenderEndTag\n", sw.ToString ().Replace ("\r", ""), "Render #1");
                }
                
                [Test]
old mode 100644 (file)
new mode 100755 (executable)
index f81a3a8..df2d711
@@ -1538,7 +1538,7 @@ namespace MonoTests.System.Web.UI.WebControls
                        Console.WriteLine ("----------------------------");
                        Console.WriteLine (renderedHtml);
                        
-                       Assert.AreEqual (origHtml, renderedHtml, "#A1");
+                       Assert.AreEqual (origHtml.Replace ("\r", ""), renderedHtml.Replace ("\r", ""), "#A1");
                }
 
                [Test]
@@ -1566,13 +1566,13 @@ namespace MonoTests.System.Web.UI.WebControls
                        string origHtml = "Header<table cellspacing=\"5\" cellpadding=\"5\">\r\n\t<tr>\r\n\t\t<td align=\"right\"><input type=\"submit\" name=\"MyWizard$StepNavigationTemplateContainerID$StepPreviousButton\" value=\"Previous\" id=\"MyWizard_StepNavigationTemplateContainerID_StepPreviousButton\" /></td><td align=\"right\"><input type=\"submit\" name=\"MyWizard$StepNavigationTemplateContainerID$StepNextButton\" value=\"Next\" id=\"MyWizard_StepNavigationTemplateContainerID_StepNextButton\" /></td>\n\t</tr>\n</table>Step";
                        string renderedHtml = HtmlDiff.GetControlFromPageHtml (result);
 
-                       Assert.AreEqual (origHtml, renderedHtml, "#A1");
+                       Assert.AreEqual (origHtml.Replace ("\r", ""), renderedHtml.Replace ("\r", ""), "#A1");
 
                        t.UserData = "RenderHeader_InSpan";
                        result = t.Run ();
                        origHtml = "Header<table cellspacing=\"5\" cellpadding=\"5\">\r\n\t<tr>\r\n\t\t<td align=\"right\"><input type=\"submit\" name=\"MyWizard$StepNavigationTemplateContainerID$StepPreviousButton\" value=\"Previous\" id=\"MyWizard_StepNavigationTemplateContainerID_StepPreviousButton\" /></td><td align=\"right\"><input type=\"submit\" name=\"MyWizard$StepNavigationTemplateContainerID$StepNextButton\" value=\"Next\" id=\"MyWizard_StepNavigationTemplateContainerID_StepNextButton\" /></td>\n\t</tr>\n</table>Step";
                        renderedHtml = HtmlDiff.GetControlFromPageHtml (result);
-                       Assert.AreEqual (origHtml, renderedHtml, "#A2");
+                       Assert.AreEqual (origHtml.Replace ("\r", ""), renderedHtml.Replace ("\r", ""), "#A2");
                }
 
                [Test]
index c78f10bd89dde97a7d1d7d0fa0704ab550894125..5774443e80666a890065b83dba4e9165cb0e6b7a 100644 (file)
@@ -2,7 +2,7 @@
 ../../build/common/MonoTODOAttribute.cs
 Assembly/AssemblyInfo.cs
 Assembly/Locale.cs
-../System/System/MonoExeLocator.cs
+../System/System/MonoToolsLocator.cs
 System.Resources/AssemblyNamesTypeResolutionService.cs
 System.Resources/ByteArrayFromResXHandler.cs
 System.Resources/ResXNullRef.cs
index daacffa14e4065fd0e7418b5c6989e6c5460a3d9..c06688dc86eee8fdd083e5f42ce1c9c06bce3472 100644 (file)
@@ -212,17 +212,7 @@ namespace Mono.Btls
 
                void SetupCertificateStore ()
                {
-#if MONODROID
-                       ctx.CertificateStore.SetDefaultPaths ();
-                       ctx.CertificateStore.AddAndroidLookup ();
-#else
-                       var userPath = MonoBtlsX509StoreManager.GetStorePath (MonoBtlsX509StoreType.UserTrustedRoots);
-                       if (Directory.Exists (userPath))
-                               ctx.CertificateStore.AddDirectoryLookup (userPath, MonoBtlsX509FileType.PEM);
-                       var machinePath = MonoBtlsX509StoreManager.GetStorePath (MonoBtlsX509StoreType.MachineTrustedRoots);
-                       if (Directory.Exists (machinePath))
-                               ctx.CertificateStore.AddDirectoryLookup (machinePath, MonoBtlsX509FileType.PEM);
-#endif
+                       MonoBtlsProvider.SetupCertificateStore (ctx.CertificateStore);
 
                        if (Settings != null && Settings.TrustAnchors != null) {
                                var trust = IsServer ? MonoBtlsX509TrustKind.TRUST_CLIENT : MonoBtlsX509TrustKind.TRUST_SERVER;
index e3e3defe7ff3f2a41da4d6896ac4368114b67564..81280b54ece80f8580681a88adee175a04727daa 100644 (file)
@@ -86,6 +86,12 @@ namespace Mono.Btls
                        return buffer;
                }
 
+               public bool IsRsa {
+                       get {
+                               return mono_btls_key_is_rsa (Handle.DangerousGetHandle ()) != 0;
+                       }
+               }
+
                public MonoBtlsKey Copy ()
                {
                        CheckThrow ();
index 93ea13747aa3fa017e5d657eac5c8d65d133c7f2..a7d42a190b441406430c5635015b200217dd2c35 100644 (file)
@@ -113,7 +113,8 @@ namespace Mono.Btls
                        var passptr = IntPtr.Zero;
                        fixed (void* ptr = buffer)
                        try {
-                               passptr = Marshal.StringToHGlobalAnsi (password ?? string.Empty);
+                               if (password != null)
+                                       passptr = Marshal.StringToHGlobalAnsi (password);
                                var ret = mono_btls_pkcs12_import (
                                        Handle.DangerousGetHandle (), ptr,
                                        buffer.Length, passptr);
index fd3f2bee79203c7fe68c0a3539c3e1eea3d5fbed..147f53e1a41d802cb43e291b530efec210506070 100644 (file)
@@ -32,7 +32,6 @@ using System;
 using System.IO;
 using System.Threading;
 using System.Threading.Tasks;
-using System.Runtime.CompilerServices;
 using System.Security.Cryptography.X509Certificates;
 using System.Security.Authentication;
 
@@ -59,12 +58,9 @@ namespace Mono.Btls
                        get { return "btls"; }
                }
 
-               [MethodImpl (MethodImplOptions.InternalCall)]
-               public extern static bool IsSupported ();
-
                internal MonoBtlsProvider ()
                {
-                       if (!IsSupported ())
+                       if (!MNS.MonoTlsProviderFactory.IsBtlsSupported ())
                                throw new NotSupportedException ("BTLS is not supported in this runtime.");
                }
 
@@ -99,7 +95,7 @@ namespace Mono.Btls
                internal override X509Certificate2Impl GetNativeCertificate (
                        byte[] data, string password, X509KeyStorageFlags flags)
                {
-                       var impl = new X509CertificateImplBtls (true);
+                       var impl = new X509CertificateImplBtls (false);
                        impl.Import (data, password, flags);
                        return impl;
                }
@@ -154,8 +150,7 @@ namespace Mono.Btls
                        using (var nativeChain = MonoBtlsProvider.GetNativeChain (certificates))
                        using (var param = GetVerifyParam (targetHost, serverMode))
                        using (var storeCtx = new MonoBtlsX509StoreCtx ()) {
-                               store.LoadLocations (null, GetSystemStoreLocation ());
-                               store.SetDefaultPaths ();
+                               SetupCertificateStore (store);
 
                                storeCtx.Initialize (store, nativeChain);
 
@@ -177,6 +172,23 @@ namespace Mono.Btls
                        }
                }
 
+               internal static bool ValidateCertificate (MonoBtlsX509Chain chain, MonoBtlsX509VerifyParam param)
+               {
+                       using (var store = new MonoBtlsX509Store ())
+                       using (var storeCtx = new MonoBtlsX509StoreCtx ()) {
+                               SetupCertificateStore (store);
+
+                               storeCtx.Initialize (store, chain);
+
+                               if (param != null)
+                                       storeCtx.SetVerifyParam (param);
+
+                               var ret = storeCtx.Verify ();
+
+                               return ret == 1;
+                       }
+               }
+
                void CheckValidationResult (
                        ICertificateValidator validator, string targetHost, bool serverMode,
                        X509CertificateCollection certificates, bool wantsChain,
@@ -189,6 +201,21 @@ namespace Mono.Btls
                        }
                }
 
+               internal static void SetupCertificateStore (MonoBtlsX509Store store)
+               {
+#if MONODROID
+                       store.SetDefaultPaths ();
+                       store.AddAndroidLookup ();
+#else
+                       var userPath = MonoBtlsX509StoreManager.GetStorePath (MonoBtlsX509StoreType.UserTrustedRoots);
+                       if (Directory.Exists (userPath))
+                               store.AddDirectoryLookup (userPath, MonoBtlsX509FileType.PEM);
+                       var machinePath = MonoBtlsX509StoreManager.GetStorePath (MonoBtlsX509StoreType.MachineTrustedRoots);
+                       if (Directory.Exists (machinePath))
+                               store.AddDirectoryLookup (machinePath, MonoBtlsX509FileType.PEM);
+#endif
+               }
+
                public static string GetSystemStoreLocation ()
                {
 #if ANDROID
index c3dae84fd6f013ba85d6ac55088186d12d9d40cc..63dba5d698778162568e0b5695a18151fa7a9765 100644 (file)
@@ -55,7 +55,8 @@ namespace Mono.Btls
                                if (Compare (oidValue, emailOid))
                                        type = MonoBtlsX509NameEntryType.Email;
                        }
-                       var text = name.GetEntryValue (index);
+                       int tag;
+                       var text = name.GetEntryValue (index, out tag);
                        if (text == null)
                                return false;
                        var oid = name.GetEntryOid (index);
@@ -121,7 +122,7 @@ namespace Mono.Btls
 
                        // 16bits or 8bits string ? TODO not complete (+special chars!)
                        char[] specials = { ',', '+', '"', '\\', '<', '>', ';' };
-                       if (quotes) {
+                       if (quotes && tag != 0x1E) {
                                if ((text.IndexOfAny (specials, 0, text.Length) > 0) ||
                                    text.StartsWith (" ") || (text.EndsWith (" ")))
                                        text = "\"" + text + "\"";
index 4d451b9b073f6dd2f6a1a506e530c5add24cffa5..31ec45810529027bb14b9d15920eaf0e2e98efee 100644 (file)
@@ -267,13 +267,13 @@ namespace Mono.Btls
                public DateTime GetNotBefore ()
                {
                        var ticks = mono_btls_x509_get_not_before (Handle.DangerousGetHandle ());
-                       return new DateTime (1970, 1, 1).AddSeconds (ticks);
+                       return new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds (ticks);
                }
 
                public DateTime GetNotAfter ()
                {
                        var ticks = mono_btls_x509_get_not_after (Handle.DangerousGetHandle ());
-                       return new DateTime (1970, 1, 1).AddSeconds (ticks);
+                       return new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds (ticks);
                }
 
                public byte[] GetPublicKeyData ()
index 7b4ab7d8c9a6523d20891d42ed39462b12921dd9..9d1868337d6f8bb114463d233e6113d02dd83d6c 100644 (file)
@@ -160,13 +160,13 @@ namespace Mono.Btls
                public DateTime GetLastUpdate ()
                {
                        var ticks = mono_btls_x509_crl_get_last_update (Handle.DangerousGetHandle ());
-                       return new DateTime (1970, 1, 1).AddSeconds (ticks);
+                       return new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds (ticks);
                }
 
                public DateTime GetNextUpdate ()
                {
                        var ticks = mono_btls_x509_crl_get_next_update (Handle.DangerousGetHandle ());
-                       return new DateTime (1970, 1, 1).AddSeconds (ticks);
+                       return new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds (ticks);
                }
 
                public long GetVersion ()
index 9b3b7230340bc36c26cc02f56d134dcccf00f623..80a322caaf3f6882df62c1005af52248341afcd6 100644 (file)
@@ -80,7 +80,7 @@ namespace Mono.Btls
                extern static int mono_btls_x509_name_get_entry_oid_data (IntPtr name, int index, out IntPtr data);
 
                [MethodImpl (MethodImplOptions.InternalCall)]
-               extern static int mono_btls_x509_name_get_entry_value (IntPtr name, int index, out IntPtr str);
+               extern static int mono_btls_x509_name_get_entry_value (IntPtr name, int index, out int tag, out IntPtr str);
 
                [MethodImpl (MethodImplOptions.InternalCall)]
                extern unsafe static IntPtr mono_btls_x509_name_from_data (void* data, int len, int use_canon_enc);
@@ -185,13 +185,13 @@ namespace Mono.Btls
                        return bytes;
                }
 
-               public unsafe string GetEntryValue (int index)
+               public unsafe string GetEntryValue (int index, out int tag)
                {
                        if (index >= GetEntryCount ())
                                throw new ArgumentOutOfRangeException ();
                        IntPtr data;
                        var ret = mono_btls_x509_name_get_entry_value (
-                               Handle.DangerousGetHandle (), index, out data);
+                               Handle.DangerousGetHandle (), index, out tag, out data);
                        if (ret <= 0)
                                return null;
                        try {
index 00aafa209fb01de3d4685156e440f16b8afbc087..4f5d79b67b41278c6a7c3d0281bcf95847fc93b9 100644 (file)
@@ -103,7 +103,7 @@ namespace Mono.Btls
                {
                        var ticks = mono_btls_x509_revoked_get_revocation_date (
                                Handle.DangerousGetHandle ());
-                       return new DateTime (1970, 1, 1).AddSeconds (ticks);
+                       return new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds (ticks);
                }
 
                public int GetReason ()
index 59c210b253ec45a61d4884949b521119ad0be97b..5c012389fdc4b92ab9f8382cdefc6e425583777f 100644 (file)
@@ -258,7 +258,7 @@ namespace Mono.Btls
                public void SetTime (DateTime time)
                {
                        WantToModify ();
-                       var epoch = new DateTime (1970, 1, 1);
+                       var epoch = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                        var ticks = (long)time.Subtract (epoch).TotalSeconds;
                        var ret = mono_btls_x509_verify_param_set_time (
                                Handle.DangerousGetHandle (), ticks);
index 022eb11f9f288d46c7bb8dfdfc560160ccf80401..ef077b80e9fedeea766e756fb2895e99c4786ff4 100644 (file)
 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 // THE SOFTWARE.
 #if SECURITY_DEP
+#if MONO_SECURITY_ALIAS
+extern alias MonoSecurity;
+#endif
+
+#if MONO_SECURITY_ALIAS
+using MX = MonoSecurity::Mono.Security.X509;
+#else
+using MX = Mono.Security.X509;
+#endif
+
 using System;
 using System.Text;
+using System.Collections;
 using System.Security;
 using System.Security.Cryptography;
 using System.Security.Cryptography.X509Certificates;
-using MX = Mono.Security.X509;
+using Mono.Security.Cryptography;
 
 namespace Mono.Btls
 {
@@ -115,12 +126,12 @@ namespace Mono.Btls
                        return true;
                }
 
-               protected override byte [] GetCertHash (bool lazy)
+               protected override byte[] GetCertHash (bool lazy)
                {
                        return X509.GetCertHash ();
                }
 
-               public override byte [] GetRawCertData ()
+               public override byte[] GetRawCertData ()
                {
                        return X509.GetRawData (MonoBtlsX509Format.DER);
                }
@@ -169,7 +180,7 @@ namespace Mono.Btls
                        return PublicKey.EncodedParameters.RawData;
                }
 
-               public override byte [] Export (X509ContentType contentType, byte [] password)
+               public override byte[] Export (X509ContentType contentType, byte[] password)
                {
                        ThrowIfContextInvalid ();
 
@@ -232,10 +243,10 @@ namespace Mono.Btls
                                throw new InvalidOperationException ();
                        if (fallback != null)
                                return;
-                       fallback = X509Helper2.Import (GetRawCertData (), null, X509KeyStorageFlags.DefaultKeySet);
+                       fallback = X509Helper2.Import (GetRawCertData (), null, X509KeyStorageFlags.DefaultKeySet, true);
                }
 
-               internal X509Certificate2Impl FallbackImpl {
+               internal override X509Certificate2Impl FallbackImpl {
                        get {
                                MustFallback ();
                                return fallback;
@@ -259,7 +270,7 @@ namespace Mono.Btls
                }
 
                public override bool HasPrivateKey {
-                       get { return FallbackImpl.HasPrivateKey; }
+                       get { return privateKey != null; }
                }
 
                public override X500DistinguishedName IssuerName {
@@ -278,7 +289,12 @@ namespace Mono.Btls
                }
 
                public override AsymmetricAlgorithm PrivateKey {
-                       get { return FallbackImpl.PrivateKey; }
+                       get {
+                               if (privateKey == null || !privateKey.IsRsa)
+                                       return null;
+                               var bytes = privateKey.GetBytes (true);
+                               return PKCS8.PrivateKeyInfo.DecodeRSA (bytes);
+                       }
                        set { FallbackImpl.PrivateKey = value; }
                }
 
@@ -325,19 +341,62 @@ namespace Mono.Btls
                        return FallbackImpl.GetNameInfo (nameType, forIssuer);
                }
 
-               public override void Import (byte [] data, string password, X509KeyStorageFlags keyStorageFlags)
+               public override void Import (byte[] data, string password, X509KeyStorageFlags keyStorageFlags)
                {
                        if (password == null) {
-                               // Does it look like PEM?
-                               if ((data.Length > 0) && (data [0] != 0x30))
-                                       x509 = MonoBtlsX509.LoadFromData (data, MonoBtlsX509Format.PEM);
-                               else
-                                       x509 = MonoBtlsX509.LoadFromData (data, MonoBtlsX509Format.DER);
-                               return;
+                               try {
+                                       Import (data);
+                               } catch (Exception e) {
+                                       try {
+                                                ImportPkcs12 (data, null);
+                                       } catch {
+                                               string msg = Locale.GetText ("Unable to decode certificate.");
+                                               // inner exception is the original (not second) exception
+                                               throw new CryptographicException (msg, e);
+                                       }
+                               }
+                       } else {
+                               // try PKCS#12
+                               try {
+                                       ImportPkcs12 (data, password);
+                               } catch (Exception e) {
+                                       try {
+                                               // it's possible to supply a (unrequired/unusued) password
+                                               // fix bug #79028
+                                               Import (data);
+                                       } catch {
+                                               string msg = Locale.GetText ("Unable to decode certificate.");
+                                               // inner exception is the original (not second) exception
+                                               throw new CryptographicException (msg, e);
+                                       }
+                               }
                        }
+               }
+
+               void Import (byte[] data)
+               {
+                       // Does it look like PEM?
+                       if ((data.Length > 0) && (data [0] != 0x30))
+                               x509 = MonoBtlsX509.LoadFromData (data, MonoBtlsX509Format.PEM);
+                       else
+                               x509 = MonoBtlsX509.LoadFromData (data, MonoBtlsX509Format.DER);
+               }
 
+               void ImportPkcs12 (byte[] data, string password)
+               {
                        using (var pkcs12 = new MonoBtlsPkcs12 ()) {
-                               pkcs12.Import (data, password);
+                               if (string.IsNullOrEmpty (password)) {
+                                       try {
+                                               // Support both unencrypted PKCS#12..
+                                               pkcs12.Import (data, null);
+                                       } catch {
+                                               // ..and PKCS#12 encrypted with an empty password
+                                               pkcs12.Import (data, string.Empty);
+                                       }
+                               } else {
+                                       pkcs12.Import (data, password);
+                               }
+
                                x509 = pkcs12.GetCertificate (0);
                                if (pkcs12.HasPrivateKey)
                                        privateKey = pkcs12.GetPrivateKey ();
@@ -355,14 +414,60 @@ namespace Mono.Btls
                        }
                }
 
-               public override byte [] Export (X509ContentType contentType, string password)
+               public override byte[] Export (X509ContentType contentType, string password)
                {
-                       return FallbackImpl.Export (contentType, password);
+                       ThrowIfContextInvalid ();
+
+                       switch (contentType) {
+                       case X509ContentType.Cert:
+                               return GetRawCertData ();
+                       case X509ContentType.Pfx: // this includes Pkcs12
+                               return ExportPkcs12 (password);
+                       case X509ContentType.SerializedCert:
+                               // TODO
+                               throw new NotSupportedException ();
+                       default:
+                               string msg = Locale.GetText ("This certificate format '{0}' cannot be exported.", contentType);
+                               throw new CryptographicException (msg);
+                       }
+               }
+
+               byte[] ExportPkcs12 (string password)
+               {
+                       var pfx = new MX.PKCS12 ();
+                       try {
+                               var attrs = new Hashtable ();
+                               var localKeyId = new ArrayList ();
+                               localKeyId.Add (new byte[] { 1, 0, 0, 0 });
+                               attrs.Add (MX.PKCS9.localKeyId, localKeyId);
+                               if (password != null)
+                                       pfx.Password = password;
+                               pfx.AddCertificate (new MX.X509Certificate (GetRawCertData ()), attrs);
+                               if (IntermediateCertificates != null) {
+                                       for (int i = 0; i < IntermediateCertificates.Count; i++)
+                                               pfx.AddCertificate (new MX.X509Certificate (IntermediateCertificates [i].GetRawCertData ()));
+                               }
+                               var privateKey = PrivateKey;
+                               if (privateKey != null)
+                                       pfx.AddPkcs8ShroudedKeyBag (privateKey, attrs);
+                               return pfx.GetBytes ();
+                       } finally {
+                               pfx.Password = null;
+                       }
                }
 
                public override bool Verify (X509Certificate2 thisCertificate)
                {
-                       return FallbackImpl.Verify (thisCertificate);
+                       using (var chain = new MonoBtlsX509Chain ()) {
+                               chain.AddCertificate (x509.Copy ());
+                               if (intermediateCerts != null) {
+                                       for (int i = 0; i < intermediateCerts.Count; i++) {
+                                               var intermediate = (X509CertificateImplBtls)intermediateCerts [i];
+                                               chain.AddCertificate (intermediate.x509.Copy ());
+                                       }
+                               }
+                               return MonoBtlsProvider.ValidateCertificate (chain, null);
+                       }
                }
 
                public override void Reset ()
index 6849b160bf35017241bdf78e4e6290bbf24748a8..db2e81529ba7704cdfee952f59b1284cb07ac1ac 100644 (file)
@@ -18,7 +18,7 @@ namespace Mono.Net.Security
                        case "legacy":
                                return new LegacyTlsProvider ();
                        case "btls":
-                               if (!MonoBtlsProvider.IsSupported ())
+                               if (!IsBtlsSupported ())
                                        throw new NotSupportedException ("BTLS in not supported!");
                                return new MonoBtlsProvider ();
                        default:
index ab6a536f2606730d1dee9361dae3479bf29ae50d..071535a5c44ca31c5d8ac4fdb84d7ffdac657c3c 100644 (file)
@@ -39,6 +39,7 @@ using System.Security.Cryptography.X509Certificates;
 using System;
 using System.Net;
 using System.Collections.Generic;
+using System.Runtime.CompilerServices;
 
 #if !MOBILE
 using System.Reflection;
@@ -107,6 +108,9 @@ namespace Mono.Net.Security
                                initialized = true;
                        }
                }
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               internal extern static bool IsBtlsSupported ();
 #endif
 
                static object locker = new object ();
@@ -157,7 +161,7 @@ namespace Mono.Net.Security
                                providerRegistration = new Dictionary<string,string> ();
                                providerRegistration.Add ("legacy", "Mono.Net.Security.LegacyTlsProvider");
                                providerRegistration.Add ("default", "Mono.Net.Security.LegacyTlsProvider");
-                               if (Mono.Btls.MonoBtlsProvider.IsSupported ())
+                               if (IsBtlsSupported ())
                                        providerRegistration.Add ("btls", "Mono.Btls.MonoBtlsProvider");
                                X509Helper2.Initialize ();
                        }
index 4e76cad89ff9e394858ed1544f99e8158ae78741..4625f2f53c20faf9bd5e30386aed0cbee5d5733f 100644 (file)
@@ -75,7 +75,7 @@ namespace Mono.Net.Security
                }
 
 #if SECURITY_DEP
-               readonly ChainValidationHelper validationHelper;
+//             readonly ChainValidationHelper validationHelper;
                readonly MonoTlsSettings settings;
 
                public MonoTlsStream (HttpWebRequest request, NetworkStream networkStream)
@@ -87,7 +87,7 @@ namespace Mono.Net.Security
                        provider = request.TlsProvider ?? MonoTlsProviderFactory.GetProviderInternal ();
                        status = WebExceptionStatus.SecureChannelFailure;
 
-                       validationHelper = ChainValidationHelper.Create (provider.Provider, ref settings, this);
+                       /*validationHelper =*/ ChainValidationHelper.Create (provider.Provider, ref settings, this);
                }
 
                internal Stream CreateStream (byte[] buffer)
index bbe72eed740eeef74c159f3b95e047f3dc38fa61..8eb5e066d02487b08f300b15d1d6b1a7ccee2ad7 100644 (file)
@@ -1,12 +1,9 @@
 using System.Diagnostics;
 
 namespace System.Net {
-       class Logging {
-               internal static bool On {
-                       get {
-                               return false;
-                       }
-               }
+       static class Logging
+       {
+               internal static readonly bool On = false;
 
                internal static TraceSource Web {
                        get {
@@ -34,6 +31,10 @@ namespace System.Net {
                internal static void Enter(TraceSource traceSource, string msg) {
                }
 
+               [Conditional ("TRACE")]
+               internal static void Enter(TraceSource traceSource, string msg, string parameters) {
+               }
+
                [Conditional ("TRACE")]
                internal static void Exception(TraceSource traceSource, object obj, string method, Exception e) {
                }
@@ -46,6 +47,10 @@ namespace System.Net {
                internal static void Exit(TraceSource traceSource, string msg) {
                }
 
+               [Conditional ("TRACE")]
+               internal static void Exit(TraceSource traceSource, string msg, string parameters) {
+               }
+
                [Conditional ("TRACE")]
                internal static void PrintInfo(TraceSource traceSource, object obj, string method, string msg) {
                }
index afe34459bbb58f8ae30911fd6b10b158757feed1..e7719c1afaadb5c134af12056a6613077c4fd021 100644 (file)
@@ -1,4 +1,5 @@
 using System.Net.Security;
+using System.Net.Sockets;
 
 namespace System.Net.Configuration {
        sealed class SettingsSectionInternal
@@ -16,8 +17,8 @@ namespace System.Net.Configuration {
                internal UnicodeDecodingConformance WebUtilityUnicodeDecodingConformance = UnicodeDecodingConformance.Auto;
 #endif
 
-               internal bool HttpListenerUnescapeRequestUrl = true;
-
+               internal readonly bool HttpListenerUnescapeRequestUrl = true;
+               internal readonly IPProtectionLevel IPProtectionLevel = IPProtectionLevel.Unspecified;
 
                internal bool UseNagleAlgorithm { get; set; }
                internal bool Expect100Continue { get; set; }
@@ -26,5 +27,20 @@ namespace System.Net.Configuration {
                internal bool EnableDnsRoundRobin { get; set; }
                internal bool CheckCertificateRevocationList { get; set; }
                internal EncryptionPolicy EncryptionPolicy { get; private set; }
+
+               internal bool Ipv6Enabled {
+                       get {
+#if CONFIGURATION_DEP && !MOBILE
+                               try {
+                                       var config = (SettingsSection) System.Configuration.ConfigurationManager.GetSection ("system.net/settings");
+                                       if (config != null)
+                                               return config.Ipv6.Enabled;
+                               } catch {
+                               }
+#endif
+
+                               return true;
+                       }
+               }
        }
 }
diff --git a/mcs/class/System/System.Net.Sockets/SendPacketsElement.cs b/mcs/class/System/System.Net.Sockets/SendPacketsElement.cs
deleted file mode 100644 (file)
index 983faa9..0000000
+++ /dev/null
@@ -1,89 +0,0 @@
-// System.Net.Sockets.SocketAsyncEventArgs.cs
-//
-// Authors:
-//     Marek Habersack (mhabersack@novell.com)
-//
-// Copyright (c) 2008 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;
-
-namespace System.Net.Sockets
-{
-       public class SendPacketsElement
-       {
-               public byte[] Buffer { get; private set; }
-               public int Count { get; private set; }
-               public bool EndOfPacket { get; private set; }
-               public string FilePath { get; private set; }
-               public int Offset { get; private set; }
-
-               public SendPacketsElement (byte[] buffer) : this (buffer, 0, buffer != null ? buffer.Length : 0)
-               {
-               }
-
-               public SendPacketsElement (byte[] buffer, int offset, int count) : this (buffer, offset, count, false)
-               {
-               }
-
-               public SendPacketsElement (byte[] buffer, int offset, int count, bool endOfPacket)
-               {
-                       if (buffer == null)
-                               throw new ArgumentNullException ("buffer");
-
-                       int buflen = buffer.Length;
-                       if (offset < 0 || offset >= buflen)
-                               throw new ArgumentOutOfRangeException ("offset");
-
-                       if (count < 0 || offset + count >= buflen)
-                               throw new ArgumentOutOfRangeException ("count");
-
-                       Buffer = buffer;
-                       Offset = offset;
-                       Count = count;
-                       EndOfPacket = endOfPacket;
-                       FilePath = null;
-               }
-               
-               public SendPacketsElement (string filepath) : this (filepath, 0, 0, false)
-               {
-               }
-
-               public SendPacketsElement (string filepath, int offset, int count) : this (filepath, offset, count, false)
-               {
-               }
-
-               // LAME SPEC: only ArgumentNullException for filepath is thrown
-               public SendPacketsElement (string filepath, int offset, int count, bool endOfPacket)
-               {
-                       if (filepath == null)
-                               throw new ArgumentNullException ("filepath");
-
-                       Buffer = null;
-                       Offset = offset;
-                       Count = count;
-                       EndOfPacket = endOfPacket;
-                       FilePath = filepath;
-               }
-       }
-}
index e80e84ac7e840ca81706a7e9e9aa36594c143174..9857fc27ed0b86ef0d14695a00a541a21784f888 100644 (file)
@@ -55,13 +55,6 @@ namespace System.Net.Sockets
                const string TIMEOUT_EXCEPTION_MSG = "A connection attempt failed because the connected party did not properly respond" +
                        "after a period of time, or established connection failed because connected host has failed to respond";
 
-               /*
-                *      These two fields are looked up by name by the runtime, don't change
-                *  their name without also updating the runtime code.
-                */
-               static int ipv4_supported = -1;
-               static int ipv6_supported = -1;
-
                /* true if we called Close_internal */
                bool is_closed;
 
@@ -98,80 +91,8 @@ namespace System.Net.Sockets
                int m_IntCleanedUp;
                internal bool connect_in_progress;
 
-               private static volatile bool s_LoggingEnabled = Logging.On;
-
 #region Constructors
 
-               static Socket ()
-               {
-                       if (ipv4_supported == -1) {
-                               try {
-                                       Socket tmp = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
-                                       tmp.Close();
-
-                                       ipv4_supported = 1;
-                               } catch {
-                                       ipv4_supported = 0;
-                               }
-                       }
-
-                       if (ipv6_supported == -1) {
-                               // We need to put a try/catch around ConfigurationManager methods as will always throw an exception 
-                               // when run in a mono embedded application.  This occurs as embedded applications do not have a setup
-                               // for application config.  The exception is not thrown when called from a normal .NET application. 
-                               //
-                               // We, then, need to guard calls to the ConfigurationManager.  If the config is not found or throws an
-                               // exception, will fall through to the existing Socket / API directly below in the code.
-                               //
-                               // Also note that catching ConfigurationErrorsException specifically would require library dependency
-                               // System.Configuration, and wanted to avoid that.
-#if !MOBILE
-#if CONFIGURATION_DEP
-                               try {
-                                       SettingsSection config;
-                                       config = (SettingsSection) System.Configuration.ConfigurationManager.GetSection ("system.net/settings");
-                                       if (config != null)
-                                               ipv6_supported = config.Ipv6.Enabled ? -1 : 0;
-                               } catch {
-                                       ipv6_supported = -1;
-                               }
-#else
-                               try {
-                                       NetConfig config = System.Configuration.ConfigurationSettings.GetConfig("system.net/settings") as NetConfig;
-                                       if (config != null)
-                                               ipv6_supported = config.ipv6Enabled ? -1 : 0;
-                               } catch {
-                                       ipv6_supported = -1;
-                               }
-#endif
-#endif
-                               if (ipv6_supported != 0) {
-                                       try {
-                                               Socket tmp = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
-                                               tmp.Close();
-
-                                               ipv6_supported = 1;
-                                       } catch {
-                                               ipv6_supported = 0;
-                                       }
-                               }
-                       }
-               }
-
-               public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
-               {
-                       this.addressFamily = addressFamily;
-                       this.socketType = socketType;
-                       this.protocolType = protocolType;
-
-                       int error;
-                       this.m_Handle = new SafeSocketHandle (Socket_internal (addressFamily, socketType, protocolType, out error), true);
-
-                       if (error != 0)
-                               throw new SocketException (error);
-
-                       SocketDefaults ();
-               }
 
                public Socket (SocketInformation socketInformation)
                {
@@ -188,6 +109,8 @@ namespace System.Net.Sockets
                        this.is_bound = (ProtocolType) (int) result [3] != 0;
                        this.m_Handle = new SafeSocketHandle ((IntPtr) (long) result [4], true);
 
+                       InitializeSockets ();
+
                        SocketDefaults ();
                }
 
@@ -200,6 +123,8 @@ namespace System.Net.Sockets
                        
                        this.m_Handle = safe_handle;
                        this.is_connected = true;
+
+                       InitializeSockets ();   
                }
 
                void SocketDefaults ()
@@ -236,54 +161,6 @@ namespace System.Net.Sockets
 
 #region Properties
 
-               [ObsoleteAttribute ("Use OSSupportsIPv4 instead")]
-               public static bool SupportsIPv4 {
-                       get { return ipv4_supported == 1; }
-               }
-
-               [ObsoleteAttribute ("Use OSSupportsIPv6 instead")]
-               public static bool SupportsIPv6 {
-                       get { return ipv6_supported == 1; }
-               }
-
-#if MOBILE
-               public static bool OSSupportsIPv4 {
-                       get { return ipv4_supported == 1; }
-               }
-#else
-               public static bool OSSupportsIPv4 {
-                       get {
-                               NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces ();
-
-                               foreach (NetworkInterface adapter in nics) {
-                                       if (adapter.Supports (NetworkInterfaceComponent.IPv4))
-                                               return true;
-                               }
-
-                               return false;
-                       }
-               }
-#endif
-
-#if MOBILE
-               public static bool OSSupportsIPv6 {
-                       get { return ipv6_supported == 1; }
-               }
-#else
-               public static bool OSSupportsIPv6 {
-                       get {
-                               NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces ();
-
-                               foreach (NetworkInterface adapter in nics) {
-                                       if (adapter.Supports (NetworkInterfaceComponent.IPv6))
-                                               return true;
-                               }
-
-                               return false;
-                       }
-               }
-#endif
-
                public int Available {
                        get {
                                ThrowIfDisposedAndClosed ();
@@ -985,7 +862,7 @@ namespace System.Net.Sockets
                                
                                iep = RemapIPEndPoint (iep);
 
-                               Connect_internal (m_Handle, iep.Serialize (), out error);
+                               Connect_internal (m_Handle, iep.Serialize (), out error, is_blocking);
                                if (error == 0) {
                                        is_connected = true;
                                        is_bound = true;
@@ -1036,7 +913,7 @@ namespace System.Net.Sockets
                        SocketAddress serial = remoteEP.Serialize ();
 
                        int error = 0;
-                       Connect_internal (m_Handle, serial, out error);
+                       Connect_internal (m_Handle, serial, out error, is_blocking);
 
                        if (error == 0 || error == 10035)
                                seed_endpoint = remoteEP; // Keep the ep around for non-blocking sockets
@@ -1178,7 +1055,7 @@ namespace System.Net.Sockets
                        bool blk = is_blocking;
                        if (blk)
                                Blocking = false;
-                       Connect_internal (m_Handle, end_point.Serialize (), out error);
+                       Connect_internal (m_Handle, end_point.Serialize (), out error, false);
                        if (blk)
                                Blocking = true;
 
@@ -1328,11 +1205,11 @@ namespace System.Net.Sockets
                        sockares.CheckIfThrowDelayedException();
                }
 
-               static void Connect_internal (SafeSocketHandle safeHandle, SocketAddress sa, out int error)
+               static void Connect_internal (SafeSocketHandle safeHandle, SocketAddress sa, out int error, bool blocking)
                {
                        try {
                                safeHandle.RegisterForBlockingSyscall ();
-                               Connect_internal (safeHandle.DangerousGetHandle (), sa, out error);
+                               Connect_internal (safeHandle.DangerousGetHandle (), sa, out error, blocking);
                        } finally {
                                safeHandle.UnRegisterForBlockingSyscall ();
                        }
@@ -1340,7 +1217,7 @@ namespace System.Net.Sockets
 
                /* Connects to the remote address */
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
-               extern static void Connect_internal(IntPtr sock, SocketAddress sa, out int error);
+               extern static void Connect_internal(IntPtr sock, SocketAddress sa, out int error, bool blocking);
 
                /* Returns :
                 *  - false when it is ok to use RemoteEndPoint
@@ -1484,7 +1361,7 @@ namespace System.Net.Sockets
                        ThrowIfBufferOutOfRange (buffer, offset, size);
 
                        int nativeError;
-                       int ret = Receive_internal (m_Handle, buffer, offset, size, socketFlags, out nativeError);
+                       int ret = Receive_internal (m_Handle, buffer, offset, size, socketFlags, out nativeError, is_blocking);
 
                        errorCode = (SocketError) nativeError;
                        if (errorCode != SocketError.Success && errorCode != SocketError.WouldBlock && errorCode != SocketError.InProgress) {
@@ -1527,7 +1404,7 @@ namespace System.Net.Sockets
                        }
 
                        try {
-                               ret = Receive_internal (m_Handle, bufarray, socketFlags, out nativeError);
+                               ret = Receive_internal (m_Handle, bufarray, socketFlags, out nativeError, is_blocking);
                        } finally {
                                for (int i = 0; i < numsegments; i++) {
                                        if (gch[i].IsAllocated)
@@ -1616,7 +1493,7 @@ namespace System.Net.Sockets
                        int total = 0;
 
                        try {
-                               total = Receive_internal (sockares.socket.m_Handle, sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, out sockares.error);
+                               total = Receive_internal (sockares.socket.m_Handle, sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, out sockares.error, sockares.socket.is_blocking);
                        } catch (Exception e) {
                                sockares.Complete (e);
                                return;
@@ -1682,31 +1559,31 @@ namespace System.Net.Sockets
                        return sockares.Total;
                }
 
-               static int Receive_internal (SafeSocketHandle safeHandle, WSABUF[] bufarray, SocketFlags flags, out int error)
+               static int Receive_internal (SafeSocketHandle safeHandle, WSABUF[] bufarray, SocketFlags flags, out int error, bool blocking)
                {
                        try {
                                safeHandle.RegisterForBlockingSyscall ();
-                               return Receive_internal (safeHandle.DangerousGetHandle (), bufarray, flags, out error);
+                               return Receive_internal (safeHandle.DangerousGetHandle (), bufarray, flags, out error, blocking);
                        } finally {
                                safeHandle.UnRegisterForBlockingSyscall ();
                        }
                }
 
                [MethodImplAttribute (MethodImplOptions.InternalCall)]
-               extern static int Receive_internal (IntPtr sock, WSABUF[] bufarray, SocketFlags flags, out int error);
+               extern static int Receive_internal (IntPtr sock, WSABUF[] bufarray, SocketFlags flags, out int error, bool blocking);
 
-               static int Receive_internal (SafeSocketHandle safeHandle, byte[] buffer, int offset, int count, SocketFlags flags, out int error)
+               static int Receive_internal (SafeSocketHandle safeHandle, byte[] buffer, int offset, int count, SocketFlags flags, out int error, bool blocking)
                {
                        try {
                                safeHandle.RegisterForBlockingSyscall ();
-                               return Receive_internal (safeHandle.DangerousGetHandle (), buffer, offset, count, flags, out error);
+                               return Receive_internal (safeHandle.DangerousGetHandle (), buffer, offset, count, flags, out error, blocking);
                        } finally {
                                safeHandle.UnRegisterForBlockingSyscall ();
                        }
                }
 
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
-               extern static int Receive_internal(IntPtr sock, byte[] buffer, int offset, int count, SocketFlags flags, out int error);
+               extern static int Receive_internal(IntPtr sock, byte[] buffer, int offset, int count, SocketFlags flags, out int error, bool blocking);
 
 #endregion
 
@@ -1735,7 +1612,7 @@ namespace System.Net.Sockets
                        SocketAddress sockaddr = remoteEP.Serialize();
 
                        int nativeError;
-                       int cnt = ReceiveFrom_internal (m_Handle, buffer, offset, size, socketFlags, ref sockaddr, out nativeError);
+                       int cnt = ReceiveFrom_internal (m_Handle, buffer, offset, size, socketFlags, ref sockaddr, out nativeError, is_blocking);
 
                        errorCode = (SocketError) nativeError;
                        if (errorCode != SocketError.Success) {
@@ -1866,18 +1743,18 @@ namespace System.Net.Sockets
 
 
 
-               static int ReceiveFrom_internal (SafeSocketHandle safeHandle, byte[] buffer, int offset, int count, SocketFlags flags, ref SocketAddress sockaddr, out int error)
+               static int ReceiveFrom_internal (SafeSocketHandle safeHandle, byte[] buffer, int offset, int count, SocketFlags flags, ref SocketAddress sockaddr, out int error, bool blocking)
                {
                        try {
                                safeHandle.RegisterForBlockingSyscall ();
-                               return ReceiveFrom_internal (safeHandle.DangerousGetHandle (), buffer, offset, count, flags, ref sockaddr, out error);
+                               return ReceiveFrom_internal (safeHandle.DangerousGetHandle (), buffer, offset, count, flags, ref sockaddr, out error, blocking);
                        } finally {
                                safeHandle.UnRegisterForBlockingSyscall ();
                        }
                }
 
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
-               extern static int ReceiveFrom_internal(IntPtr sock, byte[] buffer, int offset, int count, SocketFlags flags, ref SocketAddress sockaddr, out int error);
+               extern static int ReceiveFrom_internal(IntPtr sock, byte[] buffer, int offset, int count, SocketFlags flags, ref SocketAddress sockaddr, out int error, bool blocking);
 
 #endregion
 
@@ -1952,7 +1829,7 @@ namespace System.Net.Sockets
                        int sent = 0;
                        do {
                                sent += Send_internal (
-m_Handle, buffer, offset + sent, size - sent, socketFlags, out nativeError);
+m_Handle, buffer, offset + sent, size - sent, socketFlags, out nativeError, is_blocking);
                                errorCode = (SocketError)nativeError;
                                if (errorCode != SocketError.Success && errorCode != SocketError.WouldBlock && errorCode != SocketError.InProgress) {
                                        is_connected = false;
@@ -1995,7 +1872,7 @@ m_Handle, buffer, offset + sent, size - sent, socketFlags, out nativeError);
                        }
 
                        try {
-                               ret = Send_internal (m_Handle, bufarray, socketFlags, out nativeError);
+                               ret = Send_internal (m_Handle, bufarray, socketFlags, out nativeError, is_blocking);
                        } finally {
                                for(int i = 0; i < numsegments; i++) {
                                        if (gch[i].IsAllocated) {
@@ -2084,7 +1961,7 @@ m_Handle, buffer, offset + sent, size - sent, socketFlags, out nativeError);
                        int total = 0;
 
                        try {
-                               total = Socket.Send_internal (sockares.socket.m_Handle, sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, out sockares.error);
+                               total = Socket.Send_internal (sockares.socket.m_Handle, sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, out sockares.error, false);
                        } catch (Exception e) {
                                sockares.Complete (e);
                                return;
@@ -2172,33 +2049,31 @@ m_Handle, buffer, offset + sent, size - sent, socketFlags, out nativeError);
                        return sockares.Total;
                }
 
-               static int Send_internal (SafeSocketHandle safeHandle, WSABUF[] bufarray, SocketFlags flags, out int error)
+               static int Send_internal (SafeSocketHandle safeHandle, WSABUF[] bufarray, SocketFlags flags, out int error, bool blocking)
                {
-                       bool release = false;
                        try {
-                               safeHandle.DangerousAddRef (ref release);
-                               return Send_internal (safeHandle.DangerousGetHandle (), bufarray, flags, out error);
+                               safeHandle.RegisterForBlockingSyscall ();
+                               return Send_internal (safeHandle.DangerousGetHandle (), bufarray, flags, out error, blocking);
                        } finally {
-                               if (release)
-                                       safeHandle.DangerousRelease ();
+                               safeHandle.UnRegisterForBlockingSyscall ();
                        }
                }
 
                [MethodImplAttribute (MethodImplOptions.InternalCall)]
-               extern static int Send_internal (IntPtr sock, WSABUF[] bufarray, SocketFlags flags, out int error);
+               extern static int Send_internal (IntPtr sock, WSABUF[] bufarray, SocketFlags flags, out int error, bool blocking);
 
-               static int Send_internal (SafeSocketHandle safeHandle, byte[] buf, int offset, int count, SocketFlags flags, out int error)
+               static int Send_internal (SafeSocketHandle safeHandle, byte[] buf, int offset, int count, SocketFlags flags, out int error, bool blocking)
                {
                        try {
                                safeHandle.RegisterForBlockingSyscall ();
-                               return Send_internal (safeHandle.DangerousGetHandle (), buf, offset, count, flags, out error);
+                               return Send_internal (safeHandle.DangerousGetHandle (), buf, offset, count, flags, out error, blocking);
                        } finally {
                                safeHandle.UnRegisterForBlockingSyscall ();
                        }
                }
 
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
-               extern static int Send_internal(IntPtr sock, byte[] buf, int offset, int count, SocketFlags flags, out int error);
+               extern static int Send_internal(IntPtr sock, byte[] buf, int offset, int count, SocketFlags flags, out int error, bool blocking);
 
 #endregion
 
@@ -2214,7 +2089,7 @@ m_Handle, buffer, offset + sent, size - sent, socketFlags, out nativeError);
                                throw new ArgumentNullException("remoteEP");
 
                        int error;
-                       int ret = SendTo_internal (m_Handle, buffer, offset, size, socketFlags, remoteEP.Serialize (), out error);
+                       int ret = SendTo_internal (m_Handle, buffer, offset, size, socketFlags, remoteEP.Serialize (), out error, is_blocking);
 
                        SocketError err = (SocketError) error;
                        if (err != 0) {
@@ -2330,18 +2205,18 @@ m_Handle, buffer, offset + sent, size - sent, socketFlags, out nativeError);
                        return sockares.Total;
                }
 
-               static int SendTo_internal (SafeSocketHandle safeHandle, byte[] buffer, int offset, int count, SocketFlags flags, SocketAddress sa, out int error)
+               static int SendTo_internal (SafeSocketHandle safeHandle, byte[] buffer, int offset, int count, SocketFlags flags, SocketAddress sa, out int error, bool blocking)
                {
                        try {
                                safeHandle.RegisterForBlockingSyscall ();
-                               return SendTo_internal (safeHandle.DangerousGetHandle (), buffer, offset, count, flags, sa, out error);
+                               return SendTo_internal (safeHandle.DangerousGetHandle (), buffer, offset, count, flags, sa, out error, blocking);
                        } finally {
                                safeHandle.UnRegisterForBlockingSyscall ();
                        }
                }
 
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
-               extern static int SendTo_internal (IntPtr sock, byte[] buffer, int offset, int count, SocketFlags flags, SocketAddress sa, out int error);
+               extern static int SendTo_internal (IntPtr sock, byte[] buffer, int offset, int count, SocketFlags flags, SocketAddress sa, out int error, bool blocking);
 
 #endregion
 
@@ -2356,8 +2231,9 @@ m_Handle, buffer, offset + sent, size - sent, socketFlags, out nativeError);
                        if (!is_blocking)
                                throw new InvalidOperationException ();
 
-                       if (!SendFile_internal (m_Handle, fileName, preBuffer, postBuffer, flags)) {
-                               SocketException exc = new SocketException ();
+                       int error = 0;
+                       if (!SendFile_internal (m_Handle, fileName, preBuffer, postBuffer, flags, out error, is_blocking) || error != 0) {
+                               SocketException exc = new SocketException (error);
                                if (exc.ErrorCode == 2 || exc.ErrorCode == 3)
                                        throw new FileNotFoundException ();
                                throw exc;
@@ -2392,18 +2268,18 @@ m_Handle, buffer, offset + sent, size - sent, socketFlags, out nativeError);
                        ares.Delegate.EndInvoke (ares.Original);
                }
 
-               static bool SendFile_internal (SafeSocketHandle safeHandle, string filename, byte [] pre_buffer, byte [] post_buffer, TransmitFileOptions flags)
+               static bool SendFile_internal (SafeSocketHandle safeHandle, string filename, byte [] pre_buffer, byte [] post_buffer, TransmitFileOptions flags, out int error, bool blocking)
                {
                        try {
                                safeHandle.RegisterForBlockingSyscall ();
-                               return SendFile_internal (safeHandle.DangerousGetHandle (), filename, pre_buffer, post_buffer, flags);
+                               return SendFile_internal (safeHandle.DangerousGetHandle (), filename, pre_buffer, post_buffer, flags, out error, blocking);
                        } finally {
                                safeHandle.UnRegisterForBlockingSyscall ();
                        }
                }
 
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
-               extern static bool SendFile_internal (IntPtr sock, string filename, byte [] pre_buffer, byte [] post_buffer, TransmitFileOptions flags);
+               extern static bool SendFile_internal (IntPtr sock, string filename, byte [] pre_buffer, byte [] post_buffer, TransmitFileOptions flags, out int error, bool blocking);
 
                delegate void SendFileHandler (string fileName, byte [] preBuffer, byte [] postBuffer, TransmitFileOptions flags);
 
@@ -2919,6 +2795,41 @@ m_Handle, buffer, offset + sent, size - sent, socketFlags, out nativeError);
 
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
                internal static extern bool SupportsPortReuse (ProtocolType proto);
+
+               internal static int FamilyHint {
+                       get {
+                               // Returns one of
+                               //      MONO_HINT_UNSPECIFIED           = 0,
+                               //      MONO_HINT_IPV4                          = 1,
+                               //      MONO_HINT_IPV6                          = 2,
+
+                               int hint = 0;
+                               if (OSSupportsIPv4) {
+                                       hint = 1;
+                               }
+
+                               if (OSSupportsIPv6) {
+                                       hint = hint == 0 ? 2 : 0;
+                               }
+
+                               return hint;
+                       }
+               }
+
+               static bool IsProtocolSupported (NetworkInterfaceComponent networkInterface)
+               {
+#if MOBILE
+                       return true;
+#else
+                       var nics = NetworkInterface.GetAllNetworkInterfaces ();
+                       foreach (var adapter in nics) {
+                               if (adapter.Supports (networkInterface))
+                                       return true;
+                       }
+
+                       return false;
+#endif
+               }
        }
 }
 
index 438d4bc31e9a3dcf97f763d3ba444272030d218d..e057021f9a73ce49e43049df46a8ac68b4cab9f9 100644 (file)
@@ -177,13 +177,6 @@ namespace System.Net.Sockets
 
                        if (disposing && in_progress != 0)
                                return;
-
-                       AcceptSocket = null;
-                       Buffer = null;
-                       BufferList = null;
-                       RemoteEndPoint = null;
-                       UserToken = null;
-                       SendPacketsElements = null;
                }
 
                public void Dispose ()
diff --git a/mcs/class/System/System.Net.Sockets/SocketAsyncOperation.cs b/mcs/class/System/System.Net.Sockets/SocketAsyncOperation.cs
deleted file mode 100644 (file)
index 87d6de5..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-// System.Net.Sockets.SocketAsyncOperation.cs
-//
-// Authors:
-//     Marek Habersack (mhabersack@novell.com)
-//
-// Copyright (c) 2008 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.
-//
-namespace System.Net.Sockets
-{
-       public enum SocketAsyncOperation
-       {
-               None,
-               Accept,
-               Connect,
-               Disconnect,
-               Receive,
-               ReceiveFrom,
-               ReceiveMessageFrom,
-               Send,
-               SendPackets,
-               SendTo
-       }
-}
diff --git a/mcs/class/System/System.Net.Sockets/TcpClient.cs b/mcs/class/System/System.Net.Sockets/TcpClient.cs
deleted file mode 100644 (file)
index bbdb034..0000000
+++ /dev/null
@@ -1,450 +0,0 @@
-// TcpClient.cs
-//
-// Author:
-//     Phillip Pearson (pp@myelin.co.nz)
-//     Gonzalo Paniagua Javier (gonzalo@novell.com)
-//     Sridhar Kulkarni (sridharkulkarni@gmail.com)
-//     Marek Safar (marek.safar@gmail.com)
-//
-// Copyright (C) 2001, Phillip Pearson http://www.myelin.co.nz
-// Copyright (c) 2006 Novell, Inc. (http://www.novell.com)
-// Copyright 2011 Xamarin Inc.
-//
-
-//
-// 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.Net;
-using System.Threading.Tasks;
-
-namespace System.Net.Sockets
-{
-       public class TcpClient : IDisposable {
-               enum Properties : uint {
-                       LingerState = 1,
-                       NoDelay = 2,
-                       ReceiveBufferSize = 4,
-                       ReceiveTimeout = 8,
-                       SendBufferSize = 16,
-                       SendTimeout = 32
-               }
-
-               // private data
-               NetworkStream stream;
-               bool active;
-               Socket client;
-               bool disposed;
-               Properties values;
-               int recv_timeout, send_timeout;
-               int recv_buffer_size, send_buffer_size;
-               LingerOption linger_state;
-               bool no_delay;
-               
-               private void Init (AddressFamily family)
-               {
-                       active = false;
-
-                       if(client != null) {
-                               client.Close();
-                               client = null;
-                       }
-
-                       client = new Socket(family, SocketType.Stream, ProtocolType.Tcp);
-               }
-
-               public TcpClient ()
-               {
-                       Init(AddressFamily.InterNetwork);
-                       client.Bind(new IPEndPoint(IPAddress.Any, 0));
-               }
-
-               internal TcpClient (Socket s)
-               {
-                       client = s;
-               }
-       
-               public TcpClient (AddressFamily family)
-               {
-                       if (family != AddressFamily.InterNetwork &&
-                           family != AddressFamily.InterNetworkV6) {
-                               throw new ArgumentException ("Family must be InterNetwork or InterNetworkV6", "family");
-                       }
-                       
-                       Init (family);
-                       IPAddress any = IPAddress.Any;
-                       if (family == AddressFamily.InterNetworkV6)
-                               any = IPAddress.IPv6Any;
-                       client.Bind (new IPEndPoint (any, 0));
-               }
-
-               public TcpClient (IPEndPoint localEP)
-               {
-                       Init (localEP.AddressFamily);
-                       client.Bind (localEP);
-               }
-               
-               public TcpClient (string hostname, int port)
-               {
-                       Connect(hostname, port);
-               }
-                               
-               protected bool Active {
-                       get { return active; }
-                       set { active = value; }
-               }
-               
-               public Socket Client {
-                       get { return client; }
-                       set {
-                               client = value;
-                               stream = null;
-                       }
-               }
-
-               public int Available {
-                       get { return client.Available; }
-               }
-
-               public bool Connected {
-                       get { return client.Connected; }
-               }
-
-               public bool ExclusiveAddressUse {
-                       get {
-                               return(client.ExclusiveAddressUse);
-                       }
-                       set {
-                               client.ExclusiveAddressUse = value;
-                       }
-               }
-
-               public LingerOption LingerState {
-                       get {
-                               if ((values & Properties.LingerState) != 0)
-                                       return linger_state;
-
-                               return (LingerOption) client.GetSocketOption (SocketOptionLevel.Socket,
-                                                                       SocketOptionName.Linger);
-                       }
-                       set {
-                               if (!client.Connected) {
-                                       linger_state = value;
-                                       values |= Properties.LingerState;
-                                       return;
-                               }
-                               client.SetSocketOption(
-                                       SocketOptionLevel.Socket,
-                                       SocketOptionName.Linger, value);
-                       }
-               }
-                               
-               public bool NoDelay {
-                       get {
-                               if ((values & Properties.NoDelay) != 0)
-                                       return no_delay;
-
-                               return (bool)client.GetSocketOption(
-                                       SocketOptionLevel.Tcp,
-                                       SocketOptionName.NoDelay);
-                       }
-                       set {
-                               if (!client.Connected) {
-                                       no_delay = value;
-                                       values |= Properties.NoDelay;
-                                       return;
-                               }
-                               client.SetSocketOption(
-                                       SocketOptionLevel.Tcp,
-                                       SocketOptionName.NoDelay, value ? 1 : 0);
-                       }
-               }
-                               
-               public int ReceiveBufferSize {
-                       get {
-                               if ((values & Properties.ReceiveBufferSize) != 0)
-                                       return recv_buffer_size;
-
-                               return (int)client.GetSocketOption(
-                                       SocketOptionLevel.Socket,
-                                       SocketOptionName.ReceiveBuffer);
-                       }
-                       set {
-                               if (!client.Connected) {
-                                       recv_buffer_size = value;
-                                       values |= Properties.ReceiveBufferSize;
-                                       return;
-                               }
-                               client.SetSocketOption(
-                                       SocketOptionLevel.Socket,
-                                       SocketOptionName.ReceiveBuffer, value);
-                       }
-               }
-                       
-               public int ReceiveTimeout {
-                       get {
-                               if ((values & Properties.ReceiveTimeout) != 0)
-                                       return recv_timeout;
-
-                               return (int)client.GetSocketOption(
-                                       SocketOptionLevel.Socket,
-                                       SocketOptionName.ReceiveTimeout);
-                       }
-                       set {
-                               if (!client.Connected) {
-                                       recv_timeout = value;
-                                       values |= Properties.ReceiveTimeout;
-                                       return;
-                               }
-                               client.SetSocketOption(
-                                       SocketOptionLevel.Socket,
-                                       SocketOptionName.ReceiveTimeout, value);
-                       }
-               }
-               
-               public int SendBufferSize {
-                       get {
-                               if ((values & Properties.SendBufferSize) != 0)
-                                       return send_buffer_size;
-
-                               return (int)client.GetSocketOption(
-                                       SocketOptionLevel.Socket,
-                                       SocketOptionName.SendBuffer);
-                       }
-                       set {
-                               if (!client.Connected) {
-                                       send_buffer_size = value;
-                                       values |= Properties.SendBufferSize;
-                                       return;
-                               }
-                               client.SetSocketOption(
-                                       SocketOptionLevel.Socket,
-                                       SocketOptionName.SendBuffer, value);
-                       }
-               }
-               
-               public int SendTimeout {
-                       get {
-                               if ((values & Properties.SendTimeout) != 0)
-                                       return send_timeout;
-
-                               return (int)client.GetSocketOption(
-                                       SocketOptionLevel.Socket,
-                                       SocketOptionName.SendTimeout);
-                       }
-                       set {
-                               if (!client.Connected) {
-                                       send_timeout = value;
-                                       values |= Properties.SendTimeout;
-                                       return;
-                               }
-                               client.SetSocketOption(
-                                       SocketOptionLevel.Socket,
-                                       SocketOptionName.SendTimeout, value);
-                       }
-               }
-               
-               
-               // methods
-               
-               public void Close ()
-               {
-                       Dispose ();
-               }
-
-               public void Connect (IPEndPoint remoteEP)
-               {
-                       try {
-                               client.Connect (remoteEP);
-                               active = true;
-                       } finally {
-                               CheckDisposed ();
-                       }
-               }
-               
-               public void Connect (IPAddress address, int port)
-               {
-                       Connect(new IPEndPoint(address, port));
-               }
-
-               void SetOptions ()
-               {
-                       Properties props = values;
-                       values = 0;
-
-                       if ((props & Properties.LingerState) != 0)
-                               LingerState = linger_state;
-                       if ((props & Properties.NoDelay) != 0)
-                               NoDelay = no_delay;
-                       if ((props & Properties.ReceiveBufferSize) != 0)
-                               ReceiveBufferSize = recv_buffer_size;
-                       if ((props & Properties.ReceiveTimeout) != 0)
-                               ReceiveTimeout = recv_timeout;
-                       if ((props & Properties.SendBufferSize) != 0)
-                               SendBufferSize = send_buffer_size;
-                       if ((props & Properties.SendTimeout) != 0)
-                               SendTimeout = send_timeout;
-               }
-
-               public void Connect (string hostname, int port)
-               {
-                       IPAddress [] addresses = Dns.GetHostAddresses (hostname);
-                       Connect (addresses, port);
-               }
-
-               public void Connect (IPAddress[] ipAddresses, int port)
-               {
-                       CheckDisposed ();
-                       
-                       if (ipAddresses == null) {
-                               throw new ArgumentNullException ("ipAddresses");
-                       }
-                       
-                       for(int i = 0; i < ipAddresses.Length; i++) {
-                               try {
-                                       IPAddress address = ipAddresses[i];
-
-                                       if (address.Equals (IPAddress.Any) ||
-                                           address.Equals (IPAddress.IPv6Any)) {
-                                               throw new SocketException ((int)SocketError.AddressNotAvailable);
-                                       }
-
-                                       Init (address.AddressFamily);
-                                       
-                                       if (address.AddressFamily == AddressFamily.InterNetwork) {
-                                               client.Bind (new IPEndPoint (IPAddress.Any, 0));
-                                       } else if (address.AddressFamily == AddressFamily.InterNetworkV6) {
-                                               client.Bind (new IPEndPoint (IPAddress.IPv6Any, 0));
-                                       } else {
-                                               throw new NotSupportedException ("This method is only valid for sockets in the InterNetwork and InterNetworkV6 families");
-                                       }
-
-                                       Connect (new IPEndPoint (address, port));
-                                       
-                                       if (values != 0) {
-                                               SetOptions ();
-                                       }
-                                       
-                                       break;
-                               } catch (Exception e) {
-                                       /* Reinitialise the socket so
-                                        * other properties still work
-                                        * (see no-arg constructor)
-                                        */
-                                       Init (AddressFamily.InterNetwork);
-
-                                       /* This is the last known
-                                        * address, so re-throw the
-                                        * exception
-                                        */
-                                       if (i == ipAddresses.Length - 1) {
-                                               throw e;
-                                       }
-                               }
-                       }
-               }
-               
-               public void EndConnect (IAsyncResult asyncResult)
-               {
-                       client.EndConnect (asyncResult);
-               }
-               
-               public IAsyncResult BeginConnect (IPAddress address, int port, AsyncCallback requestCallback, object state)
-               {
-                       return client.BeginConnect (address, port, requestCallback, state);
-               }
-               
-               public IAsyncResult BeginConnect (IPAddress[] addresses, int port, AsyncCallback requestCallback, object state)
-               {
-                       return client.BeginConnect (addresses, port, requestCallback, state);
-               }
-               
-               public IAsyncResult BeginConnect (string host, int port, AsyncCallback requestCallback, object state)
-               {
-                       return client.BeginConnect (host, port, requestCallback, state);
-               }
-               
-               public void Dispose ()
-               {
-                       Dispose (true);
-                       GC.SuppressFinalize (this);
-               }
-
-               protected virtual void Dispose (bool disposing)
-               {
-                       if (disposed)
-                               return;
-                       disposed = true;
-
-                       if (disposing) {
-                               // release managed resources
-                               NetworkStream s = stream;
-                               stream = null;
-                               if (s != null) {
-                                       // This closes the socket as well, as the NetworkStream
-                                       // owns the socket.
-                                       s.Close();
-                                       active = false;
-                                       s = null;
-                               } else if (client != null){
-                                       client.Close ();
-                                       client = null;
-                               }
-                       }
-               }
-               
-               ~TcpClient ()
-               {
-                       Dispose (false);
-               }
-               
-               public NetworkStream GetStream()
-               {
-                       try {
-                               if (stream == null)
-                                       stream = new NetworkStream (client, true);
-                               return stream;
-                       }
-                       finally { CheckDisposed (); }
-               }
-
-               public Task ConnectAsync (IPAddress address, int port)
-               {
-                       return Task.Factory.FromAsync (BeginConnect, EndConnect, address, port, null);
-               }
-
-               public Task ConnectAsync (IPAddress[] addresses, int port)
-               {
-                       return Task.Factory.FromAsync (BeginConnect, EndConnect, addresses, port, null);
-               }
-
-               public Task ConnectAsync (string host, int port)
-               {
-                       return Task.Factory.FromAsync (BeginConnect, EndConnect, host, port, null);
-               }
-               private void CheckDisposed ()
-               {
-                       if (disposed)
-                               throw new ObjectDisposedException (GetType().FullName);
-               }
-       }
-}
-
diff --git a/mcs/class/System/System.Net.Sockets/TcpListener.cs b/mcs/class/System/System.Net.Sockets/TcpListener.cs
deleted file mode 100644 (file)
index e8b8ec4..0000000
+++ /dev/null
@@ -1,335 +0,0 @@
-// TcpListener.cs
-//
-// Authors:
-//    Phillip Pearson (pp@myelin.co.nz)
-//    Gonzalo Paniagua Javier (gonzalo@ximian.com)
-//       Patrik Torstensson
-//    Sridhar Kulkarni (sridharkulkarni@gmail.com)
-//    Marek Safar (marek.safar@gmail.com)
-
-//
-// Copyright (C) 2001, Phillip Pearson http://www.myelin.co.nz
-//
-// (c) 2003 Ximian, Inc. (http://www.ximian.com)
-// (c) 2004-2006 Novell, Inc.
-// Copyright 2011 Xamarin Inc.
-//
-
-//
-// 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.Net;
-using System.Threading.Tasks;
-
-namespace System.Net.Sockets
-{
-       /// <remarks>
-       /// A slightly more abstracted way to listen for incoming
-       /// network connections than a Socket.
-       /// </remarks>
-       public class TcpListener
-       {
-               // private data
-               
-               bool active;
-               Socket server;
-               EndPoint savedEP;
-               
-               // constructor
-
-               /// <summary>
-               /// Some code that is shared between the constructors.
-               /// </summary>
-               private void Init (AddressFamily family, EndPoint ep)
-               {
-                       active = false;
-                       server = new Socket(family, SocketType.Stream, ProtocolType.Tcp);
-                       savedEP = ep;
-               }
-               
-               /// <summary>
-               /// Constructs a new TcpListener to listen on a specified port
-               /// </summary>
-               /// <param name="port">The port to listen on, e.g. 80 if you 
-               /// are a web server</param>
-               [Obsolete ("Use TcpListener (IPAddress address, int port) instead")]
-               public TcpListener (int port)
-               {
-                       if (port < 0 || port > 65535)
-                               throw new ArgumentOutOfRangeException ("port");
-
-                       Init (AddressFamily.InterNetwork, new IPEndPoint (IPAddress.Any, port));
-               }
-
-               /// <summary>
-               /// Constructs a new TcpListener with a specified local endpoint
-               /// </summary>
-               /// <param name="local_end_point">The endpoint</param>
-               public TcpListener (IPEndPoint localEP)
-               {
-                       if (localEP == null)
-                               throw new ArgumentNullException ("localEP");
-
-                       Init (localEP.AddressFamily, localEP);
-               }
-               
-               /// <summary>
-               /// Constructs a new TcpListener, listening on a specified port
-               /// and IP (for use on a multi-homed machine)
-               /// </summary>
-               /// <param name="listen_ip">The IP to listen on</param>
-               /// <param name="port">The port to listen on</param>
-               public TcpListener (IPAddress localaddr, int port)
-               {
-                       if (localaddr == null)
-                               throw new ArgumentNullException ("localaddr");
-
-                       if (port < 0 || port > 65535)
-                               throw new ArgumentOutOfRangeException ("port");
-
-                       Init (localaddr.AddressFamily, new IPEndPoint (localaddr, port));
-               }
-
-
-               // properties
-
-               /// <summary>
-               /// A flag that is 'true' if the TcpListener is listening,
-               /// or 'false' if it is not listening
-               /// </summary>
-               protected bool Active
-               {
-                       get { return active; }
-               }
-
-               /// <summary>
-               /// The local end point
-               /// </summary>
-               public EndPoint LocalEndpoint
-               {
-                       get { 
-                               if (active)
-                                       return server.LocalEndPoint;
-
-                               return savedEP; 
-                       }
-               }
-               
-               /// <summary>
-               /// The listening socket
-               /// </summary>
-               public Socket Server
-               {
-                       get { return server; }
-               }
-
-               /// <summary>
-               /// Specifies whether the TcpListener allows only one
-               /// underlying socket to listen to a specific port
-               /// </summary>
-               public bool ExclusiveAddressUse
-               {
-                       get {
-                               if (server == null) {
-                                       throw new ObjectDisposedException (GetType ().ToString ());
-                               }
-                               if (active) {
-                                       throw new InvalidOperationException ("The TcpListener has been started");
-                               }
-
-                               return(server.ExclusiveAddressUse);
-                       }
-                       set {
-                               if (server == null) {
-                                       throw new ObjectDisposedException (GetType ().ToString ());
-                               }
-                               if (active) {
-                                       throw new InvalidOperationException ("The TcpListener has been started");
-                               }
-
-                               server.ExclusiveAddressUse = value;
-                       }
-               }
-               
-               // methods
-
-               /// <summary>
-               /// Accepts a pending connection
-               /// </summary>
-               /// <returns>A Socket object for the new connection</returns>
-               public Socket AcceptSocket ()
-               {
-                       if (!active)
-                               throw new InvalidOperationException ("Socket is not listening");
-
-                       return server.Accept();
-               }
-               
-               /// <summary>
-               /// Accepts a pending connection
-               /// </summary>
-               /// <returns>A TcpClient
-               /// object made from the new socket.</returns>
-               public TcpClient AcceptTcpClient ()
-               {
-                       if (!active)
-                               throw new InvalidOperationException ("Socket is not listening");
-
-                       Socket clientSocket = server.Accept ();
-
-                       TcpClient client = new TcpClient(clientSocket);
-                       
-                       return client;
-               }
-
-               public void AllowNatTraversal (bool allowed)
-               {
-                       if (active)
-                               throw new InvalidOperationException (SR.GetString (SR.net_tcplistener_mustbestopped));
-
-                       if (allowed)
-                               server.SetIPProtectionLevel (IPProtectionLevel.Unrestricted);
-                       else
-                               server.SetIPProtectionLevel (IPProtectionLevel.EdgeRestricted);
-               }
-
-               public static TcpListener Create (int port)
-               {
-                       if (port < 0 || port > 65535)
-                               throw new ArgumentOutOfRangeException ("port");
-
-                       TcpListener listener = new TcpListener (IPAddress.IPv6Any, port);
-                       listener.Server.DualMode = true;
-
-                       return listener;
-               }
-
-               /// <summary>
-               /// Destructor - stops the listener listening
-               /// </summary>
-               ~TcpListener ()
-               {
-                       if (active)
-                               Stop();
-               }
-       
-               /// <returns>
-               /// Returns 'true' if there is a connection waiting to be accepted
-               /// with AcceptSocket() or AcceptTcpClient().
-               /// </returns>
-               public bool Pending ()
-               {
-                       if (!active)
-                               throw new InvalidOperationException ("Socket is not listening");
-
-                       return server.Poll(0, SelectMode.SelectRead);
-               }
-               
-               /// <summary>
-               /// Tells the TcpListener to start listening.
-               /// </summary>
-               public void Start ()
-               {
-                       // MS: sets Listen to Int32.MaxValue
-                       this.Start (5);
-                       // According to the man page some BSD and BSD-derived
-                       // systems limit the backlog to 5.  This should really be
-                       // configurable though
-               }
-
-               /// <summary>
-               /// Tells the TcpListener to start listening for max number
-               /// of pending connections.
-               /// </summary>
-
-               public void Start (int backlog)
-               {
-                       if (active) {
-                               return;
-                       }
-                       if (server == null) {
-                               throw new InvalidOperationException ("Invalid server socket");
-                       }
-                       
-                       server.Bind (savedEP);
-                       server.Listen (backlog);
-                       active = true;
-               }
-
-               public IAsyncResult BeginAcceptSocket (AsyncCallback callback,
-                                                      object state)
-               {
-                       if (server == null) {
-                               throw new ObjectDisposedException (GetType ().ToString ());
-                       }
-                       
-                       return(server.BeginAccept (callback, state));
-               }
-               
-               public IAsyncResult BeginAcceptTcpClient (AsyncCallback callback, object state)
-               {
-                       if (server == null) {
-                               throw new ObjectDisposedException (GetType ().ToString ());
-                       }
-                       
-                       return(server.BeginAccept (callback, state));
-               }
-               
-               public Socket EndAcceptSocket (IAsyncResult asyncResult) 
-               {
-                       return(server.EndAccept (asyncResult));
-               }
-               
-               public TcpClient EndAcceptTcpClient (IAsyncResult asyncResult)
-               {
-                       Socket clientSocket = server.EndAccept (asyncResult);
-                       TcpClient client = new TcpClient (clientSocket);
-                       
-                       return(client);
-               }
-               
-               /// <summary>
-               /// Tells the TcpListener to stop listening and dispose
-               /// of all managed resources.
-               /// </summary>
-               public void Stop ()
-               {
-                       if (active) 
-                       {
-                               server.Close ();
-                               server = null;
-                       }
-
-                       Init (AddressFamily.InterNetwork, savedEP);
-               }
-
-               public Task<Socket> AcceptSocketAsync ()
-               {
-                       return Task<Socket>.Factory.FromAsync (BeginAcceptSocket, EndAcceptSocket, null);
-               }
-
-               public Task<TcpClient> AcceptTcpClientAsync ()
-               {
-                       return Task<TcpClient>.Factory.FromAsync (BeginAcceptTcpClient, EndAcceptTcpClient, null);
-               }
-       }
-}
diff --git a/mcs/class/System/System.Net.Sockets/UdpClient.cs b/mcs/class/System/System.Net.Sockets/UdpClient.cs
deleted file mode 100644 (file)
index c82529b..0000000
+++ /dev/null
@@ -1,642 +0,0 @@
-//
-// System.Net.Sockets.UdpClient.cs
-//
-// Author:
-//    Gonzalo Paniagua Javier <gonzalo@ximian.com>
-//    Sridhar Kulkarni (sridharkulkarni@gmail.com)
-//    Marek Safar (marek.safar@gmail.com)
-//
-// Copyright (C) Ximian, Inc. http://www.ximian.com
-// Copyright 2011 Xamarin Inc.
-//
-
-//
-// 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.Net;
-using System.Threading.Tasks;
-
-namespace System.Net.Sockets
-{
-       public class UdpClient : IDisposable
-       {
-               private bool disposed = false;
-               private bool active = false;
-               private Socket socket;
-               private AddressFamily family = AddressFamily.InterNetwork;
-               private byte[] recvbuffer;
-       
-               public UdpClient () : this(AddressFamily.InterNetwork)
-               {
-               }
-
-               public UdpClient(AddressFamily family)
-               {
-                       if(family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6)
-                               throw new ArgumentException ("Family must be InterNetwork or InterNetworkV6", "family");
-
-                       this.family = family;
-                       InitSocket (null);
-               }
-
-               public UdpClient (int port)
-               {
-                       if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
-                               throw new ArgumentOutOfRangeException ("port");
-
-                       this.family = AddressFamily.InterNetwork;
-
-                       IPEndPoint localEP = new IPEndPoint (IPAddress.Any, port);
-                       InitSocket (localEP);
-               }
-
-               public UdpClient (IPEndPoint localEP)
-               {
-                       if (localEP == null)
-                               throw new ArgumentNullException ("localEP");
-
-                       this.family = localEP.AddressFamily;
-
-                       InitSocket (localEP);
-               }
-
-               public UdpClient (int port, AddressFamily family)
-               {
-                       if (family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6)
-                               throw new ArgumentException ("Family must be InterNetwork or InterNetworkV6", "family");
-
-                       if (port < IPEndPoint.MinPort ||
-                           port > IPEndPoint.MaxPort) {
-                               throw new ArgumentOutOfRangeException ("port");
-                       }
-
-                       this.family = family;
-
-                       IPEndPoint localEP;
-
-                       if (family == AddressFamily.InterNetwork)
-                               localEP = new IPEndPoint (IPAddress.Any, port);
-                       else
-                               localEP = new IPEndPoint (IPAddress.IPv6Any, port);
-                       InitSocket (localEP);
-               }
-
-               public UdpClient (string hostname, int port)
-               {
-                       if (hostname == null)
-                               throw new ArgumentNullException ("hostname");
-
-                       if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
-                               throw new ArgumentOutOfRangeException ("port");
-
-                       InitSocket (null);
-                       Connect (hostname, port);
-               }
-
-               private void InitSocket (EndPoint localEP)
-               {
-                       if(socket != null) {
-                               socket.Close();
-                               socket = null;
-                       }
-
-                       socket = new Socket (family, SocketType.Dgram, ProtocolType.Udp);
-
-                       if (localEP != null)
-                               socket.Bind (localEP);
-               }
-
-               public void AllowNatTraversal (bool allowed)
-               {
-                       if (allowed)
-                               socket.SetIPProtectionLevel (IPProtectionLevel.Unrestricted);
-                       else
-                               socket.SetIPProtectionLevel (IPProtectionLevel.EdgeRestricted);
-               }
-
-               public void Close ()
-               {
-                       Dispose ();
-               }
-#region Connect
-
-               void DoConnect (IPEndPoint endPoint)
-               {
-                       /* Catch EACCES and turn on SO_BROADCAST then,
-                        * as UDP sockets don't have it set by default
-                        */
-                       try {
-                               socket.Connect (endPoint);
-                       } catch (SocketException ex) {
-                               if (ex.ErrorCode == (int)SocketError.AccessDenied) {
-                                       socket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
-                                       
-                                       socket.Connect (endPoint);
-                               } else {
-                                       throw;
-                               }
-                       }
-               }
-               
-               public void Connect (IPEndPoint endPoint)
-               {
-                       CheckDisposed ();
-                       if (endPoint == null)
-                               throw new ArgumentNullException ("endPoint");
-
-                       DoConnect (endPoint);
-                       active = true;
-               }
-
-               public void Connect (IPAddress addr, int port)
-               {
-                       if (addr == null)
-                               throw new ArgumentNullException ("addr");
-
-                       if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
-                               throw new ArgumentOutOfRangeException ("port");
-
-
-                       Connect (new IPEndPoint (addr, port));
-               }
-
-               public void Connect (string hostname, int port)
-               {
-                       if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
-                               throw new ArgumentOutOfRangeException ("port");
-
-                       IPAddress[] addresses = Dns.GetHostAddresses (hostname);
-                       for(int i=0; i<addresses.Length; i++) {
-                               try {
-                                       this.family = addresses[i].AddressFamily;
-                                       Connect (new IPEndPoint (addresses[i], port));
-                                       break;
-                               } catch(Exception e) {
-                                       if(i == addresses.Length - 1){
-                                               if(socket != null) {
-                                                       socket.Close();
-                                                       socket = null;
-                                               }
-                                               /// This is the last entry, re-throw the exception
-                                               throw e;
-                                       }
-                               }
-                       }
-               }
-#endregion
-               #region Multicast methods
-               public void DropMulticastGroup (IPAddress multicastAddr)
-               {
-                       CheckDisposed ();
-                       if (multicastAddr == null)
-                               throw new ArgumentNullException ("multicastAddr");
-
-                       if(family == AddressFamily.InterNetwork)
-                               socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.DropMembership,
-                                       new MulticastOption (multicastAddr));
-                       else
-                               socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.DropMembership,
-                                       new IPv6MulticastOption (multicastAddr));
-               }
-
-               public void DropMulticastGroup (IPAddress multicastAddr,
-                                               int ifindex)
-               {
-                       CheckDisposed ();
-
-                       /* LAMESPEC: exceptions haven't been specified
-                        * for this overload.
-                        */
-                       if (multicastAddr == null) {
-                               throw new ArgumentNullException ("multicastAddr");
-                       }
-
-                       /* Does this overload only apply to IPv6?
-                        * Only the IPv6MulticastOption has an
-                        * ifindex-using constructor.  The MS docs
-                        * don't say.
-                        */
-                       if (family == AddressFamily.InterNetworkV6) {
-                               socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.DropMembership, new IPv6MulticastOption (multicastAddr, ifindex));
-                       }
-               }
-               
-               public void JoinMulticastGroup (IPAddress multicastAddr)
-               {
-                       CheckDisposed ();
-
-                       if (multicastAddr == null)
-                               throw new ArgumentNullException ("multicastAddr");
-
-                       if(family == AddressFamily.InterNetwork)
-                               socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.AddMembership,
-                                       new MulticastOption (multicastAddr));
-                       else
-                               socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.AddMembership,
-                                       new IPv6MulticastOption (multicastAddr));
-               }
-
-               public void JoinMulticastGroup (int ifindex,
-                                               IPAddress multicastAddr)
-               {
-                       CheckDisposed ();
-
-                       if (multicastAddr == null)
-                               throw new ArgumentNullException ("multicastAddr");
-
-                       if (family == AddressFamily.InterNetworkV6)
-                               socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.AddMembership, new IPv6MulticastOption (multicastAddr, ifindex));
-                       else
-                               throw new SocketException ((int) SocketError.OperationNotSupported);
-               }
-
-               public void JoinMulticastGroup (IPAddress multicastAddr, int timeToLive)
-               {
-                       CheckDisposed ();
-                       if (multicastAddr == null)
-                               throw new ArgumentNullException ("multicastAddr");
-                       if (timeToLive < 0 || timeToLive > 255)
-                               throw new ArgumentOutOfRangeException ("timeToLive");
-
-                       JoinMulticastGroup (multicastAddr);
-                       if(family == AddressFamily.InterNetwork)
-                               socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive,
-                                       timeToLive);
-                       else
-                               socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.MulticastTimeToLive,
-                                       timeToLive);
-               }
-
-               public void JoinMulticastGroup (IPAddress multicastAddr,
-                                               IPAddress localAddress)
-               {
-                       CheckDisposed ();
-
-                       if (family == AddressFamily.InterNetwork)
-                               socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption (multicastAddr, localAddress));
-                       else
-                               throw new SocketException ((int) SocketError.OperationNotSupported);
-               }
-
-               #endregion
-               #region Data I/O
-               public byte [] Receive (ref IPEndPoint remoteEP)
-               {
-                       CheckDisposed ();
-
-                       byte [] recBuffer = new byte [65536]; // Max. size
-                       EndPoint endPoint = (EndPoint) remoteEP;
-                       int dataRead = socket.ReceiveFrom (recBuffer, ref endPoint);
-                       if (dataRead < recBuffer.Length)
-                               recBuffer = CutArray (recBuffer, dataRead);
-
-                       remoteEP = (IPEndPoint) endPoint;
-                       return recBuffer;
-               }
-
-               int DoSend (byte[] dgram, int bytes, IPEndPoint endPoint)
-               {
-                       /* Catch EACCES and turn on SO_BROADCAST then,
-                        * as UDP sockets don't have it set by default
-                        */
-                       try {
-                               if (endPoint == null) {
-                                       return(socket.Send (dgram, 0, bytes,
-                                                           SocketFlags.None));
-                               } else {
-                                       return(socket.SendTo (dgram, 0, bytes,
-                                                             SocketFlags.None,
-                                                             endPoint));
-                               }
-                       } catch (SocketException ex) {
-                               if (ex.ErrorCode == (int)SocketError.AccessDenied) {
-                                       socket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
-                                       if (endPoint == null) {
-                                               return(socket.Send (dgram, 0, bytes, SocketFlags.None));
-                                       } else {
-                                               return(socket.SendTo (dgram, 0, bytes, SocketFlags.None, endPoint));
-                                       }
-                               } else {
-                                       throw;
-                               }
-                       }
-               }
-               
-               public int Send (byte [] dgram, int bytes)
-               {
-                       CheckDisposed ();
-                       if (dgram == null)
-                               throw new ArgumentNullException ("dgram");
-
-                       if (!active)
-                               throw new InvalidOperationException ("Operation not allowed on " + 
-                                                                    "non-connected sockets.");
-
-                       return(DoSend (dgram, bytes, null));
-               }
-
-               public int Send (byte [] dgram, int bytes, IPEndPoint endPoint)
-               {
-                       CheckDisposed ();
-                       if (dgram == null)
-                               throw new ArgumentNullException ("dgram is null");
-                       
-                       if (active) {
-                               if (endPoint != null)
-                                       throw new InvalidOperationException ("Cannot send packets to an " +
-                                                                            "arbitrary host while connected.");
-
-                               return(DoSend (dgram, bytes, null));
-                       }
-
-                       return(DoSend (dgram, bytes, endPoint));
-               }
-
-               public int Send (byte [] dgram, int bytes, string hostname, int port)
-               {
-                       return Send (dgram, bytes, 
-                                    new IPEndPoint (Dns.GetHostAddresses (hostname) [0], port));
-               }
-
-               private byte [] CutArray (byte [] orig, int length)
-               {
-                       byte [] newArray = new byte [length];
-                       Buffer.BlockCopy (orig, 0, newArray, 0, length);
-
-                       return newArray;
-               }
-#endregion
-
-               IAsyncResult DoBeginSend (byte[] datagram, int bytes,
-                                         IPEndPoint endPoint,
-                                         AsyncCallback requestCallback,
-                                         object state)
-               {
-                       /* Catch EACCES and turn on SO_BROADCAST then,
-                        * as UDP sockets don't have it set by default
-                        */
-                       try {
-                               if (endPoint == null) {
-                                       return(socket.BeginSend (datagram, 0, bytes, SocketFlags.None, requestCallback, state));
-                               } else {
-                                       return(socket.BeginSendTo (datagram, 0, bytes, SocketFlags.None, endPoint, requestCallback, state));
-                               }
-                       } catch (SocketException ex) {
-                               if (ex.ErrorCode == (int)SocketError.AccessDenied) {
-                                       socket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
-                                       if (endPoint == null) {
-                                               return(socket.BeginSend (datagram, 0, bytes, SocketFlags.None, requestCallback, state));
-                                       } else {
-                                               return(socket.BeginSendTo (datagram, 0, bytes, SocketFlags.None, endPoint, requestCallback, state));
-                                       }
-                               } else {
-                                       throw;
-                               }
-                       }
-               }
-               
-               public IAsyncResult BeginSend (byte[] datagram, int bytes,
-                                              AsyncCallback requestCallback,
-                                              object state)
-               {
-                       return(BeginSend (datagram, bytes, null,
-                                         requestCallback, state));
-               }
-               
-               public IAsyncResult BeginSend (byte[] datagram, int bytes,
-                                              IPEndPoint endPoint,
-                                              AsyncCallback requestCallback,
-                                              object state)
-               {
-                       CheckDisposed ();
-
-                       if (datagram == null) {
-                               throw new ArgumentNullException ("datagram");
-                       }
-                       
-                       return(DoBeginSend (datagram, bytes, endPoint,
-                                           requestCallback, state));
-               }
-               
-               public IAsyncResult BeginSend (byte[] datagram, int bytes,
-                                              string hostname, int port,
-                                              AsyncCallback requestCallback,
-                                              object state)
-               {
-                       return(BeginSend (datagram, bytes, new IPEndPoint (Dns.GetHostAddresses (hostname) [0], port), requestCallback, state));
-               }
-               
-               public int EndSend (IAsyncResult asyncResult)
-               {
-                       CheckDisposed ();
-                       
-                       if (asyncResult == null) {
-                               throw new ArgumentNullException ("asyncResult is a null reference");
-                       }
-                       
-                       return(socket.EndSend (asyncResult));
-               }
-
-               public IAsyncResult BeginReceive (AsyncCallback requestCallback, object state)
-               {
-                       CheckDisposed ();
-
-                       recvbuffer = new byte[8192];
-                       
-                       EndPoint ep;
-                       
-                       if (family == AddressFamily.InterNetwork) {
-                               ep = new IPEndPoint (IPAddress.Any, 0);
-                       } else {
-                               ep = new IPEndPoint (IPAddress.IPv6Any, 0);
-                       }
-                       
-                       return(socket.BeginReceiveFrom (recvbuffer, 0, 8192,
-                                                       SocketFlags.None,
-                                                       ref ep,
-                                                       requestCallback, state));
-               }
-               
-               public byte[] EndReceive (IAsyncResult asyncResult, ref IPEndPoint remoteEP)
-               {
-                       CheckDisposed ();
-                       
-                       if (asyncResult == null) {
-                               throw new ArgumentNullException ("asyncResult is a null reference");
-                       }
-                       
-                       EndPoint ep;
-                       
-                       if (family == AddressFamily.InterNetwork) {
-                               ep = new IPEndPoint (IPAddress.Any, 0);
-                       } else {
-                               ep = new IPEndPoint (IPAddress.IPv6Any, 0);
-                       }
-                       
-                       int bytes = socket.EndReceiveFrom (asyncResult,
-                                                          ref ep);
-                       remoteEP = (IPEndPoint)ep;
-
-                       /* Need to copy into a new array here, because
-                        * otherwise the returned array length is not
-                        * 'bytes'
-                        */
-                       byte[] buf = new byte[bytes];
-                       Array.Copy (recvbuffer, buf, bytes);
-                       
-                       return(buf);
-               }
-                               
-#region Properties
-               protected bool Active {
-                       get { return active; }
-                       set { active = value; }
-               }
-
-               public Socket Client {
-                       get { return socket; }
-                       set { socket = value; }
-               }
-
-               public int Available
-               {
-                       get {
-                               return(socket.Available);
-                       }
-               }
-               
-               public bool DontFragment
-               {
-                       get {
-                               return(socket.DontFragment);
-                       }
-                       set {
-                               socket.DontFragment = value;
-                       }
-               }
-
-               public bool EnableBroadcast
-               {
-                       get {
-                               return(socket.EnableBroadcast);
-                       }
-                       set {
-                               socket.EnableBroadcast = value;
-                       }
-               }
-               
-               public bool ExclusiveAddressUse
-               {
-                       get {
-                               return(socket.ExclusiveAddressUse);
-                       }
-                       set {
-                               socket.ExclusiveAddressUse = value;
-                       }
-               }
-               
-               public bool MulticastLoopback
-               {
-                       get {
-                               return(socket.MulticastLoopback);
-                       }
-                       set {
-                               socket.MulticastLoopback = value;
-                       }
-               }
-               
-               public short Ttl
-               {
-                       get {
-                               return(socket.Ttl);
-                       }
-                       set {
-                               socket.Ttl = value;
-                       }
-               }
-
-#endregion
-#region Disposing
-               public void Dispose ()
-               {
-                       Dispose (true);
-                       GC.SuppressFinalize (this);
-               }
-
-               protected virtual void Dispose (bool disposing)
-               {
-                       if (disposed)
-                               return;
-                       disposed = true;
-
-                       if (disposing){
-                               if (socket != null)
-                                       socket.Close ();
-
-                               socket = null;
-                       }
-               }
-               
-               ~UdpClient ()
-               {
-                       Dispose (false);
-               }
-               
-               private void CheckDisposed ()
-               {
-                       if (disposed)
-                               throw new ObjectDisposedException (GetType().FullName);
-               }               
-#endregion
-
-               
-               public Task<UdpReceiveResult> ReceiveAsync ()
-               {
-                       return Task<UdpReceiveResult>.Factory.FromAsync (BeginReceive, r => {
-                               IPEndPoint remoteEndPoint = null;
-                               return new UdpReceiveResult (EndReceive (r, ref remoteEndPoint), remoteEndPoint);
-                       }, null);
-               }
-
-               public Task<int> SendAsync (byte[] datagram, int bytes)
-               {
-                       return Task<int>.Factory.FromAsync (BeginSend, EndSend, datagram, bytes, null);
-               }
-
-               public Task<int> SendAsync (byte[] datagram, int bytes, IPEndPoint endPoint)
-               {
-                       return Task<int>.Factory.FromAsync (BeginSend, EndSend, datagram, bytes, endPoint, null);
-               }
-
-               public Task<int> SendAsync (byte[] datagram, int bytes, string hostname, int port)
-               {
-                       var t = Tuple.Create (datagram, bytes, hostname, port, this);
-
-                       return Task<int>.Factory.FromAsync ((callback, state) => {
-                               var d = (Tuple<byte[], int, string, int, UdpClient>) state;
-                               return d.Item5.BeginSend (d.Item1, d.Item2, d.Item3, d.Item4, callback, null);
-                       }, EndSend, t);
-               }
-       }
-}
-
index 806bfc119d6e52d9f4157c3ba1552643104a9beb..dac834884441e8ccd8764f846dcea5289ebd073b 100644 (file)
@@ -295,10 +295,10 @@ namespace System.Net {
 
 
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
-               private extern static bool GetHostByName_internal(string host, out string h_name, out string[] h_aliases, out string[] h_addr_list);
+               private extern static bool GetHostByName_internal(string host, out string h_name, out string[] h_aliases, out string[] h_addr_list, int hint);
 
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
-               private extern static bool GetHostByAddr_internal(string addr, out string h_name, out string[] h_aliases, out string[] h_addr_list);
+               private extern static bool GetHostByAddr_internal(string addr, out string h_name, out string[] h_aliases, out string[] h_addr_list, int hint);
 
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
                private extern static bool GetHostName_internal(out string h_name);
@@ -372,7 +372,7 @@ namespace System.Net {
 
                        string h_name;
                        string[] h_aliases, h_addrlist;
-                       bool ret = GetHostByAddr_internal(address, out h_name, out h_aliases, out h_addrlist);
+                       bool ret = GetHostByAddr_internal(address, out h_name, out h_aliases, out h_addrlist, Socket.FamilyHint);
                        if (!ret)
                                Error_11001 (address);
                        return (hostent_to_IPHostEntry (address, h_name, h_aliases, h_addrlist));
@@ -434,7 +434,7 @@ namespace System.Net {
                        string h_name;
                        string[] h_aliases, h_addrlist;
 
-                       bool ret = GetHostByName_internal(hostName, out h_name, out h_aliases, out h_addrlist);
+                       bool ret = GetHostByName_internal(hostName, out h_name, out h_aliases, out h_addrlist, Socket.FamilyHint);
                        if (ret == false)
                                Error_11001 (hostName);
 
index 9e2c655cb2dd9842e3afde14b817fe1b32b451e2..c0ea1b551195e55dd06e5919c44646ee5548dc8e 100644 (file)
@@ -17,6 +17,7 @@ using MSI = Mono.Security.Interface;
 #endif
 
 using System;
+using System.Globalization;
 using System.IO;
 using System.Net.Sockets;
 using System.Text;
@@ -42,6 +43,7 @@ namespace System.Net
                NetworkCredential credentials;
                IPHostEntry hostEntry;
                IPEndPoint localEndPoint;
+               IPEndPoint remoteEndPoint;
                IWebProxy proxy;
                int timeout = 100000;
                int rwTimeout = 300000;
@@ -65,7 +67,9 @@ namespace System.Net
                const string PasswordCommand = "PASS";
                const string TypeCommand = "TYPE";
                const string PassiveCommand = "PASV";
+               const string ExtendedPassiveCommand = "EPSV";
                const string PortCommand = "PORT";
+               const string ExtendedPortCommand = "EPRT";
                const string AbortCommand = "ABOR";
                const string AuthCommand = "AUTH";
                const string RestCommand = "REST";
@@ -401,6 +405,7 @@ namespace System.Net
                                                State = RequestState.Scheduled;
 
                                        Thread thread = new Thread (ProcessRequest);
+                                       thread.IsBackground = true;
                                        thread.Start ();
                                }
                        }
@@ -452,6 +457,7 @@ namespace System.Net
 
                        asyncResult = new FtpAsyncResult (callback, state);
                        Thread thread = new Thread (ProcessRequest);
+                       thread.IsBackground = true;
                        thread.Start ();
 
                        return asyncResult;
@@ -775,14 +781,14 @@ namespace System.Net
                        foreach (IPAddress address in hostEntry.AddressList) {
                                sock = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
 
-                               IPEndPoint remote = new IPEndPoint (address, requestUri.Port);
+                               remoteEndPoint = new IPEndPoint (address, requestUri.Port);
 
-                               if (!ServicePoint.CallEndPointDelegate (sock, remote)) {
+                               if (!ServicePoint.CallEndPointDelegate (sock, remoteEndPoint)) {
                                        sock.Close ();
                                        sock = null;
                                } else {
                                        try {
-                                               sock.Connect (remote);
+                                               sock.Connect (remoteEndPoint);
                                                localEndPoint = (IPEndPoint) sock.LocalEndPoint;
                                                break;
                                        } catch (SocketException exc) {
@@ -837,52 +843,19 @@ namespace System.Net
                }
 
                // Probably we could do better having here a regex
-               Socket SetupPassiveConnection (string statusDescription)
+               Socket SetupPassiveConnection (string statusDescription, bool ipv6)
                {
                        // Current response string
                        string response = statusDescription;
                        if (response.Length < 4)
                                throw new WebException ("Cannot open passive data connection");
-                       
-                       // Look for first digit after code
-                       int i;
-                       for (i = 3; i < response.Length && !Char.IsDigit (response [i]); i++)
-                               ;
-                       if (i >= response.Length)
-                               throw new WebException ("Cannot open passive data connection");
-
-                       // Get six elements
-                       string [] digits = response.Substring (i).Split (new char [] {','}, 6);
-                       if (digits.Length != 6)
-                               throw new WebException ("Cannot open passive data connection");
-
-                       // Clean non-digits at the end of last element
-                       int j;
-                       for (j = digits [5].Length - 1; j >= 0 && !Char.IsDigit (digits [5][j]); j--)
-                               ;
-                       if (j < 0)
-                               throw new WebException ("Cannot open passive data connection");
-                       
-                       digits [5] = digits [5].Substring (0, j + 1);
-
-                       IPAddress ip;
-                       try {
-                               ip = IPAddress.Parse (String.Join (".", digits, 0, 4));
-                       } catch (FormatException) {
-                               throw new WebException ("Cannot open passive data connection");
-                       }
 
-                       // Get the port
-                       int p1, p2, port;
-                       if (!Int32.TryParse (digits [4], out p1) || !Int32.TryParse (digits [5], out p2))
-                               throw new WebException ("Cannot open passive data connection");
+                       int port = ipv6 ? GetPortV6 (response) : GetPortV4 (response);
 
-                       port = (p1 << 8) + p2; // p1 * 256 + p2
-                       //port = p1 * 256 + p2;
                        if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
                                throw new WebException ("Cannot open passive data connection");
 
-                       IPEndPoint ep = new IPEndPoint (ip, port);
+                       IPEndPoint ep = new IPEndPoint (remoteEndPoint.Address, port);
                        Socket sock = new Socket (ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                        try {
                                sock.Connect (ep);
@@ -894,6 +867,87 @@ namespace System.Net
                        return sock;
                }
 
+               // GetPortV4, GetPortV6, FormatAddress and FormatAddressV6 are copied from referencesource
+               // TODO: replace FtpWebRequest completely.
+               private int GetPortV4(string responseString)
+               {
+                       string [] parsedList = responseString.Split(new char [] {' ', '(', ',', ')'});
+
+                       // We need at least the status code and the port
+                       if (parsedList.Length <= 7) {
+                               throw new FormatException(SR.GetString(SR.net_ftp_response_invalid_format, responseString));
+                       }
+
+                       int index = parsedList.Length-1;
+                       // skip the last non-number token (e.g. terminating '.')
+#if MONO
+                       // the MS code expects \r\n here in parsedList[index],
+                       // but we're stripping the EOL off earlier so the array contains
+                       // an empty string here which would make Char.IsNumber throw
+                       // TODO: this can be removed once we switch FtpWebRequest to referencesource
+                       if (parsedList[index] == "" || !Char.IsNumber(parsedList[index], 0))
+#else
+                       if (!Char.IsNumber(parsedList[index], 0))
+#endif
+                               index--;
+
+                       int port = Convert.ToByte(parsedList[index--], NumberFormatInfo.InvariantInfo);
+                       port = port |
+                               (Convert.ToByte(parsedList[index--], NumberFormatInfo.InvariantInfo) << 8);
+
+                       return port;
+               }
+
+               private int GetPortV6(string responseString)
+               {
+                       int pos1 = responseString.LastIndexOf("(");
+                       int pos2 = responseString.LastIndexOf(")");
+                       if (pos1 == -1 || pos2 <= pos1) 
+                               throw new FormatException(SR.GetString(SR.net_ftp_response_invalid_format, responseString));
+
+                       // addressInfo will contain a string of format "|||<tcp-port>|"
+                       string addressInfo = responseString.Substring(pos1+1, pos2-pos1-1);
+
+                       // Although RFC2428 recommends using "|" as the delimiter,
+                       // It allows ASCII characters in range 33-126 inclusive.
+                       // We should consider allowing the full range.
+
+                       string [] parsedList = addressInfo.Split(new char [] {'|'});
+                       if (parsedList.Length < 4)
+                               throw new FormatException(SR.GetString(SR.net_ftp_response_invalid_format, responseString));
+                       
+                       return Convert.ToInt32(parsedList[3], NumberFormatInfo.InvariantInfo);
+               }
+
+               private String FormatAddress(IPAddress address, int Port )
+               {
+                       byte [] localAddressInBytes = address.GetAddressBytes();
+
+                       // produces a string in FTP IPAddress/Port encoding (a1, a2, a3, a4, p1, p2), for sending as a parameter
+                       // to the port command.
+                       StringBuilder sb = new StringBuilder(32);
+                       foreach (byte element in localAddressInBytes) {
+                               sb.Append(element);
+                               sb.Append(',');
+                       }
+                       sb.Append(Port / 256 );
+                       sb.Append(',');
+                       sb.Append(Port % 256 );
+                       return sb.ToString();
+               }
+
+               private string FormatAddressV6(IPAddress address, int port) {
+                       StringBuilder sb = new StringBuilder(43); // based on max size of IPv6 address + port + seperators
+                       String addressString = address.ToString();
+                       sb.Append("|2|");
+                       sb.Append(addressString);
+                       sb.Append('|');
+                       sb.Append(port.ToString(NumberFormatInfo.InvariantInfo));
+                       sb.Append('|');
+                       return sb.ToString();
+               }
+               //
+
                Exception CreateExceptionFromResponse (FtpStatus status)
                {
                        FtpWebResponse ftpResponse = new FtpWebResponse (this, requestUri, method, status);
@@ -932,18 +986,19 @@ namespace System.Net
                Socket InitDataConnection ()
                {
                        FtpStatus status;
-                       
+                       bool ipv6 = remoteEndPoint.AddressFamily == AddressFamily.InterNetworkV6;
+
                        if (usePassive) {
-                               status = SendCommand (PassiveCommand);
-                               if (status.StatusCode != FtpStatusCode.EnteringPassive) {
+                               status = SendCommand (ipv6 ? ExtendedPassiveCommand : PassiveCommand);
+                               if (status.StatusCode != (ipv6 ? (FtpStatusCode)229 : FtpStatusCode.EnteringPassive)) { // FtpStatusCode doesn't contain code 229 for EPSV so we need to cast...
                                        throw CreateExceptionFromResponse (status);
                                }
                                
-                               return SetupPassiveConnection (status.StatusDescription);
+                               return SetupPassiveConnection (status.StatusDescription, ipv6);
                        }
 
                        // Open a socket to listen the server's connection
-                       Socket sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+                       Socket sock = new Socket (remoteEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                        try {
                                sock.Bind (new IPEndPoint (localEndPoint.Address, 0));
                                sock.Listen (1); // We only expect a connection from server
@@ -955,12 +1010,10 @@ namespace System.Net
                        }
 
                        IPEndPoint ep = (IPEndPoint) sock.LocalEndPoint;
-                       string ipString = ep.Address.ToString ().Replace ('.', ',');
-                       int h1 = ep.Port >> 8; // ep.Port / 256
-                       int h2 = ep.Port % 256;
 
-                       string portParam = ipString + "," + h1 + "," + h2;
-                       status = SendCommand (PortCommand, portParam);
+                       var portParam = ipv6 ? FormatAddressV6 (ep.Address, ep.Port) : FormatAddress (ep.Address, ep.Port);
+
+                       status = SendCommand (ipv6 ? ExtendedPortCommand : PortCommand, portParam);
                        
                        if (status.StatusCode != FtpStatusCode.CommandOK) {
                                sock.Close ();
index afc452f7cc62474d137383f7941f292974007762..0a36e21004943427b937884ef9993d703c7a2c9c 100644 (file)
@@ -83,7 +83,6 @@ namespace System.Net
                HttpWebRequest connect_request;
 
                Exception connect_exception;
-               static object classLock = new object ();
                MonoTlsStream tlsStream;
 
 #if MONOTOUCH && !MONOTOUCH_TV && !MONOTOUCH_WATCH
@@ -257,14 +256,16 @@ namespace System.Net
                                        connect_request.Credentials = creds;
                                }
 
-                               for (int i = 0; i < challenge.Length; i++) {
-                                       var auth = AuthenticationManager.Authenticate (challenge [i], connect_request, creds);
-                                       if (auth == null)
-                                               continue;
-                                       ntlm = (auth.ModuleAuthenticationType == "NTLM");
-                                       sb.Append ("\r\nProxy-Authorization: ");
-                                       sb.Append (auth.Message);
-                                       break;
+                               if (creds != null) {
+                                       for (int i = 0; i < challenge.Length; i++) {
+                                               var auth = AuthenticationManager.Authenticate (challenge [i], connect_request, creds);
+                                               if (auth == null)
+                                                       continue;
+                                               ntlm = (auth.ModuleAuthenticationType == "NTLM");
+                                               sb.Append ("\r\nProxy-Authorization: ");
+                                               sb.Append (auth.Message);
+                                               break;
+                                       }
                                }
                        }
 
@@ -292,12 +293,14 @@ namespace System.Net
                                }
 
                                Data.StatusCode = status;
-                               Data.Challenge = result.GetValues ("Proxy-Authentic");
+                               Data.Challenge = result.GetValues ("Proxy-Authenticate");
                                Data.Headers = result;
                                return false;
-                       } else if (status != 200) {
-                               string msg = String.Format ("The remote server returned a {0} status code.", status);
-                               HandleError (WebExceptionStatus.SecureChannelFailure, null, msg);
+                       }
+
+                       if (status != 200) {
+                               Data.StatusCode = status;
+                               Data.Headers = result;
                                return false;
                        }
 
index 795f0d04b21acfabb51a09db288cfa3ccfecd274..78a87057ce7e65b89198e52ddbd940bd4c514246 100644 (file)
@@ -124,7 +124,6 @@ namespace System.Security.Cryptography.X509Certificates {
                }
 
                internal X500DistinguishedName (byte[] encoded, byte[] canonEncoding, string name)
-                       : this (encoded)
                {
                        this.canonEncoding = canonEncoding;
                        this.name = name;
@@ -234,7 +233,7 @@ namespace System.Security.Cryptography.X509Certificates {
                                if (name1.canonEncoding.Length != name2.canonEncoding.Length)
                                        return false;
                                for (int i = 0; i < name1.canonEncoding.Length; i++) {
-                                       if (name1.canonEncoding[i] != name2.canonEncoding[2])
+                                       if (name1.canonEncoding[i] != name2.canonEncoding[i])
                                                return false;
                                }
                                return true;
index bd69c786b89b80f947a56046fa9d7eb45411e291..ef10413f59722853150a79935cca076d7e1fbcae 100644 (file)
@@ -399,13 +399,10 @@ namespace System.Security.Cryptography.X509Certificates {
                // internal stuff because X509Certificate2 isn't complete enough
                // (maybe X509Certificate3 will be better?)
 
-               [Obsolete ("KILL")]
+               [MonoTODO ("See comment in X509Helper2.GetMonoCertificate().")]
                internal MX.X509Certificate MonoCertificate {
                        get {
-                               var monoImpl = Impl as X509Certificate2ImplMono;
-                               if (monoImpl == null)
-                                       throw new NotSupportedException ();
-                               return monoImpl.MonoCertificate;
+                               return X509Helper2.GetMonoCertificate (this);
                        }
                }
 
index 234d0907f2dbcaedf74a722b331e2083aaebf8af..38797d55fcee583b75ca47f09158b8dea078a3dd 100644 (file)
@@ -71,6 +71,10 @@ namespace System.Security.Cryptography.X509Certificates
                        get;
                }
 
+               internal abstract X509Certificate2Impl FallbackImpl {
+                       get;
+               }
+
                public abstract string GetNameInfo (X509NameType nameType, bool forIssuer);
 
                public abstract void Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags);
index cdc14c49eb13e2d2479c961ce8e9a4a4243ce484..ff2449906de7c2f8a45bb405397aed669f6e557e 100644 (file)
@@ -52,7 +52,6 @@ namespace System.Security.Cryptography.X509Certificates
        {
                bool _archived;
                X509ExtensionCollection _extensions;
-               string _serial;
                PublicKey _publicKey;
                X500DistinguishedName issuer_name;
                X500DistinguishedName subject_name;
@@ -483,6 +482,7 @@ namespace System.Security.Cryptography.X509Certificates
                [MonoTODO ("missing KeyStorageFlags support")]
                public override void Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
                {
+                       Reset ();
                        MX.X509Certificate cert = null;
                        if (password == null) {
                                try {
@@ -558,7 +558,6 @@ namespace System.Security.Cryptography.X509Certificates
                        _cert = null;
                        _archived = false;
                        _extensions = null;
-                       _serial = null;
                        _publicKey = null;
                        issuer_name = null;
                        subject_name = null;
@@ -718,6 +717,10 @@ namespace System.Security.Cryptography.X509Certificates
                internal MX.X509Certificate MonoCertificate {
                        get { return _cert; }
                }
+
+               internal override X509Certificate2Impl FallbackImpl {
+                       get { return this; }
+               }
        }
 }
 
index 0ea1c8e9b06ab45d4c27b716de5b7fcdea4c1e4b..a3323c8ef0c4b7d15a57dc0220289d54a6c58296 100644 (file)
@@ -47,8 +47,6 @@ namespace System.Security.Cryptography.X509Certificates {
 
                X509ChainImpl impl;
 
-               static X509ChainStatus[] Empty = new X509ChainStatus [0];
-
                internal X509ChainImpl Impl {
                        get {
                                X509Helper2.ThrowIfContextInvalid (impl);
index 337dcaf9ed2dfa175757a106f15ec849a087f06e..9bbe99f86314cd4eb7e1eafbb667171e3133e079 100644 (file)
@@ -33,10 +33,12 @@ extern alias MonoSecurity;
 
 #if MONO_SECURITY_ALIAS
 using MonoSecurity::Mono.Security.Interface;
+using MX = MonoSecurity::Mono.Security.X509;
 #else
 #if !FEATURE_NO_BSD_SOCKETS
 using Mono.Security.Interface;
 #endif
+using MX = Mono.Security.X509;
 #endif
 
 #if !FEATURE_NO_BSD_SOCKETS
@@ -122,13 +124,15 @@ namespace System.Security.Cryptography.X509Certificates
                }
 #endif // !FEATURE_NO_BSD_SOCKETS
 
-               internal static X509Certificate2Impl Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
+               internal static X509Certificate2Impl Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags, bool disableProvider = false)
                {
 #if !FEATURE_NO_BSD_SOCKETS
-                       var provider = MonoTlsProviderFactory.GetProvider ();
-                       if (provider.HasNativeCertificates) {
-                               var impl = provider.GetNativeCertificate (rawData, password, keyStorageFlags);
-                               return impl;
+                       if (!disableProvider) {
+                               var provider = MonoTlsProviderFactory.GetProvider ();
+                               if (provider.HasNativeCertificates) {
+                                       var impl = provider.GetNativeCertificate (rawData, password, keyStorageFlags);
+                                       return impl;
+                               }
                        }
 #endif // FEATURE_NO_BSD_SOCKETS
                        var impl2 = new X509Certificate2ImplMono ();
@@ -136,13 +140,15 @@ namespace System.Security.Cryptography.X509Certificates
                        return impl2;
                }
 
-               internal static X509Certificate2Impl Import (X509Certificate cert)
+               internal static X509Certificate2Impl Import (X509Certificate cert, bool disableProvider = false)
                {
 #if !FEATURE_NO_BSD_SOCKETS
-                       var provider = MonoTlsProviderFactory.GetProvider ();
-                       if (provider.HasNativeCertificates) {
-                               var impl = provider.GetNativeCertificate (cert);
-                               return impl;
+                       if (!disableProvider) {
+                               var provider = MonoTlsProviderFactory.GetProvider ();
+                               if (provider.HasNativeCertificates) {
+                                       var impl = provider.GetNativeCertificate (cert);
+                                       return impl;
+                               }
                        }
 #endif // FEATURE_NO_BSD_SOCKETS
                        var impl2 = cert.Impl as X509Certificate2Impl;
@@ -151,6 +157,27 @@ namespace System.Security.Cryptography.X509Certificates
                        return Import (cert.GetRawCertData (), null, X509KeyStorageFlags.DefaultKeySet);
                }
 
+               /*
+                * This is used by X509ChainImplMono
+                * 
+                * Some of the missing APIs such as X509v3 extensions can be added to the native
+                * BTLS implementation.
+                * 
+                * We should also consider replacing X509ChainImplMono with a new X509ChainImplBtls
+                * at some point.
+                */
+               [MonoTODO ("Investigate replacement; see comments in source.")]
+               internal static MX.X509Certificate GetMonoCertificate (X509Certificate2 certificate)
+               {
+                       var impl2 = certificate.Impl as X509Certificate2Impl;
+                       if (impl2 == null)
+                               impl2 = Import (certificate, true);
+                       var fallbackImpl = impl2.FallbackImpl as X509Certificate2ImplMono;
+                       if (fallbackImpl == null)
+                               throw new NotSupportedException ();
+                       return fallbackImpl.MonoCertificate;
+               }
+
                internal static X509ChainImpl CreateChainImpl (bool useMachineContext)
                {
                        return new X509ChainImplMono (useMachineContext);
index eca011f5bae7492477124fe6e7ff515c19d7c35a..a2128834812f8a7f1b346c9508abb42722192359 100644 (file)
@@ -161,7 +161,7 @@ System.Diagnostics/TraceImpl.cs
 System.Diagnostics/TraceSourceInfo.cs
 System.Diagnostics/Win32EventLog.cs
 System/Platform.cs
-System/MonoExeLocator.cs
+System/MonoToolsLocator.cs
 System.IO.Compression/CompressionLevel.cs
 System.IO.Compression/CompressionMode.cs
 System.IO.Compression/DeflateStream.cs
@@ -375,36 +375,11 @@ System.Net/ServicePointManager.extra.cs
 System.Net/SimpleAsyncResult.cs
 System.Net/SocketPermissionAttribute.cs
 System.Net/SocketPermission.cs
-../referencesource/System/net/System/Net/Sockets/AddressFamily.cs
-../referencesource/System/net/System/Net/Sockets/IOControlCode.cs
-../referencesource/System/net/System/Net/Sockets/IPPacketInformation.cs
-../referencesource/System/net/System/Net/Sockets/LingerOption.cs
-../referencesource/System/net/System/Net/Sockets/MulticastOption.cs
-../referencesource/System/net/System/Net/Sockets/ProtocolFamily.cs
-../referencesource/System/net/System/Net/Sockets/ProtocolType.cs
 System.Net.Sockets/SafeSocketHandle.cs
-../referencesource/System/net/System/Net/Sockets/SelectMode.cs
-System.Net.Sockets/SendPacketsElement.cs
 System.Net.Sockets/Socket.cs
-../referencesource/System/net/System/Net/Sockets/Socket.cs
 System.Net.Sockets/SocketAsyncEventArgs.cs
-System.Net.Sockets/SocketAsyncOperation.cs
 System.Net.Sockets/SocketAsyncResult.cs
-../referencesource/System/net/System/Net/Sockets/SocketErrors.cs
-../referencesource/System/net/System/Net/SocketException.cs
-../referencesource/System/net/System/Net/Sockets/SocketFlags.cs
-../referencesource/System/net/System/Net/Sockets/SocketInformation.cs
-../referencesource/System/net/System/Net/Sockets/SocketInformationOptions.cs
 System.Net.Sockets/SocketOperation.cs
-../referencesource/System/net/System/Net/Sockets/SocketOptionLevel.cs
-../referencesource/System/net/System/Net/Sockets/SocketOptionName.cs
-../referencesource/System/net/System/Net/Sockets/SocketShutdown.cs
-../referencesource/System/net/System/Net/Sockets/SocketType.cs
-System.Net.Sockets/TcpClient.cs
-System.Net.Sockets/TcpListener.cs
-../referencesource/System/net/System/Net/Sockets/TransmitFileFlags.cs
-System.Net.Sockets/UdpClient.cs
-../referencesource/System/net/System/Net/Sockets/UdpReceiveResult.cs
 System.Net/WebAsyncResult.cs
 System.Net/WebConnection.cs
 System.Net/WebConnectionData.cs
@@ -1053,6 +1028,7 @@ ReferenceSources/Win32Exception.cs
 ../referencesource/System/net/System/Net/UnicodeEncodingConformance.cs
 ../referencesource/System/net/System/Net/ServicePointManager.cs
 ../referencesource/System/net/System/Net/SocketAddress.cs
+../referencesource/System/net/System/Net/SocketException.cs
 ../referencesource/System/net/System/Net/webclient.cs
 ../referencesource/System/net/System/Net/WebException.cs
 ../referencesource/System/net/System/Net/WebExceptionStatus.cs
@@ -1072,8 +1048,30 @@ ReferenceSources/Win32Exception.cs
 
 ../referencesource/System/net/System/Net/Configuration/DefaultProxySection.cs
 
+../referencesource/System/net/System/Net/Sockets/AddressFamily.cs
+../referencesource/System/net/System/Net/Sockets/IOControlCode.cs
+../referencesource/System/net/System/Net/Sockets/IPPacketInformation.cs
 ../referencesource/System/net/System/Net/Sockets/IPProtectionLevel.cs
+../referencesource/System/net/System/Net/Sockets/LingerOption.cs
+../referencesource/System/net/System/Net/Sockets/MulticastOption.cs
 ../referencesource/System/net/System/Net/Sockets/NetworkStream.cs
+../referencesource/System/net/System/Net/Sockets/ProtocolFamily.cs
+../referencesource/System/net/System/Net/Sockets/ProtocolType.cs
+../referencesource/System/net/System/Net/Sockets/SelectMode.cs
+../referencesource/System/net/System/Net/Sockets/Socket.cs
+../referencesource/System/net/System/Net/Sockets/SocketErrors.cs
+../referencesource/System/net/System/Net/Sockets/SocketFlags.cs
+../referencesource/System/net/System/Net/Sockets/SocketInformation.cs
+../referencesource/System/net/System/Net/Sockets/SocketInformationOptions.cs
+../referencesource/System/net/System/Net/Sockets/SocketOptionLevel.cs
+../referencesource/System/net/System/Net/Sockets/SocketOptionName.cs
+../referencesource/System/net/System/Net/Sockets/SocketShutdown.cs
+../referencesource/System/net/System/Net/Sockets/SocketType.cs
+../referencesource/System/net/System/Net/Sockets/TCPClient.cs
+../referencesource/System/net/System/Net/Sockets/TCPListener.cs
+../referencesource/System/net/System/Net/Sockets/TransmitFileFlags.cs
+../referencesource/System/net/System/Net/Sockets/UdpReceiveResult.cs
+../referencesource/System/net/System/Net/Sockets/UDPClient.cs
 
 ../referencesource/System/net/System/Net/NetworkInformation/DuplicateAddressDetectionState.cs
 ../referencesource/System/net/System/Net/NetworkInformation/GatewayIPAddressInformation.cs
@@ -1107,7 +1105,6 @@ ReferenceSources/Win32Exception.cs
 ../referencesource/System/net/System/Net/NetworkInformation/SystemGatewayIPAddressInformation.cs
 ../referencesource/System/net/System/Net/NetworkInformation/SystemIPAddressInformation.cs
 ../referencesource/System/net/System/Net/NetworkInformation/SystemMulticastIPAddressInformation.cs
-../referencesource/System/net/System/Net/NetworkInformation/SystemUnicastIPAddressInformation.cs
 ../referencesource/System/net/System/Net/NetworkInformation/SystemTcpConnection.cs
 ../referencesource/System/net/System/Net/NetworkInformation/TcpConnection.cs
 ../referencesource/System/net/System/Net/NetworkInformation/TcpState.cs
diff --git a/mcs/class/System/System/MonoExeLocator.cs b/mcs/class/System/System/MonoExeLocator.cs
deleted file mode 100755 (executable)
index 4ab1b33..0000000
+++ /dev/null
@@ -1,85 +0,0 @@
-#if !MOBILE
-
-using System.Diagnostics;
-using System.IO;
-using System.Reflection;
-using System.Runtime.InteropServices;
-
-namespace System {
-
-       static class MonoToolsLocator
-       {
-               public static readonly string Mono;
-               public static readonly string CSharpCompiler;
-               public static readonly string VBCompiler;
-               public static readonly string AssemblyLinker;
-
-               // TODO: Should be lazy
-               static MonoToolsLocator ()
-               {
-                       var gac = typeof (Environment).GetProperty ("GacPath", BindingFlags.Static | BindingFlags.NonPublic);
-                       var getGacMethod = gac.GetGetMethod (true);
-                       var GacPath = Path.GetDirectoryName ((string) getGacMethod.Invoke (null, null));
-
-                       if (Path.DirectorySeparatorChar == '\\') {
-                               string processExe = Process.GetCurrentProcess ().MainModule.FileName;
-                               if (processExe != null) {
-                                       string fileName = Path.GetFileName (processExe);
-                                       if (fileName.StartsWith ("mono") && fileName.EndsWith (".exe"))
-                                               Mono = processExe;
-                               }
-
-                               if (!File.Exists (Mono))
-                                       Mono = Path.Combine (
-                                               Path.GetDirectoryName (
-                                                       Path.GetDirectoryName (GacPath)),
-                                               "bin\\mono.exe");
-
-                               if (!File.Exists (Mono))
-                                       Mono = Path.Combine (
-                                               Path.GetDirectoryName (
-                                                       Path.GetDirectoryName (
-                                                               Path.GetDirectoryName (GacPath))),
-                                               "mono\\mini\\mono.exe");
-
-                               //if (!File.Exists (Mono))
-                               //      throw new FileNotFoundException ("Windows mono path not found: " + Mono);
-
-                               CSharpCompiler = Path.Combine (GacPath, "4.5\\mcs.exe");
-                               if (!File.Exists (CSharpCompiler))
-                                       CSharpCompiler = Path.Combine (Path.GetDirectoryName (GacPath), "lib\\build\\mcs.exe");
-
-                               //if (!File.Exists (CSharpCompiler))
-                               //      throw new FileNotFoundException ("C# compiler not found at " + CSharpCompiler);
-
-                               VBCompiler = Path.Combine (GacPath,  "4.5\\vbnc.exe");
-                               AssemblyLinker = Path.Combine (GacPath, "4.5\\al.exe");
-
-                               if (!File.Exists (AssemblyLinker)) {
-                                       AssemblyLinker = Path.Combine (Path.GetDirectoryName (GacPath), "lib\\net_4_x\\al.exe");
-                               //      if (!File.Exists (AssemblyLinker))
-                               //              throw new FileNotFoundException ("Windows al path not found: " + AssemblyLinker);
-                               }
-                       } else {
-                               Mono = Path.Combine (GacPath, "bin", "mono");
-                               if (!File.Exists (Mono))
-                                       Mono = "mono";
-
-                               var mscorlibPath = new Uri (typeof (object).Assembly.CodeBase).LocalPath;
-                               CSharpCompiler = Path.GetFullPath (Path.Combine (mscorlibPath, "..", "..", "..", "..", "bin", "mcs"));
-                               if (!File.Exists (CSharpCompiler))
-                                       CSharpCompiler = "mcs";
-
-                               VBCompiler = Path.GetFullPath (Path.Combine (mscorlibPath, "..", "..", "..", "..", "bin", "vbnc"));
-                               if (!File.Exists (VBCompiler))
-                                       VBCompiler = "vbnc";
-
-                               AssemblyLinker = Path.GetFullPath (Path.Combine (mscorlibPath, "..", "..", "..", "..", "bin", "al"));
-                               if (!File.Exists (AssemblyLinker))
-                                       AssemblyLinker = "al";
-                       }
-               }
-       }
-}
-
-#endif
diff --git a/mcs/class/System/System/MonoToolsLocator.cs b/mcs/class/System/System/MonoToolsLocator.cs
new file mode 100755 (executable)
index 0000000..5443395
--- /dev/null
@@ -0,0 +1,96 @@
+#if !MOBILE
+
+using System.Diagnostics;
+using System.IO;
+using System.Reflection;
+using System.Runtime.InteropServices;
+using System.Text;
+
+namespace System {
+
+       static class MonoToolsLocator
+       {
+               public static readonly string Mono;
+               public static readonly string CSharpCompiler;
+               public static readonly string VBCompiler;
+               public static readonly string AssemblyLinker;
+
+               // TODO: Should be lazy
+               static MonoToolsLocator ()
+               {
+                       var gac = typeof (Environment).GetProperty ("GacPath", BindingFlags.Static | BindingFlags.NonPublic);
+                       var getGacMethod = gac.GetGetMethod (true);
+                       var GacPath = Path.GetDirectoryName ((string) getGacMethod.Invoke (null, null));
+
+                       if (Path.DirectorySeparatorChar == '\\') {
+                               StringBuilder moduleName = new StringBuilder (1024);
+                               GetModuleFileName (IntPtr.Zero, moduleName, moduleName.Capacity);
+                               string processExe = moduleName.ToString ();
+                               string fileName = Path.GetFileName (processExe);
+                               if (fileName.StartsWith ("mono") && fileName.EndsWith (".exe"))
+                                       Mono = processExe;
+
+                               if (!File.Exists (Mono))
+                                       Mono = Path.Combine (
+                                               Path.GetDirectoryName (
+                                                       Path.GetDirectoryName (GacPath)),
+                                               "bin\\mono.exe");
+
+                               if (!File.Exists (Mono))
+                                       Mono = Path.Combine (
+                                               Path.GetDirectoryName (
+                                                       Path.GetDirectoryName (
+                                                               Path.GetDirectoryName (GacPath))),
+                                               "mono\\mini\\mono.exe");
+
+                               //if (!File.Exists (Mono))
+                               //      throw new FileNotFoundException ("Windows mono path not found: " + Mono);
+
+                               CSharpCompiler = Path.Combine (GacPath, "4.5\\mcs.exe");
+                               if (!File.Exists (CSharpCompiler))
+                                       CSharpCompiler = Path.Combine (Path.GetDirectoryName (GacPath), "lib\\build\\mcs.exe");
+
+                               //if (!File.Exists (CSharpCompiler))
+                               //      throw new FileNotFoundException ("C# compiler not found at " + CSharpCompiler);
+
+                               VBCompiler = Path.Combine (GacPath,  "4.5\\vbnc.exe");
+                               AssemblyLinker = Path.Combine (GacPath, "4.5\\al.exe");
+
+                               if (!File.Exists (AssemblyLinker)) {
+                                       AssemblyLinker = Path.Combine (Path.GetDirectoryName (GacPath), "lib\\net_4_x\\al.exe");
+                               //      if (!File.Exists (AssemblyLinker))
+                               //              throw new FileNotFoundException ("Windows al path not found: " + AssemblyLinker);
+                               }
+                       } else {
+                               Mono = Path.Combine (GacPath, "bin", "mono");
+                               if (!File.Exists (Mono))
+                                       Mono = "mono";
+
+                               var mscorlibPath = new Uri (typeof (object).Assembly.CodeBase).LocalPath;
+                               CSharpCompiler = Path.GetFullPath (Path.Combine (mscorlibPath, "..", "..", "..", "..", "bin", "mcs"));
+                               if (!File.Exists (CSharpCompiler))
+                                       CSharpCompiler = "mcs";
+
+                               VBCompiler = Path.GetFullPath (Path.Combine (mscorlibPath, "..", "..", "..", "..", "bin", "vbnc"));
+                               if (!File.Exists (VBCompiler))
+                                       VBCompiler = "vbnc";
+
+                               AssemblyLinker = Path.GetFullPath (Path.Combine (mscorlibPath, "..", "..", "..", "..", "bin", "al"));
+                               if (!File.Exists (AssemblyLinker))
+                                       AssemblyLinker = "al";
+                       }
+               }
+
+               // Due to an issue with shadow copying  and app domains in mono, we cannot currently use 
+               // Process.GetCurrentProcess ().MainModule.FileName (which would give the same result)
+               // when running in an AppDomain (eg System.Web hosts).
+               //
+               // Using native Windows API to get current process filename. This will only
+               // be called when running on Windows. 
+               [DllImport ("kernel32.dll")]
+               static extern uint GetModuleFileName ([In] IntPtr hModule, [Out] StringBuilder lpFilename, [In] int nSize);
+
+       }
+}
+
+#endif
index f0c29764ae9ec6f78d5dae84a80e76e902e4cf70..935aa77bcdf7e46f7d4ca959825931f219cebf6b 100644 (file)
@@ -247,6 +247,25 @@ namespace MonoTests.System.Net.Sockets {
                        SocketAsyncEventArgsPoker saea = new SocketAsyncEventArgsPoker ();
                        saea.OnCompleted_ (null);
                }
+
+               [Test]
+               public void TransparentDispose ()
+               {
+                       var buffer = new byte[5];
+                       var elements = new SendPacketsElement[2];
+                       var utoken = new object();
+
+                       var saea = new SocketAsyncEventArgs();
+                       saea.SetBuffer(buffer, 0, 3);
+                       saea.SendPacketsElements = elements;
+                       saea.UserToken = utoken;
+
+                       saea.Dispose();
+
+                       Assert.AreEqual (buffer, saea.Buffer);
+                       Assert.AreEqual (elements, saea.SendPacketsElements);
+                       Assert.AreEqual (utoken, saea.UserToken);
+               }
        }
 }
 
index 5db3aadbc877713b962285ddcde3e66e83293cde..a9e849fc1e77d0e9e4aec3513ee0f37c1e345b4a 100644 (file)
@@ -173,7 +173,7 @@ namespace MonoTests.System.Net.Sockets
                                client.Connect (ipAddresses, 1234);
                                Assert.Fail ("ConnectMultiAny #1");
                        } catch (SocketException ex) {
-                               Assert.AreEqual (10049, ex.ErrorCode, "ConnectMultiAny #2");
+                               Assert.AreEqual (10061, ex.ErrorCode, "ConnectMultiAny #2");
                        } catch {
                                Assert.Fail ("ConnectMultiAny #3");
                        }
index 996da16f5cc0009ee0b3a56b4e6334812ba89508..33dc4464c86d89bbb0cfedb032c25c3ebf2e7b85 100644 (file)
@@ -558,25 +558,15 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // JoinMulticastGroup (IPAddress)
-               [Category ("NotWorking")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void JoinMulticastGroup1_Socket_NotBound ()
                {
                        IPAddress mcast_addr = IPAddress.Parse ("224.0.0.23");
 
-                       UdpClient client = new UdpClient (AddressFamily.InterNetwork);
-                       try {
+                       using (UdpClient client = new UdpClient (AddressFamily.InterNetwork)) {
                                client.JoinMulticastGroup (mcast_addr);
-                               Assert.Fail ("#1");
-                       } catch (SocketException ex) {
-                               // An invalid argument was supplied
-                               Assert.AreEqual (typeof (SocketException), ex.GetType (), "#2");
-                               Assert.AreEqual (10022, ex.ErrorCode, "#3");
-                               Assert.IsNull (ex.InnerException, "#4");
-                               Assert.IsNotNull (ex.Message, "#5");
-                               Assert.AreEqual (10022, ex.NativeErrorCode, "#6");
-                               Assert.AreEqual (SocketError.InvalidArgument, ex.SocketErrorCode, "#7");
-                       } finally {
-                               client.Close ();
                        }
                }
 
@@ -666,25 +656,15 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // JoinMulticastGroup (Int32, IPAddress)
-               [Category ("NotWorking")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void JoinMulticastGroup2_Socket_NotBound ()
                {
                        IPAddress mcast_addr = IPAddress.Parse ("ff02::1");
 
-                       UdpClient client = new UdpClient (AddressFamily.InterNetworkV6);
-                       try {
+                       using (UdpClient client = new UdpClient (AddressFamily.InterNetworkV6)) {
                                client.JoinMulticastGroup (0, mcast_addr);
-                               Assert.Fail ("#1");
-                       } catch (SocketException ex) {
-                               // An invalid argument was supplied
-                               Assert.AreEqual (typeof (SocketException), ex.GetType (), "#2");
-                               Assert.AreEqual (10022, ex.ErrorCode, "#3");
-                               Assert.IsNull (ex.InnerException, "#4");
-                               Assert.IsNotNull (ex.Message, "#5");
-                               Assert.AreEqual (10022, ex.NativeErrorCode, "#6");
-                               Assert.AreEqual (SocketError.InvalidArgument, ex.SocketErrorCode, "#7");
-                       } finally {
-                               client.Close ();
                        }
                }
 
@@ -767,25 +747,15 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // JoinMulticastGroup (IPAddress, Int32)
-               [Category ("NotWorking")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void JoinMulticastGroup3_Socket_NotBound ()
                {
                        IPAddress mcast_addr = IPAddress.Parse ("224.0.0.23");
 
-                       UdpClient client = new UdpClient (AddressFamily.InterNetwork);
-                       try {
+                       using (UdpClient client = new UdpClient (AddressFamily.InterNetwork)) {
                                client.JoinMulticastGroup (mcast_addr, 5);
-                               Assert.Fail ("#1");
-                       } catch (SocketException ex) {
-                               // An invalid argument was supplied
-                               Assert.AreEqual (typeof (SocketException), ex.GetType (), "#2");
-                               Assert.AreEqual (10022, ex.ErrorCode, "#3");
-                               Assert.IsNull (ex.InnerException, "#4");
-                               Assert.IsNotNull (ex.Message, "#5");
-                               Assert.AreEqual (10022, ex.NativeErrorCode, "#6");
-                               Assert.AreEqual (SocketError.InvalidArgument, ex.SocketErrorCode, "#7");
-                       } finally {
-                               client.Close ();
                        }
                }
 
@@ -896,26 +866,16 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // JoinMulticastGroup (IPAddress, IPAddress)
-               [Category ("NotWorking")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void JoinMulticastGroup4_Socket_NotBound ()
                {
                        IPAddress mcast_addr = IPAddress.Parse ("224.0.0.23");
                        IPAddress local_addr = Dns.GetHostEntry (string.Empty).AddressList [0];
 
-                       UdpClient client = new UdpClient (AddressFamily.InterNetwork);
-                       try {
+                       using (UdpClient client = new UdpClient (AddressFamily.InterNetwork)) {
                                client.JoinMulticastGroup (mcast_addr, local_addr);
-                               Assert.Fail ("#1");
-                       } catch (SocketException ex) {
-                               // An invalid argument was supplied
-                               Assert.AreEqual (typeof (SocketException), ex.GetType (), "#2");
-                               Assert.AreEqual (10022, ex.ErrorCode, "#3");
-                               Assert.IsNull (ex.InnerException, "#4");
-                               Assert.IsNotNull (ex.Message, "#5");
-                               Assert.AreEqual (10022, ex.NativeErrorCode, "#6");
-                               Assert.AreEqual (SocketError.InvalidArgument, ex.SocketErrorCode, "#7");
-                       } finally {
-                               client.Close ();
                        }
                }
 
index 8143edd7571492b7566dc025ffe0a8e076be7c69..771d5d1fb6ae4cf35c3e05db8b41a44cb6175435 100644 (file)
@@ -231,11 +231,28 @@ namespace MonoTests.System.Net
 #if FEATURE_NO_BSD_SOCKETS
                [ExpectedException (typeof (PlatformNotSupportedException))]
 #endif
-               public void UploadFile1 ()
+               public void UploadFile1_v4 ()
                {
-                       ServerPut sp = new ServerPut ();
+                       UploadFile1 (false);
+               }
+
+               [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
+               public void UploadFile1_v6 ()
+               {
+                       if (!Socket.OSSupportsIPv6)
+                               Assert.Ignore ("IPv6 not supported.");
+
+                       UploadFile1 (true);
+               }
+
+               void UploadFile1 (bool ipv6)
+               {
+                       ServerPut sp = new ServerPut (ipv6);
                        sp.Start ();
-                       string uri = String.Format ("ftp://{0}:{1}/uploads/file.txt", sp.IPAddress, sp.Port);
+                       string uri = String.Format ("ftp://{0}:{1}/uploads/file.txt", EncloseIPv6 (sp.IPAddress), sp.Port);
                        try {
                                FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
                                ftp.KeepAlive = false;
@@ -264,15 +281,32 @@ namespace MonoTests.System.Net
 #if FEATURE_NO_BSD_SOCKETS
                [ExpectedException (typeof (PlatformNotSupportedException))]
 #endif
-               public void UploadFile_WebClient ()
+               public void UploadFile_WebClient_v4 ()
+               {
+                       UploadFile_WebClient (false);
+               }
+
+               [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
+               public void UploadFile_WebClient_v6 ()
+               {
+                       if (!Socket.OSSupportsIPv6)
+                               Assert.Ignore ("IPv6 not supported.");
+
+                       UploadFile_WebClient (true);
+               }
+
+               public void UploadFile_WebClient (bool ipv6)
                {
-                       ServerPut sp = new ServerPut ();
+                       ServerPut sp = new ServerPut (ipv6);
                        File.WriteAllText (_tempFile, "0123456789");
                        sp.Start ();
 
                        using (WebClient m_WebClient = new WebClient())
                        {
-                               string uri = String.Format ("ftp://{0}:{1}/uploads/file.txt", sp.IPAddress, sp.Port);
+                               string uri = String.Format ("ftp://{0}:{1}/uploads/file.txt", EncloseIPv6 (sp.IPAddress), sp.Port);
                                
                                m_WebClient.UploadFile(uri, _tempFile);
                        }
@@ -285,15 +319,27 @@ namespace MonoTests.System.Net
 #if FEATURE_NO_BSD_SOCKETS
                [ExpectedException (typeof (PlatformNotSupportedException))]
 #endif
-               public void DownloadFile1 ()
+               public void DownloadFile1_v4 ()
                {
-                       DownloadFile (new ServerDownload ());
+                       DownloadFile (new ServerDownload (false));
+               }
+
+               [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
+               public void DownloadFile1_v6 ()
+               {
+                       if (!Socket.OSSupportsIPv6)
+                               Assert.Ignore ("IPv6 not supported.");
+
+                       DownloadFile (new ServerDownload (true));
                }
 
                void DownloadFile (ServerDownload sp)
                {
                        sp.Start ();
-                       string uri = String.Format ("ftp://{0}:{1}/file.txt", sp.IPAddress, sp.Port);
+                       string uri = String.Format ("ftp://{0}:{1}/file.txt", EncloseIPv6 (sp.IPAddress), sp.Port);
                        try {
                                FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
                                ftp.KeepAlive = false;
@@ -320,22 +366,50 @@ namespace MonoTests.System.Net
 #if FEATURE_NO_BSD_SOCKETS
                [ExpectedException (typeof (PlatformNotSupportedException))]
 #endif
-               public void DownloadFile2 ()
+               public void DownloadFile2_v4 ()
                {
                        // Some embedded FTP servers in Industrial Automation Hardware report
                        // the PWD using backslashes, but allow forward slashes for CWD.
-                       DownloadFile (new ServerDownload (@"\Users\someuser", "/Users/someuser/"));
+                       DownloadFile (new ServerDownload (@"\Users\someuser", "/Users/someuser/", false));
+               }
+
+               [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
+               public void DownloadFile2_v6 ()
+               {
+                       // Some embedded FTP servers in Industrial Automation Hardware report
+                       // the PWD using backslashes, but allow forward slashes for CWD.
+                       DownloadFile (new ServerDownload (@"\Users\someuser", "/Users/someuser/", true));
+               }
+
+               [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
+               public void DeleteFile1_v4 ()
+               {
+                       DeleteFile1 (false);
                }
 
                [Test]
 #if FEATURE_NO_BSD_SOCKETS
                [ExpectedException (typeof (PlatformNotSupportedException))]
 #endif
-               public void DeleteFile1 ()
+               public void DeleteFile1_v6 ()
                {
-                       ServerDeleteFile sp = new ServerDeleteFile ();
+                       if (!Socket.OSSupportsIPv6)
+                               Assert.Ignore ("IPv6 not supported.");
+
+                       DeleteFile1 (true);
+               }
+
+               void DeleteFile1 (bool ipv6)
+               {
+                       ServerDeleteFile sp = new ServerDeleteFile (ipv6);
                        sp.Start ();
-                       string uri = String.Format ("ftp://{0}:{1}/file.txt", sp.IPAddress, sp.Port);
+                       string uri = String.Format ("ftp://{0}:{1}/file.txt", EncloseIPv6 (sp.IPAddress), sp.Port);
                        try {
                                FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
                                Console.WriteLine (ftp.RequestUri);
@@ -360,11 +434,28 @@ namespace MonoTests.System.Net
 #if FEATURE_NO_BSD_SOCKETS
                [ExpectedException (typeof (PlatformNotSupportedException))]
 #endif
-               public void ListDirectory1 ()
+               public void ListDirectory1_v4 ()
+               {
+                       ListDirectory1 (false);
+               }
+
+               [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
+               public void ListDirectory1_v6 ()
                {
-                       ServerListDirectory sp = new ServerListDirectory ();
+                       if (!Socket.OSSupportsIPv6)
+                               Assert.Ignore ("IPv6 not supported.");
+
+                       ListDirectory1 (true);
+               }
+
+               void ListDirectory1 (bool ipv6)
+               {
+                       ServerListDirectory sp = new ServerListDirectory (ipv6);
                        sp.Start ();
-                       string uri = String.Format ("ftp://{0}:{1}/somedir/", sp.IPAddress, sp.Port);
+                       string uri = String.Format ("ftp://{0}:{1}/somedir/", EncloseIPv6 (sp.IPAddress), sp.Port);
                        try {
                                FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
                                Console.WriteLine (ftp.RequestUri);
@@ -387,7 +478,20 @@ namespace MonoTests.System.Net
                        }
                }
 
+               string EncloseIPv6 (IPAddress address)
+               {
+                       if (address.AddressFamily == AddressFamily.InterNetwork)
+                               return address.ToString ();
+                       
+                       return String.Format ("[{0}]", address.ToString ());
+               }
+
                class ServerListDirectory : FtpServer {
+                       public ServerListDirectory (bool ipv6)
+                               : base (ipv6)
+                       {
+                       }
+
                        protected override void Run ()
                        {
                                Socket client = control.Accept ();
@@ -405,24 +509,12 @@ namespace MonoTests.System.Net
                                }
 
                                string str = reader.ReadLine ();
-                               if (str != "PASV") {
-                                       Where = "PASV";
+                               string resp = FormatPassiveResponse (str);
+                               if (resp == null) {
                                        client.Close ();
                                        return;
                                }
-
-                               IPEndPoint end_data = (IPEndPoint) data.LocalEndPoint;
-                               byte [] addr_bytes = end_data.Address.GetAddressBytes ();
-                               byte [] port = new byte [2];
-                               port[0] = (byte) ((end_data.Port >> 8) & 255);
-                               port[1] = (byte) (end_data.Port & 255);
-                               StringBuilder sb = new StringBuilder ("227 Passive (");
-                               foreach (byte b in addr_bytes) {
-                                       sb.AppendFormat ("{0},", b);    
-                               }
-                               sb.AppendFormat ("{0},", port [0]);     
-                               sb.AppendFormat ("{0})", port [1]);     
-                               writer.WriteLine (sb.ToString ());
+                               writer.WriteLine (resp);
                                writer.Flush ();
 
                                str = reader.ReadLine ();
@@ -449,6 +541,11 @@ namespace MonoTests.System.Net
                }
 
                class ServerDeleteFile : FtpServer {
+                       public ServerDeleteFile (bool ipv6)
+                               : base (ipv6)
+                       {
+                       }
+
                        protected override void Run ()
                        {
                                Socket client = control.Accept ();
@@ -485,12 +582,13 @@ namespace MonoTests.System.Net
 
                        string Pwd, Cwd;
 
-                       public ServerDownload ()
-                               : this (null, null)
+                       public ServerDownload (bool ipv6)
+                               : this (null, null, ipv6)
                        {
                        }
 
-                       public ServerDownload (string pwd, string cwd)
+                       public ServerDownload (string pwd, string cwd, bool ipv6)
+                               : base (ipv6)
                        {
                                Pwd = pwd ?? "/home/someuser";
                                Cwd = cwd ?? "/home/someuser/";
@@ -513,24 +611,12 @@ namespace MonoTests.System.Net
                                }
 
                                string str = reader.ReadLine ();
-                               if (str != "PASV") {
-                                       Where = "PASV";
+                               string resp = FormatPassiveResponse (str);
+                               if (resp == null) {
                                        client.Close ();
                                        return;
                                }
-
-                               IPEndPoint end_data = (IPEndPoint) data.LocalEndPoint;
-                               byte [] addr_bytes = end_data.Address.GetAddressBytes ();
-                               byte [] port = new byte [2];
-                               port[0] = (byte) ((end_data.Port >> 8) & 255);
-                               port[1] = (byte) (end_data.Port & 255);
-                               StringBuilder sb = new StringBuilder ("227 Passive (");
-                               foreach (byte b in addr_bytes) {
-                                       sb.AppendFormat ("{0},", b);    
-                               }
-                               sb.AppendFormat ("{0},", port [0]);     
-                               sb.AppendFormat ("{0})", port [1]);     
-                               writer.WriteLine (sb.ToString ());
+                               writer.WriteLine (resp);
                                writer.Flush ();
 
                                str = reader.ReadLine ();
@@ -559,6 +645,11 @@ namespace MonoTests.System.Net
                class ServerPut : FtpServer {
                        public List<byte> result = new List<byte> ();
                        
+                       public ServerPut (bool ipv6)
+                               : base (ipv6)
+                       {
+                       }
+
                        protected override void Run ()
                        {
                                Socket client = control.Accept ();
@@ -576,24 +667,12 @@ namespace MonoTests.System.Net
                                }
 
                                string str = reader.ReadLine ();
-                               if (str != "PASV") {
-                                       Where = "PASV";
+                               string resp = FormatPassiveResponse (str);
+                               if (resp == null) {
                                        client.Close ();
                                        return;
                                }
-
-                               IPEndPoint end_data = (IPEndPoint) data.LocalEndPoint;
-                               byte [] addr_bytes = end_data.Address.GetAddressBytes ();
-                               byte [] port = new byte [2];
-                               port[0] = (byte) ((end_data.Port >> 8) & 255);
-                               port[1] = (byte) (end_data.Port & 255);
-                               StringBuilder sb = new StringBuilder ("227 Passive (");
-                               foreach (byte b in addr_bytes) {
-                                       sb.AppendFormat ("{0},", b);    
-                               }
-                               sb.AppendFormat ("{0},", port [0]);     
-                               sb.AppendFormat ("{0})", port [1]);     
-                               writer.WriteLine (sb.ToString ());
+                               writer.WriteLine (resp);
                                writer.Flush ();
 
                                str = reader.ReadLine ();
@@ -627,16 +706,18 @@ namespace MonoTests.System.Net
                        protected Socket control;
                        protected Socket data;
                        protected ManualResetEvent evt;
+                       protected bool ipv6;
                        public string Where = "";
 
-                       public FtpServer ()
+                       public FtpServer (bool ipv6)
                        {
-                               control = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
-                               control.Bind (new IPEndPoint (IPAddress.Loopback, 0));
+                               control = new Socket (ipv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+                               control.Bind (new IPEndPoint (ipv6 ? IPAddress.IPv6Loopback : IPAddress.Loopback, 0));
                                control.Listen (1);
-                               data = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
-                               data.Bind (new IPEndPoint (IPAddress.Loopback, 0));
+                               data = new Socket (ipv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+                               data.Bind (new IPEndPoint (ipv6 ? IPAddress.IPv6Loopback : IPAddress.Loopback, 0));
                                data.Listen (1);
+                               this.ipv6 = ipv6;
                        }
 
                        public void Start ()
@@ -720,7 +801,39 @@ namespace MonoTests.System.Net
                                writer.Flush ();
                                return true;
                        }
-                       
+
+                       protected string FormatPassiveResponse (string request)
+                       {
+                               if (ipv6) {
+                                       if (request != "EPSV") {
+                                               Where = "EPSV";
+                                               return null;
+                                       }
+
+                                       IPEndPoint end_data = (IPEndPoint) data.LocalEndPoint;
+                                       return String.Format ("229 Extended Passive (|||{0}|)", end_data.Port);
+                               }
+                               else {
+                                       if (request != "PASV") {
+                                               Where = "PASV";
+                                               return null;
+                                       }
+
+                                       IPEndPoint end_data = (IPEndPoint) data.LocalEndPoint;
+                                       byte [] addr_bytes = end_data.Address.GetAddressBytes ();
+                                       byte [] port = new byte [2];
+                                       port[0] = (byte) ((end_data.Port >> 8) & 255);
+                                       port[1] = (byte) (end_data.Port & 255);
+                                       StringBuilder sb = new StringBuilder ("227 Passive (");
+                                       foreach (byte b in addr_bytes) {
+                                               sb.AppendFormat ("{0},", b);    
+                                       }
+                                       sb.AppendFormat ("{0},", port [0]);     
+                                       sb.AppendFormat ("{0})", port [1]);     
+                                       return sb.ToString ();
+                               }
+                       }
+
                        public IPAddress IPAddress {
                                get { return ((IPEndPoint) control.LocalEndPoint).Address; }
                        }
index 9b2e93b730cdb572d1d230c1da5f8566e66c9087..a39ac73d0afa0949dcd04172bdeae22851faef21 100644 (file)
@@ -312,6 +312,8 @@ namespace MonoTests.System
                        Assert.IsFalse (Uri.IsWellFormedUriString (null, UriKind.Absolute), "null");
                        Assert.IsFalse (Uri.IsWellFormedUriString ("data", UriKind.Absolute), "data");
                        Assert.IsTrue (Uri.IsWellFormedUriString ("http://www.go-mono.com/Main_Page#1", UriKind.Absolute), "http/hex");
+                       Assert.IsTrue (Uri.IsWellFormedUriString ("test", UriKind.RelativeOrAbsolute), "rel1");
+                       Assert.IsTrue (Uri.IsWellFormedUriString ("/test", UriKind.RelativeOrAbsolute), "rel2");
                }
 
                [Test]
index 8eb0ae99dc15857a48aee48b7ea09ff939e209fd..5224c4de657da210008dee056c6c4536a0e68aeb 100644 (file)
@@ -118,36 +118,11 @@ System.Net.Security/SslPolicyErrors.cs
 System.Net.Security/SslStream.cs
 System.Net/SocketPermissionAttribute.cs
 System.Net/SocketPermission.cs
-../referencesource/System/net/System/Net/Sockets/AddressFamily.cs
-../referencesource/System/net/System/Net/Sockets/IOControlCode.cs
-../referencesource/System/net/System/Net/Sockets/IPPacketInformation.cs
-../referencesource/System/net/System/Net/Sockets/LingerOption.cs
-../referencesource/System/net/System/Net/Sockets/MulticastOption.cs
-../referencesource/System/net/System/Net/Sockets/ProtocolFamily.cs
-../referencesource/System/net/System/Net/Sockets/ProtocolType.cs
 System.Net.Sockets/SafeSocketHandle.cs
-../referencesource/System/net/System/Net/Sockets/SelectMode.cs
-System.Net.Sockets/SendPacketsElement.cs
 System.Net.Sockets/Socket.cs
-../referencesource/System/net/System/Net/Sockets/Socket.cs
 System.Net.Sockets/SocketAsyncEventArgs.cs
-System.Net.Sockets/SocketAsyncOperation.cs
 System.Net.Sockets/SocketAsyncResult.cs
-../referencesource/System/net/System/Net/Sockets/SocketErrors.cs
-../referencesource/System/net/System/Net/SocketException.cs
-../referencesource/System/net/System/Net/Sockets/SocketFlags.cs
-../referencesource/System/net/System/Net/Sockets/SocketInformation.cs
-../referencesource/System/net/System/Net/Sockets/SocketInformationOptions.cs
 System.Net.Sockets/SocketOperation.cs
-../referencesource/System/net/System/Net/Sockets/SocketOptionLevel.cs
-../referencesource/System/net/System/Net/Sockets/SocketOptionName.cs
-../referencesource/System/net/System/Net/Sockets/SocketShutdown.cs
-../referencesource/System/net/System/Net/Sockets/SocketType.cs
-System.Net.Sockets/TcpClient.cs
-System.Net.Sockets/TcpListener.cs
-../referencesource/System/net/System/Net/Sockets/TransmitFileFlags.cs
-System.Net.Sockets/UdpClient.cs
-../referencesource/System/net/System/Net/Sockets/UdpReceiveResult.cs
 System.Net/AuthenticationManager.cs
 System.Net/BasicClient.cs
 System.Net/BindIPEndPoint.cs
@@ -786,6 +761,7 @@ ReferenceSources/Win32Exception.cs
 ../referencesource/System/net/System/Net/UnicodeEncodingConformance.cs
 ../referencesource/System/net/System/Net/ServicePointManager.cs
 ../referencesource/System/net/System/Net/SocketAddress.cs
+../referencesource/System/net/System/Net/SocketException.cs
 ../referencesource/System/net/System/Net/webclient.cs
 ../referencesource/System/net/System/Net/WebException.cs
 ../referencesource/System/net/System/Net/WebExceptionStatus.cs
@@ -805,8 +781,30 @@ ReferenceSources/Win32Exception.cs
 
 ../referencesource/System/net/System/Net/Configuration/DefaultProxySection.cs
 
+../referencesource/System/net/System/Net/Sockets/AddressFamily.cs
+../referencesource/System/net/System/Net/Sockets/IOControlCode.cs
+../referencesource/System/net/System/Net/Sockets/IPPacketInformation.cs
 ../referencesource/System/net/System/Net/Sockets/IPProtectionLevel.cs
+../referencesource/System/net/System/Net/Sockets/LingerOption.cs
+../referencesource/System/net/System/Net/Sockets/MulticastOption.cs
 ../referencesource/System/net/System/Net/Sockets/NetworkStream.cs
+../referencesource/System/net/System/Net/Sockets/ProtocolFamily.cs
+../referencesource/System/net/System/Net/Sockets/ProtocolType.cs
+../referencesource/System/net/System/Net/Sockets/SelectMode.cs
+../referencesource/System/net/System/Net/Sockets/Socket.cs
+../referencesource/System/net/System/Net/Sockets/SocketErrors.cs
+../referencesource/System/net/System/Net/Sockets/SocketFlags.cs
+../referencesource/System/net/System/Net/Sockets/SocketInformation.cs
+../referencesource/System/net/System/Net/Sockets/SocketInformationOptions.cs
+../referencesource/System/net/System/Net/Sockets/SocketOptionLevel.cs
+../referencesource/System/net/System/Net/Sockets/SocketOptionName.cs
+../referencesource/System/net/System/Net/Sockets/SocketShutdown.cs
+../referencesource/System/net/System/Net/Sockets/SocketType.cs
+../referencesource/System/net/System/Net/Sockets/TCPClient.cs
+../referencesource/System/net/System/Net/Sockets/TCPListener.cs
+../referencesource/System/net/System/Net/Sockets/TransmitFileFlags.cs
+../referencesource/System/net/System/Net/Sockets/UdpReceiveResult.cs
+../referencesource/System/net/System/Net/Sockets/UDPClient.cs
 
 ../referencesource/System/net/System/Net/NetworkInformation/DuplicateAddressDetectionState.cs
 ../referencesource/System/net/System/Net/NetworkInformation/GatewayIPAddressInformation.cs
@@ -840,7 +838,6 @@ ReferenceSources/Win32Exception.cs
 ../referencesource/System/net/System/Net/NetworkInformation/SystemGatewayIPAddressInformation.cs
 ../referencesource/System/net/System/Net/NetworkInformation/SystemIPAddressInformation.cs
 ../referencesource/System/net/System/Net/NetworkInformation/SystemMulticastIPAddressInformation.cs
-../referencesource/System/net/System/Net/NetworkInformation/SystemUnicastIPAddressInformation.cs
 ../referencesource/System/net/System/Net/NetworkInformation/SystemTcpConnection.cs
 ../referencesource/System/net/System/Net/NetworkInformation/TcpConnection.cs
 ../referencesource/System/net/System/Net/NetworkInformation/TcpState.cs
index 384223cfee9079dc93c988eb752e34520ad05dd2..1f1f61233b04f32ec4b5e7004d2673a8dd13f0d8 100644 (file)
@@ -111,7 +111,6 @@ System.Net.Mail/SmtpClient.cs
 System.Net.Security/SslStream.cs
 System.Net.Sockets/TcpClient.cs
 System.Net.Sockets/TcpListener.cs
-System.Net.Sockets/UdpClient.cs
 System.Net.WebSockets/ClientWebSocket.cs
 System.Net/AuthenticationManager.cs
 System.Net/ChunkedInputStream.cs
@@ -180,3 +179,6 @@ Mono.Btls/MonoBtlsX509VerifyFlags.cs
 Mono.Btls/MonoBtlsX509VerifyParam.cs
 Mono.Btls/X509CertificateImplBtls.cs
 Mono.Btls/X509ChainImplBtls.cs
+../referencesource/System/net/System/Net/Sockets/TCPClient.cs
+../referencesource/System/net/System/Net/Sockets/TCPListener.cs
+../referencesource/System/net/System/Net/Sockets/UDPClient.cs
old mode 100644 (file)
new mode 100755 (executable)
index e4b4ae1..002d592
@@ -404,7 +404,12 @@ namespace System.IO.Packaging {
                                throw new FileFormatException ("Stream length cannot be zero with FileMode.Open");
 
                        Stream s = File.Open (path, packageMode, packageAccess, packageShare);
-                       return Open (s, packageMode, packageAccess, true);
+                       try {
+                               return Open (s, packageMode, packageAccess, true);
+                       } catch {
+                               s.Close  ();
+                               throw;
+                       }
                }
 
                static Package OpenCore (Stream stream, FileMode packageMode, FileAccess packageAccess, bool ownsStream)
index e83008d4452c91ba8e6e4ffe00dc566eaba6f6e5..6fddadb2f9167de43dcc81e91ce1875d9548c3f6 100644 (file)
@@ -259,6 +259,7 @@ namespace MonoTests.System.Windows {
                }
 
                [Test]
+               [SetCulture ("en-us")]
                public void ToStringTest ()
                {
                        Rect r = new Rect (1.0, 2.5, 3, 4);
index f0a6e5c2ab68e58364251c20accbd8f2784cb8ca..c36c7ce5608ab796e4a659abf9e57fae4d39ae48 100644 (file)
@@ -181,6 +181,7 @@ System.Windows.Threading/DispatcherUnhandledExceptionEventArgs.cs
 System.Windows.Threading/DispatcherUnhandledExceptionEventHandler.cs
 System.Windows.Threading/DispatcherUnhandledExceptionFilterEventArgs.cs
 System.Windows.Threading/DispatcherUnhandledExceptionFilterEventHandler.cs
+ZipSharp/NativeVersion.cs
 ZipSharp/IOFunctions.cs
 ZipSharp/ZipArchive.cs
 ZipSharp/UnzipArchive.cs
index 04e6a3e9ca79e7919b62d2e245dc17959a5f1be2..d339f84425e9fdd4e006e4c9384664170a678629 100644 (file)
@@ -21,16 +21,28 @@ namespace zipsharp
        internal delegate IntPtr OpenFileFunc (IntPtr opaque, string filename, int mode);
 
        [UnmanagedFunctionPointerAttribute (CallingConvention.Cdecl)]
-       internal delegate /* ulong */ IntPtr ReadFileFunc (IntPtr opaque, IntPtr stream, IntPtr buffer, /* ulong */ IntPtr size);
+       internal delegate /* uLong */ uint ReadFileFunc32 (IntPtr opaque, IntPtr stream, IntPtr buffer, /* uLong */ uint size);
 
        [UnmanagedFunctionPointerAttribute (CallingConvention.Cdecl)]
-       internal delegate /* ulong */ IntPtr WriteFileFunc (IntPtr opaque, IntPtr stream, IntPtr buffer, /* ulong */ IntPtr size);
+       internal delegate /* uLong */ uint WriteFileFunc32 (IntPtr opaque, IntPtr stream, IntPtr buffer, /* uLong */ uint size);
 
        [UnmanagedFunctionPointerAttribute (CallingConvention.Cdecl)]
-       internal delegate /* long */ IntPtr TellFileFunc (IntPtr opaque, IntPtr stream);
+       internal delegate /* long */ int TellFileFunc32 (IntPtr opaque, IntPtr stream);
 
        [UnmanagedFunctionPointerAttribute (CallingConvention.Cdecl)]
-       internal delegate /* long */ IntPtr SeekFileFunc (IntPtr opaque, IntPtr stream, /* ulong */ IntPtr offset, int origin);
+       internal delegate /* long */ int SeekFileFunc32 (IntPtr opaque, IntPtr stream, /* uLong */ uint offset, int origin);
+
+       [UnmanagedFunctionPointerAttribute (CallingConvention.Cdecl)]
+       internal delegate /* uLong */ ulong ReadFileFunc64 (IntPtr opaque, IntPtr stream, IntPtr buffer, /* uLong */ ulong size);
+
+       [UnmanagedFunctionPointerAttribute (CallingConvention.Cdecl)]
+       internal delegate /* uLong */ ulong WriteFileFunc64 (IntPtr opaque, IntPtr stream, IntPtr buffer, /* uLong */ ulong size);
+
+       [UnmanagedFunctionPointerAttribute (CallingConvention.Cdecl)]
+       internal delegate /* long */ long TellFileFunc64 (IntPtr opaque, IntPtr stream);
+
+       [UnmanagedFunctionPointerAttribute (CallingConvention.Cdecl)]
+       internal delegate /* long */ long SeekFileFunc64 (IntPtr opaque, IntPtr stream, /* uLong */ ulong offset, int origin);
 
        [UnmanagedFunctionPointerAttribute (CallingConvention.Cdecl)]
        internal delegate int CloseFileFunc (IntPtr opaque, IntPtr stream);
@@ -39,13 +51,26 @@ namespace zipsharp
        internal delegate int TestErrorFileFunc (IntPtr opaque, IntPtr stream);
 
        [StructLayout (LayoutKind.Sequential)]
-       internal struct ZlibFileFuncDef
+       internal struct ZlibFileFuncDef32
+       {
+               [MarshalAs (UnmanagedType.FunctionPtr)] public OpenFileFunc      zopen_file;
+               [MarshalAs (UnmanagedType.FunctionPtr)] public ReadFileFunc32    zread_file;
+               [MarshalAs (UnmanagedType.FunctionPtr)] public WriteFileFunc32   zwrite_file;
+               [MarshalAs (UnmanagedType.FunctionPtr)] public TellFileFunc32    ztell_file;
+               [MarshalAs (UnmanagedType.FunctionPtr)] public SeekFileFunc32    zseek_file;
+               [MarshalAs (UnmanagedType.FunctionPtr)] public CloseFileFunc     zclose_file;
+               [MarshalAs (UnmanagedType.FunctionPtr)] public TestErrorFileFunc zerror_file;
+               public IntPtr            opaque;
+       }
+
+       [StructLayout (LayoutKind.Sequential)]
+       internal struct ZlibFileFuncDef64
        {
                [MarshalAs (UnmanagedType.FunctionPtr)] public OpenFileFunc      zopen_file;
-               [MarshalAs (UnmanagedType.FunctionPtr)] public ReadFileFunc      zread_file;
-               [MarshalAs (UnmanagedType.FunctionPtr)] public WriteFileFunc     zwrite_file;
-               [MarshalAs (UnmanagedType.FunctionPtr)] public TellFileFunc      ztell_file;
-               [MarshalAs (UnmanagedType.FunctionPtr)] public SeekFileFunc      zseek_file;
+               [MarshalAs (UnmanagedType.FunctionPtr)] public ReadFileFunc64    zread_file;
+               [MarshalAs (UnmanagedType.FunctionPtr)] public WriteFileFunc64   zwrite_file;
+               [MarshalAs (UnmanagedType.FunctionPtr)] public TellFileFunc64    ztell_file;
+               [MarshalAs (UnmanagedType.FunctionPtr)] public SeekFileFunc64    zseek_file;
                [MarshalAs (UnmanagedType.FunctionPtr)] public CloseFileFunc     zclose_file;
                [MarshalAs (UnmanagedType.FunctionPtr)] public TestErrorFileFunc zerror_file;
                public IntPtr            opaque;
index 3b3c3dc5d87dcf92a442a238a6dd325c1de151fe..673a2c921ebe3f240d4e0110c503983553c10d34 100644 (file)
@@ -65,43 +65,58 @@ namespace zipsharp
                        return unztell(handle).ToInt64 ();
                }
 
-               public static long CurrentFileLength (UnzipHandle handle)
+               public static long CurrentFileLength32 (UnzipHandle handle)
                {
-                       UnzipFileInfo info;
-                       int result = unzGetCurrentFileInfo (handle, out info, null, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, null,  IntPtr.Zero);
-                       
-                       if (result != 0)
-                               return -1;
-                       else
-                               return (long)info.UncompressedSize;
+                       UnzipFileInfo32 info;
+                       int result = unzGetCurrentFileInfo_32 (handle, out info, null, 0, IntPtr.Zero, 0, null,  0);
+                       return result != 0 ? -1 : (long) info.uncompressed_size;
                }
-               
-               static string GetCurrentFileName (UnzipHandle handle)
+
+               public static long CurrentFileLength64 (UnzipHandle handle)
                {
-                       UnzipFileInfo info;
-                       int result = unzGetCurrentFileInfo (handle, out info, null, IntPtr.Zero, IntPtr.Zero, new IntPtr (0), null,  IntPtr.Zero);
+                       UnzipFileInfo64 info;
+                       int result = unzGetCurrentFileInfo_64 (handle, out info, null, 0, IntPtr.Zero, 0, null,  0);
+                       return result != 0 ? -1 : (long) info.uncompressed_size;
+               }
 
-                       if (result != 0)
+               static string GetCurrentFileName32 (UnzipHandle handle)
+               {
+                       UnzipFileInfo32 info;
+                       if (unzGetCurrentFileInfo_32 (handle, out info, null, 0, IntPtr.Zero, 0, null, 0) != 0)
                                return null;
-                       
-                       StringBuilder sbName = new StringBuilder ((int)info.SizeFilename+1); // +1 to account for extra \0 at the end
-                       result = unzGetCurrentFileInfo (handle, out info, sbName, new IntPtr (sbName.Capacity), IntPtr.Zero, new IntPtr (0), null,  IntPtr.Zero);
-                       
-                       if (result != 0)
+                       var sbName = new StringBuilder ((int) info.size_filename + 1); // +1 to account for extra \0 at the end
+                       if (unzGetCurrentFileInfo_32 (handle, out info, sbName, (uint) sbName.Capacity, IntPtr.Zero, 0, null, 0) != 0)
                                return null;
-                       else
-                               return sbName.ToString ();
+                       return sbName.ToString ();
                }
 
-               public static string[] GetFiles (UnzipHandle handle)
+               static string GetCurrentFileName64 (UnzipHandle handle)
                {
-                       List<string> files = new List<string> ();
+                       UnzipFileInfo64 info;
+                       if (unzGetCurrentFileInfo_64 (handle, out info, null, 0, IntPtr.Zero, 0, null, 0) != 0)
+                               return null;
+                       var sbName = new StringBuilder ((int) info.size_filename + 1); // +1 to account for extra \0 at the end
+                       if (unzGetCurrentFileInfo_64 (handle, out info, sbName, (uint) sbName.Capacity, IntPtr.Zero, 0, null, 0) != 0)
+                               return null;
+                       return sbName.ToString ();
+               }
 
-                       GoToFirstFile (handle);
+               public static string[] GetFiles32 (UnzipHandle handle)
+               {
+                       return GetFiles (handle, GetCurrentFileName32);
+               }
+
+               public static string[] GetFiles64 (UnzipHandle handle)
+               {
+                       return GetFiles (handle, GetCurrentFileName64);
+               }
 
+               private static string[] GetFiles (UnzipHandle handle, Func<UnzipHandle, string> getCurrentFileName)
+               {
+                       GoToFirstFile (handle);
+                       var files = new List<string> ();
                        string name;
-                       while ((name = GetCurrentFileName(handle)) != null)
-                       {
+                       while ((name = getCurrentFileName (handle)) != null) {
                                files.Add (name);
                                if (!NativeUnzip.GoToNextFile (handle))
                                        break;
@@ -121,9 +136,17 @@ namespace zipsharp
                        return unzGoToNextFile(handle) == 0;
                }
                
-               public static UnzipHandle OpenArchive (ZlibFileFuncDef fileFuncs)
+               public static UnzipHandle OpenArchive32 (ZlibFileFuncDef32 fileFuncs)
+               {
+                       UnzipHandle handle = unzOpen2_32 ("", ref fileFuncs);
+                       if (handle.IsInvalid)
+                               throw new Exception ("Could not open unzip archive");
+                       return handle;
+               }
+
+               public static UnzipHandle OpenArchive64 (ZlibFileFuncDef64 fileFuncs)
                {
-                       UnzipHandle handle = unzOpen2 ("", ref fileFuncs);
+                       UnzipHandle handle = unzOpen2_64 ("", ref fileFuncs);
                        if (handle.IsInvalid)
                                throw new Exception ("Could not open unzip archive");
                        return handle;
@@ -160,9 +183,13 @@ namespace zipsharp
                [DllImport ("MonoPosixHelper", CallingConvention=CallingConvention.Cdecl)]
                static extern int unzGoToFirstFile (UnzipHandle handle);
 
-               [DllImport ("MonoPosixHelper", CallingConvention=CallingConvention.Cdecl)]
-               static extern UnzipHandle unzOpen2 (string path,
-                                                           ref ZlibFileFuncDef pzlib_filefunc_def);
+               [DllImport ("MonoPosixHelper", EntryPoint="unzOpen2", CallingConvention=CallingConvention.Cdecl)]
+               static extern UnzipHandle unzOpen2_32 (string path,
+                                                      ref ZlibFileFuncDef32 pzlib_filefunc_def);
+
+               [DllImport ("MonoPosixHelper", EntryPoint="unzOpen2", CallingConvention=CallingConvention.Cdecl)]
+               static extern UnzipHandle unzOpen2_64 (string path,
+                                                      ref ZlibFileFuncDef64 pzlib_filefunc_def);
 
                [DllImport ("MonoPosixHelper", CallingConvention=CallingConvention.Cdecl)]
                static extern int unzGoToNextFile (UnzipHandle handle);
@@ -178,15 +205,25 @@ namespace zipsharp
                                                       out int level,
                                                       int raw);
 
-               [DllImport ("MonoPosixHelper", CallingConvention=CallingConvention.Cdecl)]
-               static extern int unzGetCurrentFileInfo (UnzipHandle handle,
-                                                                out UnzipFileInfo pfile_info,
-                                                                StringBuilder szFileName,
-                                                                IntPtr fileNameBufferSize,   // uLong
-                                                                IntPtr extraField,           // void *
-                                                                IntPtr extraFieldBufferSize, // uLong
-                                                                StringBuilder szComment,
-                                                                IntPtr commentBufferSize);   // uLong
+               [DllImport ("MonoPosixHelper", EntryPoint="unzGetCurrentFileInfo", CallingConvention=CallingConvention.Cdecl)]
+               static extern int unzGetCurrentFileInfo_32 (UnzipHandle handle,
+                                                           out UnzipFileInfo32 pfile_info,
+                                                           StringBuilder szFileName,
+                                                           uint fileNameBufferSize,   // uLong
+                                                           IntPtr extraField,         // void *
+                                                           uint extraFieldBufferSize, // uLong
+                                                           StringBuilder szComment,
+                                                           uint commentBufferSize);   // uLong
+
+               [DllImport ("MonoPosixHelper", EntryPoint="unzGetCurrentFileInfo", CallingConvention=CallingConvention.Cdecl)]
+               static extern int unzGetCurrentFileInfo_64 (UnzipHandle handle,
+                                                           out UnzipFileInfo64 pfile_info,
+                                                           StringBuilder szFileName,
+                                                           ulong fileNameBufferSize,   // uLong
+                                                           IntPtr extraField,          // void *
+                                                           ulong extraFieldBufferSize, // uLong
+                                                           StringBuilder szComment,
+                                                           ulong commentBufferSize);   // uLong
 
                [DllImport ("MonoPosixHelper", CallingConvention=CallingConvention.Cdecl)]
                static unsafe extern int unzReadCurrentFile (UnzipHandle handle,
diff --git a/mcs/class/WindowsBase/ZipSharp/NativeVersion.cs b/mcs/class/WindowsBase/ZipSharp/NativeVersion.cs
new file mode 100755 (executable)
index 0000000..ce7112e
--- /dev/null
@@ -0,0 +1,20 @@
+using System;
+
+namespace zipsharp {
+       static class NativeVersion {
+
+               /// <summary>
+               /// ZipSharp code needs different code paths
+               /// depending on the size of the C long type on the underlying platform. On
+               /// gcc/clang the C long type follows the bitness of the targeted architecture,
+               /// it's 32-bit on 32-bit systems and 64-bit on 64-bit systems. With the VS
+               /// compiler however, the C long type is always 32-bit regardless of the
+               /// target architecture. zlib and minizip uses C long in a number of 
+               /// different function signatures and structs. 
+               /// 
+               /// This field is used to easily determine if the 32 bit version of 
+               /// functions and structs should be used when interacting with zlib.
+               /// </summary>
+               public static readonly bool Use32Bit = IntPtr.Size == 4 || Environment.OSVersion.Platform != PlatformID.Unix;
+       }
+}
index 225fc1acaba49b94a58b6999f54388d202c154e1..b556a9052e661d40251b895a24648346f7413466 100644 (file)
@@ -31,24 +31,44 @@ namespace zipsharp
                        zipCloseFileInZip (handle);
                }
 
-               public static ZipHandle OpenArchive (ZlibFileFuncDef funcDef, Append append)
+               public static ZipHandle OpenArchive32 (ZlibFileFuncDef32 funcDef, Append append)
                {
-                       ZipHandle h = zipOpen2 ("", (int) append, IntPtr.Zero, ref funcDef);
+                       ZipHandle h = zipOpen2_32 ("", (int) append, IntPtr.Zero, ref funcDef);
                        if (h.IsInvalid)
                                throw new Exception ("Could not open the zip archive");
                        return h;
                }
-               
-               public static int OpenFile (ZipHandle handle, string filename)
+
+               public static ZipHandle OpenArchive64 (ZlibFileFuncDef64 funcDef, Append append)
+               {
+                       ZipHandle h = zipOpen2_64 ("", (int) append, IntPtr.Zero, ref funcDef);
+                       if (h.IsInvalid)
+                               throw new Exception ("Could not open the zip archive");
+                       return h;
+               }
+
+               public static int OpenFile32 (ZipHandle handle, string filename)
+               {
+                       return OpenFile32 (handle, filename, DEFAULT_COMPRESSION);
+               }
+
+               public static int OpenFile32 (ZipHandle handle, string filename, int compressionLevel)
+               {
+                       ZipFileInfo32 fileInfo = new ZipFileInfo32 (DateTime.Now);
+                       int method = compressionLevel == 0 ? 0 : Z_DEFLATED;
+                       return zipOpenNewFileInZip_32 (handle, filename, ref fileInfo, IntPtr.Zero, 0, IntPtr.Zero, 0, "", method, compressionLevel);
+               }
+
+               public static int OpenFile64 (ZipHandle handle, string filename)
                {
-                       return OpenFile (handle, filename, DEFAULT_COMPRESSION);
+                       return OpenFile64 (handle, filename, DEFAULT_COMPRESSION);
                }
 
-               public static int OpenFile (ZipHandle handle, string filename, int compressionLevel)
+               public static int OpenFile64 (ZipHandle handle, string filename, int compressionLevel)
                {
-                       ZipFileInfo fileInfo = new ZipFileInfo (DateTime.Now);
+                       ZipFileInfo64 fileInfo = new ZipFileInfo64 (DateTime.Now);
                        int method = compressionLevel == 0 ? 0 : Z_DEFLATED;
-                       return zipOpenNewFileInZip (handle, filename, ref fileInfo, IntPtr.Zero, 0, IntPtr.Zero, 0, "", method, compressionLevel);
+                       return zipOpenNewFileInZip_64 (handle, filename, ref fileInfo, IntPtr.Zero, 0, IntPtr.Zero, 0, "", method, compressionLevel);
                }
 
                public static unsafe void Write (ZipHandle handle, byte[] buffer, int offset, uint count)
@@ -65,26 +85,43 @@ namespace zipsharp
                [DllImport ("MonoPosixHelper")]
                static extern int zipCloseFileInZip (ZipHandle handle);
 
-               [DllImport ("MonoPosixHelper")]
-               static extern ZipHandle zipOpen2 (string pathname,
-                                                 int append,
-                                                 IntPtr globalcomment, // zipcharpc*
-                                                 ref ZlibFileFuncDef pzlib_filefunc_def); // zlib_filefunc_def*
+               [DllImport ("MonoPosixHelper", EntryPoint = "zipOpen2")]
+               static extern ZipHandle zipOpen2_32 (string pathname,
+                                                    int append,
+                                                    IntPtr globalcomment, // zipcharpc*
+                                                    ref ZlibFileFuncDef32 pzlib_filefunc_def); // zlib_filefunc_def*
+
+               [DllImport ("MonoPosixHelper", EntryPoint = "zipOpen2")]
+               static extern ZipHandle zipOpen2_64 (string pathname,
+                                                    int append,
+                                                    IntPtr globalcomment, // zipcharpc*
+                                                    ref ZlibFileFuncDef64 pzlib_filefunc_def); // zlib_filefunc_def*
 
-               
                [DllImport ("MonoPosixHelper")]
                static extern int zipClose (ZipHandle handle, string globalComment);
 
-               [DllImport ("MonoPosixHelper")]
-               static extern int zipOpenNewFileInZip (ZipHandle handle,
-                                                      string filename,
-                                                      ref ZipFileInfo zipfi,
-                                                      IntPtr extrafield_local,
-                                                      uint size_extrafield_local,
-                                                      IntPtr extrafield_global,
-                                                      uint size_extrafield_global,
-                                                      string comment,
-                                                      int method,
-                                                      int level);
+               [DllImport ("MonoPosixHelper", EntryPoint = "zipOpenNewFileInZip")]
+               static extern int zipOpenNewFileInZip_32 (ZipHandle handle,
+                                                         string filename,
+                                                         ref ZipFileInfo32 zipfi,
+                                                         IntPtr extrafield_local,
+                                                         uint size_extrafield_local,
+                                                         IntPtr extrafield_global,
+                                                         uint size_extrafield_global,
+                                                         string comment,
+                                                         int method,
+                                                         int level);
+
+               [DllImport ("MonoPosixHelper", EntryPoint = "zipOpenNewFileInZip")]
+               static extern int zipOpenNewFileInZip_64 (ZipHandle handle,
+                                                         string filename,
+                                                         ref ZipFileInfo64 zipfi,
+                                                         IntPtr extrafield_local,
+                                                         uint size_extrafield_local,
+                                                         IntPtr extrafield_global,
+                                                         uint size_extrafield_global,
+                                                         string comment,
+                                                         int method,
+                                                         int level);
        }
 }
index d3be55886bf8cb9ed2b646c8911db857cfb740a3..59a5935c1128bb07ad734a9d339ce6348763ff25 100644 (file)
@@ -38,7 +38,7 @@ namespace zipsharp
                string[] Files {
                        get {
                                if (files == null)
-                                       files = NativeUnzip.GetFiles (Handle);
+                                       files = NativeVersion.Use32Bit ? NativeUnzip.GetFiles32 (Handle) : NativeUnzip.GetFiles64 (Handle);
                                return files;
                        }
                }
@@ -66,7 +66,7 @@ namespace zipsharp
                public UnzipArchive (Stream stream, bool ownsStream)
                {
                        Stream = new ZipStream (stream, ownsStream);
-                       Handle = NativeUnzip.OpenArchive (Stream.IOFunctions);
+                       Handle = NativeVersion.Use32Bit ? NativeUnzip.OpenArchive32 (Stream.IOFunctions32) : NativeUnzip.OpenArchive64 (Stream.IOFunctions64);
                }
 
                public void Dispose ()
index 9316c0a1773d617a8c26b266ddec0dd51d764723..d69241d7fa50ef1dab26f4597b4a10b614a3672e 100644 (file)
@@ -10,103 +10,46 @@ using System.Runtime.InteropServices;
 namespace zipsharp
 {
        [StructLayout (LayoutKind.Sequential)]
-       struct UnzipFileInfo
+       struct UnzipFileInfo32
        {
-           IntPtr version;              /* version made by                 2 bytes */
-           IntPtr version_needed;       /* version needed to extract       2 bytes */
-           IntPtr flag;                 /* general purpose bit flag        2 bytes */
-           IntPtr compression_method;   /* compression method              2 bytes */
-           IntPtr dosDate;              /* last mod file date in Dos fmt   4 bytes */
-           IntPtr crc;                  /* crc-32                          4 bytes */
-           IntPtr compressed_size;      /* compressed size                 4 bytes */
-           IntPtr uncompressed_size;    /* uncompressed size               4 bytes */
-           IntPtr size_filename;        /* filename length                 2 bytes */
-           IntPtr size_file_extra;      /* extra field length              2 bytes */
-           IntPtr size_file_comment;    /* file comment length             2 bytes */
+               public uint version;              /* version made by                 2 bytes */
+               public uint version_needed;       /* version needed to extract       2 bytes */
+               public uint flag;                 /* general purpose bit flag        2 bytes */
+               public uint compression_method;   /* compression method              2 bytes */
+               public uint dosDate;              /* last mod file date in Dos fmt   4 bytes */
+               public uint crc;                  /* crc-32                          4 bytes */
+               public uint compressed_size;      /* compressed size                 4 bytes */
+               public uint uncompressed_size;    /* uncompressed size               4 bytes */
+               public uint size_filename;        /* filename length                 2 bytes */
+               public uint size_file_extra;      /* extra field length              2 bytes */
+               public uint size_file_comment;    /* file comment length             2 bytes */
        
-           IntPtr disk_num_start;       /* disk number start               2 bytes */
-           IntPtr internal_fa;          /* internal file attributes        2 bytes */
-           IntPtr external_fa;          /* external file attributes        4 bytes */
+               public uint disk_num_start;       /* disk number start               2 bytes */
+               public uint internal_fa;          /* internal file attributes        2 bytes */
+               public uint external_fa;          /* external file attributes        4 bytes */
        
            ZipTime tmu_date;
-           
-           public ulong VersionNeeded {
-               get { return (ulong)version_needed.ToInt64 (); }
-               set { version_needed = new IntPtr ((int)value); }
-           }
-           
-           public ulong Version {
-               get { return (ulong)version.ToInt64 (); }
-               set { version = new IntPtr ((int)value); }
-           }
-           
-           public ulong UncompressedSize {
-               get { return (ulong)uncompressed_size.ToInt64 (); }
-                       set { uncompressed_size = new IntPtr ((int)value); }
-           }
-           
-           public ZipTime TmuDate {
-               get { return tmu_date; }
-               set { tmu_date = value; }
-           }
-           
-           public ulong SizeFilename {
-               get { return (ulong)size_filename.ToInt64 (); }
-               set { size_filename = new IntPtr ((int)value); }
-           }
-           
-           public ulong SizeFileExtra {
-               get { return (ulong)size_file_extra.ToInt64 (); }
-               set { size_file_extra = new IntPtr ((int)value); }
-           }
-           
-           public ulong SizeFileComment {
-               get {
-                       return (ulong)size_file_comment.ToInt64 ();
-               }
-               set {
-                       size_file_comment = new IntPtr ((int)value);
-               }
-           }
-           
-           public ulong InternalFa {
-               get { return (ulong)internal_fa.ToInt64 (); }
-               set { internal_fa = new IntPtr ((int)value); }
-           }
-           
-           public ulong Flag {
-               get { return (ulong)flag.ToInt64 (); }
-               set { flag = new IntPtr ((int)value); }
-           }
-           
-           public ulong ExternalFa {
-               get { return (ulong)external_fa.ToInt64 (); }
-               set { external_fa = new IntPtr ((int)value); }
-           }
-           
-           public ulong DosDate {
-               get { return (ulong)dosDate.ToInt64 (); }
-               set { dosDate = new IntPtr ((int)value); }
-           }
-           
-           public ulong DiskNumStart {
-               get { return (ulong)disk_num_start.ToInt64 (); }
-               set { disk_num_start = new IntPtr ((int)value); }
-           }
-           
-           public ulong Crc {
-               get { return (ulong)crc.ToInt64 (); }
-               set { crc = new IntPtr ((int)value); }
-           }
-           
-           public ulong CompressionMethod {
-               get { return (ulong)compression_method.ToInt64 (); }
-               set { compression_method = new IntPtr ((int)value); }
-           }
-           
-           public ulong CompressedSize {
-               get { return (ulong)compressed_size.ToInt64 (); }
-               set { compressed_size = new IntPtr ((int)value); }
-           }
+       }
+
+       [StructLayout (LayoutKind.Sequential)]
+       struct UnzipFileInfo64
+       {
+               public ulong version;              /* version made by                 2 bytes */
+               public ulong version_needed;       /* version needed to extract       2 bytes */
+               public ulong flag;                 /* general purpose bit flag        2 bytes */
+               public ulong compression_method;   /* compression method              2 bytes */
+               public ulong dosDate;              /* last mod file date in Dos fmt   4 bytes */
+               public ulong crc;                  /* crc-32                          4 bytes */
+               public ulong compressed_size;      /* compressed size                 4 bytes */
+               public ulong uncompressed_size;    /* uncompressed size               4 bytes */
+               public ulong size_filename;        /* filename length                 2 bytes */
+               public ulong size_file_extra;      /* extra field length              2 bytes */
+               public ulong size_file_comment;    /* file comment length             2 bytes */
+
+               public ulong disk_num_start;       /* disk number start               2 bytes */
+               public ulong internal_fa;          /* internal file attributes        2 bytes */
+               public ulong external_fa;          /* external file attributes        4 bytes */
+
+               ZipTime tmu_date;
        }
 }
index 39c793e8e0b2146ab808b62350689aa6453e9377..71cc129006d23f0581d3aae3a3e0c933d1d6e325 100644 (file)
@@ -70,7 +70,7 @@ namespace zipsharp
                        Archive = archive;
                        Archive.FileActive = true;
                        CompressionLevel = compressionLevel;
-                       length = NativeUnzip.CurrentFileLength (Archive.Handle);
+                       length = NativeVersion.Use32Bit ? NativeUnzip.CurrentFileLength32 (Archive.Handle) : NativeUnzip.CurrentFileLength64 (Archive.Handle);
                }
 
                public override void Close()
index 8f60aab4e9eedc97a8f48be7ffadc1e8e50e56b4..598d163991c8821d2540e28ee9b65d9f4c2565a6 100644 (file)
@@ -31,7 +31,7 @@ namespace zipsharp
                public ZipArchive (Stream stream, Append append, bool ownsStream)
                {
                        Stream = new ZipStream (stream, ownsStream);
-                       Handle = NativeZip.OpenArchive (Stream.IOFunctions, append);
+                       Handle = NativeVersion.Use32Bit ? NativeZip.OpenArchive32 (Stream.IOFunctions32, append) : NativeZip.OpenArchive64 (Stream.IOFunctions64, append);
                }
 
                
@@ -61,8 +61,11 @@ namespace zipsharp
                {
                        if (FileActive)
                                throw new InvalidOperationException ("A file is already open");
-                       
-                       NativeZip.OpenFile (Handle, filename, ConvertCompression (option));
+
+                       if (NativeVersion.Use32Bit)
+                               NativeZip.OpenFile32 (Handle, filename, ConvertCompression (option));
+                       else
+                               NativeZip.OpenFile64 (Handle, filename, ConvertCompression (option));
                        return new ZipWriteStream (this);
                }
 
index 2a81a73959bba6ddcf3595874bb9651989261160..0c3f0eeb7f98fefaa786a2c47db873fe1392acd9 100644 (file)
@@ -10,40 +10,36 @@ using System.Runtime.InteropServices;
 namespace zipsharp
 {
        [StructLayoutAttribute (LayoutKind.Sequential)]
-       struct ZipFileInfo
+       struct ZipFileInfo32
        {
                ZipTime date;
-               IntPtr dosDate;
-               IntPtr internalFileAttributes;
-               IntPtr externalFileAttributes;
+               uint dosDate;
+               uint internalFileAttributes;
+               uint externalFileAttributes;
 
-               public DateTime FileTime
+               public ZipFileInfo32 (DateTime fileTime)
                {
-                       get { return date.Date; }
+                       date = new ZipTime (fileTime);
+                       dosDate = 0;
+                       internalFileAttributes = 0;
+                       externalFileAttributes = 0;
                }
+       }
 
-               public long DosDate
-               {
-                       get { return dosDate.ToInt64 (); }
-               }
-               
-               internal long InternalFileAttributes
-               {
-                       get { return internalFileAttributes.ToInt64 (); }
-               }
+       [StructLayoutAttribute (LayoutKind.Sequential)]
+       struct ZipFileInfo64
+       {
+               ZipTime date;
+               ulong dosDate;
+               ulong internalFileAttributes;
+               ulong externalFileAttributes;
 
-               internal long ExternalFileAttributes
-               {
-                       get { return externalFileAttributes.ToInt64 (); }
-               }
-               
-               public ZipFileInfo (DateTime fileTime)
+               public ZipFileInfo64 (DateTime fileTime)
                {
                        date = new ZipTime (fileTime);
-                       dosDate = IntPtr.Zero;
-                       internalFileAttributes = IntPtr.Zero;
-                       externalFileAttributes = IntPtr.Zero;
+                       dosDate = 0;
+                       internalFileAttributes = 0;
+                       externalFileAttributes = 0;
                }
-
        }
 }
index 51d15c56c12dfa67691c08f2019edcedbd9c4851..f0007dfb8a244c059a0f511be0fb900b6fdda0cf 100644 (file)
@@ -40,7 +40,11 @@ namespace zipsharp
                        get; set;
                }
 
-               public ZlibFileFuncDef IOFunctions {
+               public ZlibFileFuncDef32 IOFunctions32 {
+                       get; set;
+               }
+
+               public ZlibFileFuncDef64 IOFunctions64 {
                        get; set;
                }
 
@@ -67,18 +71,27 @@ namespace zipsharp
                        DataStream = dataStream;
                        OwnsStream = ownsStream;
                        
-                       ZlibFileFuncDef f = new ZlibFileFuncDef();
-                       
-                       f.opaque = IntPtr.Zero;
-                       f.zclose_file = CloseFile_Native;
-                       f.zerror_file = TestError_Native;
-                       f.zopen_file = OpenFile_Native;
-                       f.zread_file = ReadFile_Native;
-                       f.zseek_file = SeekFile_Native;
-                       f.ztell_file = TellFile_Native;
-                       f.zwrite_file = WriteFile_Native;
-
-                       IOFunctions = f;
+                       ZlibFileFuncDef32 f32 = new ZlibFileFuncDef32 ();
+                       f32.opaque = IntPtr.Zero;
+                       f32.zclose_file = CloseFile_Native;
+                       f32.zerror_file = TestError_Native;
+                       f32.zopen_file = OpenFile_Native;
+                       f32.zread_file = ReadFile_Native32;
+                       f32.zseek_file = SeekFile_Native32;
+                       f32.ztell_file = TellFile_Native32;
+                       f32.zwrite_file = WriteFile_Native32;
+                       IOFunctions32 = f32;
+
+                       ZlibFileFuncDef64 f64 = new ZlibFileFuncDef64 ();
+                       f64.opaque = IntPtr.Zero;
+                       f64.zclose_file = CloseFile_Native;
+                       f64.zerror_file = TestError_Native;
+                       f64.zopen_file = OpenFile_Native;
+                       f64.zread_file = ReadFile_Native64;
+                       f64.zseek_file = SeekFile_Native64;
+                       f64.ztell_file = TellFile_Native64;
+                       f64.zwrite_file = WriteFile_Native64;
+                       IOFunctions64 = f64;
                }
 
                protected override void Dispose(bool disposing)
@@ -130,9 +143,14 @@ namespace zipsharp
                        return new IntPtr (1);
                }
 
-               unsafe IntPtr ReadFile_Native (IntPtr opaque, IntPtr stream, IntPtr buffer, IntPtr size)
+               unsafe uint ReadFile_Native32 (IntPtr opaque, IntPtr stream, IntPtr buffer, uint size)
                {
-                       int count = size.ToInt32 ();
+                       return (uint) ReadFile_Native64 (opaque, stream, buffer, size);
+               }
+
+               unsafe ulong ReadFile_Native64 (IntPtr opaque, IntPtr stream, IntPtr buffer, ulong size)
+               {
+                       int count = (int) size;
                        byte[] b = new byte[count];
                        int read;
                        
@@ -145,10 +163,15 @@ namespace zipsharp
                                read = -1;
                        }
 
-                       return new IntPtr (read);
+                       return (ulong) read;
                }
 
-               IntPtr SeekFile_Native (IntPtr opaque, IntPtr stream, IntPtr offset, int origin)
+               int SeekFile_Native32 (IntPtr opaque, IntPtr stream, uint offset, int origin)
+               {
+                       return (int) SeekFile_Native64 (opaque, stream, offset, origin);
+               }
+
+               long SeekFile_Native64 (IntPtr opaque, IntPtr stream, ulong offset, int origin)
                {
                        SeekOrigin seek;
                        if (origin == ZipStream.ZLIB_FILEFUNC_SEEK_CUR)
@@ -158,21 +181,21 @@ namespace zipsharp
                        else if (origin == ZLIB_FILEFUNC_SEEK_SET)
                                seek = SeekOrigin.Begin;
                        else
-                               return new IntPtr (-1);
+                               return -1;
 
-                       Seek (offset.ToInt64 (), seek);
+                       Seek ((long) offset, seek);
                        
-                       return new IntPtr (0);
+                       return 0;
                }
 
-               IntPtr TellFile_Native (IntPtr opaque, IntPtr stream)
+               int TellFile_Native32 (IntPtr opaque, IntPtr stream)
                {
-                       if (IntPtr.Size == 4)
-                               return new IntPtr ((int)Position);
-                       else if (IntPtr.Size == 8)
-                               return new IntPtr (Position);
-                       else
-                               return new IntPtr (-1);
+                       return (int) TellFile_Native64 (opaque, stream);
+               }
+
+               long TellFile_Native64 (IntPtr opaque, IntPtr stream)
+               {
+                       return Position;
                }
 
                int TestError_Native (IntPtr opaque, IntPtr stream)
@@ -181,9 +204,14 @@ namespace zipsharp
                        return 0;
                }
 
-               unsafe IntPtr WriteFile_Native (IntPtr opaque, IntPtr stream, IntPtr buffer, /* ulong */ IntPtr size)
+               unsafe uint WriteFile_Native32 (IntPtr opaque, IntPtr stream, IntPtr buffer, /* ulong */ uint size)
+               {
+                       return (uint) WriteFile_Native64 (opaque, stream, buffer, size);
+               }
+
+               unsafe ulong WriteFile_Native64 (IntPtr opaque, IntPtr stream, IntPtr buffer, /* ulong */ ulong size)
                {
-                       int count = size.ToInt32 ();
+                       int count = (int) size;
                        byte[] b = new byte[count];
 
                        byte* ptrBuffer = (byte*) buffer.ToPointer ();
@@ -196,7 +224,7 @@ namespace zipsharp
                                
                        }
 
-                       return new IntPtr (count);
+                       return (ulong) count;
                }
        }
 }
index a112faf5570d99236ce2888b1c778a061d6dc4cf..a35fe1dc666eb5bcfb05e1e1fca35b2a7c611c7c 100644 (file)
@@ -39,6 +39,18 @@ namespace System.Security.Cryptography {
                {
                }
                
+               public RNGCryptoServiceProvider (byte[] rgb)
+               {
+               }
+
+               public RNGCryptoServiceProvider (CspParameters cspParams)
+               {
+               }
+
+               public RNGCryptoServiceProvider (string str) 
+               {
+               }
+
                ~RNGCryptoServiceProvider () 
                {
                }
index a0f17b0f19628aa6324538c6b019eb9e263223f7..c05eb88982187a2070f9c67e3eec257a9d60caf9 100644 (file)
@@ -35,7 +35,7 @@ RESOURCE_FILES = \
        resources/collation.cjkKO.bin \
        resources/collation.cjkKOlv2.bin
 
-REFERENCE_SOURCES_FLAGS = -d:FEATURE_PAL,GENERICS_WORK,FEATURE_LIST_PREDICATES,FEATURE_SERIALIZATION,FEATURE_ASCII,FEATURE_LATIN1,FEATURE_UTF7,FEATURE_UTF32,MONO_HYBRID_ENCODING_SUPPORT,FEATURE_ASYNC_IO,NEW_EXPERIMENTAL_ASYNC_IO,FEATURE_UTF32,FEATURE_EXCEPTIONDISPATCHINFO,FEATURE_CORRUPTING_EXCEPTIONS,FEATURE_EXCEPTION_NOTIFICATIONS,FEATURE_STRONGNAME_MIGRATION,FEATURE_USE_LCID,FEATURE_FUSION,FEATURE_CRYPTO,FEATURE_X509_SECURESTRINGS,FEATURE_SYNCHRONIZATIONCONTEXT,FEATURE_SYNCHRONIZATIONCONTEXT_WAIT
+REFERENCE_SOURCES_FLAGS = -d:FEATURE_PAL,GENERICS_WORK,FEATURE_LIST_PREDICATES,FEATURE_SERIALIZATION,FEATURE_ASCII,FEATURE_LATIN1,FEATURE_UTF7,FEATURE_UTF32,MONO_HYBRID_ENCODING_SUPPORT,FEATURE_ASYNC_IO,NEW_EXPERIMENTAL_ASYNC_IO,FEATURE_UTF32,FEATURE_EXCEPTIONDISPATCHINFO,FEATURE_CORRUPTING_EXCEPTIONS,FEATURE_EXCEPTION_NOTIFICATIONS,FEATURE_STRONGNAME_MIGRATION,FEATURE_USE_LCID,FEATURE_FUSION,FEATURE_CRYPTO,FEATURE_X509_SECURESTRINGS,FEATURE_SYNCHRONIZATIONCONTEXT,FEATURE_SYNCHRONIZATIONCONTEXT_WAIT,HAS_CORLIB_CONTRACTS
 
 ifndef MOBILE_PROFILE
 REFERENCE_SOURCES_FLAGS += -d:FEATURE_MACL
index e6741d4d3caf2c0cf6467e382e9821c4281646eb..63c0c015978b1c58d7cc38e2ad58f74ab5318958 100644 (file)
@@ -180,7 +180,6 @@ namespace System.Globalization
                        get { return territory; }
                }
 
-#if !MOBILE
                // FIXME: It is implemented, but would be hell slow.
                [ComVisible (false)]
                public CultureTypes CultureTypes {
@@ -266,7 +265,6 @@ namespace System.Globalization
                                }
                        }
                }
-#endif
 
                public virtual int LCID {
                        get {
index e97a1b4c944d0ddd652315adcfec7dc7b8d96656..30ae09cdf16be9181dcdc2efc3335c966cb0739d 100644 (file)
@@ -870,6 +870,10 @@ namespace System.Reflection.Emit
                                foreach (var cb in ctors)
                                        cb.FixupTokens (token_map, member_map);
                        }
+                       if (subtypes != null) {
+                               foreach (var tb in subtypes)
+                                       tb.FixupTokens (token_map, member_map);
+                       }
                }
 
                internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
index 33fef7a0a8d2c26525bdb5146ef1093305ae47d7..eb45ced8220104fedb88ee88eb5f57c6af55be7f 100644 (file)
@@ -106,7 +106,12 @@ namespace System.Runtime.Remoting
                {
                        lock (channelTemplates) {
                                if (!defaultConfigRead) {
-                                       ReadConfigFile (Environment.GetMachineConfigPath ());
+                                       var bundled = Environment.GetBundledMachineConfig ();
+                                       if (bundled != null)
+                                               ReadConfigString (bundled);
+
+                                       if (File.Exists (Environment.GetMachineConfigPath ()))
+                                               ReadConfigFile (Environment.GetMachineConfigPath ());
                                        defaultConfigRead = true;
                                }
 
@@ -121,6 +126,22 @@ namespace System.Runtime.Remoting
                        Configure (filename, false);
                }
 
+               private static void ReadConfigString (string filename)
+               {
+                       try
+                       {
+                               SmallXmlParser parser = new SmallXmlParser ();
+                               using (TextReader rreader = new StringReader (filename)) {
+                                       ConfigHandler handler = new ConfigHandler (false);
+                                       parser.Parse (rreader, handler);
+                               }
+                       }
+                       catch (Exception ex)
+                       {
+                               throw new RemotingException ("Configuration string could not be loaded: " + ex.Message, ex);
+                       }
+               }
+
                private static void ReadConfigFile (string filename)
                {
                        try
index 29322f74ea8b8c8c30e82044455472439bcd7eb1..9ae2a61b75ad539b714e6c40a1042d8c1f02c56b 100755 (executable)
@@ -44,6 +44,16 @@ namespace System.Security.Cryptography {
        [ComVisible (true)]
        public partial class CryptoConfig {
 
+               public static void AddAlgorithm (Type algorithm, params string[] names)
+               {
+                       throw new PlatformNotSupportedException ();
+               }
+
+               public static void AddOID (string oid, params string[] names)
+               {
+                       throw new PlatformNotSupportedException ();
+               }
+
                // try to avoid hitting the CreateFromName overloads to help the linker
 
                public static object CreateFromName (string name)
index 8a98c9d5ad849b43707eedfd77ec93b5de597c53..7abdbecd11a782671b3976c02e15089365142756 100644 (file)
@@ -58,7 +58,7 @@ namespace System.Security.Cryptography {
                        _handle = RngInitialize (null);
                        Check ();
                }
-#if !MOBILE
+
                public RNGCryptoServiceProvider (byte[] rgb)
                {
                        _handle = RngInitialize (rgb);
@@ -81,7 +81,7 @@ namespace System.Security.Cryptography {
                                _handle = RngInitialize (Encoding.UTF8.GetBytes (str));
                        Check ();
                }
-#endif
+
                private void Check () 
                {
                        if (_handle == IntPtr.Zero) {
index 76a637ea631fbd4b64cfaf30bdb37607954f8380..ea12a7f34681a93c7def93d8e8678882349c7ccc 100644 (file)
@@ -1217,14 +1217,16 @@ namespace System {
                        SetData (name, data);
                }
 
-#if !MOBILE
                [Obsolete ("Use AppDomainSetup.DynamicBase")]
                [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
                public void SetDynamicBase (string path)
                {
+#if MOBILE
+                       throw new PlatformNotSupportedException ();
+#else
                        SetupInformationNoCopy.DynamicBase = path;
+#endif // MOBILE
                }
-#endif // !MOBILE
 
                [Obsolete ("AppDomain.GetCurrentThreadId has been deprecated"
                        + " because it does not provide a stable Id when managed"
@@ -1286,14 +1288,11 @@ namespace System {
                private Assembly DoAssemblyResolve (string name, Assembly requestingAssembly, bool refonly)
                {
                        ResolveEventHandler del;
-#if !MOBILE
                        if (refonly)
                                del = ReflectionOnlyAssemblyResolve;
                        else
                                del = AssemblyResolve;
-#else
-                       del = AssemblyResolve;
-#endif
+
                        if (del == null)
                                return null;
                        
@@ -1490,9 +1489,7 @@ namespace System {
                }
 #endif // MONO_FEATURE_MULTIPLE_APPDOMAINS
 
-#if !MOBILE
                public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
-#endif
 
         #pragma warning disable 649
 #if MOBILE
index 22b4ef6748ccc18659e36beff266127d8ce5c58f..19d17929c54a552b07f4b16c4f587d6aba2ef421 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 = 158;
+               private const int mono_corlib_version = 160;
 #pragma warning restore 169
 
                [ComVisible (true)]
@@ -996,6 +996,14 @@ namespace System {
                [MethodImplAttribute (MethodImplOptions.InternalCall)]
                internal extern static int GetPageSize ();
 
+               [MethodImplAttribute(MethodImplOptions.InternalCall)]
+               extern private static string get_bundled_machine_config ();
+
+               internal static string GetBundledMachineConfig ()
+               {
+                       return get_bundled_machine_config ();
+               }
+
                static internal bool IsUnix {
                        get {
                                int platform = (int) Environment.Platform;
index be5f2168b83308df42b73a06d546194e128a8ead..ac3b1f149fa3d8e587cb8cf5a691fcc62eef46a5 100644 (file)
@@ -112,7 +112,7 @@ namespace MonoTests.System.Reflection.Emit
                                Thread.GetDomain ().DefineDynamicAssembly (
                                        assemblyName, AssemblyBuilderAccess.RunAndSave, Path.GetTempPath ());
 
-                       module = assembly.DefineDynamicModule ("module1");
+                       module = assembly.DefineDynamicModule (ASSEMBLY_NAME, ASSEMBLY_NAME + ".dll");
                }
 
                static int typeIndexer = 0;
@@ -1827,6 +1827,23 @@ namespace MonoTests.System.Reflection.Emit
                        // TODO:
                }
 
+               [Test]
+               public void NestedTypeSave () {
+                       var tb = module.DefineType (genTypeName ());
+
+                       var tbuilder = tb.DefineNestedType ("Test.CodeGen", TypeAttributes.Public | TypeAttributes.Class);
+                       var entryp = tbuilder.DefineMethod("Main", MethodAttributes.Public | MethodAttributes.Static, typeof (void), null);
+                       var ilg = entryp.GetILGenerator (128);
+                       ilg.Emit (OpCodes.Ldtoken, tb);
+                       ilg.Emit (OpCodes.Pop);
+                       ilg.Emit (OpCodes.Ret);
+
+                       tbuilder.CreateType ();
+                       tb.CreateType ();
+
+                       assembly.Save (ASSEMBLY_NAME + ".dll");
+               }
+
                [Test]
                public void DefinePInvokeMethod_Name_NullChar ()
                {
index fcace5bb0b94a5ddc0a98ea97ed8b96af3618cce..108680d10ad19f025c0b803d5cccceca134fac2c 100644 (file)
@@ -203,5 +203,21 @@ namespace MonoTests.System.Runtime.CompilerServices {
                        Assert.IsTrue (RuntimeHelpers.Equals (o1, o3));
                        Assert.IsTrue (!RuntimeHelpers.Equals (o1, o4));
                }
+
+               [Test]
+               public void TestEnsureSufficientExecutionStack ()
+               {
+                       var t = new Thread (() => {
+                               unsafe {
+                                       var s = stackalloc byte [1024];
+                               }
+
+                               RuntimeHelpers.EnsureSufficientExecutionStack ();
+                       });
+
+
+                       t.Start ();
+                       t.Join ();
+               }
        }
 }
index 1f408618bee270e7bb5c65ea1ace8861b925449e..d70e5fdde709fd20dcbcf54bf9fa7e338d5483bb 100644 (file)
@@ -3058,9 +3058,15 @@ namespace MonoTests.System
                public void MakeArrayTypeTest ()
                {
                        // This should not crash:
-                       typeof (void).MakeArrayType ();
+                       Type t = typeof (void).MakeArrayType ();
                }
                
+               [Test]
+               [ExpectedException (typeof (InvalidProgramException))]
+               public void MakeArrayTypedReferenceInstanceTest ()
+               {
+                       object o = Array.CreateInstance (typeof (global::System.TypedReference), 1);
+               }
 
                [ComVisible (true)]
                public class ComFoo<T> {
diff --git a/mcs/class/corlib/corefx/SR.cs b/mcs/class/corlib/corefx/SR.cs
new file mode 100644 (file)
index 0000000..7330ff6
--- /dev/null
@@ -0,0 +1,7 @@
+// TODO: Should be auto-generated from resources.resx
+
+static class SR
+{
+       public const string ArgumentException_ValueTupleIncorrectType = "The parameter should be a ValueTuple type of appropriate arity.";
+       public const string ArgumentException_ValueTupleLastArgumentNotAValueTuple = "The TRest type argument of ValueTuple`8 must be a ValueTuple.";
+}
\ No newline at end of file
index 63f78fbf85b693364b17a468631e549b44abcd1c..e2dfdbb5b8f46859d56b68790614970ea4a9149e 100644 (file)
@@ -906,6 +906,8 @@ ReferenceSources/SharedStatics.cs
 ReferenceSources/SecurityContext.cs
 ReferenceSources/PathInternal.cs
 ReferenceSources/BinaryCompatibility.cs
+ReferenceSources/String.cs
+ReferenceSources/Type.cs
 
 ../referencesource/mscorlib/system/__filters.cs
 ../referencesource/mscorlib/system/__hresults.cs
@@ -1640,5 +1642,10 @@ ReferenceSources/BinaryCompatibility.cs
 ../referencesource/mscorlib/microsoft/win32/safehandles/safewaithandle.cs
 ../referencesource/mscorlib/microsoft/win32/safehandles/win32safehandles.cs
 
-ReferenceSources/String.cs
-ReferenceSources/Type.cs
+corefx/SR.cs
+
+../../../external/corefx/src/Common/src/System/Numerics/Hashing/HashHelpers.cs
+
+../../../external/corefx/src/System.ValueTuple/src/System/ValueTuple/ValueTuple.cs
+../../../external/corefx/src/System.ValueTuple/src/System/ValueTuple/TupleExtensions.cs
+../../../external/corefx/src/System.ValueTuple/src/System/Runtime/CompilerServices/TupleElementNamesAttribute.cs
index 9feea179f30dba470524c8f8a4c5e69ea385fac5..d1b0ab5f9ebfd615bf7497c17a6fe2dc50c09f72 100644 (file)
@@ -31,7 +31,9 @@ namespace System.CodeDom {
         private CodeNamespaceImportCollection imports = new CodeNamespaceImportCollection();
         private CodeCommentStatementCollection comments = new CodeCommentStatementCollection();
         private CodeTypeDeclarationCollection classes = new CodeTypeDeclarationCollection();
+#if CODEDOM_NESTED_NAMESPACES
         private CodeNamespaceCollection namespaces = new CodeNamespaceCollection();
+#endif
         
         private int  populated = 0x0;
         private const int ImportsCollection = 0x1;
index 28d511744cc529a7ce58dcd005affdd709863c8f..38ccf72ec0efd622c8ddb04f9d6f9bf6d7dae25a 100644 (file)
@@ -27,7 +27,9 @@ namespace System.CodeDom {
     public class CodePropertyReferenceExpression : CodeExpression {
         private CodeExpression targetObject;
         private string propertyName;
+#if !MONO
         private CodeExpressionCollection parameters = new CodeExpressionCollection();
+#endif
 
         /// <devdoc>
         ///    <para>
index 96ec1aa520a7c723dec25a3cfec0622a4fe1ca0d..82bfe6c56ae9d6e0857deca6701a76f49326824f 100644 (file)
@@ -98,11 +98,15 @@ namespace System.ComponentModel {
         }
 
         private class LicFileLicense : License {
+#if !MONO
             private LicFileLicenseProvider owner;
+#endif
             private string key;
 
             public LicFileLicense(LicFileLicenseProvider owner, string key) {
+#if !MONO
                 this.owner = owner;
+#endif
                 this.key = key;
             }
             public override string LicenseKey { 
index cfdaabbfc31b6a1cebc722cc91676164afa19480..ce8d0cd7dfdb4d866312365a2dad2c2f79c20bc8 100644 (file)
@@ -67,9 +67,10 @@ namespace System.ComponentModel {
     /// </devdoc>
     [HostProtection(SharedState = true)]
     internal sealed class ReflectEventDescriptor : EventDescriptor {
-
+#if !MONO
         private static readonly Type[] argsNone = new Type[0];
         private static readonly object  noDefault = new object();
+#endif
 
         private Type type;           // the delegate type for the event
         private readonly Type componentClass; // the class of the component this info is for
index 401c21e4d6697f3c41556dd58df794435d5c3d73..94424b88b02e177303499237b0c0f28e7a7894e7 100644 (file)
@@ -64,7 +64,9 @@ namespace System.ComponentModel {
         
         private static TraceSwitch PropDescCreateSwitch = new TraceSwitch("PropDescCreate", "ReflectPropertyDescriptor: Dump errors when creating property info");
         private static TraceSwitch PropDescUsageSwitch  = new TraceSwitch("PropDescUsage", "ReflectPropertyDescriptor: Debug propertydescriptor usage");
+#if !MONO
         private static TraceSwitch PropDescSwitch       = new TraceSwitch("PropDesc", "ReflectPropertyDescriptor: Debug property descriptor");
+#endif
         
         private static readonly int BitDefaultValueQueried      = BitVector32.CreateMask();
         private static readonly int BitGetQueried               = BitVector32.CreateMask(BitDefaultValueQueried);
index 246b3aee430291b32e13ec4c5882d268e17ce5b4..3bcd73437916cca6106e50c327e3fb4d4b83005a 100644 (file)
@@ -28,8 +28,10 @@ namespace System.ComponentModel {
 
         private const string s_UseCompatibleTypeConverterBehavior = "UseCompatibleTypeConverterBehavior";
         private static volatile bool useCompatibleTypeConversion = false;
+#if !MONO
         private static volatile bool firstLoadAppSetting = true;
         private static object loadAppSettingLock = new Object();
+#endif
 
         private static bool UseCompatibleTypeConversion {
             get {
index 506c90a59d6cb5cdf050ab20aa639faf9fb7737e..26248db1547dde54dbe4420740baf3ef93cbee90 100644 (file)
@@ -108,12 +108,15 @@ namespace System.Net.Sockets {
         private SocketAddress   m_PermittedRemoteAddress;
 
         private DynamicWinsockMethods m_DynamicWinsockMethods;
+#endif // !MONO
 
         private static object s_InternalSyncObject;
+#if !MONO
         private int m_CloseTimeout = Socket.DefaultCloseTimeout;
         private int m_IntCleanedUp;                 // 0 if not completed >0 otherwise.
         private const int microcnv = 1000000;
         private readonly static int protocolInformationSize = Marshal.SizeOf(typeof(UnsafeNclNativeMethods.OSSOCK.WSAPROTOCOL_INFO));
+#endif // !MONO
 
         internal static volatile bool s_SupportsIPv4;
         internal static volatile bool s_SupportsIPv6;
@@ -124,7 +127,6 @@ namespace System.Net.Sockets {
 #if !FEATURE_PAL // perfcounter
         internal static volatile bool s_PerfCountersEnabled;
 #endif
-#endif // !MONO
 
 //************* constructors *************************
 
@@ -136,7 +138,6 @@ namespace System.Net.Sockets {
             DualMode = true;
         }
 
-#if !MONO
         /// <devdoc>
         ///    <para>
         ///       Initializes a new instance of the <see cref='Sockets.Socket'/> class.
@@ -146,10 +147,16 @@ namespace System.Net.Sockets {
             s_LoggingEnabled = Logging.On;
             if(s_LoggingEnabled)Logging.Enter(Logging.Sockets, this, "Socket", addressFamily);
             InitializeSockets();
+
+#if MONO
+            int error;
+            m_Handle = new SafeSocketHandle (Socket_internal (addressFamily, socketType, protocolType, out error), true);
+#else
             m_Handle = SafeCloseSocket.CreateWSASocket(
                     addressFamily,
                     socketType,
                     protocolType);
+#endif
 
             if (m_Handle.IsInvalid) {
                 //
@@ -167,10 +174,14 @@ namespace System.Net.Sockets {
                 SetIPProtectionLevel(defaultProtectionLevel);
             }
 
+#if MONO
+            SocketDefaults ();
+#endif
+
             if(s_LoggingEnabled)Logging.Exit(Logging.Sockets, this, "Socket", null);
         }
 
-
+#if !MONO
         public Socket(SocketInformation socketInformation) {
             s_LoggingEnabled = Logging.On;
             if(s_LoggingEnabled)Logging.Enter(Logging.Sockets, this, "Socket", addressFamily);
@@ -288,7 +299,7 @@ namespace System.Net.Sockets {
             protocolType = Sockets.ProtocolType.Unknown;
             if(s_LoggingEnabled)Logging.Exit(Logging.Sockets, this, "Socket", null);
         }
-
+#endif
 
 
 //************* properties *************************
@@ -339,7 +350,7 @@ namespace System.Net.Sockets {
             }
         }
 
-
+#if !MONO
         /// <devdoc>
         ///    <para>
         ///       Gets the amount of data pending in the network's input buffer that can be
@@ -5716,7 +5727,7 @@ namespace System.Net.Sockets {
             InternalSetBlocking(willBlockInternal);
             if(s_LoggingEnabled)Logging.Exit(Logging.Sockets, this, "Shutdown", "");
         }
-
+#endif
 
 
 //************* internal and private properties *************************
@@ -5731,6 +5742,7 @@ namespace System.Net.Sockets {
             }
         }
 
+#if !MONO
         private CacheSet Caches
         {
             get
@@ -6004,13 +6016,14 @@ namespace System.Net.Sockets {
 
             return socketAddress;
         }
-
+#endif
 
         internal static void InitializeSockets() {
             if (!s_Initialized) {
                 lock(InternalSyncObject){
                     if (!s_Initialized) {
 
+#if !MONO
                         WSAData wsaData = new WSAData();
 
                         SocketError errorCode =
@@ -6025,6 +6038,7 @@ namespace System.Net.Sockets {
                             // WSAStartup does not set LastWin32Error
                             throw new SocketException(errorCode);
                         }
+#endif
 
 #if !FEATURE_PAL
                         //
@@ -6045,6 +6059,10 @@ namespace System.Net.Sockets {
                         bool   ipv4      = true; 
                         bool   ipv6      = true; 
 
+#if MONO
+                        ipv4 = IsProtocolSupported (System.Net.NetworkInformation.NetworkInterfaceComponent.IPv4);
+                        ipv6 = IsProtocolSupported (System.Net.NetworkInformation.NetworkInterfaceComponent.IPv6);
+#else
                         SafeCloseSocket.InnerSafeCloseSocket socketV4 = 
                                                              UnsafeNclNativeMethods.OSSOCK.WSASocket(
                                                                     AddressFamily.InterNetwork, 
@@ -6078,7 +6096,7 @@ namespace System.Net.Sockets {
                         socketV6.Close();
 
                         // <
-
+#endif // MONO
 
 
 #if COMNET_DISABLEIPV6
@@ -6112,16 +6130,19 @@ namespace System.Net.Sockets {
 
                         // Cache some settings locally.
 
+#if !MONO
 #if !FEATURE_PAL // perfcounter
                         s_PerfCountersEnabled = NetworkingPerfCounters.Instance.Enabled;
 #endif
+#endif
+
                         s_Initialized = true;
                     }
                 }
             }
         }
 
-
+#if !MONO
         internal void InternalConnect(EndPoint remoteEP)
         {
             EndPoint endPointSnapshot = remoteEP;
@@ -8406,7 +8427,7 @@ namespace System.Net.Sockets {
         internal AcceptAsyncResult(object myObject, object myState, AsyncCallback myCallBack):base(myObject, myState, myCallBack) {
         }
     }
-
+#endif
 
     public enum SocketAsyncOperation {
         None = 0,
@@ -8427,7 +8448,11 @@ namespace System.Net.Sockets {
         internal byte [] m_Buffer;
         internal int m_Offset;
         internal int m_Count;
+#if MONO
+        bool m_endOfPacket;
+#else
         internal UnsafeNclNativeMethods.OSSOCK.TransmitPacketsElementFlags m_Flags;
+#endif
 
         // hide default constructor
         private SendPacketsElement() {}
@@ -8453,8 +8478,13 @@ namespace System.Net.Sockets {
             }
             Contract.EndContractBlock();
 
+#if MONO
+            Initialize(filepath, null, offset, count, /*UnsafeNclNativeMethods.OSSOCK.TransmitPacketsElementFlags.File,*/
+                endOfPacket);
+#else
             Initialize(filepath, null, offset, count, UnsafeNclNativeMethods.OSSOCK.TransmitPacketsElementFlags.File,
                 endOfPacket);
+#endif
         }
 
         // constructors for buffer elements
@@ -8476,21 +8506,30 @@ namespace System.Net.Sockets {
             }
             Contract.EndContractBlock();
 
+#if MONO
+            Initialize(null, buffer, offset, count, /*UnsafeNclNativeMethods.OSSOCK.TransmitPacketsElementFlags.Memory,*/
+                endOfPacket);
+#else
             Initialize(null, buffer, offset, count, UnsafeNclNativeMethods.OSSOCK.TransmitPacketsElementFlags.Memory, 
                 endOfPacket);
+#endif
         }
 
         private void Initialize(string filePath, byte[] buffer, int offset, int count, 
-            UnsafeNclNativeMethods.OSSOCK.TransmitPacketsElementFlags flags, bool endOfPacket) {
+            /*UnsafeNclNativeMethods.OSSOCK.TransmitPacketsElementFlags flags,*/ bool endOfPacket) {
 
             m_FilePath = filePath;
             m_Buffer = buffer;
             m_Offset = offset;
             m_Count = count;
+#if MONO
+            m_endOfPacket = endOfPacket;
+#else
             m_Flags = flags;
             if (endOfPacket) {
                 m_Flags |= UnsafeNclNativeMethods.OSSOCK.TransmitPacketsElementFlags.EndOfPacket;
             }
+#endif
         }
 
         // Filename property
@@ -8515,7 +8554,13 @@ namespace System.Net.Sockets {
 
         // EndOfPacket property
         public bool EndOfPacket {
-            get { return (m_Flags & UnsafeNclNativeMethods.OSSOCK.TransmitPacketsElementFlags.EndOfPacket) != 0; }
+            get {
+#if MONO
+                return m_endOfPacket;
+#else
+                return (m_Flags & UnsafeNclNativeMethods.OSSOCK.TransmitPacketsElementFlags.EndOfPacket) != 0;
+#endif
+             }
         }
     }
 
@@ -8530,6 +8575,7 @@ namespace System.Net.Sockets {
     }
     #endregion        
 
+#if !MONO
     public class SocketAsyncEventArgs : EventArgs, IDisposable {
 
         // Struct sizes needed for some custom marshalling.
index a9be75be0a64be172631a8208a3654087be8cb87..9f1444146c15c608265776922dd3d83da803f650 100644 (file)
@@ -1209,7 +1209,6 @@ namespace System.Net {
             }
         }
 
-#if !MONO
         //
         internal void SetupCacheProtocol(Uri uri)
         {
@@ -1224,6 +1223,7 @@ namespace System.Net {
             }
         }
 
+#if !MONO
         delegate void DelEtwFireBeginWRGet(object id, string uri, bool success, bool synchronous);
         delegate void DelEtwFireEndWRGet(object id, bool success, bool synchronous);
         delegate void DelEtwFireEndWRespGet(object id, bool success, bool synchronous, int statusCode);
index 2a315eaf42426b0beae95ed064b64a4e4168d184..501fc3493562b8bdc73c722de30153dc2038161e 100644 (file)
@@ -146,7 +146,9 @@ namespace System.Net {
             }
             public object OwningObject;
             public GeneralAsyncDelegate AsyncCallback;
+#if !MONO
             public bool Completed;
+#endif
             public ConnectionPool Pool;
             public int CreationTimeout;
         }
@@ -811,7 +813,9 @@ namespace System.Net {
     /// </devdoc>
     sealed internal class InterlockedStack {
         private readonly Stack _stack = new Stack();
+#if !MONO
         private int _count;
+#endif
 
 #if DEBUG
         private readonly Hashtable doublepush = new Hashtable();
@@ -832,7 +836,9 @@ namespace System.Net {
 #if DEBUG
                 GlobalLog.Assert(_count+1 == _stack.Count, "push count mishandle");
 #endif
+#if !MONO
                 _count = _stack.Count;
+#endif
             }
         }
 
@@ -845,7 +851,9 @@ namespace System.Net {
                     GlobalLog.Assert(_count-1 == _stack.Count, "pop count mishandle");
                     doublepush.Remove(pooledStream);
 #endif
+#if !MONO
                     _count = _stack.Count;
+#endif
                 }
                 return pooledStream;
             }
index 0db05f3620e2fc500dfb3c0db05801c66b6bf99c..8e2c50447f2275d3045433a231570f072dd588c1 100644 (file)
@@ -18,8 +18,10 @@ namespace System.Net {
 
         private static WaitCallback s_GetRequestStreamCallback = new WaitCallback(GetRequestStreamCallback);
         private static WaitCallback s_GetResponseCallback = new WaitCallback(GetResponseCallback);
+#if !MONO
         private static ContextCallback s_WrappedGetRequestStreamCallback = new ContextCallback(GetRequestStreamCallback);
         private static ContextCallback s_WrappedResponseCallback = new ContextCallback(GetResponseCallback);
+#endif
 
     // fields
 
index 80acb75ad34e7d3d5b2b24817a568c07b451b34f..510d7922bc73d878c8ae327beff78ae60ae00458 100644 (file)
@@ -1092,7 +1092,11 @@ namespace System.Net {
 
             internal long ContentLength;
             internal long Length;
+#if MONO
+            const int Offset = 0;
+#else
             internal int  Offset;
+#endif
 
 
             internal ProgressData Progress;
@@ -1365,8 +1369,10 @@ namespace System.Net {
                 WebClient = webClient;
             }
 
+#if !MONO
             internal long Length;
             internal int  Offset;
+#endif
 
             internal ProgressData Progress;
 
index 9f55631246f21d5a8d9579df9422dc10efdc4183..1a587adf4e833b9fe51d569212471200a7005722 100644 (file)
@@ -443,6 +443,11 @@ namespace System {
         {
             Uri result;
 
+#if MONO
+            if (uriKind == UriKind.RelativeOrAbsolute)
+                uriKind = DotNetRelativeOrAbsolute;
+#endif
+
             if (!Uri.TryCreate(uriString, uriKind, out result))
                 return false;
 
index 6f191129671672f5a0d3c58901385525b798814c..6d603688023c9cc7d06bcf48021419eb519cb3c3 100644 (file)
@@ -3033,7 +3033,9 @@ namespace System.Text.RegularExpressions {
 
     internal class RegexTypeCompiler : RegexCompiler {
         private static int _typeCount = 0;
+#if !MONO
         private static LocalDataStoreSlot _moduleSlot = Thread.AllocateDataSlot();
+#endif
 
         private  AssemblyBuilder _assembly;
         private  ModuleBuilder  _module;
index f5fabc69b61c62caeab800216bb48ca02982fb76..7be029f7e81e27c00a6f6cb479eab8e084d77c7f 100644 (file)
@@ -41,8 +41,10 @@ namespace System.Diagnostics {
         // a user's char[] directly, instead of our internal char[].
         private int _maxCharsPerBuffer;
 
+#pragma warning disable 414
         // Store a backpointer to the process class, to check for user callbacks
         private Process process;
+#pragma warning restore
 
         // Delegate to call user function.
         private UserCallBack userCallBack;
@@ -57,6 +59,11 @@ namespace System.Diagnostics {
         // Cache the last position scanned in sb when searching for lines.
         private int currentLinePos;
                
+#if MONO
+               //users to coordinate between Dispose and BeginReadLine
+               private object syncObject = new Object ();
+#endif
+
         internal AsyncStreamReader(Process process, Stream stream, UserCallBack callback, Encoding encoding) 
             : this(process, stream, callback, encoding, DefaultBufferSize) {
         }
@@ -104,6 +111,9 @@ namespace System.Diagnostics {
 
         protected virtual void Dispose(bool disposing)
         {
+#if MONO
+            lock (syncObject) {
+#endif
             if (disposing) {
                 if (stream != null)
                     stream.Close();
@@ -120,6 +130,9 @@ namespace System.Diagnostics {
                 eofEvent.Close();
                 eofEvent = null;
             }
+#if MONO
+            }
+#endif
         }
         
         public virtual Encoding CurrentEncoding {
@@ -155,6 +168,12 @@ namespace System.Diagnostics {
             int byteLen;
             
             try {
+#if MONO
+                var stream = this.stream;
+                if (stream == null)
+                byteLen = 0;
+                else
+#endif
                 byteLen = stream.EndRead(ar);
             }
             catch (IOException ) {
@@ -171,6 +190,9 @@ namespace System.Diagnostics {
                 byteLen = 0; // Treat this as EOF
             }
                 
+#if MONO
+retry_dispose:
+#endif
             if (byteLen == 0) { 
                 // We're at EOF, we won't call this function again from here on.
                 lock(messageQueue) {
@@ -186,13 +208,45 @@ namespace System.Diagnostics {
                     FlushMessageQueue();
                 }
                 finally {
+#if MONO
+                    lock (syncObject) {
+                        if (eofEvent != null) {
+                            try {
+                                eofEvent.Set ();
+                            } catch (System.ObjectDisposedException) {
+                                // This races with Dispose, it's safe to ignore the error as it comes from a SafeHandle doing its job
+                            }
+                        }
+                    }
+#else
                     eofEvent.Set();
+#endif
                 }
             } else {
+#if MONO
+                lock (syncObject) {
+                    if (decoder == null) { //we got disposed after the EndRead, retry as Diposed
+                        byteLen = 0;
+                        goto retry_dispose;
+                    }
+#endif
                 int charLen = decoder.GetChars(byteBuffer, 0, byteLen, charBuffer, 0);
                 sb.Append(charBuffer, 0, charLen);
+#if MONO
+                }
+#endif
                 GetLinesFromStringBuilder();
+#if MONO
+                lock (syncObject) {
+                    if (stream == null) { //we got disposed after the EndRead, retry as Diposed
+                        byteLen = 0;
+                        goto retry_dispose;
+                    }
+#endif
                 stream.BeginRead(byteBuffer, 0 , byteBuffer.Length,  new AsyncCallback(ReadBuffer), null);
+#if MONO
+                }
+#endif
             }
         }
         
index cbd2456ab966dcad784e6055e16ea4b2a7964721..13016654b5ce11c726809607480a982610e976c0 100644 (file)
@@ -91,12 +91,14 @@ namespace System.Diagnostics {
                
         DateTime exitTime;
         bool haveExitTime;
-        
+
+#if !MONO
         bool responding;
         bool haveResponding;
         
         bool priorityBoostEnabled;
         bool havePriorityBoostEnabled;
+#endif
         
         bool raisedOnExited;
         RegisteredWaitHandle registeredWaitHandle;
@@ -108,7 +110,9 @@ namespace System.Diagnostics {
         OperatingSystem operatingSystem;
         bool disposed;
         
+#if !MONO
         static object s_CreateProcessLock = new object();
+#endif
         
         // This enum defines the operation mode for redirected process stream.
         // We don't support switching between synchronous mode and asynchronous mode.
@@ -122,6 +126,9 @@ namespace System.Diagnostics {
         StreamReadMode outputStreamReadMode;
         StreamReadMode errorStreamReadMode;
         
+#if MONO
+        StreamReadMode inputStreamReadMode;
+#endif
        
         // Support for asynchrously reading streams
         [Browsable(true), MonitoringDescription(SR.ProcessAssociated)]
@@ -136,8 +143,9 @@ namespace System.Diagnostics {
         internal bool pendingOutputRead;
         internal bool pendingErrorRead;
 
-
+#if !MONO
         private static SafeFileHandle InvalidPipeHandle = new SafeFileHandle(IntPtr.Zero, false);
+#endif
 #if DEBUG
         internal static TraceSwitch processTracing = new TraceSwitch("processTracing", "Controls debug output from Process component");
 #else
@@ -1183,6 +1191,9 @@ namespace System.Diagnostics {
                     throw new InvalidOperationException(SR.GetString(SR.CantGetStandardIn));
                 }
 
+#if MONO
+                inputStreamReadMode = StreamReadMode.syncMode;
+#endif
                 return standardInput;
             }
         }
@@ -1346,6 +1357,40 @@ namespace System.Diagnostics {
                 machineName = ".";
                 raisedOnExited = false;
 
+#if MONO
+                //Call close on streams if the user never saw them.
+                //A stream in the undefined mode was never fetched by the user.
+                //A stream in the async mode is wrapped on a AsyncStreamReader and we should dispose that instead.
+                //  no way for users to get a hand on a AsyncStreamReader.
+                var tmpIn = standardInput;
+                standardInput = null;
+                if (inputStreamReadMode == StreamReadMode.undefined && tmpIn != null)
+                    tmpIn.Close ();
+
+                var tmpOut = standardOutput;
+                standardOutput = null;
+                if (outputStreamReadMode == StreamReadMode.undefined && tmpOut != null)
+                    tmpOut.Close ();
+
+                tmpOut = standardError;
+                standardError = null;
+                if (errorStreamReadMode == StreamReadMode.undefined && tmpOut != null)
+                    tmpOut.Close ();
+
+                var tmpAsync = output;
+                output = null;
+                if (outputStreamReadMode == StreamReadMode.asyncMode && tmpAsync != null) {
+                    tmpAsync.CancelOperation ();
+                    tmpAsync.Close ();
+                }
+
+                tmpAsync = error;
+                error = null;
+                if (errorStreamReadMode == StreamReadMode.asyncMode && tmpAsync != null) {
+                    tmpAsync.CancelOperation ();
+                    tmpAsync.Close ();
+                }
+#else
                 //Don't call close on the Readers and writers
                 //since they might be referenced by somebody else while the 
                 //process is still alive but this method called.
@@ -1356,6 +1401,7 @@ namespace System.Diagnostics {
                 output = null;
                 error = null;
        
+#endif
 
                 Refresh();
             }
@@ -1832,8 +1878,10 @@ namespace System.Diagnostics {
             haveProcessorAffinity = false;
             havePriorityClass = false;
             haveExitTime = false;
+#if !MONO
             haveResponding = false;
             havePriorityBoostEnabled = false;
+#endif
         }
 
         /// <devdoc>
index 147ef7382e1b349d631e9834a24caebff0d7bdb9..4bfcfea188124d36797966b59cecc4d6dfd0a893 100644 (file)
@@ -1357,8 +1357,9 @@ namespace System.Globalization {
         {
             return NativeInternalInitSortHandle(localeName, out handleOrigin);
         }
+#endif
 
-#if !FEATURE_CORECLR
+#if !FEATURE_CORECLR || MONO
         private const int SORT_VERSION_WHIDBEY = 0x00001000;
         private const int SORT_VERSION_V4 = 0x00060101;
 
@@ -1375,7 +1376,11 @@ namespace System.Globalization {
             [System.Security.SecuritySafeCritical]
             get
             {
+#if MONO
+                return SORT_VERSION_V4;
+#else
                 return InternalGetSortVersion();
+#endif
             }
         }
 
@@ -1389,16 +1394,21 @@ namespace System.Globalization {
             {
                 if(m_SortVersion == null) 
                 {
+#if MONO
+                    m_SortVersion = new SortVersion(SORT_VERSION_V4, new Guid("00000001-57ee-1e5c-00b4-d0000bb1e11e")); // Guid returned by corefx and .NET 4.6
+#else
                     Win32Native.NlsVersionInfoEx v = new Win32Native.NlsVersionInfoEx();
                     v.dwNLSVersionInfoSize = Marshal.SizeOf(typeof(Win32Native.NlsVersionInfoEx));
                     InternalGetNlsVersionEx(m_dataHandle, m_handleOrigin, m_sortName, ref v);
                     m_SortVersion = new SortVersion(v.dwNLSVersion, (v.dwEffectiveId != 0) ? v.dwEffectiveId : LCID, v.guidCustomVersion);
+#endif
                 }
 
                 return m_SortVersion;
             }
         }
-        
+
+#if !MONO
         [System.Security.SecurityCritical]
         [ResourceExposure(ResourceScope.None)]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
@@ -1412,7 +1422,6 @@ namespace System.Globalization {
         [SuppressUnmanagedCodeSecurity]
         private static extern uint InternalGetSortVersion();
 
-#endif
         [System.Security.SecurityCritical]
         [ResourceExposure(ResourceScope.None)]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
@@ -1456,6 +1465,8 @@ namespace System.Globalization {
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern int InternalGetSortKey(IntPtr handle, IntPtr handleOrigin, String localeName, int flags, String source, int sourceCount, byte[] target, int targetCount);
+#endif
+
 #endif
     }
 }
index b74e4d606b57f0e28c77d31cb059015706e0da26..dd983a383ef6c34e6c4701fd694e9f9ea6dffe6a 100644 (file)
@@ -151,7 +151,13 @@ namespace System.Runtime.InteropServices {
             }
         }
 
-#if FEATURE_COMINTEROP && !MONO
+#if FEATURE_COMINTEROP || MONO
+#if MONO
+        private static IntPtr GetRuntimeInterfaceImpl(Guid clsid, Guid riid)
+        {
+            throw new NotSupportedException();
+        }
+#else
         [System.Security.SecurityCritical]
         [ResourceExposure(ResourceScope.Process)]
         [ResourceConsumption(ResourceScope.Process)]
@@ -160,6 +166,7 @@ namespace System.Runtime.InteropServices {
         private static extern IntPtr GetRuntimeInterfaceImpl(
             [In, MarshalAs(UnmanagedType.LPStruct)] Guid clsid,
             [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid);
+#endif
 
         //
         // This function does the equivalent of calling GetInterface(clsid, riid) on the
index c97acf8e60bef4fd1ebc624a257471ef823acc8d..89877e0add7f11bfb3a72d4148a5df8f9e96a7f6 100644 (file)
@@ -70,6 +70,9 @@ namespace System.Security.Cryptography {
         [System.Security.SecuritySafeCritical]  // auto-generated
         public override ICryptoTransform CreateEncryptor (byte[] rgbKey, byte[] rgbIV) {
 #if MONO
+            if (m_use40bitSalt)
+                throw new NotImplementedException ("UseSalt=true is not implemented on Mono yet");
+
             return new RC2Transform (this, true, rgbKey, rgbIV);
 #else
             return _NewEncryptor(rgbKey, ModeValue, rgbIV, EffectiveKeySizeValue, 
@@ -80,6 +83,9 @@ namespace System.Security.Cryptography {
         [System.Security.SecuritySafeCritical]  // auto-generated
         public override ICryptoTransform CreateDecryptor (byte[] rgbKey, byte[] rgbIV) {
 #if MONO
+            if (m_use40bitSalt)
+                throw new NotImplementedException ("UseSalt=true is not implemented on Mono yet");
+
             return new RC2Transform (this, false, rgbKey, rgbIV);
 #else
             return _NewEncryptor(rgbKey, ModeValue, rgbIV, EffectiveKeySizeValue,
index 804eeda9bdac32d93a1173972e7989b8989a6352..63bbb53d3b13d3a79dcc27a74c3f003d6b71b568 100644 (file)
@@ -209,13 +209,15 @@ namespace System.Security.Cryptography {
             m_block++;
             return ret;
         }
-#if !MONO
         [System.Security.SecuritySafeCritical]  // auto-generated
         public byte[] CryptDeriveKey(string algname, string alghashname, int keySize, byte[] rgbIV)
         {
             if (keySize < 0)
                 throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeySize"));
 
+#if MONO
+            throw new NotSupportedException ("CspParameters are not supported by Mono");
+#else
             int algidhash = X509Utils.NameOrOidToAlgId(alghashname, OidGroup.HashAlgorithm);
             if (algidhash == 0)
                 throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_InvalidAlgorithm"));
@@ -233,8 +235,10 @@ namespace System.Security.Cryptography {
                       m_password, m_password.Length, keySize << 16, rgbIV, rgbIV.Length,
                       JitHelpers.GetObjectHandleOnStack(ref key));
             return key;
+#endif
         }
 
+#if !MONO
         [System.Security.SecurityCritical] // auto-generated
         private SafeProvHandle _safeProvHandle = null;
         private SafeProvHandle ProvHandle
index 118d89410e2efbb38ce56371da9b5012593e7e5a..74e77b0edf0f66df063ca925485701b4a139b671 100644 (file)
@@ -91,8 +91,11 @@ namespace MonoTests.Helpers
                                        listenSocket = tcpListener.AcceptSocket ();
                                        listenSocket.Send (requestHandler (listenSocket));
                                        try {
-                                               listenSocket.Shutdown (SocketShutdown.Receive);
+                                               // On Windows a Receive() is needed here before Shutdown() to consume the data some tests send.
+                                               listenSocket.ReceiveTimeout = 10 * 1000;
+                                               listenSocket.Receive (new byte [0]);
                                                listenSocket.Shutdown (SocketShutdown.Send);
+                                               listenSocket.Shutdown (SocketShutdown.Receive);
                                        } catch {
                                        }
                                } catch (SocketException ex) {
index 1915a07240b379fdf4443385f6bd5a0af1e07783..e6a95fe8163a3590acb9f23602cc10d4cdec63dd 100644 (file)
@@ -2465,6 +2465,12 @@ namespace Mono.CSharp
                                case '\"':
                                        ++str_quote;
                                        break;
+                               case '\\':
+                                       // Skip escaped " character
+                                       c = reader.Read ();
+                                       if (c == -1)
+                                               res = false;
+                                       break;
                                case -1:
                                        res = false;
                                        break;
index 17dc6f8817627126ab4fcd9d4f39b3f1dcd9fd88..14824d136b63f814975bdcedd6be3580593ce98e 100644 (file)
@@ -356,26 +356,23 @@ namespace Mono.CSharp
                        }
 
                        if (version_mismatch != null) {
-                               if (version_mismatch is AssemblyBuilder)
+                               if (is_fx_assembly || version_mismatch is AssemblyBuilder)
                                        return version_mismatch;
 
                                var ref_an = new AssemblyName (refname);
                                var v1 = ref_an.Version;
                                var v2 = version_mismatch.GetName ().Version;
+                               AssemblyReferenceMessageInfo messageInfo;
 
                                if (v1 > v2) {
-                                       var messageInfo = new AssemblyReferenceMessageInfo (ref_an, report => {
+                                       messageInfo = new AssemblyReferenceMessageInfo (ref_an, report => {
                                                report.SymbolRelatedToPreviousError (args.RequestingAssembly.Location);
                                                report.Error (1705, string.Format ("Assembly `{0}' depends on `{1}' which has a higher version number than referenced assembly `{2}'",
                                                                                                                   args.RequestingAssembly.FullName, refname, version_mismatch.GetName ().FullName));
                                        });
 
-                                       AddReferenceVersionMismatch (args.RequestingAssembly.GetName (), messageInfo);
-                                       return version_mismatch;
-                               }
-
-                               if (!is_fx_assembly) {
-                                       var messageInfo = new AssemblyReferenceMessageInfo (ref_an, report => {
+                               } else {
+                                       messageInfo = new AssemblyReferenceMessageInfo (ref_an, report => {
                                                if (v1.Major != v2.Major || v1.Minor != v2.Minor) {
                                                        report.Warning (1701, 2,
                                                                "Assuming assembly reference `{0}' matches assembly `{1}'. You may need to supply runtime policy",
@@ -386,10 +383,10 @@ namespace Mono.CSharp
                                                                refname, version_mismatch.GetName ().FullName);
                                                }
                                        });
-
-                                       AddReferenceVersionMismatch (args.RequestingAssembly.GetName (), messageInfo);
                                }
 
+                               AddReferenceVersionMismatch (args.RequestingAssembly.GetName (), messageInfo);
+
                                return version_mismatch;
                        }
 
index 3dd99f5f2797f7c0db8b3b033fa08dedab20f9ca..4cf2e64196bd6b4a50cd1036eb0f2225dd3a5036 100644 (file)
@@ -13,6 +13,13 @@ public class ParserTest
                Console.WriteLine($"This should work but the compiler explodes if the string is too long!");            
        }
 
+       void Test3 ()
+       {
+               string field = "";
+               var l1 = $"\"{field.Replace("\"", "gg")}\"";
+               var l2 = $@"""{field.Replace("\"", "gg")}""";
+       }
+
        public static void Main()
        {
        }
index 0ac3d56b53db124bf9f98bfae87da7b2ecf8f4cc..56e35f7709f857723d5c158e14535337098d1e93 100644 (file)
       <method name="Void Test2()" attrs="129">
         <size>12</size>
       </method>
+      <method name="Void Test3()" attrs="129">
+        <size>62</size>
+      </method>
     </type>
   </test>
   <test name="test-interpolation-06.cs">
index 0ef071ffefa8f25f7007d209f264bc4ca46b0263..fcdc708e0ab56fb5cba3f56b43bc2912e8d9ee54 100644 (file)
@@ -2,7 +2,7 @@ using System;
 using System.IO;
 using System.Text;
 using System.Security.Cryptography.X509Certificates;
-using Mono.Btls;
+using MNS = Mono.Net.Security;
 
 namespace Mono.Btls
 {
@@ -10,7 +10,7 @@ namespace Mono.Btls
        {
                static void Main (string[] args)
                {
-                       if (!MonoBtlsProvider.IsSupported ()) {
+                       if (!MNS.MonoTlsProviderFactory.IsBtlsSupported ()) {
                                Console.Error.WriteLine ("BTLS is not supported in this runtime!");
                                Environment.Exit (255);
                        }
index f177c17ef3a5215b60d576381f6959ff3602b474..b9262adae0c7c88c205d58cfc235ed3d615723f7 100644 (file)
@@ -14,7 +14,7 @@ namespace Xamarin {
 
        public static class CommonCryptor {
                
-               static public void Generate (string namespaceName, string typeName, string baseTypeName, string ccAlgorithmName, string feedbackSize = "8", string ctorInitializers = null)
+               static public void Generate (string namespaceName, string typeName, string baseTypeName, string ccAlgorithmName, string feedbackSize = "8", string ctorInitializers = null, string decryptorInitializers = null, string encryptorInitializers = null, string properties = null)
                {
                        string template = @"// Generated file to bind CommonCrypto cipher algorithms - DO NOT EDIT
 //
@@ -38,7 +38,9 @@ namespace %NAMESPACE% {
                        FeedbackSizeValue = %FEEDBACKSIZE%;
                        %CTOR_INIT%
                }
-               
+
+               %PROPERTIES%
+
                public override void GenerateIV ()
                {
                        IVValue = KeyBuilder.IV (BlockSizeValue >> 3);
@@ -51,6 +53,8 @@ namespace %NAMESPACE% {
                
                public override ICryptoTransform CreateDecryptor (byte[] rgbKey, byte[] rgbIV) 
                {
+                       %CREATEDECRYPTOR_INIT%
+
                        IntPtr decryptor = IntPtr.Zero;
                        switch (Mode) {
                        case CipherMode.CBC:
@@ -74,6 +78,8 @@ namespace %NAMESPACE% {
                
                public override ICryptoTransform CreateEncryptor (byte[] rgbKey, byte[] rgbIV) 
                {
+                       %CREATEENCRYPTOR_INIT%
+                       
                        IntPtr encryptor = IntPtr.Zero;
                        switch (Mode) {
                        case CipherMode.CBC:
@@ -98,6 +104,9 @@ namespace %NAMESPACE% {
                        
                        File.WriteAllText (typeName + ".g.cs", template.Replace ("%NAMESPACE%", namespaceName).
                                Replace ("%TYPE%", typeName).Replace ("%BASE%", baseTypeName).Replace("%FEEDBACKSIZE%", feedbackSize).Replace ("%CTOR_INIT%", ctorInitializers).
+                               Replace ("%CREATEDECRYPTOR_INIT%", decryptorInitializers).
+                               Replace ("%CREATEENCRYPTOR_INIT%", encryptorInitializers).
+                               Replace ("%PROPERTIES%", properties).
                                Replace ("%CCALGORITHM%", ccAlgorithmName.ToString ()));
                }
        }
index a7d13c8cb80c9738d0cd90f07c07eb333f031e62..4fb846fe8f74fa1a879236ddd0c660d9dd84f117 100644 (file)
@@ -42,7 +42,13 @@ namespace Xamarin {
                        // 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) };");
+
+                       const string checkUseSalt = "if (UseSalt) throw new NotImplementedException (\"UseSalt=true is not implemented on Mono yet\");";
+                       CommonCryptor.Generate ("System.Security.Cryptography", "RC2CryptoServiceProvider", "RC2", "RC2",
+                               ctorInitializers: "LegalKeySizesValue = new[] { new KeySizes(40, 128, 8) };",
+                               decryptorInitializers: checkUseSalt,
+                               encryptorInitializers: checkUseSalt,
+                               properties: "public bool UseSalt { get; set; }");
                        // 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)
 
index 0c39910ff5ea06b2d5a538e7ebbda7b09f27f63b..9bf293d7f13fe527b221ceab7461a6c35e2a7d84 100644 (file)
@@ -69,29 +69,27 @@ namespace Mono.Linker.Steps {
                protected virtual void InitializeAssembly (AssemblyDefinition assembly)
                {
                        MarkAssembly (assembly);
-                       foreach (TypeDefinition type in assembly.MainModule.Types) {
-                               if (!Annotations.IsMarked (type))
-                                       continue;
 
+                       foreach (TypeDefinition type in assembly.MainModule.Types)
                                InitializeType (type);
-                       }
                }
 
                void InitializeType (TypeDefinition type)
                {
+                       if (type.HasNestedTypes) {
+                               foreach (var nested in type.NestedTypes)
+                                       InitializeType (nested);
+                       }
+
+                       if (!Annotations.IsMarked (type))
+                               return;
+
                        MarkType (type);
 
                        if (type.HasFields)
                                InitializeFields (type);
                        if (type.HasMethods)
                                InitializeMethods (type.Methods);
-
-                       if (type.HasNestedTypes) {
-                               foreach (var nested in type.NestedTypes) {
-                                       if (Annotations.IsMarked (nested))
-                                               InitializeType (nested);
-                               }
-                       }
                }
 
                void InitializeFields (TypeDefinition type)
index f7074361022d4314aa934b4e5954245d5adacf89..17ed9971f2f90fb1e8cc11851737175932c2d788 100644 (file)
@@ -70,6 +70,13 @@ MONO = \
        MONO_PATH="$(topdir)/class/lib/$(PROFILE)$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" \
        $(RUNTIME) $(RUNTIME_FLAGS)
 
+DIFF = diff -rup
+DIFF_QUIET = diff --brief
+ifeq ($(PLATFORM), win32)
+DIFF = diff -rupZ
+DIFF_QUIET = diff --brief -Z
+endif
+
 dist-local: dist-default dist-tests
 
 dist-tests:
@@ -160,7 +167,7 @@ check-monodocer-addNonGeneric: $(PROGRAM)
        $(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual Test/DocTest-addNonGeneric-v2.dll
        $(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual Test/DocTest-addNonGeneric-v2.dll
        $(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual Test/DocTest-addNonGeneric-v2.dll
-       diff -rup Test/en.expected-addNonGeneric Test/en.actual
+       $(DIFF) Test/en.expected-addNonGeneric Test/en.actual
 
 check-monodocer-dropns-classic: $(PROGRAM)
        # tests the simplest --dropns case, a single class where the root namespace was dropped.
@@ -168,7 +175,7 @@ check-monodocer-dropns-classic: $(PROGRAM)
        $(MAKE) Test/DocTest-DropNS-classic.dll
        $(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual Test/DocTest-DropNS-classic.dll --api-style=classic
        $(MAKE) update-monodocer-dropns-unified
-       diff -rup Test/en.expected-dropns-classic-v1 Test/en.actual
+       $(DIFF) Test/en.expected-dropns-classic-v1 Test/en.actual
 
 check-monodocer-dropns-multi: $(PROGRAM)
        -rm -Rf Test/en.actual
@@ -185,7 +192,7 @@ check-monodocer-dropns-multi: $(PROGRAM)
        $(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual $(MULTI-CLASSIC) --api-style=classic 
        $(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual $(MULTI-UNIFIED) --api-style=unified --dropns Test/DocTest-DropNS-unified.dll=MyFramework --dropns Test/DocTest-DropNS-unified-multitest.dll=MyFramework 
        
-       diff -rup Test/en.expected-dropns-multi Test/en.actual
+       $(DIFF) Test/en.expected-dropns-multi Test/en.actual
 
 
 check-monodocer-dropns-multi-withexisting: $(PROGRAM)
@@ -203,7 +210,7 @@ check-monodocer-dropns-multi-withexisting: $(PROGRAM)
        $(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual $(MULTI-CLASSIC) --api-style=classic 
        $(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual $(MULTI-UNIFIED) --api-style=unified --dropns Test/DocTest-DropNS-unified.dll=MyFramework --dropns Test/DocTest-DropNS-unified-multitest.dll=MyFramework 
        
-       diff -rup Test/en.expected-dropns-multi-withexisting Test/en.actual
+       $(DIFF) Test/en.expected-dropns-multi-withexisting Test/en.actual
 
 check-monodocer-dropns-delete: $(PROGRAM)
        -rm -Rf Test/en.actual
@@ -217,7 +224,7 @@ check-monodocer-dropns-delete: $(PROGRAM)
        $(MONO) $(PROGRAM) update --delete --exceptions=all -o Test/en.actual Test/DocTest-DropNS-classic-deletetest.dll --api-style=classic
        $(MAKE) Test/DocTest-DropNS-unified-deletetest-V2.dll
        $(MONO) $(PROGRAM) update --delete --exceptions=all -o Test/en.actual Test/DocTest-DropNS-unified-deletetest.dll --api-style=unified --dropns Test/DocTest-DropNS-unified-deletetest.dll=MyFramework
-       diff -rup Test/en.expected-dropns-delete Test/en.actual
+       $(DIFF) Test/en.expected-dropns-delete Test/en.actual
 
 check-monodocer-dropns-classic-withsecondary: $(PROGRAM)
        # tests case where a secondary assembly is included with a --dropns parameter
@@ -226,7 +233,7 @@ check-monodocer-dropns-classic-withsecondary: $(PROGRAM)
        $(MAKE) Test/DocTest-DropNS-classic-secondary.dll
        $(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual Test/DocTest-DropNS-classic.dll Test/DocTest-DropNS-classic-secondary.dll --api-style=classic
        $(MAKE) update-monodocer-dropns-unified-withsecondary
-       diff -rup Test/en.expected-dropns-classic-withsecondary Test/en.actual
+       $(DIFF) Test/en.expected-dropns-classic-withsecondary Test/en.actual
 
 update-monodocer-dropns-unified: $(PROGRAM)
        $(MAKE) Test/DocTest-DropNS-unified.dll
@@ -245,13 +252,13 @@ check-monodocer-internal-interface: $(PROGRAM)
        -rm -Rf Test/en.actual
        $(MAKE) Test/DocTest-InternalInterface.dll
        $(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual Test/DocTest-InternalInterface.dll
-       diff -rup Test/en.expected-internal-interface Test/en.actual
+       $(DIFF) Test/en.expected-internal-interface Test/en.actual
 
 check-monodocer-enumerations: $(PROGRAM)
        -rm -Rf Test/en.actual
        $(MAKE) Test/DocTest-enumerations.dll
        $(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual Test/DocTest-enumerations.dll
-       diff -rup Test/en.expected-enumerations Test/en.actual
+       $(DIFF) Test/en.expected-enumerations Test/en.actual
 
 check-monodocer-update: $(PROGRAM)
        find Test/en.expected -name \*.xml -exec rm "{}" \;
@@ -262,9 +269,9 @@ check-monodocer: $(PROGRAM)
        -rm -Rf Test/en.actual
        $(MAKE) Test/DocTest.dll-v1
        $(MONO) $(PROGRAM) update --debug --exceptions=all -o Test/en.actual Test/DocTest.dll
-       diff -rup Test/en.expected Test/en.actual
+       $(DIFF) Test/en.expected Test/en.actual
        $(MONO) $(PROGRAM) update --debug --exceptions=all -o Test/en.actual Test/DocTest.dll 
-       diff -rup Test/en.expected Test/en.actual
+       $(DIFF) Test/en.expected Test/en.actual
 
 check-monodocer-since-update: $(PROGRAM)
        find Test/en.expected.since -name \*.xml -exec rm "{}" \;
@@ -281,7 +288,7 @@ check-monodocer-since: $(PROGRAM)
        $(MAKE) Test/DocTest.dll-v2
        $(MONO) $(PROGRAM) --debug update --exceptions=all --since="Version 2.0" \
                -o Test/en.actual Test/DocTest.dll 
-       diff -rup Test/en.expected.since Test/en.actual
+       $(DIFF) Test/en.expected.since Test/en.actual
 
 check-monodocer-delete-update: $(PROGRAM)
        find Test/en.expected.delete -type f -exec rm "{}" \;
@@ -301,7 +308,7 @@ check-monodocer-delete: $(PROGRAM)
        $(MONO) $(PROGRAM) --debug update --exceptions=all -o Test/en.actual Test/DocTest.dll
        $(MAKE) Test/DocTest.dll-v1
        $(MONO) $(PROGRAM) --debug update -fno-assembly-versions --delete --exceptions=all -o Test/en.actual Test/DocTest.dll
-       diff -rup Test/en.expected.delete Test/en.actual
+       $(DIFF) Test/en.expected.delete Test/en.actual
 
 check-monodocer-importslashdoc-update: $(PROGRAM)
        find Test/en.expected.importslashdoc -name \*.xml -exec rm "{}" \;
@@ -314,7 +321,7 @@ check-monodocer-importslashdoc: $(PROGRAM)
        $(MAKE) Test/DocTest.dll-v1 TEST_CSCFLAGS=-doc:Test/DocTest.xml
        $(MONO) $(PROGRAM) --debug update --exceptions=all -i Test/DocTest.xml \
                -o Test/en.actual Test/DocTest.dll 
-       diff -rup Test/en.expected.importslashdoc Test/en.actual
+       $(DIFF) Test/en.expected.importslashdoc Test/en.actual
 
 check-monodocer-importecmadoc-update: $(PROGRAM)
        find Test/en.expected.importecmadoc -name \*.xml -exec rm "{}" \;
@@ -331,7 +338,7 @@ check-monodocer-importecmadoc: $(PROGRAM)
                '--type=System.Action`1' --type=System.AsyncCallback \
                --type=System.Environment --type=System.Array \
                -o Test/en.actual Test/DocTest.dll 
-       diff -rup Test/en.expected.importecmadoc Test/en.actual
+       $(DIFF) Test/en.expected.importecmadoc Test/en.actual
 
 check-mdoc-export-html-update: $(PROGRAM)
        find Test/html.expected -name \*.html -exec rm "{}" \;
@@ -342,7 +349,7 @@ check-mdoc-export-html: check-monodocer $(PROGRAM)
        rm -Rf Test/html.actual
        $(MONO) $(PROGRAM) export-html -o Test/html.actual \
                Test/en.expected.importslashdoc
-       diff -rup Test/html.expected Test/html.actual
+       $(DIFF) Test/html.expected Test/html.actual
 
 check-mdoc-export-html-with-version: $(PROGRAM)
        rm -Rf Test/html.actual.v0 Test/html.actual.since-with-v0 .v0.txt .v2.txt
@@ -352,12 +359,12 @@ check-mdoc-export-html-with-version: $(PROGRAM)
                Test/en.expected.since -with-version 0.0.0.0
        (cd Test/html.actual.v0            && find . -type f) | sort > .v0.txt
        (cd Test/html.actual.since-with-v0 && find . -type f) | sort > .v2.txt
-       diff -rup .v0.txt .v2.txt   # assert no types added
+       $(DIFF) .v0.txt .v2.txt   # assert no types added
 
 check-md-html-dir: $(PROGRAM)
        rm -Rf Test/html.actual
        $(MONO) $(PROGRAM) export-html -dest:Test/html.actual $(DIR) 
-       diff -rup Test/html.expected Test/html.actual
+       $(DIFF) Test/html.expected Test/html.actual
 
 check-mdoc-export-msxdoc-update:
        $(MONO) $(PROGRAM) export-msxdoc -o - Test/en.expected.importslashdoc \
@@ -365,7 +372,7 @@ check-mdoc-export-msxdoc-update:
 
 check-mdoc-export-msxdoc:
        $(MONO) $(PROGRAM) export-msxdoc -o - Test/en.expected.importslashdoc \
-               | diff --brief - Test/msxdoc-expected.importslashdoc.xml
+               | $(DIFF_QUIET) - Test/msxdoc-expected.importslashdoc.xml
 
 my_abs_top_srcdir = $(shell cd . && pwd)
 
@@ -383,13 +390,13 @@ check-mdoc-validate-update: $(PROGRAM)
 check-mdoc-validate: $(PROGRAM)
        $(MONO) $(PROGRAM) validate -f ecma Test/en.expected 2>&1 | \
                sed 's#file://$(my_abs_top_srcdir)/##g' | \
-               diff - Test/validate.check.monodocer
+               $(DIFF_QUIET) - Test/validate.check.monodocer
        $(MONO) $(PROGRAM) validate -f ecma Test/en.expected.importslashdoc 2>&1 | \
                sed 's#file://$(my_abs_top_srcdir)/##g' | \
-               diff --brief - Test/validate.check.monodocer.importslashdoc
+               $(DIFF_QUIET) - Test/validate.check.monodocer.importslashdoc
        $(MONO) $(PROGRAM) validate -f ecma Test/en.expected.since 2>&1 | \
                sed 's#file://$(my_abs_top_srcdir)/##g' | \
-               diff --brief - Test/validate.check.monodocer.since
+               $(DIFF_QUIET) - Test/validate.check.monodocer.since
 
 run-test-local: check-doc-tools
 
index 2913fe806d04da0f3a9591c61c0389d0aaf040b9..df2fb2702a3873ac3686354a19d5f0200f233e14 100644 (file)
@@ -26,7 +26,7 @@ SYMBOLICATE_EXPECTED_FILE = Test/symbolicate.expected
 CHECK_DIFF = @\
        $(MONO) $(TEST_EXE) > $(STACKTRACE_FILE); \
        $(MONO) $(LIB_PATH)/$(PROGRAM) $(MSYM_DIR) $(STACKTRACE_FILE) > $(SYMBOLICATE_RAW_FILE); \
-       sed "s/) .* in .*\/mcs\//) in mcs\//" $(SYMBOLICATE_RAW_FILE) | sed '/\[MVID\]/d' | sed '/\[AOTID\]/d' > $(SYMBOLICATE_RESULT_FILE); \
+       cat $(SYMBOLICATE_RAW_FILE) | tr '\\' '/' | sed "s/) .* in .*\/mcs\//) in mcs\//" | sed '/\[MVID\]/d' | sed '/\[AOTID\]/d' > $(SYMBOLICATE_RESULT_FILE); \
        DIFF=$$(diff -up $(SYMBOLICATE_EXPECTED_FILE) $(SYMBOLICATE_RESULT_FILE)); \
        if [ ! -z "$$DIFF" ]; then \
                echo "Symbolicate tests failed."; \
index f253194bd75a8d28d5ca08cf0ffc4f682db7e10f..56797562e50592fbcf07f610d2bc5b2eed162755 100644 (file)
@@ -50,7 +50,7 @@ namespace Mono.Tools
                static string inputFile;
                static bool quiet;
                static bool userStore;
-               static bool btlsStore = true;
+               static bool btlsStore = false;
 
                static X509Certificate DecodeCertificate (string s)
                {
@@ -179,8 +179,8 @@ namespace Mono.Tools
                                case "--user":
                                        userStore = true;
                                        break;
-                               case "--legacy":
-                                       btlsStore = false;
+                               case "--btls":
+                                       btlsStore = true;
                                        break;
                                default:
                                        WriteLine ("Unknown option '{0}'.", args[i]);
index 064a05d74e0932b8b4e6f28dd0b974a16f3b5e7c..0bb00bf184e34924b76ab1d5e6c7d545f38d1116 100644 (file)
@@ -1,7 +1,43 @@
 BTLS_STATIC_LIST = build-static/mono-btls-static-lo.txt
 BTLS_SHARED_LIST = build-shared/mono-btls-shared-lo.txt
 
-BTLS_DEPS = $(BTLS_LIBS) build-shared/Makefile build-static/Makefile
+EXTRA_DIST = btls-android-utils.c \
+       btls-bio.c \
+       btls-bio.h \
+       btls-error.c \
+       btls-error.h \
+       btls-key.c \
+       btls-key.h \
+       btls-pkcs12.c \
+       btls-pkcs12.h \
+       btls-ssl.c \
+       btls-ssl-ctx.c \
+       btls-ssl-ctx.h \
+       btls-ssl.h \
+       btls-util.c \
+       btls-util.h \
+       btls-x509.c \
+       btls-x509-chain.c \
+       btls-x509-chain.h \
+       btls-x509-crl.c \
+       btls-x509-crl.h \
+       btls-x509.h \
+       btls-x509-lookup.c \
+       btls-x509-lookup.h \
+       btls-x509-lookup-mono.c \
+       btls-x509-lookup-mono.h \
+       btls-x509-name.c \
+       btls-x509-name.h \
+       btls-x509-revoked.c \
+       btls-x509-revoked.h \
+       btls-x509-store.c \
+       btls-x509-store-ctx.c \
+       btls-x509-store-ctx.h \
+       btls-x509-store.h \
+       btls-x509-verify-param.c \
+       btls-x509-verify-param.h \
+       CMakeLists.txt \
+       create-object-library.sh
 
 CMAKE_VERBOSE=$(if $(V),VERBOSE=1,)
 
index d76d885e6a5d1324f55f38bb858f020ce7ada336..7a40f75b53bd2b8a720d51886a72fb146323afb8 100644 (file)
@@ -272,12 +272,13 @@ mono_btls_x509_name_get_entry_oid_data (MonoBtlsX509Name *name, int index, const
 }
 
 int
-mono_btls_x509_name_get_entry_value (MonoBtlsX509Name *name, int index, unsigned char **str)
+mono_btls_x509_name_get_entry_value (MonoBtlsX509Name *name, int index, int *tag, unsigned char **str)
 {
        X509_NAME_ENTRY *entry;
        ASN1_STRING *data;
 
        *str = NULL;
+       *tag = 0;
 
        if (index >= X509_NAME_entry_count (name->name))
                return 0;
@@ -290,5 +291,6 @@ mono_btls_x509_name_get_entry_value (MonoBtlsX509Name *name, int index, unsigned
        if (!data)
                return 0;
 
+       *tag = data->type;
        return ASN1_STRING_to_UTF8 (str, data);
 }
index 20c6a68656319dc5e4613466ac034c1bc385ba54..604de2bb5e6627a682debcd033b3c4bb23420cd3 100644 (file)
@@ -75,6 +75,6 @@ int
 mono_btls_x509_name_get_entry_oid_data (MonoBtlsX509Name *name, int index, const void **data);
 
 int
-mono_btls_x509_name_get_entry_value (MonoBtlsX509Name *name, int index, unsigned char **str);
+mono_btls_x509_name_get_entry_value (MonoBtlsX509Name *name, int index, int *tag, unsigned char **str);
 
 #endif /* __btls__btls_x509_name__ */
index 54174223fb9acc33a5ecddf9307375465d692dbb..bd3100885ccad1dfb4890f10f140ec29468a0e58 100644 (file)
@@ -139,7 +139,7 @@ int
 mono_btls_x509_get_serial_number (X509 *x509, char *buffer, int size, int mono_style)
 {
        ASN1_INTEGER *serial;
-       char *pos;
+       unsigned char *temp, *p;
        int len, idx;
 
        serial = X509_get_serialNumber (x509);
@@ -151,19 +151,24 @@ mono_btls_x509_get_serial_number (X509 *x509, char *buffer, int size, int mono_s
                return serial->length;
        }
 
-       pos = buffer;
-       len = 0;
+       temp = OPENSSL_malloc (serial->length + 1);
+       if (!temp)
+               return 0;
+
+       p = temp;
+       len = i2c_ASN1_INTEGER (serial, &p);
 
-       for (idx = serial->length - 1; idx >= 0; idx--) {
-               *pos++ = serial->data [idx];
-               len++;
+       if (!len) {
+               OPENSSL_free (temp);
+               return 0;
        }
 
-       if (serial->data [0] >= 0x80) {
-               *pos++ = 0;
-               len++;
+       for (idx = 0; idx < len; idx++) {
+               buffer [idx] = *(--p);
        }
+       buffer [len] = 0;
 
+       OPENSSL_free (temp);
        return len;
 }
 
index 6e4d6d578f6e54077e8873435e5b3576b7238085..fd55cd74314bcad2d4029a28d27bcec1c3fc8b9e 100644 (file)
@@ -412,10 +412,10 @@ is_managed_binary (const char *filename)
        off_t new_offset;
        unsigned char buffer[8];
        off_t file_size, optional_header_offset;
-       off_t pe_header_offset;
+       off_t pe_header_offset, clr_header_offset;
        gboolean managed = FALSE;
        int num_read;
-       guint32 first_word, second_word;
+       guint32 first_word, second_word, magic_number;
        
        /* If we are unable to open the file, then we definitely
         * can't say that it is managed. The child mono process
@@ -480,13 +480,34 @@ is_managed_binary (const char *filename)
        if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
                goto leave;
 
+       optional_header_offset = pe_header_offset + 24;
+
+       /* Read the PE magic number */
+       new_offset = lseek (file, optional_header_offset, SEEK_SET);
+       
+       if (new_offset != optional_header_offset)
+               goto leave;
+
+       num_read = read (file, buffer, 2);
+
+       if (num_read != 2)
+               goto leave;
+
+       magic_number = (buffer[0] | (buffer[1] << 8));
+       
+       if (magic_number == 0x10B)  // PE32
+               clr_header_offset = 208;
+       else if (magic_number == 0x20B)  // PE32+
+               clr_header_offset = 224;
+       else
+               goto leave;
+
        /* Read the CLR header address and size fields. These will be
         * zero if the binary is not managed.
         */
-       optional_header_offset = pe_header_offset + 24;
-       new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
+       new_offset = lseek (file, optional_header_offset + clr_header_offset, SEEK_SET);
 
-       if (new_offset != optional_header_offset + 208)
+       if (new_offset != optional_header_offset + clr_header_offset)
                goto leave;
 
        num_read = read (file, buffer, 8);
@@ -2685,8 +2706,6 @@ MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler, (int _dummy, sigi
        int pid;
        struct MonoProcess *p;
 
-       MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "SIG CHILD handler for pid: %i\n", info->si_pid);
-
        do {
                do {
                        pid = waitpid (-1, &status, WNOHANG);
@@ -2695,8 +2714,6 @@ MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler, (int _dummy, sigi
                if (pid <= 0)
                        break;
 
-               MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "child ended: %i", pid);
-
                /*
                 * This can run concurrently with the code in the rest of this module.
                 */
@@ -2714,8 +2731,6 @@ MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler, (int _dummy, sigi
                        p->freeable = TRUE;
                }
        } while (1);
-
-       MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "SIG CHILD handler: done looping.");
 }
 
 #endif
index 60d6b47a321a2c0de23a36b3034e2f82f2c8962c..3f754d04f3f26b85edc3d982fa69080c81d79737 100644 (file)
@@ -1,9 +1,21 @@
 if HOST_WIN32
 win32_sources = \
        console-win32.c \
+       console-win32-internals.h \
+       file-io-windows.c \
+       file-io-windows-internals.h \
+       icall-windows.c \
+       icall-windows-internals.h \
+       marshal-windows.c \
+       marshal-windows-internals.h \
+       mono-security-windows.c \
+       mono-security-windows-internals.h \
+       process-windows.c \
+       process-windows-internals.h \
        w32mutex-win32.c \
        w32semaphore-win32.c \
-       w32event-win32.c
+       w32event-win32.c \
+       socket-io-windows.c
 
 platform_sources = $(win32_sources)
 
@@ -96,7 +108,7 @@ mono-config-dirs.lo: Makefile
 libmonoruntime_config_la_SOURCES = \
        mono-config-dirs.h              \
        mono-config-dirs.c
-libmonoruntime_config_la_CPPFLAGS = $(AM_CPPFLAGS) -DMONO_BINDIR=\"$(bindir)/\" -DMONO_ASSEMBLIES=\"$(assembliesdir)\" -DMONO_CFG_DIR=\"$(confdir)\"
+libmonoruntime_config_la_CPPFLAGS = $(AM_CPPFLAGS) -DMONO_BINDIR=\"$(bindir)/\" -DMONO_ASSEMBLIES=\"$(assembliesdir)\" -DMONO_CFG_DIR=\"$(confdir)\" -DMONO_RELOC_LIBDIR=\"../$(reloc_libdir)\"
 
 CLEANFILES = mono-bundle.stamp
 
@@ -120,6 +132,7 @@ common_sources = \
        console-io.h            \
        coree.c                 \
        coree.h                 \
+       coree-internals.h \
        culture-info.h          \
        culture-info-tables.h   \
        debug-helpers.c         \
@@ -137,10 +150,12 @@ common_sources = \
        exception-internals.h   \
        file-io.c               \
        file-io.h               \
+       file-io-internals.h \
        filewatcher.c           \
        filewatcher.h           \
        gc-internals.h          \
        icall.c                 \
+       icall-internals.h \
        icall-def.h             \
        image.c                 \
        image-internals.h       \
@@ -152,6 +167,7 @@ common_sources = \
        lock-tracer.h           \
        marshal.c               \
        marshal.h               \
+       marshal-internals.h \
        mempool.c               \
        mempool.h               \
        mempool-internals.h     \
@@ -189,6 +205,7 @@ common_sources = \
        socket-io.h             \
        process.c               \
        process.h               \
+       process-internals.h \
        profiler.c              \
        profiler-private.h      \
        rand.h                  \
index 58fa379e5bb57a2c73580b74fc83680d022126eb..b4c20c8e22bd57c6fad22d3e588661b55df19a35 100644 (file)
@@ -84,7 +84,7 @@
  * Changes which are already detected at runtime, like the addition
  * of icalls, do not require an increment.
  */
-#define MONO_CORLIB_VERSION 158
+#define MONO_CORLIB_VERSION 160
 
 typedef struct
 {
@@ -1415,7 +1415,12 @@ shadow_copy_sibling (gchar *src, gint srclen, const char *extension, gchar *targ
        dest = g_utf8_to_utf16 (target, strlen (target), NULL, NULL, NULL);
        
        DeleteFile (dest);
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
        copy_result = CopyFile (orig, dest, FALSE);
+#else
+       copy_result = SUCCEEDED (CopyFile2 (orig, dest, NULL));
+#endif
 
        /* Fix for bug #556884 - make sure the files have the correct mode so that they can be
         * overwritten when updated in their original locations. */
@@ -1743,7 +1748,11 @@ mono_make_shadow_copy (const char *filename, MonoError *oerror)
                return (char *)filename;
        }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
        copy_result = CopyFile (orig, dest, FALSE);
+#else
+       copy_result = SUCCEEDED (CopyFile2 (orig, dest, NULL));
+#endif
 
        /* Fix for bug #556884 - make sure the files have the correct mode so that they can be
         * overwritten when updated in their original locations. */
@@ -2568,7 +2577,7 @@ mono_domain_try_unload (MonoDomain *domain, MonoObject **exc)
         * First we create a separate thread for unloading, since
         * we might have to abort some threads, including the current one.
         */
-       thread_handle = mono_threads_create_thread (unload_thread_main, thread_data, 0, &tid);
+       thread_handle = mono_threads_create_thread (unload_thread_main, thread_data, NULL, &tid);
        if (thread_handle == NULL)
                return;
 
index 64d1000bbb63b8f896164af207e176969b6ece3c..643c4930b1a29360e4c80fc4cae1df1cf51da0bf 100644 (file)
@@ -559,6 +559,21 @@ mono_assembly_getrootdir (void)
        return default_path [0];
 }
 
+/**
+ * mono_native_getrootdir:
+ * 
+ * Obtains the root directory used for looking up native libs (.so, .dylib).
+ *
+ * Returns: a string with the directory, this string should be freed by
+ * the caller.
+ */
+G_CONST_RETURN gchar *
+mono_native_getrootdir (void)
+{
+       gchar* fullpath = g_build_path (G_DIR_SEPARATOR_S, mono_assembly_getrootdir (), mono_config_get_reloc_lib_dir(), NULL);
+       return fullpath;
+}
+
 /**
  * mono_set_dirs:
  * @assembly_dir: the base directory for assemblies
index b414971e171dd40e479f0a4e7198fdf1691fbf0b..6126feda0e1c9053ddc792e2a466a1aa60dd2953 100644 (file)
@@ -37,6 +37,7 @@ MONO_RT_EXTERNAL_ONLY MONO_API MonoImage*    mono_assembly_load_module (MonoAsse
 MONO_API void          mono_assembly_close      (MonoAssembly *assembly);
 MONO_API void          mono_assembly_setrootdir (const char *root_dir);
 MONO_API MONO_CONST_RETURN char *mono_assembly_getrootdir (void);
+MONO_API MONO_CONST_RETURN char *mono_native_getrootdir (void);
 MONO_API void        mono_assembly_foreach    (MonoFunc func, void* user_data);
 MONO_API void          mono_assembly_set_main   (MonoAssembly *assembly);
 MONO_API MonoAssembly *mono_assembly_get_main   (void);
index ea7fa289a3899b91b7917f21311f394b2726788f..01d208c2ea275de80efa69f0f93dce1fe036edbf 100644 (file)
@@ -480,7 +480,7 @@ transport_start_receive (void)
        if (!listen_fd)
                return;
 
-       receiver_thread_handle = mono_threads_create_thread (receiver_thread, NULL, 0, NULL);
+       receiver_thread_handle = mono_threads_create_thread (receiver_thread, NULL, NULL, NULL);
        g_assert (receiver_thread_handle);
 }
 
index d084501c929424aa8dc14ccb01150eb818cee407..d3debe1cd03665f7ffe5df29c3a55de1bd885660 100644 (file)
@@ -1369,6 +1369,16 @@ mono_gc_get_logfile (void)
        return NULL;
 }
 
+void
+mono_gc_params_set (const char* options)
+{
+}
+
+void
+mono_gc_debug_set (const char* options)
+{
+}
+
 void
 mono_gc_conservatively_scan_area (void *start, void *end)
 {
@@ -1932,8 +1942,9 @@ mono_gchandle_free_domain (MonoDomain *domain)
 
 }
 #else
-       #ifdef _MSC_VER
-               // Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
-               void __mono_win32_boehm_gc_quiet_lnk4221(void) {}
-       #endif
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_boehm_gc_quiet_lnk4221(void) {}
+#endif
 #endif /* no Boehm GC */
index a8e73da2776eadca38a16ba93e64332eccce2750..6305d51c2682a171b9bdbc73969e8e36e00161a8 100644 (file)
@@ -324,12 +324,7 @@ struct _MonoClass {
        guint has_finalize_inited    : 1; /* has_finalize is initialized */
        guint fields_inited : 1; /* fields is initialized */
        guint setup_fields_called : 1; /* to prevent infinite loops in setup_fields */
-
-       guint8     exception_type;      /* MONO_EXCEPTION_* */
-
-       /* Additional information about the exception */
-       /* Stored as property MONO_CLASS_PROP_EXCEPTION_DATA */
-       //void       *exception_data;
+       guint has_failure : 1; /* See MONO_CLASS_PROP_EXCEPTION_DATA for a MonoErrorBoxed with the details */
 
        MonoClass  *parent;
        MonoClass  *nested_in;
@@ -1258,10 +1253,7 @@ const char*
 mono_lookup_jit_icall_symbol (const char *name);
 
 gboolean
-mono_class_set_failure (MonoClass *klass, guint32 ex_type, void *ex_data);
-
-gpointer
-mono_class_get_exception_data (MonoClass *klass);
+mono_class_set_type_load_failure (MonoClass *klass, const char * fmt, ...) MONO_ATTR_FORMAT_PRINTF(2,3);
 
 MonoException*
 mono_class_get_exception_for_failure (MonoClass *klass);
@@ -1437,20 +1429,9 @@ MonoClass*
 mono_class_try_load_from_name (MonoImage *image, const char* name_space, const char *name);
 
 void
-mono_error_set_for_class_failure (MonoError *orerror, MonoClass *klass);
+mono_error_set_for_class_failure (MonoError *orerror, const MonoClass *klass);
 
-static inline guint8
-mono_class_get_failure (MonoClass *klass)
-{
-       g_assert (klass != NULL);
-       return klass->exception_type;
-}
-
-static inline gboolean
-mono_class_has_failure (MonoClass *klass)
-{
-       g_assert (klass != NULL);
-       return mono_class_get_failure (klass) != MONO_EXCEPTION_NONE;
-}
+gboolean
+mono_class_has_failure (const MonoClass *klass);
 
 #endif /* __MONO_METADATA_CLASS_INTERNALS_H__ */
index ed14162510d11badbc487d7b615c825375583c8a..ba8197161313c653362b932564aca2ce7caae37d 100644 (file)
@@ -77,6 +77,10 @@ static guint32 mono_field_resolve_flags (MonoClassField *field);
 static void mono_class_setup_vtable_full (MonoClass *klass, GList *in_setup);
 static void mono_generic_class_setup_parent (MonoClass *klass, MonoClass *gklass);
 
+static gboolean mono_class_set_failure (MonoClass *klass, MonoErrorBoxed *boxed_error);
+static gpointer mono_class_get_exception_data (const MonoClass *klass);
+
+
 /*
 We use gclass recording to allow recursive system f types to be referenced by a parent.
 
@@ -1361,7 +1365,7 @@ fail:
 }
 
 /*
- * Checks for MonoClass::exception_type without resolving all MonoType's into MonoClass'es
+ * Checks for MonoClass::has_failure without resolving all MonoType's into MonoClass'es
  */
 static gboolean
 mono_type_has_exceptions (MonoType *type)
@@ -1381,26 +1385,11 @@ mono_type_has_exceptions (MonoType *type)
 }
 
 void
-mono_error_set_for_class_failure (MonoError *oerror, MonoClass *klass)
+mono_error_set_for_class_failure (MonoError *oerror, const MonoClass *klass)
 {
-       gpointer exception_data = mono_class_get_exception_data (klass);
-
-       switch (mono_class_get_failure(klass)) {
-       case MONO_EXCEPTION_TYPE_LOAD: {
-               mono_error_set_type_load_class (oerror, klass, "Error Loading class");
-               return;
-       }
-       case MONO_EXCEPTION_INVALID_PROGRAM: {
-               mono_error_set_invalid_program (oerror, "%s", (const char *)exception_data);
-               return;
-       }
-       case MONO_EXCEPTION_MISSING_METHOD:
-       case MONO_EXCEPTION_MISSING_FIELD:
-       case MONO_EXCEPTION_FILE_NOT_FOUND:
-       case MONO_EXCEPTION_BAD_IMAGE:
-       default:
-               g_assert_not_reached ();
-       }
+       g_assert (mono_class_has_failure (klass));
+       MonoErrorBoxed *box = (MonoErrorBoxed*)mono_class_get_exception_data (klass);
+       mono_error_set_from_boxed (oerror, box);
 }
 
 
@@ -1493,6 +1482,33 @@ mono_class_setup_basic_field_info (MonoClass *klass)
        }
 }
 
+/**
+ * mono_class_set_failure_causedby_class:
+ * @klass: the class that is failing
+ * @caused_by: the class that caused the failure
+ * @msg: Why @klass is failing.
+ * 
+ * If @caused_by has a failure, sets a TypeLoadException failure on
+ * @klass with message "@msg, due to: {@caused_by message}".
+ *
+ * Returns: TRUE if a failiure was set, or FALSE if @caused_by doesn't have a failure.
+ */
+static gboolean
+mono_class_set_type_load_failure_causedby_class (MonoClass *klass, const MonoClass *caused_by, const gchar* msg)
+{
+       if (mono_class_has_failure (caused_by)) {
+               MonoError cause_error;
+               mono_error_init (&cause_error);
+               mono_error_set_for_class_failure (&cause_error, caused_by);
+               mono_class_set_type_load_failure (klass, "%s, due to: %s", msg, mono_error_get_message (&cause_error));
+               mono_error_cleanup (&cause_error);
+               return TRUE;
+       } else {
+               return FALSE;
+       }
+}
+
+
 /** 
  * mono_class_setup_fields:
  * @class: The class to initialize
@@ -1580,10 +1596,8 @@ mono_class_setup_fields (MonoClass *klass)
 
        if (gtd) {
                mono_class_setup_fields (gtd);
-               if (mono_class_has_failure (gtd)) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+               if (mono_class_set_type_load_failure_causedby_class (klass, gtd, "Generic type definition failed"))
                        return;
-               }
        }
 
        instance_size = 0;
@@ -1595,10 +1609,8 @@ mono_class_setup_fields (MonoClass *klass)
                mono_class_init (klass->parent);
                if (!klass->parent->size_inited) {
                        mono_class_setup_fields (klass->parent);
-                       if (mono_class_has_failure (klass->parent)) {
-                               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+                       if (mono_class_set_type_load_failure_causedby_class (klass, klass->parent, "Could not set up parent class"))
                                return;
-                       }
                }
                instance_size += klass->parent->instance_size;
                klass->min_align = klass->parent->min_align;
@@ -1623,8 +1635,7 @@ mono_class_setup_fields (MonoClass *klass)
 
        if (explicit_size) {
                if ((packing_size & 0xffffff00) != 0) {
-                       char *err_msg = g_strdup_printf ("Could not load struct '%s' with packing size %d >= 256", klass->name, packing_size);
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, err_msg);
+                       mono_class_set_type_load_failure (klass, "Could not load struct '%s' with packing size %d >= 256", klass->name, packing_size);
                        return;
                }
                klass->packing_size = packing_size;
@@ -1691,15 +1702,15 @@ mono_class_setup_fields (MonoClass *klass)
                                field->offset = offset;
 
                                if (field->offset == (guint32)-1 && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
-                                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Missing field layout info for %s", field->name));
+                                       mono_class_set_type_load_failure (klass, "Missing field layout info for %s", field->name);
                                        break;
                                }
                                if (field->offset < -1) { /*-1 is used to encode special static fields */
-                                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Invalid negative field offset %d for %s", field->offset, field->name));
+                                       mono_class_set_type_load_failure (klass, "Field '%s' has a negative offset %d", field->name, field->offset);
                                        break;
                                }
                                if (klass->generic_container) {
-                                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Generic class cannot have explicit layout."));
+                                       mono_class_set_type_load_failure (klass, "Generic class cannot have explicit layout.");
                                        break;
                                }
                        }
@@ -1714,7 +1725,11 @@ mono_class_setup_fields (MonoClass *klass)
                                if (field_class) {
                                        mono_class_setup_fields (field_class);
                                        if (mono_class_has_failure (field_class)) {
-                                               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+                                               MonoError field_error;
+                                               mono_error_init (&field_error);
+                                               mono_error_set_for_class_failure (&field_error, field_class);
+                                               mono_class_set_type_load_failure (klass, "Could not set up field '%s' due to: %s", field->name, mono_error_get_message (&field_error));
+                                               mono_error_cleanup (&field_error);
                                                break;
                                        }
                                }
@@ -1732,7 +1747,7 @@ mono_class_setup_fields (MonoClass *klass)
                        char *class_name = mono_type_get_full_name (klass);
                        char *type_name = mono_type_full_name (field->type);
 
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+                       mono_class_set_type_load_failure (klass, "");
                        g_warning ("Invalid type %s for instance field %s:%s", type_name, class_name, field->name);
                        g_free (class_name);
                        g_free (type_name);
@@ -1747,7 +1762,7 @@ mono_class_setup_fields (MonoClass *klass)
        klass->blittable = blittable;
 
        if (klass->enumtype && !mono_class_enum_basetype (klass)) {
-               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+               mono_class_set_type_load_failure (klass, "The enumeration's base type is invalid.");
                return;
        }
        if (explicit_size && real_size) {
@@ -1760,7 +1775,7 @@ mono_class_setup_fields (MonoClass *klass)
 
        /*valuetypes can't be neither bigger than 1Mb or empty. */
        if (klass->valuetype && (klass->instance_size <= 0 || klass->instance_size > (0x100000 + sizeof (MonoObject))))
-               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+               mono_class_set_type_load_failure (klass, "Value type instance size (%d) cannot be zero, negative, or bigger than 1Mb", klass->instance_size);
 
        mono_memory_barrier ();
        klass->fields_inited = 1;
@@ -1945,10 +1960,8 @@ mono_class_layout_fields (MonoClass *klass, int instance_size)
 
                if (klass->parent) {
                        mono_class_setup_fields (klass->parent);
-                       if (mono_class_has_failure (klass->parent)) {
-                               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+                       if (mono_class_set_type_load_failure_causedby_class (klass, klass->parent, "Cannot initialize parent class"))
                                return;
-                       }
                        real_size = klass->parent->instance_size;
                } else {
                        real_size = sizeof (MonoObject);
@@ -2049,7 +2062,7 @@ mono_class_layout_fields (MonoClass *klass, int instance_size)
                        ftype = mono_type_get_basic_type_from_generic (ftype);
                        if (type_has_references (klass, ftype)) {
                                if (field->offset % sizeof (gpointer)) {
-                                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+                                       mono_class_set_type_load_failure (klass, "Reference typed field '%s' has explicit offset that is not pointer-size aligned.", field->name);
                                }
                        }
 
@@ -2087,8 +2100,7 @@ mono_class_layout_fields (MonoClass *klass, int instance_size)
                                // FIXME: Too much code does this
 #if 0
                                if (!MONO_TYPE_IS_REFERENCE (field->type) && ref_bitmap [field->offset / sizeof (gpointer)]) {
-                                       char *err_msg = mono_image_strdup_printf (klass->image, "Could not load type '%s' because it contains an object field at offset %d that is incorrectly aligned or overlapped by a non-object field.", klass->name, field->offset);
-                                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, err_msg);
+                                       mono_class_set_type_load_failure (klass, "Could not load type '%s' because it contains an object field at offset %d that is incorrectly aligned or overlapped by a non-object field.", klass->name, field->offset);
                                }
 #endif
                        }
@@ -2143,7 +2155,7 @@ mono_class_layout_fields (MonoClass *klass, int instance_size)
                        continue;
 
                if (mono_type_has_exceptions (field->type)) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+                       mono_class_set_type_load_failure (klass, "Field '%s' has an invalid type.", field->name);
                        break;
                }
 
@@ -2193,7 +2205,7 @@ create_array_method (MonoClass *klass, const char *name, MonoMethodSignature *si
  * Methods belonging to an interface are assigned a sequential slot starting
  * from 0.
  *
- * On failure this function sets klass->exception_type
+ * On failure this function sets klass->has_failure and stores a MonoErrorBoxed with details
  */
 void
 mono_class_setup_methods (MonoClass *klass)
@@ -2211,11 +2223,8 @@ mono_class_setup_methods (MonoClass *klass)
                mono_class_init (gklass);
                if (!mono_class_has_failure (gklass))
                        mono_class_setup_methods (gklass);
-               if (mono_class_has_failure (gklass)) {
-                       /* FIXME make exception_data less opaque so it's possible to dup it here */
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Generic type definition failed to load"));
+               if (mono_class_set_type_load_failure_causedby_class (klass, gklass, "Generic type definition failed to load"))
                        return;
-               }
 
                /* The + 1 makes this always non-NULL to pass the check in mono_class_setup_methods () */
                count = gklass->method.count;
@@ -2226,7 +2235,7 @@ mono_class_setup_methods (MonoClass *klass)
                                gklass->methods [i], klass, mono_class_get_context (klass), &error);
                        if (!mono_error_ok (&error)) {
                                char *method = mono_method_full_name (gklass->methods [i], TRUE);
-                               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Could not inflate method %s due to %s", method, mono_error_get_message (&error)));
+                               mono_class_set_type_load_failure (klass, "Could not inflate method %s due to %s", method, mono_error_get_message (&error));
 
                                g_free (method);
                                mono_error_cleanup (&error);
@@ -2332,7 +2341,7 @@ mono_class_setup_methods (MonoClass *klass)
                        int idx = mono_metadata_translate_token_index (klass->image, MONO_TABLE_METHOD, klass->method.first + i + 1);
                        methods [i] = mono_get_method_checked (klass->image, MONO_TOKEN_METHOD_DEF | idx, klass, NULL, &error);
                        if (!methods [i]) {
-                               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Could not load method %d due to %s", i, mono_error_get_message (&error)));
+                               mono_class_set_type_load_failure (klass, "Could not load method %d due to %s", i, mono_error_get_message (&error));
                                mono_error_cleanup (&error);
                        }
                }
@@ -2509,10 +2518,8 @@ mono_class_setup_properties (MonoClass *klass)
 
                mono_class_init (gklass);
                mono_class_setup_properties (gklass);
-               if (mono_class_has_failure (gklass)) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Generic type definition failed to load"));
+               if (mono_class_set_type_load_failure_causedby_class (klass, gklass, "Generic type definition failed to load"))
                        return;
-               }
 
                properties = mono_class_new0 (klass, MonoProperty, gklass->ext->property.count + 1);
 
@@ -2642,10 +2649,8 @@ mono_class_setup_events (MonoClass *klass)
                MonoGenericContext *context = NULL;
 
                mono_class_setup_events (gklass);
-               if (mono_class_has_failure (gklass)) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Generic type definition failed to load"));
+               if (mono_class_set_type_load_failure_causedby_class (klass, gklass, "Generic type definition failed to load"))
                        return;
-               }
 
                first = gklass->ext->event.first;
                count = gklass->ext->event.count;
@@ -2683,7 +2688,6 @@ mono_class_setup_events (MonoClass *klass)
                if (count) {
                        mono_class_setup_methods (klass);
                        if (mono_class_has_failure (klass)) {
-                               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Generic type definition failed to load"));
                                return;
                        }
                }
@@ -3501,7 +3505,7 @@ mono_class_interface_match (const uint8_t *bitmap, int id)
 
 /*
  * LOCKING: this is supposed to be called with the loader lock held.
- * Return -1 on failure and set exception_type
+ * Return -1 on failure and set klass->has_failure and store a MonoErrorBoxed with the details.
  */
 static int
 setup_interface_offsets (MonoClass *klass, int cur_slot, gboolean overwrite)
@@ -3545,7 +3549,7 @@ setup_interface_offsets (MonoClass *klass, int cur_slot, gboolean overwrite)
                ifaces = mono_class_get_implemented_interfaces (k, &error);
                if (!mono_error_ok (&error)) {
                        char *name = mono_type_get_full_name (k);
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Error getting the interfaces of %s due to %s", name, mono_error_get_message (&error)));
+                       mono_class_set_type_load_failure (klass, "Error getting the interfaces of %s due to %s", name, mono_error_get_message (&error));
                        g_free (name);
                        mono_error_cleanup (&error);
                        cur_slot = -1;
@@ -3612,7 +3616,7 @@ setup_interface_offsets (MonoClass *klass, int cur_slot, gboolean overwrite)
                        count = count_virtual_methods (ic);
                        if (count == -1) {
                                char *name = mono_type_get_full_name (ic);
-                               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Error calculating interface offset of %s", name));
+                               mono_class_set_type_load_failure (klass, "Error calculating interface offset of %s", name);
                                g_free (name);
                                cur_slot = -1;
                                goto end;
@@ -3788,10 +3792,8 @@ mono_class_check_vtable_constraints (MonoClass *klass, GList *in_setup)
        }
 
        mono_class_setup_vtable_full (mono_class_get_generic_type_definition (klass), in_setup);
-       if (mono_class_has_failure (klass->generic_class->container_class)) {
-               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Failed to load generic definition vtable"));
+       if (mono_class_set_type_load_failure_causedby_class (klass, klass->generic_class->container_class, "Failed to load generic definition vtable"))
                return FALSE;
-       }
 
        ginst = klass->generic_class->context.class_inst;
        for (i = 0; i < ginst->type_argc; ++i) {
@@ -3803,7 +3805,7 @@ mono_class_check_vtable_constraints (MonoClass *klass, GList *in_setup)
                if (mono_class_has_gtd_parent (klass, arg) || mono_class_has_gtd_parent (arg, klass))
                        continue;
                if (!mono_class_check_vtable_constraints (arg, in_setup)) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Failed to load generic parameter %d", i));
+                       mono_class_set_type_load_failure (klass, "Failed to load generic parameter %d", i);
                        return FALSE;
                }
        }
@@ -3818,7 +3820,8 @@ mono_class_check_vtable_constraints (MonoClass *klass, GList *in_setup)
  * - vtable
  * - vtable_size
  * Plus all the fields initialized by setup_interface_offsets ().
- * If there is an error during vtable construction, klass->exception_type is set.
+ * If there is an error during vtable construction, klass->has_failure
+ * is set and details are stored in a MonoErrorBoxed.
  *
  * LOCKING: Acquires the loader lock.
  */
@@ -3886,7 +3889,7 @@ mono_class_setup_vtable_full (MonoClass *klass, GList *in_setup)
                if (!is_ok (&error)) {
                        mono_loader_unlock ();
                        g_list_remove (in_setup, klass);
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf(klass->image, "Could not load list of method overrides due to %s", mono_error_get_message (&error)));
+                       mono_class_set_type_load_failure (klass, "Could not load list of method overrides due to %s", mono_error_get_message (&error));
                        mono_error_cleanup (&error);
                        return;
                }
@@ -3899,7 +3902,7 @@ mono_class_setup_vtable_full (MonoClass *klass, GList *in_setup)
        if (ok)
                mono_class_setup_vtable_general (klass, overrides, onum, in_setup);
        else
-               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Could not load list of method overrides"));
+               mono_class_set_type_load_failure (klass, "Could not load list of method overrides");
                
        g_free (overrides);
 
@@ -4015,7 +4018,7 @@ check_interface_method_override (MonoClass *klass, MonoMethod *im, MonoMethod *c
                cmsig = mono_method_signature (cm);
                imsig = mono_method_signature (im);
                if (!cmsig || !imsig) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Could not resolve the signature of a virtual method"));
+                       mono_class_set_type_load_failure (klass, "Could not resolve the signature of a virtual method");
                        return FALSE;
                }
 
@@ -4033,7 +4036,7 @@ check_interface_method_override (MonoClass *klass, MonoMethod *im, MonoMethod *c
                if (is_wcf_hack_disabled () && !mono_method_can_access_method_full (cm, im, NULL)) {
                        char *body_name = mono_method_full_name (cm, TRUE);
                        char *decl_name = mono_method_full_name (im, TRUE);
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Method %s overrides method '%s' which is not accessible", body_name, decl_name));
+                       mono_class_set_type_load_failure (klass, "Method %s overrides method '%s' which is not accessible", body_name, decl_name);
                        g_free (body_name);
                        g_free (decl_name);
                        return FALSE;
@@ -4057,7 +4060,7 @@ check_interface_method_override (MonoClass *klass, MonoMethod *im, MonoMethod *c
                cmsig = mono_method_signature (cm);
                imsig = mono_method_signature (im);
                if (!cmsig || !imsig) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Could not resolve the signature of a virtual method"));
+                       mono_class_set_type_load_failure (klass, "Could not resolve the signature of a virtual method");
                        return FALSE;
                }
 
@@ -4114,7 +4117,7 @@ check_interface_method_override (MonoClass *klass, MonoMethod *im, MonoMethod *c
                if (is_wcf_hack_disabled () && !mono_method_can_access_method_full (cm, im, NULL)) {
                        char *body_name = mono_method_full_name (cm, TRUE);
                        char *decl_name = mono_method_full_name (im, TRUE);
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Method %s overrides method '%s' which is not accessible", body_name, decl_name));
+                       mono_class_set_type_load_failure (klass, "Method %s overrides method '%s' which is not accessible", body_name, decl_name);
                        g_free (body_name);
                        g_free (decl_name);
                        return FALSE;
@@ -4281,28 +4284,28 @@ verify_class_overrides (MonoClass *klass, MonoMethod **overrides, int onum)
                MonoMethod *body = overrides [i * 2 + 1];
 
                if (mono_class_get_generic_type_definition (body->klass) != mono_class_get_generic_type_definition (klass)) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Method belongs to a different class than the declared one"));
+                       mono_class_set_type_load_failure (klass, "Method belongs to a different class than the declared one");
                        return FALSE;
                }
 
                if (!(body->flags & METHOD_ATTRIBUTE_VIRTUAL) || (body->flags & METHOD_ATTRIBUTE_STATIC)) {
                        if (body->flags & METHOD_ATTRIBUTE_STATIC)
-                               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Method must not be static to override a base type"));
+                               mono_class_set_type_load_failure (klass, "Method must not be static to override a base type");
                        else
-                               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Method must be virtual to override a base type"));
+                               mono_class_set_type_load_failure (klass, "Method must be virtual to override a base type");
                        return FALSE;
                }
 
                if (!(decl->flags & METHOD_ATTRIBUTE_VIRTUAL) || (decl->flags & METHOD_ATTRIBUTE_STATIC)) {
                        if (body->flags & METHOD_ATTRIBUTE_STATIC)
-                               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Cannot override a static method in a base type"));
+                               mono_class_set_type_load_failure (klass, "Cannot override a static method in a base type");
                        else
-                               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Cannot override a non virtual method in a base type"));
+                               mono_class_set_type_load_failure (klass, "Cannot override a non virtual method in a base type");
                        return FALSE;
                }
 
                if (!mono_class_is_assignable_from_slow (decl->klass, klass)) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Method overrides a class or interface that is not extended or implemented by this type"));
+                       mono_class_set_type_load_failure (klass, "Method overrides a class or interface that is not extended or implemented by this type");
                        return FALSE;
                }
 
@@ -4312,7 +4315,7 @@ verify_class_overrides (MonoClass *klass, MonoMethod **overrides, int onum)
                if (is_wcf_hack_disabled () && !mono_method_can_access_method_full (body, decl, NULL)) {
                        char *body_name = mono_method_full_name (body, TRUE);
                        char *decl_name = mono_method_full_name (decl, TRUE);
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Method %s overrides method '%s' which is not accessible", body_name, decl_name));
+                       mono_class_set_type_load_failure (klass, "Method %s overrides method '%s' which is not accessible", body_name, decl_name);
                        g_free (body_name);
                        g_free (decl_name);
                        return FALSE;
@@ -4355,7 +4358,7 @@ mono_class_setup_vtable_general (MonoClass *klass, MonoMethod **overrides, int o
        ifaces = mono_class_get_implemented_interfaces (klass, &error);
        if (!mono_error_ok (&error)) {
                char *name = mono_type_get_full_name (klass);
-               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Could not resolve %s interfaces due to %s", name, mono_error_get_message (&error)));
+               mono_class_set_type_load_failure (klass, "Could not resolve %s interfaces due to %s", name, mono_error_get_message (&error));
                g_free (name);
                mono_error_cleanup (&error);
                return;
@@ -4372,12 +4375,8 @@ mono_class_setup_vtable_general (MonoClass *klass, MonoMethod **overrides, int o
                mono_class_init (klass->parent);
                mono_class_setup_vtable_full (klass->parent, in_setup);
 
-               if (mono_class_has_failure (klass->parent)) {
-                       char *name = mono_type_get_full_name (klass->parent);
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Parent %s failed to load", name));
-                       g_free (name);
+               if (mono_class_set_type_load_failure_causedby_class (klass, klass->parent, "Parent class failed to load"))
                        return;
-               }
 
                max_vtsize += klass->parent->vtable_size;
                cur_slot = klass->parent->vtable_size;
@@ -4411,10 +4410,8 @@ mono_class_setup_vtable_general (MonoClass *klass, MonoMethod **overrides, int o
                MonoMethod **tmp;
 
                mono_class_setup_vtable_full (gklass, in_setup);
-               if (mono_class_has_failure (gklass)) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+               if (mono_class_set_type_load_failure_causedby_class (klass, gklass, "Could not load generic definition"))
                        return;
-               }
 
                tmp = (MonoMethod **)mono_class_alloc0 (klass, sizeof (gpointer) * gklass->vtable_size);
                klass->vtable_size = gklass->vtable_size;
@@ -4422,8 +4419,7 @@ mono_class_setup_vtable_general (MonoClass *klass, MonoMethod **overrides, int o
                        if (gklass->vtable [i]) {
                                MonoMethod *inflated = mono_class_inflate_generic_method_full_checked (gklass->vtable [i], klass, mono_class_get_context (klass), &error);
                                if (!mono_error_ok (&error)) {
-                                       char *err_msg = mono_image_strdup_printf (klass->image, "Could not inflate method due to %s", mono_error_get_message (&error));
-                                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, err_msg);
+                                       mono_class_set_type_load_failure (klass, "Could not inflate method due to %s", mono_error_get_message (&error));
                                        mono_error_cleanup (&error);
                                        return;
                                }
@@ -4496,7 +4492,7 @@ mono_class_setup_vtable_general (MonoClass *klass, MonoMethod **overrides, int o
                        int dslot;
                        dslot = mono_method_get_vtable_slot (decl);
                        if (dslot == -1) {
-                               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+                               mono_class_set_type_load_failure (klass, "");
                                return;
                        }
 
@@ -4673,7 +4669,8 @@ mono_class_setup_vtable_general (MonoClass *klass, MonoMethod **overrides, int o
                                        m1sig = mono_method_signature (m1);
 
                                        if (!cmsig || !m1sig) {
-                                               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+                                               /* FIXME proper error message */
+                                               mono_class_set_type_load_failure (klass, "");
                                                return;
                                        }
 
@@ -4690,7 +4687,7 @@ mono_class_setup_vtable_general (MonoClass *klass, MonoMethod **overrides, int o
                                                if (is_wcf_hack_disabled () && !mono_method_can_access_method_full (cm, m1, NULL)) {
                                                        char *body_name = mono_method_full_name (cm, TRUE);
                                                        char *decl_name = mono_method_full_name (m1, TRUE);
-                                                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Method %s overrides method '%s' which is not accessible", body_name, decl_name));
+                                                       mono_class_set_type_load_failure (klass, "Method %s overrides method '%s' which is not accessible", body_name, decl_name);
                                                        g_free (body_name);
                                                        g_free (decl_name);
                                                        goto fail;
@@ -4775,7 +4772,7 @@ mono_class_setup_vtable_general (MonoClass *klass, MonoMethod **overrides, int o
                        if (vtable [i] == NULL || (vtable [i]->flags & (METHOD_ATTRIBUTE_ABSTRACT | METHOD_ATTRIBUTE_STATIC))) {
                                char *type_name = mono_type_get_full_name (klass);
                                char *method_name = vtable [i] ? mono_method_full_name (vtable [i], TRUE) : g_strdup ("none");
-                               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Type %s has invalid vtable method slot %d with method %s", type_name, i, method_name));
+                               mono_class_set_type_load_failure (klass, "Type %s has invalid vtable method slot %d with method %s", type_name, i, method_name);
                                g_free (type_name);
                                g_free (method_name);
                                return;
@@ -4859,7 +4856,7 @@ mono_class_setup_vtable_general (MonoClass *klass, MonoMethod **overrides, int o
 fail:
        {
        char *name = mono_type_get_full_name (klass);
-       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "VTable setup of type %s failed", name));
+       mono_class_set_type_load_failure (klass, "VTable setup of type %s failed", name);
        g_free (name);
        if (override_map)
                g_hash_table_destroy (override_map);
@@ -5099,14 +5096,14 @@ mono_class_init (MonoClass *klass)
        }
 
        if (klass->init_pending) {
-               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Recursive type definition detected"));
+               mono_class_set_type_load_failure (klass, "Recursive type definition detected");
                goto leave;
        }
 
        klass->init_pending = 1;
 
        if (mono_verifier_is_enabled_for_class (klass) && !mono_verifier_verify_class (klass)) {
-               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, concat_two_strings_with_zero (klass->image, klass->name, klass->image->assembly_name));
+               mono_class_set_type_load_failure (klass, "%s", concat_two_strings_with_zero (klass->image, klass->name, klass->image->assembly_name));
                goto leave;
        }
 
@@ -5115,10 +5112,8 @@ mono_class_init (MonoClass *klass)
                MonoClass *element_class = klass->element_class;
                if (!element_class->inited) 
                        mono_class_init (element_class);
-               if (mono_class_has_failure (element_class)) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+               if (mono_class_set_type_load_failure_causedby_class (klass, element_class, "Could not load array element class"))
                        goto leave;
-               }
        }
 
        mono_stats.initialized_class_count++;
@@ -5135,10 +5130,8 @@ mono_class_init (MonoClass *klass)
                // FIXME: Why is this needed ?
                if (!mono_class_has_failure (gklass))
                        mono_class_setup_methods (gklass);
-               if (mono_class_has_failure (gklass)) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Generic Type Defintion failed to init"));
+               if (mono_class_set_type_load_failure_causedby_class (klass, gklass, "Generic Type Definition failed to init"))
                        goto leave;
-               }
 
                if (MONO_CLASS_IS_INTERFACE (klass))
                        klass->interface_id = mono_get_unique_iid (klass);
@@ -5222,10 +5215,8 @@ mono_class_init (MonoClass *klass)
                klass->has_cctor = gklass->has_cctor;
 
                mono_class_setup_vtable (gklass);
-               if (mono_class_has_failure (gklass)) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+               if (mono_class_set_type_load_failure_causedby_class (klass, gklass, "Generic type definition failed to init"))
                        goto leave;
-               }
 
                klass->vtable_size = gklass->vtable_size;
        } else {
@@ -5270,18 +5261,18 @@ mono_class_init (MonoClass *klass)
        }
 
        if (klass->parent) {
+               MonoError parent_error;
+               mono_error_init (&parent_error);
                int first_iface_slot;
                /* This will compute klass->parent->vtable_size for some classes */
                mono_class_init (klass->parent);
-               if (mono_class_has_failure (klass->parent)) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+               if (mono_class_set_type_load_failure_causedby_class (klass, klass->parent, "Parent class failed to initialize")) {
                        goto leave;
                }
                if (!klass->parent->vtable_size) {
                        /* FIXME: Get rid of this somehow */
                        mono_class_setup_vtable (klass->parent);
-                       if (mono_class_has_failure (klass->parent)) {
-                               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+                       if (mono_class_set_type_load_failure_causedby_class (klass, klass->parent, "Parent class vtable failed to initialize")) {
                                goto leave;
                        }
                }
@@ -5297,7 +5288,7 @@ mono_class_init (MonoClass *klass)
                mono_security_core_clr_check_inheritance (klass);
 
        if (klass->generic_class && !mono_verifier_class_is_valid_generic_instantiation (klass))
-               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Invalid generic instantiation"));
+               mono_class_set_type_load_failure (klass, "Invalid generic instantiation");
 
        goto leave;
 
@@ -5533,7 +5524,7 @@ init_com_from_comimport (MonoClass *klass)
                        /* but it can not be made available for application (i.e. user code) since all COM calls
                         * are considered native calls. In this case we fail with a TypeLoadException (just like
                         * Silverlight 2 does */
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+                       mono_class_set_type_load_failure (klass, "");
                        return;
                }
        }
@@ -5577,7 +5568,7 @@ mono_class_setup_parent (MonoClass *klass, MonoClass *parent)
                if (!parent) {
                        /* set the parent to something useful and safe, but mark the type as broken */
                        parent = mono_defaults.object_class;
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+                       mono_class_set_type_load_failure (klass, "");
                }
 
                klass->parent = parent;
@@ -5695,7 +5686,7 @@ fix_gclass_incomplete_instantiation (MonoClass *gclass, void *user_data)
 static void
 mono_class_set_failure_and_error (MonoClass *klass, MonoError *error, const char *msg)
 {
-       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, msg));
+       mono_class_set_type_load_failure (klass, "%s", msg);
        mono_error_set_type_load_class (error, klass, "%s", msg);
 }
 
@@ -5790,7 +5781,7 @@ mono_class_create_from_typedef (MonoImage *image, guint32 type_token, MonoError
                        parent = mono_class_inflate_generic_class_checked (parent, context, error);
 
                if (parent == NULL) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, mono_error_get_message (error)));
+                       mono_class_set_type_load_failure (klass, "%s", mono_error_get_message (error));
                        goto parent_failure;
                }
 
@@ -5822,7 +5813,7 @@ mono_class_create_from_typedef (MonoImage *image, guint32 type_token, MonoError
                klass->nested_in = mono_class_create_from_typedef (image, nesting_tokeen, error);
                if (!mono_error_ok (error)) {
                        /*FIXME implement a mono_class_set_failure_from_mono_error */
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, mono_error_get_message (error)));
+                       mono_class_set_type_load_failure (klass, "%s",  mono_error_get_message (error));
                        mono_loader_unlock ();
                        mono_profiler_class_loaded (klass, MONO_PROFILE_FAILED);
                        return NULL;
@@ -5843,7 +5834,7 @@ mono_class_create_from_typedef (MonoImage *image, guint32 type_token, MonoError
                if (!mono_metadata_interfaces_from_typedef_full (
                            image, type_token, &interfaces, &icount, FALSE, context, error)){
 
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, mono_error_get_message (error)));
+                       mono_class_set_type_load_failure (klass, "%s", mono_error_get_message (error));
                        mono_loader_unlock ();
                        mono_profiler_class_loaded (klass, MONO_PROFILE_FAILED);
                        return NULL;
@@ -5893,7 +5884,7 @@ mono_class_create_from_typedef (MonoImage *image, guint32 type_token, MonoError
                if (!enum_basetype) {
                        /*set it to a default value as the whole runtime can't handle this to be null*/
                        klass->cast_class = klass->element_class = mono_defaults.int32_class;
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, mono_error_get_message (error)));
+                       mono_class_set_type_load_failure (klass, "%s", mono_error_get_message (error));
                        mono_loader_unlock ();
                        mono_profiler_class_loaded (klass, MONO_PROFILE_FAILED);
                        return NULL;
@@ -5907,7 +5898,7 @@ mono_class_create_from_typedef (MonoImage *image, guint32 type_token, MonoError
         * work.
         */
        if (klass->generic_container && !mono_metadata_load_generic_param_constraints_checked (image, type_token, klass->generic_container, error)) {
-               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Could not load generic parameter constrains due to %s", mono_error_get_message (error)));
+               mono_class_set_type_load_failure (klass, "Could not load generic parameter constrains due to %s", mono_error_get_message (error));
                mono_loader_unlock ();
                mono_profiler_class_loaded (klass, MONO_PROFILE_FAILED);
                return NULL;
@@ -5959,7 +5950,7 @@ mono_generic_class_setup_parent (MonoClass *klass, MonoClass *gtd)
                if (!mono_error_ok (&error)) {
                        /*Set parent to something safe as the runtime doesn't handle well this kind of failure.*/
                        klass->parent = mono_defaults.object_class;
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+                       mono_class_set_type_load_failure (klass, "Parent is a generic type instantiation that failed due to: %s", mono_error_get_message (&error));
                        mono_error_cleanup (&error);
                }
        }
@@ -6204,7 +6195,7 @@ make_generic_param_class (MonoGenericParam *param, MonoGenericParamInfo *pinfo)
        if (count - pos > 0) {
                mono_class_setup_vtable (klass->parent);
                if (mono_class_has_failure (klass->parent))
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Failed to setup parent interfaces"));
+                       mono_class_set_type_load_failure (klass, "Failed to setup parent interfaces");
                else
                        setup_interface_offsets (klass, klass->parent->vtable_size, TRUE);
        }
@@ -6419,8 +6410,7 @@ mono_ptr_class_get (MonoType *type)
        result->image = el_class->image;
        result->inited = TRUE;
        result->flags = TYPE_ATTRIBUTE_CLASS | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
-       /* Can pointers get boxed? */
-       result->instance_size = sizeof (gpointer);
+       result->instance_size = sizeof (MonoObject) + sizeof (gpointer);
        result->cast_class = result->element_class = el_class;
        result->blittable = TRUE;
 
@@ -6478,8 +6468,7 @@ mono_fnptr_class_get (MonoMethodSignature *sig)
        result->image = mono_defaults.corlib; /* need to fix... */
        result->inited = TRUE;
        result->flags = TYPE_ATTRIBUTE_CLASS; /* | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK); */
-       /* Can pointers get boxed? */
-       result->instance_size = sizeof (gpointer);
+       result->instance_size = sizeof (MonoObject) + sizeof (gpointer);
        result->cast_class = result->element_class = result;
        result->blittable = TRUE;
 
@@ -6721,7 +6710,11 @@ mono_bounded_array_class_get (MonoClass *eclass, guint32 rank, gboolean bounded)
 
        if (eclass->byval_arg.type == MONO_TYPE_TYPEDBYREF || eclass->byval_arg.type == MONO_TYPE_VOID) {
                /*Arrays of those two types are invalid.*/
-               mono_class_set_failure (klass, MONO_EXCEPTION_INVALID_PROGRAM, NULL);
+               MonoError prepared_error;
+               mono_error_init (&prepared_error);
+               mono_error_set_invalid_program (&prepared_error, "Arrays of void or System.TypedReference types are invalid.");
+               mono_class_set_failure (klass, mono_error_box (&prepared_error, klass->image));
+               mono_error_cleanup (&prepared_error);
        } else if (eclass->enumtype && !mono_class_enum_basetype (eclass)) {
                if (!eclass->ref_info_handle || eclass->wastypebuilder) {
                        g_warning ("Only incomplete TypeBuilder objects are allowed to be an enum without base_type");
@@ -6738,8 +6731,8 @@ mono_bounded_array_class_get (MonoClass *eclass, guint32 rank, gboolean bounded)
                mono_class_init (eclass);
        if (!eclass->size_inited)
                mono_class_setup_fields (eclass);
-       if (mono_class_has_failure (eclass)) /*FIXME we fail the array type, but we have to let other fields be set.*/
-               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+       mono_class_set_type_load_failure_causedby_class (klass, eclass, "Could not load array element type");
+       /*FIXME we fail the array type, but we have to let other fields be set.*/
 
        klass->has_references = MONO_TYPE_IS_REFERENCE (&eclass->byval_arg) || eclass->has_references? TRUE: FALSE;
 
@@ -9912,21 +9905,63 @@ mono_class_get_method_from_name_flags (MonoClass *klass, const char *name, int p
  *
  * LOCKING: Acquires the loader lock.
  */
-gboolean
-mono_class_set_failure (MonoClass *klass, guint32 ex_type, void *ex_data)
+static gboolean
+mono_class_set_failure (MonoClass *klass, MonoErrorBoxed *boxed_error)
 {
+       g_assert (boxed_error != NULL);
+
        if (mono_class_has_failure (klass))
                return FALSE;
 
        mono_loader_lock ();
-       klass->exception_type = ex_type;
-       if (ex_data)
-               mono_image_property_insert (klass->image, klass, MONO_CLASS_PROP_EXCEPTION_DATA, ex_data);
+       klass->has_failure = 1;
+       mono_image_property_insert (klass->image, klass, MONO_CLASS_PROP_EXCEPTION_DATA, boxed_error);
        mono_loader_unlock ();
 
        return TRUE;
 }
 
+gboolean
+mono_class_has_failure (const MonoClass *klass)
+{
+       g_assert (klass != NULL);
+       return klass->has_failure != 0;
+}
+
+
+/**
+ * mono_class_set_type_load_failure:
+ * @klass: class in which the failure was detected
+ * @fmt: Printf-style error message string.
+ *
+ * Collect detected failure informaion in the class for later processing.
+ * The error is stored as a MonoErrorBoxed as with mono_error_set_type_load_class ()
+ * Note that only the first failure is kept.
+ *
+ * Returns FALSE if a failure was already set on the class, or TRUE otherwise.
+ *
+ * LOCKING: Acquires the loader lock.
+ */
+gboolean
+mono_class_set_type_load_failure (MonoClass *klass, const char * fmt, ...)
+{
+       MonoError prepare_error;
+       va_list args;
+
+       if (mono_class_has_failure (klass))
+               return FALSE;
+       
+       mono_error_init (&prepare_error);
+       
+       va_start (args, fmt);
+       mono_error_vset_type_load_class (&prepare_error, klass, fmt, args);
+       va_end (args);
+
+       MonoErrorBoxed *box = mono_error_box (&prepare_error, klass->image);
+       mono_error_cleanup (&prepare_error);
+       return mono_class_set_failure (klass, box);
+}
+
 /*
  * mono_class_get_exception_data:
  *
@@ -9934,10 +9969,10 @@ mono_class_set_failure (MonoClass *klass, guint32 ex_type, void *ex_data)
  *
  * LOCKING: Acquires the loader lock.
  */
-gpointer
-mono_class_get_exception_data (MonoClass *klass)
+static gpointer
+mono_class_get_exception_data (const MonoClass *klass)
 {
-       return mono_image_property_lookup (klass->image, klass, MONO_CLASS_PROP_EXCEPTION_DATA);
+       return mono_image_property_lookup (klass->image, (MonoClass*)klass, MONO_CLASS_PROP_EXCEPTION_DATA);
 }
 
 /**
@@ -9987,55 +10022,12 @@ mono_classes_cleanup (void)
 MonoException*
 mono_class_get_exception_for_failure (MonoClass *klass)
 {
-       gpointer exception_data = mono_class_get_exception_data (klass);
-
-       switch (mono_class_get_failure(klass)) {
-       case MONO_EXCEPTION_TYPE_LOAD: {
-               MonoString *name;
-               MonoException *ex;
-               char *str = mono_type_get_full_name (klass);
-               char *astr = klass->image->assembly? mono_stringify_assembly_name (&klass->image->assembly->aname): NULL;
-               name = mono_string_new (mono_domain_get (), str);
-               g_free (str);
-               ex = mono_get_exception_type_load (name, astr);
-               g_free (astr);
-               return ex;
-       }
-       case MONO_EXCEPTION_MISSING_METHOD: {
-               char *class_name = (char *)exception_data;
-               char *assembly_name = class_name + strlen (class_name) + 1;
-
-               return mono_get_exception_missing_method (class_name, assembly_name);
-       }
-       case MONO_EXCEPTION_MISSING_FIELD: {
-               char *class_name = (char *)exception_data;
-               char *member_name = class_name + strlen (class_name) + 1;
-
-               return mono_get_exception_missing_field (class_name, member_name);
-       }
-       case MONO_EXCEPTION_FILE_NOT_FOUND: {
-               char *msg_format = (char *)exception_data;
-               char *assembly_name = msg_format + strlen (msg_format) + 1;
-               char *msg = g_strdup_printf (msg_format, assembly_name);
-               MonoException *ex;
-
-               ex = mono_get_exception_file_not_found2 (msg, mono_string_new (mono_domain_get (), assembly_name));
-
-               g_free (msg);
-
-               return ex;
-       }
-       case MONO_EXCEPTION_BAD_IMAGE: {
-               return mono_get_exception_bad_image_format ((const char *)exception_data);
-       }
-       case MONO_EXCEPTION_INVALID_PROGRAM: {
-               return mono_exception_from_name_msg (mono_defaults.corlib, "System", "InvalidProgramException", "");
-       }
-       default: {
-               /* TODO - handle other class related failures */
-               return mono_get_exception_execution_engine ("Unknown class failure");
-       }
-       }
+       if (!mono_class_has_failure (klass))
+               return NULL;
+       MonoError unboxed_error;
+       mono_error_init (&unboxed_error);
+       mono_error_set_for_class_failure (&unboxed_error, klass);
+       return mono_error_convert_to_exception (&unboxed_error);
 }
 
 static gboolean
@@ -10621,7 +10613,7 @@ mono_class_setup_interfaces (MonoClass *klass, MonoError *error)
 
                mono_class_setup_interfaces (gklass, error);
                if (!mono_error_ok (error)) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Could not setup the interfaces"));
+                       mono_class_set_type_load_failure (klass, "Could not setup the interfaces");
                        return;
                }
 
@@ -10630,7 +10622,7 @@ mono_class_setup_interfaces (MonoClass *klass, MonoError *error)
                for (i = 0; i < interface_count; i++) {
                        interfaces [i] = mono_class_inflate_generic_class_checked (gklass->interfaces [i], mono_generic_class_get_context (klass->generic_class), error);
                        if (!mono_error_ok (error)) {
-                               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Could not setup the interfaces"));
+                               mono_class_set_type_load_failure (klass, "Could not setup the interfaces");
                                return;
                        }
                }
@@ -10667,14 +10659,12 @@ mono_field_resolve_type (MonoClassField *field, MonoError *error)
                MonoClassField *gfield = &gtd->fields [field_idx];
                MonoType *gtype = mono_field_get_type_checked (gfield, error);
                if (!mono_error_ok (error)) {
-                       char *err_msg = mono_image_strdup_printf (klass->image, "Could not load field %d type due to: %s", field_idx, mono_error_get_message (error));
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, err_msg);
+                       mono_class_set_type_load_failure (klass, "Could not load field %d type due to: %s", field_idx, mono_error_get_message (error));
                }
 
                field->type = mono_class_inflate_generic_type_no_copy (image, gtype, mono_class_get_context (klass), error);
                if (!mono_error_ok (error)) {
-                       char *err_msg = mono_image_strdup_printf (klass->image, "Could not load field %d type due to: %s", field_idx, mono_error_get_message (error));
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, err_msg);
+                       mono_class_set_type_load_failure (klass, "Could not load field %d type due to: %s", field_idx, mono_error_get_message (error));
                }
        } else {
                const char *sig;
@@ -10697,7 +10687,7 @@ mono_field_resolve_type (MonoClassField *field, MonoError *error)
 
                if (!mono_verifier_verify_field_signature (image, cols [MONO_FIELD_SIGNATURE], NULL)) {
                        mono_error_set_type_load_class (error, klass, "Could not verify field %s signature", field->name);;
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, mono_error_get_message (error)));
+                       mono_class_set_type_load_failure (klass, "%s", mono_error_get_message (error));
                        return;
                }
 
@@ -10709,8 +10699,7 @@ mono_field_resolve_type (MonoClassField *field, MonoError *error)
 
                field->type = mono_metadata_parse_type_checked (image, container, cols [MONO_FIELD_FLAGS], FALSE, sig + 1, &sig, error);
                if (!field->type) {
-                       char *err_msg = mono_image_strdup_printf (klass->image, "Could not load field %d type due to: %s", field_idx, mono_error_get_message (error));
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, err_msg);
+                       mono_class_set_type_load_failure (klass, "Could not load field %d type due to: %s", field_idx, mono_error_get_message (error));
                }
        }
 }
diff --git a/mono/metadata/console-win32-internals.h b/mono/metadata/console-win32-internals.h
new file mode 100644 (file)
index 0000000..e0cd222
--- /dev/null
@@ -0,0 +1,18 @@
+/*
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#ifndef __MONO_CONSOLE_WIN32_INTERNALS_H__
+#define __MONO_CONSOLE_WIN32_INTERNALS_H__
+
+#include <config.h>
+#include <glib.h>
+
+#include "mono/metadata/object.h"
+#include "mono/metadata/object-internals.h"
+#include "mono/utils/mono-error.h"
+#include "mono/utils/mono-error-internals.h"
+#include <mono/metadata/console-io.h>
+
+#endif /* __MONO_CONSOLE_WIN32_INTERNALS_H__ */
+
diff --git a/mono/metadata/console-win32-uwp.c b/mono/metadata/console-win32-uwp.c
new file mode 100644 (file)
index 0000000..56d4336
--- /dev/null
@@ -0,0 +1,100 @@
+/*
+ * console-win32-uwp.c: UWP console support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+
+#if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
+#include <Windows.h>
+#include "mono/metadata/console-win32-internals.h"
+
+MonoBoolean
+ves_icall_System_ConsoleDriver_Isatty (HANDLE handle)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("Console");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "Console");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+MonoBoolean
+ves_icall_System_ConsoleDriver_SetEcho (MonoBoolean want_echo)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("Console");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "Console");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+MonoBoolean
+ves_icall_System_ConsoleDriver_SetBreak (MonoBoolean want_break)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("Console");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "Console");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+gint32
+ves_icall_System_ConsoleDriver_InternalKeyAvailable (gint32 timeout)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("Console");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "Console");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+MonoBoolean
+ves_icall_System_ConsoleDriver_TtySetup (MonoString *keypad, MonoString *teardown, MonoArray **control_chars, int **size)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("Console");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "Console");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+#else /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_console_windows_uwp_quiet_lnk4221(void) {}
+#endif
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
index c7c8c49017b6182ee292e7d2d9fc373621384b22..06a0244477e1afd5e3a0ba40d4fddcd4c8e56ed1 100644 (file)
@@ -41,11 +41,11 @@ mono_console_handle_async_ops (void)
 {
 }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 MonoBoolean
 ves_icall_System_ConsoleDriver_Isatty (HANDLE handle)
 {
        DWORD mode;
-
        return GetConsoleMode (handle, &mode) != 0;
 }
 
@@ -72,3 +72,4 @@ ves_icall_System_ConsoleDriver_TtySetup (MonoString *keypad, MonoString *teardow
 {
        return FALSE;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
diff --git a/mono/metadata/coree-internals.h b/mono/metadata/coree-internals.h
new file mode 100644 (file)
index 0000000..3df754f
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#ifndef __MONO_COREE_INTERNALS_H__
+#define __MONO_COREE_INTERNALS_H__
+
+#include <config.h>
+#include <glib.h>
+
+#ifdef HOST_WIN32
+#include <Windows.h>
+
+BOOL STDMETHODCALLTYPE
+_CorDllMain (HINSTANCE hInst, DWORD dwReason, LPVOID lpReserved);
+
+__int32 STDMETHODCALLTYPE
+_CorExeMain (void);
+
+void STDMETHODCALLTYPE
+CorExitProcess (int exitCode);
+
+STDAPI
+_CorValidateImage (PVOID *ImageBase, LPCWSTR FileName);
+
+STDAPI_(VOID)
+_CorImageUnloading (PVOID ImageBase);
+
+STDAPI
+CorBindToRuntimeEx (LPCWSTR pwszVersion, LPCWSTR pwszBuildFlavor,
+                   DWORD startupFlags, REFCLSID rclsid, REFIID riid, LPVOID FAR *ppv);
+
+STDAPI
+CorBindToRuntime (LPCWSTR pwszVersion, LPCWSTR pwszBuildFlavor,
+                 REFCLSID rclsid, REFIID riid, LPVOID FAR *ppv);
+
+HMODULE WINAPI
+MonoLoadImage (LPCWSTR FileName);
+
+void mono_coree_set_act_ctx (const char *file_name);
+#endif /* HOST_WIN32 */
+
+#endif /* __MONO_COREE_INTERNALS_H__ */
+
diff --git a/mono/metadata/coree-windows-uwp.c b/mono/metadata/coree-windows-uwp.c
new file mode 100644 (file)
index 0000000..7aacb5e
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * coree-windows-uwp.c: UWP coree support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+
+#if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
+#include <Windows.h>
+#include "mono/metadata/coree-internals.h"
+
+BOOL STDMETHODCALLTYPE
+_CorDllMain(HINSTANCE hInst, DWORD dwReason, LPVOID lpReserved)
+{
+       g_unsupported_api ("_CorDllMain");
+       return FALSE;
+}
+
+__int32 STDMETHODCALLTYPE
+_CorExeMain(void)
+{
+       g_unsupported_api ("_CorExeMain");
+       ExitProcess (EXIT_FAILURE);
+}
+
+STDAPI
+_CorValidateImage(PVOID *ImageBase, LPCWSTR FileName)
+{
+       g_unsupported_api ("_CorValidateImage");
+       return E_UNEXPECTED;
+}
+
+HMODULE WINAPI
+MonoLoadImage(LPCWSTR FileName)
+{
+       g_unsupported_api ("MonoLoadImage");
+       return NULL;
+}
+
+void
+mono_coree_set_act_ctx (const char *file_name)
+{
+       g_unsupported_api ("CreateActCtx, ActivateActCtx");
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return;
+}
+
+#else /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_coree_windows_uwp_quiet_lnk4221(void) {}
+#endif
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
index 4436229376e10101b1d16f827601c72f466d2328..428fb9b989f80b6fea16ac5b54aad5cdf52cceb3 100644 (file)
@@ -12,8 +12,8 @@
 
 #ifdef HOST_WIN32
 
-#include <string.h>
 #include <glib.h>
+#include <string.h>
 #include <mono/io-layer/io-layer.h>
 #include <mono/utils/mono-path.h>
 #include "cil-coff.h"
 #include "threads.h"
 #include "environment.h"
 #include "coree.h"
+#include "coree-internals.h"
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 #include <shellapi.h>
+#endif
 
 HMODULE coree_module_handle = NULL;
 
@@ -68,6 +71,7 @@ mono_get_module_file_name (HMODULE module_handle)
 }
 
 /* Entry point called by LdrLoadDll of ntdll.dll after _CorValidateImage. */
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 BOOL STDMETHODCALLTYPE _CorDllMain(HINSTANCE hInst, DWORD dwReason, LPVOID lpReserved)
 {
        MonoAssembly* assembly;
@@ -134,8 +138,10 @@ BOOL STDMETHODCALLTYPE _CorDllMain(HINSTANCE hInst, DWORD dwReason, LPVOID lpRes
 
        return TRUE;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
 
 /* Called by ntdll.dll reagardless of entry point after _CorValidateImage. */
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 __int32 STDMETHODCALLTYPE _CorExeMain(void)
 {
        MonoError error;
@@ -207,6 +213,7 @@ __int32 STDMETHODCALLTYPE _CorExeMain(void)
        /* return does not terminate the process. */
        ExitProcess (mono_environment_exitcode_get ());
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
 
 /* Called by msvcrt.dll when shutting down. */
 void STDMETHODCALLTYPE CorExitProcess(int exitCode)
@@ -223,6 +230,7 @@ void STDMETHODCALLTYPE CorExitProcess(int exitCode)
 }
 
 /* Called by ntdll.dll before _CorDllMain and _CorExeMain. */
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 STDAPI _CorValidateImage(PVOID *ImageBase, LPCWSTR FileName)
 {
        IMAGE_DOS_HEADER* DosHeader;
@@ -385,6 +393,7 @@ STDAPI _CorValidateImage(PVOID *ImageBase, LPCWSTR FileName)
 
        return STATUS_SUCCESS;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
 
 /* Called by ntdll.dll. */
 STDAPI_(VOID) _CorImageUnloading(PVOID ImageBase)
@@ -406,6 +415,7 @@ STDAPI CorBindToRuntime(LPCWSTR pwszVersion, LPCWSTR pwszBuildFlavor, REFCLSID r
        return CorBindToRuntimeEx (pwszVersion, pwszBuildFlavor, 0, rclsid, riid, ppv);
 }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 HMODULE WINAPI MonoLoadImage(LPCWSTR FileName)
 {
        HANDLE FileHandle;
@@ -482,6 +492,7 @@ CloseFile:
        CloseHandle(FileHandle);
        return NULL;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
 
 typedef struct _EXPORT_FIXUP
 {
@@ -499,14 +510,14 @@ typedef struct _EXPORT_FIXUP
 
 /* Has to be binary ordered. */
 static const EXPORT_FIXUP ExportFixups[] = {
-       {"CorBindToRuntime", &CorBindToRuntime},
-       {"CorBindToRuntimeEx", &CorBindToRuntimeEx},
-       {"CorExitProcess", &CorExitProcess},
-       {"_CorDllMain", &_CorDllMain},
-       {"_CorExeMain", &_CorExeMain},
-       {"_CorImageUnloading", &_CorImageUnloading},
-       {"_CorValidateImage", &_CorValidateImage},
-       {NULL, NULL}
+       {"CorBindToRuntime", {&CorBindToRuntime}},
+       {"CorBindToRuntimeEx", {&CorBindToRuntimeEx}},
+       {"CorExitProcess", {&CorExitProcess}},
+       {"_CorDllMain", {&_CorDllMain}},
+       {"_CorExeMain", {&_CorExeMain}},
+       {"_CorImageUnloading", {&_CorImageUnloading}},
+       {"_CorValidateImage", {&_CorValidateImage}},
+       {NULL, {NULL}}
 };
 
 #define EXPORT_FIXUP_COUNT (sizeof(ExportFixups) / sizeof(EXPORT_FIXUP) - 1)
@@ -795,7 +806,15 @@ STDAPI MonoFixupExe(HMODULE ModuleHandle)
                        ImportDesc = (IMAGE_IMPORT_DESCRIPTOR*)((DWORD_PTR)DosHeader + ImportDir->VirtualAddress);
                        while (ImportDesc->Name && ImportDesc->OriginalFirstThunk)
                        {
-                               ImportModuleHandle = LoadLibraryA((PCSTR)((DWORD_PTR)DosHeader + ImportDesc->Name));
+                               gchar *file_utf8 = (gchar *)((DWORD_PTR)DosHeader + ImportDesc->Name);
+
+                               gunichar2 *file_utf16 = g_utf8_to_utf16 (file_utf8, (glong)strlen (file_utf8), NULL, NULL, NULL);
+                               ImportModuleHandle = NULL;
+                               if (file_utf16 != NULL) {
+                                       ImportModuleHandle = LoadLibraryW(file_utf16);
+                                       g_free (file_utf16);
+                               }
+
                                if (ImportModuleHandle == NULL)
                                        return E_FAIL;
 
@@ -828,8 +847,9 @@ STDAPI MonoFixupExe(HMODULE ModuleHandle)
        return S_OK;
 }
 
-static void
-mono_set_act_ctx (const char* file_name)
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+void
+mono_coree_set_act_ctx (const char* file_name)
 {
        typedef HANDLE (WINAPI* CREATEACTCTXW_PROC) (PCACTCTXW pActCtx);
        typedef BOOL (WINAPI* ACTIVATEACTCTX_PROC) (HANDLE hActCtx, ULONG_PTR* lpCookie);
@@ -888,6 +908,7 @@ mono_set_act_ctx (const char* file_name)
        if (handle != INVALID_HANDLE_VALUE)
                ActivateActCtx_proc (handle, &cookie);
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
 
 void
 mono_load_coree (const char* exe_file_name)
@@ -901,7 +922,7 @@ mono_load_coree (const char* exe_file_name)
                return;
 
        if (!init_from_coree && exe_file_name)
-               mono_set_act_ctx (exe_file_name);
+               mono_coree_set_act_ctx (exe_file_name);
 
        /* ntdll.dll loads mscoree.dll from the system32 directory. */
        required_size = GetSystemDirectory (NULL, 0);
index 1f555ed4e324daf757f982df42c12e13733d4ac2..b845fc2708e7186d19458c90c47ce86045dcdb94 100644 (file)
@@ -339,7 +339,6 @@ struct _MonoDomain {
        /* Needed by Thread:GetDomainID() */
        gint32             domain_id;
        gint32             shadow_serial;
-       unsigned char      inet_family_hint; // used in socket-io.c as a cache
        GSList             *domain_assemblies;
        MonoAssembly       *entry_assembly;
        char               *friendly_name;
index d280e30982144af7f8bd20328d420f38e742ad9b..dfb3c29eefc5af88d07cdc37c168c66c6f39a58c 100644 (file)
@@ -522,7 +522,7 @@ mono_init_internal (const char *filename, const char *exe_filename, const char *
        if (domain)
                g_assert_not_reached ();
 
-#ifdef HOST_WIN32
+#if defined(HOST_WIN32) && G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
        /* Avoid system error message boxes. */
        SetErrorMode (SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
 #endif
index 02b738556c597c72fbc7ed9fe76a5acead5d97eb..b4be09844ac59ec3c482c2bb27d7620acacd7cc4 100644 (file)
@@ -976,8 +976,12 @@ mono_exception_get_native_backtrace (MonoException *exc)
        domain = mono_domain_get ();
        len = mono_array_length (arr);
        text = g_string_new_len (NULL, len * 20);
-       messages = backtrace_symbols (mono_array_addr (arr, gpointer, 0), len);
-
+       uint32_t gchandle = mono_gchandle_new (&arr->obj, TRUE); /* pinned */
+       void* addr = mono_array_addr (arr, gpointer, 0);
+       MONO_ENTER_GC_SAFE;
+       messages = backtrace_symbols (addr, len);
+       MONO_EXIT_GC_SAFE;
+       mono_gchandle_free (gchandle);
 
        for (i = 0; i < len; ++i) {
                gpointer ip = mono_array_get (arr, gpointer, i);
diff --git a/mono/metadata/file-io-internals.h b/mono/metadata/file-io-internals.h
new file mode 100644 (file)
index 0000000..3fe5970
--- /dev/null
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#ifndef __MONO_FILE_IO_INTERNALS_H__
+#define __MONO_FILE_IO_INTERNALS_H__
+
+#include <config.h>
+#include <glib.h>
+#include "mono/metadata/object.h"
+#include "mono/metadata/object-internals.h"
+
+gboolean
+mono_file_io_move_file (gunichar2 *path, gunichar2 *dest, gint32 *error);
+
+gboolean
+mono_file_io_copy_file (gunichar2 *path, gunichar2 *dest, gboolean overwrite, gint32 *error);
+
+gint64
+mono_file_io_get_file_size (HANDLE handle, gint32 *error);
+
+gboolean
+mono_file_io_lock_file (HANDLE handle, gint64 position, gint64 length, gint32 *error);
+
+gboolean
+mono_file_io_replace_file (gunichar2 *destinationFileName, gunichar2 *sourceFileName,
+                          gunichar2 *destinationBackupFileName, guint32 flags, gint32 *error);
+
+gboolean
+mono_file_io_unlock_file (HANDLE handle, gint64 position, gint64 length, gint32 *error);
+
+#endif /* __MONO_FILE_IO_INTERNALS_H__ */
diff --git a/mono/metadata/file-io-windows-internals.h b/mono/metadata/file-io-windows-internals.h
new file mode 100644 (file)
index 0000000..df372e8
--- /dev/null
@@ -0,0 +1,15 @@
+/*
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#ifndef _MONO_METADATA_FILEIO_WINDOWS_H_
+#define _MONO_METADATA_FILEIO_WINDOWS_H_
+
+#include <config.h>
+#include <glib.h>
+
+#ifdef HOST_WIN32
+#include "mono/metadata/file-io.h"
+#include "mono/metadata/file-io-internals.h"
+#endif /* HOST_WIN32 */
+#endif /* _MONO_METADATA_FILEIO_WINDOWS_H_ */
diff --git a/mono/metadata/file-io-windows-uwp.c b/mono/metadata/file-io-windows-uwp.c
new file mode 100644 (file)
index 0000000..2ece546
--- /dev/null
@@ -0,0 +1,121 @@
+/*
+ * file-io-windows-uwp.c: UWP file-io support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+
+#if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
+#include <Windows.h>
+#include "mono/metadata/file-io-windows-internals.h"
+
+gboolean
+mono_file_io_move_file (gunichar2 *path, gunichar2 *dest, gint32 *error)
+{
+       gboolean result = FALSE;
+       MONO_ENTER_GC_SAFE;
+
+       result = MoveFileEx (path, dest, MOVEFILE_COPY_ALLOWED);
+       if (result == FALSE) {
+               *error=GetLastError ();
+       }
+
+       MONO_EXIT_GC_SAFE;
+       return result;
+}
+
+gboolean
+mono_file_io_replace_file (gunichar2 *destinationFileName, gunichar2 *sourceFileName,
+                          gunichar2 *destinationBackupFileName, guint32 flags, gint32 *error)
+{
+       gboolean result = FALSE;
+       MONO_ENTER_GC_SAFE;
+
+       result = ReplaceFile (destinationFileName, sourceFileName, destinationBackupFileName, flags, NULL, NULL);
+       if (result == FALSE) {
+               *error=GetLastError ();
+       }
+
+       MONO_EXIT_GC_SAFE;
+       return result;
+}
+
+gboolean
+mono_file_io_copy_file (gunichar2 *path, gunichar2 *dest, gboolean overwrite, gint32 *error)
+{
+       gboolean                                                result = FALSE;
+       COPYFILE2_EXTENDED_PARAMETERS   copy_param = {0};
+
+       copy_param.dwSize = sizeof (COPYFILE2_EXTENDED_PARAMETERS);
+       copy_param.dwCopyFlags = (!overwrite) ? COPY_FILE_FAIL_IF_EXISTS : 0;
+
+       MONO_ENTER_GC_SAFE;
+
+       result = SUCCEEDED (CopyFile2 (path, dest, &copy_param));
+       if (result == FALSE) {
+               *error=GetLastError ();
+       }
+
+       MONO_EXIT_GC_SAFE;
+       return result;
+}
+
+gint64
+mono_file_io_get_file_size (HANDLE handle, gint32 *error)
+{
+       LARGE_INTEGER length;
+
+       MONO_ENTER_GC_SAFE;
+
+       if (!GetFileSizeEx (handle, &length)) {
+               *error=GetLastError ();
+               length.QuadPart = INVALID_FILE_SIZE;
+       }
+
+       MONO_EXIT_GC_SAFE;
+       return length.QuadPart;
+}
+
+gboolean
+mono_file_io_lock_file (HANDLE handle, gint64 position, gint64 length, gint32 *error)
+{
+       gboolean result = FALSE;
+       MONO_ENTER_GC_SAFE;
+
+       result = LockFile (handle, position & 0xFFFFFFFF, position >> 32,
+                          length & 0xFFFFFFFF, length >> 32);
+
+       if (result == FALSE) {
+               *error = GetLastError ();
+       }
+
+       MONO_EXIT_GC_SAFE;
+       return result;
+}
+
+gboolean
+mono_file_io_unlock_file (HANDLE handle, gint64 position, gint64 length, gint32 *error)
+{
+       gboolean result = FALSE;
+       MONO_ENTER_GC_SAFE;
+
+       result = UnlockFile (handle, position & 0xFFFFFFFF, position >> 32,
+                            length & 0xFFFFFFFF, length >> 32);
+
+       if (result == FALSE) {
+               *error = GetLastError ();
+       }
+
+       MONO_EXIT_GC_SAFE;
+       return result;
+}
+
+#else /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_file_io_windows_uwp_quiet_lnk4221(void) {}
+#endif
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
diff --git a/mono/metadata/file-io-windows.c b/mono/metadata/file-io-windows.c
new file mode 100644 (file)
index 0000000..fcd76cc
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * file-io-windows.c: Windows File IO internal calls.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#include <config.h>
+#include <glib.h>
+
+#if defined(HOST_WIN32)
+#include <WinSock2.h>
+#include <Windows.h>
+#include "mono/metadata/file-io-windows-internals.h"
+
+gunichar2
+ves_icall_System_IO_MonoIO_get_VolumeSeparatorChar ()
+{
+       return (gunichar2) ':'; /* colon */
+}
+
+gunichar2
+ves_icall_System_IO_MonoIO_get_DirectorySeparatorChar ()
+{
+       return (gunichar2) '\\';        /* backslash */
+}
+
+gunichar2
+ves_icall_System_IO_MonoIO_get_AltDirectorySeparatorChar ()
+{
+       return (gunichar2) '/'; /* forward slash */
+}
+
+gunichar2
+ves_icall_System_IO_MonoIO_get_PathSeparator ()
+{
+       return (gunichar2) ';'; /* semicolon */
+}
+
+void ves_icall_System_IO_MonoIO_DumpHandles (void)
+{
+       return;
+}
+#endif /* HOST_WIN32 */
index 1e0422e35fbc0f069b63b3136850af188a785384..dd722f289a958c6a8c6452a9fc6bb073d7268fe5 100644 (file)
@@ -29,6 +29,7 @@
 #include <mono/metadata/object.h>
 #include <mono/io-layer/io-layer.h>
 #include <mono/metadata/file-io.h>
+#include <mono/metadata/file-io-internals.h>
 #include <mono/metadata/exception.h>
 #include <mono/metadata/appdomain.h>
 #include <mono/metadata/marshal.h>
@@ -606,33 +607,55 @@ ves_icall_System_IO_MonoIO_SetCurrentDirectory (MonoString *path,
        return(ret);
 }
 
-MonoBoolean
-ves_icall_System_IO_MonoIO_MoveFile (MonoString *path, MonoString *dest,
-                                    gint32 *error)
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+gboolean
+mono_file_io_move_file (gunichar2 *path, gunichar2 *dest, gint32 *error)
 {
-       gboolean ret;
+       gboolean result = FALSE;
        MONO_ENTER_GC_SAFE;
-       
+
+       result = MoveFile (path, dest);
+       if (result == FALSE) {
+               *error=GetLastError ();
+       }
+
+       MONO_EXIT_GC_SAFE;
+       return result;
+}
+#endif /* HAVE_CLASSIC_WINAPI_SUPPORT */
+
+MonoBoolean
+ves_icall_System_IO_MonoIO_MoveFile (MonoString *path, MonoString *dest, gint32 *error)
+{
        *error=ERROR_SUCCESS;
+       return mono_file_io_move_file (mono_string_chars (path), mono_string_chars (dest), error);
+}
 
-       ret=MoveFile (mono_string_chars (path), mono_string_chars (dest));
-       if(ret==FALSE) {
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+gboolean
+mono_file_io_replace_file (gunichar2 *destinationFileName, gunichar2 *sourceFileName,
+                          gunichar2 *destinationBackupFileName, guint32 flags, gint32 *error)
+{
+       gboolean result = FALSE;
+       MONO_ENTER_GC_SAFE;
+
+       result = ReplaceFile (destinationFileName, sourceFileName, destinationBackupFileName, flags, NULL, NULL);
+       if (result == FALSE) {
                *error=GetLastError ();
        }
 
        MONO_EXIT_GC_SAFE;
-       return(ret);
+       return result;
 }
+#endif /* HAVE_CLASSIC_WINAPI_SUPPORT */
 
 MonoBoolean
 ves_icall_System_IO_MonoIO_ReplaceFile (MonoString *sourceFileName, MonoString *destinationFileName,
                                        MonoString *destinationBackupFileName, MonoBoolean ignoreMetadataErrors,
                                        gint32 *error)
 {
-       gboolean ret;
        gunichar2 *utf16_sourceFileName = NULL, *utf16_destinationFileName = NULL, *utf16_destinationBackupFileName = NULL;
        guint32 replaceFlags = REPLACEFILE_WRITE_THROUGH;
-       MONO_ENTER_GC_SAFE;
 
        if (sourceFileName)
                utf16_sourceFileName = mono_string_chars (sourceFileName);
@@ -646,31 +669,33 @@ ves_icall_System_IO_MonoIO_ReplaceFile (MonoString *sourceFileName, MonoString *
                replaceFlags |= REPLACEFILE_IGNORE_MERGE_ERRORS;
 
        /* FIXME: source and destination file names must not be NULL, but apparently they might be! */
-       ret = ReplaceFile (utf16_destinationFileName, utf16_sourceFileName, utf16_destinationBackupFileName,
-                        replaceFlags, NULL, NULL);
-       if (ret == FALSE)
-               *error = GetLastError ();
+       return mono_file_io_replace_file (utf16_destinationFileName, utf16_sourceFileName,
+                                         utf16_destinationBackupFileName, replaceFlags, error);
+}
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+gboolean
+mono_file_io_copy_file (gunichar2 *path, gunichar2 *dest, gboolean overwrite, gint32 *error)
+{
+       gboolean result = FALSE;
+       MONO_ENTER_GC_SAFE;
+
+       result = CopyFile (path, dest, !overwrite);
+       if (result == FALSE) {
+               *error=GetLastError ();
+       }
 
        MONO_EXIT_GC_SAFE;
-       return ret;
+       return result;
 }
+#endif /* HAVE_CLASSIC_WINAPI_SUPPORT */
 
 MonoBoolean
 ves_icall_System_IO_MonoIO_CopyFile (MonoString *path, MonoString *dest,
                                     MonoBoolean overwrite, gint32 *error)
 {
-       gboolean ret;
-       MONO_ENTER_GC_SAFE;
-       
        *error=ERROR_SUCCESS;
-       
-       ret=CopyFile (mono_string_chars (path), mono_string_chars (dest), !overwrite);
-       if(ret==FALSE) {
-               *error=GetLastError ();
-       }
-       
-       MONO_EXIT_GC_SAFE;
-       return(ret);
+       return mono_file_io_copy_file (mono_string_chars (path), mono_string_chars (dest), overwrite, error);
 }
 
 MonoBoolean
@@ -948,23 +973,31 @@ ves_icall_System_IO_MonoIO_Flush (HANDLE handle, gint32 *error)
        return(ret);
 }
 
-gint64 
-ves_icall_System_IO_MonoIO_GetLength (HANDLE handle, gint32 *error)
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+gint64
+mono_file_io_get_file_size (HANDLE handle, gint32 *error)
 {
        gint64 length;
        guint32 length_hi;
+
        MONO_ENTER_GC_SAFE;
 
-       *error=ERROR_SUCCESS;
-       
        length = GetFileSize (handle, &length_hi);
        if(length==INVALID_FILE_SIZE) {
                *error=GetLastError ();
        }
-       
+
        MONO_EXIT_GC_SAFE;
        return length | ((gint64)length_hi << 32);
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+gint64
+ves_icall_System_IO_MonoIO_GetLength (HANDLE handle, gint32 *error)
+{
+       *error=ERROR_SUCCESS;
+       return mono_file_io_get_file_size (handle, error);
+}
 
 /* FIXME make gc suspendable */
 MonoBoolean
@@ -1113,48 +1146,34 @@ ves_icall_System_IO_MonoIO_DuplicateHandle (HANDLE source_process_handle, HANDLE
        return(TRUE);
 }
 
+#ifndef HOST_WIN32
 gunichar2 
 ves_icall_System_IO_MonoIO_get_VolumeSeparatorChar ()
 {
-#if defined (TARGET_WIN32)
-       return (gunichar2) ':'; /* colon */
-#else
        return (gunichar2) '/'; /* forward slash */
-#endif
 }
 
 gunichar2 
 ves_icall_System_IO_MonoIO_get_DirectorySeparatorChar ()
 {
-#if defined (TARGET_WIN32)
-       return (gunichar2) '\\';        /* backslash */
-#else
        return (gunichar2) '/'; /* forward slash */
-#endif
 }
 
 gunichar2 
 ves_icall_System_IO_MonoIO_get_AltDirectorySeparatorChar ()
 {
-#if defined (TARGET_WIN32)
-       return (gunichar2) '/'; /* forward slash */
-#else
        if (IS_PORTABILITY_SET)
                return (gunichar2) '\\';        /* backslash */
        else
                return (gunichar2) '/'; /* forward slash */
-#endif
 }
 
 gunichar2 
 ves_icall_System_IO_MonoIO_get_PathSeparator ()
 {
-#if defined (TARGET_WIN32)
-       return (gunichar2) ';'; /* semicolon */
-#else
        return (gunichar2) ':'; /* colon */
-#endif
 }
+#endif /* !HOST_WIN32 */
 
 static const gunichar2
 invalid_path_chars [] = {
@@ -1197,38 +1216,56 @@ ves_icall_System_IO_MonoIO_get_InvalidPathChars ()
        return chars;
 }
 
-void ves_icall_System_IO_MonoIO_Lock (HANDLE handle, gint64 position,
-                                     gint64 length, gint32 *error)
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+gboolean
+mono_file_io_lock_file (HANDLE handle, gint64 position, gint64 length, gint32 *error)
 {
-       gboolean ret;
+       gboolean result = FALSE;
        MONO_ENTER_GC_SAFE;
-       
-       *error=ERROR_SUCCESS;
-       
-       ret=LockFile (handle, position & 0xFFFFFFFF, position >> 32,
-                     length & 0xFFFFFFFF, length >> 32);
-       if (ret == FALSE) {
+
+       result = LockFile (handle, position & 0xFFFFFFFF, position >> 32,
+                          length & 0xFFFFFFFF, length >> 32);
+
+       if (result == FALSE) {
                *error = GetLastError ();
        }
 
        MONO_EXIT_GC_SAFE;
+       return result;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
 
-void ves_icall_System_IO_MonoIO_Unlock (HANDLE handle, gint64 position,
-                                       gint64 length, gint32 *error)
+void ves_icall_System_IO_MonoIO_Lock (HANDLE handle, gint64 position,
+                                     gint64 length, gint32 *error)
 {
-       gboolean ret;
-       MONO_ENTER_GC_SAFE;
-       
        *error=ERROR_SUCCESS;
+       mono_file_io_lock_file (handle, position, length, error);
+}
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+gboolean
+mono_file_io_unlock_file (HANDLE handle, gint64 position, gint64 length, gint32 *error)
+{
+       gboolean result = FALSE;
+       MONO_ENTER_GC_SAFE;
        
-       ret=UnlockFile (handle, position & 0xFFFFFFFF, position >> 32,
-                       length & 0xFFFFFFFF, length >> 32);
-       if (ret == FALSE) {
+       result = UnlockFile (handle, position & 0xFFFFFFFF, position >> 32,
+                            length & 0xFFFFFFFF, length >> 32);
+
+       if (result == FALSE) {
                *error = GetLastError ();
        }
 
        MONO_EXIT_GC_SAFE;
+       return result;
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+void ves_icall_System_IO_MonoIO_Unlock (HANDLE handle, gint64 position,
+                                       gint64 length, gint32 *error)
+{
+       *error=ERROR_SUCCESS;
+       mono_file_io_unlock_file (handle, position, length, error);
 }
 
 //Support for io-layer free mmap'd files.
@@ -1274,11 +1311,12 @@ mono_filesize_from_fd (int fd)
 
 #endif
 
+#ifndef HOST_WIN32
 void mono_w32handle_dump (void);
 
 void ves_icall_System_IO_MonoIO_DumpHandles (void)
 {
-#ifndef HOST_WIN32
+
        mono_w32handle_dump ();
-#endif
 }
+#endif /* !HOST_WIN32 */
index 703ad861363ca259bc48ebf4e7a298d0595d9fc5..c90a85a3c3d4c28297ffac4faef0d189b766412d 100644 (file)
@@ -124,9 +124,6 @@ ICALL(BTLS_PKCS12_8, "mono_btls_pkcs12_import", mono_btls_pkcs12_import)
 ICALL(BTLS_PKCS12_9, "mono_btls_pkcs12_new", mono_btls_pkcs12_new)
 ICALL(BTLS_PKCS12_10, "mono_btls_pkcs12_up_ref", mono_btls_pkcs12_up_ref)
 
-ICALL_TYPE(BTLS_PROVIDER, "Mono.Btls.MonoBtlsProvider", BTLS_PROVIDER_1)
-ICALL(BTLS_PROVIDER_1, "IsSupported", ves_icall_Mono_Btls_Provider_IsSupported)
-
 ICALL_TYPE(BTLS_SSL, "Mono.Btls.MonoBtlsSsl", BTLS_SSL_1)
 ICALL(BTLS_SSL_1, "mono_btls_ssl_accept", mono_btls_ssl_accept)
 ICALL(BTLS_SSL_2, "mono_btls_ssl_add_chain_certificate", mono_btls_ssl_add_chain_certificate)
@@ -314,9 +311,6 @@ ICALL(BTLS_X509_VERIFY_PARAM_16, "mono_btls_x509_verify_param_set_mono_flags", m
 ICALL(BTLS_X509_VERIFY_PARAM_17, "mono_btls_x509_verify_param_set_name", mono_btls_x509_verify_param_set_name)
 ICALL(BTLS_X509_VERIFY_PARAM_18, "mono_btls_x509_verify_param_set_purpose", mono_btls_x509_verify_param_set_purpose)
 ICALL(BTLS_X509_VERIFY_PARAM_19, "mono_btls_x509_verify_param_set_time", mono_btls_x509_verify_param_set_time)
-#else
-ICALL_TYPE(BTLS_PROVIDER, "Mono.Btls.MonoBtlsProvider", BTLS_PROVIDER_1)
-ICALL(BTLS_PROVIDER_1, "IsSupported", ves_icall_Mono_Btls_Provider_IsSupported)
 #endif
 
 #ifndef DISABLE_COM
@@ -325,6 +319,9 @@ ICALL(COMPROX_1, "AddProxy", ves_icall_Mono_Interop_ComInteropProxy_AddProxy)
 ICALL(COMPROX_2, "FindProxy", ves_icall_Mono_Interop_ComInteropProxy_FindProxy)
 #endif
 
+ICALL_TYPE(TLS_PROVIDER_FACTORY, "Mono.Net.Security.MonoTlsProviderFactory", TLS_PROVIDER_FACTORY_1)
+ICALL(TLS_PROVIDER_FACTORY_1, "IsBtlsSupported", ves_icall_Mono_TlsProviderFactory_IsBtlsSupported)
+
 ICALL_TYPE(RUNTIME, "Mono.Runtime", RUNTIME_1)
 ICALL(RUNTIME_1, "GetDisplayName", ves_icall_Mono_Runtime_GetDisplayName)
 ICALL(RUNTIME_12, "GetNativeStackTrace", ves_icall_Mono_Runtime_GetNativeStackTrace)
@@ -412,13 +409,13 @@ ICALL_TYPE (COMPO_W, "System.ComponentModel.Win32Exception", COMPO_W_1)
 ICALL (COMPO_W_1, "W32ErrorMessage", ves_icall_System_ComponentModel_Win32Exception_W32ErrorMessage)
 
 ICALL_TYPE(DEFAULTC, "System.Configuration.DefaultConfig", DEFAULTC_1)
-HANDLES(ICALL(DEFAULTC_1, "get_bundled_machine_config", get_bundled_machine_config))
+HANDLES(ICALL(DEFAULTC_1, "get_bundled_machine_config", ves_icall_System_Configuration_DefaultConfig_get_bundled_machine_config))
 ICALL(DEFAULTC_2, "get_machine_config_path", ves_icall_System_Configuration_DefaultConfig_get_machine_config_path)
 
 /* Note that the below icall shares the same function as DefaultConfig uses */
 ICALL_TYPE(INTCFGHOST, "System.Configuration.InternalConfigurationHost", INTCFGHOST_1)
 ICALL(INTCFGHOST_1, "get_bundled_app_config", get_bundled_app_config)
-ICALL(INTCFGHOST_2, "get_bundled_machine_config", get_bundled_machine_config)
+HANDLES(ICALL(INTCFGHOST_2, "get_bundled_machine_config", ves_icall_System_Configuration_InternalConfigurationHost_get_bundled_machine_config))
 
 ICALL_TYPE(CONSOLE, "System.ConsoleDriver", CONSOLE_1)
 ICALL(CONSOLE_1, "InternalKeyAvailable", ves_icall_System_ConsoleDriver_InternalKeyAvailable )
@@ -521,6 +518,7 @@ ICALL(ENV_13, "get_Platform", ves_icall_System_Environment_get_Platform)
 ICALL(ENV_14, "get_ProcessorCount", mono_cpu_count)
 ICALL(ENV_15, "get_TickCount", ves_icall_System_Environment_get_TickCount)
 ICALL(ENV_16, "get_UserName", ves_icall_System_Environment_get_UserName)
+HANDLES(ICALL(ENV_16b, "get_bundled_machine_config", get_bundled_machine_config))
 ICALL(ENV_16m, "internalBroadcastSettingChange", ves_icall_System_Environment_BroadcastSettingChange)
 HANDLES(ICALL(ENV_17, "internalGetEnvironmentVariable_native", ves_icall_System_Environment_GetEnvironmentVariable_native))
 HANDLES(ICALL(ENV_18, "internalGetGacPath", ves_icall_System_Environment_GetGacPath))
@@ -680,8 +678,8 @@ ICALL(MCATTR_3, "IsDefinedInternal", custom_attrs_defined_internal)
 
 #ifndef DISABLE_SOCKETS
 ICALL_TYPE(NDNS, "System.Net.Dns", NDNS_1)
-ICALL(NDNS_1, "GetHostByAddr_internal(string,string&,string[]&,string[]&)", ves_icall_System_Net_Dns_GetHostByAddr_internal)
-ICALL(NDNS_2, "GetHostByName_internal(string,string&,string[]&,string[]&)", ves_icall_System_Net_Dns_GetHostByName_internal)
+ICALL(NDNS_1, "GetHostByAddr_internal(string,string&,string[]&,string[]&,int)", ves_icall_System_Net_Dns_GetHostByAddr_internal)
+ICALL(NDNS_2, "GetHostByName_internal(string,string&,string[]&,string[]&,int)", ves_icall_System_Net_Dns_GetHostByName_internal)
 ICALL(NDNS_3, "GetHostName_internal(string&)", ves_icall_System_Net_Dns_GetHostName_internal)
 
 #if defined(PLATFORM_MACOSX) || defined(PLATFORM_BSD)
@@ -695,7 +693,7 @@ ICALL(SOCK_2, "Available_internal(intptr,int&)", ves_icall_System_Net_Sockets_So
 ICALL(SOCK_3, "Bind_internal(intptr,System.Net.SocketAddress,int&)", ves_icall_System_Net_Sockets_Socket_Bind_internal)
 ICALL(SOCK_4, "Blocking_internal(intptr,bool,int&)", ves_icall_System_Net_Sockets_Socket_Blocking_internal)
 ICALL(SOCK_5, "Close_internal(intptr,int&)", ves_icall_System_Net_Sockets_Socket_Close_internal)
-ICALL(SOCK_6, "Connect_internal(intptr,System.Net.SocketAddress,int&)", ves_icall_System_Net_Sockets_Socket_Connect_internal)
+ICALL(SOCK_6, "Connect_internal(intptr,System.Net.SocketAddress,int&,bool)", ves_icall_System_Net_Sockets_Socket_Connect_internal)
 ICALL (SOCK_6a, "Disconnect_internal(intptr,bool,int&)", ves_icall_System_Net_Sockets_Socket_Disconnect_internal)
 ICALL(SOCK_7, "GetSocketOption_arr_internal(intptr,System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,byte[]&,int&)", ves_icall_System_Net_Sockets_Socket_GetSocketOption_arr_internal)
 ICALL(SOCK_8, "GetSocketOption_obj_internal(intptr,System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,object&,int&)", ves_icall_System_Net_Sockets_Socket_GetSocketOption_obj_internal)
@@ -703,15 +701,15 @@ ICALL(SOCK_21, "IOControl_internal(intptr,int,byte[],byte[],int&)", ves_icall_Sy
 ICALL(SOCK_9, "Listen_internal(intptr,int,int&)", ves_icall_System_Net_Sockets_Socket_Listen_internal)
 ICALL(SOCK_10, "LocalEndPoint_internal(intptr,int,int&)", ves_icall_System_Net_Sockets_Socket_LocalEndPoint_internal)
 ICALL(SOCK_11, "Poll_internal", ves_icall_System_Net_Sockets_Socket_Poll_internal)
-ICALL(SOCK_13, "ReceiveFrom_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,System.Net.SocketAddress&,int&)", ves_icall_System_Net_Sockets_Socket_ReceiveFrom_internal)
-ICALL(SOCK_11a, "Receive_internal(intptr,System.Net.Sockets.Socket/WSABUF[],System.Net.Sockets.SocketFlags,int&)", ves_icall_System_Net_Sockets_Socket_Receive_array_internal)
-ICALL(SOCK_12, "Receive_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,int&)", ves_icall_System_Net_Sockets_Socket_Receive_internal)
+ICALL(SOCK_13, "ReceiveFrom_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,System.Net.SocketAddress&,int&,bool)", ves_icall_System_Net_Sockets_Socket_ReceiveFrom_internal)
+ICALL(SOCK_11a, "Receive_internal(intptr,System.Net.Sockets.Socket/WSABUF[],System.Net.Sockets.SocketFlags,int&,bool)", ves_icall_System_Net_Sockets_Socket_Receive_array_internal)
+ICALL(SOCK_12, "Receive_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,int&,bool)", ves_icall_System_Net_Sockets_Socket_Receive_internal)
 ICALL(SOCK_14, "RemoteEndPoint_internal(intptr,int,int&)", ves_icall_System_Net_Sockets_Socket_RemoteEndPoint_internal)
 ICALL(SOCK_15, "Select_internal(System.Net.Sockets.Socket[]&,int,int&)", ves_icall_System_Net_Sockets_Socket_Select_internal)
-ICALL(SOCK_15a, "SendFile_internal(intptr,string,byte[],byte[],System.Net.Sockets.TransmitFileOptions)", ves_icall_System_Net_Sockets_Socket_SendFile_internal)
-ICALL(SOCK_16, "SendTo_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,System.Net.SocketAddress,int&)", ves_icall_System_Net_Sockets_Socket_SendTo_internal)
-ICALL(SOCK_16a, "Send_internal(intptr,System.Net.Sockets.Socket/WSABUF[],System.Net.Sockets.SocketFlags,int&)", ves_icall_System_Net_Sockets_Socket_Send_array_internal)
-ICALL(SOCK_17, "Send_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,int&)", ves_icall_System_Net_Sockets_Socket_Send_internal)
+ICALL(SOCK_15a, "SendFile_internal(intptr,string,byte[],byte[],System.Net.Sockets.TransmitFileOptions,int&,bool)", ves_icall_System_Net_Sockets_Socket_SendFile_internal)
+ICALL(SOCK_16, "SendTo_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,System.Net.SocketAddress,int&,bool)", ves_icall_System_Net_Sockets_Socket_SendTo_internal)
+ICALL(SOCK_16a, "Send_internal(intptr,System.Net.Sockets.Socket/WSABUF[],System.Net.Sockets.SocketFlags,int&,bool)", ves_icall_System_Net_Sockets_Socket_Send_array_internal)
+ICALL(SOCK_17, "Send_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,int&,bool)", ves_icall_System_Net_Sockets_Socket_Send_internal)
 ICALL(SOCK_18, "SetSocketOption_internal(intptr,System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,object,byte[],int,int&)", ves_icall_System_Net_Sockets_Socket_SetSocketOption_internal)
 ICALL(SOCK_19, "Shutdown_internal(intptr,System.Net.Sockets.SocketShutdown,int&)", ves_icall_System_Net_Sockets_Socket_Shutdown_internal)
 ICALL(SOCK_20, "Socket_internal(System.Net.Sockets.AddressFamily,System.Net.Sockets.SocketType,System.Net.Sockets.ProtocolType,int&)", ves_icall_System_Net_Sockets_Socket_Socket_internal)
diff --git a/mono/metadata/icall-internals.h b/mono/metadata/icall-internals.h
new file mode 100644 (file)
index 0000000..e2ec776
--- /dev/null
@@ -0,0 +1,82 @@
+/*
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#ifndef __MONO_METADATA_ICALL_INTERNALS_H__
+#define __MONO_METADATA_ICALL_INTERNALS_H__
+
+#include <config.h>
+#include <glib.h>
+#include <mono/metadata/object-internals.h>
+
+// On Windows platform implementation of bellow methods are hosted in separate source file
+// icall-windows.c or icall-windows-*.c. On other platforms the implementation is still keept
+// in icall.c still declared as static and in some places even inlined.
+#ifdef HOST_WIN32
+void
+mono_icall_make_platform_path (gchar *path);
+
+const gchar *
+mono_icall_get_file_path_prefix (const gchar *path);
+
+gpointer
+mono_icall_module_get_hinstance (MonoReflectionModule *module);
+
+MonoString *
+mono_icall_get_machine_name (void);
+
+int
+mono_icall_get_platform (void);
+
+MonoString *
+mono_icall_get_new_line (void);
+
+MonoBoolean
+mono_icall_is_64bit_os (void);
+
+MonoArray *
+mono_icall_get_environment_variable_names (void);
+
+void
+mono_icall_set_environment_variable (MonoString *name, MonoString *value);
+
+MonoString *
+mono_icall_get_windows_folder_path (int folder);
+
+void
+mono_icall_broadcast_setting_change (void);
+
+void
+mono_icall_write_windows_debug_string (MonoString *message);
+
+MonoBoolean
+mono_icall_close_process (gpointer handle);
+
+gint32
+mono_icall_wait_for_input_idle (gpointer handle, gint32 milliseconds);
+#endif  /* HOST_WIN32 */
+
+// On platforms not using classic WIN API support the  implementation of bellow methods are hosted in separate source file
+// icall-windows-*.c. On platforms using classic WIN API the implementation is still keept in icall.c and still declared
+// static and in some places even inlined.
+#if !G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+MonoArray *
+mono_icall_get_logical_drives (void);
+
+guint32
+mono_icall_drive_info_get_drive_type (MonoString *root_path_name);
+
+MonoBoolean
+mono_icall_get_process_working_set_size (gpointer handle, gsize *min, gsize *max);
+
+MonoBoolean
+mono_icall_set_process_working_set_size (gpointer handle, gsize min, gsize max);
+
+gint32
+mono_icall_get_priority_class (gpointer handle);
+
+MonoBoolean
+mono_icall_set_priority_class (gpointer handle, gint32 priorityClass);
+#endif  /* !G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+#endif /* __MONO_METADATA_ICALL_INTERNALS_H__ */
diff --git a/mono/metadata/icall-windows-internals.h b/mono/metadata/icall-windows-internals.h
new file mode 100644 (file)
index 0000000..0093767
--- /dev/null
@@ -0,0 +1,18 @@
+/*
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#ifndef __MONO_METADATA_ICALL_WINDOWS_INTERNALS_H__
+#define __MONO_METADATA_ICALL_WINDOWS_INTERNALS_H__
+
+#include <config.h>
+#include <glib.h>
+
+#ifdef HOST_WIN32
+#include "mono/metadata/icall-internals.h"
+#include "mono/metadata/object.h"
+#include "mono/metadata/object-internals.h"
+#include "mono/metadata/class.h"
+#include "mono/metadata/class-internals.h"
+#endif /* HOST_WIN32 */
+#endif /* __MONO_METADATA_ICALL_WINDOWS_INTERNALS_H__ */
diff --git a/mono/metadata/icall-windows-uwp.c b/mono/metadata/icall-windows-uwp.c
new file mode 100644 (file)
index 0000000..f273198
--- /dev/null
@@ -0,0 +1,158 @@
+/*
+ * icall-windows-uwp.c: UWP icall support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+
+#if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
+#include <Windows.h>
+#include "mono/metadata/icall-windows-internals.h"
+
+MonoString *
+mono_icall_get_machine_name (void)
+{
+       g_unsupported_api ("GetComputerName");
+       return mono_string_new (mono_domain_get (), "mono");
+}
+
+MonoString *
+mono_icall_get_windows_folder_path (int folder)
+{
+       g_unsupported_api ("SHGetFolderPath");
+       return mono_string_new (mono_domain_get (), "");
+}
+
+MonoArray *
+mono_icall_get_logical_drives (void)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("GetLogicalDriveStrings");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "GetLogicalDriveStrings");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return NULL;
+}
+
+void
+mono_icall_broadcast_setting_change (void)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("SendMessageTimeout");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "SendMessageTimeout");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return;
+}
+
+guint32
+mono_icall_drive_info_get_drive_type (MonoString *root_path_name)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("GetDriveType");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "GetDriveType");
+       mono_error_set_pending_exception (&mono_error);
+
+       return DRIVE_UNKNOWN;
+}
+
+gint32
+mono_icall_wait_for_input_idle (gpointer handle, gint32 milliseconds)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("WaitForInputIdle");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "WaitForInputIdle");
+       mono_error_set_pending_exception (&mono_error);
+
+       return WAIT_TIMEOUT;
+}
+
+MonoBoolean
+mono_icall_get_process_working_set_size (gpointer handle, gsize *min, gsize *max)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("GetProcessWorkingSetSize");
+
+       mono_error_set_not_supported(&mono_error, G_UNSUPPORTED_API, "GetProcessWorkingSetSize");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+MonoBoolean
+mono_icall_set_process_working_set_size (gpointer handle, gsize min, gsize max)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("SetProcessWorkingSetSize");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "SetProcessWorkingSetSize");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+gint32
+mono_icall_get_priority_class (gpointer handle)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("GetPriorityClass");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "GetPriorityClass");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+MonoBoolean
+mono_icall_set_priority_class (gpointer handle, gint32 priorityClass)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("SetPriorityClass");
+
+       mono_error_set_not_supported(&mono_error, G_UNSUPPORTED_API, "SetPriorityClass");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+#else /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_icall_windows_uwp_quiet_lnk4221(void) {}
+#endif
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
diff --git a/mono/metadata/icall-windows.c b/mono/metadata/icall-windows.c
new file mode 100644 (file)
index 0000000..6c80211
--- /dev/null
@@ -0,0 +1,221 @@
+/*
+ * icall-windows.c: Windows icall support.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#include <config.h>
+#include <glib.h>
+
+#if defined(HOST_WIN32)
+#include <WinSock2.h>
+#include <Windows.h>
+#include "mono/metadata/icall-windows-internals.h"
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+#include <shlobj.h>
+#endif
+
+void
+mono_icall_make_platform_path (gchar *path)
+{
+       for (size_t i = strlen (path); i > 0; i--)
+               if (path [i-1] == '\\')
+                       path [i-1] = '/';
+}
+
+const gchar *
+mono_icall_get_file_path_prefix (const gchar *path)
+{
+       if (*path == '/' && *(path + 1) == '/') {
+               return "file:";
+       } else {
+               return "file:///";
+       }
+}
+
+gpointer
+mono_icall_module_get_hinstance (MonoReflectionModule *module)
+{
+       if (module->image && module->image->is_module_handle)
+               return module->image->raw_data;
+
+       return (gpointer) (-1);
+}
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+MonoString *
+mono_icall_get_machine_name (void)
+{
+       gunichar2 *buf;
+       guint32 len;
+       MonoString *result;
+
+       len = MAX_COMPUTERNAME_LENGTH + 1;
+       buf = g_new (gunichar2, len);
+
+       result = NULL;
+       if (GetComputerName (buf, (PDWORD) &len)) {
+               MonoError error;
+               result = mono_string_new_utf16_checked (mono_domain_get (), buf, len, &error);
+               mono_error_set_pending_exception (&error);
+       }
+
+       g_free (buf);
+       return result;
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+int
+mono_icall_get_platform (void)
+{
+       /* Win32NT */
+       return 2;
+}
+
+MonoString *
+mono_icall_get_new_line (void)
+{
+       return mono_string_new (mono_domain_get (), "\r\n");
+}
+
+MonoBoolean
+mono_icall_is_64bit_os (void)
+{
+#if SIZEOF_VOID_P == 8
+       return TRUE;
+#else
+       gboolean isWow64Process = FALSE;
+       if (IsWow64Process (GetCurrentProcess (), &isWow64Process)) {
+               return (MonoBoolean)isWow64Process;
+       }
+       return FALSE;
+#endif
+}
+
+MonoArray *
+mono_icall_get_environment_variable_names (void)
+{
+       MonoError error;
+       MonoArray *names;
+       MonoDomain *domain;
+       MonoString *str;
+       WCHAR* env_strings;
+       WCHAR* env_string;
+       WCHAR* equal_str;
+       int n = 0;
+
+       env_strings = GetEnvironmentStrings();
+
+       if (env_strings) {
+               env_string = env_strings;
+               while (*env_string != '\0') {
+               /* weird case that MS seems to skip */
+                       if (*env_string != '=')
+                               n++;
+                       while (*env_string != '\0')
+                               env_string++;
+                       env_string++;
+               }
+       }
+
+       domain = mono_domain_get ();
+       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;
+               env_string = env_strings;
+               while (*env_string != '\0') {
+                       /* weird case that MS seems to skip */
+                       if (*env_string != '=') {
+                               equal_str = wcschr(env_string, '=');
+                               g_assert(equal_str);
+                               str = mono_string_new_utf16_checked (domain, env_string, (gint32)(equal_str - env_string), &error);
+                               if (mono_error_set_pending_exception (&error))
+                                       return NULL;
+
+                               mono_array_setref (names, n, str);
+                               n++;
+                       }
+                       while (*env_string != '\0')
+                               env_string++;
+                       env_string++;
+               }
+
+               FreeEnvironmentStrings (env_strings);
+       }
+
+       return names;
+}
+
+void
+mono_icall_set_environment_variable (MonoString *name, MonoString *value)
+{
+       gunichar2 *utf16_name, *utf16_value;
+
+       utf16_name = mono_string_to_utf16 (name);
+       if ((value == NULL) || (mono_string_length (value) == 0) || (mono_string_chars (value)[0] == 0)) {
+               SetEnvironmentVariable (utf16_name, NULL);
+               g_free (utf16_name);
+               return;
+       }
+
+       utf16_value = mono_string_to_utf16 (value);
+
+       SetEnvironmentVariable (utf16_name, utf16_value);
+
+       g_free (utf16_name);
+       g_free (utf16_value);
+}
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+MonoString *
+mono_icall_get_windows_folder_path (int folder)
+{
+       #ifndef CSIDL_FLAG_CREATE
+               #define CSIDL_FLAG_CREATE       0x8000
+       #endif
+
+       WCHAR path [MAX_PATH];
+       /* Create directory if no existing */
+       if (SUCCEEDED (SHGetFolderPathW (NULL, folder | CSIDL_FLAG_CREATE, NULL, 0, path))) {
+               int len = 0;
+               while (path [len])
+                       ++ len;
+               MonoError error;
+               MonoString *res = mono_string_new_utf16_checked (mono_domain_get (), path, len, &error);
+               mono_error_set_pending_exception (&error);
+               return res;
+       }
+       return mono_string_new (mono_domain_get (), "");
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+void
+mono_icall_broadcast_setting_change (void)
+{
+       SendMessageTimeout (HWND_BROADCAST, WM_SETTINGCHANGE, (WPARAM)NULL, (LPARAM)L"Environment", SMTO_ABORTIFHUNG, 2000, 0);
+}
+
+gint32
+mono_icall_wait_for_input_idle (gpointer handle, gint32 milliseconds)
+{
+       return WaitForInputIdle (handle, milliseconds);
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+void
+mono_icall_write_windows_debug_string (MonoString *message)
+{
+       OutputDebugString (mono_string_chars (message));
+}
+
+MonoBoolean
+mono_icall_close_process (gpointer handle)
+{
+       return (MonoBoolean)(CloseHandle (handle));
+}
+#endif /* HOST_WIN32 */
index bab8c6235f0fc9e7186d8f6f8b509567b1525d60..b47bf989fd47f1a860d71fc38bab7bf1557715f4 100644 (file)
 #ifdef HAVE_UNISTD_H
 #include <unistd.h>
 #endif
-#if defined (HOST_WIN32)
-#include <stdlib.h>
-#endif
 #if defined (HAVE_WCHAR_H)
 #include <wchar.h>
 #endif
-
+#include "mono/metadata/icall-internals.h"
 #include "mono/utils/mono-membar.h"
 #include <mono/metadata/object.h>
 #include <mono/metadata/threads.h>
 #include <mono/utils/mono-os-mutex.h>
 #include <mono/utils/mono-threads.h>
 
-#if defined (HOST_WIN32)
-#include <windows.h>
-#include <shlobj.h>
-#endif
 #include "decimal-ms.h"
 #include "number-ms.h"
 
@@ -158,6 +151,20 @@ mono_class_init_checked (MonoClass *klass, MonoError *error)
                mono_error_set_for_class_failure (error, klass);
 }
 
+#ifndef HOST_WIN32
+static inline void
+mono_icall_make_platform_path (gchar *path)
+{
+       return;
+}
+
+static inline const gchar *
+mono_icall_get_file_path_prefix (const gchar *path)
+{
+       return "file://";
+}
+#endif /* HOST_WIN32 */
+
 ICALL_EXPORT MonoObject *
 ves_icall_System_Array_GetValueImpl (MonoArray *arr, guint32 pos)
 {
@@ -993,15 +1000,24 @@ ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_RunModuleConstructor (M
 ICALL_EXPORT MonoBoolean
 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_SufficientExecutionStack (void)
 {
+#if defined(TARGET_WIN32) || defined(HOST_WIN32)
+       // It does not work on win32
+#else
        guint8 *stack_addr;
        guint8 *current;
        size_t stack_size;
-       /* later make this configurable and per-arch */
-       int min_size = 4096 * 4 * sizeof (void*);
+       int min_size;
+       MonoInternalThread *thread;
+
        mono_thread_info_get_stack_bounds (&stack_addr, &stack_size);
        /* if we have no info we are optimistic and assume there is enough room */
        if (!stack_addr)
                return TRUE;
+
+       thread = mono_thread_internal_current ();
+       // .net seems to check that at least 50% of stack is available
+       min_size = thread->stack_size / 2;
+
        current = (guint8 *)&stack_addr;
        if (current > stack_addr) {
                if ((current - stack_addr) < min_size)
@@ -1010,6 +1026,7 @@ ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_SufficientExecutionStac
                if (current - (stack_addr - stack_size) < min_size)
                        return FALSE;
        }
+#endif
        return TRUE;
 }
 
@@ -4433,8 +4450,8 @@ ves_icall_System_Reflection_Assembly_InternalGetType (MonoReflectionAssembly *as
                /* need to report exceptions ? */
                if (throwOnError && mono_class_has_failure (klass)) {
                        /* report SecurityException (or others) that occured when loading the assembly */
-                       MonoException *exc = mono_class_get_exception_for_failure (klass);
-                       mono_set_pending_exception (exc);
+                       mono_error_set_for_class_failure (&error, klass);
+                       mono_error_set_pending_exception (&error);
                        return NULL;
                }
        }
@@ -4495,25 +4512,13 @@ ves_icall_System_Reflection_Assembly_get_code_base (MonoReflectionAssembly *asse
 
        replace_shadow_path (domain, dirname, &absolute);
        g_free (dirname);
-#if HOST_WIN32
-       {
-               gint i;
-               for (i = strlen (absolute) - 1; i >= 0; i--)
-                       if (absolute [i] == '\\')
-                               absolute [i] = '/';
-       }
-#endif
+
+       mono_icall_make_platform_path (absolute);
+
        if (escaped) {
                uri = g_filename_to_uri (absolute, NULL, NULL);
        } else {
-               const char *prepend = "file://";
-#if HOST_WIN32
-               if (*absolute == '/' && *(absolute + 1) == '/') {
-                       prepend = "file:";
-               } else {
-                       prepend = "file:///";
-               }
-#endif
+               const gchar *prepend = mono_icall_get_file_path_prefix (absolute);
                uri = g_strconcat (prepend, absolute, NULL);
        }
 
@@ -5302,25 +5307,14 @@ fill_reflection_assembly_name (MonoDomain *domain, MonoReflectionAssemblyName *a
 
        codebase = NULL;
        if (absolute != NULL && *absolute != '\0') {
-               const gchar *prepend = "file://";
                gchar *result;
 
                codebase = g_strdup (absolute);
 
-#if HOST_WIN32
-               {
-                       gint i;
-                       for (i = strlen (codebase) - 1; i >= 0; i--)
-                               if (codebase [i] == '\\')
-                                       codebase [i] = '/';
+               mono_icall_make_platform_path (codebase);
+
+               const gchar *prepend = mono_icall_get_file_path_prefix (codebase);
 
-                       if (*codebase == '/' && *(codebase + 1) == '/') {
-                               prepend = "file:";
-                       } else {
-                               prepend = "file:///";
-                       }
-               }
-#endif
                result = g_strconcat (prepend, codebase, NULL);
                g_free (codebase);
                codebase = result;
@@ -5733,15 +5727,18 @@ ves_icall_System_Reflection_Module_GetGuidInternal (MonoReflectionModuleHandle r
        return mono_string_new_handle (domain, image->guid, error);
 }
 
+#ifndef HOST_WIN32
+static inline gpointer
+mono_icall_module_get_hinstance (MonoReflectionModule *module)
+{
+       return (gpointer) (-1);
+}
+#endif /* HOST_WIN32 */
+
 ICALL_EXPORT gpointer
 ves_icall_System_Reflection_Module_GetHINSTANCE (MonoReflectionModule *module)
 {
-#ifdef HOST_WIN32
-       if (module->image && module->image->is_module_handle)
-               return module->image->raw_data;
-#endif
-
-       return (gpointer) (-1);
+       return mono_icall_module_get_hinstance (module);
 }
 
 ICALL_EXPORT void
@@ -6144,7 +6141,6 @@ static void
 check_for_invalid_type (MonoClass *klass, MonoError *error)
 {
        char *name;
-       MonoString *str;
 
        mono_error_init (error);
 
@@ -6152,10 +6148,7 @@ check_for_invalid_type (MonoClass *klass, MonoError *error)
                return;
 
        name = mono_type_get_full_name (klass);
-       str =  mono_string_new (mono_domain_get (), name);
-       g_free (name);
-       mono_error_set_exception_instance (error, mono_get_exception_type_load (str, NULL));
-
+       mono_error_set_type_load_name (error, name, g_strdup (""), "");
 }
 ICALL_EXPORT MonoReflectionType *
 ves_icall_RuntimeType_make_array_type (MonoReflectionType *type, int rank)
@@ -6166,7 +6159,8 @@ ves_icall_RuntimeType_make_array_type (MonoReflectionType *type, int rank)
 
        klass = mono_class_from_mono_type (type->type);
        check_for_invalid_type (klass, &error);
-       mono_error_set_pending_exception (&error);
+       if (mono_error_set_pending_exception (&error))
+               return NULL;
 
        if (rank == 0) //single dimentional array
                aklass = mono_array_class_get (klass, 1);
@@ -6471,28 +6465,11 @@ ves_icall_System_Environment_get_UserName (void)
        return mono_string_new (mono_domain_get (), g_get_user_name ());
 }
 
-
-ICALL_EXPORT MonoString *
-ves_icall_System_Environment_get_MachineName (void)
+#ifndef HOST_WIN32
+static MonoString *
+mono_icall_get_machine_name (void)
 {
-#if defined (HOST_WIN32)
-       gunichar2 *buf;
-       guint32 len;
-       MonoString *result;
-
-       len = MAX_COMPUTERNAME_LENGTH + 1;
-       buf = g_new (gunichar2, len);
-
-       result = NULL;
-       if (GetComputerName (buf, (PDWORD) &len)) {
-               MonoError error;
-               result = mono_string_new_utf16_checked (mono_domain_get (), buf, len, &error);
-               mono_error_set_pending_exception (&error);
-       }
-
-       g_free (buf);
-       return result;
-#elif !defined(DISABLE_SOCKETS)
+#if !defined(DISABLE_SOCKETS)
        MonoString *result;
        char *buf;
        int n;
@@ -6515,14 +6492,19 @@ ves_icall_System_Environment_get_MachineName (void)
        return mono_string_new (mono_domain_get (), "mono");
 #endif
 }
+#endif /* !HOST_WIN32 */
 
-ICALL_EXPORT int
-ves_icall_System_Environment_get_Platform (void)
+ICALL_EXPORT MonoString *
+ves_icall_System_Environment_get_MachineName (void)
+{
+       return mono_icall_get_machine_name ();
+}
+
+#ifndef HOST_WIN32
+static inline int
+mono_icall_get_platform (void)
 {
-#if defined (TARGET_WIN32)
-       /* Win32NT */
-       return 2;
-#elif defined(__MACH__)
+#if defined(__MACH__)
        /* OSX */
        //
        // Notice that the value is hidden from user code, and only exposed
@@ -6537,29 +6519,36 @@ ves_icall_System_Environment_get_Platform (void)
        return 4;
 #endif
 }
+#endif /* !HOST_WIN32 */
+
+ICALL_EXPORT int
+ves_icall_System_Environment_get_Platform (void)
+{
+       return mono_icall_get_platform ();
+}
+
+#ifndef HOST_WIN32
+static inline MonoString *
+mono_icall_get_new_line (void)
+{
+       return mono_string_new (mono_domain_get (), "\n");
+}
+#endif /* !HOST_WIN32 */
 
 ICALL_EXPORT MonoString *
 ves_icall_System_Environment_get_NewLine (void)
 {
-#if defined (HOST_WIN32)
-       return mono_string_new (mono_domain_get (), "\r\n");
-#else
-       return mono_string_new (mono_domain_get (), "\n");
-#endif
+       return mono_icall_get_new_line ();
 }
 
-ICALL_EXPORT MonoBoolean
-ves_icall_System_Environment_GetIs64BitOperatingSystem (void)
+#ifndef HOST_WIN32
+static inline MonoBoolean
+mono_icall_is_64bit_os (void)
 {
 #if SIZEOF_VOID_P == 8
        return TRUE;
 #else
-#ifdef HOST_WIN32
-       gboolean isWow64Process = FALSE;
-       if (IsWow64Process (GetCurrentProcess (), &isWow64Process)) {
-               return (MonoBoolean)isWow64Process;
-       }
-#elif defined(HAVE_SYS_UTSNAME_H)
+#if defined(HAVE_SYS_UTSNAME_H)
        struct utsname name;
 
        if (uname (&name) >= 0) {
@@ -6569,6 +6558,13 @@ ves_icall_System_Environment_GetIs64BitOperatingSystem (void)
        return FALSE;
 #endif
 }
+#endif /* !HOST_WIN32 */
+
+ICALL_EXPORT MonoBoolean
+ves_icall_System_Environment_GetIs64BitOperatingSystem (void)
+{
+       return mono_icall_is_64bit_os ();
+}
 
 ICALL_EXPORT MonoStringHandle
 ves_icall_System_Environment_GetEnvironmentVariable_native (const gchar *utf8_name, MonoError *error)
@@ -6619,65 +6615,10 @@ ves_icall_System_Environment_GetCoomandLineArgs (void)
        return result;
 }
 
-ICALL_EXPORT MonoArray *
-ves_icall_System_Environment_GetEnvironmentVariableNames (void)
+#ifndef HOST_WIN32
+static MonoArray *
+mono_icall_get_environment_variable_names (void)
 {
-#ifdef HOST_WIN32
-       MonoError error;
-       MonoArray *names;
-       MonoDomain *domain;
-       MonoString *str;
-       WCHAR* env_strings;
-       WCHAR* env_string;
-       WCHAR* equal_str;
-       int n = 0;
-
-       env_strings = GetEnvironmentStrings();
-
-       if (env_strings) {
-               env_string = env_strings;
-               while (*env_string != '\0') {
-               /* weird case that MS seems to skip */
-                       if (*env_string != '=')
-                               n++;
-                       while (*env_string != '\0')
-                               env_string++;
-                       env_string++;
-               }
-       }
-
-       domain = mono_domain_get ();
-       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;
-               env_string = env_strings;
-               while (*env_string != '\0') {
-                       /* weird case that MS seems to skip */
-                       if (*env_string != '=') {
-                               equal_str = wcschr(env_string, '=');
-                               g_assert(equal_str);
-                               MonoError error;
-                               str = mono_string_new_utf16_checked (domain, env_string, equal_str-env_string, &error);
-                               if (mono_error_set_pending_exception (&error))
-                                       return NULL;
-
-                               mono_array_setref (names, n, str);
-                               n++;
-                       }
-                       while (*env_string != '\0')
-                               env_string++;
-                       env_string++;
-               }
-
-               FreeEnvironmentStrings (env_strings);
-       }
-
-       return names;
-
-#else
        MonoError error;
        MonoArray *names;
        MonoDomain *domain;
@@ -6708,34 +6649,22 @@ ves_icall_System_Environment_GetEnvironmentVariableNames (void)
        }
 
        return names;
-#endif
 }
+#endif /* !HOST_WIN32 */
 
-ICALL_EXPORT void
-ves_icall_System_Environment_InternalSetEnvironmentVariable (MonoString *name, MonoString *value)
+ICALL_EXPORT MonoArray *
+ves_icall_System_Environment_GetEnvironmentVariableNames (void)
+{
+       return mono_icall_get_environment_variable_names ();
+}
+
+#ifndef HOST_WIN32
+static void
+mono_icall_set_environment_variable (MonoString *name, MonoString *value)
 {
-#ifdef HOST_WIN32
-       gunichar2 *utf16_name, *utf16_value;
-#else
        gchar *utf8_name, *utf8_value;
        MonoError error;
-#endif
 
-#ifdef HOST_WIN32
-       utf16_name = mono_string_to_utf16 (name);
-       if ((value == NULL) || (mono_string_length (value) == 0) || (mono_string_chars (value)[0] == 0)) {
-               SetEnvironmentVariable (utf16_name, NULL);
-               g_free (utf16_name);
-               return;
-       }
-
-       utf16_value = mono_string_to_utf16 (value);
-
-       SetEnvironmentVariable (utf16_name, utf16_value);
-
-       g_free (utf16_name);
-       g_free (utf16_value);
-#else
        utf8_name = mono_string_to_utf8_checked (name, &error); /* FIXME: this should be ascii */
        if (mono_error_set_pending_exception (&error))
                return;
@@ -6756,7 +6685,13 @@ ves_icall_System_Environment_InternalSetEnvironmentVariable (MonoString *name, M
 
        g_free (utf8_name);
        g_free (utf8_value);
-#endif
+}
+#endif /* !HOST_WIN32 */
+
+ICALL_EXPORT void
+ves_icall_System_Environment_InternalSetEnvironmentVariable (MonoString *name, MonoString *value)
+{
+       mono_icall_set_environment_variable (name, value);
 }
 
 ICALL_EXPORT void
@@ -6788,36 +6723,27 @@ ves_icall_System_Environment_GetGacPath (MonoError *error)
        return mono_string_new_handle (mono_domain_get (), mono_assembly_getrootdir (), error);
 }
 
-ICALL_EXPORT MonoString*
-ves_icall_System_Environment_GetWindowsFolderPath (int folder)
+#ifndef HOST_WIN32
+static inline MonoString *
+mono_icall_get_windows_folder_path (int folder)
 {
-#if defined (HOST_WIN32)
-       #ifndef CSIDL_FLAG_CREATE
-               #define CSIDL_FLAG_CREATE       0x8000
-       #endif
-
-       WCHAR path [MAX_PATH];
-       /* Create directory if no existing */
-       if (SUCCEEDED (SHGetFolderPathW (NULL, folder | CSIDL_FLAG_CREATE, NULL, 0, path))) {
-               int len = 0;
-               while (path [len])
-                       ++ len;
-               MonoError error;
-               MonoString *res = mono_string_new_utf16_checked (mono_domain_get (), path, len, &error);
-               mono_error_set_pending_exception (&error);
-               return res;
-       }
-#else
        g_warning ("ves_icall_System_Environment_GetWindowsFolderPath should only be called on Windows!");
-#endif
        return mono_string_new (mono_domain_get (), "");
 }
+#endif /* !HOST_WIN32 */
 
-ICALL_EXPORT MonoArray *
-ves_icall_System_Environment_GetLogicalDrives (void)
+ICALL_EXPORT MonoString*
+ves_icall_System_Environment_GetWindowsFolderPath (int folder)
+{
+       return mono_icall_get_windows_folder_path (folder);
+}
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+static MonoArray *
+mono_icall_get_logical_drives (void)
 {
        MonoError error;
-        gunichar2 buf [256], *ptr, *dname;
+       gunichar2 buf [256], *ptr, *dname;
        gunichar2 *u16;
        guint initial_size = 127, size = 128;
        gint ndrives;
@@ -6872,6 +6798,13 @@ leave:
 
        return result;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+ICALL_EXPORT MonoArray *
+ves_icall_System_Environment_GetLogicalDrives (void)
+{
+       return mono_icall_get_logical_drives ();
+}
 
 ICALL_EXPORT MonoString *
 ves_icall_System_IO_DriveInfo_GetDriveFormat (MonoString *path)
@@ -6933,7 +6866,7 @@ ves_icall_System_Text_EncodingHelper_InternalCodePage (gint32 *int_code_page)
        *int_code_page = -1;
 
        g_get_charset (&cset);
-       c = codepage = strdup (cset);
+       c = codepage = g_strdup (cset);
        for (c = codepage; *c; c++){
                if (isascii (*c) && isalpha (*c))
                        *c = tolower (*c);
@@ -6980,12 +6913,18 @@ ves_icall_System_Environment_get_HasShutdownStarted (void)
        return FALSE;
 }
 
+#ifndef HOST_WIN32
+static inline void
+mono_icall_broadcast_setting_change (void)
+{
+       return;
+}
+#endif /* !HOST_WIN32 */
+
 ICALL_EXPORT void
 ves_icall_System_Environment_BroadcastSettingChange (void)
 {
-#ifdef HOST_WIN32
-       SendMessageTimeout (HWND_BROADCAST, WM_SETTINGCHANGE, (WPARAM)NULL, (LPARAM)L"Environment", SMTO_ABORTIFHUNG, 2000, 0);
-#endif
+       mono_icall_broadcast_setting_change ();
 }
 
 ICALL_EXPORT
@@ -7174,12 +7113,21 @@ ves_icall_System_IO_DriveInfo_GetDiskFreeSpace (MonoString *path_name, guint64 *
        return result;
 }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+static inline guint32
+mono_icall_drive_info_get_drive_type (MonoString *root_path_name)
+{
+       return GetDriveType (mono_string_chars (root_path_name));
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
 ICALL_EXPORT guint32
 ves_icall_System_IO_DriveInfo_GetDriveType (MonoString *root_path_name)
 {
-       return GetDriveType (mono_string_chars (root_path_name));
+       return mono_icall_drive_info_get_drive_type (root_path_name);
 }
-#endif
+
+#endif /* PLATFORM_NO_DRIVEINFO */
 
 ICALL_EXPORT gpointer
 ves_icall_RuntimeMethodHandle_GetFunctionPointer (MonoMethod *method)
@@ -7198,15 +7146,8 @@ ves_icall_System_Configuration_DefaultConfig_get_machine_config_path (void)
 
        path = g_build_path (G_DIR_SEPARATOR_S, mono_get_config_dir (), "mono", mono_get_runtime_info ()->framework_version, "machine.config", NULL);
 
-#if defined (HOST_WIN32)
-       /* Avoid mixing '/' and '\\' */
-       {
-               gint i;
-               for (i = strlen (path) - 1; i >= 0; i--)
-                       if (path [i] == '/')
-                               path [i] = '\\';
-       }
-#endif
+       mono_icall_make_platform_path (path);
+
        mcpath = mono_string_new (mono_domain_get (), path);
        g_free (path);
 
@@ -7260,7 +7201,6 @@ get_bundled_app_config (void)
        return mono_string_new (mono_domain_get (), app_config);
 }
 
-/* this is an icall */
 static MonoStringHandle
 get_bundled_machine_config (MonoError *error)
 {
@@ -7274,6 +7214,19 @@ get_bundled_machine_config (MonoError *error)
        return mono_string_new_handle (mono_domain_get (), machine_config, error);
 }
 
+static MonoStringHandle
+ves_icall_System_Configuration_DefaultConfig_get_bundled_machine_config (MonoError *error)
+{
+       return get_bundled_machine_config (error);
+}
+
+static MonoStringHandle
+ves_icall_System_Configuration_InternalConfigurationHost_get_bundled_machine_config (MonoError *error)
+{
+       return get_bundled_machine_config (error);
+}
+
+
 ICALL_EXPORT MonoString *
 ves_icall_System_Web_Util_ICalls_get_machine_install_dir (void)
 {
@@ -7282,15 +7235,8 @@ ves_icall_System_Web_Util_ICalls_get_machine_install_dir (void)
 
        path = g_path_get_dirname (mono_get_config_dir ());
 
-#if defined (HOST_WIN32)
-       /* Avoid mixing '/' and '\\' */
-       {
-               gint i;
-               for (i = strlen (path) - 1; i >= 0; i--)
-                       if (path [i] == '/')
-                               path [i] = '\\';
-       }
-#endif
+       mono_icall_make_platform_path (path);
+
        ipath = mono_string_new (mono_domain_get (), path);
        g_free (path);
 
@@ -7345,14 +7291,18 @@ ves_icall_System_Diagnostics_Debugger_Log (int level, MonoString *category, Mono
                mono_get_runtime_callbacks ()->debug_log (level, category, message);
 }
 
+#ifndef HOST_WIN32
+static inline void
+mono_icall_write_windows_debug_string (MonoString *message)
+{
+       g_warning ("WriteWindowsDebugString called and HOST_WIN32 not defined!\n");
+}
+#endif /* !HOST_WIN32 */
+
 ICALL_EXPORT void
 ves_icall_System_Diagnostics_DefaultTraceListener_WriteWindowsDebugString (MonoString *message)
 {
-#if defined (HOST_WIN32)
-       OutputDebugString (mono_string_chars (message));
-#else
-       g_warning ("WriteWindowsDebugString called and HOST_WIN32 not defined!\n");
-#endif
+       mono_icall_write_windows_debug_string (message);
 }
 
 /* Only used for value types */
@@ -8030,14 +7980,18 @@ ves_icall_Microsoft_Win32_NativeMethods_GetExitCodeProcess (gpointer handle, gin
        return GetExitCodeProcess (handle, (guint32*) exitcode);
 }
 
+#ifndef HOST_WIN32
+static inline MonoBoolean
+mono_icall_close_process (gpointer handle)
+{
+       return CloseProcess (handle);
+}
+#endif /* !HOST_WIN32 */
+
 ICALL_EXPORT MonoBoolean
 ves_icall_Microsoft_Win32_NativeMethods_CloseProcess (gpointer handle)
 {
-#if defined(TARGET_WIN32) || defined(HOST_WIN32)
-       return CloseHandle (handle);
-#else
-       return CloseProcess (handle);
-#endif
+       return mono_icall_close_process (handle);
 }
 
 ICALL_EXPORT MonoBoolean
@@ -8046,27 +8000,46 @@ ves_icall_Microsoft_Win32_NativeMethods_TerminateProcess (gpointer handle, gint3
        return TerminateProcess (handle, exitcode);
 }
 
+#ifndef HOST_WIN32
+static inline gint32
+mono_icall_wait_for_input_idle (gpointer handle, gint32 milliseconds)
+{
+       return WAIT_TIMEOUT;
+}
+#endif /* !HOST_WIN32 */
+
 ICALL_EXPORT gint32
 ves_icall_Microsoft_Win32_NativeMethods_WaitForInputIdle (gpointer handle, gint32 milliseconds)
 {
-#ifdef HOST_WIN32
-       return WaitForInputIdle (handle, milliseconds);
-#else
-       /*TODO: Not implemented*/
-       return WAIT_TIMEOUT;
-#endif
+       return mono_icall_wait_for_input_idle (handle, milliseconds);
 }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+static inline MonoBoolean
+mono_icall_get_process_working_set_size (gpointer handle, gsize *min, gsize *max)
+{
+       return GetProcessWorkingSetSize (handle, min, max);
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
 ICALL_EXPORT MonoBoolean
 ves_icall_Microsoft_Win32_NativeMethods_GetProcessWorkingSetSize (gpointer handle, gsize *min, gsize *max)
 {
-       return GetProcessWorkingSetSize (handle, min, max);
+       return mono_icall_get_process_working_set_size (handle, min, max);
 }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+static inline MonoBoolean
+mono_icall_set_process_working_set_size (gpointer handle, gsize min, gsize max)
+{
+       return SetProcessWorkingSetSize (handle, min, max);
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
 ICALL_EXPORT MonoBoolean
 ves_icall_Microsoft_Win32_NativeMethods_SetProcessWorkingSetSize (gpointer handle, gsize min, gsize max)
 {
-       return SetProcessWorkingSetSize (handle, min, max);
+       return mono_icall_set_process_working_set_size (handle, min, max);
 }
 
 ICALL_EXPORT MonoBoolean
@@ -8081,20 +8054,36 @@ ves_icall_Microsoft_Win32_NativeMethods_GetCurrentProcessId (void)
        return mono_process_current_pid ();
 }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+static inline gint32
+mono_icall_get_priority_class (gpointer handle)
+{
+       return GetPriorityClass (handle);
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
 ICALL_EXPORT gint32
 ves_icall_Microsoft_Win32_NativeMethods_GetPriorityClass (gpointer handle)
 {
-       return GetPriorityClass (handle);
+       return mono_icall_get_priority_class (handle);
 }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+static inline MonoBoolean
+mono_icall_set_priority_class (gpointer handle, gint32 priorityClass)
+{
+       return SetPriorityClass (handle, priorityClass);
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
 ICALL_EXPORT MonoBoolean
 ves_icall_Microsoft_Win32_NativeMethods_SetPriorityClass (gpointer handle, gint32 priorityClass)
 {
-       return SetPriorityClass (handle, priorityClass);
+       return mono_icall_set_priority_class (handle, priorityClass);
 }
 
 ICALL_EXPORT MonoBoolean
-ves_icall_Mono_Btls_Provider_IsSupported (void)
+ves_icall_Mono_TlsProviderFactory_IsBtlsSupported (void)
 {
 #if HAVE_BTLS
        return TRUE;
index 66f7d6b560d084cac2f07ffc20249e62b699c8f9..551f8a751e8e1d58edac3c6186346d64fd46100c 100644 (file)
@@ -141,8 +141,9 @@ mono_locks_lock_released (RuntimeLocks kind, gpointer lock)
        add_record (RECORD_LOCK_RELEASED, kind, lock);
 }
 #else
-       #ifdef _MSC_VER
-               // Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
-               void __mono_win32_lock_tracer_quiet_lnk4221(void) {}
-       #endif
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_lock_tracer_quiet_lnk4221(void) {}
+#endif
 #endif /* LOCK_TRACER */
diff --git a/mono/metadata/marshal-internals.h b/mono/metadata/marshal-internals.h
new file mode 100644 (file)
index 0000000..e19613a
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#ifndef __MONO_METADATA_MARSHAL_INTERNALS_H__
+#define __MONO_METADATA_MARSHAL_INTERNALS_H__
+
+#include <config.h>
+#include <glib.h>
+#include <mono/metadata/object-internals.h>
+
+// On Windows platform implementation of bellow methods are hosted in separate source file
+// masrshal-windows.c or marshal-windows-*.c. On other platforms the implementation is still keept
+// in marshal.c still declared as static and in some places even inlined.
+#ifdef HOST_WIN32
+void*
+mono_marshal_alloc_co_task_mem (size_t size);
+
+void
+mono_marshal_free_co_task_mem (void *ptr);
+
+gpointer
+mono_marshal_realloc_co_task_mem (gpointer ptr, size_t size);
+
+void*
+mono_marshal_alloc_hglobal (size_t size);
+
+gpointer
+mono_marshal_realloc_hglobal (gpointer ptr, size_t size);
+
+void
+mono_marshal_free_hglobal (void *ptr);
+
+gpointer
+mono_string_to_lpstr (MonoString *s);
+#endif  /* HOST_WIN32 */
+
+#endif /* __MONO_METADATA_MARSHAL_INTERNALS_H__ */
diff --git a/mono/metadata/marshal-windows-internals.h b/mono/metadata/marshal-windows-internals.h
new file mode 100644 (file)
index 0000000..d6b3f45
--- /dev/null
@@ -0,0 +1,17 @@
+/*
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#ifndef __MONO_METADATA_MARSHAL_WINDOWS_INTERNALS_H__
+#define __MONO_METADATA_MARSHAL_WINDOWS_INTERNALS_H__
+
+#include <config.h>
+#include <glib.h>
+
+#ifdef HOST_WIN32
+#include "mono/metadata/marshal.h"
+#include "mono/metadata/marshal-internals.h"
+#include "mono/metadata/exception.h"
+#endif /* HOST_WIN32 */
+
+#endif /* __MONO_METADATA_MARSHAL_WINDOWS_INTERNALS_H__ */
diff --git a/mono/metadata/marshal-windows-uwp.c b/mono/metadata/marshal-windows-uwp.c
new file mode 100644 (file)
index 0000000..a2fa813
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * marshal-windows-uwp.c: UWP marshal support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+
+#if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
+#include <Windows.h>
+#include "mono/metadata/marshal-windows-internals.h"
+
+void *
+mono_marshal_alloc_hglobal (size_t size)
+{
+       return HeapAlloc (GetProcessHeap (), 0, size);
+}
+
+gpointer
+mono_marshal_realloc_hglobal (gpointer ptr, size_t size)
+{
+       return HeapReAlloc (GetProcessHeap (), 0, ptr, size);
+}
+
+void
+mono_marshal_free_hglobal (gpointer ptr)
+{
+       HeapFree (GetProcessHeap (), 0, ptr);
+       return;
+}
+
+#else /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_marshal_windows_uwp_quiet_lnk4221(void) {}
+#endif
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
diff --git a/mono/metadata/marshal-windows.c b/mono/metadata/marshal-windows.c
new file mode 100644 (file)
index 0000000..db9d8be
--- /dev/null
@@ -0,0 +1,125 @@
+/*
+ * marshal-windows.c: Windows marshal support.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#include <config.h>
+#include <glib.h>
+
+#if defined(HOST_WIN32)
+#include <WinSock2.h>
+#include <Windows.h>
+#include <objbase.h>
+#include "mono/metadata/marshal-windows-internals.h"
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+void*
+mono_marshal_alloc_hglobal (size_t size)
+{
+       return GlobalAlloc (GMEM_FIXED, size);
+}
+
+gpointer
+mono_marshal_realloc_hglobal (gpointer ptr, size_t size)
+{
+       return GlobalReAlloc (ptr, size, GMEM_MOVEABLE);
+}
+
+void
+mono_marshal_free_hglobal (gpointer ptr)
+{
+       GlobalFree (ptr);
+       return;
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+void*
+mono_marshal_alloc_co_task_mem (size_t size)
+{
+       return CoTaskMemAlloc (size);
+}
+
+void
+mono_marshal_free_co_task_mem (void *ptr)
+{
+       CoTaskMemFree (ptr);
+       return;
+}
+
+gpointer
+mono_marshal_realloc_co_task_mem (gpointer ptr, size_t size)
+{
+       return CoTaskMemRealloc (ptr, size);
+}
+
+gpointer
+ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalAnsi (MonoString *string)
+{
+       MonoError error;
+       char* tres, *ret;
+       size_t len;
+       tres = mono_string_to_utf8_checked (string, &error);
+       if (mono_error_set_pending_exception (&error))
+               return NULL;
+       if (!tres)
+               return tres;
+
+       /*
+        * mono_string_to_utf8_checked() returns a memory area at least as large as the size of the
+        * MonoString, even if it contains NULL characters. The copy we allocate here has to be equally
+        * large.
+        */
+       len = MAX (strlen (tres) + 1, string->length);
+       ret = ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal ((gpointer)len);
+       memcpy (ret, tres, len);
+       g_free (tres);
+       return ret;
+}
+
+gpointer
+ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalUni (MonoString *string)
+{
+       if (string == NULL)
+               return NULL;
+       else {
+               size_t len = ((mono_string_length (string) + 1) * 2);
+               gunichar2 *res = ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal ((gpointer)len);
+
+               memcpy (res, mono_string_chars (string), mono_string_length (string) * 2);
+               res [mono_string_length (string)] = 0;
+               return res;
+       }
+}
+
+gpointer
+mono_string_to_lpstr (MonoString *s)
+{
+       char *as, *tmp;
+       glong len;
+       GError *error = NULL;
+
+       if (s == NULL)
+               return NULL;
+
+       if (!s->length) {
+               as = CoTaskMemAlloc (1);
+               as [0] = '\0';
+               return as;
+       }
+
+       tmp = g_utf16_to_utf8 (mono_string_chars (s), s->length, NULL, &len, &error);
+       if (error) {
+               MonoException *exc = mono_get_exception_argument ("string", error->message);
+               g_error_free (error);
+               mono_set_pending_exception (exc);
+               return NULL;
+       } else {
+               as = CoTaskMemAlloc (len + 1);
+               memcpy (as, tmp, len + 1);
+               g_free (tmp);
+               return as;
+       }
+}
+
+#endif /* HOST_WIN32 */
index f5cfadbb8faf929ec49a9295ab0f955476660643..a725148ad78c8b9aef410fb93b77ee9bca0e011c 100644 (file)
@@ -20,6 +20,7 @@
 #include "loader.h"
 #include "cil-coff.h"
 #include "metadata/marshal.h"
+#include "metadata/marshal-internals.h"
 #include "metadata/method-builder.h"
 #include "metadata/tabledefs.h"
 #include "metadata/exception.h"
 #include <string.h>
 #include <errno.h>
 
-#if defined(HOST_WIN32)
-#include <objbase.h>
-#endif
-
 /* #define DEBUG_RUNTIME_CODE */
 
 #define OPDEF(a,b,c,d,e,f,g,h,i,j) \
@@ -110,8 +107,10 @@ mono_marshal_string_to_utf16 (MonoString *s);
 static void *
 mono_marshal_string_to_utf16_copy (MonoString *s);
 
+#ifndef HOST_WIN32
 static gpointer
 mono_string_to_lpstr (MonoString *string_obj);
+#endif
 
 static MonoStringBuilder *
 mono_string_utf8_to_builder2 (char *text);
@@ -1080,42 +1079,16 @@ mono_string_builder_to_utf16 (MonoStringBuilder *sb)
 }
 
 /* This is a JIT icall, it sets the pending exception and returns NULL on error. */
+#ifndef HOST_WIN32
 static gpointer
 mono_string_to_lpstr (MonoString *s)
 {
-#ifdef TARGET_WIN32
-       char *as, *tmp;
-       glong len;
-       GError *error = NULL;
-
-       if (s == NULL)
-               return NULL;
-
-       if (!s->length) {
-               as = CoTaskMemAlloc (1);
-               as [0] = '\0';
-               return as;
-       }
-
-       tmp = g_utf16_to_utf8 (mono_string_chars (s), s->length, NULL, &len, &error);
-       if (error) {
-               MonoException *exc = mono_get_exception_argument ("string", error->message);
-               g_error_free (error);
-               mono_set_pending_exception (exc);
-               return NULL;
-       } else {
-               as = CoTaskMemAlloc (len + 1);
-               memcpy (as, tmp, len + 1);
-               g_free (tmp);
-               return as;
-       }
-#else
        MonoError error;
        char *result = mono_string_to_utf8_checked (s, &error);
        mono_error_set_pending_exception (&error);
        return result;
-#endif
-}      
+}
+#endif /* HOST_WIN32 */
 
 gpointer
 mono_string_to_ansibstr (MonoString *string_obj)
@@ -9369,7 +9342,8 @@ mono_marshal_get_synchronized_wrapper (MonoMethod *method)
 #endif
 
        if (method->klass->valuetype && !(method->flags & MONO_METHOD_ATTR_STATIC)) {
-               mono_class_set_failure (method->klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+               /* FIXME Is this really the best way to signal an error here?  Isn't this called much later after class setup? -AK */
+               mono_class_set_type_load_failure (method->klass, "");
 #ifndef DISABLE_JIT
                /* This will throw the type load exception when the wrapper is compiled */
                mono_mb_emit_byte (mb, CEE_LDNULL);
@@ -10523,6 +10497,18 @@ mono_marshal_get_array_accessor_wrapper (MonoMethod *method)
        return res;     
 }
 
+#ifndef HOST_WIN32
+static inline void*
+mono_marshal_alloc_co_task_mem (size_t size)
+{
+       if ((gulong)size == 0)
+               /* This returns a valid pointer for size 0 on MS.NET */
+               size = 4;
+
+       return g_try_malloc ((gulong)size);
+}
+#endif
+
 void*
 mono_marshal_alloc (gulong size, MonoError *error)
 {
@@ -10530,13 +10516,10 @@ mono_marshal_alloc (gulong size, MonoError *error)
 
        mono_error_init (error);
 
-#ifdef HOST_WIN32
-       res = CoTaskMemAlloc (size);
-#else
-       res = g_try_malloc ((gulong)size);
+       res = mono_marshal_alloc_co_task_mem (size);
        if (!res)
                mono_error_set_out_of_memory (error, "Could not allocate %lu bytes", size);
-#endif
+
        return res;
 }
 
@@ -10554,14 +10537,19 @@ ves_icall_marshal_alloc (gulong size)
        return ret;
 }
 
-void
-mono_marshal_free (gpointer ptr)
+#ifndef HOST_WIN32
+static inline void
+mono_marshal_free_co_task_mem (void *ptr)
 {
-#ifdef HOST_WIN32
-       CoTaskMemFree (ptr);
-#else
        g_free (ptr);
+       return;
+}
 #endif
+
+void
+mono_marshal_free (gpointer ptr)
+{
+       mono_marshal_free_co_task_mem (ptr);
 }
 
 void
@@ -10960,35 +10948,14 @@ ves_icall_System_Runtime_InteropServices_Marshal_OffsetOf (MonoReflectionType *t
        return info->fields [match_index].offset;
 }
 
+#ifndef HOST_WIN32
 gpointer
 ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalAnsi (MonoString *string)
 {
        MonoError error;
-#ifdef HOST_WIN32
-       char* tres, *ret;
-       size_t len;
-       tres = mono_string_to_utf8_checked (string, &error);
-       if (mono_error_set_pending_exception (&error))
-               return NULL;
-       if (!tres)
-               return tres;
-
-       /*
-        * mono_string_to_utf8_checked() returns a memory area at least as large as the size of the
-        * MonoString, even if it contains NULL characters. The copy we allocate here has to be equally
-        * large.
-        */
-       len = MAX (strlen (tres) + 1, string->length);
-       ret = ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (len);
-       memcpy (ret, tres, len);
-       g_free (tres);
-       return ret;
-
-#else
        char *ret = mono_string_to_utf8_checked (string, &error);
        mono_error_set_pending_exception (&error);
        return ret;
-#endif
 }
 
 gpointer
@@ -10997,17 +10964,14 @@ ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalUni (MonoString
        if (string == NULL)
                return NULL;
        else {
-#ifdef TARGET_WIN32
-               gunichar2 *res = ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal 
-                       ((mono_string_length (string) + 1) * 2);
-#else
                gunichar2 *res = (gunichar2 *)g_malloc ((mono_string_length (string) + 1) * 2);
-#endif
+
                memcpy (res, mono_string_chars (string), mono_string_length (string) * 2);
                res [mono_string_length (string)] = 0;
                return res;
        }
 }
+#endif /* !HOST_WIN32 */
 
 static void
 mono_struct_delete_old (MonoClass *klass, char *ptr)
@@ -11076,6 +11040,14 @@ ves_icall_System_Runtime_InteropServices_Marshal_DestroyStructure (gpointer src,
        mono_struct_delete_old (klass, (char *)src);
 }
 
+#ifndef HOST_WIN32
+static inline void *
+mono_marshal_alloc_hglobal (size_t size)
+{
+       return g_try_malloc (size);
+}
+#endif
+
 void*
 ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (gpointer size)
 {
@@ -11086,11 +11058,8 @@ ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (gpointer size)
                /* This returns a valid pointer for size 0 on MS.NET */
                s = 4;
 
-#ifdef HOST_WIN32
-       res = GlobalAlloc (GMEM_FIXED, s);
-#else
-       res = g_try_malloc (s);
-#endif
+       res = mono_marshal_alloc_hglobal (s);
+
        if (!res) {
                mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
                return NULL;
@@ -11099,6 +11068,14 @@ ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (gpointer size)
        return res;
 }
 
+#ifndef HOST_WIN32
+static inline gpointer
+mono_marshal_realloc_hglobal (gpointer ptr, size_t size)
+{
+       return g_try_realloc (ptr, size);
+}
+#endif
+
 gpointer
 ves_icall_System_Runtime_InteropServices_Marshal_ReAllocHGlobal (gpointer ptr, gpointer size)
 {
@@ -11110,11 +11087,8 @@ ves_icall_System_Runtime_InteropServices_Marshal_ReAllocHGlobal (gpointer ptr, g
                return NULL;
        }
 
-#ifdef HOST_WIN32
-       res = GlobalReAlloc (ptr, s, GMEM_MOVEABLE);
-#else
-       res = g_try_realloc (ptr, s);
-#endif
+       res = mono_marshal_realloc_hglobal (ptr, s);
+
        if (!res) {
                mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
                return NULL;
@@ -11123,30 +11097,26 @@ ves_icall_System_Runtime_InteropServices_Marshal_ReAllocHGlobal (gpointer ptr, g
        return res;
 }
 
-void
-ves_icall_System_Runtime_InteropServices_Marshal_FreeHGlobal (void *ptr)
+#ifndef HOST_WIN32
+static inline void
+mono_marshal_free_hglobal (gpointer ptr)
 {
-#ifdef HOST_WIN32
-       GlobalFree (ptr);
-#else
        g_free (ptr);
+       return;
+}
 #endif
+
+void
+ves_icall_System_Runtime_InteropServices_Marshal_FreeHGlobal (void *ptr)
+{
+       mono_marshal_free_hglobal (ptr);
 }
 
 void*
 ves_icall_System_Runtime_InteropServices_Marshal_AllocCoTaskMem (int size)
 {
-       void *res;
+       void *res = mono_marshal_alloc_co_task_mem (size);
 
-#ifdef HOST_WIN32
-       res = CoTaskMemAlloc (size);
-#else
-       if ((gulong)size == 0)
-               /* This returns a valid pointer for size 0 on MS.NET */
-               size = 4;
-
-       res = g_try_malloc ((gulong)size);
-#endif
        if (!res) {
                mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
                return NULL;
@@ -11157,23 +11127,23 @@ ves_icall_System_Runtime_InteropServices_Marshal_AllocCoTaskMem (int size)
 void
 ves_icall_System_Runtime_InteropServices_Marshal_FreeCoTaskMem (void *ptr)
 {
-#ifdef HOST_WIN32
-       CoTaskMemFree (ptr);
-#else
-       g_free (ptr);
-#endif
+       mono_marshal_free_co_task_mem (ptr);
+       return;
 }
 
+#ifndef HOST_WIN32
+static inline gpointer
+mono_marshal_realloc_co_task_mem (gpointer ptr, size_t size)
+{
+       return g_try_realloc (ptr, (gulong)size);
+}
+#endif
+
 gpointer
 ves_icall_System_Runtime_InteropServices_Marshal_ReAllocCoTaskMem (gpointer ptr, int size)
 {
-       void *res;
+       void *res = mono_marshal_realloc_co_task_mem (ptr, size);
 
-#ifdef HOST_WIN32
-       res = CoTaskMemRealloc (ptr, size);
-#else
-       res = g_try_realloc (ptr, (gulong)size);
-#endif
        if (!res) {
                mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
                return NULL;
@@ -11332,6 +11302,9 @@ mono_marshal_load_type_info (MonoClass* klass)
                j++;
        }
 
+       if (klass->byval_arg.type == MONO_TYPE_PTR)
+               info->native_size = sizeof (gpointer);
+
        if (layout != TYPE_ATTRIBUTE_AUTO_LAYOUT) {
                info->native_size = MAX (native_size, info->native_size);
                /*
index 2706ec6662b974ff39c98f87a82625cbea23c1f5..7a871f034bfd58b28de0092507c84d2cc6c41b37 100644 (file)
@@ -198,25 +198,27 @@ static mono_mutex_t mempool_tracing_lock;
 static void
 mono_backtrace (int size)
 {
-        void *array[BACKTRACE_DEPTH];
-        char **names;
-        int i, symbols;
-        static gboolean inited;
-
-        if (!inited) {
-            mono_os_mutex_init_recursive (&mempool_tracing_lock);
-            inited = TRUE;
-        }
-
-        mono_os_mutex_lock (&mempool_tracing_lock);
-        g_print ("Allocating %d bytes\n", size);
-        symbols = backtrace (array, BACKTRACE_DEPTH);
-        names = backtrace_symbols (array, symbols);
-        for (i = 1; i < symbols; ++i) {
-                g_print ("\t%s\n", names [i]);
-        }
-        g_free (names);
-        mono_os_mutex_unlock (&mempool_tracing_lock);
+       void *array[BACKTRACE_DEPTH];
+       char **names;
+       int i, symbols;
+       static gboolean inited;
+
+       if (!inited) {
+               mono_os_mutex_init_recursive (&mempool_tracing_lock);
+               inited = TRUE;
+       }
+
+       mono_os_mutex_lock (&mempool_tracing_lock);
+       g_print ("Allocating %d bytes\n", size);
+       MONO_ENTER_GC_SAFE;
+       symbols = backtrace (array, BACKTRACE_DEPTH);
+       names = backtrace_symbols (array, symbols);
+       MONO_EXIT_GC_SAFE;
+       for (i = 1; i < symbols; ++i) {
+               g_print ("\t%s\n", names [i]);
+       }
+       g_free (names);
+       mono_os_mutex_unlock (&mempool_tracing_lock);
 }
 
 #endif
index ece67d1286cd4fef23ca0b3389e7af6b58171f82..2e61a1b3373548162adf8a0291ebc00c3411fe4a 100644 (file)
@@ -41,3 +41,13 @@ mono_config_get_bin_dir (void)
 #endif
 }
 
+const char*
+mono_config_get_reloc_lib_dir (void)
+{
+#ifdef MONO_RELOC_LIBDIR
+       return MONO_RELOC_LIBDIR;
+#else
+       return NULL;
+#endif
+}
+
index 9488511bde4b719d7f0ba0a1f779915250eb5812..25e765122539c04384aad6f75ade2ee5efb39637 100644 (file)
@@ -13,4 +13,7 @@ mono_config_get_cfg_dir (void);
 const char*
 mono_config_get_bin_dir (void);
 
+const char*
+mono_config_get_reloc_lib_dir (void);
+
 #endif
index 2bedf12cd8fa713149e7ee88a43ad09cd2912988..cfe15393594f0ab94ec70b8f9479f1f4837d3aca 100644 (file)
@@ -314,13 +314,14 @@ dllmap_start (gpointer user_data,
                        else if (strcmp (attribute_names [i], "target") == 0){
                                char *p = strstr (attribute_values [i], "$mono_libdir");
                                if (p != NULL){
-                                       const char *libdir = mono_assembly_getrootdir ();
+                                       const char *libdir = mono_native_getrootdir ();
                                        size_t libdir_len = strlen (libdir);
                                        char *result;
                                        
                                        result = (char *)g_malloc (libdir_len-strlen("$mono_libdir")+strlen(attribute_values[i])+1);
                                        strncpy (result, attribute_values[i], p-attribute_values[i]);
                                        strcpy (result+(p-attribute_values[i]), libdir);
+                                       g_free (libdir);
                                        strcat (result, p+strlen("$mono_libdir"));
                                        info->target = result;
                                } else 
diff --git a/mono/metadata/mono-security-windows-internals.h b/mono/metadata/mono-security-windows-internals.h
new file mode 100644 (file)
index 0000000..a7cc247
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#ifndef __MONO_METADATA_MONO_SECURITY_WINDOWS_INTERNALS_H__
+#define __MONO_METADATA_MONO_SECURITY_WINDOWS_INTERNALS_H__
+
+#include <config.h>
+#include <glib.h>
+
+#ifdef HOST_WIN32
+#include "mono/metadata/security.h"
+#include "mono/metadata/object.h"
+#include "mono/metadata/object-internals.h"
+#include "mono/metadata/metadata.h"
+#include "mono/metadata/metadata-internals.h"
+
+gint32
+mono_security_win_get_token_name (gpointer token, gunichar2 ** uniname);
+
+gboolean
+mono_security_win_is_machine_protected (gunichar2 *path);
+
+gboolean
+mono_security_win_is_user_protected (gunichar2 *path);
+
+gboolean
+mono_security_win_protect_machine (gunichar2 *path);
+
+gboolean
+mono_security_win_protect_user (gunichar2 *path);
+#endif /* HOST_WIN32 */
+
+#endif /* __MONO_METADATA_MONO_SECURITY_WINDOWS_INTERNALS_H__ */
diff --git a/mono/metadata/mono-security-windows-uwp.c b/mono/metadata/mono-security-windows-uwp.c
new file mode 100644 (file)
index 0000000..791e76c
--- /dev/null
@@ -0,0 +1,179 @@
+/*
+ * mono-security-windows-uwp.c: UWP security support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+
+#if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
+#include <Windows.h>
+#include "mono/metadata/mono-security-windows-internals.h"
+
+gpointer
+ves_icall_System_Security_Principal_WindowsIdentity_GetCurrentToken (void)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("OpenThreadToken, OpenProcessToken");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "OpenThreadToken, OpenProcessToken");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return NULL;
+}
+
+MonoArray*
+ves_icall_System_Security_Principal_WindowsIdentity_GetRoles (gpointer token)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("GetTokenInformation");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "GetTokenInformation");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return NULL;
+}
+
+gpointer
+ves_icall_System_Security_Principal_WindowsImpersonationContext_DuplicateToken (gpointer token)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("DuplicateToken");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "DuplicateToken");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return NULL;
+}
+
+gboolean
+ves_icall_System_Security_Principal_WindowsImpersonationContext_SetCurrentToken (gpointer token)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("ImpersonateLoggedOnUser");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "ImpersonateLoggedOnUser");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+gboolean
+ves_icall_System_Security_Principal_WindowsImpersonationContext_RevertToSelf (void)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("RevertToSelf");
+
+       mono_error_set_not_supported(&mono_error, G_UNSUPPORTED_API, "RevertToSelf");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+gint32
+mono_security_win_get_token_name (gpointer token, gunichar2 ** uniname)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("GetTokenInformation");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "GetTokenInformation");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return 0;
+}
+
+gboolean
+mono_security_win_is_machine_protected (gunichar2 *path)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("GetNamedSecurityInfo, LocalFree");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "GetNamedSecurityInfo, LocalFree");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+gboolean
+mono_security_win_is_user_protected (gunichar2 *path)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("GetNamedSecurityInfo, LocalFree");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "GetNamedSecurityInfo, LocalFree");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+gboolean
+mono_security_win_protect_machine (gunichar2 *path)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("BuildTrusteeWithSid, SetEntriesInAcl, SetNamedSecurityInfo, LocalFree, FreeSid");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "BuildTrusteeWithSid, SetEntriesInAcl, SetNamedSecurityInfo, LocalFree, FreeSid");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+gboolean
+mono_security_win_protect_user (gunichar2 *path)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("BuildTrusteeWithSid, SetEntriesInAcl, SetNamedSecurityInfo, LocalFree");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "BuildTrusteeWithSid, SetEntriesInAcl, SetNamedSecurityInfo, LocalFree");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+#else /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_mono_security_windows_uwp_quiet_lnk4221(void) {}
+#endif
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
diff --git a/mono/metadata/mono-security-windows.c b/mono/metadata/mono-security-windows.c
new file mode 100644 (file)
index 0000000..fda26d3
--- /dev/null
@@ -0,0 +1,495 @@
+/*
+ * mono-security-windows.c: Windows security support.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#include <config.h>
+#include <glib.h>
+
+#if defined(HOST_WIN32)
+#include <WinSock2.h>
+#include <Windows.h>
+#include "mono/metadata/mono-security-windows-internals.h"
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+#include <aclapi.h>
+#include <accctrl.h>
+#endif
+
+#ifndef PROTECTED_DACL_SECURITY_INFORMATION
+#define PROTECTED_DACL_SECURITY_INFORMATION    0x80000000L
+#endif
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+static gunichar2*
+GetSidName (gunichar2 *server, PSID sid, gint32 *size)
+{
+       gunichar2 *uniname = NULL;
+       DWORD cchName = 0;
+       DWORD cchDomain = 0;
+       SID_NAME_USE peUse; /* out */
+
+       LookupAccountSid (server, sid, NULL, &cchName, NULL,
+               &cchDomain, &peUse);
+
+       if ((cchName > 0) && (cchDomain > 0)) {
+               gunichar2 *user = g_malloc0 ((cchName + 1) * 2);
+               gunichar2 *domain = g_malloc0 ((cchDomain + 1) * 2);
+
+               LookupAccountSid (server, sid, user, &cchName, domain,
+                       &cchDomain, &peUse);
+
+               if (cchName > 0) {
+                       if (cchDomain > 0) {
+                               /* domain/machine name included (+ sepearator) */
+                               *size = cchName + cchDomain + 1;
+                               uniname = g_malloc0 ((*size + 1) * 2);
+                               memcpy (uniname, domain, cchDomain * 2);
+                               *(uniname + cchDomain) = '\\';
+                               memcpy (uniname + cchDomain + 1, user, cchName * 2);
+                               g_free (user);
+                       }
+                       else {
+                               /* no domain / machine */
+                               *size = cchName;
+                               uniname = user;
+                       }
+               }
+               else {
+                       /* nothing -> return NULL */
+                       g_free (user);
+               }
+
+               g_free (domain);
+       }
+
+       return uniname;
+}
+
+gpointer
+ves_icall_System_Security_Principal_WindowsIdentity_GetCurrentToken (void)
+{
+       gpointer token = NULL;
+
+       /* Note: This isn't a copy of the Token - we must not close it!!!
+        * http://www.develop.com/kbrown/book/html/whatis_windowsprincipal.html
+        */
+
+       /* thread may be impersonating somebody */
+       if (OpenThreadToken (GetCurrentThread (), MAXIMUM_ALLOWED, 1, &token) == 0) {
+               /* if not take the process identity */
+               OpenProcessToken (GetCurrentProcess (), MAXIMUM_ALLOWED, &token);
+       }
+
+       return token;
+}
+
+gint32
+mono_security_win_get_token_name (gpointer token, gunichar2 ** uniname)
+{
+       gint32 size = 0;
+
+       GetTokenInformation (token, TokenUser, NULL, size, (PDWORD)&size);
+       if (size > 0) {
+               TOKEN_USER *tu = g_malloc0 (size);
+               if (GetTokenInformation (token, TokenUser, tu, size, (PDWORD)&size)) {
+                       *uniname = GetSidName (NULL, tu->User.Sid, &size);
+               }
+               g_free (tu);
+       }
+
+       return size;
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+MonoString*
+ves_icall_System_Security_Principal_WindowsIdentity_GetTokenName (gpointer token)
+{
+       MonoError error;
+       MonoString *result = NULL;
+       gunichar2 *uniname = NULL;
+       gint32 size = 0;
+
+       mono_error_init (&error);
+
+       size = mono_security_win_get_token_name (token, &uniname);
+
+       if (size > 0) {
+               result = mono_string_new_utf16_checked (mono_domain_get (), uniname, size, &error);
+       }
+       else
+               result = mono_string_new (mono_domain_get (), "");
+
+       if (uniname)
+               g_free (uniname);
+
+       mono_error_set_pending_exception (&error);
+       return result;
+}
+
+gpointer
+ves_icall_System_Security_Principal_WindowsIdentity_GetUserToken (MonoString *username)
+{
+       gpointer token = NULL;
+
+       /* TODO: MS has something like this working in Windows 2003 (client and
+        * server) but works only for domain accounts (so it's quite limiting).
+        * http://www.develop.com/kbrown/book/html/howto_logonuser.html
+        */
+       g_warning ("Unsupported on Win32 (anyway requires W2K3 minimum)");
+       return token;
+}
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+MonoArray*
+ves_icall_System_Security_Principal_WindowsIdentity_GetRoles (gpointer token)
+{
+       MonoError error;
+       MonoArray *array = NULL;
+       MonoDomain *domain = mono_domain_get ();
+
+       gint32 size = 0;
+
+       GetTokenInformation (token, TokenGroups, NULL, size, (PDWORD)&size);
+       if (size > 0) {
+               TOKEN_GROUPS *tg = g_malloc0 (size);
+               if (GetTokenInformation (token, TokenGroups, tg, size, (PDWORD)&size)) {
+                       int i=0;
+                       int num = tg->GroupCount;
+
+                       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;
+                               gunichar2 *uniname = GetSidName (NULL, tg->Groups [i].Sid, &size);
+
+                               if (uniname) {
+                                       MonoString *str = mono_string_new_utf16_checked (domain, uniname, size, &error);
+                                       if (!is_ok (&error)) {
+                                               g_free (uniname);
+                                               g_free (tg);
+                                               mono_error_set_pending_exception (&error);
+                                               return NULL;
+                                       }
+                                       mono_array_setref (array, i, str);
+                                       g_free (uniname);
+                               }
+                       }
+               }
+               g_free (tg);
+       }
+
+       if (!array) {
+               /* return empty array of string, i.e. string [0] */
+               array = mono_array_new_checked (domain, mono_get_string_class (), 0, &error);
+               mono_error_set_pending_exception (&error);
+       }
+       return array;
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+gboolean
+ves_icall_System_Security_Principal_WindowsImpersonationContext_CloseToken (gpointer token)
+{
+       gboolean result = TRUE;
+       result = (CloseHandle (token) != 0);
+       return result;
+}
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+gpointer
+ves_icall_System_Security_Principal_WindowsImpersonationContext_DuplicateToken (gpointer token)
+{
+       gpointer dupe = NULL;
+
+       if (DuplicateToken (token, SecurityImpersonation, &dupe) == 0) {
+               dupe = NULL;
+       }
+       return dupe;
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+gboolean
+ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupId (gpointer user, gpointer group)
+{
+       gboolean result = FALSE;
+
+       /* The convertion from an ID to a string is done in managed code for Windows */
+       g_warning ("IsMemberOfGroupId should never be called on Win32");
+       return result;
+}
+
+gboolean
+ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupName (gpointer user, MonoString *group)
+{
+       gboolean result = FALSE;
+
+       /* Windows version use a cache built using WindowsIdentity._GetRoles */
+       g_warning ("IsMemberOfGroupName should never be called on Win32");
+       return result;
+}
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+static PSID
+GetAdministratorsSid (void)
+{
+       SID_IDENTIFIER_AUTHORITY admins = { SECURITY_NT_AUTHORITY };
+       PSID pSid = NULL;
+       if (!AllocateAndInitializeSid (&admins, 2, SECURITY_BUILTIN_DOMAIN_RID,
+               DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &pSid))
+               return NULL;
+       /* Note: this SID must be freed with FreeSid () */
+       return pSid;
+}
+
+static PSID
+GetEveryoneSid (void)
+{
+       SID_IDENTIFIER_AUTHORITY everyone = { SECURITY_WORLD_SID_AUTHORITY };
+       PSID pSid = NULL;
+       if (!AllocateAndInitializeSid (&everyone, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &pSid))
+               return NULL;
+       /* Note: this SID must be freed with FreeSid () */
+       return pSid;
+}
+
+static PSID
+GetCurrentUserSid (void)
+{
+       PSID sid = NULL;
+       guint32 size = 0;
+       gpointer token = ves_icall_System_Security_Principal_WindowsIdentity_GetCurrentToken ();
+
+       GetTokenInformation (token, TokenUser, NULL, size, (PDWORD)&size);
+       if (size > 0) {
+               TOKEN_USER *tu = g_malloc0 (size);
+               if (GetTokenInformation (token, TokenUser, tu, size, (PDWORD)&size)) {
+                       DWORD length = GetLengthSid (tu->User.Sid);
+                       sid = (PSID) g_malloc0 (length);
+                       if (!CopySid (length, sid, tu->User.Sid)) {
+                               g_free (sid);
+                               sid = NULL;
+                       }
+               }
+               g_free (tu);
+       }
+       /* Note: this SID must be freed with g_free () */
+       return sid;
+}
+
+static ACCESS_MASK
+GetRightsFromSid (PSID sid, PACL acl)
+{
+       ACCESS_MASK rights = 0;
+       TRUSTEE trustee;
+
+       BuildTrusteeWithSidW (&trustee, sid);
+       if (GetEffectiveRightsFromAcl (acl, &trustee, &rights) != ERROR_SUCCESS)
+               return 0;
+
+       return rights;
+}
+
+gboolean
+mono_security_win_is_machine_protected (gunichar2 *path)
+{
+       gboolean success = FALSE;
+       PACL pDACL = NULL;
+       PSECURITY_DESCRIPTOR pSD = NULL;
+       PSID pEveryoneSid = NULL;
+
+       DWORD dwRes = GetNamedSecurityInfoW (path, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, &pSD);
+       if (dwRes != ERROR_SUCCESS)
+               return FALSE;
+
+       /* We check that Everyone is still limited to READ-ONLY -
+       but not if new entries have been added by an Administrator */
+
+       pEveryoneSid = GetEveryoneSid ();
+       if (pEveryoneSid) {
+               ACCESS_MASK rights = GetRightsFromSid (pEveryoneSid, pDACL);
+               /* http://msdn.microsoft.com/library/en-us/security/security/generic_access_rights.asp?frame=true */
+               success = (rights == (READ_CONTROL | SYNCHRONIZE | FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES));
+               FreeSid (pEveryoneSid);
+       }
+       /* Note: we don't need to check our own access -
+       we'll know soon enough when reading the file */
+
+       if (pSD)
+               LocalFree (pSD);
+
+       return success;
+}
+
+gboolean
+mono_security_win_is_user_protected (gunichar2 *path)
+{
+       gboolean success = FALSE;
+       PACL pDACL = NULL;
+       PSID pEveryoneSid = NULL;
+       PSECURITY_DESCRIPTOR pSecurityDescriptor = NULL;
+
+       DWORD dwRes = GetNamedSecurityInfoW (path, SE_FILE_OBJECT,
+               DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, &pSecurityDescriptor);
+       if (dwRes != ERROR_SUCCESS)
+               return FALSE;
+
+       /* We check that our original entries in the ACL are in place -
+       but not if new entries have been added by the user */
+
+       /* Everyone should be denied */
+       pEveryoneSid = GetEveryoneSid ();
+       if (pEveryoneSid) {
+               ACCESS_MASK rights = GetRightsFromSid (pEveryoneSid, pDACL);
+               success = (rights == 0);
+               FreeSid (pEveryoneSid);
+       }
+       /* Note: we don't need to check our own access -
+       we'll know soon enough when reading the file */
+
+       if (pSecurityDescriptor)
+               LocalFree (pSecurityDescriptor);
+
+       return success;
+}
+
+gboolean
+mono_security_win_protect_machine (gunichar2 *path)
+{
+       PSID pEveryoneSid = GetEveryoneSid ();
+       PSID pAdminsSid = GetAdministratorsSid ();
+       DWORD retval = -1;
+
+       if (pEveryoneSid && pAdminsSid) {
+               PACL pDACL = NULL;
+               EXPLICIT_ACCESS ea [2];
+               ZeroMemory (&ea, 2 * sizeof (EXPLICIT_ACCESS));
+
+               /* grant all access to the BUILTIN\Administrators group */
+               BuildTrusteeWithSidW (&ea [0].Trustee, pAdminsSid);
+               ea [0].grfAccessPermissions = GENERIC_ALL;
+               ea [0].grfAccessMode = SET_ACCESS;
+               ea [0].grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
+               ea [0].Trustee.TrusteeForm = TRUSTEE_IS_SID;
+               ea [0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
+
+               /* read-only access everyone */
+               BuildTrusteeWithSidW (&ea [1].Trustee, pEveryoneSid);
+               ea [1].grfAccessPermissions = GENERIC_READ;
+               ea [1].grfAccessMode = SET_ACCESS;
+               ea [1].grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
+               ea [1].Trustee.TrusteeForm = TRUSTEE_IS_SID;
+               ea [1].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
+
+               retval = SetEntriesInAcl (2, ea, NULL, &pDACL);
+               if (retval == ERROR_SUCCESS) {
+                       /* with PROTECTED_DACL_SECURITY_INFORMATION we */
+                       /* remove any existing ACL (like inherited ones) */
+                       retval = SetNamedSecurityInfo (path, SE_FILE_OBJECT,
+                               DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
+                               NULL, NULL, pDACL, NULL);
+               }
+               if (pDACL)
+                       LocalFree (pDACL);
+       }
+
+       if (pEveryoneSid)
+               FreeSid (pEveryoneSid);
+       if (pAdminsSid)
+               FreeSid (pAdminsSid);
+       return (retval == ERROR_SUCCESS);
+}
+
+gboolean
+mono_security_win_protect_user (gunichar2 *path)
+{
+       DWORD retval = -1;
+
+       PSID pCurrentSid = GetCurrentUserSid ();
+       if (pCurrentSid) {
+               PACL pDACL = NULL;
+               EXPLICIT_ACCESS ea;
+               ZeroMemory (&ea, sizeof (EXPLICIT_ACCESS));
+
+               /* grant exclusive access to the current user */
+               BuildTrusteeWithSidW (&ea.Trustee, pCurrentSid);
+               ea.grfAccessPermissions = GENERIC_ALL;
+               ea.grfAccessMode = SET_ACCESS;
+               ea.grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
+               ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
+               ea.Trustee.TrusteeType = TRUSTEE_IS_USER;
+
+               retval = SetEntriesInAcl (1, &ea, NULL, &pDACL);
+               if (retval == ERROR_SUCCESS) {
+                       /* with PROTECTED_DACL_SECURITY_INFORMATION we
+                          remove any existing ACL (like inherited ones) */
+                       retval = SetNamedSecurityInfo (path, SE_FILE_OBJECT,
+                               DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
+                               NULL, NULL, pDACL, NULL);
+               }
+
+               if (pDACL)
+                       LocalFree (pDACL);
+               g_free (pCurrentSid); /* g_malloc0 */
+       }
+
+       return (retval == ERROR_SUCCESS);
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+MonoBoolean
+ves_icall_Mono_Security_Cryptography_KeyPairPersistence_CanSecure (MonoString *root)
+{
+       gint32 flags;
+
+       /* ACL are nice... unless you have FAT or other uncivilized filesystem */
+       if (!GetVolumeInformation (mono_string_chars (root), NULL, 0, NULL, NULL, (LPDWORD)&flags, NULL, 0))
+               return FALSE;
+       return ((flags & FS_PERSISTENT_ACLS) == FS_PERSISTENT_ACLS);
+}
+
+MonoBoolean
+ves_icall_Mono_Security_Cryptography_KeyPairPersistence_IsMachineProtected (MonoString *path)
+{
+       gboolean ret = FALSE;
+
+       /* no one, but the owner, should have write access to the directory */
+       ret = mono_security_win_is_machine_protected (mono_string_chars (path));
+       return (MonoBoolean)ret;
+}
+
+MonoBoolean
+ves_icall_Mono_Security_Cryptography_KeyPairPersistence_IsUserProtected (MonoString *path)
+{
+       gboolean ret = FALSE;
+
+       /* no one, but the user, should have access to the directory */
+       ret = mono_security_win_is_user_protected (mono_string_chars (path));
+       return (MonoBoolean)ret;
+}
+
+MonoBoolean
+ves_icall_Mono_Security_Cryptography_KeyPairPersistence_ProtectMachine (MonoString *path)
+{
+       gboolean ret = FALSE;
+
+       /* read/write to owner, read to everyone else */
+       ret = mono_security_win_protect_machine (mono_string_chars (path));
+       return (MonoBoolean)ret;
+}
+
+MonoBoolean
+ves_icall_Mono_Security_Cryptography_KeyPairPersistence_ProtectUser (MonoString *path)
+{
+       gboolean ret = FALSE;
+
+       /* read/write to user, no access to everyone else */
+       ret = mono_security_win_protect_user (mono_string_chars (path));
+       return (MonoBoolean)ret;
+}
+#endif /* HOST_WIN32 */
index 865b9ca1e04236ec1a7c7840436fca8c6e02de8a..09b8cd44abe6deaba2428602aa257022dbf21a88 100644 (file)
 #include <mono/io-layer/io-layer.h>
 #include <mono/utils/strenc.h>
 
-#ifdef HOST_WIN32
-
-#include <aclapi.h>
-#include <accctrl.h>
-
-#ifndef PROTECTED_DACL_SECURITY_INFORMATION
-#define PROTECTED_DACL_SECURITY_INFORMATION    0x80000000L
-#endif
-
-#else
-
+#ifndef HOST_WIN32
 #include <config.h>
 #ifdef HAVE_GRP_H
 #include <grp.h>
 #endif
 
 #endif /* defined(__GNUC__) */
-
-#endif /* not HOST_WIN32 */
-
+#endif /* !HOST_WIN32 */
 
 /* internal functions - reuse driven */
 
-#ifdef HOST_WIN32
-
 /* ask a server to translate a SID into a textual representation */
-static gunichar2*
-GetSidName (gunichar2 *server, PSID sid, gint32 *size) 
-{
-       gunichar2 *uniname = NULL;
-       DWORD cchName = 0;
-       DWORD cchDomain = 0;
-       SID_NAME_USE peUse; /* out */
-
-       LookupAccountSid (server, sid, NULL, &cchName, NULL, 
-               &cchDomain, &peUse); 
-       
-       if ((cchName > 0) && (cchDomain > 0)) {
-               gunichar2 *user = g_malloc0 ((cchName + 1) * 2);
-               gunichar2 *domain = g_malloc0 ((cchDomain + 1) * 2);
-
-               LookupAccountSid (server, sid, user, &cchName, domain,
-                       &cchDomain, &peUse);
-
-               if (cchName > 0) {
-                       if (cchDomain > 0) {
-                               /* domain/machine name included (+ sepearator) */
-                               *size = cchName + cchDomain + 1;
-                               uniname = g_malloc0 ((*size + 1) * 2);
-                               memcpy (uniname, domain, cchDomain * 2);
-                               *(uniname + cchDomain) = '\\';
-                               memcpy (uniname + cchDomain + 1, user, cchName * 2);
-                               g_free (user);
-                       }
-                       else {
-                               /* no domain / machine */
-                               *size = cchName;
-                               uniname = user;
-                       }
-               }
-               else {
-                       /* nothing -> return NULL */
-                       g_free (user);
-               }
-
-               g_free (domain);
-       }
-
-       return uniname;
-}
-
-
-#else /* not HOST_WIN32 */
-
+#ifndef HOST_WIN32
 #define MONO_SYSCONF_DEFAULT_SIZE      ((size_t) 1024)
 
 /*
@@ -133,7 +72,6 @@ static size_t mono_sysconf (int name)
        return (size == -1) ? MONO_SYSCONF_DEFAULT_SIZE : size;
 }
 
-
 static gchar*
 GetTokenName (uid_t uid)
 {
@@ -174,7 +112,6 @@ GetTokenName (uid_t uid)
        return uname;
 }
 
-
 static gboolean
 IsMemberInList (uid_t user, struct group *g) 
 {
@@ -201,7 +138,6 @@ IsMemberInList (uid_t user, struct group *g)
        return result;
 }
 
-
 static gboolean
 IsDefaultGroup (uid_t user, gid_t group)
 {
@@ -241,7 +177,6 @@ IsDefaultGroup (uid_t user, gid_t group)
        return result;
 }
 
-
 static gboolean
 IsMemberOf (gid_t user, struct group *g) 
 {
@@ -255,37 +190,34 @@ IsMemberOf (gid_t user, struct group *g)
        /* is the user in the group list */
        return IsMemberInList (user, g);
 }
-
-#endif
-
+#endif /* !HOST_WIN32 */
 
 /* ICALLS */
 
-
 /* System.Security.Principal.WindowsIdentity */
 
-
+#ifndef HOST_WIN32
 gpointer
 ves_icall_System_Security_Principal_WindowsIdentity_GetCurrentToken (void)
 {
-       gpointer token = NULL;
+       return GINT_TO_POINTER (geteuid ());
+}
+
+static gint32
+internal_get_token_name (gpointer token, gunichar2 ** uniname)
+{
+       gint32 size = 0;
 
-#ifdef HOST_WIN32
-       /* Note: This isn't a copy of the Token - we must not close it!!!
-        * http://www.develop.com/kbrown/book/html/whatis_windowsprincipal.html
-        */
+       gchar *uname = GetTokenName ((uid_t) GPOINTER_TO_INT (token));
 
-       /* thread may be impersonating somebody */
-       if (OpenThreadToken (GetCurrentThread (), MAXIMUM_ALLOWED, 1, &token) == 0) {
-               /* if not take the process identity */
-               OpenProcessToken (GetCurrentProcess (), MAXIMUM_ALLOWED, &token);
+       if (uname) {
+               size = strlen (uname);
+               *uniname = g_utf8_to_utf16 (uname, size, NULL, NULL, NULL);
+               g_free (uname);
        }
-#else
-       token = GINT_TO_POINTER (geteuid ());
-#endif
-       return token;
-}
 
+       return size;
+}
 
 MonoString*
 ves_icall_System_Security_Principal_WindowsIdentity_GetTokenName (gpointer token)
@@ -296,24 +228,8 @@ ves_icall_System_Security_Principal_WindowsIdentity_GetTokenName (gpointer token
        gint32 size = 0;
 
        mono_error_init (&error);
-#ifdef HOST_WIN32
-       GetTokenInformation (token, TokenUser, NULL, size, (PDWORD)&size);
-       if (size > 0) {
-               TOKEN_USER *tu = g_malloc0 (size);
-               if (GetTokenInformation (token, TokenUser, tu, size, (PDWORD)&size)) {
-                       uniname = GetSidName (NULL, tu->User.Sid, &size);
-               }
-               g_free (tu);
-       }
-#else 
-       gchar *uname = GetTokenName ((uid_t) GPOINTER_TO_INT (token));
 
-       if (uname) {
-               size = strlen (uname);
-               uniname = g_utf8_to_utf16 (uname, size, NULL, NULL, NULL);
-               g_free (uname);
-       }
-#endif /* HOST_WIN32 */
+       size = internal_get_token_name (token, &uniname);
 
        if (size > 0) {
                result = mono_string_new_utf16_checked (mono_domain_get (), uniname, size, &error);
@@ -327,22 +243,12 @@ ves_icall_System_Security_Principal_WindowsIdentity_GetTokenName (gpointer token
        mono_error_set_pending_exception (&error);
        return result;
 }
+#endif  /* !HOST_WIN32 */
 
-
+#ifndef HOST_WIN32
 gpointer
 ves_icall_System_Security_Principal_WindowsIdentity_GetUserToken (MonoString *username)
 {
-#ifdef HOST_WIN32
-       gpointer token = NULL;
-
-       /* TODO: MS has something like this working in Windows 2003 (client and
-        * server) but works only for domain accounts (so it's quite limiting).
-        * http://www.develop.com/kbrown/book/html/howto_logonuser.html
-        */
-       g_warning ("Unsupported on Win32 (anyway requires W2K3 minimum)");
-
-#else /* HOST_WIN32*/
-
 #ifdef HAVE_GETPWNAM_R
        struct passwd pwd;
        size_t fbufsize;
@@ -380,59 +286,26 @@ ves_icall_System_Security_Principal_WindowsIdentity_GetUserToken (MonoString *us
        g_free (fbuf);
 #endif
        g_free (utf8_name);
-#endif
+
        return token;
 }
-
+#endif /* HOST_WIN32 */
 
 /* http://www.dotnet247.com/247reference/msgs/39/195403.aspx
 // internal static string[] WindowsIdentity._GetRoles (IntPtr token)
 */
+
+#ifndef HOST_WIN32
 MonoArray*
-ves_icall_System_Security_Principal_WindowsIdentity_GetRoles (gpointer token) 
+ves_icall_System_Security_Principal_WindowsIdentity_GetRoles (gpointer token)
 {
        MonoError error;
        MonoArray *array = NULL;
-       MonoDomain *domain = mono_domain_get (); 
-#ifdef HOST_WIN32
-       gint32 size = 0;
-
-       GetTokenInformation (token, TokenGroups, NULL, size, (PDWORD)&size);
-       if (size > 0) {
-               TOKEN_GROUPS *tg = g_malloc0 (size);
-               if (GetTokenInformation (token, TokenGroups, tg, size, (PDWORD)&size)) {
-                       int i=0;
-                       int num = tg->GroupCount;
-
-                       array = mono_array_new_checked (domain, mono_get_string_class (), num, &error);
-                       if (mono_error_set_pending_exception (&error)) {
-                               g_free (tg);
-                               return NULL;
-                       }
+       MonoDomain *domain = mono_domain_get ();
 
-                       for (i=0; i < num; i++) {
-                               gint32 size = 0;
-                               gunichar2 *uniname = GetSidName (NULL, tg->Groups [i].Sid, &size);
-
-                               if (uniname) {
-                                       MonoString *str = mono_string_new_utf16_checked (domain, uniname, size, &error);
-                                       if (!is_ok (&error)) {
-                                               g_free (uniname);
-                                               g_free (tg);
-                                               mono_error_set_pending_exception (&error);
-                                               return NULL;
-                                       }
-                                       mono_array_setref (array, i, str);
-                                       g_free (uniname);
-                               }
-                       }
-               }
-               g_free (tg);
-       }
-#else
        /* POSIX-compliant systems should use IsMemberOfGroupId or IsMemberOfGroupName */
        g_warning ("WindowsIdentity._GetRoles should never be called on POSIX");
-#endif
+
        if (!array) {
                /* return empty array of string, i.e. string [0] */
                array = mono_array_new_checked (domain, mono_get_string_class (), 0, &error);
@@ -440,39 +313,27 @@ ves_icall_System_Security_Principal_WindowsIdentity_GetRoles (gpointer token)
        }
        return array;
 }
-
+#endif /* !HOST_WIN32 */
 
 /* System.Security.Principal.WindowsImpersonationContext */
 
-
+#ifndef HOST_WIN32
 gboolean
 ves_icall_System_Security_Principal_WindowsImpersonationContext_CloseToken (gpointer token)
 {
-       gboolean result = TRUE;
-
-#ifdef HOST_WIN32
-       result = (CloseHandle (token) != 0);
-#endif
-       return result;
+       return TRUE;
 }
+#endif /* !HOST_WIN32 */
 
-
+#ifndef HOST_WIN32
 gpointer
 ves_icall_System_Security_Principal_WindowsImpersonationContext_DuplicateToken (gpointer token)
 {
-       gpointer dupe = NULL;
-
-#ifdef HOST_WIN32
-       if (DuplicateToken (token, SecurityImpersonation, &dupe) == 0) {
-               dupe = NULL;
-       }
-#else
-       dupe = token;
-#endif
-       return dupe;
+       return token;
 }
+#endif /* !HOST_WIN32 */
 
-
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 gboolean
 ves_icall_System_Security_Principal_WindowsImpersonationContext_SetCurrentToken (gpointer token)
 {
@@ -480,28 +341,22 @@ ves_icall_System_Security_Principal_WindowsImpersonationContext_SetCurrentToken
        return (ImpersonateLoggedOnUser (token) != 0);
 }
 
-
 gboolean
 ves_icall_System_Security_Principal_WindowsImpersonationContext_RevertToSelf (void)
 {
        /* Posix version implemented in /mono/mono/io-layer/security.c */
        return (RevertToSelf () != 0);
 }
-
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
 
 /* System.Security.Principal.WindowsPrincipal */
 
+#ifndef HOST_WIN32
 gboolean
 ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupId (gpointer user, gpointer group)
 {
        gboolean result = FALSE;
 
-#ifdef HOST_WIN32
-       /* The convertion from an ID to a string is done in managed code for Windows */
-       g_warning ("IsMemberOfGroupId should never be called on Win32");
-
-#else /* HOST_WIN32 */
-
 #ifdef HAVE_GETGRGID_R
        struct group grp;
        size_t fbufsize;
@@ -533,22 +388,13 @@ ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupId (gpointer
        g_free (fbuf);
 #endif
 
-#endif /* HOST_WIN32 */
-
        return result;
 }
 
-
 gboolean
 ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupName (gpointer user, MonoString *group)
 {
        gboolean result = FALSE;
-
-#ifdef HOST_WIN32
-       /* Windows version use a cache built using WindowsIdentity._GetRoles */
-       g_warning ("IsMemberOfGroupName should never be called on Win32");
-
-#else /* HOST_WIN32 */
        gchar *utf8_groupname;
 
        utf8_groupname = mono_unicode_to_external (mono_string_chars (group));
@@ -581,232 +427,15 @@ ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupName (gpoint
 #endif
                g_free (utf8_groupname);
        }
-#endif /* HOST_WIN32 */
 
        return result;
 }
-
+#endif /* !HOST_WIN32 */
 
 /* Mono.Security.Cryptography IO related internal calls */
 
-#ifdef HOST_WIN32
-
-static PSID
-GetAdministratorsSid (void) 
-{
-       SID_IDENTIFIER_AUTHORITY admins = SECURITY_NT_AUTHORITY;
-       PSID pSid = NULL;
-       if (!AllocateAndInitializeSid (&admins, 2, SECURITY_BUILTIN_DOMAIN_RID, 
-               DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &pSid)) 
-               return NULL;
-       /* Note: this SID must be freed with FreeSid () */
-       return pSid;
-}
-
-
-static PSID
-GetEveryoneSid (void)
-{
-       SID_IDENTIFIER_AUTHORITY everyone = SECURITY_WORLD_SID_AUTHORITY;
-       PSID pSid = NULL;
-       if (!AllocateAndInitializeSid (&everyone, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &pSid))
-               return NULL;
-       /* Note: this SID must be freed with FreeSid () */
-       return pSid;
-}
-
-
-static PSID
-GetCurrentUserSid (void) 
-{
-       PSID sid = NULL;
-       guint32 size = 0;
-       gpointer token = ves_icall_System_Security_Principal_WindowsIdentity_GetCurrentToken ();
-
-       GetTokenInformation (token, TokenUser, NULL, size, (PDWORD)&size);
-       if (size > 0) {
-               TOKEN_USER *tu = g_malloc0 (size);
-               if (GetTokenInformation (token, TokenUser, tu, size, (PDWORD)&size)) {
-                       DWORD length = GetLengthSid (tu->User.Sid);
-                       sid = (PSID) g_malloc0 (length);
-                       if (!CopySid (length, sid, tu->User.Sid)) {
-                               g_free (sid);
-                               sid = NULL;
-                       }
-               }
-               g_free (tu);
-       }
-       /* Note: this SID must be freed with g_free () */
-       return sid;
-}
-
-
-static ACCESS_MASK
-GetRightsFromSid (PSID sid, PACL acl) 
-{
-       ACCESS_MASK rights = 0;
-       TRUSTEE trustee;
-
-       BuildTrusteeWithSidW (&trustee, sid);
-       if (GetEffectiveRightsFromAcl (acl, &trustee, &rights) != ERROR_SUCCESS)
-               return 0;
-
-       return rights;
-}
-
-
-static gboolean 
-IsMachineProtected (gunichar2 *path)
-{
-       gboolean success = FALSE;
-       PACL pDACL = NULL;
-       PSECURITY_DESCRIPTOR pSD = NULL;
-       PSID pEveryoneSid = NULL;
-
-       DWORD dwRes = GetNamedSecurityInfoW (path, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, &pSD);
-       if (dwRes != ERROR_SUCCESS)
-               return FALSE;
-
-       /* We check that Everyone is still limited to READ-ONLY -
-       but not if new entries have been added by an Administrator */
-
-       pEveryoneSid = GetEveryoneSid ();
-       if (pEveryoneSid) {
-               ACCESS_MASK rights = GetRightsFromSid (pEveryoneSid, pDACL);
-               /* http://msdn.microsoft.com/library/en-us/security/security/generic_access_rights.asp?frame=true */
-               success = (rights == (READ_CONTROL | SYNCHRONIZE | FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES));
-               FreeSid (pEveryoneSid);
-       }
-       /* Note: we don't need to check our own access - 
-       we'll know soon enough when reading the file */
-
-       if (pSD)
-               LocalFree (pSD);
-
-       return success;
-}
-
-
-static gboolean 
-IsUserProtected (gunichar2 *path)
-{
-       gboolean success = FALSE;
-       PACL pDACL = NULL;
-       PSID pEveryoneSid = NULL;
-       PSECURITY_DESCRIPTOR pSecurityDescriptor = NULL;
-
-       DWORD dwRes = GetNamedSecurityInfoW (path, SE_FILE_OBJECT, 
-               DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, &pSecurityDescriptor);
-       if (dwRes != ERROR_SUCCESS)
-               return FALSE;
-
-       /* We check that our original entries in the ACL are in place -
-       but not if new entries have been added by the user */
-
-       /* Everyone should be denied */
-       pEveryoneSid = GetEveryoneSid ();
-       if (pEveryoneSid) {
-               ACCESS_MASK rights = GetRightsFromSid (pEveryoneSid, pDACL);
-               success = (rights == 0);
-               FreeSid (pEveryoneSid);
-       }
-       /* Note: we don't need to check our own access - 
-       we'll know soon enough when reading the file */
-
-       if (pSecurityDescriptor)
-               LocalFree (pSecurityDescriptor);
-
-       return success;
-}
-
-
-static gboolean 
-ProtectMachine (gunichar2 *path)
-{
-       PSID pEveryoneSid = GetEveryoneSid ();
-       PSID pAdminsSid = GetAdministratorsSid ();
-       DWORD retval = -1;
-
-       if (pEveryoneSid && pAdminsSid) {
-               PACL pDACL = NULL;
-               EXPLICIT_ACCESS ea [2];
-               ZeroMemory (&ea, 2 * sizeof (EXPLICIT_ACCESS));
-
-               /* grant all access to the BUILTIN\Administrators group */
-               BuildTrusteeWithSidW (&ea [0].Trustee, pAdminsSid);
-               ea [0].grfAccessPermissions = GENERIC_ALL;
-               ea [0].grfAccessMode = SET_ACCESS;
-               ea [0].grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
-               ea [0].Trustee.TrusteeForm = TRUSTEE_IS_SID;
-               ea [0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
-
-               /* read-only access everyone */
-               BuildTrusteeWithSidW (&ea [1].Trustee, pEveryoneSid);
-               ea [1].grfAccessPermissions = GENERIC_READ;
-               ea [1].grfAccessMode = SET_ACCESS;
-               ea [1].grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
-               ea [1].Trustee.TrusteeForm = TRUSTEE_IS_SID;
-               ea [1].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
-
-               retval = SetEntriesInAcl (2, ea, NULL, &pDACL);
-               if (retval == ERROR_SUCCESS) {
-                       /* with PROTECTED_DACL_SECURITY_INFORMATION we */
-                       /* remove any existing ACL (like inherited ones) */
-                       retval = SetNamedSecurityInfo (path, SE_FILE_OBJECT, 
-                               DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
-                               NULL, NULL, pDACL, NULL);
-               }
-               if (pDACL)
-                       LocalFree (pDACL);
-       }
-
-       if (pEveryoneSid)
-               FreeSid (pEveryoneSid);
-       if (pAdminsSid)
-               FreeSid (pAdminsSid);
-       return (retval == ERROR_SUCCESS);
-}
-
-
-static gboolean 
-ProtectUser (gunichar2 *path)
-{
-       DWORD retval = -1;
-
-       PSID pCurrentSid = GetCurrentUserSid ();
-       if (pCurrentSid) {
-               PACL pDACL = NULL;
-               EXPLICIT_ACCESS ea;
-               ZeroMemory (&ea, sizeof (EXPLICIT_ACCESS));
-
-               /* grant exclusive access to the current user */
-               BuildTrusteeWithSidW (&ea.Trustee, pCurrentSid);
-               ea.grfAccessPermissions = GENERIC_ALL;
-               ea.grfAccessMode = SET_ACCESS;
-               ea.grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
-               ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
-               ea.Trustee.TrusteeType = TRUSTEE_IS_USER;
-
-               retval = SetEntriesInAcl (1, &ea, NULL, &pDACL);
-               if (retval == ERROR_SUCCESS) {
-                       /* with PROTECTED_DACL_SECURITY_INFORMATION we
-                          remove any existing ACL (like inherited ones) */
-                       retval = SetNamedSecurityInfo (path, SE_FILE_OBJECT, 
-                               DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
-                               NULL, NULL, pDACL, NULL);
-               }
-
-               if (pDACL)
-                       LocalFree (pDACL);
-               g_free (pCurrentSid); /* g_malloc0 */
-       }
-
-       return (retval == ERROR_SUCCESS);
-}
-
-#else
-
-static gboolean 
+#ifndef HOST_WIN32
+static gboolean
 IsProtected (MonoString *path, gint32 protection) 
 {
        gboolean result = FALSE;
@@ -822,7 +451,7 @@ IsProtected (MonoString *path, gint32 protection)
 }
 
 
-static gboolean 
+static gboolean
 Protect (MonoString *path, gint32 file_mode, gint32 add_dir_mode)
 {
        gboolean result = FALSE;
@@ -840,85 +469,53 @@ Protect (MonoString *path, gint32 file_mode, gint32 add_dir_mode)
        return result;
 }
 
-#endif /* not HOST_WIN32 */
-
-
 MonoBoolean
 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_CanSecure (MonoString *root)
 {
-#if HOST_WIN32
-       gint32 flags;
-
-       /* ACL are nice... unless you have FAT or other uncivilized filesystem */
-       if (!GetVolumeInformation (mono_string_chars (root), NULL, 0, NULL, NULL, (LPDWORD)&flags, NULL, 0))
-               return FALSE;
-       return ((flags & FS_PERSISTENT_ACLS) == FS_PERSISTENT_ACLS);
-#else
        /* we assume some kind of security is applicable outside Windows */
        return TRUE;
-#endif
 }
 
-
 MonoBoolean
 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_IsMachineProtected (MonoString *path)
 {
        gboolean ret = FALSE;
 
        /* no one, but the owner, should have write access to the directory */
-#ifdef HOST_WIN32
-       ret = IsMachineProtected (mono_string_chars (path));
-#else
        ret = IsProtected (path, (S_IWGRP | S_IWOTH));
-#endif
-       return ret;
+       return (MonoBoolean)ret;
 }
 
-
 MonoBoolean
 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_IsUserProtected (MonoString *path)
 {
        gboolean ret = FALSE;
 
        /* no one, but the user, should have access to the directory */
-#ifdef HOST_WIN32
-       ret = IsUserProtected (mono_string_chars (path));
-#else
        ret = IsProtected (path, (S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH));
-#endif
-       return ret;
+       return (MonoBoolean)ret;
 }
 
-
 MonoBoolean
 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_ProtectMachine (MonoString *path)
 {
        gboolean ret = FALSE;
 
        /* read/write to owner, read to everyone else */
-#ifdef HOST_WIN32
-       ret = ProtectMachine (mono_string_chars (path));
-#else
        ret = Protect (path, (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH), (S_IXUSR | S_IXGRP | S_IXOTH));
-#endif
-       return ret;
+       return (MonoBoolean)ret;
 }
 
-
 MonoBoolean
 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_ProtectUser (MonoString *path)
 {
        gboolean ret = FALSE;
        
        /* read/write to user, no access to everyone else */
-#ifdef HOST_WIN32
-       ret = ProtectUser (mono_string_chars (path));
-#else
        ret = Protect (path, (S_IRUSR | S_IWUSR), S_IXUSR);
-#endif
-       return ret;
+       return (MonoBoolean)ret;
 }
-
+#endif /* !HOST_WIN32 */
 
 /*
  * Returns TRUE if there is "something" where the Authenticode signature is 
@@ -930,7 +527,7 @@ MonoBoolean
 ves_icall_System_Security_Policy_Evidence_IsAuthenticodePresent (MonoReflectionAssembly *refass)
 {
        if (refass && refass->assembly && refass->assembly->image) {
-               return mono_image_has_authenticode_entry (refass->assembly->image);
+               return (MonoBoolean)mono_image_has_authenticode_entry (refass->assembly->image);
        }
        return FALSE;
 }
index aa8bc0259bb91a23d08f559f83d96b51d352aabf..b3224372ddef5b678b1d512be8e23fa527bbdf8e 100644 (file)
@@ -461,6 +461,16 @@ mono_gc_get_logfile (void)
        return NULL;
 }
 
+void
+mono_gc_params_set (const char* options)
+{
+}
+
+void
+mono_gc_debug_set (const char* options)
+{
+}
+
 void
 mono_gc_conservatively_scan_area (void *start, void *end)
 {
@@ -546,8 +556,9 @@ mono_gc_is_null (void)
        return TRUE;
 }
 #else
-       #ifdef _MSC_VER
-               // Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
-               void __mono_win32_null_gc_quiet_lnk4221(void) {}
-       #endif
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_null_gc_quiet_lnk4221(void) {}
+#endif
 #endif /* HAVE_NULL_GC */
index 3ab92326b1b388bfdf002a7bc1074694047887c4..61c9d61f7e586ba19550a965b89147833c85db05 100644 (file)
@@ -1890,7 +1890,7 @@ mono_class_create_runtime_vtable (MonoDomain *domain, MonoClass *klass, MonoErro
                if (mono_class_has_failure (element_class)) {
                        /*Can happen if element_class only got bad after mono_class_setup_vtable*/
                        if (!mono_class_has_failure (klass))
-                               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+                               mono_class_set_type_load_failure (klass, "");
                        mono_domain_unlock (domain);
                        mono_loader_unlock ();
                        mono_error_set_for_class_failure (error, klass);
diff --git a/mono/metadata/process-internals.h b/mono/metadata/process-internals.h
new file mode 100644 (file)
index 0000000..cfc34e8
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#ifndef __MONO_METADATA_PROCESS_INTERNALS_H__
+#define __MONO_METADATA_PROCESS_INTERNALS_H__
+
+#include <config.h>
+#include <glib.h>
+
+// On Windows platform implementation of bellow methods are hosted in separate source file
+// process-windows.c or process-windows-*.c. On other platforms the implementation is still keept
+// in process.c still declared as static and in some places even inlined.
+#ifdef HOST_WIN32
+gchar*
+mono_process_quote_path (const gchar *path);
+
+gchar*
+mono_process_unquote_application_name (gchar *path);
+
+gboolean
+mono_process_get_shell_arguments (MonoProcessStartInfo *proc_start_info, gunichar2 **shell_path,
+                                 MonoString **cmd);
+#endif  /* HOST_WIN32 */
+
+// On platforms not using classic WIN API support the  implementation of bellow methods are hosted in separate source file
+// process-windows-*.c. On platforms using classic WIN API the implementation is still keept in process.c and still declared
+// static and in some places even inlined.
+#if !G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+void
+process_get_fileversion (MonoObject *filever, gunichar2 *filename, MonoError *error);
+
+void
+mono_process_init_startup_info (HANDLE stdin_handle, HANDLE stdout_handle,
+                               HANDLE stderr_handle,STARTUPINFO *startinfo);
+
+gboolean
+mono_process_create_process (MonoProcInfo *mono_process_info, gunichar2 *shell_path, MonoString *cmd,
+                            guint32 creation_flags, gchar *env_vars, gunichar2 *dir, STARTUPINFO *start_info,
+                            PROCESS_INFORMATION *process_info);
+#endif  /* !G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+// Shared between all platforms and implemented in process.c.
+gboolean
+mono_process_complete_path (const gunichar2 *appname, gchar **completed);
+
+#endif /* __MONO_METADATA_PROCESS_INTERNALS_H__ */
diff --git a/mono/metadata/process-windows-internals.h b/mono/metadata/process-windows-internals.h
new file mode 100644 (file)
index 0000000..68721fa
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#ifndef __MONO_METADATA_PROCESS_WINDOWS_INTERNALS_H__
+#define __MONO_METADATA_PROCESS_WINDOWS_INTERNALS_H__
+
+#include <config.h>
+#include <glib.h>
+
+#ifdef HOST_WIN32
+#include "mono/metadata/process.h"
+#include "mono/metadata/process-internals.h"
+#include "mono/metadata/object.h"
+#include "mono/metadata/object-internals.h"
+#include "mono/metadata/exception.h"
+
+// On platforms not using classic WIN API support the  implementation of bellow methods are hosted in separate source file
+// process-windows-*.c. On platforms using classic WIN API the implementation is still keept in process.c and still declared
+// static and in some places even inlined.
+#if !G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+gboolean
+mono_process_win_enum_processes (DWORD *pids, DWORD count, DWORD *needed);
+#endif  /* !G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+#endif /* HOST_WIN32 */
+
+#endif /* __MONO_METADATA_PROCESS_WINDOWS_INTERNALS_H__ */
diff --git a/mono/metadata/process-windows-uwp.c b/mono/metadata/process-windows-uwp.c
new file mode 100644 (file)
index 0000000..905555f
--- /dev/null
@@ -0,0 +1,157 @@
+/*
+ * process-windows-uwp.c: UWP process support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+
+#if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
+#include <Windows.h>
+#include "mono/metadata/process-windows-internals.h"
+
+gboolean
+mono_process_win_enum_processes (DWORD *pids, DWORD count, DWORD *needed)
+{
+       g_unsupported_api ("EnumProcesses");
+       *needed = 0;
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+HANDLE
+ves_icall_System_Diagnostics_Process_GetProcess_internal (guint32 pid)
+{
+       HANDLE handle;
+
+       /* GetCurrentProcess returns a pseudo-handle, so use
+        * OpenProcess instead
+        */
+       handle = OpenProcess (PROCESS_ALL_ACCESS, TRUE, pid);
+       if (handle == NULL)
+               /* FIXME: Throw an exception */
+               return NULL;
+       return handle;
+}
+
+void
+process_get_fileversion (MonoObject *filever, gunichar2 *filename, MonoError *error)
+{
+       g_unsupported_api ("GetFileVersionInfoSize, GetFileVersionInfo, VerQueryValue, VerLanguageName");
+
+       mono_error_init (error);
+       mono_error_set_not_supported (error, G_UNSUPPORTED_API, "GetFileVersionInfoSize, GetFileVersionInfo, VerQueryValue, VerLanguageName");
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+}
+
+MonoObject*
+process_add_module (HANDLE process, HMODULE mod, gunichar2 *filename, gunichar2 *modulename, MonoClass *proc_class, MonoError *error)
+{
+       g_unsupported_api ("GetModuleInformation");
+
+       mono_error_init (error);
+       mono_error_set_not_supported (error, G_UNSUPPORTED_API, "GetModuleInformation");
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return NULL;
+}
+
+MonoArray *
+ves_icall_System_Diagnostics_Process_GetModules_internal (MonoObject *this_obj, HANDLE process)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("EnumProcessModules, GetModuleBaseName, GetModuleFileNameEx");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "EnumProcessModules, GetModuleBaseName, GetModuleFileNameEx");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return NULL;
+}
+
+MonoBoolean
+ves_icall_System_Diagnostics_Process_ShellExecuteEx_internal (MonoProcessStartInfo *proc_start_info, MonoProcInfo *process_info)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("ShellExecuteEx");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "ShellExecuteEx");
+       mono_error_set_pending_exception (&mono_error);
+
+       process_info->pid = (guint32)(-ERROR_NOT_SUPPORTED);
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+MonoString *
+ves_icall_System_Diagnostics_Process_ProcessName_internal (HANDLE process)
+{
+       MonoError error;
+       MonoString *string;
+       gunichar2 name[MAX_PATH];
+       guint32 len;
+
+       len = GetModuleFileName (NULL, name, G_N_ELEMENTS (name));
+       if (len == 0)
+               return NULL;
+
+       string = mono_string_new_utf16_checked (mono_domain_get (), name, len, &error);
+       if (!mono_error_ok (&error))
+               mono_error_set_pending_exception (&error);
+
+       return string;
+}
+
+void
+mono_process_init_startup_info (HANDLE stdin_handle, HANDLE stdout_handle, HANDLE stderr_handle, STARTUPINFO *startinfo)
+{
+       startinfo->cb = sizeof(STARTUPINFO);
+       startinfo->dwFlags = 0;
+       startinfo->hStdInput = INVALID_HANDLE_VALUE;
+       startinfo->hStdOutput = INVALID_HANDLE_VALUE;
+       startinfo->hStdError = INVALID_HANDLE_VALUE;
+       return;
+}
+
+gboolean
+mono_process_create_process (MonoProcInfo *mono_process_info, gunichar2 *shell_path, MonoString *cmd, guint32 creation_flags,
+                            gchar *env_vars, gunichar2 *dir, STARTUPINFO *start_info, PROCESS_INFORMATION *process_info)
+{
+       MonoError       mono_error;
+       gchar           *api_name = "";
+
+       if (mono_process_info->username) {
+               api_name = "CreateProcessWithLogonW";
+       } else {
+               api_name = "CreateProcess";
+       }
+
+       memset (&process_info, 0, sizeof (PROCESS_INFORMATION));
+       g_unsupported_api (api_name);
+
+       mono_error_init (&mono_error);
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, api_name);
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+#else /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_process_windows_uwp_quiet_lnk4221(void) {}
+#endif
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
diff --git a/mono/metadata/process-windows.c b/mono/metadata/process-windows.c
new file mode 100644 (file)
index 0000000..847612d
--- /dev/null
@@ -0,0 +1,129 @@
+/*
+ * process-windows.c: Windows process support.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+
+#include <config.h>
+#include <glib.h>
+
+#if defined(HOST_WIN32)
+#include <WinSock2.h>
+#include <Windows.h>
+#include "mono/metadata/process-windows-internals.h"
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+static inline gboolean
+mono_process_win_enum_processes (DWORD *pids, DWORD count, DWORD *needed)
+{
+       return EnumProcesses (pids, count, needed);
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+MonoArray *
+ves_icall_System_Diagnostics_Process_GetProcesses_internal (void)
+{
+       MonoError error;
+       MonoArray *procs;
+       gboolean ret;
+       DWORD needed;
+       int count;
+       DWORD *pids;
+
+       count = 512;
+       do {
+               pids = g_new0 (DWORD, count);
+               ret = mono_process_win_enum_processes (pids, count * sizeof (guint32), &needed);
+               if (ret == FALSE) {
+                       MonoException *exc;
+
+                       g_free (pids);
+                       pids = NULL;
+                       exc = mono_get_exception_not_supported ("This system does not support EnumProcesses");
+                       mono_set_pending_exception (exc);
+                       return NULL;
+               }
+               if (needed < (count * sizeof (guint32)))
+                       break;
+               g_free (pids);
+               pids = NULL;
+               count = (count * 3) / 2;
+       } while (TRUE);
+
+       count = needed / sizeof (guint32);
+       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;
+
+       return procs;
+}
+
+gchar*
+mono_process_quote_path (const gchar *path)
+{
+       gchar *res = g_shell_quote (path);
+       gchar *q = res;
+       while (*q) {
+               if (*q == '\'')
+                       *q = '\"';
+               q++;
+       }
+       return res;
+}
+
+gchar*
+mono_process_unquote_application_name (gchar *appname)
+{
+       size_t len = strlen (appname);
+       if (len) {
+               if (appname[len-1] == '\"')
+                       appname[len-1] = '\0';
+               if (appname[0] == '\"')
+                       appname++;
+       }
+
+       return appname;
+}
+
+gboolean
+mono_process_get_shell_arguments (MonoProcessStartInfo *proc_start_info, gunichar2 **shell_path, MonoString **cmd)
+{
+       gchar           *spath = NULL;
+       gchar           *new_cmd, *cmd_utf8;
+       MonoError       mono_error;
+
+       *shell_path = NULL;
+       *cmd = proc_start_info->arguments;
+
+       mono_process_complete_path (mono_string_chars (proc_start_info->filename), &spath);
+       if (spath != NULL) {
+               /* Seems like our CreateProcess does not work as the windows one.
+                * This hack is needed to deal with paths containing spaces */
+               if (*cmd) {
+                       cmd_utf8 = mono_string_to_utf8_checked (*cmd, &mono_error);
+                       if (!mono_error_set_pending_exception (&mono_error)) {
+                               new_cmd = g_strdup_printf ("%s %s", spath, cmd_utf8);
+                               *cmd = mono_string_new_wrapper (new_cmd);
+                               g_free (cmd_utf8);
+                               g_free (new_cmd);
+                       } else {
+                               *cmd = NULL;
+                       }
+               }
+               else {
+                       *cmd = mono_string_new_wrapper (spath);
+               }
+
+               g_free (spath);
+       }
+
+       return (*cmd != NULL) ? TRUE : FALSE;
+}
+#endif /* HOST_WIN32 */
index 96814db8480518f5f35f83caea8c66f18a9ec520..b1bff0b5ecad403e85d7f82ada5d42f06d08b8c5 100644 (file)
@@ -16,6 +16,7 @@
 
 #include <mono/metadata/object-internals.h>
 #include <mono/metadata/process.h>
+#include <mono/metadata/process-internals.h>
 #include <mono/metadata/assembly.h>
 #include <mono/metadata/appdomain.h>
 #include <mono/metadata/image.h>
 #define LOGDEBUG(...)  
 /* define LOGDEBUG(...) g_message(__VA_ARGS__)  */
 
-#ifdef _WIN32
+#if defined(HOST_WIN32) && G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 #include <shellapi.h>
 #endif
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 HANDLE
 ves_icall_System_Diagnostics_Process_GetProcess_internal (guint32 pid)
 {
@@ -50,6 +52,7 @@ ves_icall_System_Diagnostics_Process_GetProcess_internal (guint32 pid)
                return NULL;
        return handle;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT | HAVE_UWP_WINAPI_SUPPORT) */
 
 static MonoImage *system_assembly;
 
@@ -196,11 +199,11 @@ process_set_field_bool (MonoObject *obj, const gchar *fieldname,
 #define SFI_SPECIALBUILD       "\\StringFileInfo\\%02X%02X%02X%02X\\SpecialBuild"
 #define EMPTY_STRING           (gunichar2*)"\000\000"
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 static void
 process_module_string_read (MonoObject *filever, gpointer data,
-                                                       const gchar *fieldname,
-                                                       guchar lang_hi, guchar lang_lo,
-                                                       const gchar *key, MonoError *error)
+                           const gchar *fieldname, guchar lang_hi, guchar lang_lo,
+                           const gchar *key, MonoError *error)
 {
        gchar *lang_key_utf8;
        gunichar2 *lang_key, *buffer;
@@ -367,6 +370,7 @@ process_get_fileversion (MonoObject *filever, gunichar2 *filename, MonoError *er
                g_free (data);
        }
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
 
 static void
 process_get_assembly_fileversion (MonoObject *filever, MonoAssembly *assembly)
@@ -409,6 +413,7 @@ get_process_module (MonoAssembly *assembly, MonoClass *proc_class, MonoError *er
        return item;
 }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 static MonoObject*
 process_add_module (HANDLE process, HMODULE mod, gunichar2 *filename, gunichar2 *modulename, MonoClass *proc_class, MonoError *error)
 {
@@ -451,6 +456,7 @@ process_add_module (HANDLE process, HMODULE mod, gunichar2 *filename, gunichar2
 
        return item;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
 
 static GPtrArray*
 get_domain_assemblies (MonoDomain *domain)
@@ -476,6 +482,7 @@ get_domain_assemblies (MonoDomain *domain)
 }
 
 /* Returns an array of System.Diagnostics.ProcessModule */
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 MonoArray *
 ves_icall_System_Diagnostics_Process_GetModules_internal (MonoObject *this_obj, HANDLE process)
 {
@@ -546,6 +553,7 @@ ves_icall_System_Diagnostics_Process_GetModules_internal (MonoObject *this_obj,
 
        return arr;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
 
 void
 ves_icall_System_Diagnostics_FileVersionInfo_GetVersionInfo_internal (MonoObject *this_obj, MonoString *filename)
@@ -569,53 +577,38 @@ ves_icall_System_Diagnostics_FileVersionInfo_GetVersionInfo_internal (MonoObject
 }
 
 /* Only used when UseShellExecute is false */
-static gchar *
-quote_path (const gchar *path)
+#ifndef HOST_WIN32
+static inline gchar *
+mono_process_quote_path (const gchar *path)
 {
-       gchar *res = g_shell_quote (path);
-#ifdef TARGET_WIN32
-       {
-       gchar *q = res;
-       while (*q) {
-               if (*q == '\'')
-                       *q = '\"';
-               q++;
-       }
-       }
-#endif
-       return res;
+       return g_shell_quote (path);
 }
 
+static inline gchar *
+mono_process_unquote_application_name (gchar *path)
+{
+       return path;
+}
+#endif /* !HOST_WIN32 */
+
 /* Only used when UseShellExecute is false */
-static gboolean
-complete_path (const gunichar2 *appname, gchar **completed)
+gboolean
+mono_process_complete_path (const gunichar2 *appname, gchar **completed)
 {
        gchar *utf8app, *utf8appmemory;
        gchar *found;
 
-       utf8appmemory = utf8app = g_utf16_to_utf8 (appname, -1, NULL, NULL, NULL);
-#ifdef TARGET_WIN32 // Should this happen on all platforms? 
-       {
-               // remove the quotes around utf8app.
-               size_t len;
-               len = strlen (utf8app);
-               if (len) {
-                       if (utf8app[len-1] == '\"')
-                               utf8app[len-1] = '\0';
-                       if (utf8app[0] == '\"')
-                               utf8app++;
-               }
-       }
-#endif
+       utf8appmemory = g_utf16_to_utf8 (appname, -1, NULL, NULL, NULL);
+       utf8app = mono_process_unquote_application_name (utf8appmemory);
 
        if (g_path_is_absolute (utf8app)) {
-               *completed = quote_path (utf8app);
+               *completed = mono_process_quote_path (utf8app);
                g_free (utf8appmemory);
                return TRUE;
        }
 
        if (g_file_test (utf8app, G_FILE_TEST_IS_EXECUTABLE) && !g_file_test (utf8app, G_FILE_TEST_IS_DIR)) {
-               *completed = quote_path (utf8app);
+               *completed = mono_process_quote_path (utf8app);
                g_free (utf8appmemory);
                return TRUE;
        }
@@ -627,12 +620,13 @@ complete_path (const gunichar2 *appname, gchar **completed)
                return FALSE;
        }
 
-       *completed = quote_path (found);
+       *completed = mono_process_quote_path (found);
        g_free (found);
        g_free (utf8appmemory);
        return TRUE;
 }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 MonoBoolean
 ves_icall_System_Diagnostics_Process_ShellExecuteEx_internal (MonoProcessStartInfo *proc_start_info, MonoProcInfo *process_info)
 {
@@ -684,62 +678,102 @@ ves_icall_System_Diagnostics_Process_ShellExecuteEx_internal (MonoProcessStartIn
 
        return ret;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+static inline void
+mono_process_init_startup_info (HANDLE stdin_handle, HANDLE stdout_handle, HANDLE stderr_handle, STARTUPINFO *startinfo)
+{
+       startinfo->cb = sizeof(STARTUPINFO);
+       startinfo->dwFlags = STARTF_USESTDHANDLES;
+       startinfo->hStdInput = stdin_handle;
+       startinfo->hStdOutput = stdout_handle;
+       startinfo->hStdError = stderr_handle;
+       return;
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+#ifndef HOST_WIN32
+static gboolean
+mono_process_get_shell_arguments (MonoProcessStartInfo *proc_start_info, gunichar2 **shell_path, MonoString **cmd)
+{
+       gchar *spath = NULL;
+
+       *shell_path = NULL;
+       *cmd = proc_start_info->arguments;
+
+       mono_process_complete_path (mono_string_chars (proc_start_info->filename), &spath);
+       if (spath != NULL) {
+               *shell_path = g_utf8_to_utf16 (spath, -1, NULL, NULL, NULL);
+               g_free (spath);
+       }
+
+       return (*shell_path != NULL) ? TRUE : FALSE;
+}
+#endif /* !HOST_WIN32 */
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+static gboolean
+mono_process_create_process (MonoProcInfo *mono_process_info, gunichar2 *shell_path,
+                            MonoString *cmd, guint32 creation_flags, gchar *env_vars,
+                            gunichar2 *dir, STARTUPINFO *start_info, PROCESS_INFORMATION *process_info)
+{
+       gboolean result = FALSE;
+
+       if (mono_process_info->username) {
+               guint32 logon_flags = mono_process_info->load_user_profile ? LOGON_WITH_PROFILE : 0;
+
+               result = CreateProcessWithLogonW (mono_string_chars (mono_process_info->username),
+                                                 mono_process_info->domain ? mono_string_chars (mono_process_info->domain) : NULL,
+                                                 (const gunichar2 *)mono_process_info->password,
+                                                 logon_flags,
+                                                 shell_path,
+                                                 cmd ? mono_string_chars (cmd) : NULL,
+                                                 creation_flags,
+                                                 env_vars, dir, start_info, process_info);
+
+       } else {
+
+               result = CreateProcess (shell_path,
+                                       cmd ? mono_string_chars (cmd): NULL,
+                                       NULL,
+                                       NULL,
+                                       TRUE,
+                                       creation_flags,
+                                       env_vars,
+                                       dir,
+                                       start_info,
+                                       process_info);
+
+       }
+
+       return result;
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
 
 MonoBoolean
-ves_icall_System_Diagnostics_Process_CreateProcess_internal (MonoProcessStartInfo *proc_start_info, HANDLE stdin_handle, HANDLE stdout_handle, HANDLE stderr_handle, MonoProcInfo *process_info)
+ves_icall_System_Diagnostics_Process_CreateProcess_internal (MonoProcessStartInfo *proc_start_info, HANDLE stdin_handle,
+                                                            HANDLE stdout_handle, HANDLE stderr_handle, MonoProcInfo *process_info)
 {
-       MonoError error G_GNUC_UNUSED;
        gboolean ret;
        gunichar2 *dir;
        STARTUPINFO startinfo={0};
        PROCESS_INFORMATION procinfo;
        gunichar2 *shell_path = NULL;
        gchar *env_vars = NULL;
-       gboolean free_shell_path = TRUE;
-       gchar *spath = NULL;
-       MonoString *cmd = proc_start_info->arguments;
-       guint32 creation_flags, logon_flags;
-       
-       startinfo.cb = sizeof(STARTUPINFO);
-       startinfo.dwFlags = STARTF_USESTDHANDLES;
-       startinfo.hStdInput = stdin_handle;
-       startinfo.hStdOutput = stdout_handle;
-       startinfo.hStdError = stderr_handle;
+       MonoString *cmd = NULL;
+       guint32 creation_flags;
+
+       mono_process_init_startup_info (stdin_handle, stdout_handle, stderr_handle, &startinfo);
 
        creation_flags = CREATE_UNICODE_ENVIRONMENT;
        if (proc_start_info->create_no_window)
                creation_flags |= CREATE_NO_WINDOW;
        
-       shell_path = mono_string_chars (proc_start_info->filename);
-       complete_path (shell_path, &spath);
-       if (spath == NULL) {
+       if (mono_process_get_shell_arguments (proc_start_info, &shell_path, &cmd) == FALSE) {
                process_info->pid = -ERROR_FILE_NOT_FOUND;
                return FALSE;
        }
-#ifdef TARGET_WIN32
-       /* Seems like our CreateProcess does not work as the windows one.
-        * This hack is needed to deal with paths containing spaces */
-       shell_path = NULL;
-       free_shell_path = FALSE;
-       if (cmd) {
-               gchar *newcmd, *tmp;
-               tmp = mono_string_to_utf8_checked (cmd, &error);
-               if (mono_error_set_pending_exception (&error)) {
-                       g_free (spath);
-                       return NULL;
-               }
-               newcmd = g_strdup_printf ("%s %s", spath, tmp);
-               cmd = mono_string_new_wrapper (newcmd);
-               g_free (tmp);
-               g_free (newcmd);
-       }
-       else {
-               cmd = mono_string_new_wrapper (spath);
-       }
-#else
-       shell_path = g_utf8_to_utf16 (spath, -1, NULL, NULL, NULL);
-#endif
-       g_free (spath);
 
        if (process_info->env_keys) {
                gint i, len; 
@@ -790,20 +824,10 @@ ves_icall_System_Diagnostics_Process_CreateProcess_internal (MonoProcessStartInf
        else
                dir = mono_string_chars (proc_start_info->working_directory);
 
-       if (process_info->username) {
-               logon_flags = process_info->load_user_profile ? LOGON_WITH_PROFILE : 0;
-               ret = CreateProcessWithLogonW (
-                       mono_string_chars (process_info->username),
-                       process_info->domain ? mono_string_chars (process_info->domain) : NULL,
-                       (const gunichar2 *)process_info->password, logon_flags, shell_path,
-                       cmd ? mono_string_chars (cmd) : NULL,
-                       creation_flags, env_vars, dir, &startinfo, &procinfo);
-       } else {
-               ret = CreateProcess (shell_path, cmd ? mono_string_chars (cmd): NULL, NULL, NULL, TRUE, creation_flags, env_vars, dir, &startinfo, &procinfo);
-       }
+       ret = mono_process_create_process (process_info, shell_path, cmd, creation_flags, env_vars, dir, &startinfo, &procinfo);
 
        g_free (env_vars);
-       if (free_shell_path)
+       if (shell_path != NULL)
                g_free (shell_path);
 
        if (ret) {
@@ -821,22 +845,24 @@ ves_icall_System_Diagnostics_Process_CreateProcess_internal (MonoProcessStartInf
        return ret;
 }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 MonoString *
 ves_icall_System_Diagnostics_Process_ProcessName_internal (HANDLE process)
 {
        MonoError error;
        MonoString *string;
+       gunichar2 name[MAX_PATH];
+       guint32 len;
        gboolean ok;
        HMODULE mod;
-       gunichar2 name[MAX_PATH];
        DWORD needed;
-       guint32 len;
-       
+
        ok = EnumProcessModules (process, &mod, sizeof(mod), &needed);
        if (!ok)
                return NULL;
        
        len = GetModuleBaseName (process, mod, name, MAX_PATH);
+
        if (len == 0)
                return NULL;
        
@@ -848,12 +874,13 @@ ves_icall_System_Diagnostics_Process_ProcessName_internal (HANDLE process)
        
        return string;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
 
+#ifndef HOST_WIN32
 /* Returns an array of pids */
 MonoArray *
 ves_icall_System_Diagnostics_Process_GetProcesses_internal (void)
 {
-#if !defined(HOST_WIN32)
        MonoError error;
        MonoArray *procs;
        gpointer *pidarray;
@@ -878,48 +905,8 @@ ves_icall_System_Diagnostics_Process_GetProcesses_internal (void)
        g_free (pidarray);
 
        return procs;
-#else
-       MonoError error;
-       MonoArray *procs;
-       gboolean ret;
-       DWORD needed;
-       int count;
-       guint32 *pids;
-
-       count = 512;
-       do {
-               pids = g_new0 (guint32, count);
-               ret = EnumProcesses (pids, count * sizeof (guint32), &needed);
-               if (ret == FALSE) {
-                       MonoException *exc;
-
-                       g_free (pids);
-                       pids = NULL;
-                       exc = mono_get_exception_not_supported ("This system does not support EnumProcesses");
-                       mono_set_pending_exception (exc);
-                       return NULL;
-               }
-               if (needed < (count * sizeof (guint32)))
-                       break;
-               g_free (pids);
-               pids = NULL;
-               count = (count * 3) / 2;
-       } while (TRUE);
-
-       count = needed / sizeof (guint32);
-       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;
-       
-       return procs;
-#endif
 }
+#endif /* !HOST_WIN32 */
 
 gint64
 ves_icall_System_Diagnostics_Process_GetProcessData (int pid, gint32 data_type, gint32 *error)
index b8b5e08da499becfb47ed64e24eba3c2916dfa33..e17bf8692087481ac62bb52e93ba94263d8ecd34 100644 (file)
@@ -323,36 +323,6 @@ mono_module_file_get_object_checked (MonoDomain *domain, MonoImage *image, int t
        return res;
 }
 
-static gboolean
-verify_safe_for_managed_space (MonoType *type)
-{
-       switch (type->type) {
-#ifdef DEBUG_HARDER
-       case MONO_TYPE_ARRAY:
-               return verify_safe_for_managed_space (&type->data.array->eklass->byval_arg);
-       case MONO_TYPE_PTR:
-               return verify_safe_for_managed_space (type->data.type);
-       case MONO_TYPE_SZARRAY:
-               return verify_safe_for_managed_space (&type->data.klass->byval_arg);
-       case MONO_TYPE_GENERICINST: {
-               MonoGenericInst *inst = type->data.generic_class->inst;
-               int i;
-               if (!inst->is_open)
-                       break;
-               for (i = 0; i < inst->type_argc; ++i)
-                       if (!verify_safe_for_managed_space (inst->type_argv [i]))
-                               return FALSE;
-               return TRUE;
-       }
-#endif
-       case MONO_TYPE_VAR:
-       case MONO_TYPE_MVAR:
-               return TRUE;
-       default:
-               return TRUE;
-       }
-}
-
 static MonoType*
 mono_type_normalize (MonoType *type)
 {
@@ -481,40 +451,10 @@ mono_type_get_object_checked (MonoDomain *domain, MonoType *type, MonoError *err
        if ((type->type == MONO_TYPE_GENERICINST) && type->data.generic_class->is_dynamic && !type->data.generic_class->container_class->wastypebuilder)
                g_assert (0);
 
-       if (!verify_safe_for_managed_space (type)) {
+       if (mono_class_get_ref_info (klass) && !klass->wastypebuilder && !type->byref) {
                mono_domain_unlock (domain);
                mono_loader_unlock ();
-               mono_error_set_generic_error (error, "System", "InvalidOperationException", "This type cannot be propagated to managed space");
-               return NULL;
-       }
-
-       if (mono_class_get_ref_info (klass) && !klass->wastypebuilder) {
-               gboolean is_type_done = TRUE;
-               /* Generic parameters have reflection_info set but they are not finished together with their enclosing type.
-                * We must ensure that once a type is finished we don't return a GenericTypeParameterBuilder.
-                * We can't simply close the types as this will interfere with other parts of the generics machinery.
-               */
-               if (klass->byval_arg.type == MONO_TYPE_MVAR || klass->byval_arg.type == MONO_TYPE_VAR) {
-                       MonoGenericParam *gparam = klass->byval_arg.data.generic_param;
-
-                       if (gparam->owner && gparam->owner->is_method && !gparam->owner->is_anonymous) {
-                               MonoMethod *method = gparam->owner->owner.method;
-                               if (method && mono_class_get_generic_type_definition (method->klass)->wastypebuilder)
-                                       is_type_done = FALSE;
-                       } else if (gparam->owner && !gparam->owner->is_method) {
-                               MonoClass *klass = gparam->owner->owner.klass;
-                               if (klass && mono_class_get_generic_type_definition (klass)->wastypebuilder)
-                                       is_type_done = FALSE;
-                       }
-               } 
-
-               /* g_assert_not_reached (); */
-               /* should this be considered an error condition? */
-               if (is_type_done && !type->byref) {
-                       mono_domain_unlock (domain);
-                       mono_loader_unlock ();
-                       return (MonoReflectionType *)mono_class_get_ref_info (klass);
-               }
+               return (MonoReflectionType *)mono_class_get_ref_info (klass);
        }
        /* This is stored in vtables/JITted code so it has to be pinned */
        res = (MonoReflectionType *)mono_object_new_pinned (domain, mono_defaults.runtimetype_class, error);
index 30595ee5410e1a43cf886966b5e7175899ccf2ff..a29cf91a1cc2fb23cdd1dc9400203e7107d8ac36 100644 (file)
@@ -197,7 +197,10 @@ 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);
+
+#ifndef DISABLE_JIT
                register_icall (mono_compile_method_icall, "mono_compile_method_icall", "ptr ptr", FALSE);
+#endif
 
        }
 
index b228c6295afbec039774e955d7a315558c68614e..b93c72203221ac36fd6a656ca7a2d5fa4dff61a0 100644 (file)
@@ -166,7 +166,7 @@ set_type_load_exception_type (const char *format, MonoClass *klass)
        g_free (type_name);
        
        mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, "%s", message);
-       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, message);
+       mono_class_set_type_load_failure (klass, "%s", message);
        // note: do not free string given to mono_class_set_failure
 }
 
@@ -189,7 +189,7 @@ set_type_load_exception_methods (const char *format, MonoMethod *override, MonoM
        g_free (method_name);
 
        mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, "%s", message);
-       mono_class_set_failure (override->klass, MONO_EXCEPTION_TYPE_LOAD, message);
+       mono_class_set_type_load_failure (override->klass, "%s", message);
        // note: do not free string given to mono_class_set_failure
 }
 
index 32bab7ebcb8655cc6adf94c918beb880ce7a8a72..aab29b6466c453eeb89eba799141674c467ad615 100644 (file)
@@ -67,9 +67,10 @@ mono_gc_get_restart_signal (void)
        return -1;
 }
 #else
-       #ifdef _MSC_VER
-               // Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
-               void __mono_win32_sgen_os_coop_quiet_lnk4221(void) {}
-       #endif
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_sgen_os_coop_quiet_lnk4221(void) {}
+#endif
 #endif /* USE_COOP_GC */
 #endif
diff --git a/mono/metadata/socket-io-windows-internals.h b/mono/metadata/socket-io-windows-internals.h
new file mode 100644 (file)
index 0000000..b76f9cb
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+* socket-io-windows-internals.h: Windows specific socket code.
+*
+* Copyright 2016 Microsoft
+* Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#ifndef __MONO_METADATA_SOCKET_IO_WINDOWS_INTERNALS_H__
+#define __MONO_METADATA_SOCKET_IO_WINDOWS_INTERNALS_H__
+
+#include <config.h>
+#include <glib.h>
+#include <mono/io-layer/io-layer.h>
+
+SOCKET alertable_accept (SOCKET s, struct sockaddr *addr, int *addrlen, gboolean blocking);
+int alertable_connect (SOCKET s, const struct sockaddr *name, int namelen, gboolean blocking);
+int alertable_recv (SOCKET s, char *buf, int len, int flags, gboolean blocking);
+int alertable_recvfrom (SOCKET s, char *buf, int len, int flags, struct sockaddr *from, int *fromlen, gboolean blocking);
+int alertable_WSARecv (SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount, LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, LPWSAOVERLAPPED lpOverlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, gboolean blocking);
+int alertable_send (SOCKET s, char *buf, int len, int flags, gboolean blocking);
+int alertable_sendto (SOCKET s, const char *buf, int len, int flags, const struct sockaddr *to, int tolen, gboolean blocking);
+int alertable_WSASend (SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount, LPDWORD lpNumberOfBytesRecvd, DWORD lpFlags, LPWSAOVERLAPPED lpOverlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, gboolean blocking);
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT | HAVE_UWP_WINAPI_SUPPORT)
+BOOL alertable_TransmitFile (SOCKET hSocket, HANDLE hFile, DWORD nNumberOfBytesToWrite, DWORD nNumberOfBytesPerSend, LPOVERLAPPED lpOverlapped, LPTRANSMIT_FILE_BUFFERS lpTransmitBuffers, DWORD dwReserved, gboolean blocking);
+#endif
+
+#endif // __MONO_METADATA_SOCKET_IO_WINDOWS_INTERNALS_H__
diff --git a/mono/metadata/socket-io-windows.c b/mono/metadata/socket-io-windows.c
new file mode 100644 (file)
index 0000000..125dbeb
--- /dev/null
@@ -0,0 +1,209 @@
+/*
+* socket-io-windows.c: Windows specific socket code.
+*
+* Copyright 2016 Microsoft
+* Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+
+#include "mono/metadata/socket-io-windows-internals.h"
+
+#define LOGDEBUG(...)  
+
+static gboolean set_blocking (SOCKET sock, gboolean block)
+{
+       u_long non_block = block ? 0 : 1;
+       return ioctlsocket (sock, FIONBIO, &non_block) != SOCKET_ERROR;
+}
+
+static DWORD get_socket_timeout (SOCKET sock, int optname)
+{
+       DWORD timeout = 0;
+       int optlen = sizeof (DWORD);
+       if (getsockopt (sock, SOL_SOCKET, optname, (char *)&timeout, &optlen) == SOCKET_ERROR) {
+               WSASetLastError (0);
+               return WSA_INFINITE;
+       }
+       if (timeout == 0)
+               timeout = WSA_INFINITE; // 0 means infinite
+       return timeout;
+}
+
+/*
+* Performs an alertable wait for the specified event (FD_ACCEPT_BIT,
+* FD_CONNECT_BIT, FD_READ_BIT, FD_WRITE_BIT) on the specified socket.
+* Returns TRUE if the event is fired without errors. Calls WSASetLastError()
+* with WSAEINTR and returns FALSE if the thread is alerted. If the event is
+* fired but with an error WSASetLastError() is called to set the error and the
+* function returns FALSE.
+*/
+static gboolean alertable_socket_wait (SOCKET sock, int event_bit)
+{
+       static char *EVENT_NAMES[] = { "FD_READ", "FD_WRITE", NULL /*FD_OOB*/, "FD_ACCEPT", "FD_CONNECT", "FD_CLOSE" };
+       gboolean success = FALSE;
+       int error = -1;
+       DWORD timeout = WSA_INFINITE;
+       if (event_bit == FD_READ_BIT || event_bit == FD_WRITE_BIT) {
+               timeout = get_socket_timeout (sock, event_bit == FD_READ_BIT ? SO_RCVTIMEO : SO_SNDTIMEO);
+       }
+       WSASetLastError (0);
+       WSAEVENT event = WSACreateEvent ();
+       if (event != WSA_INVALID_EVENT) {
+               if (WSAEventSelect (sock, event, (1 << event_bit) | FD_CLOSE) != SOCKET_ERROR) {
+                       LOGDEBUG (g_message ("%06d - Calling WSAWaitForMultipleEvents () on socket %d", GetCurrentThreadId (), sock));
+                       DWORD ret = WSAWaitForMultipleEvents (1, &event, TRUE, timeout, TRUE);
+                       if (ret == WSA_WAIT_IO_COMPLETION) {
+                               LOGDEBUG (g_message ("%06d - WSAWaitForMultipleEvents () returned WSA_WAIT_IO_COMPLETION for socket %d", GetCurrentThreadId (), sock));
+                               error = WSAEINTR;
+                       } else if (ret == WSA_WAIT_TIMEOUT) {
+                               error = WSAETIMEDOUT;
+                       } else {
+                               g_assert (ret == WSA_WAIT_EVENT_0);
+                               WSANETWORKEVENTS ne = { 0 };
+                               if (WSAEnumNetworkEvents (sock, event, &ne) != SOCKET_ERROR) {
+                                       if (ne.lNetworkEvents & (1 << event_bit) && ne.iErrorCode[event_bit]) {
+                                               LOGDEBUG (g_message ("%06d - %s error %d on socket %d", GetCurrentThreadId (), EVENT_NAMES[event_bit], ne.iErrorCode[event_bit], sock));
+                                               error = ne.iErrorCode[event_bit];
+                                       } else if (ne.lNetworkEvents & FD_CLOSE_BIT && ne.iErrorCode[FD_CLOSE_BIT]) {
+                                               LOGDEBUG (g_message ("%06d - FD_CLOSE error %d on socket %d", GetCurrentThreadId (), ne.iErrorCode[FD_CLOSE_BIT], sock));
+                                               error = ne.iErrorCode[FD_CLOSE_BIT];
+                                       } else {
+                                               LOGDEBUG (g_message ("%06d - WSAEnumNetworkEvents () finished successfully on socket %d", GetCurrentThreadId (), sock));
+                                               success = TRUE;
+                                               error = 0;
+                                       }
+                               }
+                       }
+                       WSAEventSelect (sock, NULL, 0);
+               }
+               WSACloseEvent (event);
+       }
+       if (error != -1) {
+               WSASetLastError (error);
+       }
+       return success;
+}
+
+#define ALERTABLE_SOCKET_CALL(event_bit, blocking, repeat, ret, op, sock, ...) \
+       LOGDEBUG (g_message ("%06d - Performing %s " #op " () on socket %d", GetCurrentThreadId (), blocking ? "blocking" : "non-blocking", sock)); \
+       if (blocking) { \
+               if (set_blocking(sock, FALSE)) { \
+                       while (-1 == (int) (ret = op (sock, __VA_ARGS__))) { \
+                               int _error = WSAGetLastError ();\
+                               if (_error != WSAEWOULDBLOCK && _error != WSA_IO_PENDING) \
+                                       break; \
+                               if (!alertable_socket_wait (sock, event_bit) || !repeat) \
+                                       break; \
+                       } \
+                       int _saved_error = WSAGetLastError (); \
+                       set_blocking (sock, TRUE); \
+                       WSASetLastError (_saved_error); \
+               } \
+       } else { \
+               ret = op (sock, __VA_ARGS__); \
+       } \
+       int _saved_error = WSAGetLastError (); \
+       LOGDEBUG (g_message ("%06d - Finished %s " #op " () on socket %d (ret = %d, WSAGetLastError() = %d)", GetCurrentThreadId (), \
+               blocking ? "blocking" : "non-blocking", sock, ret, _saved_error)); \
+       WSASetLastError (_saved_error);
+
+SOCKET alertable_accept (SOCKET s, struct sockaddr *addr, int *addrlen, gboolean blocking)
+{
+       SOCKET newsock = INVALID_SOCKET;
+       ALERTABLE_SOCKET_CALL (FD_ACCEPT_BIT, blocking, TRUE, newsock, accept, s, addr, addrlen);
+       return newsock;
+}
+
+int alertable_connect (SOCKET s, const struct sockaddr *name, int namelen, gboolean blocking)
+{
+       int ret = SOCKET_ERROR;
+       ALERTABLE_SOCKET_CALL (FD_CONNECT_BIT, blocking, FALSE, ret, connect, s, name, namelen);
+       ret = WSAGetLastError () != 0 ? SOCKET_ERROR : 0;
+       return ret;
+}
+
+int alertable_recv (SOCKET s, char *buf, int len, int flags, gboolean blocking)
+{
+       int ret = SOCKET_ERROR;
+       ALERTABLE_SOCKET_CALL (FD_READ_BIT, blocking, TRUE, ret, recv, s, buf, len, flags);
+       return ret;
+}
+
+int alertable_recvfrom (SOCKET s, char *buf, int len, int flags, struct sockaddr *from, int *fromlen, gboolean blocking)
+{
+       int ret = SOCKET_ERROR;
+       ALERTABLE_SOCKET_CALL (FD_READ_BIT, blocking, TRUE, ret, recvfrom, s, buf, len, flags, from, fromlen);
+       return ret;
+}
+
+int alertable_WSARecv (SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount, LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, LPWSAOVERLAPPED lpOverlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, gboolean blocking)
+{
+       int ret = SOCKET_ERROR;
+       ALERTABLE_SOCKET_CALL (FD_READ_BIT, blocking, TRUE, ret, WSARecv, s, lpBuffers, dwBufferCount, lpNumberOfBytesRecvd, lpFlags, lpOverlapped, lpCompletionRoutine);
+       return ret;
+}
+
+int alertable_send (SOCKET s, char *buf, int len, int flags, gboolean blocking)
+{
+       int ret = SOCKET_ERROR;
+       ALERTABLE_SOCKET_CALL (FD_WRITE_BIT, blocking, FALSE, ret, send, s, buf, len, flags);
+       return ret;
+}
+
+int alertable_sendto (SOCKET s, const char *buf, int len, int flags, const struct sockaddr *to, int tolen, gboolean blocking)
+{
+       int ret = SOCKET_ERROR;
+       ALERTABLE_SOCKET_CALL (FD_WRITE_BIT, blocking, FALSE, ret, sendto, s, buf, len, flags, to, tolen);
+       return ret;
+}
+
+int alertable_WSASend (SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount, LPDWORD lpNumberOfBytesRecvd, DWORD lpFlags, LPWSAOVERLAPPED lpOverlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, gboolean blocking)
+{
+       int ret = SOCKET_ERROR;
+       ALERTABLE_SOCKET_CALL (FD_WRITE_BIT, blocking, FALSE, ret, WSASend, s, lpBuffers, dwBufferCount, lpNumberOfBytesRecvd, lpFlags, lpOverlapped, lpCompletionRoutine);
+       return ret;
+}
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT | HAVE_UWP_WINAPI_SUPPORT)
+BOOL alertable_TransmitFile (SOCKET hSocket, HANDLE hFile, DWORD nNumberOfBytesToWrite, DWORD nNumberOfBytesPerSend, LPOVERLAPPED lpOverlapped, LPTRANSMIT_FILE_BUFFERS lpTransmitBuffers, DWORD dwReserved, gboolean blocking)
+{
+       LOGDEBUG (g_message ("%06d - Performing %s TransmitFile () on socket %d", GetCurrentThreadId (), blocking ? "blocking" : "non-blocking", hSocket));
+
+       int error = 0;
+       if (blocking) {
+               g_assert (lpOverlapped == NULL);
+               OVERLAPPED overlapped = { 0 };
+               overlapped.hEvent = WSACreateEvent ();
+               if (overlapped.hEvent == WSA_INVALID_EVENT)
+                       return FALSE;
+               if (!TransmitFile (hSocket, hFile, nNumberOfBytesToWrite, nNumberOfBytesPerSend, &overlapped, lpTransmitBuffers, dwReserved)) {
+                       error = WSAGetLastError ();
+                       if (error == WSA_IO_PENDING) {
+                               error = 0;
+                               // NOTE: .NET's Socket.SendFile() doesn't honor the Socket's SendTimeout so we shouldn't either
+                               DWORD ret = WaitForSingleObjectEx (overlapped.hEvent, INFINITE, TRUE);
+                               if (ret == WAIT_IO_COMPLETION) {
+                                       LOGDEBUG (g_message ("%06d - WaitForSingleObjectEx () returned WSA_WAIT_IO_COMPLETION for socket %d", GetCurrentThreadId (), hSocket));
+                                       error = WSAEINTR;
+                               } else if (ret == WAIT_TIMEOUT) {
+                                       error = WSAETIMEDOUT;
+                               } else if (ret != WAIT_OBJECT_0) {
+                                       error = GetLastError ();
+                               }
+                       }
+               }
+               WSACloseEvent (overlapped.hEvent);
+       } else {
+               if (!TransmitFile (hSocket, hFile, nNumberOfBytesToWrite, nNumberOfBytesPerSend, lpOverlapped, lpTransmitBuffers, dwReserved)) {
+                       error = WSAGetLastError ();
+               }
+       }
+
+       LOGDEBUG (g_message ("%06d - Finished %s TransmitFile () on socket %d (ret = %d, WSAGetLastError() = %d)", GetCurrentThreadId (), \
+               blocking ? "blocking" : "non-blocking", hSocket, error == 0, error));
+       WSASetLastError (error);
+
+       return error == 0;
+}
+#endif /* #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT | HAVE_UWP_WINAPI_SUPPORT) */
index b4a85f27fa4f6d899ad1f40a3e895e9eaabef393..2df84e99c8f9658a398e4c089d1155be2e64906a 100644 (file)
 #include <ifaddrs.h>
 #endif
 
+#if defined(_MSC_VER) && G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT | HAVE_UWP_WINAPI_SUPPORT)
+#include <MSWSock.h>
+#endif
+
 #include "mono/io-layer/socket-wrappers.h"
+#ifdef HOST_WIN32
+#include "mono/metadata/socket-io-windows-internals.h"
+#endif
 
 #define LOGDEBUG(...)  
 /* define LOGDEBUG(...) g_message(__VA_ARGS__)  */
@@ -588,61 +595,6 @@ get_socket_assembly (void)
        return domain->socket_assembly;
 }
 
-static gint32
-get_family_hint (MonoError *error)
-{
-       MonoDomain *domain = mono_domain_get ();
-
-       mono_error_init (error);
-
-       if (!domain->inet_family_hint) {
-               MonoImage *socket_assembly;
-               MonoClass *socket_class;
-               MonoClassField *ipv6_field, *ipv4_field;
-               gint32 ipv6_enabled = -1, ipv4_enabled = -1;
-               MonoVTable *vtable;
-
-               socket_assembly = get_socket_assembly ();
-               g_assert (socket_assembly);
-
-               socket_class = mono_class_load_from_name (socket_assembly, "System.Net.Sockets", "Socket");
-
-               ipv4_field = mono_class_get_field_from_name (socket_class, "ipv4_supported");
-               g_assert (ipv4_field);
-
-               ipv6_field = mono_class_get_field_from_name (socket_class, "ipv6_supported");
-               g_assert (ipv6_field);
-
-               vtable = mono_class_vtable (mono_domain_get (), socket_class);
-               g_assert (vtable);
-
-               mono_runtime_class_init_full (vtable, error);
-               return_val_if_nok (error, -1);
-
-               mono_field_static_get_value_checked (vtable, ipv4_field, &ipv4_enabled, error);
-               return_val_if_nok (error, -1);
-               mono_field_static_get_value_checked (vtable, ipv6_field, &ipv6_enabled, error);
-               return_val_if_nok (error, -1);
-
-               mono_domain_lock (domain);
-               if (ipv4_enabled == 1 && ipv6_enabled == 1) {
-                       domain->inet_family_hint = 1;
-               } else if (ipv4_enabled == 1) {
-                       domain->inet_family_hint = 2;
-               } else {
-                       domain->inet_family_hint = 3;
-               }
-               mono_domain_unlock (domain);
-       }
-       switch (domain->inet_family_hint) {
-       case 1: return PF_UNSPEC;
-       case 2: return PF_INET;
-       case 3: return PF_INET6;
-       default:
-               return PF_UNSPEC;
-       }
-}
-
 gpointer
 ves_icall_System_Net_Sockets_Socket_Socket_internal (MonoObject *this_obj, gint32 family, gint32 type, gint32 proto, gint32 *werror)
 {
@@ -765,7 +717,7 @@ ves_icall_System_Net_Sockets_Socket_Accept_internal (SOCKET sock, gint32 *werror
        {
                MonoInternalThread *curthread = mono_thread_internal_current ();
                curthread->interrupt_on_stop = (gpointer)TRUE;
-               newsock = _wapi_accept (sock, NULL, 0);
+               newsock = alertable_accept (sock, NULL, 0, blocking);
                curthread->interrupt_on_stop = (gpointer)FALSE;
        }
 #else
@@ -1303,7 +1255,7 @@ ves_icall_System_Net_Sockets_Socket_Poll_internal (SOCKET sock, gint mode,
 }
 
 void
-ves_icall_System_Net_Sockets_Socket_Connect_internal (SOCKET sock, MonoObject *sockaddr, gint32 *werror)
+ves_icall_System_Net_Sockets_Socket_Connect_internal (SOCKET sock, MonoObject *sockaddr, gint32 *werror, gboolean blocking)
 {
        MonoError error;
        struct sockaddr *sa;
@@ -1331,7 +1283,11 @@ ves_icall_System_Net_Sockets_Socket_Connect_internal (SOCKET sock, MonoObject *s
 
        MONO_ENTER_GC_SAFE;
 
+#ifdef HOST_WIN32
+       ret = alertable_connect (sock, sa, sa_size, blocking);
+#else
        ret = _wapi_connect (sock, sa, sa_size);
+#endif
 
        MONO_EXIT_GC_SAFE;
 
@@ -1345,6 +1301,7 @@ ves_icall_System_Net_Sockets_Socket_Connect_internal (SOCKET sock, MonoObject *s
        g_free (sa);
 }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT | HAVE_UWP_WINAPI_SUPPORT)
 /* These #defines from mswsock.h from wine.  Defining them here allows
  * us to build this file on a mingw box that doesn't know the magic
  * numbers, but still run on a newer windows box that does.
@@ -1435,9 +1392,10 @@ ves_icall_System_Net_Sockets_Socket_Disconnect_internal (SOCKET sock, MonoBoolea
        if (interrupted)
                *werror = WSAEINTR;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT | HAVE_UWP_WINAPI_SUPPORT) */
 
 gint32
-ves_icall_System_Net_Sockets_Socket_Receive_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *werror)
+ves_icall_System_Net_Sockets_Socket_Receive_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *werror, gboolean blocking)
 {
        int ret;
        guchar *buf;
@@ -1469,7 +1427,7 @@ ves_icall_System_Net_Sockets_Socket_Receive_internal (SOCKET sock, MonoArray *bu
 #ifdef HOST_WIN32
        {
                curthread->interrupt_on_stop = (gpointer)TRUE;
-               ret = _wapi_recv (sock, buf, count, recvflags);
+               ret = alertable_recv (sock, buf, count, recvflags, blocking);
                curthread->interrupt_on_stop = (gpointer)FALSE;
        }
 #else
@@ -1492,7 +1450,7 @@ ves_icall_System_Net_Sockets_Socket_Receive_internal (SOCKET sock, MonoArray *bu
 }
 
 gint32
-ves_icall_System_Net_Sockets_Socket_Receive_array_internal (SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *werror)
+ves_icall_System_Net_Sockets_Socket_Receive_array_internal (SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *werror, gboolean blocking)
 {
        int ret, count;
        gboolean interrupted;
@@ -1519,7 +1477,11 @@ ves_icall_System_Net_Sockets_Socket_Receive_array_internal (SOCKET sock, MonoArr
 
        MONO_ENTER_GC_SAFE;
 
+#ifdef HOST_WIN32
+       ret = alertable_WSARecv (sock, wsabufs, count, &recv, &recvflags, NULL, NULL, blocking);
+#else
        ret = WSARecv (sock, wsabufs, count, &recv, &recvflags, NULL, NULL);
+#endif
 
        MONO_EXIT_GC_SAFE;
 
@@ -1537,7 +1499,7 @@ ves_icall_System_Net_Sockets_Socket_Receive_array_internal (SOCKET sock, MonoArr
 }
 
 gint32
-ves_icall_System_Net_Sockets_Socket_ReceiveFrom_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject **sockaddr, gint32 *werror)
+ves_icall_System_Net_Sockets_Socket_ReceiveFrom_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject **sockaddr, gint32 *werror, gboolean blocking)
 {
        MonoError error;
        int ret;
@@ -1579,7 +1541,11 @@ ves_icall_System_Net_Sockets_Socket_ReceiveFrom_internal (SOCKET sock, MonoArray
 
        MONO_ENTER_GC_SAFE;
 
+#ifdef HOST_WIN32
+       ret = alertable_recvfrom (sock, buf, count, recvflags, sa, &sa_size, blocking);
+#else
        ret = _wapi_recvfrom (sock, buf, count, recvflags, sa, &sa_size);
+#endif
 
        MONO_EXIT_GC_SAFE;
 
@@ -1617,7 +1583,7 @@ ves_icall_System_Net_Sockets_Socket_ReceiveFrom_internal (SOCKET sock, MonoArray
 }
 
 gint32
-ves_icall_System_Net_Sockets_Socket_Send_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *werror)
+ves_icall_System_Net_Sockets_Socket_Send_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *werror, gboolean blocking)
 {
        int ret;
        guchar *buf;
@@ -1651,7 +1617,11 @@ ves_icall_System_Net_Sockets_Socket_Send_internal (SOCKET sock, MonoArray *buffe
 
        MONO_ENTER_GC_SAFE;
 
+#ifdef HOST_WIN32
+       ret = alertable_send (sock, buf, count, sendflags, blocking);
+#else
        ret = _wapi_send (sock, buf, count, sendflags);
+#endif
 
        MONO_EXIT_GC_SAFE;
 
@@ -1669,7 +1639,7 @@ ves_icall_System_Net_Sockets_Socket_Send_internal (SOCKET sock, MonoArray *buffe
 }
 
 gint32
-ves_icall_System_Net_Sockets_Socket_Send_array_internal (SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *werror)
+ves_icall_System_Net_Sockets_Socket_Send_array_internal (SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *werror, gboolean blocking)
 {
        int ret, count;
        DWORD sent;
@@ -1696,7 +1666,11 @@ ves_icall_System_Net_Sockets_Socket_Send_array_internal (SOCKET sock, MonoArray
 
        MONO_ENTER_GC_SAFE;
 
+#ifdef HOST_WIN32
+       ret = alertable_WSASend (sock, wsabufs, count, &sent, sendflags, NULL, NULL, blocking);
+#else
        ret = WSASend (sock, wsabufs, count, &sent, sendflags, NULL, NULL);
+#endif
 
        MONO_EXIT_GC_SAFE;
 
@@ -1714,7 +1688,7 @@ ves_icall_System_Net_Sockets_Socket_Send_array_internal (SOCKET sock, MonoArray
 }
 
 gint32
-ves_icall_System_Net_Sockets_Socket_SendTo_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject *sockaddr, gint32 *werror)
+ves_icall_System_Net_Sockets_Socket_SendTo_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject *sockaddr, gint32 *werror, gboolean blocking)
 {
        MonoError error;
        int ret;
@@ -1762,7 +1736,11 @@ ves_icall_System_Net_Sockets_Socket_SendTo_internal (SOCKET sock, MonoArray *buf
 
        MONO_ENTER_GC_SAFE;
 
+#ifdef HOST_WIN32
+       ret = alertable_sendto (sock, buf, count, sendflags, sa, sa_size, blocking);
+#else
        ret = _wapi_sendto (sock, buf, count, sendflags, sa, sa_size);
+#endif
 
        MONO_EXIT_GC_SAFE;
 
@@ -2613,50 +2591,18 @@ leave2:
        return is_ok (error);
 }
 
-static int
-get_addrinfo_family_hint (MonoError *error)
-{
-       int hint;
-
-       mono_error_init (error);
-
-       hint = get_family_hint (error);
-       return_val_if_nok (error, 0);
-
-       switch (hint) {
-       case PF_UNSPEC:
-               return MONO_HINT_UNSPECIFIED;
-       case PF_INET:
-               return MONO_HINT_IPV4;
-#ifdef PF_INET6
-       case PF_INET6:
-               return MONO_HINT_IPV6;
-#endif
-       default:
-               g_error ("invalid hint");
-               return 0;
-       }
-}
-
 MonoBoolean
-ves_icall_System_Net_Dns_GetHostByName_internal (MonoString *host, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list)
+ves_icall_System_Net_Dns_GetHostByName_internal (MonoString *host, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list, gint32 hint)
 {
        MonoError error;
        gboolean add_local_ips = FALSE, add_info_ok = TRUE;
        gchar this_hostname [256];
        MonoAddressInfo *info = NULL;
-       int hint;
 
        char *hostname = mono_string_to_utf8_checked (host, &error);
        if (mono_error_set_pending_exception (&error))
                return FALSE;
 
-       hint = get_addrinfo_family_hint (&error);
-       if (!mono_error_ok (&error)) {
-               mono_error_set_pending_exception (&error);
-               return FALSE;
-       }
-
        if (*hostname == '\0') {
                add_local_ips = TRUE;
                *h_name = host;
@@ -2691,14 +2637,14 @@ ves_icall_System_Net_Dns_GetHostByName_internal (MonoString *host, MonoString **
 }
 
 MonoBoolean
-ves_icall_System_Net_Dns_GetHostByAddr_internal (MonoString *addr, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list)
+ves_icall_System_Net_Dns_GetHostByAddr_internal (MonoString *addr, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list, gint32 hint)
 {
        char *address;
        struct sockaddr_in saddr;
        struct sockaddr_in6 saddr6;
        MonoAddressInfo *info = NULL;
        MonoError error;
-       gint32 family, hint;
+       gint32 family;
        gchar hostname [NI_MAXHOST] = { 0 };
        gboolean ret;
 
@@ -2745,11 +2691,6 @@ ves_icall_System_Net_Dns_GetHostByAddr_internal (MonoString *addr, MonoString **
        if (!ret)
                return FALSE;
 
-       hint = get_addrinfo_family_hint (&error);
-       if (!mono_error_ok (&error)) {
-               mono_error_set_pending_exception (&error);
-               return FALSE;
-       }
        if (mono_get_address_info (hostname, 0, hint | MONO_HINT_CANONICAL_NAME | MONO_HINT_CONFIGURED_ONLY, &info) != 0)
                return FALSE;
 
@@ -2773,11 +2714,11 @@ ves_icall_System_Net_Dns_GetHostName_internal (MonoString **h_name)
        return TRUE;
 }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT | HAVE_UWP_WINAPI_SUPPORT)
 gboolean
-ves_icall_System_Net_Sockets_Socket_SendFile_internal (SOCKET sock, MonoString *filename, MonoArray *pre_buffer, MonoArray *post_buffer, gint flags)
+ves_icall_System_Net_Sockets_Socket_SendFile_internal (SOCKET sock, MonoString *filename, MonoArray *pre_buffer, MonoArray *post_buffer, gint flags, gint32 *werror, gboolean blocking)
 {
        HANDLE file;
-       gint32 werror;
        gboolean ret;
        gboolean interrupted;
        TRANSMIT_FILE_BUFFERS buffers;
@@ -2787,10 +2728,10 @@ ves_icall_System_Net_Sockets_Socket_SendFile_internal (SOCKET sock, MonoString *
 
        /* FIXME: replace file by a proper fd that we can call open and close on, as they are interruptible */
 
-       file = ves_icall_System_IO_MonoIO_Open (filename, FileMode_Open, FileAccess_Read, FileShare_Read, 0, &werror);
+       file = ves_icall_System_IO_MonoIO_Open (filename, FileMode_Open, FileAccess_Read, FileShare_Read, 0, werror);
 
        if (file == INVALID_HANDLE_VALUE) {
-               SetLastError (werror);
+               SetLastError (*werror);
                return FALSE;
        }
 
@@ -2813,14 +2754,21 @@ ves_icall_System_Net_Sockets_Socket_SendFile_internal (SOCKET sock, MonoString *
 
        MONO_ENTER_GC_SAFE;
 
+#ifdef HOST_WIN32
+       ret = alertable_TransmitFile (sock, file, 0, 0, NULL, &buffers, flags, blocking);
+#else
        ret = TransmitFile (sock, file, 0, 0, NULL, &buffers, flags);
+#endif
 
        MONO_EXIT_GC_SAFE;
 
+       if (!ret)
+               *werror = WSAGetLastError ();
+
        mono_thread_info_uninstall_interrupt (&interrupted);
        if (interrupted) {
                CloseHandle (file);
-               SetLastError (WSAEINTR);
+               *werror = WSAEINTR;
                return FALSE;
        }
 
@@ -2830,8 +2778,12 @@ ves_icall_System_Net_Sockets_Socket_SendFile_internal (SOCKET sock, MonoString *
 
        MONO_EXIT_GC_SAFE;
 
+       if (*werror)
+               return FALSE;
+
        return ret;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT | HAVE_UWP_WINAPI_SUPPORT) */
 
 gboolean
 ves_icall_System_Net_Sockets_Socket_SupportPortReuse (MonoProtocolType proto)
index e228f0a2e63df038682a3d004622f541cf928284..7a8c9361ad6334ca7843275c0eb43f9ac99ebe18 100644 (file)
@@ -169,25 +169,25 @@ extern void ves_icall_System_Net_Sockets_Socket_Listen_internal(SOCKET sock, gui
 extern MonoObject *ves_icall_System_Net_Sockets_Socket_LocalEndPoint_internal(SOCKET sock, gint32 af, gint32 *error);
 extern MonoObject *ves_icall_System_Net_Sockets_Socket_RemoteEndPoint_internal(SOCKET sock, gint32 af, gint32 *error);
 extern void ves_icall_System_Net_Sockets_Socket_Bind_internal(SOCKET sock, MonoObject *sockaddr, gint32 *error);
-extern void ves_icall_System_Net_Sockets_Socket_Connect_internal(SOCKET sock, MonoObject *sockaddr, gint32 *error);
-extern gint32 ves_icall_System_Net_Sockets_Socket_Receive_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *error);
-extern gint32 ves_icall_System_Net_Sockets_Socket_Receive_array_internal(SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *error);
-extern gint32 ves_icall_System_Net_Sockets_Socket_ReceiveFrom_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject **sockaddr, gint32 *error);
-extern gint32 ves_icall_System_Net_Sockets_Socket_Send_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *error);
-extern gint32 ves_icall_System_Net_Sockets_Socket_Send_array_internal(SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *error);
-extern gint32 ves_icall_System_Net_Sockets_Socket_SendTo_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject *sockaddr, gint32 *error);
+extern void ves_icall_System_Net_Sockets_Socket_Connect_internal(SOCKET sock, MonoObject *sockaddr, gint32 *error, gboolean blocking);
+extern gint32 ves_icall_System_Net_Sockets_Socket_Receive_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *error, gboolean blocking);
+extern gint32 ves_icall_System_Net_Sockets_Socket_Receive_array_internal(SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *error, gboolean blocking);
+extern gint32 ves_icall_System_Net_Sockets_Socket_ReceiveFrom_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject **sockaddr, gint32 *error, gboolean blocking);
+extern gint32 ves_icall_System_Net_Sockets_Socket_Send_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *error, gboolean blocking);
+extern gint32 ves_icall_System_Net_Sockets_Socket_Send_array_internal(SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *error, gboolean blocking);
+extern gint32 ves_icall_System_Net_Sockets_Socket_SendTo_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject *sockaddr, gint32 *error, gboolean blocking);
 extern void ves_icall_System_Net_Sockets_Socket_Select_internal(MonoArray **sockets, gint32 timeout, gint32 *error);
 extern void ves_icall_System_Net_Sockets_Socket_Shutdown_internal(SOCKET sock, gint32 how, gint32 *error);
 extern void ves_icall_System_Net_Sockets_Socket_GetSocketOption_obj_internal(SOCKET sock, gint32 level, gint32 name, MonoObject **obj_val, gint32 *error);
 extern void ves_icall_System_Net_Sockets_Socket_GetSocketOption_arr_internal(SOCKET sock, gint32 level, gint32 name, MonoArray **byte_val, gint32 *error);
 extern void ves_icall_System_Net_Sockets_Socket_SetSocketOption_internal(SOCKET sock, gint32 level, gint32 name, MonoObject *obj_val, MonoArray *byte_val, gint32 int_val, gint32 *error);
 extern int ves_icall_System_Net_Sockets_Socket_IOControl_internal (SOCKET sock, gint32 code, MonoArray *input, MonoArray *output, gint32 *error);
-extern MonoBoolean ves_icall_System_Net_Dns_GetHostByName_internal(MonoString *host, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list);
-extern MonoBoolean ves_icall_System_Net_Dns_GetHostByAddr_internal(MonoString *addr, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list);
+extern MonoBoolean ves_icall_System_Net_Dns_GetHostByName_internal(MonoString *host, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list, gint32 hint);
+extern MonoBoolean ves_icall_System_Net_Dns_GetHostByAddr_internal(MonoString *addr, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list, gint32 hint);
 extern MonoBoolean ves_icall_System_Net_Dns_GetHostName_internal(MonoString **h_name);
 extern MonoBoolean ves_icall_System_Net_Sockets_Socket_Poll_internal (SOCKET sock, gint mode, gint timeout, gint32 *error);
 extern void ves_icall_System_Net_Sockets_Socket_Disconnect_internal(SOCKET sock, MonoBoolean reuse, gint32 *error);
-extern gboolean ves_icall_System_Net_Sockets_Socket_SendFile_internal (SOCKET sock, MonoString *filename, MonoArray *pre_buffer, MonoArray *post_buffer, gint flags);
+extern gboolean ves_icall_System_Net_Sockets_Socket_SendFile_internal (SOCKET sock, MonoString *filename, MonoArray *pre_buffer, MonoArray *post_buffer, gint flags, gint32 *error, gboolean blocking);
 void icall_cancel_blocking_socket_operation (MonoThread *thread);
 extern gboolean ves_icall_System_Net_Sockets_Socket_SupportPortReuse (MonoProtocolType proto);
 
index 2bd9121b9ebf7b54489782ddab54ddcd98f01b5d..3bdacdb2248ae3d64b3670fabe21b4583fc011d4 100644 (file)
@@ -2702,6 +2702,9 @@ reflection_methodbuilder_to_mono_method (MonoClass *klass,
                        container->type_params [i].param.owner = container;
 
                        gp->type.type->data.generic_param = (MonoGenericParam*)&container->type_params [i];
+
+                       MonoClass *gklass = mono_class_from_mono_type (gp_type);
+                       gklass->wastypebuilder = TRUE;
                }
 
                /*
@@ -3053,7 +3056,7 @@ ensure_runtime_vtable (MonoClass *klass, MonoError *error)
                }
        } else if (klass->generic_class){
                if (!ensure_generic_class_runtime_vtable (klass, error)) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+                       mono_class_set_type_load_failure (klass, "Could not initialize vtable for generic class due to: %s", mono_error_get_message (error));
                        return FALSE;
                }
        }
@@ -3185,8 +3188,7 @@ typebuilder_setup_fields (MonoClass *klass, MonoError *error)
 
        if (tb->class_size) {
                if ((tb->packing_size & 0xffffff00) != 0) {
-                       char *err_msg = mono_image_strdup_printf (klass->image, "Could not load struct '%s' with packing size %d >= 256", klass->name, tb->packing_size);
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, err_msg);
+                       mono_class_set_type_load_failure (klass, "Could not load struct '%s' with packing size %d >= 256", klass->name, tb->packing_size);
                        return;
                }
                klass->packing_size = tb->packing_size;
@@ -3381,7 +3383,7 @@ remove_instantiations_of_and_ensure_contents (gpointer key,
                MonoClass *inst_klass = mono_class_from_mono_type (type);
                //Ensure it's safe to use it.
                if (!fix_partial_generic_class (inst_klass, error)) {
-                       mono_class_set_failure (inst_klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+                       mono_class_set_type_load_failure (inst_klass, "Could not initialized generic type instance due to: %s", mono_error_get_message (error));
                        // Marked the class with failure, but since some other instantiation already failed,
                        // just report that one, and swallow the error from this one.
                        if (already_failed)
@@ -3492,6 +3494,16 @@ ves_icall_TypeBuilder_create_runtime_class (MonoReflectionTypeBuilder *tb)
 
        klass->wastypebuilder = TRUE;
 
+       if (tb->generic_params) {
+               for (i = 0; i < mono_array_length (tb->generic_params); i++) {
+                       MonoReflectionGenericParam *gparam = (MonoReflectionGenericParam *)mono_array_get (tb->generic_params, gpointer, i);
+                       MonoType *param_type = mono_reflection_type_get_handle ((MonoReflectionType*)gparam, &error);
+                       MonoClass *gklass = mono_class_from_mono_type (param_type);
+
+                       gklass->wastypebuilder = TRUE;
+               }
+       }
+
        /* 
         * If we are a generic TypeBuilder, there might be instantiations in the type cache
         * which have type System.Reflection.MonoGenericClass, but after the type is created, 
@@ -3513,7 +3525,7 @@ ves_icall_TypeBuilder_create_runtime_class (MonoReflectionTypeBuilder *tb)
        mono_loader_unlock ();
 
        if (klass->enumtype && !mono_class_is_valid_enum (klass)) {
-               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+               mono_class_set_type_load_failure (klass, "Not a valid enumeration");
                mono_error_set_type_load_class (&error, klass, "Not a valid enumeration");
                goto failure_unlocked;
        }
@@ -3527,7 +3539,7 @@ ves_icall_TypeBuilder_create_runtime_class (MonoReflectionTypeBuilder *tb)
        return res;
 
 failure:
-       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+       mono_class_set_type_load_failure (klass, "TypeBuilder could not create runtime class due to: %s", mono_error_get_message (&error));
        klass->wastypebuilder = TRUE;
        mono_domain_unlock (domain);
        mono_loader_unlock ();
index 0b8aa7c4fb9a8f3a81632bd188c153adab92f204..2ae43aab0ae3be675b979e4cb5756fc1d6ed169a 100644 (file)
@@ -910,6 +910,7 @@ create_thread (MonoThread *thread, MonoInternalThread *internal, MonoObject *sta
        HANDLE thread_handle;
        MonoNativeThreadId tid;
        gboolean ret;
+       gsize stack_set_size;
 
        if (start_delegate)
                g_assert (!start_func && !start_func_arg);
@@ -951,9 +952,11 @@ create_thread (MonoThread *thread, MonoInternalThread *internal, MonoObject *sta
        mono_coop_sem_init (&start_info->registered, 0);
 
        if (stack_size == 0)
-               stack_size = default_stacksize_for_thread (internal);
+               stack_set_size = default_stacksize_for_thread (internal);
+       else
+               stack_set_size = 0;
 
-       thread_handle = mono_threads_create_thread (start_wrapper, start_info, stack_size, &tid);
+       thread_handle = mono_threads_create_thread (start_wrapper, start_info, &stack_set_size, &tid);
 
        if (thread_handle == NULL) {
                /* The thread couldn't be created, so set an exception */
@@ -967,6 +970,8 @@ create_thread (MonoThread *thread, MonoInternalThread *internal, MonoObject *sta
                goto done;
        }
 
+       internal->stack_size = (int) stack_set_size;
+
        THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Launching thread %p (%"G_GSIZE_FORMAT")", __func__, mono_native_thread_id_get (), internal, (gsize)internal->tid));
 
        /*
index d7c6b621a5cec0c9adbb964abe371f25c1a27c8b..bd6bdc97e8e3fcc7d749d0464a758e30e559e846 100644 (file)
@@ -17,6 +17,7 @@ mono_w32semaphore_init (void)
 {
 }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT | HAVE_UWP_WINAPI_SUPPORT)
 gpointer
 ves_icall_System_Threading_Semaphore_CreateSemaphore_internal (gint32 initialCount, gint32 maximumCount, MonoString *name, gint32 *error)
 { 
@@ -28,6 +29,7 @@ ves_icall_System_Threading_Semaphore_CreateSemaphore_internal (gint32 initialCou
 
        return sem;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT | HAVE_UWP_WINAPI_SUPPORT) */
 
 MonoBoolean
 ves_icall_System_Threading_Semaphore_ReleaseSemaphore_internal (gpointer handle, gint32 releaseCount, gint32 *prevcount)
index 62e771c78b912a21c14142bccfcf772d1b1fde9e..488b3cd0c4e2b9baad71d2b42eeb3599f74e1bdb 100755 (executable)
@@ -373,6 +373,7 @@ darwin_sources = \
 
 windows_sources = \
        mini-windows.c \
+       mini-windows.h \
        mini-windows-dllmain.c
 
 posix_sources = \
index 4a5029641218fe7804917a84c70c3fdc85eaf849..309e5ed029be1e731da99cbae98df6186eb0d628 100644 (file)
@@ -3844,13 +3844,14 @@ add_wrappers (MonoAotCompile *acfg)
                csig->params [1] = &mono_defaults.exception_class->byval_arg;
                add_method (acfg, get_runtime_invoke_sig (csig));
 
-               /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
-               csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
+               /* Assembly runtime-invoke (string, Assembly, bool) [DoAssemblyResolve] */
+               csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
                csig->hasthis = 1;
                csig->ret = &(mono_class_load_from_name (
                                                                                        mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
                csig->params [0] = &mono_defaults.string_class->byval_arg;
-               csig->params [1] = &mono_defaults.boolean_class->byval_arg;
+               csig->params [1] = &(mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
+               csig->params [2] = &mono_defaults.boolean_class->byval_arg;
                add_method (acfg, get_runtime_invoke_sig (csig));
 
                /* runtime-invoke used by finalizers */
@@ -8895,13 +8896,13 @@ emit_extra_methods (MonoAotCompile *acfg)
 static void
 generate_aotid (guint8* aotid)
 {
-       gpointer *rand_handle;
+       gpointer rand_handle;
        MonoError error;
 
        mono_rand_open ();
        rand_handle = mono_rand_init (NULL, 0);
 
-       mono_rand_try_get_bytes (rand_handle, aotid, 16, &error);
+       mono_rand_try_get_bytes (&rand_handle, aotid, 16, &error);
        mono_error_assert_ok (&error);
 
        mono_rand_close (rand_handle);
@@ -9813,7 +9814,7 @@ compile_methods (MonoAotCompile *acfg)
                        user_data [1] = acfg;
                        user_data [2] = frag;
                        
-                       handle = mono_threads_create_thread (compile_thread_main, (gpointer) user_data, 0, NULL);
+                       handle = mono_threads_create_thread (compile_thread_main, (gpointer) user_data, NULL, NULL);
                        g_ptr_array_add (threads, handle);
                }
                g_free (methods);
index 9bfbb44647b784d6b4181dab24f7666c35d4a123..8ba135ce1321da6d05b39b6e080ac940c4c03162 100644 (file)
@@ -71,6 +71,7 @@
 #include <mono/utils/mono-time.h>
 #include <mono/utils/mono-threads.h>
 #include <mono/utils/networking.h>
+#include <mono/utils/mono-proclib.h>
 #include "debugger-agent.h"
 #include "mini.h"
 #include "seq-points.h"
@@ -932,7 +933,7 @@ mono_debugger_agent_parse_options (char *options)
                /* Waiting for deferred attachment */
                agent_config.defer = TRUE;
                if (agent_config.address == NULL) {
-                       agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (getpid () % 1000));
+                       agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (mono_process_current_pid () % 1000));
                }
        }
 
@@ -1628,7 +1629,7 @@ stop_debugger_thread (void)
 static void
 start_debugger_thread (void)
 {
-       debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, 0, NULL);
+       debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, NULL, NULL);
        g_assert (debugger_thread_handle);
 }
 
index 6e06724a9f0ea42b1cdbde2ee17b88333099c2d2..e31628dc795b53151c8028fd03e04d7386e705c8 100644 (file)
@@ -1434,6 +1434,10 @@ mono_jit_parse_options (int argc, char * argv[])
                        
                        if (!mono_debugger_insert_breakpoint (argv [++i], FALSE))
                                fprintf (stderr, "Error: invalid method name '%s'\n", argv [i]);
+               } else if (strncmp (argv[i], "--gc-params=", 12) == 0) {
+                       mono_gc_params_set (argv[i] + 12);
+               } else if (strncmp (argv[i], "--gc-debug=", 11) == 0) {
+                       mono_gc_debug_set (argv[i] + 11);
                } else if (strcmp (argv [i], "--llvm") == 0) {
 #ifndef MONO_ARCH_LLVM_SUPPORTED
                        fprintf (stderr, "Mono Warning: --llvm not supported on this platform.\n");
@@ -1679,6 +1683,10 @@ mono_main (int argc, char* argv[])
                        switch_gc (argv, "sgen");
                } else if (strcmp (argv [i], "--gc=boehm") == 0) {
                        switch_gc (argv, "boehm");
+               } else if (strncmp (argv[i], "--gc-params=", 12) == 0) {
+                       mono_gc_params_set (argv[i] + 12);
+               } else if (strncmp (argv[i], "--gc-debug=", 11) == 0) {
+                       mono_gc_debug_set (argv[i] + 11);
                }
 #ifdef TARGET_OSX
                else if (strcmp (argv [i], "--arch=32") == 0) {
@@ -2113,7 +2121,7 @@ mono_main (int argc, char* argv[])
                        exit (1);
                }
 
-#ifdef HOST_WIN32
+#if defined(HOST_WIN32) && G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
                /* Detach console when executing IMAGE_SUBSYSTEM_WINDOWS_GUI on win32 */
                if (!enable_debugging && !mono_compile_aot && ((MonoCLIImageInfo*)(mono_assembly_get_image (assembly)->image_info))->cli_header.nt.pe_subsys_required == IMAGE_SUBSYSTEM_WINDOWS_GUI)
                        FreeConsole ();
index 919682acca6a9c5fb1d2d38456f16fabb01a9227..dbef0887519b5e12e85ba3320e952eef4a086c15 100644 (file)
@@ -152,6 +152,7 @@ void win32_seh_set_handler(int type, MonoW32ExceptionHandler handler)
 
 #endif /* TARGET_WIN32 */
 
+#ifndef DISABLE_JIT
 /*
  * mono_arch_get_restore_context:
  *
@@ -285,6 +286,7 @@ mono_arch_get_call_filter (MonoTrampInfo **info, gboolean aot)
 
        return start;
 }
+#endif /* !DISABLE_JIT */
 
 /* 
  * The first few arguments are dummy, to force the other arguments to be passed on
@@ -350,6 +352,7 @@ mono_amd64_resume_unwind (guint64 dummy1, guint64 dummy2, guint64 dummy3, guint6
        mono_resume_unwind (&ctx);
 }
 
+#ifndef DISABLE_JIT
 /*
  * get_throw_trampoline:
  *
@@ -496,6 +499,7 @@ mono_arch_get_throw_corlib_exception (MonoTrampInfo **info, gboolean aot)
 {
        return get_throw_trampoline (info, FALSE, TRUE, FALSE, FALSE, "throw_corlib_exception", aot);
 }
+#endif /* !DISABLE_JIT */
 
 /*
  * mono_arch_unwind_frame:
@@ -833,6 +837,7 @@ mono_amd64_get_original_ip (void)
        return lmf->rip;
 }
 
+#ifndef DISABLE_JIT
 GSList*
 mono_amd64_get_exception_trampolines (gboolean aot)
 {
@@ -851,6 +856,7 @@ mono_amd64_get_exception_trampolines (gboolean aot)
 
        return tramps;
 }
+#endif /* !DISABLE_JIT */
 
 void
 mono_arch_exceptions_init (void)
@@ -878,7 +884,7 @@ mono_arch_exceptions_init (void)
        }
 }
 
-#ifdef TARGET_WIN32
+#if defined(TARGET_WIN32) && !defined(DISABLE_JIT)
 
 /*
  * The mono_arch_unwindinfo* methods are used to build and add
@@ -1118,9 +1124,9 @@ mono_arch_unwindinfo_install_unwind_info (gpointer* monoui, gpointer code, guint
        RtlInstallFunctionTableCallback (((DWORD64)code) | 0x3, (DWORD64)code, code_size, MONO_GET_RUNTIME_FUNCTION_CALLBACK, code, NULL);
 }
 
-#endif
+#endif /* defined(TARGET_WIN32) !defined(DISABLE_JIT) */
 
-#if MONO_SUPPORT_TASKLETS
+#if MONO_SUPPORT_TASKLETS && !defined(DISABLE_JIT)
 MonoContinuationRestore
 mono_tasklets_arch_restore (void)
 {
@@ -1172,7 +1178,7 @@ mono_tasklets_arch_restore (void)
        saved = start;
        return (MonoContinuationRestore)saved;
 }
-#endif
+#endif /* MONO_SUPPORT_TASKLETS && !defined(DISABLE_JIT) */
 
 /*
  * mono_arch_setup_resume_sighandler_ctx:
@@ -1190,3 +1196,56 @@ mono_arch_setup_resume_sighandler_ctx (MonoContext *ctx, gpointer func)
                MONO_CONTEXT_SET_SP (ctx, (guint64)MONO_CONTEXT_GET_SP (ctx) - 8);
        MONO_CONTEXT_SET_IP (ctx, func);
 }
+
+#ifdef DISABLE_JIT
+gpointer
+mono_arch_get_restore_context (MonoTrampInfo **info, gboolean aot)
+{
+       g_assert_not_reached ();
+       return NULL;
+}
+
+gpointer
+mono_arch_get_call_filter (MonoTrampInfo **info, gboolean aot)
+{
+       g_assert_not_reached ();
+       return NULL;
+}
+
+gpointer
+mono_arch_get_throw_exception (MonoTrampInfo **info, gboolean aot)
+{
+       g_assert_not_reached ();
+       return NULL;
+}
+
+gpointer
+mono_arch_get_rethrow_exception (MonoTrampInfo **info, gboolean aot)
+{
+       g_assert_not_reached ();
+       return NULL;
+}
+
+gpointer
+mono_arch_get_throw_corlib_exception (MonoTrampInfo **info, gboolean aot)
+{
+       g_assert_not_reached ();
+       return NULL;
+}
+
+GSList*
+mono_amd64_get_exception_trampolines (gboolean aot)
+{
+       g_assert_not_reached ();
+       return NULL;
+}
+#endif /* DISABLE_JIT */
+
+#if !MONO_SUPPORT_TASKLETS || defined(DISABLE_JIT)
+MonoContinuationRestore
+mono_tasklets_arch_restore (void)
+{
+       g_assert_not_reached ();
+       return NULL;
+}
+#endif /* !MONO_SUPPORT_TASKLETS || defined(DISABLE_JIT) */
index 80638b5048e6edf80854c7509ee3b7d18292cd5c..018619449191a8cf24899b7d1cba6f55519a85d0 100644 (file)
@@ -1272,7 +1272,6 @@ class Tests
                c.throw_catch_t ();
                return 0;
        }
-
 }
 
 #if !__MOBILE__
index 88f8c2ebb22b780a3c461daf2d8b62e6370f3e68..65151b07024e8d1a2199d9b76119cd07be48c527 100644 (file)
@@ -1907,6 +1907,40 @@ public class Tests
                bool success = zz == 0xAAAAAAAAAAAAAAAA;
                return success ? 20 : 1;
        }
+
+       void gsharedvt_try_at_offset_0<T> (ref T disposable)
+               where T : class, IDisposable {
+                       try {
+                               disposable.Dispose ();
+                       } finally {
+                               disposable = null;
+                       }
+               }
+
+       [MethodImplAttribute (MethodImplOptions.NoInlining)]
+       static DateTimeOffset gsharedvt_vphi_inner<T> (T t) {
+               return DateTimeOffset.MinValue;
+       }
+
+       static DateTimeOffset gsharedvt_vphi<T> (T t) {
+               int[] arr = new int [10];
+
+               try {
+                       DateTimeOffset v;
+                       if (arr [0] == 0)
+                               v = gsharedvt_vphi_inner (t);
+                       else
+                               v = gsharedvt_vphi_inner (t);
+                       return v;
+               } catch {
+                       return DateTimeOffset.MinValue;
+               }
+       }
+
+       static int test_0_gsharedvt_vphi_volatile () {
+               gsharedvt_vphi (0);
+               return 0;
+       }
 }
 
 // #13191
index 04373359fb46ead9bc1ea8d96249d33ee4c15948..e19b91c5fcab116663a5971c7d925362daaeaadf 100644 (file)
@@ -171,6 +171,8 @@ mono_strength_reduction_division (MonoCompile *cfg, MonoInst *ins)
                                ins->inst_imm = power2;
                                break;
                        }
+                       if (cfg->backend->disable_div_with_mul)
+                               break;
                        allocated_vregs = TRUE;
                        /*
                         * Replacement of unsigned division with multiplication,
@@ -243,6 +245,8 @@ mono_strength_reduction_division (MonoCompile *cfg, MonoInst *ins)
                                break;
                        }
 
+                       if (cfg->backend->disable_div_with_mul)
+                               break;
                        /*
                         * Replacement of signed division with multiplication,
                         * shifts and additions Hacker's Delight, chapter 10-6.
index be20f3e03397d9063e27406e77085ef5a05c8ea7..ad00295b8d291f8c9d4a7d1f60cd8e34fa15b088 100644 (file)
@@ -8479,7 +8479,8 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
 
        /* we use a separate basic block for the initialization code */
        NEW_BBLOCK (cfg, init_localsbb);
-       cfg->bb_init = init_localsbb;
+       if (cfg->method == method)
+               cfg->bb_init = init_localsbb;
        init_localsbb->real_offset = cfg->real_offset;
        start_bblock->next_bb = init_localsbb;
        init_localsbb->next_bb = cfg->cbb;
@@ -13690,7 +13691,10 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
        if (cfg->method == method) {
                MonoBasicBlock *bb;
                for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
-                       bb->region = mono_find_block_region (cfg, bb->real_offset);
+                       if (bb == cfg->bb_init)
+                               bb->region = -1;
+                       else
+                               bb->region = mono_find_block_region (cfg, bb->real_offset);
                        if (cfg->spvars)
                                mono_create_spvar_for_region (cfg, bb->region);
                        if (cfg->verbose_level > 2)
index fa24b73f186132b30eb3d4b358664d3f59e2d4f6..903739445c1a86806640ce725f856958421865f6 100644 (file)
@@ -1290,7 +1290,10 @@ build_native_trace (MonoError *error)
 #if defined (HAVE_BACKTRACE_SYMBOLS) && defined (TARGET_ARM)
        MonoArray *res;
        void *native_trace [MAX_UNMANAGED_BACKTRACE];
-       int size = backtrace (native_trace, MAX_UNMANAGED_BACKTRACE);
+       int size = -1;
+       MONO_ENTER_GC_SAFE;
+       size = backtrace (native_trace, MAX_UNMANAGED_BACKTRACE);
+       MONO_EXIT_GC_SAFE;
        int i;
 
        if (!size)
index 54873523202042720ff13d345b428e48f2bbab1e..117260ff2c69be08a4c753aab164357cb23af4d1 100644 (file)
@@ -148,6 +148,7 @@ typedef struct {
        LLVMValueRef rgctx_arg;
        LLVMValueRef this_arg;
        LLVMTypeRef *vreg_types;
+       gboolean *is_vphi;
        LLVMTypeRef method_type;
        LLVMBasicBlockRef init_bb, inited_bb;
        gboolean *is_dead;
@@ -1740,6 +1741,8 @@ get_handler_clause (MonoCompile *cfg, MonoBasicBlock *bb)
 static MonoExceptionClause *
 get_most_deep_clause (MonoCompile *cfg, EmitContext *ctx, MonoBasicBlock *bb)
 {
+       if (bb == cfg->bb_init)
+               return NULL;
        // Since they're sorted by nesting we just need
        // the first one that the bb is a member of
        for (int i = 0; i < cfg->header->num_clauses; i++) {
@@ -6566,7 +6569,7 @@ process_bb (EmitContext *ctx, MonoBasicBlock *bb)
 
                /* Convert the value to the type required by phi nodes */
                if (spec [MONO_INST_DEST] != ' ' && !MONO_IS_STORE_MEMBASE (ins) && ctx->vreg_types [ins->dreg]) {
-                       if (!values [ins->dreg])
+                       if (ctx->is_vphi [ins->dreg])
                                /* vtypes */
                                values [ins->dreg] = addresses [ins->dreg];
                        else
@@ -6715,6 +6718,7 @@ free_ctx (EmitContext *ctx)
        g_free (ctx->values);
        g_free (ctx->addresses);
        g_free (ctx->vreg_types);
+       g_free (ctx->is_vphi);
        g_free (ctx->vreg_cli_types);
        g_free (ctx->is_dead);
        g_free (ctx->unreachable);
@@ -6775,6 +6779,7 @@ mono_llvm_emit_method (MonoCompile *cfg)
         */
        ctx->addresses = g_new0 (LLVMValueRef, cfg->next_vreg);
        ctx->vreg_types = g_new0 (LLVMTypeRef, cfg->next_vreg);
+       ctx->is_vphi = g_new0 (gboolean, cfg->next_vreg);
        ctx->vreg_cli_types = g_new0 (MonoType*, cfg->next_vreg);
        ctx->phi_values = g_ptr_array_sized_new (256);
        /* 
@@ -7123,8 +7128,11 @@ emit_method_inner (EmitContext *ctx)
                                for (i = 0; i < ins->inst_phi_args [0]; i++) {
                                        int sreg1 = ins->inst_phi_args [i + 1];
                                        
-                                       if (sreg1 != -1)
+                                       if (sreg1 != -1) {
+                                               if (ins->opcode == OP_VPHI)
+                                                       ctx->is_vphi [sreg1] = TRUE;
                                                ctx->vreg_types [sreg1] = phi_type;
+                                       }
                                }
                                break;
                                }
index 8af84338759ecf8629b8b541dfb679058df08b2e..ea7474dd28bbfbfdd1a6bf703467bf5e23b37141 100644 (file)
@@ -2175,12 +2175,6 @@ mono_arch_decompose_long_opts (MonoCompile *cfg, MonoInst *ins)
        int tmp5 = -1;
 
        switch (ins->opcode) {
-#if 0
-       case OP_LCOMPARE:
-       case OP_LCOMPARE_IMM:
-               mono_print_ins (ins);
-               g_assert_not_reached ();
-#endif
        case OP_LADD:
                tmp1 = mono_alloc_ireg (cfg);
                MONO_EMIT_NEW_BIALU (cfg, OP_IADD, ins->dreg+1, ins->sreg1+1, ins->sreg2+1);
@@ -2217,17 +2211,6 @@ mono_arch_decompose_long_opts (MonoCompile *cfg, MonoInst *ins)
                NULLIFY_INS(ins);
                break;
 
-       case OP_LMUL:
-       case OP_LDIV:
-       case OP_LDIV_UN:
-       case OP_LREM:
-       case OP_LREM_UN:
-       case OP_LSHL:
-       case OP_LSHR:
-       case OP_LSHR_UN:
-               mono_print_ins (ins);
-               g_assert_not_reached ();
-
        case OP_LNEG:
                tmp1 = mono_alloc_ireg (cfg);
                MONO_EMIT_NEW_BIALU (cfg, OP_ISUB, ins->dreg+1, mips_zero, ins->sreg1+1);
@@ -2237,27 +2220,6 @@ mono_arch_decompose_long_opts (MonoCompile *cfg, MonoInst *ins)
                NULLIFY_INS(ins);
                break;
 
-#if 0
-       case OP_LNOT:
-#endif
-#if 0
-       case OP_LCONV_TO_I1:
-       case OP_LCONV_TO_I2:
-       case OP_LCONV_TO_I4:
-       case OP_LCONV_TO_I8:
-       case OP_LCONV_TO_R4:
-       case OP_LCONV_TO_R8:
-       case OP_LCONV_TO_U4:
-       case OP_LCONV_TO_U8:
-       case OP_LCONV_TO_U2:
-       case OP_LCONV_TO_U1:
-       case OP_LCONV_TO_I:
-       case OP_LCONV_TO_OVF_I:
-       case OP_LCONV_TO_OVF_U:
-#endif
-               mono_print_ins (ins);
-               g_assert_not_reached ();
-
        case OP_LADD_OVF:
                tmp1 = mono_alloc_ireg (cfg);
                tmp2 = mono_alloc_ireg (cfg);
@@ -2310,11 +2272,6 @@ mono_arch_decompose_long_opts (MonoCompile *cfg, MonoInst *ins)
                NULLIFY_INS(ins);
                break;
 
-       case OP_LMUL_OVF:
-       case OP_LMUL_OVF_UN:
-               mono_print_ins (ins);
-               g_assert_not_reached ();
-
        case OP_LSUB_OVF:
                tmp1 = mono_alloc_ireg (cfg);
                tmp2 = mono_alloc_ireg (cfg);
@@ -2361,60 +2318,6 @@ mono_arch_decompose_long_opts (MonoCompile *cfg, MonoInst *ins)
                MONO_EMIT_NEW_COMPARE_EXC (cfg, NE_UN, tmp2, mips_zero, "OverflowException");
                NULLIFY_INS(ins);
                break;
-#if 0
-       case OP_LCONV_TO_OVF_I1_UN:
-       case OP_LCONV_TO_OVF_I2_UN:
-       case OP_LCONV_TO_OVF_I4_UN:
-       case OP_LCONV_TO_OVF_I8_UN:
-       case OP_LCONV_TO_OVF_U1_UN:
-       case OP_LCONV_TO_OVF_U2_UN:
-       case OP_LCONV_TO_OVF_U4_UN:
-       case OP_LCONV_TO_OVF_U8_UN:
-       case OP_LCONV_TO_OVF_I_UN:
-       case OP_LCONV_TO_OVF_U_UN:
-       case OP_LCONV_TO_OVF_I1:
-       case OP_LCONV_TO_OVF_U1:
-       case OP_LCONV_TO_OVF_I2:
-       case OP_LCONV_TO_OVF_U2:
-       case OP_LCONV_TO_OVF_I4:
-       case OP_LCONV_TO_OVF_U4:
-       case OP_LCONV_TO_OVF_I8:
-       case OP_LCONV_TO_OVF_U8:
-#endif
-       case OP_LCEQ:
-       case OP_LCGT:
-       case OP_LCGT_UN:
-       case OP_LCLT:
-       case OP_LCLT_UN:
-#if 0
-       case OP_LCONV_TO_R_UN:
-       case OP_LCONV_TO_U:
-#endif
-       case OP_LMUL_IMM:
-       case OP_LSHL_IMM:
-       case OP_LSHR_IMM:
-       case OP_LSHR_UN_IMM:
-       case OP_LDIV_IMM:
-       case OP_LDIV_UN_IMM:
-       case OP_LREM_IMM:
-       case OP_LREM_UN_IMM:
-       case OP_LBEQ:
-       case OP_LBGE:
-       case OP_LBGT:
-       case OP_LBLE:
-       case OP_LBLT:
-       case OP_LBNE_UN:
-       case OP_LBGE_UN:
-       case OP_LBGT_UN:
-       case OP_LBLE_UN:
-       case OP_LBLT_UN:
-               mono_print_ins (ins);
-               g_assert_not_reached ();
-#if 0
-       case OP_LCONV_TO_R8_2:
-       case OP_LCONV_TO_R4_2:
-       case OP_LCONV_TO_R_UN_2:
-#endif
        case OP_LCONV_TO_OVF_I4_2:
                tmp1 = mono_alloc_ireg (cfg);
 
@@ -2424,14 +2327,6 @@ mono_arch_decompose_long_opts (MonoCompile *cfg, MonoInst *ins)
                MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, ins->dreg, ins->sreg1);
                NULLIFY_INS(ins);
                break;
-
-       case OP_LMIN_UN:
-       case OP_LMAX_UN:
-       case OP_LMIN:
-       case OP_LMAX:
-               mono_print_ins (ins);
-               g_assert_not_reached ();
-
        default:
                break;
        }
index 06c533aee46cffa33e738dfd1b665dd6685f85e9..df179bd2545334cd8cf1eca629efc0f54b487a43 100644 (file)
@@ -233,6 +233,15 @@ typedef struct MonoCompileArch {
 #define MONO_ARCH_EMULATE_FREM 1
 #endif
 
+/*
+ * mips backend misses some instructions that enable emitting of optimal
+ * code on other targets and, additionally, the register allocator gets
+ * confused by this optimization, failing to allocate all hw regs.
+ */
+#if SIZEOF_REGISTER == 4
+#define MONO_ARCH_NO_DIV_WITH_MUL
+#endif
+
 #if SIZEOF_REGISTER == 8
 #define MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS
 #endif
diff --git a/mono/mini/mini-windows-uwp.c b/mono/mini/mini-windows-uwp.c
new file mode 100644 (file)
index 0000000..c2367aa
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * mini-windows-uwp.c: UWP profiler stat support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#include <config.h>
+#include <glib.h>
+
+#if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
+#include <Windows.h>
+
+void
+mono_runtime_setup_stat_profiler (void)
+{
+       g_unsupported_api ("OpenThread, GetThreadContext");
+       SetLastError (ERROR_NOT_SUPPORTED);
+       return;
+}
+
+void
+mono_runtime_shutdown_stat_profiler (void)
+{
+       g_unsupported_api ("OpenThread, GetThreadContext");
+       SetLastError (ERROR_NOT_SUPPORTED);
+       return;
+}
+
+static gboolean
+mono_setup_thread_context(DWORD thread_id, MonoContext *mono_context)
+{
+       memset (mono_context, 0, sizeof (MonoContext));
+       return FALSE;
+}
+
+#else /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_mini_windows_uwp_quiet_lnk4221(void) {}
+#endif
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
index e7764e91beb749709474b294aef00cb5c30932ce..2aa3a7b75d1bc21d177500be8388a7448a6991fd 100644 (file)
@@ -44,6 +44,7 @@
 #include <mono/utils/dtrace.h>
 
 #include "mini.h"
+#include "mini-windows.h"
 #include <string.h>
 #include <ctype.h>
 #include "trace.h"
@@ -51,7 +52,7 @@
 
 #include "jit-icalls.h"
 
-#ifdef _WIN32
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 #include <mmsystem.h>
 #endif
 
@@ -91,16 +92,17 @@ MONO_SIG_HANDLER_SIGNATURE (mono_chain_signal)
        return TRUE;
 }
 
-static HANDLE win32_main_thread;
-static MMRESULT win32_timer;
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+static MMRESULT        g_timer_event = 0;
+static HANDLE g_timer_main_thread = INVALID_HANDLE_VALUE;
 
-static void CALLBACK
-win32_time_proc (UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2)
+static VOID
+thread_timer_expired (HANDLE thread)
 {
        CONTEXT context;
 
        context.ContextFlags = CONTEXT_CONTROL;
-       if (GetThreadContext (win32_main_thread, &context)) {
+       if (GetThreadContext (thread, &context)) {
 #ifdef _WIN64
                mono_profiler_stat_hit ((guchar *) context.Rip, &context);
 #else
@@ -109,57 +111,75 @@ win32_time_proc (UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2)
        }
 }
 
-void
-mono_runtime_setup_stat_profiler (void)
+static VOID CALLBACK
+timer_event_proc (UINT uID, UINT uMsg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
 {
-       static int inited = 0;
-       TIMECAPS timecaps;
+       thread_timer_expired ((HANDLE)dwUser);
+}
 
-       if (inited)
-               return;
+static VOID
+stop_profiler_timer_event (void)
+{
+       if (g_timer_event != 0) {
+
+               timeKillEvent (g_timer_event);
+               g_timer_event = 0;
+       }
+
+       if (g_timer_main_thread != INVALID_HANDLE_VALUE) {
+
+               CloseHandle (g_timer_main_thread);
+               g_timer_main_thread = INVALID_HANDLE_VALUE;
+       }
+}
+
+static VOID
+start_profiler_timer_event (void)
+{
+       g_return_if_fail (g_timer_main_thread == INVALID_HANDLE_VALUE && g_timer_event == 0);
+
+       TIMECAPS timecaps;
 
-       inited = 1;
        if (timeGetDevCaps (&timecaps, sizeof (timecaps)) != TIMERR_NOERROR)
                return;
 
-       if ((win32_main_thread = OpenThread (READ_CONTROL | THREAD_GET_CONTEXT, FALSE, GetCurrentThreadId ())) == NULL)
+       g_timer_main_thread = OpenThread (READ_CONTROL | THREAD_GET_CONTEXT, FALSE, GetCurrentThreadId ());
+       if (g_timer_main_thread == NULL)
                return;
 
        if (timeBeginPeriod (1) != TIMERR_NOERROR)
                return;
 
-       if ((win32_timer = timeSetEvent (1, 0, (LPTIMECALLBACK)win32_time_proc, (DWORD_PTR)NULL, TIME_PERIODIC)) == 0) {
+       g_timer_event = timeSetEvent (1, 0, (LPTIMECALLBACK)timer_event_proc, (DWORD_PTR)g_timer_main_thread, TIME_PERIODIC | TIME_KILL_SYNCHRONOUS);
+       if (g_timer_event == 0) {
                timeEndPeriod (1);
                return;
        }
 }
 
+void
+mono_runtime_setup_stat_profiler (void)
+{
+       start_profiler_timer_event ();
+       return;
+}
+
 void
 mono_runtime_shutdown_stat_profiler (void)
 {
+       stop_profiler_timer_event ();
+       return;
 }
 
 gboolean
-mono_thread_state_init_from_handle (MonoThreadUnwindState *tctx, MonoThreadInfo *info)
+mono_setup_thread_context(DWORD thread_id, MonoContext *mono_context)
 {
-       DWORD id = mono_thread_info_get_tid (info);
        HANDLE handle;
        CONTEXT context;
-       DWORD result;
-       MonoContext *ctx;
-       MonoJitTlsData *jit_tls;
-       void *domain;
-       MonoLMF *lmf = NULL;
-       gpointer *addr;
-
-       tctx->valid = FALSE;
-       tctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] = NULL;
-       tctx->unwind_data [MONO_UNWIND_DATA_LMF] = NULL;
-       tctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = NULL;
 
-       g_assert (id != GetCurrentThreadId ());
+       g_assert (thread_id != GetCurrentThreadId ());
 
-       handle = OpenThread (THREAD_ALL_ACCESS, FALSE, id);
+       handle = OpenThread (THREAD_ALL_ACCESS, FALSE, thread_id);
        g_assert (handle);
 
        context.ContextFlags = CONTEXT_INTEGER | CONTEXT_CONTROL;
@@ -172,10 +192,29 @@ mono_thread_state_init_from_handle (MonoThreadUnwindState *tctx, MonoThreadInfo
        g_assert (context.ContextFlags & CONTEXT_INTEGER);
        g_assert (context.ContextFlags & CONTEXT_CONTROL);
 
-       ctx = &tctx->ctx;
+       memset (mono_context, 0, sizeof (MonoContext));
+       mono_sigctx_to_monoctx (&context, mono_context);
 
-       memset (ctx, 0, sizeof (MonoContext));
-       mono_sigctx_to_monoctx (&context, ctx);
+       CloseHandle (handle);
+       return TRUE;
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+gboolean
+mono_thread_state_init_from_handle (MonoThreadUnwindState *tctx, MonoThreadInfo *info)
+{
+       DWORD id = mono_thread_info_get_tid (info);
+       MonoJitTlsData *jit_tls;
+       void *domain;
+       MonoLMF *lmf = NULL;
+       gpointer *addr;
+
+       tctx->valid = FALSE;
+       tctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] = NULL;
+       tctx->unwind_data [MONO_UNWIND_DATA_LMF] = NULL;
+       tctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = NULL;
+
+       mono_setup_thread_context(id, &tctx->ctx);
 
        /* mono_set_jit_tls () sets this */
        jit_tls = mono_thread_info_tls_get (info, TLS_KEY_JIT_TLS);
@@ -203,4 +242,3 @@ mono_thread_state_init_from_handle (MonoThreadUnwindState *tctx, MonoThreadInfo
 
        return TRUE;
 }
-
diff --git a/mono/mini/mini-windows.h b/mono/mini/mini-windows.h
new file mode 100644 (file)
index 0000000..337b1ab
--- /dev/null
@@ -0,0 +1,15 @@
+#ifndef __MONO_MINI_WINDOWS_H__
+#define __MONO_MINI_WINDOWS_H__
+
+#include <config.h>
+#include <glib.h>
+
+#ifdef HOST_WIN32
+#include "Windows.h"
+#include "mini.h"
+#include "mono/utils/mono-context.h"
+
+gboolean
+mono_setup_thread_context(DWORD thread_id, MonoContext *mono_context);
+#endif /* HOST_WIN32 */
+#endif /* __MONO_MINI_WINDOWS_H__ */
index f6ce09236813eef8630c1ccb9a30322eeaa4b715..51ca3d5c79cc415a49c4f92c14bccba3c6be9bec 100644 (file)
@@ -3175,6 +3175,9 @@ init_backend (MonoBackend *backend)
 #ifdef MONO_ARCH_DYN_CALL_PARAM_AREA
        backend->dyn_call_param_area = MONO_ARCH_DYN_CALL_PARAM_AREA;
 #endif
+#ifdef MONO_ARCH_NO_DIV_WITH_MUL
+       backend->disable_div_with_mul = 1;
+#endif
 }
 
 /*
index ab2ba4e9dcdf58c7e41b8d3ff7e52a53873a5ccf..dd24cd540b12b9ff16146e1192d68942ef79c60e 100644 (file)
@@ -1498,6 +1498,7 @@ typedef struct {
        guint            need_got_var : 1;
        guint            need_div_check : 1;
        guint            no_unaligned_access : 1;
+       guint            disable_div_with_mul : 1;
        int              monitor_enter_adjustment;
        int              dyn_call_param_area;
 } MonoBackend;
index cf769a9e5305d3319ac8e1eed0e4167cc6102b6c..7d7cc41aa618c99bb060fd69eedcf9441ba4b559 100644 (file)
@@ -33,6 +33,7 @@
 
 #define IS_REX(inst) (((inst) >= 0x40) && ((inst) <= 0x4f))
 
+#ifndef DISABLE_JIT
 /*
  * mono_arch_get_unbox_trampoline:
  * @m: method pointer
@@ -110,6 +111,7 @@ mono_arch_get_static_rgctx_trampoline (MonoMethod *m, MonoMethodRuntimeGenericCo
 
        return start;
 }
+#endif /* !DISABLE_JIT */
 
 #ifdef _WIN64
 // Workaround lack of Valgrind support for 64-bit Windows
@@ -171,6 +173,7 @@ mono_arch_patch_callsite (guint8 *method_start, guint8 *orig_code, guint8 *addr)
        }
 }
 
+#ifndef DISABLE_JIT
 guint8*
 mono_arch_create_llvm_native_thunk (MonoDomain *domain, guint8 *addr)
 {
@@ -190,6 +193,7 @@ mono_arch_create_llvm_native_thunk (MonoDomain *domain, guint8 *addr)
        mono_profiler_code_buffer_new (thunk_start, thunk_code - thunk_start, MONO_PROFILER_CODE_BUFFER_HELPER, NULL);
        return addr;
 }
+#endif /* !DISABLE_JIT */
 
 void
 mono_arch_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
@@ -208,6 +212,7 @@ mono_arch_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *a
        InterlockedExchangePointer (plt_jump_table_entry, addr);
 }
 
+#ifndef DISABLE_JIT
 static void
 stack_unaligned (MonoTrampolineType tramp_type)
 {
@@ -756,6 +761,7 @@ mono_arch_invalidate_method (MonoJitInfo *ji, void *func, gpointer func_arg)
        x86_push_imm (code, (guint64)func_arg);
        amd64_call_reg (code, AMD64_R11);
 }
+#endif /* !DISABLE_JIT */
 
 gpointer
 mono_amd64_handler_block_trampoline_helper (void)
@@ -764,6 +770,7 @@ mono_amd64_handler_block_trampoline_helper (void)
        return jit_tls->handler_block_return_address;
 }
 
+#ifndef DISABLE_JIT
 gpointer
 mono_arch_create_handler_block_trampoline (MonoTrampInfo **info, gboolean aot)
 {
@@ -832,6 +839,7 @@ mono_arch_create_handler_block_trampoline (MonoTrampInfo **info, gboolean aot)
 
        return buf;
 }
+#endif /* !DISABLE_JIT */
 
 /*
  * mono_arch_get_call_target:
@@ -862,6 +870,7 @@ mono_arch_get_plt_info_offset (guint8 *plt_entry, mgreg_t *regs, guint8 *code)
        return *(guint32*)(plt_entry + 6);
 }
 
+#ifndef DISABLE_JIT
 /*
  * mono_arch_create_sdb_trampoline:
  *
@@ -960,3 +969,69 @@ mono_arch_create_sdb_trampoline (gboolean single_step, MonoTrampInfo **info, gbo
 
        return buf;
 }
+#endif /* !DISABLE_JIT */
+
+#ifdef DISABLE_JIT
+gpointer
+mono_arch_get_unbox_trampoline (MonoMethod *m, gpointer addr)
+{
+       g_assert_not_reached ();
+       return NULL;
+}
+
+gpointer
+mono_arch_get_static_rgctx_trampoline (MonoMethod *m, MonoMethodRuntimeGenericContext *mrgctx, gpointer addr)
+{
+       g_assert_not_reached ();
+       return NULL;
+}
+
+gpointer
+mono_arch_create_rgctx_lazy_fetch_trampoline (guint32 slot, MonoTrampInfo **info, gboolean aot)
+{
+       g_assert_not_reached ();
+       return NULL;
+}
+
+guchar*
+mono_arch_create_generic_trampoline (MonoTrampolineType tramp_type, MonoTrampInfo **info, gboolean aot)
+{
+       g_assert_not_reached ();
+       return NULL;
+}
+
+gpointer
+mono_arch_create_specific_trampoline (gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
+{
+       g_assert_not_reached ();
+       return NULL;
+}
+
+gpointer
+mono_arch_create_general_rgctx_lazy_fetch_trampoline (MonoTrampInfo **info, gboolean aot)
+{
+       g_assert_not_reached ();
+       return NULL;
+}
+
+gpointer
+mono_arch_create_handler_block_trampoline (MonoTrampInfo **info, gboolean aot)
+{
+        g_assert_not_reached ();
+        return NULL;
+}
+
+void
+mono_arch_invalidate_method (MonoJitInfo *ji, void *func, gpointer func_arg)
+{
+       g_assert_not_reached ();
+       return;
+}
+
+guint8*
+mono_arch_create_sdb_trampoline (gboolean single_step, MonoTrampInfo **info, gboolean aot)
+{
+       g_assert_not_reached ();
+       return NULL;
+}
+#endif /* DISABLE_JIT */
index ae6c72067e047d2c9b0a727dbd65ff964c624b4d..67741d99d34f14bbf06ca8335ed7a63bc4b23908 100644 (file)
@@ -4471,9 +4471,6 @@ runtime_initialized (MonoProfiler *profiler)
 {
        InterlockedWrite (&runtime_inited, 1);
 
-       start_writer_thread (profiler);
-       start_dumper_thread (profiler);
-
        register_counter ("Sample events allocated", &sample_allocations_ctr);
        register_counter ("Log buffers allocated", &buffer_allocations_ctr);
 
@@ -4530,7 +4527,14 @@ runtime_initialized (MonoProfiler *profiler)
 
        counters_init (profiler);
 
+       /*
+        * We must start the helper thread before the writer thread. This is
+        * because the helper thread sets up the command port which is written to
+        * the log header by the writer thread.
+        */
        start_helper_thread (profiler);
+       start_writer_thread (profiler);
+       start_dumper_thread (profiler);
 }
 
 static MonoProfiler*
index 9fe2f3ceeb4a62b9fc16be861e6d28179fcaac1c..62039f7267901a805e94c8e1fb79c4c7c72a9dca 100644 (file)
@@ -110,4 +110,9 @@ void mono_gc_memmove_aligned (void *dest, const void *src, size_t size);
 
 FILE *mono_gc_get_logfile (void);
 
+/* equivalent to options set via MONO_GC_PARAMS */
+void mono_gc_params_set (const char* options);
+/* equivalent to options set via MONO_GC_DEBUG */
+void mono_gc_debug_set (const char* options);
+
 #endif
index f83cffc919e0364ae1aae42c0513fba6699f66c7..2fdd86c2bf0613f7e75129c417d5a3341f82c1a4 100644 (file)
@@ -290,6 +290,8 @@ static SGEN_TV_DECLARE (time_major_conc_collection_end);
 
 int gc_debug_level = 0;
 FILE* gc_debug_file;
+static char* gc_params_options;
+static char* gc_debug_options;
 
 /*
 void
@@ -990,6 +992,24 @@ mono_gc_get_logfile (void)
        return gc_debug_file;
 }
 
+void
+mono_gc_params_set (const char* options)
+{
+       if (gc_params_options)
+               g_free (gc_params_options);
+
+       gc_params_options = g_strdup (options);
+}
+
+void
+mono_gc_debug_set (const char* options)
+{
+       if (gc_debug_options)
+               g_free (gc_debug_options);
+
+       gc_debug_options = g_strdup (options);
+}
+
 static void
 scan_finalizer_entries (SgenPointerQueue *fin_queue, ScanCopyContext ctx)
 {
@@ -2735,6 +2755,8 @@ sgen_gc_init (void)
        char **opts, **ptr;
        char *major_collector_opt = NULL;
        char *minor_collector_opt = NULL;
+       char *params_opts = NULL;
+       char *debug_opts = NULL;
        size_t max_heap = 0;
        size_t soft_limit = 0;
        int result;
@@ -2772,8 +2794,12 @@ sgen_gc_init (void)
 
        mono_coop_mutex_init (&sgen_interruption_mutex);
 
-       if ((env = g_getenv (MONO_GC_PARAMS_NAME))) {
-               opts = g_strsplit (env, ",", -1);
+       if ((env = g_getenv (MONO_GC_PARAMS_NAME)) || gc_params_options) {
+               params_opts = g_strdup_printf ("%s,%s", gc_params_options ? gc_params_options : "", env ? env : "");
+       }
+
+       if (params_opts) {
+               opts = g_strsplit (params_opts, ",", -1);
                for (ptr = opts; *ptr; ++ptr) {
                        char *opt = *ptr;
                        if (g_str_has_prefix (opt, "major=")) {
@@ -2975,15 +3001,22 @@ sgen_gc_init (void)
        if (minor_collector_opt)
                g_free (minor_collector_opt);
 
+       if (params_opts)
+               g_free (params_opts);
+
        alloc_nursery ();
 
        sgen_pinning_init ();
        sgen_cement_init (cement_enabled);
 
-       if ((env = g_getenv (MONO_GC_DEBUG_NAME))) {
+       if ((env = g_getenv (MONO_GC_DEBUG_NAME)) || gc_debug_options) {
+               debug_opts = g_strdup_printf ("%s,%s", gc_debug_options ? gc_debug_options  : "", env ? env : "");
+       }
+
+       if (debug_opts) {
                gboolean usage_printed = FALSE;
 
-               opts = g_strsplit (env, ",", -1);
+               opts = g_strsplit (debug_opts, ",", -1);
                for (ptr = opts; ptr && *ptr; ptr ++) {
                        char *opt = *ptr;
                        if (!strcmp (opt, ""))
@@ -3114,6 +3147,9 @@ sgen_gc_init (void)
                g_strfreev (opts);
        }
 
+       if (debug_opts)
+               g_free (debug_opts);
+
        if (check_mark_bits_after_major_collection)
                nursery_clear_policy = CLEAR_AT_GC;
 
index 84ea7d4549a9b72c2179c676fc5d1dccf9a63feb..e8c0d7ab595a74fa63e86d3a8e03e087df4fd542 100644 (file)
@@ -65,12 +65,13 @@ block_size (size_t slot_size)
        static int pagesize = -1;
 
        int size;
+       size_t aligned_slot_size = SGEN_ALIGN_UP_TO (slot_size, SIZEOF_VOID_P);
 
        if (pagesize == -1)
                pagesize = mono_pagesize ();
 
        for (size = pagesize; size < LOCK_FREE_ALLOC_SB_MAX_SIZE; size <<= 1) {
-               if (slot_size * 2 <= LOCK_FREE_ALLOC_SB_USABLE_SIZE (size))
+               if (aligned_slot_size * 2 <= LOCK_FREE_ALLOC_SB_USABLE_SIZE (size))
                        return size;
        }
        return LOCK_FREE_ALLOC_SB_MAX_SIZE;
@@ -292,6 +293,9 @@ sgen_init_internal_allocator (void)
                 * so that we do not get different block sizes for sizes that should go to the same one
                 */
                g_assert (allocator_sizes [index_for_size (max_size)] == max_size);
+               g_assert (block_size (max_size) == size);
+               if (size < LOCK_FREE_ALLOC_SB_MAX_SIZE)
+                       g_assert (block_size (max_size + 1) == size << 1);
        }
 }
 
index de70fe0b446e5c46d283e401eb4d1f264fd844bf..9f3996923b4931e3420e9811db9233fdf3d60852 100644 (file)
@@ -140,6 +140,7 @@ BASE_TEST_MOBILE_STATIC_NOT_SUPPORTED= \
        threadpool-exceptions7.cs # Needs AppDomains \
        cross-domain.cs # Needs AppDomains \
        generic-unloading.2.cs # Needs AppDomains \
+       namedmutex-destroy-race.cs # needs named Mutex \
        thread6.cs # On MOBILE, ThreadAbortException doesn't have necessary field for this test
 
 # Disabled until ?mcs is fixed
@@ -468,7 +469,6 @@ BASE_TEST_CS_SRC_UNIVERSAL=         \
        bug-29585.cs    \
        priority.cs     \
        abort-cctor.cs  \
-       namedmutex-destroy-race.cs      \
        thread-native-exit.cs
 
 if INSTALL_MOBILE_STATIC
index 62529ecc557579f80dd442a8da3fcac7ca42ca1e..d2a09a6d068a6290ca4045289e175b872061f7f8 100644 (file)
@@ -7229,3 +7229,15 @@ mono_test_marshal_fixed_array (FixedArrayStruct s)
 {
        return s.array [0] + s.array [1] + s.array [2];
 }
+
+LIBTEST_API int STDCALL
+mono_test_marshal_pointer_array (int *arr[])
+{
+       int i;
+
+       for (i = 0; i < 10; ++i) {
+               if (*arr [i] != -1)
+                       return 1;
+       }
+       return 0;
+}
index e170ba441ab44b5f9b32da5c914faac2a80d437d..f9ecf68a4027a95b9da5b0681024afd47b435f97 100644 (file)
@@ -1922,5 +1922,22 @@ public unsafe class Tests {
 
                return mono_test_marshal_fixed_array (s);
        }
+
+       [DllImport ("libtest", EntryPoint="mono_test_marshal_pointer_array")]
+       public static extern int mono_test_marshal_pointer_array (int*[] arr);
+
+       public static unsafe int test_0_pointer_array () {
+               var arr = new int [10];
+               for (int i = 0; i < arr.Length; i++)
+                       arr [i] = -1;
+               var arr2 = new int*[10];
+               for (int i = 0; i < arr2.Length; i++) {
+                       GCHandle handle = GCHandle.Alloc(arr[i], GCHandleType.Pinned);
+                       fixed (int *ptr = &arr[i]) {
+                               arr2[i] = ptr;
+                       }
+               }
+               return mono_test_marshal_pointer_array (arr2);
+       }
 }
 
index 3e29ab15df46efe42c1bb846bc2a57b0ef1345f8..5bc5bbd600326c90c774a43f7280e805ff0e1c04 100644 (file)
@@ -27,6 +27,7 @@ monoutils_sources = \
        mono-dl-darwin.c        \
        mono-dl-posix.c         \
        mono-dl.h               \
+       mono-dl-windows.h       \
        mono-log-windows.c      \
        mono-log-common.c       \
        mono-log-posix.c        \
@@ -40,8 +41,10 @@ monoutils_sources = \
        mono-filemap.c          \
        mono-math.c             \
        mono-mmap.c             \
+       mono-mmap-windows.c             \
        mono-mmap.h             \
        mono-mmap-internals.h   \
+       mono-mmap-windows.h     \
        mono-os-mutex.h         \
        mono-coop-mutex.h               \
        mono-once.h             \
@@ -49,7 +52,9 @@ monoutils_sources = \
        mono-networkinterfaces.c                \
        mono-networkinterfaces.h                \
        mono-proclib.c          \
+       mono-proclib-windows.c          \
        mono-proclib.h          \
+       mono-proclib-windows.h          \
        mono-publib.c           \
        mono-string.h           \
        mono-time.c             \
@@ -149,7 +154,9 @@ monoutils_sources = \
        networking-windows.c    \
        networking.h    \
        mono-rand.c     \
+       mono-rand-windows.c     \
        mono-rand.h \
+       mono-rand-windows.h \
        memfuncs.c \
        memfuncs.h \
        parse.c \
index 86afad502ffe27947c4bf7718bc49abbd4ded33c..2f5e8a8a673a8688e78c577b57b7c194effaad76 100644 (file)
@@ -581,6 +581,10 @@ InterlockedCompareExchange64(volatile gint64 *dest, gint64 exch, gint64 comp)
        return(old);
 }
 
+#endif
 #endif
 
+#if defined(HOST_WIN32) && defined(_MSC_VER)
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_atomic_lnk4221(void) {}
 #endif
index 8a044e50d31a2eb15cc4bb2a56a2266db85644b6..7becf4816ffd571052129646b5c7c39ae7db4275 100644 (file)
 #include <direct.h>
 #define mkdir(x)       _mkdir(x)
 
-/* GCC specific functions aren't available */
-#define __builtin_return_address(x)    NULL
-
 #define __func__ __FUNCTION__
 
 #include <BaseTsd.h>
index 2704c8662a8d1e2919a99fb3afb91361a551bb1d..0a1bd524cfd42261ac798b6f0b2eb1b8c7fe726f 100644 (file)
@@ -699,6 +699,8 @@ mono_ia64_context_get_fp (MonoContext *ctx)
 
 #elif ((defined(__mips__) && !defined(MONO_CROSS_COMPILE)) || (defined(TARGET_MIPS))) && SIZEOF_REGISTER == 4 /* defined(__ia64__) */
 
+#define MONO_ARCH_HAS_MONO_CONTEXT 1
+
 #include <mono/arch/mips/mips-codegen.h>
 
 typedef struct {
diff --git a/mono/utils/mono-dl-windows-uwp.c b/mono/utils/mono-dl-windows-uwp.c
new file mode 100644 (file)
index 0000000..8bb8e6c
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * mono-dl-windows-uwp.c: UWP dl support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+
+#if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
+#include <Windows.h>
+#include "mono/utils/mono-dl-windows.h"
+
+void*
+mono_dl_lookup_symbol_in_process (const char *symbol_name)
+{
+       g_unsupported_api ("EnumProcessModules");
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return NULL;
+}
+
+char*
+mono_dl_current_error_string (void)
+{
+       char *ret = NULL;
+       TCHAR buf [1024];
+       DWORD code = GetLastError ();
+
+       if (!FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
+               code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, G_N_ELEMENTS(buf) - 1, NULL))
+               buf[0] = TEXT('\0');
+
+       ret = u16to8 (buf);
+       return ret;
+}
+
+#else /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_mono_dl_windows_uwp_quiet_lnk4221(void) {}
+#endif
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
index 9e3efa796f7aa93503ab2fa1712d2be476519c73..04f695d22de38e15d4a199142b400023df9e5f1c 100644 (file)
@@ -13,6 +13,7 @@
 #if defined(HOST_WIN32)
 
 #include "mono/utils/mono-dl.h"
+#include "mono/utils/mono-dl-windows.h"
 #include "mono/utils/mono-embed.h"
 #include "mono/utils/mono-path.h"
 
@@ -25,7 +26,6 @@
 #include <windows.h>
 #include <psapi.h>
 
-
 const char*
 mono_dl_get_so_prefix (void)
 {
@@ -48,14 +48,20 @@ mono_dl_open_file (const char *file, int flags)
        gpointer hModule = NULL;
        if (file) {
                gunichar2* file_utf16 = g_utf8_to_utf16 (file, strlen (file), NULL, NULL, NULL);
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
                guint last_sem = SetErrorMode (SEM_FAILCRITICALERRORS);
+#endif
                guint32 last_error = 0;
 
                hModule = LoadLibrary (file_utf16);
                if (!hModule)
                        last_error = GetLastError ();
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
                SetErrorMode (last_sem);
+#endif
+
                g_free (file_utf16);
 
                if (!hModule)
@@ -73,23 +79,15 @@ mono_dl_close_handle (MonoDl *module)
                FreeLibrary (module->handle);
 }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 void*
-mono_dl_lookup_symbol (MonoDl *module, const char *symbol_name)
+mono_dl_lookup_symbol_in_process (const char *symbol_name)
 {
        HMODULE *modules;
        DWORD buffer_size = sizeof (HMODULE) * 1024;
        DWORD needed, i;
        gpointer proc = NULL;
 
-       /* get the symbol directly from the specified module */
-       if (!module->main_module)
-               return GetProcAddress (module->handle, symbol_name);
-
-       /* get the symbol from the main module */
-       proc = GetProcAddress (module->handle, symbol_name);
-       if (proc != NULL)
-               return proc;
-
        /* get the symbol from the loaded DLLs */
        modules = (HMODULE *) g_malloc (buffer_size);
        if (modules == NULL)
@@ -129,6 +127,25 @@ mono_dl_lookup_symbol (MonoDl *module, const char *symbol_name)
        g_free (modules);
        return NULL;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+void*
+mono_dl_lookup_symbol (MonoDl *module, const char *symbol_name)
+{
+       gpointer proc = NULL;
+
+       /* get the symbol directly from the specified module */
+       if (!module->main_module)
+               return GetProcAddress (module->handle, symbol_name);
+
+       /* get the symbol from the main module */
+       proc = GetProcAddress (module->handle, symbol_name);
+       if (proc != NULL)
+               return proc;
+
+       /* get the symbol from the loaded DLLs */
+       return mono_dl_lookup_symbol_in_process (symbol_name);
+}
 
 int
 mono_dl_convert_flags (int flags)
@@ -136,6 +153,7 @@ mono_dl_convert_flags (int flags)
        return 0;
 }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 char*
 mono_dl_current_error_string (void)
 {
@@ -153,6 +171,7 @@ mono_dl_current_error_string (void)
        }
        return ret;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
 
 int
 mono_dl_get_executable_path (char *buf, int buflen)
@@ -165,5 +184,4 @@ mono_dl_get_system_dir (void)
 {
        return NULL;
 }
-
 #endif
diff --git a/mono/utils/mono-dl-windows.h b/mono/utils/mono-dl-windows.h
new file mode 100644 (file)
index 0000000..5215418
--- /dev/null
@@ -0,0 +1,14 @@
+#ifndef __MONO_UTILS_DL_WINDOWS_H__
+#define __MONO_UTILS_DL_WINDOWS_H__
+
+#include <config.h>
+#include <glib.h>
+
+#ifdef HOST_WIN32
+#include "mono/utils/mono-dl.h"
+
+void*
+mono_dl_lookup_symbol_in_process (const char *symbol_name);
+#endif /* HOST_WIN32 */
+#endif /* __MONO_UTILS_DL_WINDOWS_H__ */
+
index fb9fdcacb7e84ef33c2587dbf9f067bfd6627350..c74923c00944b34d83aa5c2da0cc4a2fa19931d4 100644 (file)
@@ -32,6 +32,12 @@ typedef struct {
        void *padding [3];
 } MonoErrorInternal;
 
+/* Invariant: the error strings are allocated in the mempool of the given image */
+struct _MonoErrorBoxed {
+       MonoError error;
+       MonoImage *image;
+};
+
 #define error_init(error) do { \
        ((MonoErrorInternal*)(error))->error_code = MONO_ERROR_NONE;    \
        ((MonoErrorInternal*)(error))->flags = 0;       \
@@ -68,6 +74,9 @@ mono_error_set_assembly_load_simple (MonoError *error, const char *assembly_name
 void
 mono_error_set_type_load_class (MonoError *error, MonoClass *klass, const char *msg_format, ...) MONO_ATTR_FORMAT_PRINTF(3,4);
 
+void
+mono_error_vset_type_load_class (MonoError *error, MonoClass *klass, const char *msg_format, va_list args);
+
 void
 mono_error_set_type_load_name (MonoError *error, const char *type_name, const char *assembly_name, const char *msg_format, ...) MONO_ATTR_FORMAT_PRINTF(4,5);
 
@@ -128,4 +137,11 @@ mono_error_raise_exception (MonoError *error);
 void
 mono_error_move (MonoError *dest, MonoError *src);
 
+MonoErrorBoxed*
+mono_error_box (const MonoError *error, MonoImage *image);
+
+gboolean
+mono_error_set_from_boxed (MonoError *error, const MonoErrorBoxed *from);
+
+
 #endif
index 5ef98e1e9ef8047b95f38c555a8519b19ffd8bf3..a59f2a123fb112f62d245290be57a7c909920f8b 100644 (file)
@@ -38,6 +38,12 @@ is_managed_exception (MonoErrorInternal *error)
        return (error->error_code == MONO_ERROR_EXCEPTION_INSTANCE);
 }
 
+static gboolean
+is_boxed (MonoErrorInternal *error)
+{
+       return ((error->flags & MONO_ERROR_MEMPOOL_BOXED) != 0);
+}
+
 static void
 mono_error_prepare (MonoErrorInternal *error)
 {
@@ -116,6 +122,8 @@ mono_error_cleanup (MonoError *oerror)
 
        /* Two cleanups in a row without an intervening init. */
        g_assert (orig_error_code != MONO_ERROR_CLEANUP_CALLED_SENTINEL);
+       /* Mempool stored error shouldn't be cleaned up */
+       g_assert (!is_boxed (error));
 
        /* Mark it as cleaned up. */
        error->error_code = MONO_ERROR_CLEANUP_CALLED_SENTINEL;
@@ -294,13 +302,22 @@ mono_error_set_assembly_load_simple (MonoError *oerror, const char *assembly_nam
 
 void
 mono_error_set_type_load_class (MonoError *oerror, MonoClass *klass, const char *msg_format, ...)
+{
+       va_list args;
+       va_start (args, msg_format);
+       mono_error_vset_type_load_class (oerror, klass, msg_format, args);
+       va_end (args);
+}
+
+void
+mono_error_vset_type_load_class (MonoError *oerror, MonoClass *klass, const char *msg_format, va_list args)
 {
        MonoErrorInternal *error = (MonoErrorInternal*)oerror;
        mono_error_prepare (error);
 
        error->error_code = MONO_ERROR_TYPE_LOAD;
        mono_error_set_class (oerror, klass);
-       set_error_message ();
+       set_error_messagev ();
 }
 
 /*
@@ -730,6 +747,9 @@ mono_error_convert_to_exception (MonoError *target_error)
        MonoError error;
        MonoException *ex;
 
+       /* Mempool stored error shouldn't be cleaned up */
+       g_assert (!is_boxed ((MonoErrorInternal*)target_error));
+
        if (mono_error_ok (target_error))
                return NULL;
 
@@ -752,3 +772,97 @@ mono_error_move (MonoError *dest, MonoError *src)
        memcpy (dest, src, sizeof (MonoErrorInternal));
        mono_error_init (src);
 }
+
+/**
+ * mono_error_box:
+ * @ierror: The input error that will be boxed.
+ * @image: The mempool of this image will hold the boxed error.
+ *
+ * Creates a new boxed error in the given mempool from MonoError.
+ * It does not alter ierror, so you still have to clean it up with
+ * mono_error_cleanup or mono_error_convert_to_exception or another such function.
+ *
+ * Returns the boxed error, or NULL if the mempool could not allocate.
+ */
+MonoErrorBoxed*
+mono_error_box (const MonoError *ierror, MonoImage *image)
+{
+       MonoErrorInternal *from = (MonoErrorInternal*)ierror;
+       /* Don't know how to box a gchandle */
+       g_assert (!is_managed_exception (from));
+       MonoErrorBoxed* box = mono_image_alloc (image, sizeof (MonoErrorBoxed));
+       box->image = image;
+       mono_error_init_flags (&box->error, MONO_ERROR_MEMPOOL_BOXED);
+       MonoErrorInternal *to = (MonoErrorInternal*)&box->error;
+
+#define DUP_STR(field) do {                                            \
+               if (from->field) {                                      \
+                       if (!(to->field = mono_image_strdup (image, from->field))) \
+                               to->flags |= MONO_ERROR_INCOMPLETE;     \
+               } else {                                                \
+                       to->field = NULL;                               \
+               }                                                       \
+       } while (0)
+
+       to->error_code = from->error_code;
+       DUP_STR (type_name);
+       DUP_STR (assembly_name);
+       DUP_STR (member_name);
+       DUP_STR (exception_name_space);
+       DUP_STR (exception_name);
+       DUP_STR (full_message);
+       DUP_STR (full_message_with_fields);
+       DUP_STR (first_argument);
+       to->exn.klass = from->exn.klass;
+
+#undef DUP_STR
+       
+       return box;
+}
+
+
+/**
+ * mono_error_set_from_boxed:
+ * @oerror: The error that will be set to the contents of the box.
+ * @box: A mempool-allocated error.
+ *
+ * Sets the error condition in the oerror from the contents of the
+ * given boxed error.  Does not alter the boxed error, so it can be
+ * used in a future call to mono_error_set_from_boxed as needed.  The
+ * oerror should've been previously initialized with mono_error_init,
+ * as usual.
+ *
+ * Returns TRUE on success or FALSE on failure.
+ */
+gboolean
+mono_error_set_from_boxed (MonoError *oerror, const MonoErrorBoxed *box)
+{
+       MonoErrorInternal* to = (MonoErrorInternal*)oerror;
+       MonoErrorInternal* from = (MonoErrorInternal*)&box->error;
+       g_assert (!is_managed_exception (from));
+
+       mono_error_prepare (to);
+       to->flags |= MONO_ERROR_FREE_STRINGS;
+#define DUP_STR(field) do {                                            \
+               if (from->field) {                                      \
+                       if (!(to->field = g_strdup (from->field)))      \
+                               to->flags |= MONO_ERROR_INCOMPLETE;     \
+               } else {                                                \
+                       to->field = NULL;                               \
+               }                                                       \
+       } while (0)
+
+       to->error_code = from->error_code;
+       DUP_STR (type_name);
+       DUP_STR (assembly_name);
+       DUP_STR (member_name);
+       DUP_STR (exception_name_space);
+       DUP_STR (exception_name);
+       DUP_STR (full_message);
+       DUP_STR (full_message_with_fields);
+       DUP_STR (first_argument);
+       to->exn.klass = from->exn.klass;
+                 
+#undef DUP_STR
+       return (to->flags & MONO_ERROR_INCOMPLETE) == 0 ;
+}
index 0aba0e1d61abb4219d6cfc15a9a8ead976c1ceaa..fa9caa6759e36bb2cecb619b19822f56e08520e2 100644 (file)
@@ -12,7 +12,11 @@ enum {
        /*
        Something happened while processing the error and the resulting message is incomplete.
        */
-       MONO_ERROR_INCOMPLETE = 0x0002
+       MONO_ERROR_INCOMPLETE = 0x0002,
+       /*
+       This MonoError is heap allocated in a mempool
+        */
+       MONO_ERROR_MEMPOOL_BOXED = 0x0004
 };
 
 enum {
@@ -48,6 +52,9 @@ typedef struct _MonoError {
        void *hidden_1 [12]; /*DON'T TOUCH */
 } MonoError;
 
+/* Mempool-allocated MonoError.*/
+typedef struct _MonoErrorBoxed MonoErrorBoxed;
+
 MONO_BEGIN_DECLS
 
 MONO_API void
index 54c6320d2b6f6a08bc8fc2fe249f315bbde8cac8..f423096a7800194c73af530b756e897f9b8050c9 100644 (file)
@@ -387,4 +387,11 @@ static inline gchar *mono_portability_find_file_internal (GString **report, cons
        g_free (new_pathname);
        return(NULL);
 }
+
+#else /* DISABLE_PORTABILITY */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_mono_io_portability_quiet_lnk4221(void) {}
 #endif
+#endif /* DISABLE_PORTABILITY */
index 4948b91b80fbd84435428d56098e47d751d3b2a0..bdb6dffb50e27f1838959452b585907afa062bbf 100644 (file)
@@ -26,6 +26,7 @@
 #include <process.h>
 #endif
 #include "mono-logger-internals.h"
+#include "mono-proclib.h"
 
 static FILE *logFile = NULL;
 static void *logUserData = NULL;
@@ -119,7 +120,7 @@ mono_log_write_logfile (const char *log_domain, GLogLevelFlags level, mono_bool
                struct tm *tod;
                time(&t);
                tod = localtime(&t);
-               pid = _getpid();
+               pid = mono_process_current_pid ();
                strftime(logTime, sizeof(logTime), "%F %T", tod);
 #endif
                fprintf (logFile, "%s level[%c] mono[%d]: %s\n", logTime, mapLogFileLevel (level), pid, message);
index f6cd987fbba85c31ebda11b966b220ef3067f7ac..ab5db470e1941f75bd2e712d119f979ffa6ff602 100644 (file)
@@ -24,6 +24,7 @@
 #include <time.h>
 #include <process.h>
 #include "mono-logger-internals.h"
+#include "mono-proclib.h"
 
 static FILE *logFile = NULL;
 static void *logUserData = NULL;
@@ -88,7 +89,7 @@ void
 mono_log_write_syslog(const char *domain, GLogLevelFlags level, mono_bool hdr, const char *message)
 {
        time_t t;
-       pid_t pid;
+       int pid;
        char logTime [80];
 
        if (logFile == NULL)
@@ -97,7 +98,7 @@ mono_log_write_syslog(const char *domain, GLogLevelFlags level, mono_bool hdr, c
        struct tm *tod;
        time(&t);
        tod = localtime(&t);
-       pid = _getpid();
+       pid = mono_process_current_pid ();
        strftime(logTime, sizeof(logTime), "%F %T", tod);
 
        fprintf (logFile, "%s level[%c] mono[%d]: %s\n", logTime, mapLogFileLevel (level), pid, message);
index b4367a73367dc03ff57c2a4d76cbc6fab9d9b553..5cc59c77fbe6dd87bf56d097df56dc7380e9baf9 100644 (file)
@@ -291,7 +291,7 @@ mono_trace_set_mask_string (const char *value)
                        continue;
                }
                for (i = 0; valid_flags[i]; i++) {
-                       int len = strlen (valid_flags[i]);
+                       size_t len = strlen (valid_flags[i]);
                        if (strncmp (tok, valid_flags[i], len) == 0 && (tok[len] == 0 || tok[len] == ',')) {
                                flags |= valid_masks[i];
                                tok += len;
index faca70b8ca95e655d759182f8538356a5291a8e5..90695609f0875b608f7c6ad3069b970459e4e86c 100644 (file)
 
 #include "mono-compiler.h"
 
-int mono_pages_not_faulted (void *addr, size_t length);
+void *
+malloc_shared_area (int pid);
+
+char*
+aligned_address (char *mem, size_t size, size_t alignment);
+
+void
+account_mem (MonoMemAccountType type, ssize_t size);
+
+int
+mono_pages_not_faulted (void *addr, size_t length);
 
 #endif /* __MONO_UTILS_MMAP_INTERNAL_H__ */
 
diff --git a/mono/utils/mono-mmap-windows-uwp.c b/mono/utils/mono-mmap-windows-uwp.c
new file mode 100644 (file)
index 0000000..5565200
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * mono-dl-windows-uwp.c: UWP dl support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+
+#if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
+#include <Windows.h>
+#include <mono/utils/mono-mmap-windows.h>
+
+void*
+mono_file_map (size_t length, int flags, int fd, guint64 offset, void **ret_handle)
+{
+       void *ptr;
+       int mflags = 0;
+       HANDLE file, mapping;
+       int prot = mono_mmap_win_prot_from_flags (flags);
+
+       mflags = FILE_MAP_READ;
+       if (flags & MONO_MMAP_WRITE)
+               mflags = FILE_MAP_COPY;
+
+       file = (HANDLE) _get_osfhandle (fd);
+       mapping = CreateFileMappingFromApp (file, NULL, prot, length, NULL);
+
+       if (mapping == NULL)
+               return NULL;
+
+       ptr = MapViewOfFileFromApp (mapping, mflags, offset, length);
+
+       if (ptr == NULL) {
+               CloseHandle (mapping);
+               return NULL;
+       }
+
+       *ret_handle = (void*)mapping;
+       return ptr;
+}
+
+int
+mono_file_unmap (void *addr, void *handle)
+{
+       UnmapViewOfFile (addr);
+       CloseHandle ((HANDLE)handle);
+       return 0;
+}
+
+#else /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_mono_mmap_windows_uwp_quiet_lnk4221(void) {}
+#endif
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
diff --git a/mono/utils/mono-mmap-windows.c b/mono/utils/mono-mmap-windows.c
new file mode 100644 (file)
index 0000000..6fe7766
--- /dev/null
@@ -0,0 +1,204 @@
+/*
+ * mono-mmap-windows.c: Windows support for mapping code into the process address space
+ *
+ * Author:
+ *   Mono Team (mono-list@lists.ximian.com)
+ *
+ * Copyright 2001-2008 Novell, Inc.
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+
+#include <config.h>
+#include <glib.h>
+
+#if defined(HOST_WIN32)
+#include <Windows.h>
+#include "mono/utils/mono-mmap-windows.h"
+#include <mono/utils/mono-counters.h>
+#include <io.h>
+
+static void *malloced_shared_area = NULL;
+
+int
+mono_pagesize (void)
+{
+       SYSTEM_INFO info;
+       static int saved_pagesize = 0;
+       if (saved_pagesize)
+               return saved_pagesize;
+       GetSystemInfo (&info);
+       saved_pagesize = info.dwAllocationGranularity;
+       return saved_pagesize;
+}
+
+int
+mono_mmap_win_prot_from_flags (int flags)
+{
+       int prot = flags & (MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
+       switch (prot) {
+       case 0: prot = PAGE_NOACCESS; break;
+       case MONO_MMAP_READ: prot = PAGE_READONLY; break;
+       case MONO_MMAP_READ|MONO_MMAP_EXEC: prot = PAGE_EXECUTE_READ; break;
+       case MONO_MMAP_READ|MONO_MMAP_WRITE: prot = PAGE_READWRITE; break;
+       case MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC: prot = PAGE_EXECUTE_READWRITE; break;
+       case MONO_MMAP_WRITE: prot = PAGE_READWRITE; break;
+       case MONO_MMAP_WRITE|MONO_MMAP_EXEC: prot = PAGE_EXECUTE_READWRITE; break;
+       case MONO_MMAP_EXEC: prot = PAGE_EXECUTE; break;
+       default:
+               g_assert_not_reached ();
+       }
+       return prot;
+}
+
+void*
+mono_valloc (void *addr, size_t length, int flags, MonoMemAccountType type)
+{
+       void *ptr;
+       int mflags = MEM_RESERVE|MEM_COMMIT;
+       int prot = mono_mmap_win_prot_from_flags (flags);
+       /* translate the flags */
+
+       ptr = VirtualAlloc (addr, length, mflags, prot);
+
+       account_mem (type, (ssize_t)length);
+
+       return ptr;
+}
+
+void*
+mono_valloc_aligned (size_t length, size_t alignment, int flags, MonoMemAccountType type)
+{
+       int prot = mono_mmap_win_prot_from_flags (flags);
+       char *mem = VirtualAlloc (NULL, length + alignment, MEM_RESERVE, prot);
+       char *aligned;
+
+       if (!mem)
+               return NULL;
+
+       aligned = aligned_address (mem, length, alignment);
+
+       aligned = VirtualAlloc (aligned, length, MEM_COMMIT, prot);
+       g_assert (aligned);
+
+       account_mem (type, (ssize_t)length);
+
+       return aligned;
+}
+
+int
+mono_vfree (void *addr, size_t length, MonoMemAccountType type)
+{
+       MEMORY_BASIC_INFORMATION mbi;
+       SIZE_T query_result = VirtualQuery (addr, &mbi, sizeof (mbi));
+       BOOL res;
+
+       g_assert (query_result);
+
+       res = VirtualFree (mbi.AllocationBase, 0, MEM_RELEASE);
+
+       g_assert (res);
+
+       account_mem (type, -(ssize_t)length);
+
+       return 0;
+}
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+void*
+mono_file_map (size_t length, int flags, int fd, guint64 offset, void **ret_handle)
+{
+       void *ptr;
+       int mflags = 0;
+       HANDLE file, mapping;
+       int prot = mono_mmap_win_prot_from_flags (flags);
+       /* translate the flags */
+       /*if (flags & MONO_MMAP_PRIVATE)
+               mflags |= MAP_PRIVATE;
+       if (flags & MONO_MMAP_SHARED)
+               mflags |= MAP_SHARED;
+       if (flags & MONO_MMAP_ANON)
+               mflags |= MAP_ANONYMOUS;
+       if (flags & MONO_MMAP_FIXED)
+               mflags |= MAP_FIXED;
+       if (flags & MONO_MMAP_32BIT)
+               mflags |= MAP_32BIT;*/
+
+       mflags = FILE_MAP_READ;
+       if (flags & MONO_MMAP_WRITE)
+               mflags = FILE_MAP_COPY;
+
+       file = (HANDLE) _get_osfhandle (fd);
+
+       mapping = CreateFileMapping (file, NULL, prot, 0, 0, NULL);
+
+       if (mapping == NULL)
+               return NULL;
+
+       ptr = MapViewOfFile (mapping, mflags, 0, offset, length);
+
+       if (ptr == NULL) {
+               CloseHandle (mapping);
+               return NULL;
+       }
+       *ret_handle = (void*)mapping;
+       return ptr;
+}
+
+int
+mono_file_unmap (void *addr, void *handle)
+{
+       UnmapViewOfFile (addr);
+       CloseHandle ((HANDLE)handle);
+       return 0;
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+int
+mono_mprotect (void *addr, size_t length, int flags)
+{
+       DWORD oldprot;
+       int prot = mono_mmap_win_prot_from_flags (flags);
+
+       if (flags & MONO_MMAP_DISCARD) {
+               VirtualFree (addr, length, MEM_DECOMMIT);
+               VirtualAlloc (addr, length, MEM_COMMIT, prot);
+               return 0;
+       }
+       return VirtualProtect (addr, length, prot, &oldprot) == 0;
+}
+
+void*
+mono_shared_area (void)
+{
+       if (!malloced_shared_area)
+               malloced_shared_area = malloc_shared_area (0);
+       /* get the pid here */
+       return malloced_shared_area;
+}
+
+void
+mono_shared_area_remove (void)
+{
+       if (malloced_shared_area)
+               g_free (malloced_shared_area);
+       malloced_shared_area = NULL;
+}
+
+void*
+mono_shared_area_for_pid (void *pid)
+{
+       return NULL;
+}
+
+void
+mono_shared_area_unload (void *area)
+{
+}
+
+int
+mono_shared_area_instances (void **array, int count)
+{
+       return 0;
+}
+
+#endif
diff --git a/mono/utils/mono-mmap-windows.h b/mono/utils/mono-mmap-windows.h
new file mode 100644 (file)
index 0000000..44da254
--- /dev/null
@@ -0,0 +1,15 @@
+#ifndef __MONO_UTILS_MMAP_WINDOWS_H__
+#define __MONO_UTILS_MMAP_WINDOWS_H__
+
+#include <config.h>
+#include <glib.h>
+
+#ifdef HOST_WIN32
+#include "mono/utils/mono-mmap.h"
+#include "mono/utils/mono-mmap-internals.h"
+
+int
+mono_mmap_win_prot_from_flags (int flags);
+#endif /* HOST_WIN32 */
+#endif /* __MONO_UTILS_MMAP_WINDOWS_H__ */
+
index 491318465faf804a0767d46b45b838d8020814b5..91fe5a12def4517d7c1d364df7117cef53aa988f 100644 (file)
@@ -8,12 +8,9 @@
  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
  */
 
-#include "config.h"
+#include <config.h>
 
-#ifdef HOST_WIN32
-#include <windows.h>
-#include <io.h>
-#else
+#ifndef HOST_WIN32
 #include <sys/types.h>
 #if HAVE_SYS_STAT_H
 #include <sys/stat.h>
@@ -29,7 +26,7 @@
 #include <unistd.h>
 #include <stdlib.h>
 #include <errno.h>
-#endif
+#endif /* !HOST_WIN32 */
 
 #include "mono-mmap.h"
 #include "mono-mmap-internals.h"
@@ -38,7 +35,6 @@
 #include <mono/utils/atomic.h>
 #include <mono/utils/mono-counters.h>
 
-
 #define BEGIN_CRITICAL_SECTION do { \
        MonoThreadInfo *__info = mono_thread_info_current_unchecked (); \
        if (__info) __info->inside_critical_region = TRUE;      \
@@ -63,9 +59,7 @@ typedef struct {
        short stats_end;
 } SAreaHeader;
 
-static void* malloced_shared_area = NULL;
-
-static void*
+void*
 malloc_shared_area (int pid)
 {
        int size = mono_pagesize ();
@@ -78,7 +72,7 @@ malloc_shared_area (int pid)
        return sarea;
 }
 
-static char*
+char*
 aligned_address (char *mem, size_t size, size_t alignment)
 {
        char *aligned = (char*)((size_t)(mem + (alignment - 1)) & ~(alignment - 1));
@@ -88,7 +82,7 @@ aligned_address (char *mem, size_t size, size_t alignment)
 
 static volatile size_t allocation_count [MONO_MEM_ACCOUNT_MAX];
 
-static void
+void
 account_mem (MonoMemAccountType type, ssize_t size)
 {
 #if SIZEOF_VOID_P == 4
@@ -135,186 +129,12 @@ mono_mem_account_register_counters (void)
 }
 
 #ifdef HOST_WIN32
-
-int
-mono_pagesize (void)
-{
-       SYSTEM_INFO info;
-       static int saved_pagesize = 0;
-       if (saved_pagesize)
-               return saved_pagesize;
-       GetSystemInfo (&info);
-       saved_pagesize = info.dwAllocationGranularity;
-       return saved_pagesize;
-}
-
-static int
-prot_from_flags (int flags)
-{
-       int prot = flags & (MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
-       switch (prot) {
-       case 0: prot = PAGE_NOACCESS; break;
-       case MONO_MMAP_READ: prot = PAGE_READONLY; break;
-       case MONO_MMAP_READ|MONO_MMAP_EXEC: prot = PAGE_EXECUTE_READ; break;
-       case MONO_MMAP_READ|MONO_MMAP_WRITE: prot = PAGE_READWRITE; break;
-       case MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC: prot = PAGE_EXECUTE_READWRITE; break;
-       case MONO_MMAP_WRITE: prot = PAGE_READWRITE; break;
-       case MONO_MMAP_WRITE|MONO_MMAP_EXEC: prot = PAGE_EXECUTE_READWRITE; break;
-       case MONO_MMAP_EXEC: prot = PAGE_EXECUTE; break;
-       default:
-               g_assert_not_reached ();
-       }
-       return prot;
-}
-
-void*
-mono_valloc (void *addr, size_t length, int flags, MonoMemAccountType type)
-{
-       void *ptr;
-       int mflags = MEM_RESERVE|MEM_COMMIT;
-       int prot = prot_from_flags (flags);
-       /* translate the flags */
-
-       ptr = VirtualAlloc (addr, length, mflags, prot);
-
-       account_mem (type, (ssize_t)length);
-
-       return ptr;
-}
-
-void*
-mono_valloc_aligned (size_t length, size_t alignment, int flags, MonoMemAccountType type)
-{
-       int prot = prot_from_flags (flags);
-       char *mem = VirtualAlloc (NULL, length + alignment, MEM_RESERVE, prot);
-       char *aligned;
-
-       if (!mem)
-               return NULL;
-
-       aligned = aligned_address (mem, length, alignment);
-
-       aligned = VirtualAlloc (aligned, length, MEM_COMMIT, prot);
-       g_assert (aligned);
-
-       account_mem (type, (ssize_t)length);
-
-       return aligned;
-}
-
+// Windows specific implementation in mono-mmap-windows.c
 #define HAVE_VALLOC_ALIGNED
 
-int
-mono_vfree (void *addr, size_t length, MonoMemAccountType type)
-{
-       MEMORY_BASIC_INFORMATION mbi;
-       SIZE_T query_result = VirtualQuery (addr, &mbi, sizeof (mbi));
-       BOOL res;
-
-       g_assert (query_result);
-
-       res = VirtualFree (mbi.AllocationBase, 0, MEM_RELEASE);
-
-       g_assert (res);
-
-       account_mem (type, -(ssize_t)length);
-
-       return 0;
-}
-
-void*
-mono_file_map (size_t length, int flags, int fd, guint64 offset, void **ret_handle)
-{
-       void *ptr;
-       int mflags = 0;
-       HANDLE file, mapping;
-       int prot = prot_from_flags (flags);
-       /* translate the flags */
-       /*if (flags & MONO_MMAP_PRIVATE)
-               mflags |= MAP_PRIVATE;
-       if (flags & MONO_MMAP_SHARED)
-               mflags |= MAP_SHARED;
-       if (flags & MONO_MMAP_ANON)
-               mflags |= MAP_ANONYMOUS;
-       if (flags & MONO_MMAP_FIXED)
-               mflags |= MAP_FIXED;
-       if (flags & MONO_MMAP_32BIT)
-               mflags |= MAP_32BIT;*/
-
-       mflags = FILE_MAP_READ;
-       if (flags & MONO_MMAP_WRITE)
-               mflags = FILE_MAP_COPY;
-
-       file = (HANDLE) _get_osfhandle (fd);
-       mapping = CreateFileMapping (file, NULL, prot, 0, 0, NULL);
-       if (mapping == NULL)
-               return NULL;
-       ptr = MapViewOfFile (mapping, mflags, 0, offset, length);
-       if (ptr == NULL) {
-               CloseHandle (mapping);
-               return NULL;
-       }
-       *ret_handle = (void*)mapping;
-       return ptr;
-}
-
-int
-mono_file_unmap (void *addr, void *handle)
-{
-       UnmapViewOfFile (addr);
-       CloseHandle ((HANDLE)handle);
-       return 0;
-}
-
-int
-mono_mprotect (void *addr, size_t length, int flags)
-{
-       DWORD oldprot;
-       int prot = prot_from_flags (flags);
-
-       if (flags & MONO_MMAP_DISCARD) {
-               VirtualFree (addr, length, MEM_DECOMMIT);
-               VirtualAlloc (addr, length, MEM_COMMIT, prot);
-               return 0;
-       }
-       return VirtualProtect (addr, length, prot, &oldprot) == 0;
-}
-
-void*
-mono_shared_area (void)
-{
-       if (!malloced_shared_area)
-               malloced_shared_area = malloc_shared_area (0);
-       /* get the pid here */
-       return malloced_shared_area;
-}
-
-void
-mono_shared_area_remove (void)
-{
-       if (malloced_shared_area)
-               g_free (malloced_shared_area);
-       malloced_shared_area = NULL;
-}
-
-void*
-mono_shared_area_for_pid (void *pid)
-{
-       return NULL;
-}
-
-void
-mono_shared_area_unload (void *area)
-{
-}
-
-int
-mono_shared_area_instances (void **array, int count)
-{
-       return 0;
-}
-
 #else
+
+static void* malloced_shared_area = NULL;
 #if defined(HAVE_MMAP)
 
 /**
diff --git a/mono/utils/mono-proclib-windows-uwp.c b/mono/utils/mono-proclib-windows-uwp.c
new file mode 100644 (file)
index 0000000..e278ecc
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * mono-proclib-windows-uwp.c: UWP proclib support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+
+#if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
+#include <Windows.h>
+#include <mono/utils/mono-proclib.h>
+
+gint32
+mono_cpu_usage (MonoCpuUsageState *prev)
+{
+       gint32 cpu_usage = 0;
+       gint64 cpu_total_time;
+       gint64 cpu_busy_time;
+       guint64 idle_time;
+       guint64 kernel_time;
+       guint64 user_time;
+       guint64 current_time;
+       guint64 creation_time;
+       guint64 exit_time;
+
+       GetSystemTimeAsFileTime ((FILETIME*)&current_time);
+       if (!GetProcessTimes (GetCurrentProcess (), (FILETIME*)&creation_time, (FILETIME*)&exit_time, (FILETIME*)&kernel_time, (FILETIME*)&user_time)) {
+               g_error ("GetProcessTimes() failed, error code is %d\n", GetLastError ());
+               return -1;
+       }
+
+       // GetProcessTimes user_time is a sum of user time spend by all threads in the process.
+       // This means that the total user time can be more than real time. In order to adjust for this
+       // the total available time that we can be scheduled depends on the number of available cores.
+       // For example, having 2 threads running 100% on a 2 core system for 100 ms will return a user_time of 200ms
+       // but the current_time - creation_time will only be 100ms but by adjusting the available time based on number of
+       // of availalbe cores will gives use the total load of the process.
+       guint64 total_available_time = (current_time - creation_time) * mono_cpu_count ();
+
+       idle_time = total_available_time - (kernel_time + user_time);
+
+       cpu_total_time = (gint64)((idle_time - (prev ? prev->idle_time : 0)) + (user_time - (prev ? prev->user_time : 0)) + (kernel_time - (prev ? prev->kernel_time : 0)));
+       cpu_busy_time = (gint64)(cpu_total_time - (idle_time - (prev ? prev->idle_time : 0)));
+
+       if (prev) {
+               prev->idle_time = idle_time;
+               prev->kernel_time = kernel_time;
+               prev->user_time = user_time;
+       }
+
+       if (cpu_total_time > 0 && cpu_busy_time > 0)
+               cpu_usage = (gint32)(cpu_busy_time * 100 / cpu_total_time);
+
+       return cpu_usage;
+}
+
+#else /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_mono_proclib_windows_uwp_quiet_lnk4221(void) {}
+#endif
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
diff --git a/mono/utils/mono-proclib-windows.c b/mono/utils/mono-proclib-windows.c
new file mode 100644 (file)
index 0000000..6386a51
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * mono-proclib-windows.c: Windows proclib support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+
+#include <config.h>
+#include <glib.h>
+
+#ifdef HOST_WIN32
+#include <windows.h>
+#include "mono/utils/mono-proclib.h"
+
+int
+mono_process_current_pid ()
+{
+       return (int) GetCurrentProcessId ();
+}
+
+/**
+ * mono_cpu_count:
+ *
+ * Return the number of processors on the system.
+ */
+int
+mono_cpu_count (void)
+{
+       SYSTEM_INFO info;
+       GetSystemInfo (&info);
+       return info.dwNumberOfProcessors;
+}
+
+/*
+ * This function returns the cpu usage in percentage,
+ * normalized on the number of cores.
+ *
+ * Warning : the percentage returned can be > 100%. This
+ * might happens on systems like Android which, for
+ * battery and performance reasons, shut down cores and
+ * lie about the number of active cores.
+ */
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+gint32
+mono_cpu_usage (MonoCpuUsageState *prev)
+{
+       gint32 cpu_usage = 0;
+       gint64 cpu_total_time;
+       gint64 cpu_busy_time;
+       guint64 idle_time;
+       guint64 kernel_time;
+       guint64 user_time;
+
+       if (!GetSystemTimes ((FILETIME*) &idle_time, (FILETIME*) &kernel_time, (FILETIME*) &user_time)) {
+               g_error ("GetSystemTimes() failed, error code is %d\n", GetLastError ());
+               return -1;
+       }
+
+       cpu_total_time = (gint64)((user_time - (prev ? prev->user_time : 0)) + (kernel_time - (prev ? prev->kernel_time : 0)));
+       cpu_busy_time = (gint64)(cpu_total_time - (idle_time - (prev ? prev->idle_time : 0)));
+
+       if (prev) {
+               prev->idle_time = idle_time;
+               prev->kernel_time = kernel_time;
+               prev->user_time = user_time;
+       }
+
+       if (cpu_total_time > 0 && cpu_busy_time > 0)
+               cpu_usage = (gint32)(cpu_busy_time * 100 / cpu_total_time);
+
+       return cpu_usage;
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+#endif /* HOST_WIN32*/
diff --git a/mono/utils/mono-proclib-windows.h b/mono/utils/mono-proclib-windows.h
new file mode 100644 (file)
index 0000000..f14c7a4
--- /dev/null
@@ -0,0 +1,13 @@
+#ifndef __MONO_UTILS_PROCLIB_WINDOWS_H__
+#define __MONO_UTILS_PROCLIB_WINDOWS_H__
+
+#include <config.h>
+#include <glib.h>
+
+#ifdef HOST_WIN32
+#include <process.h>
+#include "mono/utils/mono-proclib.h"
+
+#endif /* HOST_WIN32 */
+#endif /* __MONO_UTILS_PROCLIB_WINDOWS_H__ */
+
index 79da32b45118f4e6f992207c723ce14f880477c0..9c37ccf2ec11874e121c4a394e980461c8a3c9f3 100644 (file)
 #include <sched.h>
 #endif
 
-#ifdef HOST_WIN32
-#include <windows.h>
-#include <process.h>
-#endif
-
 #if defined(_POSIX_VERSION)
 #include <sys/errno.h>
 #include <sys/param.h>
@@ -187,7 +182,7 @@ get_pid_status_item_buf (int pid, const char *item, char *rbuf, int blen, MonoPr
        char buf [256];
        char *s;
        FILE *f;
-       int len = strlen (item);
+       size_t len = strlen (item);
 
        g_snprintf (buf, sizeof (buf), "/proc/%d/status", pid);
        f = fopen (buf, "r");
@@ -286,7 +281,7 @@ mono_process_get_name (gpointer pid, char *buf, int len)
        char fname [128];
        FILE *file;
        char *p;
-       int r;
+       size_t r;
        sprintf (fname, "/proc/%d/cmdline", GPOINTER_TO_INT (pid));
        buf [0] = 0;
        file = fopen (fname, "r");
@@ -443,7 +438,8 @@ get_process_stat_item (int pid, int pos, int sum, MonoProcessError *error)
        char buf [512];
        char *s, *end;
        FILE *f;
-       int len, i;
+       size_t len;
+       int i;
        gint64 value;
 
        g_snprintf (buf, sizeof (buf), "/proc/%d/stat", pid);
@@ -637,31 +633,27 @@ mono_process_get_data (gpointer pid, MonoProcessData data)
        return mono_process_get_data_with_error (pid, data, &error);
 }
 
+#ifndef HOST_WIN32
 int
 mono_process_current_pid ()
 {
 #if defined(HAVE_UNISTD_H)
        return (int) getpid ();
-#elif defined(HOST_WIN32)
-       return (int) GetCurrentProcessId ();
 #else
 #error getpid
 #endif
 }
+#endif /* !HOST_WIN32 */
 
 /**
  * mono_cpu_count:
  *
  * Return the number of processors on the system.
  */
+#ifndef HOST_WIN32
 int
 mono_cpu_count (void)
 {
-#ifdef HOST_WIN32
-       SYSTEM_INFO info;
-       GetSystemInfo (&info);
-       return info.dwNumberOfProcessors;
-#else
 #ifdef PLATFORM_ANDROID
        /* Android tries really hard to save power by powering off CPUs on SMP phones which
         * means the normal way to query cpu count returns a wrong value with userspace API.
@@ -779,10 +771,10 @@ mono_cpu_count (void)
                        return count;
        }
 #endif
-#endif /* HOST_WIN32 */
        /* FIXME: warn */
        return 1;
 }
+#endif /* !HOST_WIN32 */
 
 static void
 get_cpu_times (int cpu_id, gint64 *user, gint64 *systemt, gint64 *irq, gint64 *sirq, gint64 *idle)
@@ -889,14 +881,13 @@ mono_atexit (void (*func)(void))
  * battery and performance reasons, shut down cores and
  * lie about the number of active cores.
  */
+#ifndef HOST_WIN32
 gint32
 mono_cpu_usage (MonoCpuUsageState *prev)
 {
        gint32 cpu_usage = 0;
        gint64 cpu_total_time;
        gint64 cpu_busy_time;
-
-#ifndef HOST_WIN32
        struct rusage resource_usage;
        gint64 current_time;
        gint64 kernel_time;
@@ -919,28 +910,10 @@ mono_cpu_usage (MonoCpuUsageState *prev)
                prev->user_time = user_time;
                prev->current_time = current_time;
        }
-#else
-       guint64 idle_time;
-       guint64 kernel_time;
-       guint64 user_time;
-
-       if (!GetSystemTimes ((FILETIME*) &idle_time, (FILETIME*) &kernel_time, (FILETIME*) &user_time)) {
-               g_error ("GetSystemTimes() failed, error code is %d\n", GetLastError ());
-               return -1;
-       }
-
-       cpu_total_time = (gint64)((user_time - (prev ? prev->user_time : 0)) + (kernel_time - (prev ? prev->kernel_time : 0)));
-       cpu_busy_time = (gint64)(cpu_total_time - (idle_time - (prev ? prev->idle_time : 0)));
-
-       if (prev) {
-               prev->idle_time = idle_time;
-               prev->kernel_time = kernel_time;
-               prev->user_time = user_time;
-       }
-#endif
 
        if (cpu_total_time > 0 && cpu_busy_time > 0)
                cpu_usage = (gint32)(cpu_busy_time * 100 / cpu_total_time);
 
        return cpu_usage;
 }
+#endif /* !HOST_WIN32 */
diff --git a/mono/utils/mono-rand-windows-uwp.c b/mono/utils/mono-rand-windows-uwp.c
new file mode 100644 (file)
index 0000000..e9030fe
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+ * mono-rand-windows-uwp.c: UWP rand support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+
+#if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
+#include <Windows.h>
+#include "mono/utils/mono-rand-windows.h"
+
+MONO_WIN32_CRYPT_PROVIDER_HANDLE
+mono_rand_win_open_provider (void)
+{
+       MONO_WIN32_CRYPT_PROVIDER_HANDLE provider = 0;
+
+       if (!BCRYPT_SUCCESS (BCryptOpenAlgorithmProvider (&provider, BCRYPT_RNG_ALGORITHM, NULL, 0)))
+               provider = 0;
+
+       return provider;
+}
+
+gboolean
+mono_rand_win_gen (MONO_WIN32_CRYPT_PROVIDER_HANDLE provider, guchar *buffer, size_t buffer_size)
+{
+       g_assert (provider != 0 && buffer != 0);
+       return (BCRYPT_SUCCESS (BCryptGenRandom (provider, buffer, (ULONG) buffer_size, 0))) ? TRUE : FALSE;
+}
+
+gboolean
+mono_rand_win_seed (MONO_WIN32_CRYPT_PROVIDER_HANDLE provider, guchar *seed, size_t seed_size)
+{
+       g_assert (provider != 0 && seed != 0);
+       return (BCRYPT_SUCCESS (BCryptGenRandom (provider, seed, (ULONG) seed_size, BCRYPT_RNG_USE_ENTROPY_IN_BUFFER))) ? TRUE : FALSE;
+}
+
+void
+mono_rand_win_close_provider (MONO_WIN32_CRYPT_PROVIDER_HANDLE provider)
+{
+       g_assert (provider != 0);
+       BCryptCloseAlgorithmProvider (provider, 0);
+}
+
+#else /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_mono_rand_windows_uwp_quiet_lnk4221(void) {}
+#endif
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
diff --git a/mono/utils/mono-rand-windows.c b/mono/utils/mono-rand-windows.c
new file mode 100644 (file)
index 0000000..2ff32a9
--- /dev/null
@@ -0,0 +1,172 @@
+/*
+ * mono-rand-windows.c: Windows rand support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+#include "mono-error.h"
+#include "mono-error-internals.h"
+#include "mono-rand.h"
+
+#if defined(HOST_WIN32)
+#include <windows.h>
+#include "mono/utils/mono-rand-windows.h"
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+#ifndef PROV_INTEL_SEC
+#define PROV_INTEL_SEC         22
+#endif
+#ifndef CRYPT_VERIFY_CONTEXT
+#define CRYPT_VERIFY_CONTEXT   0xF0000000
+#endif
+
+MONO_WIN32_CRYPT_PROVIDER_HANDLE
+mono_rand_win_open_provider (void)
+{
+       MONO_WIN32_CRYPT_PROVIDER_HANDLE provider = 0;
+
+       /* There is no need to create a container for just random data,
+        * so we can use CRYPT_VERIFY_CONTEXT (one call) see:
+        * http://blogs.msdn.com/dangriff/archive/2003/11/19/51709.aspx */
+
+       /* We first try to use the Intel PIII RNG if drivers are present */
+       if (!CryptAcquireContext (&provider, NULL, NULL, PROV_INTEL_SEC, CRYPT_VERIFY_CONTEXT)) {
+               /* not a PIII or no drivers available, use default RSA CSP */
+               if (!CryptAcquireContext (&provider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFY_CONTEXT)) {
+                       /* exception will be thrown in managed code */
+                       provider = 0;
+               }
+       }
+
+       return provider;
+}
+
+void
+mono_rand_win_close_provider (MONO_WIN32_CRYPT_PROVIDER_HANDLE provider)
+{
+       CryptReleaseContext (provider, 0);
+}
+
+gboolean
+mono_rand_win_gen (MONO_WIN32_CRYPT_PROVIDER_HANDLE provider, guchar *buffer, size_t buffer_size)
+{
+       return CryptGenRandom (provider, (DWORD) buffer_size, buffer);
+}
+
+gboolean
+mono_rand_win_seed (MONO_WIN32_CRYPT_PROVIDER_HANDLE provider, guchar *seed, size_t seed_size)
+{
+       /* add seeding material to the RNG */
+       return CryptGenRandom (provider, (DWORD) seed_size, seed);
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+/**
+ * mono_rand_open:
+ *
+ * Returns: True if random source is global, false if mono_rand_init can be called repeatedly to get randomness instances.
+ *
+ * Initializes entire RNG system. Must be called once per process before calling mono_rand_init.
+ */
+gboolean
+mono_rand_open (void)
+{
+       return FALSE;
+}
+
+/**
+ * mono_rand_init:
+ * @seed: A string containing seed data
+ * @seed_size: Length of seed string
+ *
+ * Returns: On success, a non-NULL handle which can be used to fetch random data from mono_rand_try_get_bytes. On failure, NULL.
+ *
+ * Initializes an RNG client.
+ */
+gpointer
+mono_rand_init (guchar *seed, gint seed_size)
+{
+       MONO_WIN32_CRYPT_PROVIDER_HANDLE provider = 0;
+
+       /* try to open crypto provider. */
+       provider = mono_rand_win_open_provider ();
+
+       /* seed the CSP with the supplied buffer (if present) */
+       if (provider != 0 && seed != NULL) {
+               /* the call we replace the seed with random - this isn't what is
+                * expected from the class library user */
+               guchar *data = g_malloc (seed_size);
+               if (data != NULL) {
+                       memcpy (data, seed, seed_size);
+                       /* add seeding material to the RNG */
+                       mono_rand_win_seed (provider, data, seed_size);
+                       /* zeroize and free */
+                       memset (data, 0, seed_size);
+                       g_free (data);
+               }
+       }
+
+       return (gpointer) provider;
+}
+
+/**
+ * mono_rand_try_get_bytes:
+ * @handle: A pointer to an RNG handle. Handle is set to NULL on failure.
+ * @buffer: A buffer into which to write random data.
+ * @buffer_size: Number of bytes to write into buffer.
+ * @error: Set on error.
+ *
+ * Returns: FALSE on failure and sets @error, TRUE on success.
+ *
+ * Extracts bytes from an RNG handle.
+ */
+gboolean
+mono_rand_try_get_bytes (gpointer *handle, guchar *buffer, gint buffer_size, MonoError *error)
+{
+       MONO_WIN32_CRYPT_PROVIDER_HANDLE provider;
+
+       mono_error_init (error);
+
+       g_assert (handle);
+       provider = (MONO_WIN32_CRYPT_PROVIDER_HANDLE) *handle;
+
+       /* generate random bytes */
+       if (!mono_rand_win_gen (provider, buffer, buffer_size)) {
+               mono_rand_win_close_provider (provider);
+               /* we may have lost our context with CryptoAPI, but all hope isn't lost yet! */
+               provider = mono_rand_win_open_provider ();
+               if (provider != 0) {
+
+                       /* retry generate of random bytes */
+                       if (!mono_rand_win_gen (provider, buffer, buffer_size)) {
+                               /* failure, close provider */
+                               mono_rand_win_close_provider (provider);
+                               provider = 0;
+                       }
+               }
+
+               /* make sure client gets new opened provider handle or NULL on failure */
+               *handle = (gpointer) provider;
+               if (*handle == 0) {
+                       /* exception will be thrown in managed code */
+                       mono_error_set_execution_engine (error, "Failed to gen random bytes (%d)", GetLastError ());
+                       return FALSE;
+               }
+       }
+       return TRUE;
+}
+
+/**
+ * mono_rand_close:
+ * @handle: An RNG handle.
+ *
+ * Releases an RNG handle.
+ */
+void
+mono_rand_close (gpointer handle)
+{
+       mono_rand_win_close_provider ((MONO_WIN32_CRYPT_PROVIDER_HANDLE) handle);
+}
+#endif /* HOST_WIN32 */
diff --git a/mono/utils/mono-rand-windows.h b/mono/utils/mono-rand-windows.h
new file mode 100644 (file)
index 0000000..f60c121
--- /dev/null
@@ -0,0 +1,33 @@
+#ifndef _MONO_UTILS_RAND_WINDOWS_H_
+#define _MONO_UTILS_RAND_WINDOWS_H_
+
+#include <config.h>
+#include <glib.h>
+
+#ifdef HOST_WIN32
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+#include <wincrypt.h>
+#define MONO_WIN32_CRYPT_PROVIDER_HANDLE HCRYPTPROV
+
+#else
+
+#include <bcrypt.h>
+#define MONO_WIN32_CRYPT_PROVIDER_HANDLE BCRYPT_ALG_HANDLE
+#endif
+
+MONO_WIN32_CRYPT_PROVIDER_HANDLE
+mono_rand_win_open_provider (void);
+
+gboolean
+mono_rand_win_gen (MONO_WIN32_CRYPT_PROVIDER_HANDLE provider, guchar *buffer, size_t buffer_size);
+
+gboolean
+mono_rand_win_seed (MONO_WIN32_CRYPT_PROVIDER_HANDLE provider, guchar *seed, size_t seed_size);
+
+void
+mono_rand_win_close_provider (MONO_WIN32_CRYPT_PROVIDER_HANDLE provider);
+
+#endif /* HOST_WIN32 */
+#endif /* _MONO_UTILS_RAND_WINDOWS_H_ */
+
index 0e5a85384705341e3c5233e0db110fae07201803..1ac91179382d2ffb4ee7f5e826bca141e7cc4bb5 100644 (file)
@@ -13,7 +13,6 @@
  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
  */
 
-
 #include <glib.h>
 #include <config.h>
 
 #include "metadata/object.h"
 
 #ifdef HOST_WIN32
-
-#include <windows.h>
-#include <wincrypt.h>
-
-#ifndef PROV_INTEL_SEC
-#define PROV_INTEL_SEC         22
-#endif
-#ifndef CRYPT_VERIFY_CONTEXT
-#define CRYPT_VERIFY_CONTEXT   0xF0000000
-#endif
-
-/**
- * mono_rand_open:
- *
- * Returns: True if random source is global, false if mono_rand_init can be called repeatedly to get randomness instances.
- *
- * Initializes entire RNG system. Must be called once per process before calling mono_rand_init.
- */
-gboolean
-mono_rand_open (void)
-{
-       return FALSE;
-}
-
-/**
- * mono_rand_init:
- * @seed: A string containing seed data
- * @seed_size: Length of seed string
- *
- * Returns: On success, a non-NULL handle which can be used to fetch random data from mono_rand_try_get_bytes. On failure, NULL.
- *
- * Initializes an RNG client.
- */
-gpointer
-mono_rand_init (guchar *seed, gint seed_size)
-{
-       HCRYPTPROV provider = 0;
-
-       /* There is no need to create a container for just random data,
-        * so we can use CRYPT_VERIFY_CONTEXT (one call) see: 
-        * http://blogs.msdn.com/dangriff/archive/2003/11/19/51709.aspx */
-
-       /* We first try to use the Intel PIII RNG if drivers are present */
-       if (!CryptAcquireContext (&provider, NULL, NULL, PROV_INTEL_SEC, CRYPT_VERIFY_CONTEXT)) {
-               /* not a PIII or no drivers available, use default RSA CSP */
-               if (!CryptAcquireContext (&provider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFY_CONTEXT)) {
-                       /* exception will be thrown in managed code */
-                       provider = 0;
-               }
-       }
-
-       /* seed the CSP with the supplied buffer (if present) */
-       if (provider != 0 && seed) {
-               /* the call we replace the seed with random - this isn't what is
-                * expected from the class library user */
-               guchar *data = g_malloc (seed_size);
-               if (data) {
-                       memcpy (data, seed, seed_size);
-                       /* add seeding material to the RNG */
-                       CryptGenRandom (provider, seed_size, data);
-                       /* zeroize and free */
-                       memset (data, 0, seed_size);
-                       g_free (data);
-               }
-       }
-
-       return (gpointer) provider;
-}
-
-/**
- * mono_rand_try_get_bytes:
- * @handle: A pointer to an RNG handle. Handle is set to NULL on failure.
- * @buffer: A buffer into which to write random data.
- * @buffer_size: Number of bytes to write into buffer.
- * @error: Set on error.
- *
- * Returns: FALSE on failure and sets @error, TRUE on success.
- *
- * Extracts bytes from an RNG handle.
- */
-gboolean
-mono_rand_try_get_bytes (gpointer *handle, guchar *buffer, gint buffer_size, MonoError *error)
-{
-       HCRYPTPROV provider;
-
-       mono_error_init (error);
-
-       g_assert (handle);
-       provider = (HCRYPTPROV) *handle;
-
-       if (!CryptGenRandom (provider, buffer_size, buffer)) {
-               CryptReleaseContext (provider, 0);
-               /* we may have lost our context with CryptoAPI, but all hope isn't lost yet! */
-               provider = (HCRYPTPROV) mono_rand_init (NULL, 0);
-               if (!CryptGenRandom (provider, buffer_size, buffer)) {
-                       /* exception will be thrown in managed code */
-                       CryptReleaseContext (provider, 0);
-                       *handle = 0;
-                       mono_error_set_execution_engine (error, "Failed to gen random bytes (%d)", GetLastError ());
-                       return FALSE;
-               }
-       }
-       return TRUE;
-}
-
-/**
- * mono_rand_close:
- * @handle: An RNG handle.
- * @buffer: A buffer into which to write random data.
- * @buffer_size: Number of bytes to write into buffer.
- *
- * Releases an RNG handle.
- */
-void
-mono_rand_close (gpointer handle)
-{
-       CryptReleaseContext ((HCRYPTPROV) handle, 0);
-}
-
+// Windows specific implementation in mono-rand-windows.c
 #elif defined (HAVE_SYS_UN_H) && !defined(__native_client__)
 
 #include <errno.h>
index 7d656132b5908b35b491f4c439eefa66c83cd243..29486bac076f757f7882a401b576b661da675d82 100644 (file)
@@ -54,35 +54,42 @@ mono_threads_platform_register (MonoThreadInfo *info)
 }
 
 int
-mono_threads_platform_create_thread (MonoThreadStart thread_fn, gpointer thread_data, gsize stack_size, MonoNativeThreadId *out_tid)
+mono_threads_platform_create_thread (MonoThreadStart thread_fn, gpointer thread_data, gsize* const stack_size, MonoNativeThreadId *out_tid)
 {
        pthread_attr_t attr;
        pthread_t thread;
        int policy;
        struct sched_param param;
        gint res;
+       gsize set_stack_size;
+       size_t min_size;
 
        res = pthread_attr_init (&attr);
        g_assert (!res);
 
+       if (stack_size)
+               set_stack_size = *stack_size;
+       else
+               set_stack_size = 0;
+
 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
-       if (stack_size == 0) {
+       if (set_stack_size == 0) {
 #if HAVE_VALGRIND_MEMCHECK_H
                if (RUNNING_ON_VALGRIND)
-                       stack_size = 1 << 20;
+                       set_stack_size = 1 << 20;
                else
-                       stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
+                       set_stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
 #else
-               stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
+               set_stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
 #endif
        }
 
 #ifdef PTHREAD_STACK_MIN
-       if (stack_size < PTHREAD_STACK_MIN)
-               stack_size = PTHREAD_STACK_MIN;
+       if (set_stack_size < PTHREAD_STACK_MIN)
+               set_stack_size = PTHREAD_STACK_MIN;
 #endif
 
-       res = pthread_attr_setstacksize (&attr, stack_size);
+       res = pthread_attr_setstacksize (&attr, set_stack_size);
        g_assert (!res);
 #endif /* HAVE_PTHREAD_ATTR_SETSTACKSIZE */
 
@@ -125,6 +132,14 @@ mono_threads_platform_create_thread (MonoThreadStart thread_fn, gpointer thread_
        if (res != 0)
                g_error ("%s: pthread_attr_setschedparam failed, error: \"%s\" (%d)", g_strerror (res), res);
 
+       if (stack_size) {
+               res = pthread_attr_getstacksize (&attr, &min_size);
+               if (res != 0)
+                       g_error ("%s: pthread_attr_getstacksize failed, error: \"%s\" (%d)", g_strerror (res), res);
+               else
+                       *stack_size = min_size;
+       }
+
        /* Actually start the thread */
        res = mono_gc_pthread_create (&thread, &attr, (gpointer (*)(gpointer)) thread_fn, thread_data);
        if (res)
index 19afe3e6b8e0d4276d3abb4aa01d328a0f291407..02d25b76e1cd31061a36a1e32bb8614edc8ea433 100644 (file)
@@ -24,6 +24,7 @@ mono_threads_abort_syscall_init (void)
 static void CALLBACK
 abort_apc (ULONG_PTR param)
 {
+       THREADS_INTERRUPT_DEBUG ("%06d - abort_apc () called", GetCurrentThreadId ());
 }
 
 void
@@ -35,6 +36,7 @@ mono_threads_suspend_abort_syscall (MonoThreadInfo *info)
        handle = OpenThread (THREAD_ALL_ACCESS, FALSE, id);
        g_assert (handle);
 
+       THREADS_INTERRUPT_DEBUG ("%06d - Aborting syscall in thread %06d", GetCurrentThreadId (), id);
        QueueUserAPC ((PAPCFUNC)abort_apc, handle, (ULONG_PTR)NULL);
 
        CloseHandle (handle);
index 5d6774ed4d7ea1c051365f841939c9d407dcec22..791b898005ad36573273f75ac53d5b2fcdf032eb 100644 (file)
@@ -149,12 +149,12 @@ mono_threads_platform_register (MonoThreadInfo *info)
 }
 
 int
-mono_threads_platform_create_thread (MonoThreadStart thread_fn, gpointer thread_data, gsize stack_size, MonoNativeThreadId *out_tid)
+mono_threads_platform_create_thread (MonoThreadStart thread_fn, gpointer thread_data, gsize* const stack_size, MonoNativeThreadId *out_tid)
 {
        HANDLE result;
        DWORD thread_id;
 
-       result = CreateThread (NULL, stack_size, (LPTHREAD_START_ROUTINE) thread_fn, thread_data, 0, &thread_id);
+       result = CreateThread (NULL, stack_size ? *stack_size : 0, (LPTHREAD_START_ROUTINE) thread_fn, thread_data, 0, &thread_id);
        if (!result)
                return -1;
 
@@ -165,6 +165,12 @@ mono_threads_platform_create_thread (MonoThreadStart thread_fn, gpointer thread_
        if (out_tid)
                *out_tid = thread_id;
 
+       if (stack_size) {
+               // TOOD: Use VirtualQuery to get correct value 
+               // http://stackoverflow.com/questions/2480095/thread-stack-size-on-windows-visual-c
+               *stack_size = 2 * 1024 * 1024;
+       }
+
        return 0;
 }
 
index f8c716b5038d941b9a74edbf0f0ab84e52be9450..6ead6cfc23d1ba088f9654673d7ee14b45018d64 100644 (file)
@@ -1185,7 +1185,7 @@ inner_start_thread (gpointer data)
  * Returns: a windows or io-layer handle for the thread.
  */
 HANDLE
-mono_threads_create_thread (MonoThreadStart start, gpointer arg, gsize stack_size, MonoNativeThreadId *out_tid)
+mono_threads_create_thread (MonoThreadStart start, gpointer arg, gsize * const stack_size, MonoNativeThreadId *out_tid)
 {
        CreateThreadData *thread_data;
        gint res;
index 72f90e38157111c857703ab676bda8cb7ba12162..aebfaca9952904d246f54e863254c8054d92f97f 100644 (file)
@@ -443,7 +443,7 @@ gboolean
 mono_thread_info_is_live (THREAD_INFO_TYPE *info);
 
 HANDLE
-mono_threads_create_thread (MonoThreadStart start, gpointer arg, gsize stack_size, MonoNativeThreadId *out_tid);
+mono_threads_create_thread (MonoThreadStart start, gpointer arg, gsize * const stack_size, MonoNativeThreadId *out_tid);
 
 int
 mono_threads_get_max_stack_size (void);
@@ -516,7 +516,7 @@ gboolean mono_threads_suspend_needs_abort_syscall (void);
 
 void mono_threads_platform_register (THREAD_INFO_TYPE *info);
 void mono_threads_platform_unregister (THREAD_INFO_TYPE *info);
-int mono_threads_platform_create_thread (MonoThreadStart thread_fn, gpointer thread_data, gsize stack_size, MonoNativeThreadId *out_tid);
+int mono_threads_platform_create_thread (MonoThreadStart thread_fn, gpointer thread_data, gsize* const stack_size, MonoNativeThreadId *out_tid);
 void mono_threads_platform_get_stack_bounds (guint8 **staddr, size_t *stsize);
 gboolean mono_threads_platform_yield (void);
 void mono_threads_platform_exit (int exit_code);
index c3501f25268fdc6b74b4bea84595698f1139a935..763c85b0d3757f6244eef499a30492de291cc39d 100644 (file)
@@ -53,4 +53,10 @@ inet_pton (int family, const char *address, void *inaddrp)
        return -1;
 }
 
+#else /* !HAVE_INET_PTON */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_networking_missing_lnk4221(void) {}
+#endif
 #endif /* !HAVE_INET_PTON */
index 5d638f1b8fb83ca27fd2e0ea78b5c61c346f91f7..775c7b8e5e3c98948f5eefbe4603b6f662985c80 100644 (file)
@@ -60,6 +60,7 @@
       <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>\r
       <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>\r
     </ClInclude>\r
+    <ClInclude Include="..\mono\mini\mini-windows.h" />\r
     <ClInclude Include="..\mono\mini\mini-x86.h">\r
       <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>\r
       <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>\r
index 35641c0e6af5d06deb99314d48f855f80a571cc8..e0a3ad1227f88d363f3e10bf3fe48b46bde5e444 100644 (file)
     <ClInclude Include="..\mono\mini\mini-amd64-gsharedvt.h">\r
       <Filter>Header Files</Filter>\r
     </ClInclude>\r
+    <ClInclude Include="..\mono\mini\mini-windows.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
   </ItemGroup>\r
   <ItemGroup>\r
     <Filter Include="Header Files">\r
index 78517bc7c3aece3e8f2b96fc3d519c791872fe43..06836b9b0f83279c80f69bfadb86467affbc24e2 100644 (file)
     <ClCompile Include="..\mono\metadata\class.c" />\r
     <ClCompile Include="..\mono\metadata\cominterop.c" />\r
     <ClCompile Include="..\mono\metadata\console-win32.c" />\r
+    <ClCompile Include="..\mono\metadata\socket-io-windows.c" />\r
+    <ClCompile Include="..\mono\metadata\file-io-windows.c" />\r
+    <ClCompile Include="..\mono\metadata\icall-windows.c" />\r
+    <ClCompile Include="..\mono\metadata\marshal-windows.c" />\r
+    <ClCompile Include="..\mono\metadata\mono-security-windows.c" />\r
+    <ClCompile Include="..\mono\metadata\process-windows.c" />\r
     <ClCompile Include="..\mono\metadata\w32mutex-win32.c" />\r
     <ClCompile Include="..\mono\metadata\w32semaphore-win32.c" />\r
     <ClCompile Include="..\mono\metadata\w32event-win32.c" />\r
     <ClInclude Include="..\mono\metadata\class.h" />\r
     <ClInclude Include="..\mono\metadata\cominterop.h" />\r
     <ClInclude Include="..\mono\metadata\console-io.h" />\r
+    <ClInclude Include="..\mono\metadata\console-win32-internals.h" />\r
+    <ClInclude Include="..\mono\metadata\coree-internals.h" />\r
     <ClInclude Include="..\mono\metadata\coree.h" />\r
     <ClInclude Include="..\mono\metadata\culture-info-tables.h" />\r
     <ClInclude Include="..\mono\metadata\culture-info.h" />\r
     <ClInclude Include="..\mono\metadata\dynamic-stream-internals.h" />\r
     <ClInclude Include="..\mono\metadata\environment.h" />\r
     <ClInclude Include="..\mono\metadata\exception.h" />\r
+    <ClInclude Include="..\mono\metadata\file-io-internals.h" />\r
+    <ClInclude Include="..\mono\metadata\file-io-windows-internals.h" />\r
     <ClInclude Include="..\mono\metadata\file-io.h" />\r
     <ClInclude Include="..\mono\metadata\filewatcher.h" />\r
     <ClInclude Include="..\mono\metadata\gc-internals.h" />\r
     <ClInclude Include="..\mono\metadata\handle.h" />\r
+    <ClInclude Include="..\mono\metadata\icall-windows-internals.h" />\r
+    <ClInclude Include="..\mono\metadata\icall-internals.h" />\r
+    <ClInclude Include="..\mono\metadata\marshal-internals.h" />\r
+    <ClInclude Include="..\mono\metadata\marshal-windows-internals.h" />\r
+    <ClInclude Include="..\mono\metadata\mono-security-windows-internals.h" />\r
     <ClInclude Include="..\mono\metadata\number-ms.h" />\r
+    <ClInclude Include="..\mono\metadata\process-internals.h" />\r
+    <ClInclude Include="..\mono\metadata\process-windows-internals.h" />\r
     <ClInclude Include="..\mono\metadata\remoting.h" />\r
     <ClInclude Include="..\mono\metadata\seq-points-data.h" />\r
     <ClInclude Include="..\mono\metadata\sgen-bridge-internals.h" />\r
     <ClInclude Include="..\mono\metadata\sgen-client-mono.h" />\r
+    <ClInclude Include="..\mono\metadata\socket-io-windows-internals.h" />\r
     <ClInclude Include="..\mono\metadata\threadpool-ms-io.h" />\r
     <ClInclude Include="..\mono\metadata\threadpool-ms.h" />\r
     <ClInclude Include="..\mono\sgen\gc-internal-agnostic.h" />\r
index ba4d25f1ba94d8e9c6028b819c66bbfb4f414532..10ea5f5b356ae49a74d1e9fa5acba34a46039444 100644 (file)
     <ClCompile Include="..\mono\metadata\sgen-os-coop.c">\r
       <Filter>Source Files\sgen</Filter>\r
     </ClCompile>\r
+    <ClCompile Include="..\mono\metadata\socket-io-windows.c">\r
+         <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\mono\metadata\file-io-windows.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\mono\metadata\icall-windows.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\mono\metadata\marshal-windows.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\mono\metadata\mono-security-windows.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\mono\metadata\process-windows.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
   </ItemGroup>\r
   <ItemGroup>\r
     <ClInclude Include="..\mono\metadata\appdomain.h">\r
     <ClInclude Include="..\mono\metadata\sre-internals.h">\r
       <Filter>Header Files</Filter>\r
     </ClInclude>\r
+    <ClInclude Include="..\mono\metadata\socket-io-windows-internals.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\mono\metadata\coree-internals.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\mono\metadata\console-win32-internals.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\mono\metadata\file-io-windows-internals.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\mono\metadata\file-io-internals.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\mono\metadata\icall-internals.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\mono\metadata\icall-windows-internals.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\mono\metadata\marshal-windows-internals.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\mono\metadata\marshal-internals.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\mono\metadata\mono-security-windows-internals.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\mono\metadata\process-windows-internals.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\mono\metadata\process-internals.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
   </ItemGroup>\r
   <ItemGroup>\r
     <Filter Include="Header Files">\r
index ca9ce67c4658365ada96d183ab9f909a5e9a2ec0..5f2d80f47a6dee4d3cf0566fa981ec9ba4216a07 100644 (file)
     <ClCompile Include="..\mono\utils\mono-log-common.c" />\r
     <ClCompile Include="..\mono\utils\mono-math.c" />\r
     <ClCompile Include="..\mono\utils\mono-md5.c" />\r
+    <ClCompile Include="..\mono\utils\mono-mmap-windows.c" />\r
     <ClCompile Include="..\mono\utils\mono-mmap.c" />\r
     <ClCompile Include="..\mono\utils\mono-networkinterfaces.c" />\r
+    <ClCompile Include="..\mono\utils\mono-proclib-windows.c" />\r
+    <ClCompile Include="..\mono\utils\mono-rand-windows.c" />\r
     <ClCompile Include="..\mono\utils\mono-rand.c" />\r
     <ClCompile Include="..\mono\utils\mono-threads-state-machine.c" />\r
     <ClCompile Include="..\mono\utils\networking.c" />\r
     <ClInclude Include="..\mono\utils\mono-counters.h" />\r
     <ClInclude Include="..\mono\utils\mono-digest.h" />\r
     <ClInclude Include="..\mono\utils\mono-dl-fallback.h" />\r
+    <ClInclude Include="..\mono\utils\mono-dl-windows.h" />\r
     <ClInclude Include="..\mono\utils\mono-dl.h" />\r
     <ClInclude Include="..\mono\utils\mono-error-internals.h" />\r
     <ClInclude Include="..\mono\utils\mono-error.h" />\r
     <ClInclude Include="..\mono\utils\mono-math.h" />\r
     <ClInclude Include="..\mono\utils\mono-membar.h" />\r
     <ClInclude Include="..\mono\utils\mono-memory-model.h" />\r
+    <ClInclude Include="..\mono\utils\mono-mmap-windows.h" />\r
     <ClInclude Include="..\mono\utils\mono-mmap.h" />\r
     <ClInclude Include="..\mono\utils\mono-networkinterfaces.h" />\r
     <ClInclude Include="..\mono\utils\mono-once.h" />\r
     <ClInclude Include="..\mono\utils\mono-os-semaphore.h" />\r
     <ClInclude Include="..\mono\utils\mono-path.h" />\r
     <ClInclude Include="..\mono\utils\mono-poll.h" />\r
+    <ClInclude Include="..\mono\utils\mono-proclib-windows.h" />\r
     <ClInclude Include="..\mono\utils\mono-proclib.h" />\r
     <ClInclude Include="..\mono\utils\mono-property-hash.h" />\r
     <ClInclude Include="..\mono\utils\mono-publib.h" />\r
+    <ClInclude Include="..\mono\utils\mono-rand-windows.h" />\r
     <ClInclude Include="..\mono\utils\mono-rand.h" />\r
     <ClInclude Include="..\mono\utils\mono-sigcontext.h" />\r
     <ClInclude Include="..\mono\utils\mono-stack-unwinding.h" />\r
   <ImportGroup Label="ExtensionTargets">\r
     <Import Project="$(VCTargetsPath)\BuildCustomizations\masm.targets" />\r
   </ImportGroup>\r
-</Project>
+</Project>
\ No newline at end of file
index dae5e304a8738c178927c709bde9b29795b02e85..f74ea0cb33c66b7a97f36ed73dd04fc2f5716d84 100644 (file)
     <ClCompile Include="..\mono\utils\mono-log-windows.c">\r
       <Filter>Source Files</Filter>\r
     </ClCompile>\r
+    <ClCompile Include="..\mono\utils\mono-rand-windows.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\mono\utils\mono-proclib-windows.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\mono\utils\mono-mmap-windows.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
   </ItemGroup>\r
   <ItemGroup>\r
     <ClInclude Include="..\mono\utils\atomic.h">\r
     <ClInclude Include="..\mono\utils\valgrind.h">\r
       <Filter>Header Files</Filter>\r
     </ClInclude>\r
+    <ClInclude Include="..\mono\utils\mono-rand-windows.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\mono\utils\mono-dl-windows.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\mono\utils\mono-mmap-windows.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\mono\utils\mono-proclib-windows.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
   </ItemGroup>\r
   <ItemGroup>\r
     <Filter Include="Header Files">\r
index fca1c3d1d9c09cfb2b76a2fac8804126d102934a..611e4c7035cc49ff71830dfce29f6a8eabeb4c0f 100644 (file)
@@ -97,4 +97,18 @@ CloseZStream
 ReadZStream\r
 WriteZStream\r
 Flush\r
-\r
+zipWriteInFileInZip\r
+zipCloseFileInZip\r
+zipOpen2\r
+zipClose\r
+zipOpenNewFileInZip\r
+unzOpen2\r
+unzCloseCurrentFile\r
+unztell\r
+unzGoToFirstFile\r
+unzGoToNextFile\r
+unzLocateFile\r
+unzOpenCurrentFile2\r
+unzGetCurrentFileInfo\r
+unzReadCurrentFile\r
+unzClose\r
index 83304969ab20ec2f93929d747146fd03db64a965..de0276892fa51410ace9318b026d559401d2cdc4 100644 (file)
@@ -87,7 +87,6 @@
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">\r
     <ClCompile>\r
       <Optimization>Disabled</Optimization>\r
-      <AdditionalIncludeDirectories>$(MONO_DIR);$(MONO_EGLIB_SOURCE_DIR);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
       <PreprocessorDefinitions>_DEBUG;__i386__;TARGET_X86;_WIN32_WINNT=0x0600;WIN32;_WIN32;__WIN32__;_WINDOWS;WINDOWS;HOST_WIN32;TARGET_WIN32;_CRT_SECURE_NO_DEPRECATE;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
       <MinimalRebuild>true</MinimalRebuild>\r
       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>\r
@@ -96,6 +95,7 @@
       <WarningLevel>Level3</WarningLevel>\r
       <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r
       <CompileAs>CompileAsC</CompileAs>\r
+      <AdditionalIncludeDirectories>$(MONO_DIR);$(MONO_EGLIB_SOURCE_DIR);$(MONO_DIR)/support;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
     </ClCompile>\r
     <Link>\r
       <AdditionalDependencies>eglib.lib;%(AdditionalDependencies)</AdditionalDependencies>\r
     </Midl>\r
     <ClCompile>\r
       <Optimization>Disabled</Optimization>\r
-      <AdditionalIncludeDirectories>$(MONO_DIR);$(MONO_EGLIB_SOURCE_DIR);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
       <PreprocessorDefinitions>_DEBUG;__x86_64__;_WIN32_WINNT=0x0600;WIN64;_WIN64;WIN32;_WIN32;__WIN32__;_WINDOWS;WINDOWS;HOST_WIN32;TARGET_WIN32;_CRT_SECURE_NO_DEPRECATE;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
       <MinimalRebuild>true</MinimalRebuild>\r
       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>\r
       <WarningLevel>Level3</WarningLevel>\r
       <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r
       <CompileAs>CompileAsC</CompileAs>\r
+      <AdditionalIncludeDirectories>$(MONO_DIR);$(MONO_EGLIB_SOURCE_DIR);$(MONO_DIR)/support;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
     </ClCompile>\r
     <Link>\r
       <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>\r
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">\r
     <ClCompile>\r
       <Optimization>MinSpace</Optimization>\r
-      <AdditionalIncludeDirectories>$(MONO_DIR);$(MONO_EGLIB_SOURCE_DIR);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
       <PreprocessorDefinitions>NDEBUG;__i386__;TARGET_X86;i386;_WIN32_WINNT=0x0600;WIN32;_WIN32;__WIN32__;_WINDOWS;WINDOWS;HOST_WIN32;TARGET_WIN32;_CRT_SECURE_NO_DEPRECATE;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
       <PrecompiledHeader>\r
       </PrecompiledHeader>\r
       <WarningLevel>Level3</WarningLevel>\r
       <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r
       <CompileAs>CompileAsC</CompileAs>\r
+      <AdditionalIncludeDirectories>$(MONO_DIR);$(MONO_EGLIB_SOURCE_DIR);$(MONO_DIR)/support;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
     </ClCompile>\r
     <Link>\r
       <AdditionalDependencies>eglib.lib;%(AdditionalDependencies)</AdditionalDependencies>\r
     </Midl>\r
     <ClCompile>\r
       <Optimization>MinSpace</Optimization>\r
-      <AdditionalIncludeDirectories>$(MONO_DIR);$(MONO_EGLIB_SOURCE_DIR);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
       <PreprocessorDefinitions>NDEBUG;__x86_64__;_WIN32_WINNT=0x0600;WIN64;_WIN64;WIN32;_WIN32;__WIN32__;_WINDOWS;WINDOWS;HOST_WIN32;TARGET_WIN32;_CRT_SECURE_NO_DEPRECATE;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
       <PrecompiledHeader>\r
       </PrecompiledHeader>\r
       <WarningLevel>Level3</WarningLevel>\r
       <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r
       <CompileAs>CompileAsC</CompileAs>\r
+      <AdditionalIncludeDirectories>$(MONO_DIR);$(MONO_EGLIB_SOURCE_DIR);$(MONO_DIR)/support;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
     </ClCompile>\r
     <Link>\r
       <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>\r
     <ClCompile Include="..\support\inflate.c" />\r
     <ClCompile Include="..\support\inftrees.c" />\r
     <ClCompile Include="..\support\map.c" />\r
+    <ClCompile Include="..\support\minizip\ioapi.c" />\r
+    <ClCompile Include="..\support\minizip\iowin32.c" />\r
+    <ClCompile Include="..\support\minizip\minizip.c" />\r
+    <ClCompile Include="..\support\minizip\unzip.c" />\r
+    <ClCompile Include="..\support\minizip\zip.c" />\r
     <ClCompile Include="..\support\signal.c" />\r
     <ClCompile Include="..\support\stdio.c" />\r
     <ClCompile Include="..\support\stdlib.c" />\r
     <ClInclude Include="..\support\inflate.h" />\r
     <ClInclude Include="..\support\inftrees.h" />\r
     <ClInclude Include="..\support\map.h" />\r
+    <ClInclude Include="..\support\minizip\crypt.h" />\r
+    <ClInclude Include="..\support\minizip\ioapi.h" />\r
+    <ClInclude Include="..\support\minizip\iowin32.h" />\r
+    <ClInclude Include="..\support\minizip\unzip.h" />\r
+    <ClInclude Include="..\support\minizip\zip.h" />\r
     <ClInclude Include="..\support\mph.h" />\r
     <ClInclude Include="..\support\trees.h" />\r
     <ClInclude Include="..\support\zconf.h" />\r
+    <ClInclude Include="..\support\zlib.h" />\r
     <ClInclude Include="..\support\zutil.h" />\r
   </ItemGroup>\r
   <ItemGroup>\r
index 9df33f5e0d4580e92a5ec3325a5827f1df5a95d1..1cd4d6b86659f977351c9e9a6ab4f309af855c4f 100644 (file)
     <ClCompile Include="..\support\zutil.c">\r
       <Filter>Source Files</Filter>\r
     </ClCompile>\r
+    <ClCompile Include="..\support\minizip\iowin32.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\support\minizip\minizip.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\support\minizip\unzip.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\support\minizip\zip.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\support\minizip\ioapi.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
   </ItemGroup>\r
   <ItemGroup>\r
     <ClInclude Include="..\support\crc32.h">\r
     <ClInclude Include="..\support\zutil.h">\r
       <Filter>Header Files</Filter>\r
     </ClInclude>\r
+    <ClInclude Include="..\support\minizip\crypt.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\support\minizip\unzip.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\support\minizip\iowin32.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\support\minizip\zip.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\support\zlib.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\support\minizip\ioapi.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
   </ItemGroup>\r
   <ItemGroup>\r
     <Filter Include="Header Files">\r
index 5a6e9116bd9759204af84f6bbdaa11fd2f611fb0..36dc0ecaab784bf2821ed819726385cece236c45 100644 (file)
@@ -96,7 +96,7 @@
     <ClCompile>\r
       <Optimization>Disabled</Optimization>\r
       <AdditionalIncludeDirectories>$(MONO_DIR);$(MONO_INCLUDE_DIR);$(MONO_JIT_INCLUDE_DIR);$(MONO_EGLIB_SOURCE_DIR);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
-      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_WINDOWS;__WIN32__;HOST_WIN32;TARGET_WIN32;__i386__;TARGET_X86;GC_NOT_DLL;GC_GCJ_SUPPORT;GC_WIN32_THREADS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <PreprocessorDefinitions>WIN32;WIN32_LEAN_AND_MEAN;_DEBUG;_CONSOLE;_WINDOWS;__WIN32__;HOST_WIN32;TARGET_WIN32;__i386__;TARGET_X86;GC_NOT_DLL;GC_GCJ_SUPPORT;GC_WIN32_THREADS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
       <MinimalRebuild>true</MinimalRebuild>\r
       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>\r
       <PrecompiledHeader>\r
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">\r
     <ClCompile>\r
       <Optimization>MinSpace</Optimization>\r
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <PreprocessorDefinitions>WIN32;WIN32_LEAN_AND_MEAN;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
       <PrecompiledHeader>\r
       </PrecompiledHeader>\r
       <WarningLevel>Level3</WarningLevel>\r
     <ClCompile>\r
       <Optimization>Disabled</Optimization>\r
       <AdditionalIncludeDirectories>$(MONO_DIR);$(MONO_INCLUDE_DIR);$(MONO_JIT_INCLUDE_DIR);$(MONO_EGLIB_SOURCE_DIR);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
-      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_WINDOWS;__WIN32__;HOST_WIN32;TARGET_WIN32;__i386__;TARGET_X86;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <PreprocessorDefinitions>WIN32;WIN32_LEAN_AND_MEAN;_DEBUG;_CONSOLE;_WINDOWS;__WIN32__;HOST_WIN32;TARGET_WIN32;__i386__;TARGET_X86;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
       <MinimalRebuild>true</MinimalRebuild>\r
       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>\r
       <PrecompiledHeader>\r
     </Midl>\r
     <ClCompile>\r
       <Optimization>MinSpace</Optimization>\r
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <PreprocessorDefinitions>WIN32;WIN32_LEAN_AND_MEAN;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
       <PrecompiledHeader>\r
       </PrecompiledHeader>\r
       <WarningLevel>Level3</WarningLevel>\r
     <ClCompile Include="..\mono\metadata\console-win32.c" />\r
     <ClCompile Include="..\mono\metadata\domain.c" />\r
     <ClCompile Include="..\mono\metadata\environment.c" />\r
+    <ClCompile Include="..\mono\metadata\file-io-windows.c" />\r
     <ClCompile Include="..\mono\metadata\file-io.c" />\r
     <ClCompile Include="..\mono\metadata\filewatcher.c" />\r
     <ClCompile Include="..\mono\metadata\gc.c" />\r
+    <ClCompile Include="..\mono\metadata\icall-windows.c" />\r
     <ClCompile Include="..\mono\metadata\icall.c" />\r
     <ClCompile Include="..\mono\metadata\image.c" />\r
     <ClCompile Include="..\mono\metadata\loader.c" />\r
     <ClCompile Include="..\mono\metadata\locales.c" />\r
+    <ClCompile Include="..\mono\metadata\marshal-windows.c" />\r
     <ClCompile Include="..\mono\metadata\marshal.c" />\r
     <ClCompile Include="..\mono\metadata\metadata.c" />\r
     <ClCompile Include="..\mono\metadata\monitor.c" />\r
     <ClCompile Include="..\mono\metadata\mono-config.c" />\r
+    <ClCompile Include="..\mono\metadata\process-windows.c" />\r
     <ClCompile Include="..\mono\utils\mono-dl.c" />\r
     <ClCompile Include="..\mono\metadata\object.c" />\r
     <ClCompile Include="..\mono\metadata\process.c" />\r
index 7658bc13f5ccac3041bad6c063a548c009266315..d05fff4fa9698c44a9e6d05351d256f696703009 100644 (file)
     <ClCompile Include="..\tools\pedump\pedump.c">\r
       <Filter>Source Files</Filter>\r
     </ClCompile>\r
+    <ClCompile Include="..\mono\metadata\process-windows.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\mono\metadata\marshal-windows.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\mono\metadata\icall-windows.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\mono\metadata\file-io-windows.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
   </ItemGroup>\r
   <ItemGroup>\r
     <Filter Include="Header Files">\r
index 3174ec4c3fa0308aa18ed717a3e714e9eafce8c3..39595455dadf28dc64a1a5e957b13143d0b365b0 100644 (file)
@@ -158,6 +158,7 @@ EXTRA_DIST =                        \
        update_submodules               \
        mcs.in                          \
        dmcs.in                         \
+       mono-package-runtime    \
        mono-test-install       \
        mono-heapviz            \
        $(MDOC_COMPAT)          \
index 17a154768a1a950c05a644b10d7c75bfb8966647..4784623bd063e18cc08c7080500ffb8b9b3c76fd 100755 (executable)
@@ -9,10 +9,11 @@ ${TESTCMD} --label=verify --timeout=15m make -w -C runtime mcs-compileall
 ${TESTCMD} --label=profiler --timeout=30m make -w -C mono/profiler -k check
 ${TESTCMD} --label=compiler --timeout=30m make -w -C mcs/tests run-test
 ${TESTCMD} --label=compiler-errors --timeout=30m make -w -C mcs/errors run-test
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=System --skip; else ${TESTCMD} --label=System --timeout=10m make -w -C mcs/class/System run-test; fi
+if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=System --skip; else ${TESTCMD} --label=System --timeout=10m bash -c "export MONO_TLS_PROVIDER=legacy && make -w -C mcs/class/System run-test"; fi
+if [[ ${label} == osx-* ]]; then ${TESTCMD} --label=System-btls --timeout=10m bash -c "export MONO_TLS_PROVIDER=btls && make -w -C mcs/class/System run-test"; fi
 ${TESTCMD} --label=System.XML --timeout=5m make -w -C mcs/class/System.XML run-test
 ${TESTCMD} --label=Mono.Security --timeout=5m make -w -C mcs/class/Mono.Security run-test
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=System.Security --skip; else ${TESTCMD} --label=System.Security --timeout=5m make -w -C mcs/class/System.Security run-test; fi
+${TESTCMD} --label=System.Security --timeout=5m make -w -C mcs/class/System.Security run-test
 if [[ ${label} == w* ]]
 then ${TESTCMD} --label=System.Drawing --skip;
 else ${TESTCMD} --label=System.Drawing --timeout=5m make -w -C mcs/class/System.Drawing run-test
@@ -25,7 +26,7 @@ ${TESTCMD} --label=System.Data --timeout=5m make -w -C mcs/class/System.Data run
 ${TESTCMD} --label=System.Data.OracleClient --timeout=5m make -w -C mcs/class/System.Data.OracleClient run-test;
 ${TESTCMD} --label=System.Design --timeout=5m make -w -C mcs/class/System.Design run-test;
 if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=Mono.Posix --skip; else ${TESTCMD} --label=Mono.Posix --timeout=5m make -w -C mcs/class/Mono.Posix run-test; fi
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=System.Web --skip; else ${TESTCMD} --label=System.Web --timeout=30m make -w -C mcs/class/System.Web run-test; fi
+${TESTCMD} --label=System.Web --timeout=30m make -w -C mcs/class/System.Web run-test
 ${TESTCMD} --label=System.Web.Services --timeout=5m make -w -C mcs/class/System.Web.Services run-test
 ${TESTCMD} --label=System.Runtime.SFS --timeout=5m make -w -C mcs/class/System.Runtime.Serialization.Formatters.Soap run-test;
 if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=System.Runtime.Remoting --skip; else ${TESTCMD} --label=System.Runtime.Remoting --timeout=5m make -w -C mcs/class/System.Runtime.Remoting run-test; fi
@@ -36,15 +37,15 @@ ${TESTCMD} --label=I18N.CJK --timeout=5m make -w -C mcs/class/I18N/CJK run-test
 ${TESTCMD} --label=I18N.West --timeout=5m make -w -C mcs/class/I18N/West run-test
 ${TESTCMD} --label=I18N.MidEast --timeout=5m make -w -C mcs/class/I18N/MidEast run-test
 ${TESTCMD} --label=System.DirectoryServices --timeout=5m make -w -C mcs/class/System.DirectoryServices run-test
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=Microsoft.Build.Engine --skip; else ${TESTCMD} --label=Microsoft.Build.Engine --timeout=5m make -w -C mcs/class/Microsoft.Build.Engine run-test; fi
+${TESTCMD} --label=Microsoft.Build.Engine --timeout=5m make -w -C mcs/class/Microsoft.Build.Engine run-test
 ${TESTCMD} --label=Microsoft.Build.Framework --timeout=5m make -w -C mcs/class/Microsoft.Build.Framework run-test
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=Microsoft.Build.Tasks --skip; else ${TESTCMD} --label=Microsoft.Build.Tasks --timeout=5m make -w -C mcs/class/Microsoft.Build.Tasks run-test; fi
+${TESTCMD} --label=Microsoft.Build.Tasks --timeout=5m make -w -C mcs/class/Microsoft.Build.Tasks run-test
 ${TESTCMD} --label=Microsoft.Build.Utilities --timeout=5m make -w -C mcs/class/Microsoft.Build.Utilities run-test
 ${TESTCMD} --label=Mono.C5 --timeout=5m make -w -C mcs/class/Mono.C5 run-test
 ${TESTCMD} --label=Mono.Tasklets --timeout=5m make -w -C mcs/class/Mono.Tasklets run-test
 ${TESTCMD} --label=System.Configuration --timeout=5m make -w -C mcs/class/System.Configuration run-test
 ${TESTCMD} --label=System.Transactions --timeout=5m make -w -C mcs/class/System.Transactions run-test
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=System.Web.Extensions --skip; else ${TESTCMD} --label=System.Web.Extensions --timeout=5m make -w -C mcs/class/System.Web.Extensions run-test; fi
+${TESTCMD} --label=System.Web.Extensions --timeout=5m make -w -C mcs/class/System.Web.Extensions run-test
 if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=System.Core --skip; else ${TESTCMD} --label=System.Core --timeout=15m make -w -C mcs/class/System.Core run-test; fi
 if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=symbolicate --skip; else ${TESTCMD} --label=symbolicate --timeout=60m make -w -C mcs/tools/mono-symbolicate check; fi
 ${TESTCMD} --label=System.Xml.Linq --timeout=5m make -w -C mcs/class/System.Xml.Linq run-test
@@ -60,9 +61,9 @@ ${TESTCMD} --label=System.ComponentModel.DataAnnotations --timeout=5m make -w -C
 ${TESTCMD} --label=Mono.CodeContracts --timeout=5m make -w -C mcs/class/Mono.CodeContracts run-test
 ${TESTCMD} --label=System.Runtime.Caching --timeout=5m make -w -C mcs/class/System.Runtime.Caching run-test
 ${TESTCMD} --label=System.Data.Services --timeout=5m make -w -C mcs/class/System.Data.Services run-test
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=System.Web.DynamicData --skip; else ${TESTCMD} --label=System.Web.DynamicData --timeout=5m make -w -C mcs/class/System.Web.DynamicData run-test; fi
+${TESTCMD} --label=System.Web.DynamicData --timeout=5m make -w -C mcs/class/System.Web.DynamicData run-test
 ${TESTCMD} --label=Mono.CSharp --timeout=5m make -w -C mcs/class/Mono.CSharp run-test
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=WindowsBase --skip; else ${TESTCMD} --label=WindowsBase --timeout=5m make -w -C mcs/class/WindowsBase run-test; fi
+${TESTCMD} --label=WindowsBase --timeout=5m make -w -C mcs/class/WindowsBase run-test
 ${TESTCMD} --label=System.Numerics --timeout=5m make -w -C mcs/class/System.Numerics run-test
 ${TESTCMD} --label=System.Runtime.DurableInstancing --timeout=5m make -w -C mcs/class/System.Runtime.DurableInstancing run-test
 ${TESTCMD} --label=System.ServiceModel.Discovery --timeout=5m make -w -C mcs/class/System.ServiceModel.Discovery run-test
@@ -71,17 +72,17 @@ ${TESTCMD} --label=System.Net.Http --timeout=5m make -w -C mcs/class/System.Net.
 ${TESTCMD} --label=System.Json --timeout=5m make -w -C mcs/class/System.Json run-test
 ${TESTCMD} --label=System.Threading.Tasks.Dataflow --timeout=5m make -w -C mcs/class/System.Threading.Tasks.Dataflow run-test
 ${TESTCMD} --label=Mono.Debugger.Soft --timeout=5m make -w -C mcs/class/Mono.Debugger.Soft run-test
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=Microsoft.Build --skip; else ${TESTCMD} --label=Microsoft.Build --timeout=5m make -w -C mcs/class/Microsoft.Build run-test; fi
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=monodoc --skip; else ${TESTCMD} --label=monodoc --timeout=10m make -w -C mcs/tools/mdoc run-test; fi
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=Microsoft.Build-12 --skip; else ${TESTCMD} --label=Microsoft.Build-12 --timeout=10m make -w -C mcs/class/Microsoft.Build run-test PROFILE=xbuild_12; fi
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=Microsoft.Build.Engine-12 --skip; else ${TESTCMD} --label=Microsoft.Build.Engine-12 --timeout=60m make -w -C mcs/class/Microsoft.Build.Engine run-test PROFILE=xbuild_12; fi
+${TESTCMD} --label=Microsoft.Build --timeout=5m make -w -C mcs/class/Microsoft.Build run-test
+${TESTCMD} --label=monodoc --timeout=10m make -w -C mcs/tools/mdoc run-test
+${TESTCMD} --label=Microsoft.Build-12 --timeout=10m make -w -C mcs/class/Microsoft.Build run-test PROFILE=xbuild_12
+${TESTCMD} --label=Microsoft.Build.Engine-12 --timeout=60m make -w -C mcs/class/Microsoft.Build.Engine run-test PROFILE=xbuild_12
 ${TESTCMD} --label=Microsoft.Build.Framework-12 --timeout=60m make -w -C mcs/class/Microsoft.Build.Framework run-test PROFILE=xbuild_12
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=Microsoft.Build.Tasks-12 --skip; else ${TESTCMD} --label=Microsoft.Build.Tasks-12 --timeout=60m make -w -C mcs/class/Microsoft.Build.Tasks run-test PROFILE=xbuild_12; fi
+${TESTCMD} --label=Microsoft.Build.Tasks-12 --timeout=60m make -w -C mcs/class/Microsoft.Build.Tasks run-test PROFILE=xbuild_12
 ${TESTCMD} --label=Microsoft.Build.Utilities-12 --timeout=60m make -w -C mcs/class/Microsoft.Build.Utilities run-test PROFILE=xbuild_12
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=Microsoft.Build-14 --skip; else ${TESTCMD} --label=Microsoft.Build-14 --timeout=60m make -w -C mcs/class/Microsoft.Build run-test PROFILE=xbuild_14; fi
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=Microsoft.Build.Engine-14 --skip; else ${TESTCMD} --label=Microsoft.Build.Engine-14 --timeout=60m make -w -C mcs/class/Microsoft.Build.Engine run-test PROFILE=xbuild_14; fi
+${TESTCMD} --label=Microsoft.Build-14 --timeout=60m make -w -C mcs/class/Microsoft.Build run-test PROFILE=xbuild_14
+${TESTCMD} --label=Microsoft.Build.Engine-14 --timeout=60m make -w -C mcs/class/Microsoft.Build.Engine run-test PROFILE=xbuild_14
 ${TESTCMD} --label=Microsoft.Build.Framework-14 --timeout=60m make -w -C mcs/class/Microsoft.Build.Framework run-test PROFILE=xbuild_14
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=Microsoft.Build.Tasks-14 --skip; else ${TESTCMD} --label=Microsoft.Build.Tasks-14 --timeout=60m make -w -C mcs/class/Microsoft.Build.Tasks run-test PROFILE=xbuild_14; fi
+${TESTCMD} --label=Microsoft.Build.Tasks-14 --timeout=60m make -w -C mcs/class/Microsoft.Build.Tasks run-test PROFILE=xbuild_14
 ${TESTCMD} --label=Microsoft.Build.Utilities-14 --timeout=60m make -w -C mcs/class/Microsoft.Build.Utilities run-test PROFILE=xbuild_14
 if [[ ${label} == osx-* ]]
 then ${TESTCMD} --label=ms-test-suite --timeout=15m make -w -C acceptance-tests check-ms-test-suite