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
libgc_threads=win32
with_sigaltstack=no
with_tls=pthread
+ with_sgen_default_concurrent=yes
LN_S=cp
# This forces libgc to use the DllMain based thread registration code on win32
libgc_configure_args="$libgc_configure_args --enable-win32-dllmain=yes"
libgc_threads=pthreads
with_sigaltstack=no
use_sigposix=yes
+ with_sgen_default_concurrent=yes
;;
*-*-kfreebsd*-gnu)
CPPFLAGS="$CPPFLAGS -DGC_FREEBSD_THREADS -D_GNU_SOURCE -D_REENTRANT -DUSE_MMAP -DUSE_MUNMAP -DTHREAD_LOCAL_ALLOC -pthread"
need_link_unlink=yes
with_sigaltstack=no
use_sigposix=yes
+ with_sgen_default_concurrent=yes
;;
*-*-*freebsd*)
if test "x$PTHREAD_CFLAGS" = "x"; then
libgc_threads=pthreads
use_sigposix=yes
has_dtrace=yes
+ with_sgen_default_concurrent=yes
;;
*-*-*openbsd*)
CPPFLAGS="$CPPFLAGS -D_THREAD_SAFE -DGC_OPENBSD_THREADS -DPLATFORM_BSD -D_REENTRANT -DUSE_MMAP"
libgc_threads=pthreads
with_sigaltstack=no
use_sigposix=yes
+ with_sgen_default_concurrent=yes
;;
*-*-linux-android*)
platform_android=yes
disable_munmap=yes
;;
esac
+ with_sgen_default_concurrent=yes
;;
*-*-nacl*)
CPPFLAGS="$CPPFLAGS -DGC_LINUX_THREADS -D_GNU_SOURCE -D_REENTRANT -DUSE_MMAP"
CFLAGS_FOR_LIBGC="$CFLAGS_FOR_LIBGC $BROKEN_DARWIN_FLAGS"
CPPFLAGS_FOR_EGLIB="$CPPFLAGS_FOR_EGLIB $BROKEN_DARWIN_CPPFLAGS"
CFLAGS_FOR_EGLIB="$CFLAGS_FOR_EGLIB $BROKEN_DARWIN_FLAGS"
+ with_sgen_default_concurrent=yes
;;
x*64-*-darwin*)
+ with_sgen_default_concurrent=yes
;;
arm*-darwin*)
has_dtrace=no
-Subproject commit 9f44f259bf5059df6c8019948ea75313bd09a9fb
+Subproject commit 367864ef810859ae3ce652864233b35f2dd5fdbe
\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
using System;
using Mono.Security.Interface;
using System.Security.Cryptography.X509Certificates;
+using MNS = Mono.Net.Security;
namespace Mono.Btls.Interface
{
{
public static bool IsSupported ()
{
- return MonoBtlsProvider.IsSupported ();
+ return MNS.MonoTlsProviderFactory.IsBtlsSupported ();
}
public static MonoTlsProvider GetProvider ()
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
SqliteParameterUnitTests.cs
SqliteFunctionTests.cs
Bug27864.cs
-
+SqliteTests.cs
// Copyright 2015 Xamarin Inc.
//
-#if MONOTOUCH
using System;
using System.Data;
using System.IO;
}
}
} 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
--- /dev/null
+//
+// 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");
+ }
+ }
+ }
+ }
+ }
+}
+++ /dev/null
-//
-// 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);
- }
- }
-}
+++ /dev/null
-//
-// 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);
- }
- }
-}
+++ /dev/null
-//
-// 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
- }
-}
+++ /dev/null
-//
-// 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
- }
-}
+++ /dev/null
-//
-// 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; }
- }
- }
-}
+++ /dev/null
-//
-// 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
- }
-}
+++ /dev/null
-//
-// 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
- }
-}
+++ /dev/null
-//
-// 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);
- }
- }
-}
+++ /dev/null
-//
-// 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 ()
- {
- }
- }
-}
+++ /dev/null
-//
-// 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
- }
-}
+++ /dev/null
-//
-// 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);
- }
- }
-}
+++ /dev/null
-//
-// 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; }
- }
- }
-}
+++ /dev/null
-//
-// 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
- }
-}
+++ /dev/null
-//
-// 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
- }
-}
+++ /dev/null
-//
-// 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
- }
-}
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);
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
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 ();
using System.IO;
using System.Threading;
using System.Threading.Tasks;
-using System.Runtime.CompilerServices;
using System.Security.Cryptography.X509Certificates;
using System.Security.Authentication;
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.");
}
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 ()
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 ()
{
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 ()
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);
case "legacy":
return new LegacyTlsProvider ();
case "btls":
- if (!MonoBtlsProvider.IsSupported ())
+ if (!IsBtlsSupported ())
throw new NotSupportedException ("BTLS in not supported!");
return new MonoBtlsProvider ();
default:
using System;
using System.Net;
using System.Collections.Generic;
+using System.Runtime.CompilerServices;
#if !MOBILE
using System.Reflection;
initialized = true;
}
}
+
+ [MethodImpl (MethodImplOptions.InternalCall)]
+ internal extern static bool IsBtlsSupported ();
#endif
static object locker = new object ();
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 ();
}
}
#if SECURITY_DEP
- readonly ChainValidationHelper validationHelper;
+// readonly ChainValidationHelper validationHelper;
readonly MonoTlsSettings settings;
public MonoTlsStream (HttpWebRequest request, NetworkStream networkStream)
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)
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 {
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) {
}
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) {
}
using System.Net.Security;
+using System.Net.Sockets;
namespace System.Net.Configuration {
sealed class SettingsSectionInternal
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; }
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;
+ }
+ }
}
}
+++ /dev/null
-// 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;
- }
- }
-}
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;
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)
{
this.is_bound = (ProtocolType) (int) result [3] != 0;
this.m_Handle = new SafeSocketHandle ((IntPtr) (long) result [4], true);
+ InitializeSockets ();
+
SocketDefaults ();
}
this.m_Handle = safe_handle;
this.is_connected = true;
+
+ InitializeSockets ();
}
void SocketDefaults ()
#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 ();
[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
+ }
}
}
if (disposing && in_progress != 0)
return;
-
- AcceptSocket = null;
- Buffer = null;
- BufferList = null;
- RemoteEndPoint = null;
- UserToken = null;
- SendPacketsElements = null;
}
public void Dispose ()
+++ /dev/null
-// 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
- }
-}
+++ /dev/null
-// 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);
- }
- }
-}
-
+++ /dev/null
-// 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);
- }
- }
-}
+++ /dev/null
-//
-// 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);
-
- }
- }
-}
-
[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);
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));
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);
#endif
using System;
+using System.Globalization;
using System.IO;
using System.Net.Sockets;
using System.Text;
NetworkCredential credentials;
IPHostEntry hostEntry;
IPEndPoint localEndPoint;
+ IPEndPoint remoteEndPoint;
IWebProxy proxy;
int timeout = 100000;
int rwTimeout = 300000;
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";
State = RequestState.Scheduled;
Thread thread = new Thread (ProcessRequest);
+ thread.IsBackground = true;
thread.Start ();
}
}
asyncResult = new FtpAsyncResult (callback, state);
Thread thread = new Thread (ProcessRequest);
+ thread.IsBackground = true;
thread.Start ();
return asyncResult;
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) {
}
// 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);
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);
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
}
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 ();
HttpWebRequest connect_request;
Exception connect_exception;
- static object classLock = new object ();
MonoTlsStream tlsStream;
#if MONOTOUCH && !MONOTOUCH_TV && !MONOTOUCH_WATCH
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;
+ }
}
}
}
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;
}
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;
{
bool _archived;
X509ExtensionCollection _extensions;
- string _serial;
PublicKey _publicKey;
X500DistinguishedName issuer_name;
X500DistinguishedName subject_name;
_cert = null;
_archived = false;
_extensions = null;
- _serial = null;
_publicKey = null;
issuer_name = null;
subject_name = null;
X509ChainImpl impl;
- static X509ChainStatus[] Empty = new X509ChainStatus [0];
-
internal X509ChainImpl Impl {
get {
X509Helper2.ThrowIfContextInvalid (impl);
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
../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
../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
../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
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);
+ }
}
}
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");
}
}
[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 ();
}
}
}
[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 ();
}
}
}
[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 ();
}
}
}
[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 ();
}
}
#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;
#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);
}
#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;
#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);
#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);
}
}
+ 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 ();
}
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 ();
}
class ServerDeleteFile : FtpServer {
+ public ServerDeleteFile (bool ipv6)
+ : base (ipv6)
+ {
+ }
+
protected override void Run ()
{
Socket client = control.Accept ();
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/";
}
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 ();
class ServerPut : FtpServer {
public List<byte> result = new List<byte> ();
+ public ServerPut (bool ipv6)
+ : base (ipv6)
+ {
+ }
+
protected override void Run ()
{
Socket client = control.Accept ();
}
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 ();
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 ()
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; }
}
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
../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
../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
../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
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
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
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)
}
[Test]
+ [SetCulture ("en-us")]
public void ToStringTest ()
{
Rect r = new Rect (1.0, 2.5, 3, 4);
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
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);
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;
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;
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;
[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);
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,
--- /dev/null
+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;
+ }
+}
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)
[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);
}
}
string[] Files {
get {
if (files == null)
- files = NativeUnzip.GetFiles (Handle);
+ files = NativeVersion.Use32Bit ? NativeUnzip.GetFiles32 (Handle) : NativeUnzip.GetFiles64 (Handle);
return files;
}
}
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 ()
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;
}
}
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()
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);
}
{
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);
}
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;
}
-
}
}
get; set;
}
- public ZlibFileFuncDef IOFunctions {
+ public ZlibFileFuncDef32 IOFunctions32 {
+ get; set;
+ }
+
+ public ZlibFileFuncDef64 IOFunctions64 {
get; set;
}
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)
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;
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)
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)
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 ();
}
- return new IntPtr (count);
+ return (ulong) count;
}
}
}
{
}
+ public RNGCryptoServiceProvider (byte[] rgb)
+ {
+ }
+
+ public RNGCryptoServiceProvider (CspParameters cspParams)
+ {
+ }
+
+ public RNGCryptoServiceProvider (string str)
+ {
+ }
+
~RNGCryptoServiceProvider ()
{
}
get { return territory; }
}
-#if !MOBILE
// FIXME: It is implemented, but would be hell slow.
[ComVisible (false)]
public CultureTypes CultureTypes {
}
}
}
-#endif
public virtual int LCID {
get {
{
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;
}
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
[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)
_handle = RngInitialize (null);
Check ();
}
-#if !MOBILE
+
public RNGCryptoServiceProvider (byte[] rgb)
{
_handle = RngInitialize (rgb);
_handle = RngInitialize (Encoding.UTF8.GetBytes (str));
Check ();
}
-#endif
+
private void Check ()
{
if (_handle == IntPtr.Zero) {
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"
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;
}
#endif // MONO_FEATURE_MULTIPLE_APPDOMAINS
-#if !MOBILE
public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
-#endif
#pragma warning disable 649
#if MOBILE
* of icalls, do not require an increment.
*/
#pragma warning disable 169
- private const int mono_corlib_version = 159;
+ private const int mono_corlib_version = 160;
#pragma warning restore 169
[ComVisible (true)]
[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;
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 ();
+ }
}
}
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;
public class CodePropertyReferenceExpression : CodeExpression {
private CodeExpression targetObject;
private string propertyName;
+#if !MONO
private CodeExpressionCollection parameters = new CodeExpressionCollection();
+#endif
/// <devdoc>
/// <para>
}
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 {
/// </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
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);
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 {
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;
#if !FEATURE_PAL // perfcounter
internal static volatile bool s_PerfCountersEnabled;
#endif
-#endif // !MONO
//************* constructors *************************
DualMode = true;
}
-#if !MONO
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='Sockets.Socket'/> class.
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) {
//
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);
protocolType = Sockets.ProtocolType.Unknown;
if(s_LoggingEnabled)Logging.Exit(Logging.Sockets, this, "Socket", null);
}
-
+#endif
//************* properties *************************
}
}
-
+#if !MONO
/// <devdoc>
/// <para>
/// Gets the amount of data pending in the network's input buffer that can be
InternalSetBlocking(willBlockInternal);
if(s_LoggingEnabled)Logging.Exit(Logging.Sockets, this, "Shutdown", "");
}
-
+#endif
//************* internal and private properties *************************
}
}
+#if !MONO
private CacheSet Caches
{
get
return socketAddress;
}
-
+#endif
internal static void InitializeSockets() {
if (!s_Initialized) {
lock(InternalSyncObject){
if (!s_Initialized) {
+#if !MONO
WSAData wsaData = new WSAData();
SocketError errorCode =
// WSAStartup does not set LastWin32Error
throw new SocketException(errorCode);
}
+#endif
#if !FEATURE_PAL
//
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,
socketV6.Close();
// <
-
+#endif // MONO
#if COMNET_DISABLEIPV6
// 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;
internal AcceptAsyncResult(object myObject, object myState, AsyncCallback myCallBack):base(myObject, myState, myCallBack) {
}
}
-
+#endif
public enum SocketAsyncOperation {
None = 0,
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() {}
}
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
}
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
// 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
+ }
}
}
}
#endregion
+#if !MONO
public class SocketAsyncEventArgs : EventArgs, IDisposable {
// Struct sizes needed for some custom marshalling.
}
}
-#if !MONO
//
internal void SetupCacheProtocol(Uri uri)
{
}
}
+#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);
}
public object OwningObject;
public GeneralAsyncDelegate AsyncCallback;
+#if !MONO
public bool Completed;
+#endif
public ConnectionPool Pool;
public int CreationTimeout;
}
/// </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();
#if DEBUG
GlobalLog.Assert(_count+1 == _stack.Count, "push count mishandle");
#endif
+#if !MONO
_count = _stack.Count;
+#endif
}
}
GlobalLog.Assert(_count-1 == _stack.Count, "pop count mishandle");
doublepush.Remove(pooledStream);
#endif
+#if !MONO
_count = _stack.Count;
+#endif
}
return pooledStream;
}
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
internal long ContentLength;
internal long Length;
+#if MONO
+ const int Offset = 0;
+#else
internal int Offset;
+#endif
internal ProgressData Progress;
WebClient = webClient;
}
+#if !MONO
internal long Length;
internal int Offset;
+#endif
internal ProgressData Progress;
internal class RegexTypeCompiler : RegexCompiler {
private static int _typeCount = 0;
+#if !MONO
private static LocalDataStoreSlot _moduleSlot = Thread.AllocateDataSlot();
+#endif
private AssemblyBuilder _assembly;
private ModuleBuilder _module;
// 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;
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) {
#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) //not continue if the stream is gone / dispose
+ 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
DateTime exitTime;
bool haveExitTime;
-
+
+#if !MONO
bool responding;
bool haveResponding;
bool priorityBoostEnabled;
bool havePriorityBoostEnabled;
+#endif
bool raisedOnExited;
RegisteredWaitHandle registeredWaitHandle;
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.
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
haveProcessorAffinity = false;
havePriorityClass = false;
haveExitTime = false;
+#if !MONO
haveResponding = false;
havePriorityBoostEnabled = false;
+#endif
}
/// <devdoc>
{
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;
[System.Security.SecuritySafeCritical]
get
{
+#if MONO
+ return SORT_VERSION_V4;
+#else
return InternalGetSortVersion();
+#endif
}
}
{
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)]
[SuppressUnmanagedCodeSecurity]
private static extern uint InternalGetSortVersion();
-#endif
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.None)]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[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
}
}
}
}
-#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)]
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
[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,
[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,
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"));
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
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) {
case '\"':
++str_quote;
break;
+ case '\\':
+ // Skip escaped " character
+ c = reader.Read ();
+ if (c == -1)
+ res = false;
+ break;
case -1:
res = false;
break;
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()
{
}
<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">
using System.IO;
using System.Text;
using System.Security.Cryptography.X509Certificates;
-using Mono.Btls;
+using MNS = Mono.Net.Security;
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);
}
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
//
FeedbackSizeValue = %FEEDBACKSIZE%;
%CTOR_INIT%
}
-
+
+ %PROPERTIES%
+
public override void GenerateIV ()
{
IVValue = KeyBuilder.IV (BlockSizeValue >> 3);
public override ICryptoTransform CreateDecryptor (byte[] rgbKey, byte[] rgbIV)
{
+ %CREATEDECRYPTOR_INIT%
+
IntPtr decryptor = IntPtr.Zero;
switch (Mode) {
case CipherMode.CBC:
public override ICryptoTransform CreateEncryptor (byte[] rgbKey, byte[] rgbIV)
{
+ %CREATEENCRYPTOR_INIT%
+
IntPtr encryptor = IntPtr.Zero;
switch (Mode) {
case CipherMode.CBC:
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 ()));
}
}
// 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)
static string inputFile;
static bool quiet;
static bool userStore;
- static bool btlsStore = true;
+ static bool btlsStore = false;
static X509Certificate DecodeCertificate (string s)
{
case "--user":
userStore = true;
break;
- case "--legacy":
- btlsStore = false;
+ case "--btls":
+ btlsStore = true;
break;
default:
WriteLine ("Unknown option '{0}'.", args[i]);
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);
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;
}
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
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);
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 \
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
console-io.h \
coree.c \
coree.h \
+ coree-internals.h \
culture-info.h \
culture-info-tables.h \
debug-helpers.c \
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 \
lock-tracer.h \
marshal.c \
marshal.h \
+ marshal-internals.h \
mempool.c \
mempool.h \
mempool-internals.h \
socket-io.h \
process.c \
process.h \
+ process-internals.h \
profiler.c \
profiler-private.h \
rand.h \
* Changes which are already detected at runtime, like the addition
* of icalls, do not require an increment.
*/
-#define MONO_CORLIB_VERSION 159
+#define MONO_CORLIB_VERSION 160
typedef struct
{
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. */
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. */
* 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;
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
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);
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);
}
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)
{
}
#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 */
--- /dev/null
+/*
+ * 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__ */
+
--- /dev/null
+/*
+ * 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) */
{
}
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
MonoBoolean
ves_icall_System_ConsoleDriver_Isatty (HANDLE handle)
{
DWORD mode;
-
return GetConsoleMode (handle, &mode) != 0;
}
{
return FALSE;
}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
--- /dev/null
+/*
+ * 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__ */
+
--- /dev/null
+/*
+ * 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) */
#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;
}
/* 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;
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;
/* 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)
}
/* 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;
return STATUS_SUCCESS;
}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
/* Called by ntdll.dll. */
STDAPI_(VOID) _CorImageUnloading(PVOID ImageBase)
return CorBindToRuntimeEx (pwszVersion, pwszBuildFlavor, 0, rclsid, riid, ppv);
}
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
HMODULE WINAPI MonoLoadImage(LPCWSTR FileName)
{
HANDLE FileHandle;
CloseHandle(FileHandle);
return NULL;
}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
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)
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;
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);
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)
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);
/* 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;
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
--- /dev/null
+/*
+ * 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__ */
--- /dev/null
+/*
+ * 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_ */
--- /dev/null
+/*
+ * 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, ©_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) */
--- /dev/null
+/*
+ * 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 */
#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>
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);
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
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
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 [] = {
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.
#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 */
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)
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
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)
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", ves_icall_System_Environment_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))
#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)
--- /dev/null
+/*
+ * 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__ */
--- /dev/null
+/*
+ * 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__ */
--- /dev/null
+/*
+ * 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) */
--- /dev/null
+/*
+ * 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 */
#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"
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)
{
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)
if (current - (stack_addr - stack_size) < min_size)
return FALSE;
}
+#endif
return TRUE;
}
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);
}
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;
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
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;
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
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) {
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)
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;
}
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;
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
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;
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)
*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);
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
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)
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);
return mono_string_new_handle (mono_domain_get (), machine_config, error);
}
-static MonoStringHandle
+ICALL_EXPORT MonoStringHandle
+ves_icall_System_Environment_get_bundled_machine_config (MonoError *error)
+{
+ return get_bundled_machine_config (error);
+}
+
+
+ICALL_EXPORT MonoStringHandle
ves_icall_System_Configuration_DefaultConfig_get_bundled_machine_config (MonoError *error)
{
return get_bundled_machine_config (error);
}
-static MonoStringHandle
+ICALL_EXPORT MonoStringHandle
ves_icall_System_Configuration_InternalConfigurationHost_get_bundled_machine_config (MonoError *error)
{
return get_bundled_machine_config (error);
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);
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 */
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
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
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;
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 */
--- /dev/null
+/*
+ * 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__ */
--- /dev/null
+/*
+ * 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__ */
--- /dev/null
+/*
+ * 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) */
--- /dev/null
+/*
+ * 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 */
#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) \
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);
}
/* 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)
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)
{
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;
}
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
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
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)
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)
{
/* 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;
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)
{
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;
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;
-
-#ifdef HOST_WIN32
- res = CoTaskMemAlloc (size);
-#else
- if ((gulong)size == 0)
- /* This returns a valid pointer for size 0 on MS.NET */
- size = 4;
+ void *res = mono_marshal_alloc_co_task_mem (size);
- res = g_try_malloc ((gulong)size);
-#endif
if (!res) {
mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
return NULL;
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;
#endif
}
+const char*
+mono_config_get_reloc_lib_dir (void)
+{
+#ifdef MONO_RELOC_LIBDIR
+ return MONO_RELOC_LIBDIR;
+#else
+ return NULL;
+#endif
+}
+
const char*
mono_config_get_bin_dir (void);
+const char*
+mono_config_get_reloc_lib_dir (void);
+
#endif
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
--- /dev/null
+/*
+ * 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__ */
--- /dev/null
+/*
+ * 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) */
--- /dev/null
+/*
+ * 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 */
#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)
/*
return (size == -1) ? MONO_SYSCONF_DEFAULT_SIZE : size;
}
-
static gchar*
GetTokenName (uid_t uid)
{
return uname;
}
-
static gboolean
IsMemberInList (uid_t user, struct group *g)
{
return result;
}
-
static gboolean
IsDefaultGroup (uid_t user, gid_t group)
{
return result;
}
-
static gboolean
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)
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);
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;
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);
}
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)
{
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;
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));
#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;
}
-static gboolean
+static gboolean
Protect (MonoString *path, gint32 file_mode, gint32 add_dir_mode)
{
gboolean result = FALSE;
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
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;
}
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)
{
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 */
--- /dev/null
+/*
+ * 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__ */
--- /dev/null
+/*
+ * 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__ */
--- /dev/null
+/*
+ * 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) */
--- /dev/null
+/*
+ * 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 */
#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)
{
return NULL;
return handle;
}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT | HAVE_UWP_WINAPI_SUPPORT) */
static MonoImage *system_assembly;
#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;
g_free (data);
}
}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
static void
process_get_assembly_fileversion (MonoObject *filever, MonoAssembly *assembly)
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)
{
return item;
}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
static GPtrArray*
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)
{
return arr;
}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
void
ves_icall_System_Diagnostics_FileVersionInfo_GetVersionInfo_internal (MonoObject *this_obj, MonoString *filename)
}
/* 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;
}
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)
{
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;
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) {
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;
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;
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)
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
}
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
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__
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));
return error == 0;
}
+#endif /* #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT | HAVE_UWP_WINAPI_SUPPORT) */
#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"
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)
{
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.
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, gboolean blocking)
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;
}
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;
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;
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, gint32 *werror, gboolean blocking)
{
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)
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);
HANDLE thread_handle;
MonoNativeThreadId tid;
gboolean ret;
+ gsize stack_set_size;
if (start_delegate)
g_assert (!start_func && !start_func_arg);
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 */
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));
/*
{
}
+#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)
{
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)
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);
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);
}
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");
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) {
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
ins->inst_imm = power2;
break;
}
+ if (cfg->backend->disable_div_with_mul)
+ break;
allocated_vregs = TRUE;
/*
* Replacement of unsigned division with multiplication,
break;
}
+ if (cfg->backend->disable_div_with_mul)
+ break;
/*
* Replacement of signed division with multiplication,
* shifts and additions Hacker's Delight, chapter 10-6.
int vtable_reg = alloc_preg (cfg);
MonoInst *klass_inst = NULL;
- if (src->opcode == OP_PCONST && src->inst_p0 == 0)
+ if (MONO_INS_IS_PCONST_NULL (src))
return src;
if (context_used) {
/* Set target field */
/* Optimize away setting of NULL target */
- if (!(target->opcode == OP_PCONST && target->inst_p0 == 0)) {
+ if (!MONO_INS_IS_PCONST_NULL (target)) {
MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, target), target->dreg);
if (cfg->gen_write_barriers) {
dreg = alloc_preg (cfg);
emit_array_store (MonoCompile *cfg, MonoClass *klass, MonoInst **sp, gboolean safety_checks)
{
if (safety_checks && generic_class_is_reference_type (cfg, klass) &&
- !(sp [2]->opcode == OP_PCONST && sp [2]->inst_p0 == NULL)) {
+ !(MONO_INS_IS_PCONST_NULL (sp [2]))) {
MonoClass *obj_array = mono_array_class_get_cached (mono_defaults.object_class, 1);
MonoMethod *helper = mono_marshal_get_virtual_stelemref (obj_array);
MonoInst *iargs [3];
addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, TRUE);
EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, fsig->params [fsig->param_count - 1], addr->dreg, 0, val->dreg);
- if (cfg->gen_write_barriers && val->type == STACK_OBJ && !(val->opcode == OP_PCONST && val->inst_c0 == 0))
+ if (cfg->gen_write_barriers && val->type == STACK_OBJ && !MONO_INS_IS_PCONST_NULL (val))
emit_write_barrier (cfg, addr, val);
if (cfg->gen_write_barriers && mini_is_gsharedvt_klass (cmethod->klass))
GSHAREDVT_FAILURE (*ip);
MONO_ADD_INS (cfg->cbb, ins);
- if (cfg->gen_write_barriers && *ip == CEE_STIND_REF && method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER && !((sp [1]->opcode == OP_PCONST) && (sp [1]->inst_p0 == 0)))
+ if (cfg->gen_write_barriers && *ip == CEE_STIND_REF && method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER && !MONO_INS_IS_PCONST_NULL (sp [1]))
emit_write_barrier (cfg, sp [0], sp [1]);
inline_costs += 1;
res = handle_unbox_gsharedvt (cfg, klass, *sp);
inline_costs += 2;
} else if (generic_class_is_reference_type (cfg, klass)) {
- MONO_INST_NEW (cfg, res, OP_CASTCLASS);
- res->dreg = alloc_preg (cfg);
- res->sreg1 = (*sp)->dreg;
- res->klass = klass;
- res->type = STACK_OBJ;
- MONO_ADD_INS (cfg->cbb, res);
- cfg->flags |= MONO_CFG_HAS_TYPE_CHECK;
+ if (MONO_INS_IS_PCONST_NULL (*sp)) {
+ EMIT_NEW_PCONST (cfg, res, NULL);
+ res->type = STACK_OBJ;
+ } else {
+ MONO_INST_NEW (cfg, res, OP_CASTCLASS);
+ res->dreg = alloc_preg (cfg);
+ res->sreg1 = (*sp)->dreg;
+ res->klass = klass;
+ res->type = STACK_OBJ;
+ MONO_ADD_INS (cfg->cbb, res);
+ cfg->flags |= MONO_CFG_HAS_TYPE_CHECK;
+ }
} else if (mono_class_is_nullable (klass)) {
res = handle_unbox_nullable (cfg, *sp, klass, context_used);
} else {
if (sp [0]->opcode != OP_LDADDR)
store->flags |= MONO_INST_FAULT;
- if (cfg->gen_write_barriers && mini_type_to_stind (cfg, field->type) == CEE_STIND_REF && !(sp [1]->opcode == OP_PCONST && sp [1]->inst_c0 == 0)) {
+ if (cfg->gen_write_barriers && mini_type_to_stind (cfg, field->type) == CEE_STIND_REF && !MONO_INS_IS_PCONST_NULL (sp [1])) {
if (mini_is_gsharedvt_klass (klass)) {
g_assert (wbarrier_ptr_ins);
emit_write_barrier (cfg, wbarrier_ptr_ins, sp [1]);
EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, sp [0]->dreg, 0, sp [1]->dreg);
ins->flags |= ins_flag;
if (cfg->gen_write_barriers && cfg->method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER &&
- generic_class_is_reference_type (cfg, klass)) {
+ generic_class_is_reference_type (cfg, klass) && !MONO_INS_IS_PCONST_NULL (sp [1])) {
/* insert call to write barrier */
emit_write_barrier (cfg, sp [0], sp [1]);
}
LLVMValueRef rgctx_arg;
LLVMValueRef this_arg;
LLVMTypeRef *vreg_types;
+ gboolean *is_vphi;
LLVMTypeRef method_type;
LLVMBasicBlockRef init_bb, inited_bb;
gboolean *is_dead;
/* 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
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);
*/
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);
/*
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;
}
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);
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);
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);
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);
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);
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;
}
#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
#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
}
/*
/* INEG sets the condition codes, and the OP_LNEG decomposition depends on this on x86 */
#define MONO_INS_HAS_NO_SIDE_EFFECT(ins) (MONO_IS_MOVE (ins) || (ins->opcode == OP_ICONST) || (ins->opcode == OP_I8CONST) || MONO_IS_ZERO (ins) || (ins->opcode == OP_ADD_IMM) || (ins->opcode == OP_R8CONST) || (ins->opcode == OP_LADD_IMM) || (ins->opcode == OP_ISUB_IMM) || (ins->opcode == OP_IADD_IMM) || (ins->opcode == OP_LNEG) || (ins->opcode == OP_ISUB) || (ins->opcode == OP_CMOV_IGE) || (ins->opcode == OP_ISHL_IMM) || (ins->opcode == OP_ISHR_IMM) || (ins->opcode == OP_ISHR_UN_IMM) || (ins->opcode == OP_IAND_IMM) || (ins->opcode == OP_ICONV_TO_U1) || (ins->opcode == OP_ICONV_TO_I1) || (ins->opcode == OP_SEXT_I4) || (ins->opcode == OP_LCONV_TO_U1) || (ins->opcode == OP_ICONV_TO_U2) || (ins->opcode == OP_ICONV_TO_I2) || (ins->opcode == OP_LCONV_TO_I2) || (ins->opcode == OP_LDADDR) || (ins->opcode == OP_PHI) || (ins->opcode == OP_NOP) || (ins->opcode == OP_ZEXT_I4) || (ins->opcode == OP_NOT_NULL) || (ins->opcode == OP_IL_SEQ_POINT))
+#define MONO_INS_IS_PCONST_NULL(ins) ((ins)->opcode == OP_PCONST && (ins)->inst_p0 == 0)
+
#define MONO_METHOD_IS_FINAL(m) (((m)->flags & METHOD_ATTRIBUTE_FINAL) || ((m)->klass && ((m)->klass->flags & TYPE_ATTRIBUTE_SEALED)))
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;
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
int gc_debug_level = 0;
FILE* gc_debug_file;
+static char* gc_params_options;
+static char* gc_debug_options;
/*
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)
{
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;
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=")) {
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, ""))
g_strfreev (opts);
}
+ if (debug_opts)
+ g_free (debug_opts);
+
if (check_mark_bits_after_major_collection)
nursery_clear_policy = CLEAR_AT_GC;
endif
sgen-regular-tests: $(SGEN_REGULAR_TESTS)
- $(MAKE) sgen-regular-tests-plain
+ $(MAKE) sgen-regular-tests-ms
$(MAKE) sgen-regular-tests-ms-conc
$(MAKE) sgen-regular-tests-ms-conc-split
$(MAKE) sgen-regular-tests-ms-split
- $(MAKE) sgen-regular-tests-ms-split-95
- $(MAKE) sgen-regular-tests-plain-clear-at-gc
+ $(MAKE) sgen-regular-tests-ms-conc-split-95
+ $(MAKE) sgen-regular-tests-ms-clear-at-gc
$(MAKE) sgen-regular-tests-ms-conc-clear-at-gc
- $(MAKE) sgen-regular-tests-ms-split-clear-at-gc
+ $(MAKE) sgen-regular-tests-ms-conc-split-clear-at-gc
-sgen-regular-tests-plain: $(SGEN_REGULAR_TESTS) test-runner.exe
- MONO_ENV_OPTIONS="--gc=sgen" MONO_GC_DEBUG="" MONO_GC_PARAMS="" $(RUNTIME) $(TEST_RUNNER) $(TEST_RUNNER_ARGS) --testsuite-name $@ --timeout 900 $(SGEN_REGULAR_TESTS)
+sgen-regular-tests-ms: $(SGEN_REGULAR_TESTS) test-runner.exe
+ MONO_ENV_OPTIONS="--gc=sgen" MONO_GC_DEBUG="" MONO_GC_PARAMS="major=marksweep" $(RUNTIME) $(TEST_RUNNER) $(TEST_RUNNER_ARGS) --testsuite-name $@ --timeout 900 $(SGEN_REGULAR_TESTS)
sgen-regular-tests-ms-conc: $(SGEN_REGULAR_TESTS) test-runner.exe
MONO_ENV_OPTIONS="--gc=sgen" MONO_GC_DEBUG="" MONO_GC_PARAMS="major=marksweep-conc" $(RUNTIME) $(TEST_RUNNER) $(TEST_RUNNER_ARGS) --testsuite-name $@ --timeout 900 $(SGEN_REGULAR_TESTS)
sgen-regular-tests-ms-conc-split: $(SGEN_REGULAR_TESTS) test-runner.exe
MONO_ENV_OPTIONS="--gc=sgen" MONO_GC_DEBUG="" MONO_GC_PARAMS="major=marksweep-conc,minor=split" $(RUNTIME) $(TEST_RUNNER) $(TEST_RUNNER_ARGS) --testsuite-name $@ --timeout 900 $(SGEN_REGULAR_TESTS)
sgen-regular-tests-ms-split: $(SGEN_REGULAR_TESTS) test-runner.exe
- MONO_ENV_OPTIONS="--gc=sgen" MONO_GC_DEBUG="" MONO_GC_PARAMS="minor=split" $(RUNTIME) $(TEST_RUNNER) $(TEST_RUNNER_ARGS) --testsuite-name $@ --timeout 900 $(SGEN_REGULAR_TESTS)
-sgen-regular-tests-ms-split-95: $(SGEN_REGULAR_TESTS) test-runner.exe
- MONO_ENV_OPTIONS="--gc=sgen" MONO_GC_DEBUG="" MONO_GC_PARAMS="minor=split,alloc-ratio=95" $(RUNTIME) $(TEST_RUNNER) $(TEST_RUNNER_ARGS) --testsuite-name $@ --timeout 900 $(SGEN_REGULAR_TESTS)
-sgen-regular-tests-plain-clear-at-gc: $(SGEN_REGULAR_TESTS) test-runner.exe
- MONO_ENV_OPTIONS="--gc=sgen" MONO_GC_DEBUG="clear-at-gc" MONO_GC_PARAMS="" $(RUNTIME) $(TEST_RUNNER) $(TEST_RUNNER_ARGS) --testsuite-name $@ --timeout 900 $(SGEN_REGULAR_TESTS)
+ MONO_ENV_OPTIONS="--gc=sgen" MONO_GC_DEBUG="" MONO_GC_PARAMS="major=marksweep,minor=split" $(RUNTIME) $(TEST_RUNNER) $(TEST_RUNNER_ARGS) --testsuite-name $@ --timeout 900 $(SGEN_REGULAR_TESTS)
+sgen-regular-tests-ms-conc-split-95: $(SGEN_REGULAR_TESTS) test-runner.exe
+ MONO_ENV_OPTIONS="--gc=sgen" MONO_GC_DEBUG="" MONO_GC_PARAMS="major=marksweep-conc,minor=split,alloc-ratio=95" $(RUNTIME) $(TEST_RUNNER) $(TEST_RUNNER_ARGS) --testsuite-name $@ --timeout 900 $(SGEN_REGULAR_TESTS)
+sgen-regular-tests-ms-clear-at-gc: $(SGEN_REGULAR_TESTS) test-runner.exe
+ MONO_ENV_OPTIONS="--gc=sgen" MONO_GC_DEBUG="clear-at-gc" MONO_GC_PARAMS="major=marksweep" $(RUNTIME) $(TEST_RUNNER) $(TEST_RUNNER_ARGS) --testsuite-name $@ --timeout 900 $(SGEN_REGULAR_TESTS)
sgen-regular-tests-ms-conc-clear-at-gc: $(SGEN_REGULAR_TESTS) test-runner.exe
MONO_ENV_OPTIONS="--gc=sgen" MONO_GC_DEBUG="clear-at-gc" MONO_GC_PARAMS="major=marksweep-conc" $(RUNTIME) $(TEST_RUNNER) $(TEST_RUNNER_ARGS) --testsuite-name $@ --timeout 900 $(SGEN_REGULAR_TESTS)
-sgen-regular-tests-ms-split-clear-at-gc: $(SGEN_REGULAR_TESTS) test-runner.exe
- MONO_ENV_OPTIONS="--gc=sgen" MONO_GC_DEBUG="clear-at-gc" MONO_GC_PARAMS="minor=split" $(RUNTIME) $(TEST_RUNNER) $(TEST_RUNNER_ARGS) --testsuite-name $@ --timeout 900 $(SGEN_REGULAR_TESTS)
+sgen-regular-tests-ms-conc-split-clear-at-gc: $(SGEN_REGULAR_TESTS) test-runner.exe
+ MONO_ENV_OPTIONS="--gc=sgen" MONO_GC_DEBUG="clear-at-gc" MONO_GC_PARAMS="major=marksweep-conc,minor=split" $(RUNTIME) $(TEST_RUNNER) $(TEST_RUNNER_ARGS) --testsuite-name $@ --timeout 900 $(SGEN_REGULAR_TESTS)
SGEN_TOGGLEREF_TESTS= \
sgen-toggleref.exe
#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 {
}
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 */
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)
}
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;
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;
}
* 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;
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);
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);
<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
<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
<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
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
<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
<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
<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
<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
<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
${TESTCMD} --label=System.Data.Services --timeout=5m make -w -C mcs/class/System.Data.Services run-test
${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