path = external/boringssl
url = git://github.com/mono/boringssl.git
branch = mono
+[submodule "external/corefx"]
+ path = external/corefx
+ url = git://github.com/mono/corefx.git
dnl *** Btls ***
dnl **************
-AC_ARG_ENABLE(btls, [ --disable-blts Disable the BoringTls provider], enable_btls=$enableval, enable_btls=$BTLS_SUPPORTED)
+AC_ARG_ENABLE(btls, [ --disable-btls Disable the BoringTls provider], enable_btls=$enableval, enable_btls=$BTLS_SUPPORTED)
AC_ARG_WITH(btls_android_ndk, [ --with-btls-android-ndk Android NDK for BoringTls])
AM_CONDITIONAL(BTLS, test x$enable_btls = xyes)
--- /dev/null
+Subproject commit b1aa1d92ca33d0cb8ffbac9b6ff73b284db6bbf1
\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
MicrosoftAjaxLibrary/License.htm \
test-helpers/NetworkHelpers.cs \
test-helpers/SocketResponder.cs \
+ lib/$(monolite_dir)/basic.exe \
$(monolite_files)
.PHONY: all-local $(STD_TARGETS:=-local)
$(monolite_files): lib/$(monolite_dir)/%: lib/build/%
cp -p $< $@
+lib/$(monolite_dir)/basic.exe:
+ cp -p lib/basic/basic.exe lib/$(monolite_dir)
+
$(build_files:%=lib/build/%):
cd $(topdir) && $(MAKE) profile-do--build--all NO_DIR_CHECK=1 SKIP_AOT=1
-dist-monolite: $(monolite_files)
- cp -p lib/basic/basic.exe lib/$(monolite_dir)
+dist-monolite: $(monolite_files) lib/$(monolite_dir)/basic.exe
dist-default: dist-monolite
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
+using System.IO;
using Microsoft.Build.BuildEngine;
using NUnit.Framework;
</Project>
";
+ if (Path.DirectorySeparatorChar == '\\') {
+ documentString = documentString.Replace ("/home", "c:/home");
+ documentString = documentString.Replace ("/tmp", "c:/tmp");
+ }
+
var engine = new Engine (Consts.BinPath);
var project = engine.CreateNewProject ();
project.LoadXml (documentString);
[TestFixture]
public class TargetTest {
+ static bool isMono = Type.GetType ("Mono.Runtime", false) != null;
Engine engine;
Project project;
bool Build (string projectXml, ILogger logger)
{
- if (Environment.OSVersion.Platform == PlatformID.Win32NT) {
+ if (!isMono) {
var reader = new StringReader (projectXml);
var xml = XmlReader.Create (reader);
- return BuildOnWindows (xml, logger);
+ return BuildOnDotNet (xml, logger);
} else {
- return BuildOnLinux (projectXml, logger);
+ return BuildOnMono (projectXml, logger);
}
}
- bool BuildOnWindows (XmlReader reader, ILogger logger)
+ bool BuildOnDotNet (XmlReader reader, ILogger logger)
{
var type = Type.GetType ("Microsoft.Build.Evaluation.ProjectCollection, Microsoft.Build, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
return ret;
}
- bool BuildOnLinux (string projectXml, ILogger logger)
+ bool BuildOnMono (string projectXml, ILogger logger)
{
var engine = new Engine (Consts.BinPath);
var project = engine.CreateNewProject ();
}
[Test]
+ [SetCulture ("en-us")]
public void AllowedFrameworkMembers ()
{
string documentString = @"
}
[Test]
+ [SetCulture ("en-us")]
public void MSBuildPropertyFunctions ()
{
string documentString = @"
Assert.AreEqual(files.Length, include.Count, id + "2");
for (int i = 0; i < files.Length; i++) {
- Assert.AreEqual (files [i], include [i].FinalItemSpec, id + "3, file #" + i);
+ Assert.AreEqual (files [i], include [i].FinalItemSpec.Replace ("\\", "/"), id + "3, file #" + i);
Assert.IsTrue (include[i].HasMetadata ("TargetPath"), id + "4, file #" + i + ", TargetPath metadata missing");
Assert.AreEqual (assignedFiles [i], include[i].GetMetadata("TargetPath"), id + "5, file #" + i);
Assert.IsTrue (include [i].HasMetadata ("Child"), id + "6, file #" + i + ", Child metadata missing");
- Assert.AreEqual ("C" + files [i], include [i].GetMetadata ("Child"), id + "7, file #" + i + ", Child metadata value incorrect");
+ Assert.AreEqual ("C" + files [i], include [i].GetMetadata ("Child").Replace ("\\", "/"), id + "7, file #" + i + ", Child metadata value incorrect");
}
}
Assert.Fail ("Build failed");
}
Assert.IsTrue (File.Exists (target_file), "A2");
- Assert.AreEqual (FileAttributes.Normal, File.GetAttributes (target_file), "A3");
+ if (Environment.OSVersion.Platform == PlatformID.Unix)
+ Assert.AreEqual (FileAttributes.Normal, File.GetAttributes (target_file), "A3");
+ else
+ // On Windows the Archive attribute will be set, not the Normal attribute.
+ Assert.AreEqual (FileAttributes.Archive, File.GetAttributes (target_file), "A3");
}
[Test]
Assert.Fail ("Build failed " + sb.ToString ());
}
Assert.IsTrue (File.Exists (target_file), "A2");
- Assert.AreEqual (FileAttributes.Normal, File.GetAttributes (target_file), "A3");
+ var target_file_attrs = File.GetAttributes (target_file);
+ if (Environment.OSVersion.Platform == PlatformID.Unix)
+ Assert.AreEqual (FileAttributes.Normal, File.GetAttributes (target_file), "A3");
+ else
+ // On Windows the Archive attribute will be set, not the Normal attribute.
+ Assert.AreEqual (FileAttributes.Archive, File.GetAttributes (target_file), "A3");
}
[Test]
[Test]
public void TestLineWithEscapedQuote ()
{
+ if (Environment.OSVersion.Platform != PlatformID.Unix) {
+ Assert.Ignore ("Throws \"Illegal characters in path\" on Windows since \" is not a legal Windows path character");
+ }
string[] lines = new string[] { "%22abc test%22 123 %22def%22" };
CreateProjectAndCheck (full_filepath, lines, false, true, delegate () {
CheckFileExists (full_filepath, true);
{
string project_xml = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<ItemGroup>
- <Foo Include='Test/ProjectItemTestTemporary/parent/dir*/a*.cs;Test/ProjectItemTestTemporary/x.cs' />
+ <Foo Include='" + "Test/ProjectItemTestTemporary/parent/dir*/a*.cs;Test/ProjectItemTestTemporary/x.cs".Replace ('/', Path.DirectorySeparatorChar) + @"' />
</ItemGroup>
</Project>";
try {
{
string project_xml = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<ItemGroup>
- <Foo Include='Test/ProjectItemTestTemporary/parent/**/a*.cs;Test/ProjectItemTestTemporary/x.cs' />
+ <Foo Include='" + "Test/ProjectItemTestTemporary/parent/**/a*.cs;Test/ProjectItemTestTemporary/x.cs".Replace ('/', Path.DirectorySeparatorChar) + @"' />
</ItemGroup>
</Project>";
try {
// sort is needed because they are only sorted by ItemType.
var items = proj.Items.OrderBy (p => p.EvaluatedInclude).ToArray ();
Assert.AreEqual (5, items.Length, "#1");
- Assert.AreEqual (string.Format ("Test/ProjectItemTestTemporary/parent/dir1{0}a.cs", Path.DirectorySeparatorChar), items [0].EvaluatedInclude, "#2");
+ Assert.AreEqual ("Test/ProjectItemTestTemporary/parent/dir1/a.cs", items [0].EvaluatedInclude.Replace (Path.DirectorySeparatorChar, '/'), "#2");
Assert.AreEqual ("a", items [0].GetMetadataValue ("Filename"), "#3");
if (hasRecursiveDir)
Assert.AreEqual ("dir1" + sep, items [0].GetMetadataValue ("RecursiveDir"), "#3.2");
- Assert.AreEqual (string.Format ("Test/ProjectItemTestTemporary/parent/dir1{0}a1.cs", Path.DirectorySeparatorChar), items [1].EvaluatedInclude, "#4");
+ Assert.AreEqual ("Test/ProjectItemTestTemporary/parent/dir1/a1.cs", items [1].EvaluatedInclude.Replace (Path.DirectorySeparatorChar, '/'), "#4");
Assert.AreEqual ("a1", items [1].GetMetadataValue ("Filename"), "#5");
if (hasRecursiveDir)
Assert.AreEqual ("dir1" + sep, items [1].GetMetadataValue ("RecursiveDir"), "#5.2");
- Assert.AreEqual (string.Format ("Test/ProjectItemTestTemporary/parent/dir2{0}a.cs", Path.DirectorySeparatorChar), items [2].EvaluatedInclude, "#6");
+ Assert.AreEqual ("Test/ProjectItemTestTemporary/parent/dir2/a.cs", items [2].EvaluatedInclude.Replace (Path.DirectorySeparatorChar, '/'), "#6");
Assert.AreEqual ("a", items [2].GetMetadataValue ("Filename"), "#7");
if (hasRecursiveDir)
Assert.AreEqual ("dir2" + sep, items [2].GetMetadataValue ("RecursiveDir"), "#7.2");
- Assert.AreEqual (string.Format ("Test/ProjectItemTestTemporary/parent/dir2{0}a2.cs", Path.DirectorySeparatorChar), items [3].EvaluatedInclude, "#8");
+ Assert.AreEqual ("Test/ProjectItemTestTemporary/parent/dir2/a2.cs", items [3].EvaluatedInclude.Replace (Path.DirectorySeparatorChar, '/'), "#8");
Assert.AreEqual ("a2", items [3].GetMetadataValue ("Filename"), "#9");
if (hasRecursiveDir)
Assert.AreEqual ("dir2" + sep, items [3].GetMetadataValue ("RecursiveDir"), "#9.2");
- Assert.AreEqual ("Test/ProjectItemTestTemporary/x.cs", items [4].EvaluatedInclude, "#10");
+ Assert.AreEqual ("Test/ProjectItemTestTemporary/x.cs", items [4].EvaluatedInclude.Replace (Path.DirectorySeparatorChar, '/'), "#10");
for (int i = 0; i < items.Length; i++)
Assert.AreEqual (xitem, items [i].Xml, "#11:" + i);
}
Assert.IsTrue (sub.BuildResult.OverallResult == BuildResultCode.Success, "#1");
DateTime endBuildDone = DateTime.Now;
Assert.IsTrue (endBuildDone - beforeExec >= TimeSpan.FromSeconds (1), "#2");
- Assert.IsTrue (endBuildDone > waitDone, "#3");
+ Assert.IsTrue (waitDone >= beforeExec, "#3");
+ Assert.IsTrue (endBuildDone >= waitDone, "#4");
}
[Test]
+++ /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
if (t != Token.Type.Token)
return false;
- int nvalue;
+ long nvalue;
if (!lexer.IsStarStringValue (t)) {
if (!lexer.TryGetNumericValue (t, out nvalue)) {
var s = lexer.GetStringValue (t);
if (sep.Length != 2)
return false;
- if (!int.TryParse (sep[0], NumberStyles.None, CultureInfo.InvariantCulture, out nvalue))
+ if (!long.TryParse (sep[0], NumberStyles.None, CultureInfo.InvariantCulture, out nvalue))
return false;
value.From = nvalue;
- if (!int.TryParse (sep[1], NumberStyles.None, CultureInfo.InvariantCulture, out nvalue))
+ if (!long.TryParse (sep[1], NumberStyles.None, CultureInfo.InvariantCulture, out nvalue))
return false;
value.To = nvalue;
}
} catch (WebException we) {
if (we.Status != WebExceptionStatus.RequestCanceled)
- throw;
+ throw new HttpRequestException ("An error occurred while sending the request", we);
+ } catch (System.IO.IOException ex) {
+ throw new HttpRequestException ("An error occurred while sending the request", ex);
}
if (cancellationToken.IsCancellationRequested) {
Assert.IsNull (res.To, "#22");
Assert.IsNull (res.Length, "#23");
Assert.AreEqual ("by */*", res.ToString (), "#24");
+
+ res = ContentRangeHeaderValue.Parse("bytes 199999999999999999 - 999999999999999999/ 9223372036854775807");
+ Assert.AreEqual (199999999999999999, res.From, "#31");
+ Assert.AreEqual (999999999999999999, res.To, "#32");
+ Assert.AreEqual (9223372036854775807, res.Length, "#33");
+ Assert.AreEqual ("bytes 199999999999999999-999999999999999999/9223372036854775807", res.ToString (), "#34");
}
[Test]
public class WebOperationContextTest
{
// MonoTouch does not support dynamic proxy code generation.
-#if !MONOTOUCH
+#if !MONOTOUCH && !MOBILE_STATIC
[Test]
#endif
public void Current ()
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 ();
../../build/common/Consts.cs
../../build/common/Locale.cs
../../build/common/MonoTODOAttribute.cs
-../System/System/MonoExeLocator.cs
+../System/System/MonoToolsLocator.cs
../System.Windows.Forms/System.Resources/AssemblyNamesTypeResolutionService.cs
../System.Windows.Forms/System.Resources/ByteArrayFromResXHandler.cs
../System.Windows.Forms/System.Resources/ResXNullRef.cs
sw = new StringWriter();
w = new HtmlTextWriter(sw);
a.Render (w);
- Assert.AreEqual ("RenderBeginTag\nRenderContents\nRenderEndTag\n", sw.ToString(), "Render #1");
+ Assert.AreEqual ("RenderBeginTag\nRenderContents\nRenderEndTag\n", sw.ToString().Replace ("\r", ""), "Render #1");
sw = new StringWriter();
public void RenderBeginTag ()
{
a.RenderBeginTag (w);
- Assert.AreEqual ("RenderBeginTag\n", sw.ToString (), "RenderBeginTag #1");
+ Assert.AreEqual ("RenderBeginTag\n", sw.ToString ().Replace ("\r", ""), "RenderBeginTag #1");
}
[Test]
public void RenderContentsTag ()
{
a.RenderContents (w);
- Assert.AreEqual ("RenderContents\n", sw.ToString (), "RenderContents #1");
+ Assert.AreEqual ("RenderContents\n", sw.ToString ().Replace ("\r", ""), "RenderContents #1");
}
[Test]
public void RenderEndTag ()
{
a.RenderEndTag (w);
- Assert.AreEqual ("RenderEndTag\n", sw.ToString (), "RenderEndTag #1");
+ Assert.AreEqual ("RenderEndTag\n", sw.ToString ().Replace ("\r", ""), "RenderEndTag #1");
}
[Test]
public void RenderBeginTag ()
{
a.RenderBeginTag (w);
- Assert.AreEqual ("RenderBeginTag\n", sw.ToString (), "RenderBeginTag #1");
+ Assert.AreEqual ("RenderBeginTag\n", sw.ToString ().Replace ("\r", ""), "RenderBeginTag #1");
}
[Test]
public void RenderContentsTag ()
{
a.RenderContents (w);
- Assert.AreEqual ("RenderContents\n", sw.ToString (), "RenderContents #1");
+ Assert.AreEqual ("RenderContents\n", sw.ToString ().Replace ("\r", ""), "RenderContents #1");
}
[Test]
public void RenderEndTag ()
{
a.RenderEndTag (w);
- Assert.AreEqual ("RenderEndTag\n", sw.ToString (), "RenderEndTag #1");
+ Assert.AreEqual ("RenderEndTag\n", sw.ToString ().Replace ("\r", ""), "RenderEndTag #1");
}
[Test]
public void Render ()
{
a.Render (w);
- Assert.AreEqual ("RenderBeginTag\nRenderContents\nRenderEndTag\n", sw.ToString (), "Render #1");
+ Assert.AreEqual ("RenderBeginTag\nRenderContents\nRenderEndTag\n", sw.ToString ().Replace ("\r", ""), "Render #1");
}
[Test]
Console.WriteLine ("----------------------------");
Console.WriteLine (renderedHtml);
- Assert.AreEqual (origHtml, renderedHtml, "#A1");
+ Assert.AreEqual (origHtml.Replace ("\r", ""), renderedHtml.Replace ("\r", ""), "#A1");
}
[Test]
string origHtml = "Header<table cellspacing=\"5\" cellpadding=\"5\">\r\n\t<tr>\r\n\t\t<td align=\"right\"><input type=\"submit\" name=\"MyWizard$StepNavigationTemplateContainerID$StepPreviousButton\" value=\"Previous\" id=\"MyWizard_StepNavigationTemplateContainerID_StepPreviousButton\" /></td><td align=\"right\"><input type=\"submit\" name=\"MyWizard$StepNavigationTemplateContainerID$StepNextButton\" value=\"Next\" id=\"MyWizard_StepNavigationTemplateContainerID_StepNextButton\" /></td>\n\t</tr>\n</table>Step";
string renderedHtml = HtmlDiff.GetControlFromPageHtml (result);
- Assert.AreEqual (origHtml, renderedHtml, "#A1");
+ Assert.AreEqual (origHtml.Replace ("\r", ""), renderedHtml.Replace ("\r", ""), "#A1");
t.UserData = "RenderHeader_InSpan";
result = t.Run ();
origHtml = "Header<table cellspacing=\"5\" cellpadding=\"5\">\r\n\t<tr>\r\n\t\t<td align=\"right\"><input type=\"submit\" name=\"MyWizard$StepNavigationTemplateContainerID$StepPreviousButton\" value=\"Previous\" id=\"MyWizard_StepNavigationTemplateContainerID_StepPreviousButton\" /></td><td align=\"right\"><input type=\"submit\" name=\"MyWizard$StepNavigationTemplateContainerID$StepNextButton\" value=\"Next\" id=\"MyWizard_StepNavigationTemplateContainerID_StepNextButton\" /></td>\n\t</tr>\n</table>Step";
renderedHtml = HtmlDiff.GetControlFromPageHtml (result);
- Assert.AreEqual (origHtml, renderedHtml, "#A2");
+ Assert.AreEqual (origHtml.Replace ("\r", ""), renderedHtml.Replace ("\r", ""), "#A2");
}
[Test]
../../build/common/MonoTODOAttribute.cs
Assembly/AssemblyInfo.cs
Assembly/Locale.cs
-../System/System/MonoExeLocator.cs
+../System/System/MonoToolsLocator.cs
System.Resources/AssemblyNamesTypeResolutionService.cs
System.Resources/ByteArrayFromResXHandler.cs
System.Resources/ResXNullRef.cs
void SetupCertificateStore ()
{
-#if MONODROID
- ctx.CertificateStore.SetDefaultPaths ();
- ctx.CertificateStore.AddAndroidLookup ();
-#else
- var userPath = MonoBtlsX509StoreManager.GetStorePath (MonoBtlsX509StoreType.UserTrustedRoots);
- if (Directory.Exists (userPath))
- ctx.CertificateStore.AddDirectoryLookup (userPath, MonoBtlsX509FileType.PEM);
- var machinePath = MonoBtlsX509StoreManager.GetStorePath (MonoBtlsX509StoreType.MachineTrustedRoots);
- if (Directory.Exists (machinePath))
- ctx.CertificateStore.AddDirectoryLookup (machinePath, MonoBtlsX509FileType.PEM);
-#endif
+ MonoBtlsProvider.SetupCertificateStore (ctx.CertificateStore);
if (Settings != null && Settings.TrustAnchors != null) {
var trust = IsServer ? MonoBtlsX509TrustKind.TRUST_CLIENT : MonoBtlsX509TrustKind.TRUST_SERVER;
return buffer;
}
+ public bool IsRsa {
+ get {
+ return mono_btls_key_is_rsa (Handle.DangerousGetHandle ()) != 0;
+ }
+ }
+
public MonoBtlsKey Copy ()
{
CheckThrow ();
var passptr = IntPtr.Zero;
fixed (void* ptr = buffer)
try {
- passptr = Marshal.StringToHGlobalAnsi (password ?? string.Empty);
+ if (password != null)
+ passptr = Marshal.StringToHGlobalAnsi (password);
var ret = mono_btls_pkcs12_import (
Handle.DangerousGetHandle (), ptr,
buffer.Length, passptr);
internal override X509Certificate2Impl GetNativeCertificate (
byte[] data, string password, X509KeyStorageFlags flags)
{
- var impl = new X509CertificateImplBtls (true);
+ var impl = new X509CertificateImplBtls (false);
impl.Import (data, password, flags);
return impl;
}
using (var nativeChain = MonoBtlsProvider.GetNativeChain (certificates))
using (var param = GetVerifyParam (targetHost, serverMode))
using (var storeCtx = new MonoBtlsX509StoreCtx ()) {
- store.LoadLocations (null, GetSystemStoreLocation ());
- store.SetDefaultPaths ();
+ SetupCertificateStore (store);
storeCtx.Initialize (store, nativeChain);
}
}
+ internal static bool ValidateCertificate (MonoBtlsX509Chain chain, MonoBtlsX509VerifyParam param)
+ {
+ using (var store = new MonoBtlsX509Store ())
+ using (var storeCtx = new MonoBtlsX509StoreCtx ()) {
+ SetupCertificateStore (store);
+
+ storeCtx.Initialize (store, chain);
+
+ if (param != null)
+ storeCtx.SetVerifyParam (param);
+
+ var ret = storeCtx.Verify ();
+
+ return ret == 1;
+ }
+ }
+
void CheckValidationResult (
ICertificateValidator validator, string targetHost, bool serverMode,
X509CertificateCollection certificates, bool wantsChain,
}
}
+ internal static void SetupCertificateStore (MonoBtlsX509Store store)
+ {
+#if MONODROID
+ store.SetDefaultPaths ();
+ store.AddAndroidLookup ();
+#else
+ var userPath = MonoBtlsX509StoreManager.GetStorePath (MonoBtlsX509StoreType.UserTrustedRoots);
+ if (Directory.Exists (userPath))
+ store.AddDirectoryLookup (userPath, MonoBtlsX509FileType.PEM);
+ var machinePath = MonoBtlsX509StoreManager.GetStorePath (MonoBtlsX509StoreType.MachineTrustedRoots);
+ if (Directory.Exists (machinePath))
+ store.AddDirectoryLookup (machinePath, MonoBtlsX509FileType.PEM);
+#endif
+ }
+
public static string GetSystemStoreLocation ()
{
#if ANDROID
if (Compare (oidValue, emailOid))
type = MonoBtlsX509NameEntryType.Email;
}
- var text = name.GetEntryValue (index);
+ int tag;
+ var text = name.GetEntryValue (index, out tag);
if (text == null)
return false;
var oid = name.GetEntryOid (index);
// 16bits or 8bits string ? TODO not complete (+special chars!)
char[] specials = { ',', '+', '"', '\\', '<', '>', ';' };
- if (quotes) {
+ if (quotes && tag != 0x1E) {
if ((text.IndexOfAny (specials, 0, text.Length) > 0) ||
text.StartsWith (" ") || (text.EndsWith (" ")))
text = "\"" + text + "\"";
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 ()
extern static int mono_btls_x509_name_get_entry_oid_data (IntPtr name, int index, out IntPtr data);
[MethodImpl (MethodImplOptions.InternalCall)]
- extern static int mono_btls_x509_name_get_entry_value (IntPtr name, int index, out IntPtr str);
+ extern static int mono_btls_x509_name_get_entry_value (IntPtr name, int index, out int tag, out IntPtr str);
[MethodImpl (MethodImplOptions.InternalCall)]
extern unsafe static IntPtr mono_btls_x509_name_from_data (void* data, int len, int use_canon_enc);
return bytes;
}
- public unsafe string GetEntryValue (int index)
+ public unsafe string GetEntryValue (int index, out int tag)
{
if (index >= GetEntryCount ())
throw new ArgumentOutOfRangeException ();
IntPtr data;
var ret = mono_btls_x509_name_get_entry_value (
- Handle.DangerousGetHandle (), index, out data);
+ Handle.DangerousGetHandle (), index, out tag, out data);
if (ret <= 0)
return null;
try {
{
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);
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if SECURITY_DEP
+#if MONO_SECURITY_ALIAS
+extern alias MonoSecurity;
+#endif
+
+#if MONO_SECURITY_ALIAS
+using MX = MonoSecurity::Mono.Security.X509;
+#else
+using MX = Mono.Security.X509;
+#endif
+
using System;
using System.Text;
+using System.Collections;
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
-using MX = Mono.Security.X509;
+using Mono.Security.Cryptography;
namespace Mono.Btls
{
return true;
}
- protected override byte [] GetCertHash (bool lazy)
+ protected override byte[] GetCertHash (bool lazy)
{
return X509.GetCertHash ();
}
- public override byte [] GetRawCertData ()
+ public override byte[] GetRawCertData ()
{
return X509.GetRawData (MonoBtlsX509Format.DER);
}
return PublicKey.EncodedParameters.RawData;
}
- public override byte [] Export (X509ContentType contentType, byte [] password)
+ public override byte[] Export (X509ContentType contentType, byte[] password)
{
ThrowIfContextInvalid ();
throw new InvalidOperationException ();
if (fallback != null)
return;
- fallback = X509Helper2.Import (GetRawCertData (), null, X509KeyStorageFlags.DefaultKeySet);
+ fallback = X509Helper2.Import (GetRawCertData (), null, X509KeyStorageFlags.DefaultKeySet, true);
}
- internal X509Certificate2Impl FallbackImpl {
+ internal override X509Certificate2Impl FallbackImpl {
get {
MustFallback ();
return fallback;
}
public override bool HasPrivateKey {
- get { return FallbackImpl.HasPrivateKey; }
+ get { return privateKey != null; }
}
public override X500DistinguishedName IssuerName {
}
public override AsymmetricAlgorithm PrivateKey {
- get { return FallbackImpl.PrivateKey; }
+ get {
+ if (privateKey == null || !privateKey.IsRsa)
+ return null;
+ var bytes = privateKey.GetBytes (true);
+ return PKCS8.PrivateKeyInfo.DecodeRSA (bytes);
+ }
set { FallbackImpl.PrivateKey = value; }
}
return FallbackImpl.GetNameInfo (nameType, forIssuer);
}
- public override void Import (byte [] data, string password, X509KeyStorageFlags keyStorageFlags)
+ public override void Import (byte[] data, string password, X509KeyStorageFlags keyStorageFlags)
{
if (password == null) {
- // Does it look like PEM?
- if ((data.Length > 0) && (data [0] != 0x30))
- x509 = MonoBtlsX509.LoadFromData (data, MonoBtlsX509Format.PEM);
- else
- x509 = MonoBtlsX509.LoadFromData (data, MonoBtlsX509Format.DER);
- return;
+ try {
+ Import (data);
+ } catch (Exception e) {
+ try {
+ ImportPkcs12 (data, null);
+ } catch {
+ string msg = Locale.GetText ("Unable to decode certificate.");
+ // inner exception is the original (not second) exception
+ throw new CryptographicException (msg, e);
+ }
+ }
+ } else {
+ // try PKCS#12
+ try {
+ ImportPkcs12 (data, password);
+ } catch (Exception e) {
+ try {
+ // it's possible to supply a (unrequired/unusued) password
+ // fix bug #79028
+ Import (data);
+ } catch {
+ string msg = Locale.GetText ("Unable to decode certificate.");
+ // inner exception is the original (not second) exception
+ throw new CryptographicException (msg, e);
+ }
+ }
}
+ }
+
+ void Import (byte[] data)
+ {
+ // Does it look like PEM?
+ if ((data.Length > 0) && (data [0] != 0x30))
+ x509 = MonoBtlsX509.LoadFromData (data, MonoBtlsX509Format.PEM);
+ else
+ x509 = MonoBtlsX509.LoadFromData (data, MonoBtlsX509Format.DER);
+ }
+ void ImportPkcs12 (byte[] data, string password)
+ {
using (var pkcs12 = new MonoBtlsPkcs12 ()) {
- pkcs12.Import (data, password);
+ if (string.IsNullOrEmpty (password)) {
+ try {
+ // Support both unencrypted PKCS#12..
+ pkcs12.Import (data, null);
+ } catch {
+ // ..and PKCS#12 encrypted with an empty password
+ pkcs12.Import (data, string.Empty);
+ }
+ } else {
+ pkcs12.Import (data, password);
+ }
+
x509 = pkcs12.GetCertificate (0);
if (pkcs12.HasPrivateKey)
privateKey = pkcs12.GetPrivateKey ();
}
}
- public override byte [] Export (X509ContentType contentType, string password)
+ public override byte[] Export (X509ContentType contentType, string password)
{
- return FallbackImpl.Export (contentType, password);
+ ThrowIfContextInvalid ();
+
+ switch (contentType) {
+ case X509ContentType.Cert:
+ return GetRawCertData ();
+ case X509ContentType.Pfx: // this includes Pkcs12
+ return ExportPkcs12 (password);
+ case X509ContentType.SerializedCert:
+ // TODO
+ throw new NotSupportedException ();
+ default:
+ string msg = Locale.GetText ("This certificate format '{0}' cannot be exported.", contentType);
+ throw new CryptographicException (msg);
+ }
+ }
+
+ byte[] ExportPkcs12 (string password)
+ {
+ var pfx = new MX.PKCS12 ();
+ try {
+ var attrs = new Hashtable ();
+ var localKeyId = new ArrayList ();
+ localKeyId.Add (new byte[] { 1, 0, 0, 0 });
+ attrs.Add (MX.PKCS9.localKeyId, localKeyId);
+ if (password != null)
+ pfx.Password = password;
+ pfx.AddCertificate (new MX.X509Certificate (GetRawCertData ()), attrs);
+ if (IntermediateCertificates != null) {
+ for (int i = 0; i < IntermediateCertificates.Count; i++)
+ pfx.AddCertificate (new MX.X509Certificate (IntermediateCertificates [i].GetRawCertData ()));
+ }
+ var privateKey = PrivateKey;
+ if (privateKey != null)
+ pfx.AddPkcs8ShroudedKeyBag (privateKey, attrs);
+ return pfx.GetBytes ();
+ } finally {
+ pfx.Password = null;
+ }
}
public override bool Verify (X509Certificate2 thisCertificate)
{
- return FallbackImpl.Verify (thisCertificate);
+ using (var chain = new MonoBtlsX509Chain ()) {
+ chain.AddCertificate (x509.Copy ());
+ if (intermediateCerts != null) {
+ for (int i = 0; i < intermediateCerts.Count; i++) {
+ var intermediate = (X509CertificateImplBtls)intermediateCerts [i];
+ chain.AddCertificate (intermediate.x509.Copy ());
+ }
+ }
+ return MonoBtlsProvider.ValidateCertificate (chain, null);
+ }
}
public override void Reset ()
iep = RemapIPEndPoint (iep);
- Connect_internal (m_Handle, iep.Serialize (), out error);
+ Connect_internal (m_Handle, iep.Serialize (), out error, is_blocking);
if (error == 0) {
is_connected = true;
is_bound = true;
SocketAddress serial = remoteEP.Serialize ();
int error = 0;
- Connect_internal (m_Handle, serial, out error);
+ Connect_internal (m_Handle, serial, out error, is_blocking);
if (error == 0 || error == 10035)
seed_endpoint = remoteEP; // Keep the ep around for non-blocking sockets
bool blk = is_blocking;
if (blk)
Blocking = false;
- Connect_internal (m_Handle, end_point.Serialize (), out error);
+ Connect_internal (m_Handle, end_point.Serialize (), out error, false);
if (blk)
Blocking = true;
sockares.CheckIfThrowDelayedException();
}
- static void Connect_internal (SafeSocketHandle safeHandle, SocketAddress sa, out int error)
+ static void Connect_internal (SafeSocketHandle safeHandle, SocketAddress sa, out int error, bool blocking)
{
try {
safeHandle.RegisterForBlockingSyscall ();
- Connect_internal (safeHandle.DangerousGetHandle (), sa, out error);
+ Connect_internal (safeHandle.DangerousGetHandle (), sa, out error, blocking);
} finally {
safeHandle.UnRegisterForBlockingSyscall ();
}
/* Connects to the remote address */
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- extern static void Connect_internal(IntPtr sock, SocketAddress sa, out int error);
+ extern static void Connect_internal(IntPtr sock, SocketAddress sa, out int error, bool blocking);
/* Returns :
* - false when it is ok to use RemoteEndPoint
ThrowIfBufferOutOfRange (buffer, offset, size);
int nativeError;
- int ret = Receive_internal (m_Handle, buffer, offset, size, socketFlags, out nativeError);
+ int ret = Receive_internal (m_Handle, buffer, offset, size, socketFlags, out nativeError, is_blocking);
errorCode = (SocketError) nativeError;
if (errorCode != SocketError.Success && errorCode != SocketError.WouldBlock && errorCode != SocketError.InProgress) {
}
try {
- ret = Receive_internal (m_Handle, bufarray, socketFlags, out nativeError);
+ ret = Receive_internal (m_Handle, bufarray, socketFlags, out nativeError, is_blocking);
} finally {
for (int i = 0; i < numsegments; i++) {
if (gch[i].IsAllocated)
int total = 0;
try {
- total = Receive_internal (sockares.socket.m_Handle, sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, out sockares.error);
+ total = Receive_internal (sockares.socket.m_Handle, sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, out sockares.error, sockares.socket.is_blocking);
} catch (Exception e) {
sockares.Complete (e);
return;
return sockares.Total;
}
- static int Receive_internal (SafeSocketHandle safeHandle, WSABUF[] bufarray, SocketFlags flags, out int error)
+ static int Receive_internal (SafeSocketHandle safeHandle, WSABUF[] bufarray, SocketFlags flags, out int error, bool blocking)
{
try {
safeHandle.RegisterForBlockingSyscall ();
- return Receive_internal (safeHandle.DangerousGetHandle (), bufarray, flags, out error);
+ return Receive_internal (safeHandle.DangerousGetHandle (), bufarray, flags, out error, blocking);
} finally {
safeHandle.UnRegisterForBlockingSyscall ();
}
}
[MethodImplAttribute (MethodImplOptions.InternalCall)]
- extern static int Receive_internal (IntPtr sock, WSABUF[] bufarray, SocketFlags flags, out int error);
+ extern static int Receive_internal (IntPtr sock, WSABUF[] bufarray, SocketFlags flags, out int error, bool blocking);
- static int Receive_internal (SafeSocketHandle safeHandle, byte[] buffer, int offset, int count, SocketFlags flags, out int error)
+ static int Receive_internal (SafeSocketHandle safeHandle, byte[] buffer, int offset, int count, SocketFlags flags, out int error, bool blocking)
{
try {
safeHandle.RegisterForBlockingSyscall ();
- return Receive_internal (safeHandle.DangerousGetHandle (), buffer, offset, count, flags, out error);
+ return Receive_internal (safeHandle.DangerousGetHandle (), buffer, offset, count, flags, out error, blocking);
} finally {
safeHandle.UnRegisterForBlockingSyscall ();
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- extern static int Receive_internal(IntPtr sock, byte[] buffer, int offset, int count, SocketFlags flags, out int error);
+ extern static int Receive_internal(IntPtr sock, byte[] buffer, int offset, int count, SocketFlags flags, out int error, bool blocking);
#endregion
SocketAddress sockaddr = remoteEP.Serialize();
int nativeError;
- int cnt = ReceiveFrom_internal (m_Handle, buffer, offset, size, socketFlags, ref sockaddr, out nativeError);
+ int cnt = ReceiveFrom_internal (m_Handle, buffer, offset, size, socketFlags, ref sockaddr, out nativeError, is_blocking);
errorCode = (SocketError) nativeError;
if (errorCode != SocketError.Success) {
- static int ReceiveFrom_internal (SafeSocketHandle safeHandle, byte[] buffer, int offset, int count, SocketFlags flags, ref SocketAddress sockaddr, out int error)
+ static int ReceiveFrom_internal (SafeSocketHandle safeHandle, byte[] buffer, int offset, int count, SocketFlags flags, ref SocketAddress sockaddr, out int error, bool blocking)
{
try {
safeHandle.RegisterForBlockingSyscall ();
- return ReceiveFrom_internal (safeHandle.DangerousGetHandle (), buffer, offset, count, flags, ref sockaddr, out error);
+ return ReceiveFrom_internal (safeHandle.DangerousGetHandle (), buffer, offset, count, flags, ref sockaddr, out error, blocking);
} finally {
safeHandle.UnRegisterForBlockingSyscall ();
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- extern static int ReceiveFrom_internal(IntPtr sock, byte[] buffer, int offset, int count, SocketFlags flags, ref SocketAddress sockaddr, out int error);
+ extern static int ReceiveFrom_internal(IntPtr sock, byte[] buffer, int offset, int count, SocketFlags flags, ref SocketAddress sockaddr, out int error, bool blocking);
#endregion
int sent = 0;
do {
sent += Send_internal (
-m_Handle, buffer, offset + sent, size - sent, socketFlags, out nativeError);
+m_Handle, buffer, offset + sent, size - sent, socketFlags, out nativeError, is_blocking);
errorCode = (SocketError)nativeError;
if (errorCode != SocketError.Success && errorCode != SocketError.WouldBlock && errorCode != SocketError.InProgress) {
is_connected = false;
}
try {
- ret = Send_internal (m_Handle, bufarray, socketFlags, out nativeError);
+ ret = Send_internal (m_Handle, bufarray, socketFlags, out nativeError, is_blocking);
} finally {
for(int i = 0; i < numsegments; i++) {
if (gch[i].IsAllocated) {
int total = 0;
try {
- total = Socket.Send_internal (sockares.socket.m_Handle, sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, out sockares.error);
+ total = Socket.Send_internal (sockares.socket.m_Handle, sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, out sockares.error, false);
} catch (Exception e) {
sockares.Complete (e);
return;
return sockares.Total;
}
- static int Send_internal (SafeSocketHandle safeHandle, WSABUF[] bufarray, SocketFlags flags, out int error)
+ static int Send_internal (SafeSocketHandle safeHandle, WSABUF[] bufarray, SocketFlags flags, out int error, bool blocking)
{
- bool release = false;
try {
- safeHandle.DangerousAddRef (ref release);
- return Send_internal (safeHandle.DangerousGetHandle (), bufarray, flags, out error);
+ safeHandle.RegisterForBlockingSyscall ();
+ return Send_internal (safeHandle.DangerousGetHandle (), bufarray, flags, out error, blocking);
} finally {
- if (release)
- safeHandle.DangerousRelease ();
+ safeHandle.UnRegisterForBlockingSyscall ();
}
}
[MethodImplAttribute (MethodImplOptions.InternalCall)]
- extern static int Send_internal (IntPtr sock, WSABUF[] bufarray, SocketFlags flags, out int error);
+ extern static int Send_internal (IntPtr sock, WSABUF[] bufarray, SocketFlags flags, out int error, bool blocking);
- static int Send_internal (SafeSocketHandle safeHandle, byte[] buf, int offset, int count, SocketFlags flags, out int error)
+ static int Send_internal (SafeSocketHandle safeHandle, byte[] buf, int offset, int count, SocketFlags flags, out int error, bool blocking)
{
try {
safeHandle.RegisterForBlockingSyscall ();
- return Send_internal (safeHandle.DangerousGetHandle (), buf, offset, count, flags, out error);
+ return Send_internal (safeHandle.DangerousGetHandle (), buf, offset, count, flags, out error, blocking);
} finally {
safeHandle.UnRegisterForBlockingSyscall ();
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- extern static int Send_internal(IntPtr sock, byte[] buf, int offset, int count, SocketFlags flags, out int error);
+ extern static int Send_internal(IntPtr sock, byte[] buf, int offset, int count, SocketFlags flags, out int error, bool blocking);
#endregion
throw new ArgumentNullException("remoteEP");
int error;
- int ret = SendTo_internal (m_Handle, buffer, offset, size, socketFlags, remoteEP.Serialize (), out error);
+ int ret = SendTo_internal (m_Handle, buffer, offset, size, socketFlags, remoteEP.Serialize (), out error, is_blocking);
SocketError err = (SocketError) error;
if (err != 0) {
return sockares.Total;
}
- static int SendTo_internal (SafeSocketHandle safeHandle, byte[] buffer, int offset, int count, SocketFlags flags, SocketAddress sa, out int error)
+ static int SendTo_internal (SafeSocketHandle safeHandle, byte[] buffer, int offset, int count, SocketFlags flags, SocketAddress sa, out int error, bool blocking)
{
try {
safeHandle.RegisterForBlockingSyscall ();
- return SendTo_internal (safeHandle.DangerousGetHandle (), buffer, offset, count, flags, sa, out error);
+ return SendTo_internal (safeHandle.DangerousGetHandle (), buffer, offset, count, flags, sa, out error, blocking);
} finally {
safeHandle.UnRegisterForBlockingSyscall ();
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- extern static int SendTo_internal (IntPtr sock, byte[] buffer, int offset, int count, SocketFlags flags, SocketAddress sa, out int error);
+ extern static int SendTo_internal (IntPtr sock, byte[] buffer, int offset, int count, SocketFlags flags, SocketAddress sa, out int error, bool blocking);
#endregion
if (!is_blocking)
throw new InvalidOperationException ();
- if (!SendFile_internal (m_Handle, fileName, preBuffer, postBuffer, flags)) {
- SocketException exc = new SocketException ();
+ int error = 0;
+ if (!SendFile_internal (m_Handle, fileName, preBuffer, postBuffer, flags, out error, is_blocking) || error != 0) {
+ SocketException exc = new SocketException (error);
if (exc.ErrorCode == 2 || exc.ErrorCode == 3)
throw new FileNotFoundException ();
throw exc;
ares.Delegate.EndInvoke (ares.Original);
}
- static bool SendFile_internal (SafeSocketHandle safeHandle, string filename, byte [] pre_buffer, byte [] post_buffer, TransmitFileOptions flags)
+ static bool SendFile_internal (SafeSocketHandle safeHandle, string filename, byte [] pre_buffer, byte [] post_buffer, TransmitFileOptions flags, out int error, bool blocking)
{
try {
safeHandle.RegisterForBlockingSyscall ();
- return SendFile_internal (safeHandle.DangerousGetHandle (), filename, pre_buffer, post_buffer, flags);
+ return SendFile_internal (safeHandle.DangerousGetHandle (), filename, pre_buffer, post_buffer, flags, out error, blocking);
} finally {
safeHandle.UnRegisterForBlockingSyscall ();
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- extern static bool SendFile_internal (IntPtr sock, string filename, byte [] pre_buffer, byte [] post_buffer, TransmitFileOptions flags);
+ extern static bool SendFile_internal (IntPtr sock, string filename, byte [] pre_buffer, byte [] post_buffer, TransmitFileOptions flags, out int error, bool blocking);
delegate void SendFileHandler (string fileName, byte [] preBuffer, byte [] postBuffer, TransmitFileOptions flags);
+++ /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);
-
- }
- }
-}
-
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;
}
}
internal X500DistinguishedName (byte[] encoded, byte[] canonEncoding, string name)
- : this (encoded)
{
this.canonEncoding = canonEncoding;
this.name = name;
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;
// internal stuff because X509Certificate2 isn't complete enough
// (maybe X509Certificate3 will be better?)
- [Obsolete ("KILL")]
+ [MonoTODO ("See comment in X509Helper2.GetMonoCertificate().")]
internal MX.X509Certificate MonoCertificate {
get {
- var monoImpl = Impl as X509Certificate2ImplMono;
- if (monoImpl == null)
- throw new NotSupportedException ();
- return monoImpl.MonoCertificate;
+ return X509Helper2.GetMonoCertificate (this);
}
}
get;
}
+ internal abstract X509Certificate2Impl FallbackImpl {
+ get;
+ }
+
public abstract string GetNameInfo (X509NameType nameType, bool forIssuer);
public abstract void Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags);
[MonoTODO ("missing KeyStorageFlags support")]
public override void Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
{
+ Reset ();
MX.X509Certificate cert = null;
if (password == null) {
try {
internal MX.X509Certificate MonoCertificate {
get { return _cert; }
}
+
+ internal override X509Certificate2Impl FallbackImpl {
+ get { return this; }
+ }
}
}
#if MONO_SECURITY_ALIAS
using MonoSecurity::Mono.Security.Interface;
+using MX = MonoSecurity::Mono.Security.X509;
#else
#if !FEATURE_NO_BSD_SOCKETS
using Mono.Security.Interface;
#endif
+using MX = Mono.Security.X509;
#endif
#if !FEATURE_NO_BSD_SOCKETS
}
#endif // !FEATURE_NO_BSD_SOCKETS
- internal static X509Certificate2Impl Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
+ internal static X509Certificate2Impl Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags, bool disableProvider = false)
{
#if !FEATURE_NO_BSD_SOCKETS
- var provider = MonoTlsProviderFactory.GetProvider ();
- if (provider.HasNativeCertificates) {
- var impl = provider.GetNativeCertificate (rawData, password, keyStorageFlags);
- return impl;
+ if (!disableProvider) {
+ var provider = MonoTlsProviderFactory.GetProvider ();
+ if (provider.HasNativeCertificates) {
+ var impl = provider.GetNativeCertificate (rawData, password, keyStorageFlags);
+ return impl;
+ }
}
#endif // FEATURE_NO_BSD_SOCKETS
var impl2 = new X509Certificate2ImplMono ();
return impl2;
}
- internal static X509Certificate2Impl Import (X509Certificate cert)
+ internal static X509Certificate2Impl Import (X509Certificate cert, bool disableProvider = false)
{
#if !FEATURE_NO_BSD_SOCKETS
- var provider = MonoTlsProviderFactory.GetProvider ();
- if (provider.HasNativeCertificates) {
- var impl = provider.GetNativeCertificate (cert);
- return impl;
+ if (!disableProvider) {
+ var provider = MonoTlsProviderFactory.GetProvider ();
+ if (provider.HasNativeCertificates) {
+ var impl = provider.GetNativeCertificate (cert);
+ return impl;
+ }
}
#endif // FEATURE_NO_BSD_SOCKETS
var impl2 = cert.Impl as X509Certificate2Impl;
return Import (cert.GetRawCertData (), null, X509KeyStorageFlags.DefaultKeySet);
}
+ /*
+ * This is used by X509ChainImplMono
+ *
+ * Some of the missing APIs such as X509v3 extensions can be added to the native
+ * BTLS implementation.
+ *
+ * We should also consider replacing X509ChainImplMono with a new X509ChainImplBtls
+ * at some point.
+ */
+ [MonoTODO ("Investigate replacement; see comments in source.")]
+ internal static MX.X509Certificate GetMonoCertificate (X509Certificate2 certificate)
+ {
+ var impl2 = certificate.Impl as X509Certificate2Impl;
+ if (impl2 == null)
+ impl2 = Import (certificate, true);
+ var fallbackImpl = impl2.FallbackImpl as X509Certificate2ImplMono;
+ if (fallbackImpl == null)
+ throw new NotSupportedException ();
+ return fallbackImpl.MonoCertificate;
+ }
+
internal static X509ChainImpl CreateChainImpl (bool useMachineContext)
{
return new X509ChainImplMono (useMachineContext);
System.Diagnostics/TraceSourceInfo.cs
System.Diagnostics/Win32EventLog.cs
System/Platform.cs
-System/MonoExeLocator.cs
+System/MonoToolsLocator.cs
System.IO.Compression/CompressionLevel.cs
System.IO.Compression/CompressionMode.cs
System.IO.Compression/DeflateStream.cs
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
../referencesource/System/net/System/Net/Sockets/IPProtectionLevel.cs
../referencesource/System/net/System/Net/Sockets/NetworkStream.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
+++ /dev/null
-#if !MOBILE
-
-using System.Diagnostics;
-using System.IO;
-using System.Reflection;
-using System.Runtime.InteropServices;
-
-namespace System {
-
- static class MonoToolsLocator
- {
- public static readonly string Mono;
- public static readonly string CSharpCompiler;
- public static readonly string VBCompiler;
- public static readonly string AssemblyLinker;
-
- // TODO: Should be lazy
- static MonoToolsLocator ()
- {
- var gac = typeof (Environment).GetProperty ("GacPath", BindingFlags.Static | BindingFlags.NonPublic);
- var getGacMethod = gac.GetGetMethod (true);
- var GacPath = Path.GetDirectoryName ((string) getGacMethod.Invoke (null, null));
-
- if (Path.DirectorySeparatorChar == '\\') {
- string processExe = Process.GetCurrentProcess ().MainModule.FileName;
- if (processExe != null) {
- string fileName = Path.GetFileName (processExe);
- if (fileName.StartsWith ("mono") && fileName.EndsWith (".exe"))
- Mono = processExe;
- }
-
- if (!File.Exists (Mono))
- Mono = Path.Combine (
- Path.GetDirectoryName (
- Path.GetDirectoryName (GacPath)),
- "bin\\mono.exe");
-
- if (!File.Exists (Mono))
- Mono = Path.Combine (
- Path.GetDirectoryName (
- Path.GetDirectoryName (
- Path.GetDirectoryName (GacPath))),
- "mono\\mini\\mono.exe");
-
- //if (!File.Exists (Mono))
- // throw new FileNotFoundException ("Windows mono path not found: " + Mono);
-
- CSharpCompiler = Path.Combine (GacPath, "4.5\\mcs.exe");
- if (!File.Exists (CSharpCompiler))
- CSharpCompiler = Path.Combine (Path.GetDirectoryName (GacPath), "lib\\build\\mcs.exe");
-
- //if (!File.Exists (CSharpCompiler))
- // throw new FileNotFoundException ("C# compiler not found at " + CSharpCompiler);
-
- VBCompiler = Path.Combine (GacPath, "4.5\\vbnc.exe");
- AssemblyLinker = Path.Combine (GacPath, "4.5\\al.exe");
-
- if (!File.Exists (AssemblyLinker)) {
- AssemblyLinker = Path.Combine (Path.GetDirectoryName (GacPath), "lib\\net_4_x\\al.exe");
- // if (!File.Exists (AssemblyLinker))
- // throw new FileNotFoundException ("Windows al path not found: " + AssemblyLinker);
- }
- } else {
- Mono = Path.Combine (GacPath, "bin", "mono");
- if (!File.Exists (Mono))
- Mono = "mono";
-
- var mscorlibPath = new Uri (typeof (object).Assembly.CodeBase).LocalPath;
- CSharpCompiler = Path.GetFullPath (Path.Combine (mscorlibPath, "..", "..", "..", "..", "bin", "mcs"));
- if (!File.Exists (CSharpCompiler))
- CSharpCompiler = "mcs";
-
- VBCompiler = Path.GetFullPath (Path.Combine (mscorlibPath, "..", "..", "..", "..", "bin", "vbnc"));
- if (!File.Exists (VBCompiler))
- VBCompiler = "vbnc";
-
- AssemblyLinker = Path.GetFullPath (Path.Combine (mscorlibPath, "..", "..", "..", "..", "bin", "al"));
- if (!File.Exists (AssemblyLinker))
- AssemblyLinker = "al";
- }
- }
- }
-}
-
-#endif
--- /dev/null
+#if !MOBILE
+
+using System.Diagnostics;
+using System.IO;
+using System.Reflection;
+using System.Runtime.InteropServices;
+using System.Text;
+
+namespace System {
+
+ static class MonoToolsLocator
+ {
+ public static readonly string Mono;
+ public static readonly string CSharpCompiler;
+ public static readonly string VBCompiler;
+ public static readonly string AssemblyLinker;
+
+ // TODO: Should be lazy
+ static MonoToolsLocator ()
+ {
+ var gac = typeof (Environment).GetProperty ("GacPath", BindingFlags.Static | BindingFlags.NonPublic);
+ var getGacMethod = gac.GetGetMethod (true);
+ var GacPath = Path.GetDirectoryName ((string) getGacMethod.Invoke (null, null));
+
+ if (Path.DirectorySeparatorChar == '\\') {
+ StringBuilder moduleName = new StringBuilder (1024);
+ GetModuleFileName (IntPtr.Zero, moduleName, moduleName.Capacity);
+ string processExe = moduleName.ToString ();
+ string fileName = Path.GetFileName (processExe);
+ if (fileName.StartsWith ("mono") && fileName.EndsWith (".exe"))
+ Mono = processExe;
+
+ if (!File.Exists (Mono))
+ Mono = Path.Combine (
+ Path.GetDirectoryName (
+ Path.GetDirectoryName (GacPath)),
+ "bin\\mono.exe");
+
+ if (!File.Exists (Mono))
+ Mono = Path.Combine (
+ Path.GetDirectoryName (
+ Path.GetDirectoryName (
+ Path.GetDirectoryName (GacPath))),
+ "mono\\mini\\mono.exe");
+
+ //if (!File.Exists (Mono))
+ // throw new FileNotFoundException ("Windows mono path not found: " + Mono);
+
+ CSharpCompiler = Path.Combine (GacPath, "4.5\\mcs.exe");
+ if (!File.Exists (CSharpCompiler))
+ CSharpCompiler = Path.Combine (Path.GetDirectoryName (GacPath), "lib\\build\\mcs.exe");
+
+ //if (!File.Exists (CSharpCompiler))
+ // throw new FileNotFoundException ("C# compiler not found at " + CSharpCompiler);
+
+ VBCompiler = Path.Combine (GacPath, "4.5\\vbnc.exe");
+ AssemblyLinker = Path.Combine (GacPath, "4.5\\al.exe");
+
+ if (!File.Exists (AssemblyLinker)) {
+ AssemblyLinker = Path.Combine (Path.GetDirectoryName (GacPath), "lib\\net_4_x\\al.exe");
+ // if (!File.Exists (AssemblyLinker))
+ // throw new FileNotFoundException ("Windows al path not found: " + AssemblyLinker);
+ }
+ } else {
+ Mono = Path.Combine (GacPath, "bin", "mono");
+ if (!File.Exists (Mono))
+ Mono = "mono";
+
+ var mscorlibPath = new Uri (typeof (object).Assembly.CodeBase).LocalPath;
+ CSharpCompiler = Path.GetFullPath (Path.Combine (mscorlibPath, "..", "..", "..", "..", "bin", "mcs"));
+ if (!File.Exists (CSharpCompiler))
+ CSharpCompiler = "mcs";
+
+ VBCompiler = Path.GetFullPath (Path.Combine (mscorlibPath, "..", "..", "..", "..", "bin", "vbnc"));
+ if (!File.Exists (VBCompiler))
+ VBCompiler = "vbnc";
+
+ AssemblyLinker = Path.GetFullPath (Path.Combine (mscorlibPath, "..", "..", "..", "..", "bin", "al"));
+ if (!File.Exists (AssemblyLinker))
+ AssemblyLinker = "al";
+ }
+ }
+
+ // Due to an issue with shadow copying and app domains in mono, we cannot currently use
+ // Process.GetCurrentProcess ().MainModule.FileName (which would give the same result)
+ // when running in an AppDomain (eg System.Web hosts).
+ //
+ // Using native Windows API to get current process filename. This will only
+ // be called when running on Windows.
+ [DllImport ("kernel32.dll")]
+ static extern uint GetModuleFileName ([In] IntPtr hModule, [Out] StringBuilder lpFilename, [In] int nSize);
+
+ }
+}
+
+#endif
}
[Test] // JoinMulticastGroup (IPAddress)
- [Category ("NotWorking")]
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")]
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")]
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")]
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 ();
}
}
Assert.IsFalse (Uri.IsWellFormedUriString (null, UriKind.Absolute), "null");
Assert.IsFalse (Uri.IsWellFormedUriString ("data", UriKind.Absolute), "data");
Assert.IsTrue (Uri.IsWellFormedUriString ("http://www.go-mono.com/Main_Page#1", UriKind.Absolute), "http/hex");
+ Assert.IsTrue (Uri.IsWellFormedUriString ("test", UriKind.RelativeOrAbsolute), "rel1");
+ Assert.IsTrue (Uri.IsWellFormedUriString ("/test", UriKind.RelativeOrAbsolute), "rel2");
}
[Test]
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
../referencesource/System/net/System/Net/Sockets/IPProtectionLevel.cs
../referencesource/System/net/System/Net/Sockets/NetworkStream.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
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/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 ()
{
}
resources/collation.cjkKO.bin \
resources/collation.cjkKOlv2.bin
-REFERENCE_SOURCES_FLAGS = -d:FEATURE_PAL,GENERICS_WORK,FEATURE_LIST_PREDICATES,FEATURE_SERIALIZATION,FEATURE_ASCII,FEATURE_LATIN1,FEATURE_UTF7,FEATURE_UTF32,MONO_HYBRID_ENCODING_SUPPORT,FEATURE_ASYNC_IO,NEW_EXPERIMENTAL_ASYNC_IO,FEATURE_UTF32,FEATURE_EXCEPTIONDISPATCHINFO,FEATURE_CORRUPTING_EXCEPTIONS,FEATURE_EXCEPTION_NOTIFICATIONS,FEATURE_STRONGNAME_MIGRATION,FEATURE_USE_LCID,FEATURE_FUSION,FEATURE_CRYPTO,FEATURE_X509_SECURESTRINGS,FEATURE_SYNCHRONIZATIONCONTEXT,FEATURE_SYNCHRONIZATIONCONTEXT_WAIT
+REFERENCE_SOURCES_FLAGS = -d:FEATURE_PAL,GENERICS_WORK,FEATURE_LIST_PREDICATES,FEATURE_SERIALIZATION,FEATURE_ASCII,FEATURE_LATIN1,FEATURE_UTF7,FEATURE_UTF32,MONO_HYBRID_ENCODING_SUPPORT,FEATURE_ASYNC_IO,NEW_EXPERIMENTAL_ASYNC_IO,FEATURE_UTF32,FEATURE_EXCEPTIONDISPATCHINFO,FEATURE_CORRUPTING_EXCEPTIONS,FEATURE_EXCEPTION_NOTIFICATIONS,FEATURE_STRONGNAME_MIGRATION,FEATURE_USE_LCID,FEATURE_FUSION,FEATURE_CRYPTO,FEATURE_X509_SECURESTRINGS,FEATURE_SYNCHRONIZATIONCONTEXT,FEATURE_SYNCHRONIZATIONCONTEXT_WAIT,HAS_CORLIB_CONTRACTS
ifndef MOBILE_PROFILE
REFERENCE_SOURCES_FLAGS += -d:FEATURE_MACL
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 {
foreach (var cb in ctors)
cb.FixupTokens (token_map, member_map);
}
+ if (subtypes != null) {
+ foreach (var tb in subtypes)
+ tb.FixupTokens (token_map, member_map);
+ }
}
internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
[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 = 158;
+ private const int mono_corlib_version = 159;
#pragma warning restore 169
[ComVisible (true)]
Thread.GetDomain ().DefineDynamicAssembly (
assemblyName, AssemblyBuilderAccess.RunAndSave, Path.GetTempPath ());
- module = assembly.DefineDynamicModule ("module1");
+ module = assembly.DefineDynamicModule (ASSEMBLY_NAME, ASSEMBLY_NAME + ".dll");
}
static int typeIndexer = 0;
// TODO:
}
+ [Test]
+ public void NestedTypeSave () {
+ var tb = module.DefineType (genTypeName ());
+
+ var tbuilder = tb.DefineNestedType ("Test.CodeGen", TypeAttributes.Public | TypeAttributes.Class);
+ var entryp = tbuilder.DefineMethod("Main", MethodAttributes.Public | MethodAttributes.Static, typeof (void), null);
+ var ilg = entryp.GetILGenerator (128);
+ ilg.Emit (OpCodes.Ldtoken, tb);
+ ilg.Emit (OpCodes.Pop);
+ ilg.Emit (OpCodes.Ret);
+
+ tbuilder.CreateType ();
+ tb.CreateType ();
+
+ assembly.Save (ASSEMBLY_NAME + ".dll");
+ }
+
[Test]
public void DefinePInvokeMethod_Name_NullChar ()
{
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 ();
+ }
}
}
public void MakeArrayTypeTest ()
{
// This should not crash:
- typeof (void).MakeArrayType ();
+ Type t = typeof (void).MakeArrayType ();
}
+ [Test]
+ [ExpectedException (typeof (InvalidProgramException))]
+ public void MakeArrayTypedReferenceInstanceTest ()
+ {
+ object o = Array.CreateInstance (typeof (global::System.TypedReference), 1);
+ }
[ComVisible (true)]
public class ComFoo<T> {
--- /dev/null
+// TODO: Should be auto-generated from resources.resx
+
+static class SR
+{
+ public const string ArgumentException_ValueTupleIncorrectType = "The parameter should be a ValueTuple type of appropriate arity.";
+ public const string ArgumentException_ValueTupleLastArgumentNotAValueTuple = "The TRest type argument of ValueTuple`8 must be a ValueTuple.";
+}
\ No newline at end of file
ReferenceSources/SecurityContext.cs
ReferenceSources/PathInternal.cs
ReferenceSources/BinaryCompatibility.cs
+ReferenceSources/String.cs
+ReferenceSources/Type.cs
../referencesource/mscorlib/system/__filters.cs
../referencesource/mscorlib/system/__hresults.cs
../referencesource/mscorlib/microsoft/win32/safehandles/safewaithandle.cs
../referencesource/mscorlib/microsoft/win32/safehandles/win32safehandles.cs
-ReferenceSources/String.cs
-ReferenceSources/Type.cs
+corefx/SR.cs
+
+../../../external/corefx/src/Common/src/System/Numerics/Hashing/HashHelpers.cs
+
+../../../external/corefx/src/System.ValueTuple/src/System/ValueTuple/ValueTuple.cs
+../../../external/corefx/src/System.ValueTuple/src/System/ValueTuple/TupleExtensions.cs
+../../../external/corefx/src/System.ValueTuple/src/System/Runtime/CompilerServices/TupleElementNamesAttribute.cs
{
Uri result;
+#if MONO
+ if (uriKind == UriKind.RelativeOrAbsolute)
+ uriKind = DotNetRelativeOrAbsolute;
+#endif
+
if (!Uri.TryCreate(uriString, uriKind, out result))
return false;
// Cache the last position scanned in sb when searching for lines.
private int currentLinePos;
+#if MONO
+ //users to coordinate between Dispose and BeginReadLine
+ private object syncObject = new Object ();
+#endif
+
internal AsyncStreamReader(Process process, Stream stream, UserCallBack callback, Encoding encoding)
: this(process, stream, callback, encoding, DefaultBufferSize) {
}
protected virtual void Dispose(bool disposing)
{
+#if MONO
+ lock (syncObject) {
+#endif
if (disposing) {
if (stream != null)
stream.Close();
eofEvent.Close();
eofEvent = null;
}
+#if MONO
+ }
+#endif
}
public virtual Encoding CurrentEncoding {
int byteLen;
try {
+#if MONO
+ var stream = this.stream;
+ if (stream == null)
+ byteLen = 0;
+ else
+#endif
byteLen = stream.EndRead(ar);
}
catch (IOException ) {
FlushMessageQueue();
}
finally {
+#if MONO
+ lock (syncObject) {
+ if (eofEvent != null) {
+ try {
+ eofEvent.Set ();
+ } catch (System.ObjectDisposedException) {
+ // This races with Dispose, it's safe to ignore the error as it comes from a SafeHandle doing its job
+ }
+ }
+ }
+#else
eofEvent.Set();
+#endif
}
} else {
int charLen = decoder.GetChars(byteBuffer, 0, byteLen, charBuffer, 0);
sb.Append(charBuffer, 0, charLen);
GetLinesFromStringBuilder();
+#if MONO
+ lock (syncObject) {
+ if (stream != null) //not continue if the stream is gone / dispose
+#endif
stream.BeginRead(byteBuffer, 0 , byteBuffer.Length, new AsyncCallback(ReadBuffer), null);
+#if MONO
+ }
+#endif
}
}
StreamReadMode outputStreamReadMode;
StreamReadMode errorStreamReadMode;
+#if MONO
+ StreamReadMode inputStreamReadMode;
+#endif
// Support for asynchrously reading streams
[Browsable(true), MonitoringDescription(SR.ProcessAssociated)]
throw new InvalidOperationException(SR.GetString(SR.CantGetStandardIn));
}
+#if MONO
+ inputStreamReadMode = StreamReadMode.syncMode;
+#endif
return standardInput;
}
}
machineName = ".";
raisedOnExited = false;
+#if MONO
+ //Call close on streams if the user never saw them.
+ //A stream in the undefined mode was never fetched by the user.
+ //A stream in the async mode is wrapped on a AsyncStreamReader and we should dispose that instead.
+ // no way for users to get a hand on a AsyncStreamReader.
+ var tmpIn = standardInput;
+ standardInput = null;
+ if (inputStreamReadMode == StreamReadMode.undefined && tmpIn != null)
+ tmpIn.Close ();
+
+ var tmpOut = standardOutput;
+ standardOutput = null;
+ if (outputStreamReadMode == StreamReadMode.undefined && tmpOut != null)
+ tmpOut.Close ();
+
+ tmpOut = standardError;
+ standardError = null;
+ if (errorStreamReadMode == StreamReadMode.undefined && tmpOut != null)
+ tmpOut.Close ();
+
+ var tmpAsync = output;
+ output = null;
+ if (outputStreamReadMode == StreamReadMode.asyncMode && tmpAsync != null) {
+ tmpAsync.CancelOperation ();
+ tmpAsync.Close ();
+ }
+
+ tmpAsync = error;
+ error = null;
+ if (errorStreamReadMode == StreamReadMode.asyncMode && tmpAsync != null) {
+ tmpAsync.CancelOperation ();
+ tmpAsync.Close ();
+ }
+#else
//Don't call close on the Readers and writers
//since they might be referenced by somebody else while the
//process is still alive but this method called.
output = null;
error = null;
+#endif
Refresh();
}
{
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) {
}
if (version_mismatch != null) {
- if (version_mismatch is AssemblyBuilder)
+ if (is_fx_assembly || version_mismatch is AssemblyBuilder)
return version_mismatch;
var ref_an = new AssemblyName (refname);
var v1 = ref_an.Version;
var v2 = version_mismatch.GetName ().Version;
+ AssemblyReferenceMessageInfo messageInfo;
if (v1 > v2) {
- var messageInfo = new AssemblyReferenceMessageInfo (ref_an, report => {
+ messageInfo = new AssemblyReferenceMessageInfo (ref_an, report => {
report.SymbolRelatedToPreviousError (args.RequestingAssembly.Location);
report.Error (1705, string.Format ("Assembly `{0}' depends on `{1}' which has a higher version number than referenced assembly `{2}'",
args.RequestingAssembly.FullName, refname, version_mismatch.GetName ().FullName));
});
- AddReferenceVersionMismatch (args.RequestingAssembly.GetName (), messageInfo);
- return version_mismatch;
- }
-
- if (!is_fx_assembly) {
- var messageInfo = new AssemblyReferenceMessageInfo (ref_an, report => {
+ } else {
+ messageInfo = new AssemblyReferenceMessageInfo (ref_an, report => {
if (v1.Major != v2.Major || v1.Minor != v2.Minor) {
report.Warning (1701, 2,
"Assuming assembly reference `{0}' matches assembly `{1}'. You may need to supply runtime policy",
refname, version_mismatch.GetName ().FullName);
}
});
-
- AddReferenceVersionMismatch (args.RequestingAssembly.GetName (), messageInfo);
}
+ AddReferenceVersionMismatch (args.RequestingAssembly.GetName (), messageInfo);
+
return version_mismatch;
}
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)
protected virtual void InitializeAssembly (AssemblyDefinition assembly)
{
MarkAssembly (assembly);
- foreach (TypeDefinition type in assembly.MainModule.Types) {
- if (!Annotations.IsMarked (type))
- continue;
+ foreach (TypeDefinition type in assembly.MainModule.Types)
InitializeType (type);
- }
}
void InitializeType (TypeDefinition type)
{
+ if (type.HasNestedTypes) {
+ foreach (var nested in type.NestedTypes)
+ InitializeType (nested);
+ }
+
+ if (!Annotations.IsMarked (type))
+ return;
+
MarkType (type);
if (type.HasFields)
InitializeFields (type);
if (type.HasMethods)
InitializeMethods (type.Methods);
-
- if (type.HasNestedTypes) {
- foreach (var nested in type.NestedTypes) {
- if (Annotations.IsMarked (nested))
- InitializeType (nested);
- }
- }
}
void InitializeFields (TypeDefinition type)
MONO_PATH="$(topdir)/class/lib/$(PROFILE)$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" \
$(RUNTIME) $(RUNTIME_FLAGS)
+DIFF = diff -rup
+DIFF_QUIET = diff --brief
+ifeq ($(PLATFORM), win32)
+DIFF = diff -rupZ
+DIFF_QUIET = diff --brief -Z
+endif
+
dist-local: dist-default dist-tests
dist-tests:
$(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual Test/DocTest-addNonGeneric-v2.dll
$(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual Test/DocTest-addNonGeneric-v2.dll
$(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual Test/DocTest-addNonGeneric-v2.dll
- diff -rup Test/en.expected-addNonGeneric Test/en.actual
+ $(DIFF) Test/en.expected-addNonGeneric Test/en.actual
check-monodocer-dropns-classic: $(PROGRAM)
# tests the simplest --dropns case, a single class where the root namespace was dropped.
$(MAKE) Test/DocTest-DropNS-classic.dll
$(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual Test/DocTest-DropNS-classic.dll --api-style=classic
$(MAKE) update-monodocer-dropns-unified
- diff -rup Test/en.expected-dropns-classic-v1 Test/en.actual
+ $(DIFF) Test/en.expected-dropns-classic-v1 Test/en.actual
check-monodocer-dropns-multi: $(PROGRAM)
-rm -Rf Test/en.actual
$(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual $(MULTI-CLASSIC) --api-style=classic
$(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual $(MULTI-UNIFIED) --api-style=unified --dropns Test/DocTest-DropNS-unified.dll=MyFramework --dropns Test/DocTest-DropNS-unified-multitest.dll=MyFramework
- diff -rup Test/en.expected-dropns-multi Test/en.actual
+ $(DIFF) Test/en.expected-dropns-multi Test/en.actual
check-monodocer-dropns-multi-withexisting: $(PROGRAM)
$(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual $(MULTI-CLASSIC) --api-style=classic
$(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual $(MULTI-UNIFIED) --api-style=unified --dropns Test/DocTest-DropNS-unified.dll=MyFramework --dropns Test/DocTest-DropNS-unified-multitest.dll=MyFramework
- diff -rup Test/en.expected-dropns-multi-withexisting Test/en.actual
+ $(DIFF) Test/en.expected-dropns-multi-withexisting Test/en.actual
check-monodocer-dropns-delete: $(PROGRAM)
-rm -Rf Test/en.actual
$(MONO) $(PROGRAM) update --delete --exceptions=all -o Test/en.actual Test/DocTest-DropNS-classic-deletetest.dll --api-style=classic
$(MAKE) Test/DocTest-DropNS-unified-deletetest-V2.dll
$(MONO) $(PROGRAM) update --delete --exceptions=all -o Test/en.actual Test/DocTest-DropNS-unified-deletetest.dll --api-style=unified --dropns Test/DocTest-DropNS-unified-deletetest.dll=MyFramework
- diff -rup Test/en.expected-dropns-delete Test/en.actual
+ $(DIFF) Test/en.expected-dropns-delete Test/en.actual
check-monodocer-dropns-classic-withsecondary: $(PROGRAM)
# tests case where a secondary assembly is included with a --dropns parameter
$(MAKE) Test/DocTest-DropNS-classic-secondary.dll
$(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual Test/DocTest-DropNS-classic.dll Test/DocTest-DropNS-classic-secondary.dll --api-style=classic
$(MAKE) update-monodocer-dropns-unified-withsecondary
- diff -rup Test/en.expected-dropns-classic-withsecondary Test/en.actual
+ $(DIFF) Test/en.expected-dropns-classic-withsecondary Test/en.actual
update-monodocer-dropns-unified: $(PROGRAM)
$(MAKE) Test/DocTest-DropNS-unified.dll
-rm -Rf Test/en.actual
$(MAKE) Test/DocTest-InternalInterface.dll
$(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual Test/DocTest-InternalInterface.dll
- diff -rup Test/en.expected-internal-interface Test/en.actual
+ $(DIFF) Test/en.expected-internal-interface Test/en.actual
check-monodocer-enumerations: $(PROGRAM)
-rm -Rf Test/en.actual
$(MAKE) Test/DocTest-enumerations.dll
$(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual Test/DocTest-enumerations.dll
- diff -rup Test/en.expected-enumerations Test/en.actual
+ $(DIFF) Test/en.expected-enumerations Test/en.actual
check-monodocer-update: $(PROGRAM)
find Test/en.expected -name \*.xml -exec rm "{}" \;
-rm -Rf Test/en.actual
$(MAKE) Test/DocTest.dll-v1
$(MONO) $(PROGRAM) update --debug --exceptions=all -o Test/en.actual Test/DocTest.dll
- diff -rup Test/en.expected Test/en.actual
+ $(DIFF) Test/en.expected Test/en.actual
$(MONO) $(PROGRAM) update --debug --exceptions=all -o Test/en.actual Test/DocTest.dll
- diff -rup Test/en.expected Test/en.actual
+ $(DIFF) Test/en.expected Test/en.actual
check-monodocer-since-update: $(PROGRAM)
find Test/en.expected.since -name \*.xml -exec rm "{}" \;
$(MAKE) Test/DocTest.dll-v2
$(MONO) $(PROGRAM) --debug update --exceptions=all --since="Version 2.0" \
-o Test/en.actual Test/DocTest.dll
- diff -rup Test/en.expected.since Test/en.actual
+ $(DIFF) Test/en.expected.since Test/en.actual
check-monodocer-delete-update: $(PROGRAM)
find Test/en.expected.delete -type f -exec rm "{}" \;
$(MONO) $(PROGRAM) --debug update --exceptions=all -o Test/en.actual Test/DocTest.dll
$(MAKE) Test/DocTest.dll-v1
$(MONO) $(PROGRAM) --debug update -fno-assembly-versions --delete --exceptions=all -o Test/en.actual Test/DocTest.dll
- diff -rup Test/en.expected.delete Test/en.actual
+ $(DIFF) Test/en.expected.delete Test/en.actual
check-monodocer-importslashdoc-update: $(PROGRAM)
find Test/en.expected.importslashdoc -name \*.xml -exec rm "{}" \;
$(MAKE) Test/DocTest.dll-v1 TEST_CSCFLAGS=-doc:Test/DocTest.xml
$(MONO) $(PROGRAM) --debug update --exceptions=all -i Test/DocTest.xml \
-o Test/en.actual Test/DocTest.dll
- diff -rup Test/en.expected.importslashdoc Test/en.actual
+ $(DIFF) Test/en.expected.importslashdoc Test/en.actual
check-monodocer-importecmadoc-update: $(PROGRAM)
find Test/en.expected.importecmadoc -name \*.xml -exec rm "{}" \;
'--type=System.Action`1' --type=System.AsyncCallback \
--type=System.Environment --type=System.Array \
-o Test/en.actual Test/DocTest.dll
- diff -rup Test/en.expected.importecmadoc Test/en.actual
+ $(DIFF) Test/en.expected.importecmadoc Test/en.actual
check-mdoc-export-html-update: $(PROGRAM)
find Test/html.expected -name \*.html -exec rm "{}" \;
rm -Rf Test/html.actual
$(MONO) $(PROGRAM) export-html -o Test/html.actual \
Test/en.expected.importslashdoc
- diff -rup Test/html.expected Test/html.actual
+ $(DIFF) Test/html.expected Test/html.actual
check-mdoc-export-html-with-version: $(PROGRAM)
rm -Rf Test/html.actual.v0 Test/html.actual.since-with-v0 .v0.txt .v2.txt
Test/en.expected.since -with-version 0.0.0.0
(cd Test/html.actual.v0 && find . -type f) | sort > .v0.txt
(cd Test/html.actual.since-with-v0 && find . -type f) | sort > .v2.txt
- diff -rup .v0.txt .v2.txt # assert no types added
+ $(DIFF) .v0.txt .v2.txt # assert no types added
check-md-html-dir: $(PROGRAM)
rm -Rf Test/html.actual
$(MONO) $(PROGRAM) export-html -dest:Test/html.actual $(DIR)
- diff -rup Test/html.expected Test/html.actual
+ $(DIFF) Test/html.expected Test/html.actual
check-mdoc-export-msxdoc-update:
$(MONO) $(PROGRAM) export-msxdoc -o - Test/en.expected.importslashdoc \
check-mdoc-export-msxdoc:
$(MONO) $(PROGRAM) export-msxdoc -o - Test/en.expected.importslashdoc \
- | diff --brief - Test/msxdoc-expected.importslashdoc.xml
+ | $(DIFF_QUIET) - Test/msxdoc-expected.importslashdoc.xml
my_abs_top_srcdir = $(shell cd . && pwd)
check-mdoc-validate: $(PROGRAM)
$(MONO) $(PROGRAM) validate -f ecma Test/en.expected 2>&1 | \
sed 's#file://$(my_abs_top_srcdir)/##g' | \
- diff - Test/validate.check.monodocer
+ $(DIFF_QUIET) - Test/validate.check.monodocer
$(MONO) $(PROGRAM) validate -f ecma Test/en.expected.importslashdoc 2>&1 | \
sed 's#file://$(my_abs_top_srcdir)/##g' | \
- diff --brief - Test/validate.check.monodocer.importslashdoc
+ $(DIFF_QUIET) - Test/validate.check.monodocer.importslashdoc
$(MONO) $(PROGRAM) validate -f ecma Test/en.expected.since 2>&1 | \
sed 's#file://$(my_abs_top_srcdir)/##g' | \
- diff --brief - Test/validate.check.monodocer.since
+ $(DIFF_QUIET) - Test/validate.check.monodocer.since
run-test-local: check-doc-tools
CHECK_DIFF = @\
$(MONO) $(TEST_EXE) > $(STACKTRACE_FILE); \
$(MONO) $(LIB_PATH)/$(PROGRAM) $(MSYM_DIR) $(STACKTRACE_FILE) > $(SYMBOLICATE_RAW_FILE); \
- sed "s/) .* in .*\/mcs\//) in mcs\//" $(SYMBOLICATE_RAW_FILE) | sed '/\[MVID\]/d' | sed '/\[AOTID\]/d' > $(SYMBOLICATE_RESULT_FILE); \
+ cat $(SYMBOLICATE_RAW_FILE) | tr '\\' '/' | sed "s/) .* in .*\/mcs\//) in mcs\//" | sed '/\[MVID\]/d' | sed '/\[AOTID\]/d' > $(SYMBOLICATE_RESULT_FILE); \
DIFF=$$(diff -up $(SYMBOLICATE_EXPECTED_FILE) $(SYMBOLICATE_RESULT_FILE)); \
if [ ! -z "$$DIFF" ]; then \
echo "Symbolicate tests failed."; \
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]);
BTLS_STATIC_LIST = build-static/mono-btls-static-lo.txt
BTLS_SHARED_LIST = build-shared/mono-btls-shared-lo.txt
-BTLS_DEPS = $(BTLS_LIBS) build-shared/Makefile build-static/Makefile
+EXTRA_DIST = btls-android-utils.c \
+ btls-bio.c \
+ btls-bio.h \
+ btls-error.c \
+ btls-error.h \
+ btls-key.c \
+ btls-key.h \
+ btls-pkcs12.c \
+ btls-pkcs12.h \
+ btls-ssl.c \
+ btls-ssl-ctx.c \
+ btls-ssl-ctx.h \
+ btls-ssl.h \
+ btls-util.c \
+ btls-util.h \
+ btls-x509.c \
+ btls-x509-chain.c \
+ btls-x509-chain.h \
+ btls-x509-crl.c \
+ btls-x509-crl.h \
+ btls-x509.h \
+ btls-x509-lookup.c \
+ btls-x509-lookup.h \
+ btls-x509-lookup-mono.c \
+ btls-x509-lookup-mono.h \
+ btls-x509-name.c \
+ btls-x509-name.h \
+ btls-x509-revoked.c \
+ btls-x509-revoked.h \
+ btls-x509-store.c \
+ btls-x509-store-ctx.c \
+ btls-x509-store-ctx.h \
+ btls-x509-store.h \
+ btls-x509-verify-param.c \
+ btls-x509-verify-param.h \
+ CMakeLists.txt \
+ create-object-library.sh
CMAKE_VERBOSE=$(if $(V),VERBOSE=1,)
}
int
-mono_btls_x509_name_get_entry_value (MonoBtlsX509Name *name, int index, unsigned char **str)
+mono_btls_x509_name_get_entry_value (MonoBtlsX509Name *name, int index, int *tag, unsigned char **str)
{
X509_NAME_ENTRY *entry;
ASN1_STRING *data;
*str = NULL;
+ *tag = 0;
if (index >= X509_NAME_entry_count (name->name))
return 0;
if (!data)
return 0;
+ *tag = data->type;
return ASN1_STRING_to_UTF8 (str, data);
}
mono_btls_x509_name_get_entry_oid_data (MonoBtlsX509Name *name, int index, const void **data);
int
-mono_btls_x509_name_get_entry_value (MonoBtlsX509Name *name, int index, unsigned char **str);
+mono_btls_x509_name_get_entry_value (MonoBtlsX509Name *name, int index, int *tag, unsigned char **str);
#endif /* __btls__btls_x509_name__ */
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);
int pid;
struct MonoProcess *p;
- MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "SIG CHILD handler for pid: %i\n", info->si_pid);
-
do {
do {
pid = waitpid (-1, &status, WNOHANG);
if (pid <= 0)
break;
- MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "child ended: %i", pid);
-
/*
* This can run concurrently with the code in the rest of this module.
*/
p->freeable = TRUE;
}
} while (1);
-
- MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "SIG CHILD handler: done looping.");
}
#endif
console-win32.c \
w32mutex-win32.c \
w32semaphore-win32.c \
- w32event-win32.c
+ w32event-win32.c \
+ socket-io-windows.c
platform_sources = $(win32_sources)
* Changes which are already detected at runtime, like the addition
* of icalls, do not require an increment.
*/
-#define MONO_CORLIB_VERSION 158
+#define MONO_CORLIB_VERSION 159
typedef struct
{
* 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;
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)
{
guint has_finalize_inited : 1; /* has_finalize is initialized */
guint fields_inited : 1; /* fields is initialized */
guint setup_fields_called : 1; /* to prevent infinite loops in setup_fields */
-
- guint8 exception_type; /* MONO_EXCEPTION_* */
-
- /* Additional information about the exception */
- /* Stored as property MONO_CLASS_PROP_EXCEPTION_DATA */
- //void *exception_data;
+ guint has_failure : 1; /* See MONO_CLASS_PROP_EXCEPTION_DATA for a MonoErrorBoxed with the details */
MonoClass *parent;
MonoClass *nested_in;
mono_lookup_jit_icall_symbol (const char *name);
gboolean
-mono_class_set_failure (MonoClass *klass, guint32 ex_type, void *ex_data);
-
-gpointer
-mono_class_get_exception_data (MonoClass *klass);
+mono_class_set_type_load_failure (MonoClass *klass, const char * fmt, ...) MONO_ATTR_FORMAT_PRINTF(2,3);
MonoException*
mono_class_get_exception_for_failure (MonoClass *klass);
mono_class_try_load_from_name (MonoImage *image, const char* name_space, const char *name);
void
-mono_error_set_for_class_failure (MonoError *orerror, MonoClass *klass);
+mono_error_set_for_class_failure (MonoError *orerror, const MonoClass *klass);
-static inline guint8
-mono_class_get_failure (MonoClass *klass)
-{
- g_assert (klass != NULL);
- return klass->exception_type;
-}
-
-static inline gboolean
-mono_class_has_failure (MonoClass *klass)
-{
- g_assert (klass != NULL);
- return mono_class_get_failure (klass) != MONO_EXCEPTION_NONE;
-}
+gboolean
+mono_class_has_failure (const MonoClass *klass);
#endif /* __MONO_METADATA_CLASS_INTERNALS_H__ */
static void mono_class_setup_vtable_full (MonoClass *klass, GList *in_setup);
static void mono_generic_class_setup_parent (MonoClass *klass, MonoClass *gklass);
+static gboolean mono_class_set_failure (MonoClass *klass, MonoErrorBoxed *boxed_error);
+static gpointer mono_class_get_exception_data (const MonoClass *klass);
+
+
/*
We use gclass recording to allow recursive system f types to be referenced by a parent.
}
/*
- * Checks for MonoClass::exception_type without resolving all MonoType's into MonoClass'es
+ * Checks for MonoClass::has_failure without resolving all MonoType's into MonoClass'es
*/
static gboolean
mono_type_has_exceptions (MonoType *type)
}
void
-mono_error_set_for_class_failure (MonoError *oerror, MonoClass *klass)
+mono_error_set_for_class_failure (MonoError *oerror, const MonoClass *klass)
{
- gpointer exception_data = mono_class_get_exception_data (klass);
-
- switch (mono_class_get_failure(klass)) {
- case MONO_EXCEPTION_TYPE_LOAD: {
- mono_error_set_type_load_class (oerror, klass, "Error Loading class");
- return;
- }
- case MONO_EXCEPTION_INVALID_PROGRAM: {
- mono_error_set_invalid_program (oerror, "%s", (const char *)exception_data);
- return;
- }
- case MONO_EXCEPTION_MISSING_METHOD:
- case MONO_EXCEPTION_MISSING_FIELD:
- case MONO_EXCEPTION_FILE_NOT_FOUND:
- case MONO_EXCEPTION_BAD_IMAGE:
- default:
- g_assert_not_reached ();
- }
+ g_assert (mono_class_has_failure (klass));
+ MonoErrorBoxed *box = (MonoErrorBoxed*)mono_class_get_exception_data (klass);
+ mono_error_set_from_boxed (oerror, box);
}
}
}
+/**
+ * mono_class_set_failure_causedby_class:
+ * @klass: the class that is failing
+ * @caused_by: the class that caused the failure
+ * @msg: Why @klass is failing.
+ *
+ * If @caused_by has a failure, sets a TypeLoadException failure on
+ * @klass with message "@msg, due to: {@caused_by message}".
+ *
+ * Returns: TRUE if a failiure was set, or FALSE if @caused_by doesn't have a failure.
+ */
+static gboolean
+mono_class_set_type_load_failure_causedby_class (MonoClass *klass, const MonoClass *caused_by, const gchar* msg)
+{
+ if (mono_class_has_failure (caused_by)) {
+ MonoError cause_error;
+ mono_error_init (&cause_error);
+ mono_error_set_for_class_failure (&cause_error, caused_by);
+ mono_class_set_type_load_failure (klass, "%s, due to: %s", msg, mono_error_get_message (&cause_error));
+ mono_error_cleanup (&cause_error);
+ return TRUE;
+ } else {
+ return FALSE;
+ }
+}
+
+
/**
* mono_class_setup_fields:
* @class: The class to initialize
if (gtd) {
mono_class_setup_fields (gtd);
- if (mono_class_has_failure (gtd)) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+ if (mono_class_set_type_load_failure_causedby_class (klass, gtd, "Generic type definition failed"))
return;
- }
}
instance_size = 0;
mono_class_init (klass->parent);
if (!klass->parent->size_inited) {
mono_class_setup_fields (klass->parent);
- if (mono_class_has_failure (klass->parent)) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+ if (mono_class_set_type_load_failure_causedby_class (klass, klass->parent, "Could not set up parent class"))
return;
- }
}
instance_size += klass->parent->instance_size;
klass->min_align = klass->parent->min_align;
if (explicit_size) {
if ((packing_size & 0xffffff00) != 0) {
- char *err_msg = g_strdup_printf ("Could not load struct '%s' with packing size %d >= 256", klass->name, packing_size);
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, err_msg);
+ mono_class_set_type_load_failure (klass, "Could not load struct '%s' with packing size %d >= 256", klass->name, packing_size);
return;
}
klass->packing_size = packing_size;
field->offset = offset;
if (field->offset == (guint32)-1 && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Missing field layout info for %s", field->name));
+ mono_class_set_type_load_failure (klass, "Missing field layout info for %s", field->name);
break;
}
if (field->offset < -1) { /*-1 is used to encode special static fields */
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Invalid negative field offset %d for %s", field->offset, field->name));
+ mono_class_set_type_load_failure (klass, "Field '%s' has a negative offset %d", field->name, field->offset);
break;
}
if (klass->generic_container) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Generic class cannot have explicit layout."));
+ mono_class_set_type_load_failure (klass, "Generic class cannot have explicit layout.");
break;
}
}
if (field_class) {
mono_class_setup_fields (field_class);
if (mono_class_has_failure (field_class)) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+ MonoError field_error;
+ mono_error_init (&field_error);
+ mono_error_set_for_class_failure (&field_error, field_class);
+ mono_class_set_type_load_failure (klass, "Could not set up field '%s' due to: %s", field->name, mono_error_get_message (&field_error));
+ mono_error_cleanup (&field_error);
break;
}
}
char *class_name = mono_type_get_full_name (klass);
char *type_name = mono_type_full_name (field->type);
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+ mono_class_set_type_load_failure (klass, "");
g_warning ("Invalid type %s for instance field %s:%s", type_name, class_name, field->name);
g_free (class_name);
g_free (type_name);
klass->blittable = blittable;
if (klass->enumtype && !mono_class_enum_basetype (klass)) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+ mono_class_set_type_load_failure (klass, "The enumeration's base type is invalid.");
return;
}
if (explicit_size && real_size) {
/*valuetypes can't be neither bigger than 1Mb or empty. */
if (klass->valuetype && (klass->instance_size <= 0 || klass->instance_size > (0x100000 + sizeof (MonoObject))))
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+ mono_class_set_type_load_failure (klass, "Value type instance size (%d) cannot be zero, negative, or bigger than 1Mb", klass->instance_size);
mono_memory_barrier ();
klass->fields_inited = 1;
if (klass->parent) {
mono_class_setup_fields (klass->parent);
- if (mono_class_has_failure (klass->parent)) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+ if (mono_class_set_type_load_failure_causedby_class (klass, klass->parent, "Cannot initialize parent class"))
return;
- }
real_size = klass->parent->instance_size;
} else {
real_size = sizeof (MonoObject);
ftype = mono_type_get_basic_type_from_generic (ftype);
if (type_has_references (klass, ftype)) {
if (field->offset % sizeof (gpointer)) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+ mono_class_set_type_load_failure (klass, "Reference typed field '%s' has explicit offset that is not pointer-size aligned.", field->name);
}
}
// FIXME: Too much code does this
#if 0
if (!MONO_TYPE_IS_REFERENCE (field->type) && ref_bitmap [field->offset / sizeof (gpointer)]) {
- char *err_msg = mono_image_strdup_printf (klass->image, "Could not load type '%s' because it contains an object field at offset %d that is incorrectly aligned or overlapped by a non-object field.", klass->name, field->offset);
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, err_msg);
+ mono_class_set_type_load_failure (klass, "Could not load type '%s' because it contains an object field at offset %d that is incorrectly aligned or overlapped by a non-object field.", klass->name, field->offset);
}
#endif
}
continue;
if (mono_type_has_exceptions (field->type)) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+ mono_class_set_type_load_failure (klass, "Field '%s' has an invalid type.", field->name);
break;
}
* Methods belonging to an interface are assigned a sequential slot starting
* from 0.
*
- * On failure this function sets klass->exception_type
+ * On failure this function sets klass->has_failure and stores a MonoErrorBoxed with details
*/
void
mono_class_setup_methods (MonoClass *klass)
mono_class_init (gklass);
if (!mono_class_has_failure (gklass))
mono_class_setup_methods (gklass);
- if (mono_class_has_failure (gklass)) {
- /* FIXME make exception_data less opaque so it's possible to dup it here */
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Generic type definition failed to load"));
+ if (mono_class_set_type_load_failure_causedby_class (klass, gklass, "Generic type definition failed to load"))
return;
- }
/* The + 1 makes this always non-NULL to pass the check in mono_class_setup_methods () */
count = gklass->method.count;
gklass->methods [i], klass, mono_class_get_context (klass), &error);
if (!mono_error_ok (&error)) {
char *method = mono_method_full_name (gklass->methods [i], TRUE);
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Could not inflate method %s due to %s", method, mono_error_get_message (&error)));
+ mono_class_set_type_load_failure (klass, "Could not inflate method %s due to %s", method, mono_error_get_message (&error));
g_free (method);
mono_error_cleanup (&error);
int idx = mono_metadata_translate_token_index (klass->image, MONO_TABLE_METHOD, klass->method.first + i + 1);
methods [i] = mono_get_method_checked (klass->image, MONO_TOKEN_METHOD_DEF | idx, klass, NULL, &error);
if (!methods [i]) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Could not load method %d due to %s", i, mono_error_get_message (&error)));
+ mono_class_set_type_load_failure (klass, "Could not load method %d due to %s", i, mono_error_get_message (&error));
mono_error_cleanup (&error);
}
}
mono_class_init (gklass);
mono_class_setup_properties (gklass);
- if (mono_class_has_failure (gklass)) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Generic type definition failed to load"));
+ if (mono_class_set_type_load_failure_causedby_class (klass, gklass, "Generic type definition failed to load"))
return;
- }
properties = mono_class_new0 (klass, MonoProperty, gklass->ext->property.count + 1);
MonoGenericContext *context = NULL;
mono_class_setup_events (gklass);
- if (mono_class_has_failure (gklass)) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Generic type definition failed to load"));
+ if (mono_class_set_type_load_failure_causedby_class (klass, gklass, "Generic type definition failed to load"))
return;
- }
first = gklass->ext->event.first;
count = gklass->ext->event.count;
if (count) {
mono_class_setup_methods (klass);
if (mono_class_has_failure (klass)) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Generic type definition failed to load"));
return;
}
}
/*
* LOCKING: this is supposed to be called with the loader lock held.
- * Return -1 on failure and set exception_type
+ * Return -1 on failure and set klass->has_failure and store a MonoErrorBoxed with the details.
*/
static int
setup_interface_offsets (MonoClass *klass, int cur_slot, gboolean overwrite)
ifaces = mono_class_get_implemented_interfaces (k, &error);
if (!mono_error_ok (&error)) {
char *name = mono_type_get_full_name (k);
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Error getting the interfaces of %s due to %s", name, mono_error_get_message (&error)));
+ mono_class_set_type_load_failure (klass, "Error getting the interfaces of %s due to %s", name, mono_error_get_message (&error));
g_free (name);
mono_error_cleanup (&error);
cur_slot = -1;
count = count_virtual_methods (ic);
if (count == -1) {
char *name = mono_type_get_full_name (ic);
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Error calculating interface offset of %s", name));
+ mono_class_set_type_load_failure (klass, "Error calculating interface offset of %s", name);
g_free (name);
cur_slot = -1;
goto end;
}
mono_class_setup_vtable_full (mono_class_get_generic_type_definition (klass), in_setup);
- if (mono_class_has_failure (klass->generic_class->container_class)) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Failed to load generic definition vtable"));
+ if (mono_class_set_type_load_failure_causedby_class (klass, klass->generic_class->container_class, "Failed to load generic definition vtable"))
return FALSE;
- }
ginst = klass->generic_class->context.class_inst;
for (i = 0; i < ginst->type_argc; ++i) {
if (mono_class_has_gtd_parent (klass, arg) || mono_class_has_gtd_parent (arg, klass))
continue;
if (!mono_class_check_vtable_constraints (arg, in_setup)) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Failed to load generic parameter %d", i));
+ mono_class_set_type_load_failure (klass, "Failed to load generic parameter %d", i);
return FALSE;
}
}
* - vtable
* - vtable_size
* Plus all the fields initialized by setup_interface_offsets ().
- * If there is an error during vtable construction, klass->exception_type is set.
+ * If there is an error during vtable construction, klass->has_failure
+ * is set and details are stored in a MonoErrorBoxed.
*
* LOCKING: Acquires the loader lock.
*/
if (!is_ok (&error)) {
mono_loader_unlock ();
g_list_remove (in_setup, klass);
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf(klass->image, "Could not load list of method overrides due to %s", mono_error_get_message (&error)));
+ mono_class_set_type_load_failure (klass, "Could not load list of method overrides due to %s", mono_error_get_message (&error));
mono_error_cleanup (&error);
return;
}
if (ok)
mono_class_setup_vtable_general (klass, overrides, onum, in_setup);
else
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Could not load list of method overrides"));
+ mono_class_set_type_load_failure (klass, "Could not load list of method overrides");
g_free (overrides);
cmsig = mono_method_signature (cm);
imsig = mono_method_signature (im);
if (!cmsig || !imsig) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Could not resolve the signature of a virtual method"));
+ mono_class_set_type_load_failure (klass, "Could not resolve the signature of a virtual method");
return FALSE;
}
if (is_wcf_hack_disabled () && !mono_method_can_access_method_full (cm, im, NULL)) {
char *body_name = mono_method_full_name (cm, TRUE);
char *decl_name = mono_method_full_name (im, TRUE);
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Method %s overrides method '%s' which is not accessible", body_name, decl_name));
+ mono_class_set_type_load_failure (klass, "Method %s overrides method '%s' which is not accessible", body_name, decl_name);
g_free (body_name);
g_free (decl_name);
return FALSE;
cmsig = mono_method_signature (cm);
imsig = mono_method_signature (im);
if (!cmsig || !imsig) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Could not resolve the signature of a virtual method"));
+ mono_class_set_type_load_failure (klass, "Could not resolve the signature of a virtual method");
return FALSE;
}
if (is_wcf_hack_disabled () && !mono_method_can_access_method_full (cm, im, NULL)) {
char *body_name = mono_method_full_name (cm, TRUE);
char *decl_name = mono_method_full_name (im, TRUE);
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Method %s overrides method '%s' which is not accessible", body_name, decl_name));
+ mono_class_set_type_load_failure (klass, "Method %s overrides method '%s' which is not accessible", body_name, decl_name);
g_free (body_name);
g_free (decl_name);
return FALSE;
MonoMethod *body = overrides [i * 2 + 1];
if (mono_class_get_generic_type_definition (body->klass) != mono_class_get_generic_type_definition (klass)) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Method belongs to a different class than the declared one"));
+ mono_class_set_type_load_failure (klass, "Method belongs to a different class than the declared one");
return FALSE;
}
if (!(body->flags & METHOD_ATTRIBUTE_VIRTUAL) || (body->flags & METHOD_ATTRIBUTE_STATIC)) {
if (body->flags & METHOD_ATTRIBUTE_STATIC)
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Method must not be static to override a base type"));
+ mono_class_set_type_load_failure (klass, "Method must not be static to override a base type");
else
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Method must be virtual to override a base type"));
+ mono_class_set_type_load_failure (klass, "Method must be virtual to override a base type");
return FALSE;
}
if (!(decl->flags & METHOD_ATTRIBUTE_VIRTUAL) || (decl->flags & METHOD_ATTRIBUTE_STATIC)) {
if (body->flags & METHOD_ATTRIBUTE_STATIC)
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Cannot override a static method in a base type"));
+ mono_class_set_type_load_failure (klass, "Cannot override a static method in a base type");
else
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Cannot override a non virtual method in a base type"));
+ mono_class_set_type_load_failure (klass, "Cannot override a non virtual method in a base type");
return FALSE;
}
if (!mono_class_is_assignable_from_slow (decl->klass, klass)) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Method overrides a class or interface that is not extended or implemented by this type"));
+ mono_class_set_type_load_failure (klass, "Method overrides a class or interface that is not extended or implemented by this type");
return FALSE;
}
if (is_wcf_hack_disabled () && !mono_method_can_access_method_full (body, decl, NULL)) {
char *body_name = mono_method_full_name (body, TRUE);
char *decl_name = mono_method_full_name (decl, TRUE);
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Method %s overrides method '%s' which is not accessible", body_name, decl_name));
+ mono_class_set_type_load_failure (klass, "Method %s overrides method '%s' which is not accessible", body_name, decl_name);
g_free (body_name);
g_free (decl_name);
return FALSE;
ifaces = mono_class_get_implemented_interfaces (klass, &error);
if (!mono_error_ok (&error)) {
char *name = mono_type_get_full_name (klass);
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Could not resolve %s interfaces due to %s", name, mono_error_get_message (&error)));
+ mono_class_set_type_load_failure (klass, "Could not resolve %s interfaces due to %s", name, mono_error_get_message (&error));
g_free (name);
mono_error_cleanup (&error);
return;
mono_class_init (klass->parent);
mono_class_setup_vtable_full (klass->parent, in_setup);
- if (mono_class_has_failure (klass->parent)) {
- char *name = mono_type_get_full_name (klass->parent);
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Parent %s failed to load", name));
- g_free (name);
+ if (mono_class_set_type_load_failure_causedby_class (klass, klass->parent, "Parent class failed to load"))
return;
- }
max_vtsize += klass->parent->vtable_size;
cur_slot = klass->parent->vtable_size;
MonoMethod **tmp;
mono_class_setup_vtable_full (gklass, in_setup);
- if (mono_class_has_failure (gklass)) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+ if (mono_class_set_type_load_failure_causedby_class (klass, gklass, "Could not load generic definition"))
return;
- }
tmp = (MonoMethod **)mono_class_alloc0 (klass, sizeof (gpointer) * gklass->vtable_size);
klass->vtable_size = gklass->vtable_size;
if (gklass->vtable [i]) {
MonoMethod *inflated = mono_class_inflate_generic_method_full_checked (gklass->vtable [i], klass, mono_class_get_context (klass), &error);
if (!mono_error_ok (&error)) {
- char *err_msg = mono_image_strdup_printf (klass->image, "Could not inflate method due to %s", mono_error_get_message (&error));
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, err_msg);
+ mono_class_set_type_load_failure (klass, "Could not inflate method due to %s", mono_error_get_message (&error));
mono_error_cleanup (&error);
return;
}
int dslot;
dslot = mono_method_get_vtable_slot (decl);
if (dslot == -1) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+ mono_class_set_type_load_failure (klass, "");
return;
}
m1sig = mono_method_signature (m1);
if (!cmsig || !m1sig) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+ /* FIXME proper error message */
+ mono_class_set_type_load_failure (klass, "");
return;
}
if (is_wcf_hack_disabled () && !mono_method_can_access_method_full (cm, m1, NULL)) {
char *body_name = mono_method_full_name (cm, TRUE);
char *decl_name = mono_method_full_name (m1, TRUE);
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Method %s overrides method '%s' which is not accessible", body_name, decl_name));
+ mono_class_set_type_load_failure (klass, "Method %s overrides method '%s' which is not accessible", body_name, decl_name);
g_free (body_name);
g_free (decl_name);
goto fail;
if (vtable [i] == NULL || (vtable [i]->flags & (METHOD_ATTRIBUTE_ABSTRACT | METHOD_ATTRIBUTE_STATIC))) {
char *type_name = mono_type_get_full_name (klass);
char *method_name = vtable [i] ? mono_method_full_name (vtable [i], TRUE) : g_strdup ("none");
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Type %s has invalid vtable method slot %d with method %s", type_name, i, method_name));
+ mono_class_set_type_load_failure (klass, "Type %s has invalid vtable method slot %d with method %s", type_name, i, method_name);
g_free (type_name);
g_free (method_name);
return;
fail:
{
char *name = mono_type_get_full_name (klass);
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "VTable setup of type %s failed", name));
+ mono_class_set_type_load_failure (klass, "VTable setup of type %s failed", name);
g_free (name);
if (override_map)
g_hash_table_destroy (override_map);
}
if (klass->init_pending) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Recursive type definition detected"));
+ mono_class_set_type_load_failure (klass, "Recursive type definition detected");
goto leave;
}
klass->init_pending = 1;
if (mono_verifier_is_enabled_for_class (klass) && !mono_verifier_verify_class (klass)) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, concat_two_strings_with_zero (klass->image, klass->name, klass->image->assembly_name));
+ mono_class_set_type_load_failure (klass, "%s", concat_two_strings_with_zero (klass->image, klass->name, klass->image->assembly_name));
goto leave;
}
MonoClass *element_class = klass->element_class;
if (!element_class->inited)
mono_class_init (element_class);
- if (mono_class_has_failure (element_class)) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+ if (mono_class_set_type_load_failure_causedby_class (klass, element_class, "Could not load array element class"))
goto leave;
- }
}
mono_stats.initialized_class_count++;
// FIXME: Why is this needed ?
if (!mono_class_has_failure (gklass))
mono_class_setup_methods (gklass);
- if (mono_class_has_failure (gklass)) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Generic Type Defintion failed to init"));
+ if (mono_class_set_type_load_failure_causedby_class (klass, gklass, "Generic Type Definition failed to init"))
goto leave;
- }
if (MONO_CLASS_IS_INTERFACE (klass))
klass->interface_id = mono_get_unique_iid (klass);
klass->has_cctor = gklass->has_cctor;
mono_class_setup_vtable (gklass);
- if (mono_class_has_failure (gklass)) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+ if (mono_class_set_type_load_failure_causedby_class (klass, gklass, "Generic type definition failed to init"))
goto leave;
- }
klass->vtable_size = gklass->vtable_size;
} else {
}
if (klass->parent) {
+ MonoError parent_error;
+ mono_error_init (&parent_error);
int first_iface_slot;
/* This will compute klass->parent->vtable_size for some classes */
mono_class_init (klass->parent);
- if (mono_class_has_failure (klass->parent)) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+ if (mono_class_set_type_load_failure_causedby_class (klass, klass->parent, "Parent class failed to initialize")) {
goto leave;
}
if (!klass->parent->vtable_size) {
/* FIXME: Get rid of this somehow */
mono_class_setup_vtable (klass->parent);
- if (mono_class_has_failure (klass->parent)) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+ if (mono_class_set_type_load_failure_causedby_class (klass, klass->parent, "Parent class vtable failed to initialize")) {
goto leave;
}
}
mono_security_core_clr_check_inheritance (klass);
if (klass->generic_class && !mono_verifier_class_is_valid_generic_instantiation (klass))
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Invalid generic instantiation"));
+ mono_class_set_type_load_failure (klass, "Invalid generic instantiation");
goto leave;
/* but it can not be made available for application (i.e. user code) since all COM calls
* are considered native calls. In this case we fail with a TypeLoadException (just like
* Silverlight 2 does */
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+ mono_class_set_type_load_failure (klass, "");
return;
}
}
if (!parent) {
/* set the parent to something useful and safe, but mark the type as broken */
parent = mono_defaults.object_class;
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+ mono_class_set_type_load_failure (klass, "");
}
klass->parent = parent;
static void
mono_class_set_failure_and_error (MonoClass *klass, MonoError *error, const char *msg)
{
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, msg));
+ mono_class_set_type_load_failure (klass, "%s", msg);
mono_error_set_type_load_class (error, klass, "%s", msg);
}
parent = mono_class_inflate_generic_class_checked (parent, context, error);
if (parent == NULL) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, mono_error_get_message (error)));
+ mono_class_set_type_load_failure (klass, "%s", mono_error_get_message (error));
goto parent_failure;
}
klass->nested_in = mono_class_create_from_typedef (image, nesting_tokeen, error);
if (!mono_error_ok (error)) {
/*FIXME implement a mono_class_set_failure_from_mono_error */
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, mono_error_get_message (error)));
+ mono_class_set_type_load_failure (klass, "%s", mono_error_get_message (error));
mono_loader_unlock ();
mono_profiler_class_loaded (klass, MONO_PROFILE_FAILED);
return NULL;
if (!mono_metadata_interfaces_from_typedef_full (
image, type_token, &interfaces, &icount, FALSE, context, error)){
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, mono_error_get_message (error)));
+ mono_class_set_type_load_failure (klass, "%s", mono_error_get_message (error));
mono_loader_unlock ();
mono_profiler_class_loaded (klass, MONO_PROFILE_FAILED);
return NULL;
if (!enum_basetype) {
/*set it to a default value as the whole runtime can't handle this to be null*/
klass->cast_class = klass->element_class = mono_defaults.int32_class;
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, mono_error_get_message (error)));
+ mono_class_set_type_load_failure (klass, "%s", mono_error_get_message (error));
mono_loader_unlock ();
mono_profiler_class_loaded (klass, MONO_PROFILE_FAILED);
return NULL;
* work.
*/
if (klass->generic_container && !mono_metadata_load_generic_param_constraints_checked (image, type_token, klass->generic_container, error)) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup_printf (klass->image, "Could not load generic parameter constrains due to %s", mono_error_get_message (error)));
+ mono_class_set_type_load_failure (klass, "Could not load generic parameter constrains due to %s", mono_error_get_message (error));
mono_loader_unlock ();
mono_profiler_class_loaded (klass, MONO_PROFILE_FAILED);
return NULL;
if (!mono_error_ok (&error)) {
/*Set parent to something safe as the runtime doesn't handle well this kind of failure.*/
klass->parent = mono_defaults.object_class;
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+ mono_class_set_type_load_failure (klass, "Parent is a generic type instantiation that failed due to: %s", mono_error_get_message (&error));
mono_error_cleanup (&error);
}
}
if (count - pos > 0) {
mono_class_setup_vtable (klass->parent);
if (mono_class_has_failure (klass->parent))
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Failed to setup parent interfaces"));
+ mono_class_set_type_load_failure (klass, "Failed to setup parent interfaces");
else
setup_interface_offsets (klass, klass->parent->vtable_size, TRUE);
}
result->image = el_class->image;
result->inited = TRUE;
result->flags = TYPE_ATTRIBUTE_CLASS | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
- /* Can pointers get boxed? */
- result->instance_size = sizeof (gpointer);
+ result->instance_size = sizeof (MonoObject) + sizeof (gpointer);
result->cast_class = result->element_class = el_class;
result->blittable = TRUE;
result->image = mono_defaults.corlib; /* need to fix... */
result->inited = TRUE;
result->flags = TYPE_ATTRIBUTE_CLASS; /* | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK); */
- /* Can pointers get boxed? */
- result->instance_size = sizeof (gpointer);
+ result->instance_size = sizeof (MonoObject) + sizeof (gpointer);
result->cast_class = result->element_class = result;
result->blittable = TRUE;
if (eclass->byval_arg.type == MONO_TYPE_TYPEDBYREF || eclass->byval_arg.type == MONO_TYPE_VOID) {
/*Arrays of those two types are invalid.*/
- mono_class_set_failure (klass, MONO_EXCEPTION_INVALID_PROGRAM, NULL);
+ MonoError prepared_error;
+ mono_error_init (&prepared_error);
+ mono_error_set_invalid_program (&prepared_error, "Arrays of void or System.TypedReference types are invalid.");
+ mono_class_set_failure (klass, mono_error_box (&prepared_error, klass->image));
+ mono_error_cleanup (&prepared_error);
} else if (eclass->enumtype && !mono_class_enum_basetype (eclass)) {
if (!eclass->ref_info_handle || eclass->wastypebuilder) {
g_warning ("Only incomplete TypeBuilder objects are allowed to be an enum without base_type");
mono_class_init (eclass);
if (!eclass->size_inited)
mono_class_setup_fields (eclass);
- if (mono_class_has_failure (eclass)) /*FIXME we fail the array type, but we have to let other fields be set.*/
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+ mono_class_set_type_load_failure_causedby_class (klass, eclass, "Could not load array element type");
+ /*FIXME we fail the array type, but we have to let other fields be set.*/
klass->has_references = MONO_TYPE_IS_REFERENCE (&eclass->byval_arg) || eclass->has_references? TRUE: FALSE;
*
* LOCKING: Acquires the loader lock.
*/
-gboolean
-mono_class_set_failure (MonoClass *klass, guint32 ex_type, void *ex_data)
+static gboolean
+mono_class_set_failure (MonoClass *klass, MonoErrorBoxed *boxed_error)
{
+ g_assert (boxed_error != NULL);
+
if (mono_class_has_failure (klass))
return FALSE;
mono_loader_lock ();
- klass->exception_type = ex_type;
- if (ex_data)
- mono_image_property_insert (klass->image, klass, MONO_CLASS_PROP_EXCEPTION_DATA, ex_data);
+ klass->has_failure = 1;
+ mono_image_property_insert (klass->image, klass, MONO_CLASS_PROP_EXCEPTION_DATA, boxed_error);
mono_loader_unlock ();
return TRUE;
}
+gboolean
+mono_class_has_failure (const MonoClass *klass)
+{
+ g_assert (klass != NULL);
+ return klass->has_failure != 0;
+}
+
+
+/**
+ * mono_class_set_type_load_failure:
+ * @klass: class in which the failure was detected
+ * @fmt: Printf-style error message string.
+ *
+ * Collect detected failure informaion in the class for later processing.
+ * The error is stored as a MonoErrorBoxed as with mono_error_set_type_load_class ()
+ * Note that only the first failure is kept.
+ *
+ * Returns FALSE if a failure was already set on the class, or TRUE otherwise.
+ *
+ * LOCKING: Acquires the loader lock.
+ */
+gboolean
+mono_class_set_type_load_failure (MonoClass *klass, const char * fmt, ...)
+{
+ MonoError prepare_error;
+ va_list args;
+
+ if (mono_class_has_failure (klass))
+ return FALSE;
+
+ mono_error_init (&prepare_error);
+
+ va_start (args, fmt);
+ mono_error_vset_type_load_class (&prepare_error, klass, fmt, args);
+ va_end (args);
+
+ MonoErrorBoxed *box = mono_error_box (&prepare_error, klass->image);
+ mono_error_cleanup (&prepare_error);
+ return mono_class_set_failure (klass, box);
+}
+
/*
* mono_class_get_exception_data:
*
*
* LOCKING: Acquires the loader lock.
*/
-gpointer
-mono_class_get_exception_data (MonoClass *klass)
+static gpointer
+mono_class_get_exception_data (const MonoClass *klass)
{
- return mono_image_property_lookup (klass->image, klass, MONO_CLASS_PROP_EXCEPTION_DATA);
+ return mono_image_property_lookup (klass->image, (MonoClass*)klass, MONO_CLASS_PROP_EXCEPTION_DATA);
}
/**
MonoException*
mono_class_get_exception_for_failure (MonoClass *klass)
{
- gpointer exception_data = mono_class_get_exception_data (klass);
-
- switch (mono_class_get_failure(klass)) {
- case MONO_EXCEPTION_TYPE_LOAD: {
- MonoString *name;
- MonoException *ex;
- char *str = mono_type_get_full_name (klass);
- char *astr = klass->image->assembly? mono_stringify_assembly_name (&klass->image->assembly->aname): NULL;
- name = mono_string_new (mono_domain_get (), str);
- g_free (str);
- ex = mono_get_exception_type_load (name, astr);
- g_free (astr);
- return ex;
- }
- case MONO_EXCEPTION_MISSING_METHOD: {
- char *class_name = (char *)exception_data;
- char *assembly_name = class_name + strlen (class_name) + 1;
-
- return mono_get_exception_missing_method (class_name, assembly_name);
- }
- case MONO_EXCEPTION_MISSING_FIELD: {
- char *class_name = (char *)exception_data;
- char *member_name = class_name + strlen (class_name) + 1;
-
- return mono_get_exception_missing_field (class_name, member_name);
- }
- case MONO_EXCEPTION_FILE_NOT_FOUND: {
- char *msg_format = (char *)exception_data;
- char *assembly_name = msg_format + strlen (msg_format) + 1;
- char *msg = g_strdup_printf (msg_format, assembly_name);
- MonoException *ex;
-
- ex = mono_get_exception_file_not_found2 (msg, mono_string_new (mono_domain_get (), assembly_name));
-
- g_free (msg);
-
- return ex;
- }
- case MONO_EXCEPTION_BAD_IMAGE: {
- return mono_get_exception_bad_image_format ((const char *)exception_data);
- }
- case MONO_EXCEPTION_INVALID_PROGRAM: {
- return mono_exception_from_name_msg (mono_defaults.corlib, "System", "InvalidProgramException", "");
- }
- default: {
- /* TODO - handle other class related failures */
- return mono_get_exception_execution_engine ("Unknown class failure");
- }
- }
+ if (!mono_class_has_failure (klass))
+ return NULL;
+ MonoError unboxed_error;
+ mono_error_init (&unboxed_error);
+ mono_error_set_for_class_failure (&unboxed_error, klass);
+ return mono_error_convert_to_exception (&unboxed_error);
}
static gboolean
mono_class_setup_interfaces (gklass, error);
if (!mono_error_ok (error)) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Could not setup the interfaces"));
+ mono_class_set_type_load_failure (klass, "Could not setup the interfaces");
return;
}
for (i = 0; i < interface_count; i++) {
interfaces [i] = mono_class_inflate_generic_class_checked (gklass->interfaces [i], mono_generic_class_get_context (klass->generic_class), error);
if (!mono_error_ok (error)) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, "Could not setup the interfaces"));
+ mono_class_set_type_load_failure (klass, "Could not setup the interfaces");
return;
}
}
MonoClassField *gfield = >d->fields [field_idx];
MonoType *gtype = mono_field_get_type_checked (gfield, error);
if (!mono_error_ok (error)) {
- char *err_msg = mono_image_strdup_printf (klass->image, "Could not load field %d type due to: %s", field_idx, mono_error_get_message (error));
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, err_msg);
+ mono_class_set_type_load_failure (klass, "Could not load field %d type due to: %s", field_idx, mono_error_get_message (error));
}
field->type = mono_class_inflate_generic_type_no_copy (image, gtype, mono_class_get_context (klass), error);
if (!mono_error_ok (error)) {
- char *err_msg = mono_image_strdup_printf (klass->image, "Could not load field %d type due to: %s", field_idx, mono_error_get_message (error));
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, err_msg);
+ mono_class_set_type_load_failure (klass, "Could not load field %d type due to: %s", field_idx, mono_error_get_message (error));
}
} else {
const char *sig;
if (!mono_verifier_verify_field_signature (image, cols [MONO_FIELD_SIGNATURE], NULL)) {
mono_error_set_type_load_class (error, klass, "Could not verify field %s signature", field->name);;
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, mono_image_strdup (klass->image, mono_error_get_message (error)));
+ mono_class_set_type_load_failure (klass, "%s", mono_error_get_message (error));
return;
}
field->type = mono_metadata_parse_type_checked (image, container, cols [MONO_FIELD_FLAGS], FALSE, sig + 1, &sig, error);
if (!field->type) {
- char *err_msg = mono_image_strdup_printf (klass->image, "Could not load field %d type due to: %s", field_idx, mono_error_get_message (error));
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, err_msg);
+ mono_class_set_type_load_failure (klass, "Could not load field %d type due to: %s", field_idx, mono_error_get_message (error));
}
}
}
domain = mono_domain_get ();
len = mono_array_length (arr);
text = g_string_new_len (NULL, len * 20);
- messages = backtrace_symbols (mono_array_addr (arr, gpointer, 0), len);
-
+ uint32_t gchandle = mono_gchandle_new (&arr->obj, TRUE); /* pinned */
+ void* addr = mono_array_addr (arr, gpointer, 0);
+ MONO_ENTER_GC_SAFE;
+ messages = backtrace_symbols (addr, len);
+ MONO_EXIT_GC_SAFE;
+ mono_gchandle_free (gchandle);
for (i = 0; i < len; ++i) {
gpointer ip = mono_array_get (arr, gpointer, i);
ICALL (COMPO_W_1, "W32ErrorMessage", ves_icall_System_ComponentModel_Win32Exception_W32ErrorMessage)
ICALL_TYPE(DEFAULTC, "System.Configuration.DefaultConfig", DEFAULTC_1)
-HANDLES(ICALL(DEFAULTC_1, "get_bundled_machine_config", get_bundled_machine_config))
+HANDLES(ICALL(DEFAULTC_1, "get_bundled_machine_config", ves_icall_System_Configuration_DefaultConfig_get_bundled_machine_config))
ICALL(DEFAULTC_2, "get_machine_config_path", ves_icall_System_Configuration_DefaultConfig_get_machine_config_path)
/* Note that the below icall shares the same function as DefaultConfig uses */
ICALL_TYPE(INTCFGHOST, "System.Configuration.InternalConfigurationHost", INTCFGHOST_1)
ICALL(INTCFGHOST_1, "get_bundled_app_config", get_bundled_app_config)
-ICALL(INTCFGHOST_2, "get_bundled_machine_config", get_bundled_machine_config)
+HANDLES(ICALL(INTCFGHOST_2, "get_bundled_machine_config", ves_icall_System_Configuration_InternalConfigurationHost_get_bundled_machine_config))
ICALL_TYPE(CONSOLE, "System.ConsoleDriver", CONSOLE_1)
ICALL(CONSOLE_1, "InternalKeyAvailable", ves_icall_System_ConsoleDriver_InternalKeyAvailable )
ICALL(SOCK_3, "Bind_internal(intptr,System.Net.SocketAddress,int&)", ves_icall_System_Net_Sockets_Socket_Bind_internal)
ICALL(SOCK_4, "Blocking_internal(intptr,bool,int&)", ves_icall_System_Net_Sockets_Socket_Blocking_internal)
ICALL(SOCK_5, "Close_internal(intptr,int&)", ves_icall_System_Net_Sockets_Socket_Close_internal)
-ICALL(SOCK_6, "Connect_internal(intptr,System.Net.SocketAddress,int&)", ves_icall_System_Net_Sockets_Socket_Connect_internal)
+ICALL(SOCK_6, "Connect_internal(intptr,System.Net.SocketAddress,int&,bool)", ves_icall_System_Net_Sockets_Socket_Connect_internal)
ICALL (SOCK_6a, "Disconnect_internal(intptr,bool,int&)", ves_icall_System_Net_Sockets_Socket_Disconnect_internal)
ICALL(SOCK_7, "GetSocketOption_arr_internal(intptr,System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,byte[]&,int&)", ves_icall_System_Net_Sockets_Socket_GetSocketOption_arr_internal)
ICALL(SOCK_8, "GetSocketOption_obj_internal(intptr,System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,object&,int&)", ves_icall_System_Net_Sockets_Socket_GetSocketOption_obj_internal)
ICALL(SOCK_9, "Listen_internal(intptr,int,int&)", ves_icall_System_Net_Sockets_Socket_Listen_internal)
ICALL(SOCK_10, "LocalEndPoint_internal(intptr,int,int&)", ves_icall_System_Net_Sockets_Socket_LocalEndPoint_internal)
ICALL(SOCK_11, "Poll_internal", ves_icall_System_Net_Sockets_Socket_Poll_internal)
-ICALL(SOCK_13, "ReceiveFrom_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,System.Net.SocketAddress&,int&)", ves_icall_System_Net_Sockets_Socket_ReceiveFrom_internal)
-ICALL(SOCK_11a, "Receive_internal(intptr,System.Net.Sockets.Socket/WSABUF[],System.Net.Sockets.SocketFlags,int&)", ves_icall_System_Net_Sockets_Socket_Receive_array_internal)
-ICALL(SOCK_12, "Receive_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,int&)", ves_icall_System_Net_Sockets_Socket_Receive_internal)
+ICALL(SOCK_13, "ReceiveFrom_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,System.Net.SocketAddress&,int&,bool)", ves_icall_System_Net_Sockets_Socket_ReceiveFrom_internal)
+ICALL(SOCK_11a, "Receive_internal(intptr,System.Net.Sockets.Socket/WSABUF[],System.Net.Sockets.SocketFlags,int&,bool)", ves_icall_System_Net_Sockets_Socket_Receive_array_internal)
+ICALL(SOCK_12, "Receive_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,int&,bool)", ves_icall_System_Net_Sockets_Socket_Receive_internal)
ICALL(SOCK_14, "RemoteEndPoint_internal(intptr,int,int&)", ves_icall_System_Net_Sockets_Socket_RemoteEndPoint_internal)
ICALL(SOCK_15, "Select_internal(System.Net.Sockets.Socket[]&,int,int&)", ves_icall_System_Net_Sockets_Socket_Select_internal)
-ICALL(SOCK_15a, "SendFile_internal(intptr,string,byte[],byte[],System.Net.Sockets.TransmitFileOptions)", ves_icall_System_Net_Sockets_Socket_SendFile_internal)
-ICALL(SOCK_16, "SendTo_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,System.Net.SocketAddress,int&)", ves_icall_System_Net_Sockets_Socket_SendTo_internal)
-ICALL(SOCK_16a, "Send_internal(intptr,System.Net.Sockets.Socket/WSABUF[],System.Net.Sockets.SocketFlags,int&)", ves_icall_System_Net_Sockets_Socket_Send_array_internal)
-ICALL(SOCK_17, "Send_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,int&)", ves_icall_System_Net_Sockets_Socket_Send_internal)
+ICALL(SOCK_15a, "SendFile_internal(intptr,string,byte[],byte[],System.Net.Sockets.TransmitFileOptions,int&,bool)", ves_icall_System_Net_Sockets_Socket_SendFile_internal)
+ICALL(SOCK_16, "SendTo_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,System.Net.SocketAddress,int&,bool)", ves_icall_System_Net_Sockets_Socket_SendTo_internal)
+ICALL(SOCK_16a, "Send_internal(intptr,System.Net.Sockets.Socket/WSABUF[],System.Net.Sockets.SocketFlags,int&,bool)", ves_icall_System_Net_Sockets_Socket_Send_array_internal)
+ICALL(SOCK_17, "Send_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,int&,bool)", ves_icall_System_Net_Sockets_Socket_Send_internal)
ICALL(SOCK_18, "SetSocketOption_internal(intptr,System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,object,byte[],int,int&)", ves_icall_System_Net_Sockets_Socket_SetSocketOption_internal)
ICALL(SOCK_19, "Shutdown_internal(intptr,System.Net.Sockets.SocketShutdown,int&)", ves_icall_System_Net_Sockets_Socket_Shutdown_internal)
ICALL(SOCK_20, "Socket_internal(System.Net.Sockets.AddressFamily,System.Net.Sockets.SocketType,System.Net.Sockets.ProtocolType,int&)", ves_icall_System_Net_Sockets_Socket_Socket_internal)
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;
}
if (type == NULL){
if (throwOnError) {
- mono_error_set_type_load_name (&error, g_strdup (str), NULL, "");
+ mono_error_set_type_load_name (&error, g_strdup (str), g_strdup (""), "");
goto leave;
}
}
/* need to report exceptions ? */
if (throwOnError && mono_class_has_failure (klass)) {
/* report SecurityException (or others) that occured when loading the assembly */
- MonoException *exc = mono_class_get_exception_for_failure (klass);
- mono_set_pending_exception (exc);
+ mono_error_set_for_class_failure (&error, klass);
+ mono_error_set_pending_exception (&error);
return NULL;
}
}
check_for_invalid_type (MonoClass *klass, MonoError *error)
{
char *name;
- MonoString *str;
mono_error_init (error);
return;
name = mono_type_get_full_name (klass);
- str = mono_string_new (mono_domain_get (), name);
- g_free (name);
- mono_error_set_exception_instance (error, mono_get_exception_type_load (str, NULL));
-
+ mono_error_set_type_load_name (error, name, g_strdup (""), "");
}
ICALL_EXPORT MonoReflectionType *
ves_icall_RuntimeType_make_array_type (MonoReflectionType *type, int rank)
klass = mono_class_from_mono_type (type->type);
check_for_invalid_type (klass, &error);
- mono_error_set_pending_exception (&error);
+ if (mono_error_set_pending_exception (&error))
+ return NULL;
if (rank == 0) //single dimentional array
aklass = mono_array_class_get (klass, 1);
return mono_string_new (mono_domain_get (), app_config);
}
-/* this is an icall */
static MonoStringHandle
get_bundled_machine_config (MonoError *error)
{
return mono_string_new_handle (mono_domain_get (), machine_config, error);
}
+static MonoStringHandle
+ves_icall_System_Configuration_DefaultConfig_get_bundled_machine_config (MonoError *error)
+{
+ return get_bundled_machine_config (error);
+}
+
+static MonoStringHandle
+ves_icall_System_Configuration_InternalConfigurationHost_get_bundled_machine_config (MonoError *error)
+{
+ return get_bundled_machine_config (error);
+}
+
+
ICALL_EXPORT MonoString *
ves_icall_System_Web_Util_ICalls_get_machine_install_dir (void)
{
#endif
if (method->klass->valuetype && !(method->flags & MONO_METHOD_ATTR_STATIC)) {
- mono_class_set_failure (method->klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+ /* FIXME Is this really the best way to signal an error here? Isn't this called much later after class setup? -AK */
+ mono_class_set_type_load_failure (method->klass, "");
#ifndef DISABLE_JIT
/* This will throw the type load exception when the wrapper is compiled */
mono_mb_emit_byte (mb, CEE_LDNULL);
j++;
}
+ if (klass->byval_arg.type == MONO_TYPE_PTR)
+ info->native_size = sizeof (gpointer);
+
if (layout != TYPE_ATTRIBUTE_AUTO_LAYOUT) {
info->native_size = MAX (native_size, info->native_size);
/*
static void
mono_backtrace (int size)
{
- void *array[BACKTRACE_DEPTH];
- char **names;
- int i, symbols;
- static gboolean inited;
-
- if (!inited) {
- mono_os_mutex_init_recursive (&mempool_tracing_lock);
- inited = TRUE;
- }
-
- mono_os_mutex_lock (&mempool_tracing_lock);
- g_print ("Allocating %d bytes\n", size);
- symbols = backtrace (array, BACKTRACE_DEPTH);
- names = backtrace_symbols (array, symbols);
- for (i = 1; i < symbols; ++i) {
- g_print ("\t%s\n", names [i]);
- }
- g_free (names);
- mono_os_mutex_unlock (&mempool_tracing_lock);
+ void *array[BACKTRACE_DEPTH];
+ char **names;
+ int i, symbols;
+ static gboolean inited;
+
+ if (!inited) {
+ mono_os_mutex_init_recursive (&mempool_tracing_lock);
+ inited = TRUE;
+ }
+
+ mono_os_mutex_lock (&mempool_tracing_lock);
+ g_print ("Allocating %d bytes\n", size);
+ MONO_ENTER_GC_SAFE;
+ symbols = backtrace (array, BACKTRACE_DEPTH);
+ names = backtrace_symbols (array, symbols);
+ MONO_EXIT_GC_SAFE;
+ for (i = 1; i < symbols; ++i) {
+ g_print ("\t%s\n", names [i]);
+ }
+ g_free (names);
+ mono_os_mutex_unlock (&mempool_tracing_lock);
}
#endif
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)
{
if (mono_class_has_failure (element_class)) {
/*Can happen if element_class only got bad after mono_class_setup_vtable*/
if (!mono_class_has_failure (klass))
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+ mono_class_set_type_load_failure (klass, "");
mono_domain_unlock (domain);
mono_loader_unlock ();
mono_error_set_for_class_failure (error, klass);
return res;
}
-static gboolean
-verify_safe_for_managed_space (MonoType *type)
-{
- switch (type->type) {
-#ifdef DEBUG_HARDER
- case MONO_TYPE_ARRAY:
- return verify_safe_for_managed_space (&type->data.array->eklass->byval_arg);
- case MONO_TYPE_PTR:
- return verify_safe_for_managed_space (type->data.type);
- case MONO_TYPE_SZARRAY:
- return verify_safe_for_managed_space (&type->data.klass->byval_arg);
- case MONO_TYPE_GENERICINST: {
- MonoGenericInst *inst = type->data.generic_class->inst;
- int i;
- if (!inst->is_open)
- break;
- for (i = 0; i < inst->type_argc; ++i)
- if (!verify_safe_for_managed_space (inst->type_argv [i]))
- return FALSE;
- return TRUE;
- }
-#endif
- case MONO_TYPE_VAR:
- case MONO_TYPE_MVAR:
- return TRUE;
- default:
- return TRUE;
- }
-}
-
static MonoType*
mono_type_normalize (MonoType *type)
{
if ((type->type == MONO_TYPE_GENERICINST) && type->data.generic_class->is_dynamic && !type->data.generic_class->container_class->wastypebuilder)
g_assert (0);
- if (!verify_safe_for_managed_space (type)) {
+ if (mono_class_get_ref_info (klass) && !klass->wastypebuilder && !type->byref) {
mono_domain_unlock (domain);
mono_loader_unlock ();
- mono_error_set_generic_error (error, "System", "InvalidOperationException", "This type cannot be propagated to managed space");
- return NULL;
- }
-
- if (mono_class_get_ref_info (klass) && !klass->wastypebuilder) {
- gboolean is_type_done = TRUE;
- /* Generic parameters have reflection_info set but they are not finished together with their enclosing type.
- * We must ensure that once a type is finished we don't return a GenericTypeParameterBuilder.
- * We can't simply close the types as this will interfere with other parts of the generics machinery.
- */
- if (klass->byval_arg.type == MONO_TYPE_MVAR || klass->byval_arg.type == MONO_TYPE_VAR) {
- MonoGenericParam *gparam = klass->byval_arg.data.generic_param;
-
- if (gparam->owner && gparam->owner->is_method && !gparam->owner->is_anonymous) {
- MonoMethod *method = gparam->owner->owner.method;
- if (method && mono_class_get_generic_type_definition (method->klass)->wastypebuilder)
- is_type_done = FALSE;
- } else if (gparam->owner && !gparam->owner->is_method) {
- MonoClass *klass = gparam->owner->owner.klass;
- if (klass && mono_class_get_generic_type_definition (klass)->wastypebuilder)
- is_type_done = FALSE;
- }
- }
-
- /* g_assert_not_reached (); */
- /* should this be considered an error condition? */
- if (is_type_done && !type->byref) {
- mono_domain_unlock (domain);
- mono_loader_unlock ();
- return (MonoReflectionType *)mono_class_get_ref_info (klass);
- }
+ return (MonoReflectionType *)mono_class_get_ref_info (klass);
}
/* This is stored in vtables/JITted code so it has to be pinned */
res = (MonoReflectionType *)mono_object_new_pinned (domain, mono_defaults.runtimetype_class, error);
g_free (type_name);
mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, "%s", message);
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, message);
+ mono_class_set_type_load_failure (klass, "%s", message);
// note: do not free string given to mono_class_set_failure
}
g_free (method_name);
mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, "%s", message);
- mono_class_set_failure (override->klass, MONO_EXCEPTION_TYPE_LOAD, message);
+ mono_class_set_type_load_failure (override->klass, "%s", message);
// note: do not free string given to mono_class_set_failure
}
--- /dev/null
+/*
+* socket-io-windows-internals.h: Windows specific socket code.
+*
+* Copyright 2016 Microsoft
+* Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#ifndef __MONO_METADATA_SOCKET_IO_WINDOWS_INTERNALS_H__
+#define __MONO_METADATA_SOCKET_IO_WINDOWS_INTERNALS_H__
+
+#include <config.h>
+#include <glib.h>
+#include <mono/io-layer/io-layer.h>
+
+SOCKET alertable_accept (SOCKET s, struct sockaddr *addr, int *addrlen, gboolean blocking);
+int alertable_connect (SOCKET s, const struct sockaddr *name, int namelen, gboolean blocking);
+int alertable_recv (SOCKET s, char *buf, int len, int flags, gboolean blocking);
+int alertable_recvfrom (SOCKET s, char *buf, int len, int flags, struct sockaddr *from, int *fromlen, gboolean blocking);
+int alertable_WSARecv (SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount, LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, LPWSAOVERLAPPED lpOverlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, gboolean blocking);
+int alertable_send (SOCKET s, char *buf, int len, int flags, gboolean blocking);
+int alertable_sendto (SOCKET s, const char *buf, int len, int flags, const struct sockaddr *to, int tolen, gboolean blocking);
+int alertable_WSASend (SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount, LPDWORD lpNumberOfBytesRecvd, DWORD lpFlags, LPWSAOVERLAPPED lpOverlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, gboolean blocking);
+BOOL alertable_TransmitFile (SOCKET hSocket, HANDLE hFile, DWORD nNumberOfBytesToWrite, DWORD nNumberOfBytesPerSend, LPOVERLAPPED lpOverlapped, LPTRANSMIT_FILE_BUFFERS lpTransmitBuffers, DWORD dwReserved, gboolean blocking);
+
+#endif // __MONO_METADATA_SOCKET_IO_WINDOWS_INTERNALS_H__
--- /dev/null
+/*
+* socket-io-windows.c: Windows specific socket code.
+*
+* Copyright 2016 Microsoft
+* Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+
+#include "mono/metadata/socket-io-windows-internals.h"
+
+#define LOGDEBUG(...)
+
+static gboolean set_blocking (SOCKET sock, gboolean block)
+{
+ u_long non_block = block ? 0 : 1;
+ return ioctlsocket (sock, FIONBIO, &non_block) != SOCKET_ERROR;
+}
+
+static DWORD get_socket_timeout (SOCKET sock, int optname)
+{
+ DWORD timeout = 0;
+ int optlen = sizeof (DWORD);
+ if (getsockopt (sock, SOL_SOCKET, optname, (char *)&timeout, &optlen) == SOCKET_ERROR) {
+ WSASetLastError (0);
+ return WSA_INFINITE;
+ }
+ if (timeout == 0)
+ timeout = WSA_INFINITE; // 0 means infinite
+ return timeout;
+}
+
+/*
+* Performs an alertable wait for the specified event (FD_ACCEPT_BIT,
+* FD_CONNECT_BIT, FD_READ_BIT, FD_WRITE_BIT) on the specified socket.
+* Returns TRUE if the event is fired without errors. Calls WSASetLastError()
+* with WSAEINTR and returns FALSE if the thread is alerted. If the event is
+* fired but with an error WSASetLastError() is called to set the error and the
+* function returns FALSE.
+*/
+static gboolean alertable_socket_wait (SOCKET sock, int event_bit)
+{
+ static char *EVENT_NAMES[] = { "FD_READ", "FD_WRITE", NULL /*FD_OOB*/, "FD_ACCEPT", "FD_CONNECT", "FD_CLOSE" };
+ gboolean success = FALSE;
+ int error = -1;
+ DWORD timeout = WSA_INFINITE;
+ if (event_bit == FD_READ_BIT || event_bit == FD_WRITE_BIT) {
+ timeout = get_socket_timeout (sock, event_bit == FD_READ_BIT ? SO_RCVTIMEO : SO_SNDTIMEO);
+ }
+ WSASetLastError (0);
+ WSAEVENT event = WSACreateEvent ();
+ if (event != WSA_INVALID_EVENT) {
+ if (WSAEventSelect (sock, event, (1 << event_bit) | FD_CLOSE) != SOCKET_ERROR) {
+ LOGDEBUG (g_message ("%06d - Calling WSAWaitForMultipleEvents () on socket %d", GetCurrentThreadId (), sock));
+ DWORD ret = WSAWaitForMultipleEvents (1, &event, TRUE, timeout, TRUE);
+ if (ret == WSA_WAIT_IO_COMPLETION) {
+ LOGDEBUG (g_message ("%06d - WSAWaitForMultipleEvents () returned WSA_WAIT_IO_COMPLETION for socket %d", GetCurrentThreadId (), sock));
+ error = WSAEINTR;
+ } else if (ret == WSA_WAIT_TIMEOUT) {
+ error = WSAETIMEDOUT;
+ } else {
+ g_assert (ret == WSA_WAIT_EVENT_0);
+ WSANETWORKEVENTS ne = { 0 };
+ if (WSAEnumNetworkEvents (sock, event, &ne) != SOCKET_ERROR) {
+ if (ne.lNetworkEvents & (1 << event_bit) && ne.iErrorCode[event_bit]) {
+ LOGDEBUG (g_message ("%06d - %s error %d on socket %d", GetCurrentThreadId (), EVENT_NAMES[event_bit], ne.iErrorCode[event_bit], sock));
+ error = ne.iErrorCode[event_bit];
+ } else if (ne.lNetworkEvents & FD_CLOSE_BIT && ne.iErrorCode[FD_CLOSE_BIT]) {
+ LOGDEBUG (g_message ("%06d - FD_CLOSE error %d on socket %d", GetCurrentThreadId (), ne.iErrorCode[FD_CLOSE_BIT], sock));
+ error = ne.iErrorCode[FD_CLOSE_BIT];
+ } else {
+ LOGDEBUG (g_message ("%06d - WSAEnumNetworkEvents () finished successfully on socket %d", GetCurrentThreadId (), sock));
+ success = TRUE;
+ error = 0;
+ }
+ }
+ }
+ WSAEventSelect (sock, NULL, 0);
+ }
+ WSACloseEvent (event);
+ }
+ if (error != -1) {
+ WSASetLastError (error);
+ }
+ return success;
+}
+
+#define ALERTABLE_SOCKET_CALL(event_bit, blocking, repeat, ret, op, sock, ...) \
+ LOGDEBUG (g_message ("%06d - Performing %s " #op " () on socket %d", GetCurrentThreadId (), blocking ? "blocking" : "non-blocking", sock)); \
+ if (blocking) { \
+ if (set_blocking(sock, FALSE)) { \
+ while (-1 == (int) (ret = op (sock, __VA_ARGS__))) { \
+ int _error = WSAGetLastError ();\
+ if (_error != WSAEWOULDBLOCK && _error != WSA_IO_PENDING) \
+ break; \
+ if (!alertable_socket_wait (sock, event_bit) || !repeat) \
+ break; \
+ } \
+ int _saved_error = WSAGetLastError (); \
+ set_blocking (sock, TRUE); \
+ WSASetLastError (_saved_error); \
+ } \
+ } else { \
+ ret = op (sock, __VA_ARGS__); \
+ } \
+ int _saved_error = WSAGetLastError (); \
+ LOGDEBUG (g_message ("%06d - Finished %s " #op " () on socket %d (ret = %d, WSAGetLastError() = %d)", GetCurrentThreadId (), \
+ blocking ? "blocking" : "non-blocking", sock, ret, _saved_error)); \
+ WSASetLastError (_saved_error);
+
+SOCKET alertable_accept (SOCKET s, struct sockaddr *addr, int *addrlen, gboolean blocking)
+{
+ SOCKET newsock = INVALID_SOCKET;
+ ALERTABLE_SOCKET_CALL (FD_ACCEPT_BIT, blocking, TRUE, newsock, accept, s, addr, addrlen);
+ return newsock;
+}
+
+int alertable_connect (SOCKET s, const struct sockaddr *name, int namelen, gboolean blocking)
+{
+ int ret = SOCKET_ERROR;
+ ALERTABLE_SOCKET_CALL (FD_CONNECT_BIT, blocking, FALSE, ret, connect, s, name, namelen);
+ ret = WSAGetLastError () != 0 ? SOCKET_ERROR : 0;
+ return ret;
+}
+
+int alertable_recv (SOCKET s, char *buf, int len, int flags, gboolean blocking)
+{
+ int ret = SOCKET_ERROR;
+ ALERTABLE_SOCKET_CALL (FD_READ_BIT, blocking, TRUE, ret, recv, s, buf, len, flags);
+ return ret;
+}
+
+int alertable_recvfrom (SOCKET s, char *buf, int len, int flags, struct sockaddr *from, int *fromlen, gboolean blocking)
+{
+ int ret = SOCKET_ERROR;
+ ALERTABLE_SOCKET_CALL (FD_READ_BIT, blocking, TRUE, ret, recvfrom, s, buf, len, flags, from, fromlen);
+ return ret;
+}
+
+int alertable_WSARecv (SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount, LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, LPWSAOVERLAPPED lpOverlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, gboolean blocking)
+{
+ int ret = SOCKET_ERROR;
+ ALERTABLE_SOCKET_CALL (FD_READ_BIT, blocking, TRUE, ret, WSARecv, s, lpBuffers, dwBufferCount, lpNumberOfBytesRecvd, lpFlags, lpOverlapped, lpCompletionRoutine);
+ return ret;
+}
+
+int alertable_send (SOCKET s, char *buf, int len, int flags, gboolean blocking)
+{
+ int ret = SOCKET_ERROR;
+ ALERTABLE_SOCKET_CALL (FD_WRITE_BIT, blocking, FALSE, ret, send, s, buf, len, flags);
+ return ret;
+}
+
+int alertable_sendto (SOCKET s, const char *buf, int len, int flags, const struct sockaddr *to, int tolen, gboolean blocking)
+{
+ int ret = SOCKET_ERROR;
+ ALERTABLE_SOCKET_CALL (FD_WRITE_BIT, blocking, FALSE, ret, sendto, s, buf, len, flags, to, tolen);
+ return ret;
+}
+
+int alertable_WSASend (SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount, LPDWORD lpNumberOfBytesRecvd, DWORD lpFlags, LPWSAOVERLAPPED lpOverlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, gboolean blocking)
+{
+ int ret = SOCKET_ERROR;
+ ALERTABLE_SOCKET_CALL (FD_WRITE_BIT, blocking, FALSE, ret, WSASend, s, lpBuffers, dwBufferCount, lpNumberOfBytesRecvd, lpFlags, lpOverlapped, lpCompletionRoutine);
+ return ret;
+}
+
+BOOL alertable_TransmitFile (SOCKET hSocket, HANDLE hFile, DWORD nNumberOfBytesToWrite, DWORD nNumberOfBytesPerSend, LPOVERLAPPED lpOverlapped, LPTRANSMIT_FILE_BUFFERS lpTransmitBuffers, DWORD dwReserved, gboolean blocking)
+{
+ LOGDEBUG (g_message ("%06d - Performing %s TransmitFile () on socket %d", GetCurrentThreadId (), blocking ? "blocking" : "non-blocking", hSocket));
+
+ int error = 0;
+ if (blocking) {
+ g_assert (lpOverlapped == NULL);
+ OVERLAPPED overlapped = { 0 };
+ overlapped.hEvent = WSACreateEvent ();
+ if (overlapped.hEvent == WSA_INVALID_EVENT)
+ return FALSE;
+ if (!TransmitFile (hSocket, hFile, nNumberOfBytesToWrite, nNumberOfBytesPerSend, &overlapped, lpTransmitBuffers, dwReserved)) {
+ error = WSAGetLastError ();
+ if (error == WSA_IO_PENDING) {
+ error = 0;
+ // NOTE: .NET's Socket.SendFile() doesn't honor the Socket's SendTimeout so we shouldn't either
+ DWORD ret = WaitForSingleObjectEx (overlapped.hEvent, INFINITE, TRUE);
+ if (ret == WAIT_IO_COMPLETION) {
+ LOGDEBUG (g_message ("%06d - WaitForSingleObjectEx () returned WSA_WAIT_IO_COMPLETION for socket %d", GetCurrentThreadId (), hSocket));
+ error = WSAEINTR;
+ } else if (ret == WAIT_TIMEOUT) {
+ error = WSAETIMEDOUT;
+ } else if (ret != WAIT_OBJECT_0) {
+ error = GetLastError ();
+ }
+ }
+ }
+ WSACloseEvent (overlapped.hEvent);
+ } else {
+ if (!TransmitFile (hSocket, hFile, nNumberOfBytesToWrite, nNumberOfBytesPerSend, lpOverlapped, lpTransmitBuffers, dwReserved)) {
+ error = WSAGetLastError ();
+ }
+ }
+
+ LOGDEBUG (g_message ("%06d - Finished %s TransmitFile () on socket %d (ret = %d, WSAGetLastError() = %d)", GetCurrentThreadId (), \
+ blocking ? "blocking" : "non-blocking", hSocket, error == 0, error));
+ WSASetLastError (error);
+
+ return error == 0;
+}
#endif
#include "mono/io-layer/socket-wrappers.h"
+#ifdef HOST_WIN32
+#include "mono/metadata/socket-io-windows-internals.h"
+#endif
#define LOGDEBUG(...)
/* define LOGDEBUG(...) g_message(__VA_ARGS__) */
{
MonoInternalThread *curthread = mono_thread_internal_current ();
curthread->interrupt_on_stop = (gpointer)TRUE;
- newsock = _wapi_accept (sock, NULL, 0);
+ newsock = alertable_accept (sock, NULL, 0, blocking);
curthread->interrupt_on_stop = (gpointer)FALSE;
}
#else
}
void
-ves_icall_System_Net_Sockets_Socket_Connect_internal (SOCKET sock, MonoObject *sockaddr, gint32 *werror)
+ves_icall_System_Net_Sockets_Socket_Connect_internal (SOCKET sock, MonoObject *sockaddr, gint32 *werror, gboolean blocking)
{
MonoError error;
struct sockaddr *sa;
MONO_ENTER_GC_SAFE;
+#ifdef HOST_WIN32
+ ret = alertable_connect (sock, sa, sa_size, blocking);
+#else
ret = _wapi_connect (sock, sa, sa_size);
+#endif
MONO_EXIT_GC_SAFE;
}
gint32
-ves_icall_System_Net_Sockets_Socket_Receive_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *werror)
+ves_icall_System_Net_Sockets_Socket_Receive_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *werror, gboolean blocking)
{
int ret;
guchar *buf;
#ifdef HOST_WIN32
{
curthread->interrupt_on_stop = (gpointer)TRUE;
- ret = _wapi_recv (sock, buf, count, recvflags);
+ ret = alertable_recv (sock, buf, count, recvflags, blocking);
curthread->interrupt_on_stop = (gpointer)FALSE;
}
#else
}
gint32
-ves_icall_System_Net_Sockets_Socket_Receive_array_internal (SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *werror)
+ves_icall_System_Net_Sockets_Socket_Receive_array_internal (SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *werror, gboolean blocking)
{
int ret, count;
gboolean interrupted;
MONO_ENTER_GC_SAFE;
+#ifdef HOST_WIN32
+ ret = alertable_WSARecv (sock, wsabufs, count, &recv, &recvflags, NULL, NULL, blocking);
+#else
ret = WSARecv (sock, wsabufs, count, &recv, &recvflags, NULL, NULL);
+#endif
MONO_EXIT_GC_SAFE;
}
gint32
-ves_icall_System_Net_Sockets_Socket_ReceiveFrom_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject **sockaddr, gint32 *werror)
+ves_icall_System_Net_Sockets_Socket_ReceiveFrom_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject **sockaddr, gint32 *werror, gboolean blocking)
{
MonoError error;
int ret;
MONO_ENTER_GC_SAFE;
+#ifdef HOST_WIN32
+ ret = alertable_recvfrom (sock, buf, count, recvflags, sa, &sa_size, blocking);
+#else
ret = _wapi_recvfrom (sock, buf, count, recvflags, sa, &sa_size);
+#endif
MONO_EXIT_GC_SAFE;
}
gint32
-ves_icall_System_Net_Sockets_Socket_Send_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *werror)
+ves_icall_System_Net_Sockets_Socket_Send_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *werror, gboolean blocking)
{
int ret;
guchar *buf;
MONO_ENTER_GC_SAFE;
+#ifdef HOST_WIN32
+ ret = alertable_send (sock, buf, count, sendflags, blocking);
+#else
ret = _wapi_send (sock, buf, count, sendflags);
+#endif
MONO_EXIT_GC_SAFE;
}
gint32
-ves_icall_System_Net_Sockets_Socket_Send_array_internal (SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *werror)
+ves_icall_System_Net_Sockets_Socket_Send_array_internal (SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *werror, gboolean blocking)
{
int ret, count;
DWORD sent;
MONO_ENTER_GC_SAFE;
+#ifdef HOST_WIN32
+ ret = alertable_WSASend (sock, wsabufs, count, &sent, sendflags, NULL, NULL, blocking);
+#else
ret = WSASend (sock, wsabufs, count, &sent, sendflags, NULL, NULL);
+#endif
MONO_EXIT_GC_SAFE;
}
gint32
-ves_icall_System_Net_Sockets_Socket_SendTo_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject *sockaddr, gint32 *werror)
+ves_icall_System_Net_Sockets_Socket_SendTo_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject *sockaddr, gint32 *werror, gboolean blocking)
{
MonoError error;
int ret;
MONO_ENTER_GC_SAFE;
+#ifdef HOST_WIN32
+ ret = alertable_sendto (sock, buf, count, sendflags, sa, sa_size, blocking);
+#else
ret = _wapi_sendto (sock, buf, count, sendflags, sa, sa_size);
+#endif
MONO_EXIT_GC_SAFE;
}
gboolean
-ves_icall_System_Net_Sockets_Socket_SendFile_internal (SOCKET sock, MonoString *filename, MonoArray *pre_buffer, MonoArray *post_buffer, gint flags)
+ves_icall_System_Net_Sockets_Socket_SendFile_internal (SOCKET sock, MonoString *filename, MonoArray *pre_buffer, MonoArray *post_buffer, gint flags, gint32 *werror, gboolean blocking)
{
HANDLE file;
- gint32 werror;
gboolean ret;
gboolean interrupted;
TRANSMIT_FILE_BUFFERS buffers;
/* FIXME: replace file by a proper fd that we can call open and close on, as they are interruptible */
- file = ves_icall_System_IO_MonoIO_Open (filename, FileMode_Open, FileAccess_Read, FileShare_Read, 0, &werror);
+ file = ves_icall_System_IO_MonoIO_Open (filename, FileMode_Open, FileAccess_Read, FileShare_Read, 0, werror);
if (file == INVALID_HANDLE_VALUE) {
- SetLastError (werror);
+ SetLastError (*werror);
return FALSE;
}
MONO_ENTER_GC_SAFE;
+#ifdef HOST_WIN32
+ ret = alertable_TransmitFile (sock, file, 0, 0, NULL, &buffers, flags, blocking);
+#else
ret = TransmitFile (sock, file, 0, 0, NULL, &buffers, flags);
+#endif
MONO_EXIT_GC_SAFE;
+ if (!ret)
+ *werror = WSAGetLastError ();
+
mono_thread_info_uninstall_interrupt (&interrupted);
if (interrupted) {
CloseHandle (file);
- SetLastError (WSAEINTR);
+ *werror = WSAEINTR;
return FALSE;
}
MONO_EXIT_GC_SAFE;
+ if (*werror)
+ return FALSE;
+
return ret;
}
extern MonoObject *ves_icall_System_Net_Sockets_Socket_LocalEndPoint_internal(SOCKET sock, gint32 af, gint32 *error);
extern MonoObject *ves_icall_System_Net_Sockets_Socket_RemoteEndPoint_internal(SOCKET sock, gint32 af, gint32 *error);
extern void ves_icall_System_Net_Sockets_Socket_Bind_internal(SOCKET sock, MonoObject *sockaddr, gint32 *error);
-extern void ves_icall_System_Net_Sockets_Socket_Connect_internal(SOCKET sock, MonoObject *sockaddr, gint32 *error);
-extern gint32 ves_icall_System_Net_Sockets_Socket_Receive_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *error);
-extern gint32 ves_icall_System_Net_Sockets_Socket_Receive_array_internal(SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *error);
-extern gint32 ves_icall_System_Net_Sockets_Socket_ReceiveFrom_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject **sockaddr, gint32 *error);
-extern gint32 ves_icall_System_Net_Sockets_Socket_Send_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *error);
-extern gint32 ves_icall_System_Net_Sockets_Socket_Send_array_internal(SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *error);
-extern gint32 ves_icall_System_Net_Sockets_Socket_SendTo_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject *sockaddr, gint32 *error);
+extern void ves_icall_System_Net_Sockets_Socket_Connect_internal(SOCKET sock, MonoObject *sockaddr, gint32 *error, gboolean blocking);
+extern gint32 ves_icall_System_Net_Sockets_Socket_Receive_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *error, gboolean blocking);
+extern gint32 ves_icall_System_Net_Sockets_Socket_Receive_array_internal(SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *error, gboolean blocking);
+extern gint32 ves_icall_System_Net_Sockets_Socket_ReceiveFrom_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject **sockaddr, gint32 *error, gboolean blocking);
+extern gint32 ves_icall_System_Net_Sockets_Socket_Send_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *error, gboolean blocking);
+extern gint32 ves_icall_System_Net_Sockets_Socket_Send_array_internal(SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *error, gboolean blocking);
+extern gint32 ves_icall_System_Net_Sockets_Socket_SendTo_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject *sockaddr, gint32 *error, gboolean blocking);
extern void ves_icall_System_Net_Sockets_Socket_Select_internal(MonoArray **sockets, gint32 timeout, gint32 *error);
extern void ves_icall_System_Net_Sockets_Socket_Shutdown_internal(SOCKET sock, gint32 how, gint32 *error);
extern void ves_icall_System_Net_Sockets_Socket_GetSocketOption_obj_internal(SOCKET sock, gint32 level, gint32 name, MonoObject **obj_val, gint32 *error);
extern MonoBoolean ves_icall_System_Net_Dns_GetHostName_internal(MonoString **h_name);
extern MonoBoolean ves_icall_System_Net_Sockets_Socket_Poll_internal (SOCKET sock, gint mode, gint timeout, gint32 *error);
extern void ves_icall_System_Net_Sockets_Socket_Disconnect_internal(SOCKET sock, MonoBoolean reuse, gint32 *error);
-extern gboolean ves_icall_System_Net_Sockets_Socket_SendFile_internal (SOCKET sock, MonoString *filename, MonoArray *pre_buffer, MonoArray *post_buffer, gint flags);
+extern gboolean ves_icall_System_Net_Sockets_Socket_SendFile_internal (SOCKET sock, MonoString *filename, MonoArray *pre_buffer, MonoArray *post_buffer, gint flags, gint32 *error, gboolean blocking);
void icall_cancel_blocking_socket_operation (MonoThread *thread);
extern gboolean ves_icall_System_Net_Sockets_Socket_SupportPortReuse (MonoProtocolType proto);
container->type_params [i].param.owner = container;
gp->type.type->data.generic_param = (MonoGenericParam*)&container->type_params [i];
+
+ MonoClass *gklass = mono_class_from_mono_type (gp_type);
+ gklass->wastypebuilder = TRUE;
}
/*
}
} else if (klass->generic_class){
if (!ensure_generic_class_runtime_vtable (klass, error)) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+ mono_class_set_type_load_failure (klass, "Could not initialize vtable for generic class due to: %s", mono_error_get_message (error));
return FALSE;
}
}
if (tb->class_size) {
if ((tb->packing_size & 0xffffff00) != 0) {
- char *err_msg = mono_image_strdup_printf (klass->image, "Could not load struct '%s' with packing size %d >= 256", klass->name, tb->packing_size);
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, err_msg);
+ mono_class_set_type_load_failure (klass, "Could not load struct '%s' with packing size %d >= 256", klass->name, tb->packing_size);
return;
}
klass->packing_size = tb->packing_size;
MonoClass *inst_klass = mono_class_from_mono_type (type);
//Ensure it's safe to use it.
if (!fix_partial_generic_class (inst_klass, error)) {
- mono_class_set_failure (inst_klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+ mono_class_set_type_load_failure (inst_klass, "Could not initialized generic type instance due to: %s", mono_error_get_message (error));
// Marked the class with failure, but since some other instantiation already failed,
// just report that one, and swallow the error from this one.
if (already_failed)
klass->wastypebuilder = TRUE;
+ if (tb->generic_params) {
+ for (i = 0; i < mono_array_length (tb->generic_params); i++) {
+ MonoReflectionGenericParam *gparam = (MonoReflectionGenericParam *)mono_array_get (tb->generic_params, gpointer, i);
+ MonoType *param_type = mono_reflection_type_get_handle ((MonoReflectionType*)gparam, &error);
+ MonoClass *gklass = mono_class_from_mono_type (param_type);
+
+ gklass->wastypebuilder = TRUE;
+ }
+ }
+
/*
* If we are a generic TypeBuilder, there might be instantiations in the type cache
* which have type System.Reflection.MonoGenericClass, but after the type is created,
mono_loader_unlock ();
if (klass->enumtype && !mono_class_is_valid_enum (klass)) {
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+ mono_class_set_type_load_failure (klass, "Not a valid enumeration");
mono_error_set_type_load_class (&error, klass, "Not a valid enumeration");
goto failure_unlocked;
}
return res;
failure:
- mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+ mono_class_set_type_load_failure (klass, "TypeBuilder could not create runtime class due to: %s", mono_error_get_message (&error));
klass->wastypebuilder = TRUE;
mono_domain_unlock (domain);
mono_loader_unlock ();
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));
/*
windows_sources = \
mini-windows.c \
+ mini-windows.h \
mini-windows-dllmain.c
posix_sources = \
csig->params [1] = &mono_defaults.exception_class->byval_arg;
add_method (acfg, get_runtime_invoke_sig (csig));
- /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
- csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
+ /* Assembly runtime-invoke (string, Assembly, bool) [DoAssemblyResolve] */
+ csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
csig->hasthis = 1;
csig->ret = &(mono_class_load_from_name (
mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
csig->params [0] = &mono_defaults.string_class->byval_arg;
- csig->params [1] = &mono_defaults.boolean_class->byval_arg;
+ csig->params [1] = &(mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
+ csig->params [2] = &mono_defaults.boolean_class->byval_arg;
add_method (acfg, get_runtime_invoke_sig (csig));
/* runtime-invoke used by finalizers */
static void
generate_aotid (guint8* aotid)
{
- gpointer *rand_handle;
+ gpointer rand_handle;
MonoError error;
mono_rand_open ();
rand_handle = mono_rand_init (NULL, 0);
- mono_rand_try_get_bytes (rand_handle, aotid, 16, &error);
+ mono_rand_try_get_bytes (&rand_handle, aotid, 16, &error);
mono_error_assert_ok (&error);
mono_rand_close (rand_handle);
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);
#include <mono/utils/mono-time.h>
#include <mono/utils/mono-threads.h>
#include <mono/utils/networking.h>
+#include <mono/utils/mono-proclib.h>
#include "debugger-agent.h"
#include "mini.h"
#include "seq-points.h"
/* Waiting for deferred attachment */
agent_config.defer = TRUE;
if (agent_config.address == NULL) {
- agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (getpid () % 1000));
+ agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (mono_process_current_pid () % 1000));
}
}
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) {
exit (1);
}
-#ifdef HOST_WIN32
+#if defined(HOST_WIN32) && G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
/* Detach console when executing IMAGE_SUBSYSTEM_WINDOWS_GUI on win32 */
if (!enable_debugging && !mono_compile_aot && ((MonoCLIImageInfo*)(mono_assembly_get_image (assembly)->image_info))->cli_header.nt.pe_subsys_required == IMAGE_SUBSYSTEM_WINDOWS_GUI)
FreeConsole ();
#endif /* TARGET_WIN32 */
+#ifndef DISABLE_JIT
/*
* mono_arch_get_restore_context:
*
return start;
}
+#endif /* !DISABLE_JIT */
/*
* The first few arguments are dummy, to force the other arguments to be passed on
mono_resume_unwind (&ctx);
}
+#ifndef DISABLE_JIT
/*
* get_throw_trampoline:
*
{
return get_throw_trampoline (info, FALSE, TRUE, FALSE, FALSE, "throw_corlib_exception", aot);
}
+#endif /* !DISABLE_JIT */
/*
* mono_arch_unwind_frame:
return lmf->rip;
}
+#ifndef DISABLE_JIT
GSList*
mono_amd64_get_exception_trampolines (gboolean aot)
{
return tramps;
}
+#endif /* !DISABLE_JIT */
void
mono_arch_exceptions_init (void)
}
}
-#ifdef TARGET_WIN32
+#if defined(TARGET_WIN32) && !defined(DISABLE_JIT)
/*
* The mono_arch_unwindinfo* methods are used to build and add
RtlInstallFunctionTableCallback (((DWORD64)code) | 0x3, (DWORD64)code, code_size, MONO_GET_RUNTIME_FUNCTION_CALLBACK, code, NULL);
}
-#endif
+#endif /* defined(TARGET_WIN32) !defined(DISABLE_JIT) */
-#if MONO_SUPPORT_TASKLETS
+#if MONO_SUPPORT_TASKLETS && !defined(DISABLE_JIT)
MonoContinuationRestore
mono_tasklets_arch_restore (void)
{
saved = start;
return (MonoContinuationRestore)saved;
}
-#endif
+#endif /* MONO_SUPPORT_TASKLETS && !defined(DISABLE_JIT) */
/*
* mono_arch_setup_resume_sighandler_ctx:
MONO_CONTEXT_SET_SP (ctx, (guint64)MONO_CONTEXT_GET_SP (ctx) - 8);
MONO_CONTEXT_SET_IP (ctx, func);
}
+
+#ifdef DISABLE_JIT
+gpointer
+mono_arch_get_restore_context (MonoTrampInfo **info, gboolean aot)
+{
+ g_assert_not_reached ();
+ return NULL;
+}
+
+gpointer
+mono_arch_get_call_filter (MonoTrampInfo **info, gboolean aot)
+{
+ g_assert_not_reached ();
+ return NULL;
+}
+
+gpointer
+mono_arch_get_throw_exception (MonoTrampInfo **info, gboolean aot)
+{
+ g_assert_not_reached ();
+ return NULL;
+}
+
+gpointer
+mono_arch_get_rethrow_exception (MonoTrampInfo **info, gboolean aot)
+{
+ g_assert_not_reached ();
+ return NULL;
+}
+
+gpointer
+mono_arch_get_throw_corlib_exception (MonoTrampInfo **info, gboolean aot)
+{
+ g_assert_not_reached ();
+ return NULL;
+}
+
+GSList*
+mono_amd64_get_exception_trampolines (gboolean aot)
+{
+ g_assert_not_reached ();
+ return NULL;
+}
+#endif /* DISABLE_JIT */
+
+#if !MONO_SUPPORT_TASKLETS || defined(DISABLE_JIT)
+MonoContinuationRestore
+mono_tasklets_arch_restore (void)
+{
+ g_assert_not_reached ();
+ return NULL;
+}
+#endif /* !MONO_SUPPORT_TASKLETS || defined(DISABLE_JIT) */
c.throw_catch_t ();
return 0;
}
-
}
#if !__MOBILE__
bool success = zz == 0xAAAAAAAAAAAAAAAA;
return success ? 20 : 1;
}
+
+ void gsharedvt_try_at_offset_0<T> (ref T disposable)
+ where T : class, IDisposable {
+ try {
+ disposable.Dispose ();
+ } finally {
+ disposable = null;
+ }
+ }
}
// #13191
/* we use a separate basic block for the initialization code */
NEW_BBLOCK (cfg, init_localsbb);
- cfg->bb_init = init_localsbb;
+ if (cfg->method == method)
+ cfg->bb_init = init_localsbb;
init_localsbb->real_offset = cfg->real_offset;
start_bblock->next_bb = init_localsbb;
init_localsbb->next_bb = cfg->cbb;
if (cfg->method == method) {
MonoBasicBlock *bb;
for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
- bb->region = mono_find_block_region (cfg, bb->real_offset);
+ if (bb == cfg->bb_init)
+ bb->region = -1;
+ else
+ bb->region = mono_find_block_region (cfg, bb->real_offset);
if (cfg->spvars)
mono_create_spvar_for_region (cfg, bb->region);
if (cfg->verbose_level > 2)
#if defined (HAVE_BACKTRACE_SYMBOLS) && defined (TARGET_ARM)
MonoArray *res;
void *native_trace [MAX_UNMANAGED_BACKTRACE];
- int size = backtrace (native_trace, MAX_UNMANAGED_BACKTRACE);
+ int size = -1;
+ MONO_ENTER_GC_SAFE;
+ size = backtrace (native_trace, MAX_UNMANAGED_BACKTRACE);
+ MONO_EXIT_GC_SAFE;
int i;
if (!size)
static MonoExceptionClause *
get_most_deep_clause (MonoCompile *cfg, EmitContext *ctx, MonoBasicBlock *bb)
{
+ if (bb == cfg->bb_init)
+ return NULL;
// Since they're sorted by nesting we just need
// the first one that the bb is a member of
for (int i = 0; i < cfg->header->num_clauses; i++) {
--- /dev/null
+/*
+ * mini-windows-uwp.c: UWP profiler stat support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#include <config.h>
+#include <glib.h>
+
+#if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
+#include <Windows.h>
+
+void
+mono_runtime_setup_stat_profiler (void)
+{
+ g_unsupported_api ("OpenThread, GetThreadContext");
+ SetLastError (ERROR_NOT_SUPPORTED);
+ return;
+}
+
+void
+mono_runtime_shutdown_stat_profiler (void)
+{
+ g_unsupported_api ("OpenThread, GetThreadContext");
+ SetLastError (ERROR_NOT_SUPPORTED);
+ return;
+}
+
+static gboolean
+mono_setup_thread_context(DWORD thread_id, MonoContext *mono_context)
+{
+ memset (mono_context, 0, sizeof (MonoContext));
+ return FALSE;
+}
+
+#else /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_mini_windows_uwp_quiet_lnk4221(void) {}
+#endif
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
#include <mono/utils/dtrace.h>
#include "mini.h"
+#include "mini-windows.h"
#include <string.h>
#include <ctype.h>
#include "trace.h"
#include "jit-icalls.h"
-#ifdef _WIN32
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
#include <mmsystem.h>
#endif
return TRUE;
}
-static HANDLE win32_main_thread;
-static MMRESULT win32_timer;
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+static MMRESULT g_timer_event = 0;
+static HANDLE g_timer_main_thread = INVALID_HANDLE_VALUE;
-static void CALLBACK
-win32_time_proc (UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2)
+static VOID
+thread_timer_expired (HANDLE thread)
{
CONTEXT context;
context.ContextFlags = CONTEXT_CONTROL;
- if (GetThreadContext (win32_main_thread, &context)) {
+ if (GetThreadContext (thread, &context)) {
#ifdef _WIN64
mono_profiler_stat_hit ((guchar *) context.Rip, &context);
#else
}
}
-void
-mono_runtime_setup_stat_profiler (void)
+static VOID CALLBACK
+timer_event_proc (UINT uID, UINT uMsg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
{
- static int inited = 0;
- TIMECAPS timecaps;
+ thread_timer_expired ((HANDLE)dwUser);
+}
- if (inited)
- return;
+static VOID
+stop_profiler_timer_event (void)
+{
+ if (g_timer_event != 0) {
+
+ timeKillEvent (g_timer_event);
+ g_timer_event = 0;
+ }
+
+ if (g_timer_main_thread != INVALID_HANDLE_VALUE) {
+
+ CloseHandle (g_timer_main_thread);
+ g_timer_main_thread = INVALID_HANDLE_VALUE;
+ }
+}
+
+static VOID
+start_profiler_timer_event (void)
+{
+ g_return_if_fail (g_timer_main_thread == INVALID_HANDLE_VALUE && g_timer_event == 0);
+
+ TIMECAPS timecaps;
- inited = 1;
if (timeGetDevCaps (&timecaps, sizeof (timecaps)) != TIMERR_NOERROR)
return;
- if ((win32_main_thread = OpenThread (READ_CONTROL | THREAD_GET_CONTEXT, FALSE, GetCurrentThreadId ())) == NULL)
+ g_timer_main_thread = OpenThread (READ_CONTROL | THREAD_GET_CONTEXT, FALSE, GetCurrentThreadId ());
+ if (g_timer_main_thread == NULL)
return;
if (timeBeginPeriod (1) != TIMERR_NOERROR)
return;
- if ((win32_timer = timeSetEvent (1, 0, (LPTIMECALLBACK)win32_time_proc, (DWORD_PTR)NULL, TIME_PERIODIC)) == 0) {
+ g_timer_event = timeSetEvent (1, 0, (LPTIMECALLBACK)timer_event_proc, (DWORD_PTR)g_timer_main_thread, TIME_PERIODIC | TIME_KILL_SYNCHRONOUS);
+ if (g_timer_event == 0) {
timeEndPeriod (1);
return;
}
}
+void
+mono_runtime_setup_stat_profiler (void)
+{
+ start_profiler_timer_event ();
+ return;
+}
+
void
mono_runtime_shutdown_stat_profiler (void)
{
+ stop_profiler_timer_event ();
+ return;
}
gboolean
-mono_thread_state_init_from_handle (MonoThreadUnwindState *tctx, MonoThreadInfo *info)
+mono_setup_thread_context(DWORD thread_id, MonoContext *mono_context)
{
- DWORD id = mono_thread_info_get_tid (info);
HANDLE handle;
CONTEXT context;
- DWORD result;
- MonoContext *ctx;
- MonoJitTlsData *jit_tls;
- void *domain;
- MonoLMF *lmf = NULL;
- gpointer *addr;
-
- tctx->valid = FALSE;
- tctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] = NULL;
- tctx->unwind_data [MONO_UNWIND_DATA_LMF] = NULL;
- tctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = NULL;
- g_assert (id != GetCurrentThreadId ());
+ g_assert (thread_id != GetCurrentThreadId ());
- handle = OpenThread (THREAD_ALL_ACCESS, FALSE, id);
+ handle = OpenThread (THREAD_ALL_ACCESS, FALSE, thread_id);
g_assert (handle);
context.ContextFlags = CONTEXT_INTEGER | CONTEXT_CONTROL;
g_assert (context.ContextFlags & CONTEXT_INTEGER);
g_assert (context.ContextFlags & CONTEXT_CONTROL);
- ctx = &tctx->ctx;
+ memset (mono_context, 0, sizeof (MonoContext));
+ mono_sigctx_to_monoctx (&context, mono_context);
- memset (ctx, 0, sizeof (MonoContext));
- mono_sigctx_to_monoctx (&context, ctx);
+ CloseHandle (handle);
+ return TRUE;
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+gboolean
+mono_thread_state_init_from_handle (MonoThreadUnwindState *tctx, MonoThreadInfo *info)
+{
+ DWORD id = mono_thread_info_get_tid (info);
+ MonoJitTlsData *jit_tls;
+ void *domain;
+ MonoLMF *lmf = NULL;
+ gpointer *addr;
+
+ tctx->valid = FALSE;
+ tctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] = NULL;
+ tctx->unwind_data [MONO_UNWIND_DATA_LMF] = NULL;
+ tctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = NULL;
+
+ mono_setup_thread_context(id, &tctx->ctx);
/* mono_set_jit_tls () sets this */
jit_tls = mono_thread_info_tls_get (info, TLS_KEY_JIT_TLS);
return TRUE;
}
-
--- /dev/null
+#ifndef __MONO_MINI_WINDOWS_H__
+#define __MONO_MINI_WINDOWS_H__
+
+#include <config.h>
+#include <glib.h>
+
+#ifdef HOST_WIN32
+#include "Windows.h"
+#include "mini.h"
+#include "mono/utils/mono-context.h"
+
+gboolean
+mono_setup_thread_context(DWORD thread_id, MonoContext *mono_context);
+#endif /* HOST_WIN32 */
+#endif /* __MONO_MINI_WINDOWS_H__ */
#define IS_REX(inst) (((inst) >= 0x40) && ((inst) <= 0x4f))
+#ifndef DISABLE_JIT
/*
* mono_arch_get_unbox_trampoline:
* @m: method pointer
return start;
}
+#endif /* !DISABLE_JIT */
#ifdef _WIN64
// Workaround lack of Valgrind support for 64-bit Windows
}
}
+#ifndef DISABLE_JIT
guint8*
mono_arch_create_llvm_native_thunk (MonoDomain *domain, guint8 *addr)
{
mono_profiler_code_buffer_new (thunk_start, thunk_code - thunk_start, MONO_PROFILER_CODE_BUFFER_HELPER, NULL);
return addr;
}
+#endif /* !DISABLE_JIT */
void
mono_arch_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
InterlockedExchangePointer (plt_jump_table_entry, addr);
}
+#ifndef DISABLE_JIT
static void
stack_unaligned (MonoTrampolineType tramp_type)
{
x86_push_imm (code, (guint64)func_arg);
amd64_call_reg (code, AMD64_R11);
}
+#endif /* !DISABLE_JIT */
gpointer
mono_amd64_handler_block_trampoline_helper (void)
return jit_tls->handler_block_return_address;
}
+#ifndef DISABLE_JIT
gpointer
mono_arch_create_handler_block_trampoline (MonoTrampInfo **info, gboolean aot)
{
return buf;
}
+#endif /* !DISABLE_JIT */
/*
* mono_arch_get_call_target:
return *(guint32*)(plt_entry + 6);
}
+#ifndef DISABLE_JIT
/*
* mono_arch_create_sdb_trampoline:
*
return buf;
}
+#endif /* !DISABLE_JIT */
+
+#ifdef DISABLE_JIT
+gpointer
+mono_arch_get_unbox_trampoline (MonoMethod *m, gpointer addr)
+{
+ g_assert_not_reached ();
+ return NULL;
+}
+
+gpointer
+mono_arch_get_static_rgctx_trampoline (MonoMethod *m, MonoMethodRuntimeGenericContext *mrgctx, gpointer addr)
+{
+ g_assert_not_reached ();
+ return NULL;
+}
+
+gpointer
+mono_arch_create_rgctx_lazy_fetch_trampoline (guint32 slot, MonoTrampInfo **info, gboolean aot)
+{
+ g_assert_not_reached ();
+ return NULL;
+}
+
+guchar*
+mono_arch_create_generic_trampoline (MonoTrampolineType tramp_type, MonoTrampInfo **info, gboolean aot)
+{
+ g_assert_not_reached ();
+ return NULL;
+}
+
+gpointer
+mono_arch_create_specific_trampoline (gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
+{
+ g_assert_not_reached ();
+ return NULL;
+}
+
+gpointer
+mono_arch_create_general_rgctx_lazy_fetch_trampoline (MonoTrampInfo **info, gboolean aot)
+{
+ g_assert_not_reached ();
+ return NULL;
+}
+
+gpointer
+mono_arch_create_handler_block_trampoline (MonoTrampInfo **info, gboolean aot)
+{
+ g_assert_not_reached ();
+ return NULL;
+}
+
+void
+mono_arch_invalidate_method (MonoJitInfo *ji, void *func, gpointer func_arg)
+{
+ g_assert_not_reached ();
+ return;
+}
+
+guint8*
+mono_arch_create_sdb_trampoline (gboolean single_step, MonoTrampInfo **info, gboolean aot)
+{
+ g_assert_not_reached ();
+ return NULL;
+}
+#endif /* DISABLE_JIT */
{
InterlockedWrite (&runtime_inited, 1);
- start_writer_thread (profiler);
- start_dumper_thread (profiler);
-
register_counter ("Sample events allocated", &sample_allocations_ctr);
register_counter ("Log buffers allocated", &buffer_allocations_ctr);
counters_init (profiler);
+ /*
+ * We must start the helper thread before the writer thread. This is
+ * because the helper thread sets up the command port which is written to
+ * the log header by the writer thread.
+ */
start_helper_thread (profiler);
+ start_writer_thread (profiler);
+ start_dumper_thread (profiler);
}
static MonoProfiler*
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;
static int pagesize = -1;
int size;
+ size_t aligned_slot_size = SGEN_ALIGN_UP_TO (slot_size, SIZEOF_VOID_P);
if (pagesize == -1)
pagesize = mono_pagesize ();
for (size = pagesize; size < LOCK_FREE_ALLOC_SB_MAX_SIZE; size <<= 1) {
- if (slot_size * 2 <= LOCK_FREE_ALLOC_SB_USABLE_SIZE (size))
+ if (aligned_slot_size * 2 <= LOCK_FREE_ALLOC_SB_USABLE_SIZE (size))
return size;
}
return LOCK_FREE_ALLOC_SB_MAX_SIZE;
* so that we do not get different block sizes for sizes that should go to the same one
*/
g_assert (allocator_sizes [index_for_size (max_size)] == max_size);
+ g_assert (block_size (max_size) == size);
+ if (size < LOCK_FREE_ALLOC_SB_MAX_SIZE)
+ g_assert (block_size (max_size + 1) == size << 1);
}
}
threadpool-exceptions7.cs # Needs AppDomains \
cross-domain.cs # Needs AppDomains \
generic-unloading.2.cs # Needs AppDomains \
+ namedmutex-destroy-race.cs # needs named Mutex \
thread6.cs # On MOBILE, ThreadAbortException doesn't have necessary field for this test
# Disabled until ?mcs is fixed
bug-29585.cs \
priority.cs \
abort-cctor.cs \
- namedmutex-destroy-race.cs \
thread-native-exit.cs
if INSTALL_MOBILE_STATIC
{
return s.array [0] + s.array [1] + s.array [2];
}
+
+LIBTEST_API int STDCALL
+mono_test_marshal_pointer_array (int *arr[])
+{
+ int i;
+
+ for (i = 0; i < 10; ++i) {
+ if (*arr [i] != -1)
+ return 1;
+ }
+ return 0;
+}
return mono_test_marshal_fixed_array (s);
}
+
+ [DllImport ("libtest", EntryPoint="mono_test_marshal_pointer_array")]
+ public static extern int mono_test_marshal_pointer_array (int*[] arr);
+
+ public static unsafe int test_0_pointer_array () {
+ var arr = new int [10];
+ for (int i = 0; i < arr.Length; i++)
+ arr [i] = -1;
+ var arr2 = new int*[10];
+ for (int i = 0; i < arr2.Length; i++) {
+ GCHandle handle = GCHandle.Alloc(arr[i], GCHandleType.Pinned);
+ fixed (int *ptr = &arr[i]) {
+ arr2[i] = ptr;
+ }
+ }
+ return mono_test_marshal_pointer_array (arr2);
+ }
}
mono-dl-darwin.c \
mono-dl-posix.c \
mono-dl.h \
+ mono-dl-windows.h \
mono-log-windows.c \
mono-log-common.c \
mono-log-posix.c \
mono-filemap.c \
mono-math.c \
mono-mmap.c \
+ mono-mmap-windows.c \
mono-mmap.h \
mono-mmap-internals.h \
+ mono-mmap-windows.h \
mono-os-mutex.h \
mono-coop-mutex.h \
mono-once.h \
mono-networkinterfaces.c \
mono-networkinterfaces.h \
mono-proclib.c \
+ mono-proclib-windows.c \
mono-proclib.h \
+ mono-proclib-windows.h \
mono-publib.c \
mono-string.h \
mono-time.c \
networking-windows.c \
networking.h \
mono-rand.c \
+ mono-rand-windows.c \
mono-rand.h \
+ mono-rand-windows.h \
memfuncs.c \
memfuncs.h \
parse.c \
return(old);
}
+#endif
#endif
+#if defined(HOST_WIN32) && defined(_MSC_VER)
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_atomic_lnk4221(void) {}
#endif
#include <direct.h>
#define mkdir(x) _mkdir(x)
-/* GCC specific functions aren't available */
-#define __builtin_return_address(x) NULL
-
#define __func__ __FUNCTION__
#include <BaseTsd.h>
--- /dev/null
+/*
+ * mono-dl-windows-uwp.c: UWP dl support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+
+#if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
+#include <Windows.h>
+#include "mono/utils/mono-dl-windows.h"
+
+void*
+mono_dl_lookup_symbol_in_process (const char *symbol_name)
+{
+ g_unsupported_api ("EnumProcessModules");
+ SetLastError (ERROR_NOT_SUPPORTED);
+
+ return NULL;
+}
+
+char*
+mono_dl_current_error_string (void)
+{
+ char *ret = NULL;
+ TCHAR buf [1024];
+ DWORD code = GetLastError ();
+
+ if (!FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
+ code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, G_N_ELEMENTS(buf) - 1, NULL))
+ buf[0] = TEXT('\0');
+
+ ret = u16to8 (buf);
+ return ret;
+}
+
+#else /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_mono_dl_windows_uwp_quiet_lnk4221(void) {}
+#endif
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
#if defined(HOST_WIN32)
#include "mono/utils/mono-dl.h"
+#include "mono/utils/mono-dl-windows.h"
#include "mono/utils/mono-embed.h"
#include "mono/utils/mono-path.h"
#include <windows.h>
#include <psapi.h>
-
const char*
mono_dl_get_so_prefix (void)
{
gpointer hModule = NULL;
if (file) {
gunichar2* file_utf16 = g_utf8_to_utf16 (file, strlen (file), NULL, NULL, NULL);
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
guint last_sem = SetErrorMode (SEM_FAILCRITICALERRORS);
+#endif
guint32 last_error = 0;
hModule = LoadLibrary (file_utf16);
if (!hModule)
last_error = GetLastError ();
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
SetErrorMode (last_sem);
+#endif
+
g_free (file_utf16);
if (!hModule)
FreeLibrary (module->handle);
}
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
void*
-mono_dl_lookup_symbol (MonoDl *module, const char *symbol_name)
+mono_dl_lookup_symbol_in_process (const char *symbol_name)
{
HMODULE *modules;
DWORD buffer_size = sizeof (HMODULE) * 1024;
DWORD needed, i;
gpointer proc = NULL;
- /* get the symbol directly from the specified module */
- if (!module->main_module)
- return GetProcAddress (module->handle, symbol_name);
-
- /* get the symbol from the main module */
- proc = GetProcAddress (module->handle, symbol_name);
- if (proc != NULL)
- return proc;
-
/* get the symbol from the loaded DLLs */
modules = (HMODULE *) g_malloc (buffer_size);
if (modules == NULL)
g_free (modules);
return NULL;
}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+void*
+mono_dl_lookup_symbol (MonoDl *module, const char *symbol_name)
+{
+ gpointer proc = NULL;
+
+ /* get the symbol directly from the specified module */
+ if (!module->main_module)
+ return GetProcAddress (module->handle, symbol_name);
+
+ /* get the symbol from the main module */
+ proc = GetProcAddress (module->handle, symbol_name);
+ if (proc != NULL)
+ return proc;
+
+ /* get the symbol from the loaded DLLs */
+ return mono_dl_lookup_symbol_in_process (symbol_name);
+}
int
mono_dl_convert_flags (int flags)
return 0;
}
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
char*
mono_dl_current_error_string (void)
{
}
return ret;
}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
int
mono_dl_get_executable_path (char *buf, int buflen)
{
return NULL;
}
-
#endif
--- /dev/null
+#ifndef __MONO_UTILS_DL_WINDOWS_H__
+#define __MONO_UTILS_DL_WINDOWS_H__
+
+#include <config.h>
+#include <glib.h>
+
+#ifdef HOST_WIN32
+#include "mono/utils/mono-dl.h"
+
+void*
+mono_dl_lookup_symbol_in_process (const char *symbol_name);
+#endif /* HOST_WIN32 */
+#endif /* __MONO_UTILS_DL_WINDOWS_H__ */
+
void *padding [3];
} MonoErrorInternal;
+/* Invariant: the error strings are allocated in the mempool of the given image */
+struct _MonoErrorBoxed {
+ MonoError error;
+ MonoImage *image;
+};
+
#define error_init(error) do { \
((MonoErrorInternal*)(error))->error_code = MONO_ERROR_NONE; \
((MonoErrorInternal*)(error))->flags = 0; \
void
mono_error_set_type_load_class (MonoError *error, MonoClass *klass, const char *msg_format, ...) MONO_ATTR_FORMAT_PRINTF(3,4);
+void
+mono_error_vset_type_load_class (MonoError *error, MonoClass *klass, const char *msg_format, va_list args);
+
void
mono_error_set_type_load_name (MonoError *error, const char *type_name, const char *assembly_name, const char *msg_format, ...) MONO_ATTR_FORMAT_PRINTF(4,5);
void
mono_error_move (MonoError *dest, MonoError *src);
+MonoErrorBoxed*
+mono_error_box (const MonoError *error, MonoImage *image);
+
+gboolean
+mono_error_set_from_boxed (MonoError *error, const MonoErrorBoxed *from);
+
+
#endif
return (error->error_code == MONO_ERROR_EXCEPTION_INSTANCE);
}
+static gboolean
+is_boxed (MonoErrorInternal *error)
+{
+ return ((error->flags & MONO_ERROR_MEMPOOL_BOXED) != 0);
+}
+
static void
mono_error_prepare (MonoErrorInternal *error)
{
/* Two cleanups in a row without an intervening init. */
g_assert (orig_error_code != MONO_ERROR_CLEANUP_CALLED_SENTINEL);
+ /* Mempool stored error shouldn't be cleaned up */
+ g_assert (!is_boxed (error));
/* Mark it as cleaned up. */
error->error_code = MONO_ERROR_CLEANUP_CALLED_SENTINEL;
void
mono_error_set_type_load_class (MonoError *oerror, MonoClass *klass, const char *msg_format, ...)
+{
+ va_list args;
+ va_start (args, msg_format);
+ mono_error_vset_type_load_class (oerror, klass, msg_format, args);
+ va_end (args);
+}
+
+void
+mono_error_vset_type_load_class (MonoError *oerror, MonoClass *klass, const char *msg_format, va_list args)
{
MonoErrorInternal *error = (MonoErrorInternal*)oerror;
mono_error_prepare (error);
error->error_code = MONO_ERROR_TYPE_LOAD;
mono_error_set_class (oerror, klass);
- set_error_message ();
+ set_error_messagev ();
}
/*
}
exception = mono_exception_from_name_two_strings_checked (mono_get_corlib (), "System", "TypeLoadException", type_name, assembly_name, error_out);
- if (exception)
+ if (exception && error->full_message != NULL && strcmp (error->full_message, ""))
set_message_on_exception (exception, error, error_out);
} else {
exception = mono_exception_from_name_msg (mono_defaults.corlib, "System", "TypeLoadException", error->full_message);
MonoError error;
MonoException *ex;
+ /* Mempool stored error shouldn't be cleaned up */
+ g_assert (!is_boxed ((MonoErrorInternal*)target_error));
+
if (mono_error_ok (target_error))
return NULL;
memcpy (dest, src, sizeof (MonoErrorInternal));
mono_error_init (src);
}
+
+/**
+ * mono_error_box:
+ * @ierror: The input error that will be boxed.
+ * @image: The mempool of this image will hold the boxed error.
+ *
+ * Creates a new boxed error in the given mempool from MonoError.
+ * It does not alter ierror, so you still have to clean it up with
+ * mono_error_cleanup or mono_error_convert_to_exception or another such function.
+ *
+ * Returns the boxed error, or NULL if the mempool could not allocate.
+ */
+MonoErrorBoxed*
+mono_error_box (const MonoError *ierror, MonoImage *image)
+{
+ MonoErrorInternal *from = (MonoErrorInternal*)ierror;
+ /* Don't know how to box a gchandle */
+ g_assert (!is_managed_exception (from));
+ MonoErrorBoxed* box = mono_image_alloc (image, sizeof (MonoErrorBoxed));
+ box->image = image;
+ mono_error_init_flags (&box->error, MONO_ERROR_MEMPOOL_BOXED);
+ MonoErrorInternal *to = (MonoErrorInternal*)&box->error;
+
+#define DUP_STR(field) do { \
+ if (from->field) { \
+ if (!(to->field = mono_image_strdup (image, from->field))) \
+ to->flags |= MONO_ERROR_INCOMPLETE; \
+ } else { \
+ to->field = NULL; \
+ } \
+ } while (0)
+
+ to->error_code = from->error_code;
+ DUP_STR (type_name);
+ DUP_STR (assembly_name);
+ DUP_STR (member_name);
+ DUP_STR (exception_name_space);
+ DUP_STR (exception_name);
+ DUP_STR (full_message);
+ DUP_STR (full_message_with_fields);
+ DUP_STR (first_argument);
+ to->exn.klass = from->exn.klass;
+
+#undef DUP_STR
+
+ return box;
+}
+
+
+/**
+ * mono_error_set_from_boxed:
+ * @oerror: The error that will be set to the contents of the box.
+ * @box: A mempool-allocated error.
+ *
+ * Sets the error condition in the oerror from the contents of the
+ * given boxed error. Does not alter the boxed error, so it can be
+ * used in a future call to mono_error_set_from_boxed as needed. The
+ * oerror should've been previously initialized with mono_error_init,
+ * as usual.
+ *
+ * Returns TRUE on success or FALSE on failure.
+ */
+gboolean
+mono_error_set_from_boxed (MonoError *oerror, const MonoErrorBoxed *box)
+{
+ MonoErrorInternal* to = (MonoErrorInternal*)oerror;
+ MonoErrorInternal* from = (MonoErrorInternal*)&box->error;
+ g_assert (!is_managed_exception (from));
+
+ mono_error_prepare (to);
+ to->flags |= MONO_ERROR_FREE_STRINGS;
+#define DUP_STR(field) do { \
+ if (from->field) { \
+ if (!(to->field = g_strdup (from->field))) \
+ to->flags |= MONO_ERROR_INCOMPLETE; \
+ } else { \
+ to->field = NULL; \
+ } \
+ } while (0)
+
+ to->error_code = from->error_code;
+ DUP_STR (type_name);
+ DUP_STR (assembly_name);
+ DUP_STR (member_name);
+ DUP_STR (exception_name_space);
+ DUP_STR (exception_name);
+ DUP_STR (full_message);
+ DUP_STR (full_message_with_fields);
+ DUP_STR (first_argument);
+ to->exn.klass = from->exn.klass;
+
+#undef DUP_STR
+ return (to->flags & MONO_ERROR_INCOMPLETE) == 0 ;
+}
/*
Something happened while processing the error and the resulting message is incomplete.
*/
- MONO_ERROR_INCOMPLETE = 0x0002
+ MONO_ERROR_INCOMPLETE = 0x0002,
+ /*
+ This MonoError is heap allocated in a mempool
+ */
+ MONO_ERROR_MEMPOOL_BOXED = 0x0004
};
enum {
void *hidden_1 [12]; /*DON'T TOUCH */
} MonoError;
+/* Mempool-allocated MonoError.*/
+typedef struct _MonoErrorBoxed MonoErrorBoxed;
+
MONO_BEGIN_DECLS
MONO_API void
g_free (new_pathname);
return(NULL);
}
+
+#else /* DISABLE_PORTABILITY */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_mono_io_portability_quiet_lnk4221(void) {}
#endif
+#endif /* DISABLE_PORTABILITY */
#include <process.h>
#endif
#include "mono-logger-internals.h"
+#include "mono-proclib.h"
static FILE *logFile = NULL;
static void *logUserData = NULL;
struct tm *tod;
time(&t);
tod = localtime(&t);
- pid = _getpid();
+ pid = mono_process_current_pid ();
strftime(logTime, sizeof(logTime), "%F %T", tod);
#endif
fprintf (logFile, "%s level[%c] mono[%d]: %s\n", logTime, mapLogFileLevel (level), pid, message);
#include <time.h>
#include <process.h>
#include "mono-logger-internals.h"
+#include "mono-proclib.h"
static FILE *logFile = NULL;
static void *logUserData = NULL;
mono_log_write_syslog(const char *domain, GLogLevelFlags level, mono_bool hdr, const char *message)
{
time_t t;
- pid_t pid;
+ int pid;
char logTime [80];
if (logFile == NULL)
struct tm *tod;
time(&t);
tod = localtime(&t);
- pid = _getpid();
+ pid = mono_process_current_pid ();
strftime(logTime, sizeof(logTime), "%F %T", tod);
fprintf (logFile, "%s level[%c] mono[%d]: %s\n", logTime, mapLogFileLevel (level), pid, message);
continue;
}
for (i = 0; valid_flags[i]; i++) {
- int len = strlen (valid_flags[i]);
+ size_t len = strlen (valid_flags[i]);
if (strncmp (tok, valid_flags[i], len) == 0 && (tok[len] == 0 || tok[len] == ',')) {
flags |= valid_masks[i];
tok += len;
#include "mono-compiler.h"
-int mono_pages_not_faulted (void *addr, size_t length);
+void *
+malloc_shared_area (int pid);
+
+char*
+aligned_address (char *mem, size_t size, size_t alignment);
+
+void
+account_mem (MonoMemAccountType type, ssize_t size);
+
+int
+mono_pages_not_faulted (void *addr, size_t length);
#endif /* __MONO_UTILS_MMAP_INTERNAL_H__ */
--- /dev/null
+/*
+ * mono-dl-windows-uwp.c: UWP dl support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+
+#if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
+#include <Windows.h>
+#include <mono/utils/mono-mmap-windows.h>
+
+void*
+mono_file_map (size_t length, int flags, int fd, guint64 offset, void **ret_handle)
+{
+ void *ptr;
+ int mflags = 0;
+ HANDLE file, mapping;
+ int prot = mono_mmap_win_prot_from_flags (flags);
+
+ mflags = FILE_MAP_READ;
+ if (flags & MONO_MMAP_WRITE)
+ mflags = FILE_MAP_COPY;
+
+ file = (HANDLE) _get_osfhandle (fd);
+ mapping = CreateFileMappingFromApp (file, NULL, prot, length, NULL);
+
+ if (mapping == NULL)
+ return NULL;
+
+ ptr = MapViewOfFileFromApp (mapping, mflags, offset, length);
+
+ if (ptr == NULL) {
+ CloseHandle (mapping);
+ return NULL;
+ }
+
+ *ret_handle = (void*)mapping;
+ return ptr;
+}
+
+int
+mono_file_unmap (void *addr, void *handle)
+{
+ UnmapViewOfFile (addr);
+ CloseHandle ((HANDLE)handle);
+ return 0;
+}
+
+#else /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_mono_mmap_windows_uwp_quiet_lnk4221(void) {}
+#endif
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
--- /dev/null
+/*
+ * mono-mmap-windows.c: Windows support for mapping code into the process address space
+ *
+ * Author:
+ * Mono Team (mono-list@lists.ximian.com)
+ *
+ * Copyright 2001-2008 Novell, Inc.
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+
+#include <config.h>
+#include <glib.h>
+
+#if defined(HOST_WIN32)
+#include <Windows.h>
+#include "mono/utils/mono-mmap-windows.h"
+#include <mono/utils/mono-counters.h>
+#include <io.h>
+
+static void *malloced_shared_area = NULL;
+
+int
+mono_pagesize (void)
+{
+ SYSTEM_INFO info;
+ static int saved_pagesize = 0;
+ if (saved_pagesize)
+ return saved_pagesize;
+ GetSystemInfo (&info);
+ saved_pagesize = info.dwAllocationGranularity;
+ return saved_pagesize;
+}
+
+int
+mono_mmap_win_prot_from_flags (int flags)
+{
+ int prot = flags & (MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
+ switch (prot) {
+ case 0: prot = PAGE_NOACCESS; break;
+ case MONO_MMAP_READ: prot = PAGE_READONLY; break;
+ case MONO_MMAP_READ|MONO_MMAP_EXEC: prot = PAGE_EXECUTE_READ; break;
+ case MONO_MMAP_READ|MONO_MMAP_WRITE: prot = PAGE_READWRITE; break;
+ case MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC: prot = PAGE_EXECUTE_READWRITE; break;
+ case MONO_MMAP_WRITE: prot = PAGE_READWRITE; break;
+ case MONO_MMAP_WRITE|MONO_MMAP_EXEC: prot = PAGE_EXECUTE_READWRITE; break;
+ case MONO_MMAP_EXEC: prot = PAGE_EXECUTE; break;
+ default:
+ g_assert_not_reached ();
+ }
+ return prot;
+}
+
+void*
+mono_valloc (void *addr, size_t length, int flags, MonoMemAccountType type)
+{
+ void *ptr;
+ int mflags = MEM_RESERVE|MEM_COMMIT;
+ int prot = mono_mmap_win_prot_from_flags (flags);
+ /* translate the flags */
+
+ ptr = VirtualAlloc (addr, length, mflags, prot);
+
+ account_mem (type, (ssize_t)length);
+
+ return ptr;
+}
+
+void*
+mono_valloc_aligned (size_t length, size_t alignment, int flags, MonoMemAccountType type)
+{
+ int prot = mono_mmap_win_prot_from_flags (flags);
+ char *mem = VirtualAlloc (NULL, length + alignment, MEM_RESERVE, prot);
+ char *aligned;
+
+ if (!mem)
+ return NULL;
+
+ aligned = aligned_address (mem, length, alignment);
+
+ aligned = VirtualAlloc (aligned, length, MEM_COMMIT, prot);
+ g_assert (aligned);
+
+ account_mem (type, (ssize_t)length);
+
+ return aligned;
+}
+
+int
+mono_vfree (void *addr, size_t length, MonoMemAccountType type)
+{
+ MEMORY_BASIC_INFORMATION mbi;
+ SIZE_T query_result = VirtualQuery (addr, &mbi, sizeof (mbi));
+ BOOL res;
+
+ g_assert (query_result);
+
+ res = VirtualFree (mbi.AllocationBase, 0, MEM_RELEASE);
+
+ g_assert (res);
+
+ account_mem (type, -(ssize_t)length);
+
+ return 0;
+}
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+void*
+mono_file_map (size_t length, int flags, int fd, guint64 offset, void **ret_handle)
+{
+ void *ptr;
+ int mflags = 0;
+ HANDLE file, mapping;
+ int prot = mono_mmap_win_prot_from_flags (flags);
+ /* translate the flags */
+ /*if (flags & MONO_MMAP_PRIVATE)
+ mflags |= MAP_PRIVATE;
+ if (flags & MONO_MMAP_SHARED)
+ mflags |= MAP_SHARED;
+ if (flags & MONO_MMAP_ANON)
+ mflags |= MAP_ANONYMOUS;
+ if (flags & MONO_MMAP_FIXED)
+ mflags |= MAP_FIXED;
+ if (flags & MONO_MMAP_32BIT)
+ mflags |= MAP_32BIT;*/
+
+ mflags = FILE_MAP_READ;
+ if (flags & MONO_MMAP_WRITE)
+ mflags = FILE_MAP_COPY;
+
+ file = (HANDLE) _get_osfhandle (fd);
+
+ mapping = CreateFileMapping (file, NULL, prot, 0, 0, NULL);
+
+ if (mapping == NULL)
+ return NULL;
+
+ ptr = MapViewOfFile (mapping, mflags, 0, offset, length);
+
+ if (ptr == NULL) {
+ CloseHandle (mapping);
+ return NULL;
+ }
+ *ret_handle = (void*)mapping;
+ return ptr;
+}
+
+int
+mono_file_unmap (void *addr, void *handle)
+{
+ UnmapViewOfFile (addr);
+ CloseHandle ((HANDLE)handle);
+ return 0;
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+int
+mono_mprotect (void *addr, size_t length, int flags)
+{
+ DWORD oldprot;
+ int prot = mono_mmap_win_prot_from_flags (flags);
+
+ if (flags & MONO_MMAP_DISCARD) {
+ VirtualFree (addr, length, MEM_DECOMMIT);
+ VirtualAlloc (addr, length, MEM_COMMIT, prot);
+ return 0;
+ }
+ return VirtualProtect (addr, length, prot, &oldprot) == 0;
+}
+
+void*
+mono_shared_area (void)
+{
+ if (!malloced_shared_area)
+ malloced_shared_area = malloc_shared_area (0);
+ /* get the pid here */
+ return malloced_shared_area;
+}
+
+void
+mono_shared_area_remove (void)
+{
+ if (malloced_shared_area)
+ g_free (malloced_shared_area);
+ malloced_shared_area = NULL;
+}
+
+void*
+mono_shared_area_for_pid (void *pid)
+{
+ return NULL;
+}
+
+void
+mono_shared_area_unload (void *area)
+{
+}
+
+int
+mono_shared_area_instances (void **array, int count)
+{
+ return 0;
+}
+
+#endif
--- /dev/null
+#ifndef __MONO_UTILS_MMAP_WINDOWS_H__
+#define __MONO_UTILS_MMAP_WINDOWS_H__
+
+#include <config.h>
+#include <glib.h>
+
+#ifdef HOST_WIN32
+#include "mono/utils/mono-mmap.h"
+#include "mono/utils/mono-mmap-internals.h"
+
+int
+mono_mmap_win_prot_from_flags (int flags);
+#endif /* HOST_WIN32 */
+#endif /* __MONO_UTILS_MMAP_WINDOWS_H__ */
+
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
-#include "config.h"
+#include <config.h>
-#ifdef HOST_WIN32
-#include <windows.h>
-#include <io.h>
-#else
+#ifndef HOST_WIN32
#include <sys/types.h>
#if HAVE_SYS_STAT_H
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
-#endif
+#endif /* !HOST_WIN32 */
#include "mono-mmap.h"
#include "mono-mmap-internals.h"
#include <mono/utils/atomic.h>
#include <mono/utils/mono-counters.h>
-
#define BEGIN_CRITICAL_SECTION do { \
MonoThreadInfo *__info = mono_thread_info_current_unchecked (); \
if (__info) __info->inside_critical_region = TRUE; \
short stats_end;
} SAreaHeader;
-static void* malloced_shared_area = NULL;
-
-static void*
+void*
malloc_shared_area (int pid)
{
int size = mono_pagesize ();
return sarea;
}
-static char*
+char*
aligned_address (char *mem, size_t size, size_t alignment)
{
char *aligned = (char*)((size_t)(mem + (alignment - 1)) & ~(alignment - 1));
static volatile size_t allocation_count [MONO_MEM_ACCOUNT_MAX];
-static void
+void
account_mem (MonoMemAccountType type, ssize_t size)
{
#if SIZEOF_VOID_P == 4
}
#ifdef HOST_WIN32
-
-int
-mono_pagesize (void)
-{
- SYSTEM_INFO info;
- static int saved_pagesize = 0;
- if (saved_pagesize)
- return saved_pagesize;
- GetSystemInfo (&info);
- saved_pagesize = info.dwAllocationGranularity;
- return saved_pagesize;
-}
-
-static int
-prot_from_flags (int flags)
-{
- int prot = flags & (MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
- switch (prot) {
- case 0: prot = PAGE_NOACCESS; break;
- case MONO_MMAP_READ: prot = PAGE_READONLY; break;
- case MONO_MMAP_READ|MONO_MMAP_EXEC: prot = PAGE_EXECUTE_READ; break;
- case MONO_MMAP_READ|MONO_MMAP_WRITE: prot = PAGE_READWRITE; break;
- case MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC: prot = PAGE_EXECUTE_READWRITE; break;
- case MONO_MMAP_WRITE: prot = PAGE_READWRITE; break;
- case MONO_MMAP_WRITE|MONO_MMAP_EXEC: prot = PAGE_EXECUTE_READWRITE; break;
- case MONO_MMAP_EXEC: prot = PAGE_EXECUTE; break;
- default:
- g_assert_not_reached ();
- }
- return prot;
-}
-
-void*
-mono_valloc (void *addr, size_t length, int flags, MonoMemAccountType type)
-{
- void *ptr;
- int mflags = MEM_RESERVE|MEM_COMMIT;
- int prot = prot_from_flags (flags);
- /* translate the flags */
-
- ptr = VirtualAlloc (addr, length, mflags, prot);
-
- account_mem (type, (ssize_t)length);
-
- return ptr;
-}
-
-void*
-mono_valloc_aligned (size_t length, size_t alignment, int flags, MonoMemAccountType type)
-{
- int prot = prot_from_flags (flags);
- char *mem = VirtualAlloc (NULL, length + alignment, MEM_RESERVE, prot);
- char *aligned;
-
- if (!mem)
- return NULL;
-
- aligned = aligned_address (mem, length, alignment);
-
- aligned = VirtualAlloc (aligned, length, MEM_COMMIT, prot);
- g_assert (aligned);
-
- account_mem (type, (ssize_t)length);
-
- return aligned;
-}
-
+// Windows specific implementation in mono-mmap-windows.c
#define HAVE_VALLOC_ALIGNED
-int
-mono_vfree (void *addr, size_t length, MonoMemAccountType type)
-{
- MEMORY_BASIC_INFORMATION mbi;
- SIZE_T query_result = VirtualQuery (addr, &mbi, sizeof (mbi));
- BOOL res;
-
- g_assert (query_result);
-
- res = VirtualFree (mbi.AllocationBase, 0, MEM_RELEASE);
-
- g_assert (res);
-
- account_mem (type, -(ssize_t)length);
-
- return 0;
-}
-
-void*
-mono_file_map (size_t length, int flags, int fd, guint64 offset, void **ret_handle)
-{
- void *ptr;
- int mflags = 0;
- HANDLE file, mapping;
- int prot = prot_from_flags (flags);
- /* translate the flags */
- /*if (flags & MONO_MMAP_PRIVATE)
- mflags |= MAP_PRIVATE;
- if (flags & MONO_MMAP_SHARED)
- mflags |= MAP_SHARED;
- if (flags & MONO_MMAP_ANON)
- mflags |= MAP_ANONYMOUS;
- if (flags & MONO_MMAP_FIXED)
- mflags |= MAP_FIXED;
- if (flags & MONO_MMAP_32BIT)
- mflags |= MAP_32BIT;*/
-
- mflags = FILE_MAP_READ;
- if (flags & MONO_MMAP_WRITE)
- mflags = FILE_MAP_COPY;
-
- file = (HANDLE) _get_osfhandle (fd);
- mapping = CreateFileMapping (file, NULL, prot, 0, 0, NULL);
- if (mapping == NULL)
- return NULL;
- ptr = MapViewOfFile (mapping, mflags, 0, offset, length);
- if (ptr == NULL) {
- CloseHandle (mapping);
- return NULL;
- }
- *ret_handle = (void*)mapping;
- return ptr;
-}
-
-int
-mono_file_unmap (void *addr, void *handle)
-{
- UnmapViewOfFile (addr);
- CloseHandle ((HANDLE)handle);
- return 0;
-}
-
-int
-mono_mprotect (void *addr, size_t length, int flags)
-{
- DWORD oldprot;
- int prot = prot_from_flags (flags);
-
- if (flags & MONO_MMAP_DISCARD) {
- VirtualFree (addr, length, MEM_DECOMMIT);
- VirtualAlloc (addr, length, MEM_COMMIT, prot);
- return 0;
- }
- return VirtualProtect (addr, length, prot, &oldprot) == 0;
-}
-
-void*
-mono_shared_area (void)
-{
- if (!malloced_shared_area)
- malloced_shared_area = malloc_shared_area (0);
- /* get the pid here */
- return malloced_shared_area;
-}
-
-void
-mono_shared_area_remove (void)
-{
- if (malloced_shared_area)
- g_free (malloced_shared_area);
- malloced_shared_area = NULL;
-}
-
-void*
-mono_shared_area_for_pid (void *pid)
-{
- return NULL;
-}
-
-void
-mono_shared_area_unload (void *area)
-{
-}
-
-int
-mono_shared_area_instances (void **array, int count)
-{
- return 0;
-}
-
#else
+
+static void* malloced_shared_area = NULL;
#if defined(HAVE_MMAP)
/**
--- /dev/null
+/*
+ * mono-proclib-windows-uwp.c: UWP proclib support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+
+#if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
+#include <Windows.h>
+#include <mono/utils/mono-proclib.h>
+
+gint32
+mono_cpu_usage (MonoCpuUsageState *prev)
+{
+ gint32 cpu_usage = 0;
+ gint64 cpu_total_time;
+ gint64 cpu_busy_time;
+ guint64 idle_time;
+ guint64 kernel_time;
+ guint64 user_time;
+ guint64 current_time;
+ guint64 creation_time;
+ guint64 exit_time;
+
+ GetSystemTimeAsFileTime ((FILETIME*)¤t_time);
+ if (!GetProcessTimes (GetCurrentProcess (), (FILETIME*)&creation_time, (FILETIME*)&exit_time, (FILETIME*)&kernel_time, (FILETIME*)&user_time)) {
+ g_error ("GetProcessTimes() failed, error code is %d\n", GetLastError ());
+ return -1;
+ }
+
+ // GetProcessTimes user_time is a sum of user time spend by all threads in the process.
+ // This means that the total user time can be more than real time. In order to adjust for this
+ // the total available time that we can be scheduled depends on the number of available cores.
+ // For example, having 2 threads running 100% on a 2 core system for 100 ms will return a user_time of 200ms
+ // but the current_time - creation_time will only be 100ms but by adjusting the available time based on number of
+ // of availalbe cores will gives use the total load of the process.
+ guint64 total_available_time = (current_time - creation_time) * mono_cpu_count ();
+
+ idle_time = total_available_time - (kernel_time + user_time);
+
+ cpu_total_time = (gint64)((idle_time - (prev ? prev->idle_time : 0)) + (user_time - (prev ? prev->user_time : 0)) + (kernel_time - (prev ? prev->kernel_time : 0)));
+ cpu_busy_time = (gint64)(cpu_total_time - (idle_time - (prev ? prev->idle_time : 0)));
+
+ if (prev) {
+ prev->idle_time = idle_time;
+ prev->kernel_time = kernel_time;
+ prev->user_time = user_time;
+ }
+
+ if (cpu_total_time > 0 && cpu_busy_time > 0)
+ cpu_usage = (gint32)(cpu_busy_time * 100 / cpu_total_time);
+
+ return cpu_usage;
+}
+
+#else /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_mono_proclib_windows_uwp_quiet_lnk4221(void) {}
+#endif
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
--- /dev/null
+/*
+ * mono-proclib-windows.c: Windows proclib support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+
+#include <config.h>
+#include <glib.h>
+
+#ifdef HOST_WIN32
+#include <windows.h>
+#include "mono/utils/mono-proclib.h"
+
+int
+mono_process_current_pid ()
+{
+ return (int) GetCurrentProcessId ();
+}
+
+/**
+ * mono_cpu_count:
+ *
+ * Return the number of processors on the system.
+ */
+int
+mono_cpu_count (void)
+{
+ SYSTEM_INFO info;
+ GetSystemInfo (&info);
+ return info.dwNumberOfProcessors;
+}
+
+/*
+ * This function returns the cpu usage in percentage,
+ * normalized on the number of cores.
+ *
+ * Warning : the percentage returned can be > 100%. This
+ * might happens on systems like Android which, for
+ * battery and performance reasons, shut down cores and
+ * lie about the number of active cores.
+ */
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+gint32
+mono_cpu_usage (MonoCpuUsageState *prev)
+{
+ gint32 cpu_usage = 0;
+ gint64 cpu_total_time;
+ gint64 cpu_busy_time;
+ guint64 idle_time;
+ guint64 kernel_time;
+ guint64 user_time;
+
+ if (!GetSystemTimes ((FILETIME*) &idle_time, (FILETIME*) &kernel_time, (FILETIME*) &user_time)) {
+ g_error ("GetSystemTimes() failed, error code is %d\n", GetLastError ());
+ return -1;
+ }
+
+ cpu_total_time = (gint64)((user_time - (prev ? prev->user_time : 0)) + (kernel_time - (prev ? prev->kernel_time : 0)));
+ cpu_busy_time = (gint64)(cpu_total_time - (idle_time - (prev ? prev->idle_time : 0)));
+
+ if (prev) {
+ prev->idle_time = idle_time;
+ prev->kernel_time = kernel_time;
+ prev->user_time = user_time;
+ }
+
+ if (cpu_total_time > 0 && cpu_busy_time > 0)
+ cpu_usage = (gint32)(cpu_busy_time * 100 / cpu_total_time);
+
+ return cpu_usage;
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+#endif /* HOST_WIN32*/
--- /dev/null
+#ifndef __MONO_UTILS_PROCLIB_WINDOWS_H__
+#define __MONO_UTILS_PROCLIB_WINDOWS_H__
+
+#include <config.h>
+#include <glib.h>
+
+#ifdef HOST_WIN32
+#include <process.h>
+#include "mono/utils/mono-proclib.h"
+
+#endif /* HOST_WIN32 */
+#endif /* __MONO_UTILS_PROCLIB_WINDOWS_H__ */
+
#include <sched.h>
#endif
-#ifdef HOST_WIN32
-#include <windows.h>
-#include <process.h>
-#endif
-
#if defined(_POSIX_VERSION)
#include <sys/errno.h>
#include <sys/param.h>
char buf [256];
char *s;
FILE *f;
- int len = strlen (item);
+ size_t len = strlen (item);
g_snprintf (buf, sizeof (buf), "/proc/%d/status", pid);
f = fopen (buf, "r");
char fname [128];
FILE *file;
char *p;
- int r;
+ size_t r;
sprintf (fname, "/proc/%d/cmdline", GPOINTER_TO_INT (pid));
buf [0] = 0;
file = fopen (fname, "r");
char buf [512];
char *s, *end;
FILE *f;
- int len, i;
+ size_t len;
+ int i;
gint64 value;
g_snprintf (buf, sizeof (buf), "/proc/%d/stat", pid);
return mono_process_get_data_with_error (pid, data, &error);
}
+#ifndef HOST_WIN32
int
mono_process_current_pid ()
{
#if defined(HAVE_UNISTD_H)
return (int) getpid ();
-#elif defined(HOST_WIN32)
- return (int) GetCurrentProcessId ();
#else
#error getpid
#endif
}
+#endif /* !HOST_WIN32 */
/**
* mono_cpu_count:
*
* Return the number of processors on the system.
*/
+#ifndef HOST_WIN32
int
mono_cpu_count (void)
{
-#ifdef HOST_WIN32
- SYSTEM_INFO info;
- GetSystemInfo (&info);
- return info.dwNumberOfProcessors;
-#else
#ifdef PLATFORM_ANDROID
/* Android tries really hard to save power by powering off CPUs on SMP phones which
* means the normal way to query cpu count returns a wrong value with userspace API.
return count;
}
#endif
-#endif /* HOST_WIN32 */
/* FIXME: warn */
return 1;
}
+#endif /* !HOST_WIN32 */
static void
get_cpu_times (int cpu_id, gint64 *user, gint64 *systemt, gint64 *irq, gint64 *sirq, gint64 *idle)
* battery and performance reasons, shut down cores and
* lie about the number of active cores.
*/
+#ifndef HOST_WIN32
gint32
mono_cpu_usage (MonoCpuUsageState *prev)
{
gint32 cpu_usage = 0;
gint64 cpu_total_time;
gint64 cpu_busy_time;
-
-#ifndef HOST_WIN32
struct rusage resource_usage;
gint64 current_time;
gint64 kernel_time;
prev->user_time = user_time;
prev->current_time = current_time;
}
-#else
- guint64 idle_time;
- guint64 kernel_time;
- guint64 user_time;
-
- if (!GetSystemTimes ((FILETIME*) &idle_time, (FILETIME*) &kernel_time, (FILETIME*) &user_time)) {
- g_error ("GetSystemTimes() failed, error code is %d\n", GetLastError ());
- return -1;
- }
-
- cpu_total_time = (gint64)((user_time - (prev ? prev->user_time : 0)) + (kernel_time - (prev ? prev->kernel_time : 0)));
- cpu_busy_time = (gint64)(cpu_total_time - (idle_time - (prev ? prev->idle_time : 0)));
-
- if (prev) {
- prev->idle_time = idle_time;
- prev->kernel_time = kernel_time;
- prev->user_time = user_time;
- }
-#endif
if (cpu_total_time > 0 && cpu_busy_time > 0)
cpu_usage = (gint32)(cpu_busy_time * 100 / cpu_total_time);
return cpu_usage;
}
+#endif /* !HOST_WIN32 */
--- /dev/null
+/*
+ * mono-rand-windows-uwp.c: UWP rand support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+
+#if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
+#include <Windows.h>
+#include "mono/utils/mono-rand-windows.h"
+
+MONO_WIN32_CRYPT_PROVIDER_HANDLE
+mono_rand_win_open_provider (void)
+{
+ MONO_WIN32_CRYPT_PROVIDER_HANDLE provider = 0;
+
+ if (!BCRYPT_SUCCESS (BCryptOpenAlgorithmProvider (&provider, BCRYPT_RNG_ALGORITHM, NULL, 0)))
+ provider = 0;
+
+ return provider;
+}
+
+gboolean
+mono_rand_win_gen (MONO_WIN32_CRYPT_PROVIDER_HANDLE provider, guchar *buffer, size_t buffer_size)
+{
+ g_assert (provider != 0 && buffer != 0);
+ return (BCRYPT_SUCCESS (BCryptGenRandom (provider, buffer, (ULONG) buffer_size, 0))) ? TRUE : FALSE;
+}
+
+gboolean
+mono_rand_win_seed (MONO_WIN32_CRYPT_PROVIDER_HANDLE provider, guchar *seed, size_t seed_size)
+{
+ g_assert (provider != 0 && seed != 0);
+ return (BCRYPT_SUCCESS (BCryptGenRandom (provider, seed, (ULONG) seed_size, BCRYPT_RNG_USE_ENTROPY_IN_BUFFER))) ? TRUE : FALSE;
+}
+
+void
+mono_rand_win_close_provider (MONO_WIN32_CRYPT_PROVIDER_HANDLE provider)
+{
+ g_assert (provider != 0);
+ BCryptCloseAlgorithmProvider (provider, 0);
+}
+
+#else /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_mono_rand_windows_uwp_quiet_lnk4221(void) {}
+#endif
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
--- /dev/null
+/*
+ * mono-rand-windows.c: Windows rand support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+#include "mono-error.h"
+#include "mono-error-internals.h"
+#include "mono-rand.h"
+
+#if defined(HOST_WIN32)
+#include <windows.h>
+#include "mono/utils/mono-rand-windows.h"
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+#ifndef PROV_INTEL_SEC
+#define PROV_INTEL_SEC 22
+#endif
+#ifndef CRYPT_VERIFY_CONTEXT
+#define CRYPT_VERIFY_CONTEXT 0xF0000000
+#endif
+
+MONO_WIN32_CRYPT_PROVIDER_HANDLE
+mono_rand_win_open_provider (void)
+{
+ MONO_WIN32_CRYPT_PROVIDER_HANDLE provider = 0;
+
+ /* There is no need to create a container for just random data,
+ * so we can use CRYPT_VERIFY_CONTEXT (one call) see:
+ * http://blogs.msdn.com/dangriff/archive/2003/11/19/51709.aspx */
+
+ /* We first try to use the Intel PIII RNG if drivers are present */
+ if (!CryptAcquireContext (&provider, NULL, NULL, PROV_INTEL_SEC, CRYPT_VERIFY_CONTEXT)) {
+ /* not a PIII or no drivers available, use default RSA CSP */
+ if (!CryptAcquireContext (&provider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFY_CONTEXT)) {
+ /* exception will be thrown in managed code */
+ provider = 0;
+ }
+ }
+
+ return provider;
+}
+
+void
+mono_rand_win_close_provider (MONO_WIN32_CRYPT_PROVIDER_HANDLE provider)
+{
+ CryptReleaseContext (provider, 0);
+}
+
+gboolean
+mono_rand_win_gen (MONO_WIN32_CRYPT_PROVIDER_HANDLE provider, guchar *buffer, size_t buffer_size)
+{
+ return CryptGenRandom (provider, (DWORD) buffer_size, buffer);
+}
+
+gboolean
+mono_rand_win_seed (MONO_WIN32_CRYPT_PROVIDER_HANDLE provider, guchar *seed, size_t seed_size)
+{
+ /* add seeding material to the RNG */
+ return CryptGenRandom (provider, (DWORD) seed_size, seed);
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+/**
+ * mono_rand_open:
+ *
+ * Returns: True if random source is global, false if mono_rand_init can be called repeatedly to get randomness instances.
+ *
+ * Initializes entire RNG system. Must be called once per process before calling mono_rand_init.
+ */
+gboolean
+mono_rand_open (void)
+{
+ return FALSE;
+}
+
+/**
+ * mono_rand_init:
+ * @seed: A string containing seed data
+ * @seed_size: Length of seed string
+ *
+ * Returns: On success, a non-NULL handle which can be used to fetch random data from mono_rand_try_get_bytes. On failure, NULL.
+ *
+ * Initializes an RNG client.
+ */
+gpointer
+mono_rand_init (guchar *seed, gint seed_size)
+{
+ MONO_WIN32_CRYPT_PROVIDER_HANDLE provider = 0;
+
+ /* try to open crypto provider. */
+ provider = mono_rand_win_open_provider ();
+
+ /* seed the CSP with the supplied buffer (if present) */
+ if (provider != 0 && seed != NULL) {
+ /* the call we replace the seed with random - this isn't what is
+ * expected from the class library user */
+ guchar *data = g_malloc (seed_size);
+ if (data != NULL) {
+ memcpy (data, seed, seed_size);
+ /* add seeding material to the RNG */
+ mono_rand_win_seed (provider, data, seed_size);
+ /* zeroize and free */
+ memset (data, 0, seed_size);
+ g_free (data);
+ }
+ }
+
+ return (gpointer) provider;
+}
+
+/**
+ * mono_rand_try_get_bytes:
+ * @handle: A pointer to an RNG handle. Handle is set to NULL on failure.
+ * @buffer: A buffer into which to write random data.
+ * @buffer_size: Number of bytes to write into buffer.
+ * @error: Set on error.
+ *
+ * Returns: FALSE on failure and sets @error, TRUE on success.
+ *
+ * Extracts bytes from an RNG handle.
+ */
+gboolean
+mono_rand_try_get_bytes (gpointer *handle, guchar *buffer, gint buffer_size, MonoError *error)
+{
+ MONO_WIN32_CRYPT_PROVIDER_HANDLE provider;
+
+ mono_error_init (error);
+
+ g_assert (handle);
+ provider = (MONO_WIN32_CRYPT_PROVIDER_HANDLE) *handle;
+
+ /* generate random bytes */
+ if (!mono_rand_win_gen (provider, buffer, buffer_size)) {
+ mono_rand_win_close_provider (provider);
+ /* we may have lost our context with CryptoAPI, but all hope isn't lost yet! */
+ provider = mono_rand_win_open_provider ();
+ if (provider != 0) {
+
+ /* retry generate of random bytes */
+ if (!mono_rand_win_gen (provider, buffer, buffer_size)) {
+ /* failure, close provider */
+ mono_rand_win_close_provider (provider);
+ provider = 0;
+ }
+ }
+
+ /* make sure client gets new opened provider handle or NULL on failure */
+ *handle = (gpointer) provider;
+ if (*handle == 0) {
+ /* exception will be thrown in managed code */
+ mono_error_set_execution_engine (error, "Failed to gen random bytes (%d)", GetLastError ());
+ return FALSE;
+ }
+ }
+ return TRUE;
+}
+
+/**
+ * mono_rand_close:
+ * @handle: An RNG handle.
+ *
+ * Releases an RNG handle.
+ */
+void
+mono_rand_close (gpointer handle)
+{
+ mono_rand_win_close_provider ((MONO_WIN32_CRYPT_PROVIDER_HANDLE) handle);
+}
+#endif /* HOST_WIN32 */
--- /dev/null
+#ifndef _MONO_UTILS_RAND_WINDOWS_H_
+#define _MONO_UTILS_RAND_WINDOWS_H_
+
+#include <config.h>
+#include <glib.h>
+
+#ifdef HOST_WIN32
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+#include <wincrypt.h>
+#define MONO_WIN32_CRYPT_PROVIDER_HANDLE HCRYPTPROV
+
+#else
+
+#include <bcrypt.h>
+#define MONO_WIN32_CRYPT_PROVIDER_HANDLE BCRYPT_ALG_HANDLE
+#endif
+
+MONO_WIN32_CRYPT_PROVIDER_HANDLE
+mono_rand_win_open_provider (void);
+
+gboolean
+mono_rand_win_gen (MONO_WIN32_CRYPT_PROVIDER_HANDLE provider, guchar *buffer, size_t buffer_size);
+
+gboolean
+mono_rand_win_seed (MONO_WIN32_CRYPT_PROVIDER_HANDLE provider, guchar *seed, size_t seed_size);
+
+void
+mono_rand_win_close_provider (MONO_WIN32_CRYPT_PROVIDER_HANDLE provider);
+
+#endif /* HOST_WIN32 */
+#endif /* _MONO_UTILS_RAND_WINDOWS_H_ */
+
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
-
#include <glib.h>
#include <config.h>
#include "metadata/object.h"
#ifdef HOST_WIN32
-
-#include <windows.h>
-#include <wincrypt.h>
-
-#ifndef PROV_INTEL_SEC
-#define PROV_INTEL_SEC 22
-#endif
-#ifndef CRYPT_VERIFY_CONTEXT
-#define CRYPT_VERIFY_CONTEXT 0xF0000000
-#endif
-
-/**
- * mono_rand_open:
- *
- * Returns: True if random source is global, false if mono_rand_init can be called repeatedly to get randomness instances.
- *
- * Initializes entire RNG system. Must be called once per process before calling mono_rand_init.
- */
-gboolean
-mono_rand_open (void)
-{
- return FALSE;
-}
-
-/**
- * mono_rand_init:
- * @seed: A string containing seed data
- * @seed_size: Length of seed string
- *
- * Returns: On success, a non-NULL handle which can be used to fetch random data from mono_rand_try_get_bytes. On failure, NULL.
- *
- * Initializes an RNG client.
- */
-gpointer
-mono_rand_init (guchar *seed, gint seed_size)
-{
- HCRYPTPROV provider = 0;
-
- /* There is no need to create a container for just random data,
- * so we can use CRYPT_VERIFY_CONTEXT (one call) see:
- * http://blogs.msdn.com/dangriff/archive/2003/11/19/51709.aspx */
-
- /* We first try to use the Intel PIII RNG if drivers are present */
- if (!CryptAcquireContext (&provider, NULL, NULL, PROV_INTEL_SEC, CRYPT_VERIFY_CONTEXT)) {
- /* not a PIII or no drivers available, use default RSA CSP */
- if (!CryptAcquireContext (&provider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFY_CONTEXT)) {
- /* exception will be thrown in managed code */
- provider = 0;
- }
- }
-
- /* seed the CSP with the supplied buffer (if present) */
- if (provider != 0 && seed) {
- /* the call we replace the seed with random - this isn't what is
- * expected from the class library user */
- guchar *data = g_malloc (seed_size);
- if (data) {
- memcpy (data, seed, seed_size);
- /* add seeding material to the RNG */
- CryptGenRandom (provider, seed_size, data);
- /* zeroize and free */
- memset (data, 0, seed_size);
- g_free (data);
- }
- }
-
- return (gpointer) provider;
-}
-
-/**
- * mono_rand_try_get_bytes:
- * @handle: A pointer to an RNG handle. Handle is set to NULL on failure.
- * @buffer: A buffer into which to write random data.
- * @buffer_size: Number of bytes to write into buffer.
- * @error: Set on error.
- *
- * Returns: FALSE on failure and sets @error, TRUE on success.
- *
- * Extracts bytes from an RNG handle.
- */
-gboolean
-mono_rand_try_get_bytes (gpointer *handle, guchar *buffer, gint buffer_size, MonoError *error)
-{
- HCRYPTPROV provider;
-
- mono_error_init (error);
-
- g_assert (handle);
- provider = (HCRYPTPROV) *handle;
-
- if (!CryptGenRandom (provider, buffer_size, buffer)) {
- CryptReleaseContext (provider, 0);
- /* we may have lost our context with CryptoAPI, but all hope isn't lost yet! */
- provider = (HCRYPTPROV) mono_rand_init (NULL, 0);
- if (!CryptGenRandom (provider, buffer_size, buffer)) {
- /* exception will be thrown in managed code */
- CryptReleaseContext (provider, 0);
- *handle = 0;
- mono_error_set_execution_engine (error, "Failed to gen random bytes (%d)", GetLastError ());
- return FALSE;
- }
- }
- return TRUE;
-}
-
-/**
- * mono_rand_close:
- * @handle: An RNG handle.
- * @buffer: A buffer into which to write random data.
- * @buffer_size: Number of bytes to write into buffer.
- *
- * Releases an RNG handle.
- */
-void
-mono_rand_close (gpointer handle)
-{
- CryptReleaseContext ((HCRYPTPROV) handle, 0);
-}
-
+// Windows specific implementation in mono-rand-windows.c
#elif defined (HAVE_SYS_UN_H) && !defined(__native_client__)
#include <errno.h>
}
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)
static void CALLBACK
abort_apc (ULONG_PTR param)
{
+ THREADS_INTERRUPT_DEBUG ("%06d - abort_apc () called", GetCurrentThreadId ());
}
void
handle = OpenThread (THREAD_ALL_ACCESS, FALSE, id);
g_assert (handle);
+ THREADS_INTERRUPT_DEBUG ("%06d - Aborting syscall in thread %06d", GetCurrentThreadId (), id);
QueueUserAPC ((PAPCFUNC)abort_apc, handle, (ULONG_PTR)NULL);
CloseHandle (handle);
}
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);
return -1;
}
+#else /* !HAVE_INET_PTON */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_networking_missing_lnk4221(void) {}
+#endif
#endif /* !HAVE_INET_PTON */
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>\r
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>\r
</ClInclude>\r
+ <ClInclude Include="..\mono\mini\mini-windows.h" />\r
<ClInclude Include="..\mono\mini\mini-x86.h">\r
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>\r
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>\r
<ClInclude Include="..\mono\mini\mini-amd64-gsharedvt.h">\r
<Filter>Header Files</Filter>\r
</ClInclude>\r
+ <ClInclude Include="..\mono\mini\mini-windows.h">\r
+ <Filter>Header Files</Filter>\r
+ </ClInclude>\r
</ItemGroup>\r
<ItemGroup>\r
<Filter Include="Header Files">\r
<ClCompile Include="..\mono\metadata\class.c" />\r
<ClCompile Include="..\mono\metadata\cominterop.c" />\r
<ClCompile Include="..\mono\metadata\console-win32.c" />\r
+ <ClCompile Include="..\mono\metadata\socket-io-windows.c" />\r
<ClCompile Include="..\mono\metadata\w32mutex-win32.c" />\r
<ClCompile Include="..\mono\metadata\w32semaphore-win32.c" />\r
<ClCompile Include="..\mono\metadata\w32event-win32.c" />\r
<ClInclude Include="..\mono\metadata\seq-points-data.h" />\r
<ClInclude Include="..\mono\metadata\sgen-bridge-internals.h" />\r
<ClInclude Include="..\mono\metadata\sgen-client-mono.h" />\r
+ <ClInclude Include="..\mono\metadata\socket-io-windows-internals.h" />\r
<ClInclude Include="..\mono\metadata\threadpool-ms-io.h" />\r
<ClInclude Include="..\mono\metadata\threadpool-ms.h" />\r
<ClInclude Include="..\mono\sgen\gc-internal-agnostic.h" />\r
<ClCompile Include="..\mono\metadata\sgen-os-coop.c">\r
<Filter>Source Files\sgen</Filter>\r
</ClCompile>\r
+ <ClCompile Include="..\mono\metadata\socket-io-windows.c">\r
+ <Filter>Source Files</Filter>\r
+ </ClCompile>\r
</ItemGroup>\r
<ItemGroup>\r
<ClInclude Include="..\mono\metadata\appdomain.h">\r
<ClInclude Include="..\mono\metadata\sre-internals.h">\r
<Filter>Header Files</Filter>\r
</ClInclude>\r
+ <ClInclude Include="..\mono\metadata\socket-io-windows-internals.h">\r
+ <Filter>Header Files</Filter>\r
+ </ClInclude>\r
</ItemGroup>\r
<ItemGroup>\r
<Filter Include="Header Files">\r
<ClCompile Include="..\mono\utils\mono-log-common.c" />\r
<ClCompile Include="..\mono\utils\mono-math.c" />\r
<ClCompile Include="..\mono\utils\mono-md5.c" />\r
+ <ClCompile Include="..\mono\utils\mono-mmap-windows.c" />\r
<ClCompile Include="..\mono\utils\mono-mmap.c" />\r
<ClCompile Include="..\mono\utils\mono-networkinterfaces.c" />\r
+ <ClCompile Include="..\mono\utils\mono-proclib-windows.c" />\r
+ <ClCompile Include="..\mono\utils\mono-rand-windows.c" />\r
<ClCompile Include="..\mono\utils\mono-rand.c" />\r
<ClCompile Include="..\mono\utils\mono-threads-state-machine.c" />\r
<ClCompile Include="..\mono\utils\networking.c" />\r
<ClInclude Include="..\mono\utils\mono-counters.h" />\r
<ClInclude Include="..\mono\utils\mono-digest.h" />\r
<ClInclude Include="..\mono\utils\mono-dl-fallback.h" />\r
+ <ClInclude Include="..\mono\utils\mono-dl-windows.h" />\r
<ClInclude Include="..\mono\utils\mono-dl.h" />\r
<ClInclude Include="..\mono\utils\mono-error-internals.h" />\r
<ClInclude Include="..\mono\utils\mono-error.h" />\r
<ClInclude Include="..\mono\utils\mono-math.h" />\r
<ClInclude Include="..\mono\utils\mono-membar.h" />\r
<ClInclude Include="..\mono\utils\mono-memory-model.h" />\r
+ <ClInclude Include="..\mono\utils\mono-mmap-windows.h" />\r
<ClInclude Include="..\mono\utils\mono-mmap.h" />\r
<ClInclude Include="..\mono\utils\mono-networkinterfaces.h" />\r
<ClInclude Include="..\mono\utils\mono-once.h" />\r
<ClInclude Include="..\mono\utils\mono-os-semaphore.h" />\r
<ClInclude Include="..\mono\utils\mono-path.h" />\r
<ClInclude Include="..\mono\utils\mono-poll.h" />\r
+ <ClInclude Include="..\mono\utils\mono-proclib-windows.h" />\r
<ClInclude Include="..\mono\utils\mono-proclib.h" />\r
<ClInclude Include="..\mono\utils\mono-property-hash.h" />\r
<ClInclude Include="..\mono\utils\mono-publib.h" />\r
+ <ClInclude Include="..\mono\utils\mono-rand-windows.h" />\r
<ClInclude Include="..\mono\utils\mono-rand.h" />\r
<ClInclude Include="..\mono\utils\mono-sigcontext.h" />\r
<ClInclude Include="..\mono\utils\mono-stack-unwinding.h" />\r
<ImportGroup Label="ExtensionTargets">\r
<Import Project="$(VCTargetsPath)\BuildCustomizations\masm.targets" />\r
</ImportGroup>\r
-</Project>
+</Project>
\ No newline at end of file
<ClCompile Include="..\mono\utils\mono-log-windows.c">\r
<Filter>Source Files</Filter>\r
</ClCompile>\r
+ <ClCompile Include="..\mono\utils\mono-rand-windows.c">\r
+ <Filter>Source Files</Filter>\r
+ </ClCompile>\r
+ <ClCompile Include="..\mono\utils\mono-proclib-windows.c">\r
+ <Filter>Source Files</Filter>\r
+ </ClCompile>\r
+ <ClCompile Include="..\mono\utils\mono-mmap-windows.c">\r
+ <Filter>Source Files</Filter>\r
+ </ClCompile>\r
</ItemGroup>\r
<ItemGroup>\r
<ClInclude Include="..\mono\utils\atomic.h">\r
<ClInclude Include="..\mono\utils\valgrind.h">\r
<Filter>Header Files</Filter>\r
</ClInclude>\r
+ <ClInclude Include="..\mono\utils\mono-rand-windows.h">\r
+ <Filter>Header Files</Filter>\r
+ </ClInclude>\r
+ <ClInclude Include="..\mono\utils\mono-dl-windows.h">\r
+ <Filter>Header Files</Filter>\r
+ </ClInclude>\r
+ <ClInclude Include="..\mono\utils\mono-mmap-windows.h">\r
+ <Filter>Header Files</Filter>\r
+ </ClInclude>\r
+ <ClInclude Include="..\mono\utils\mono-proclib-windows.h">\r
+ <Filter>Header Files</Filter>\r
+ </ClInclude>\r
</ItemGroup>\r
<ItemGroup>\r
<Filter Include="Header Files">\r
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
update_submodules \
mcs.in \
dmcs.in \
+ mono-package-runtime \
mono-test-install \
mono-heapviz \
$(MDOC_COMPAT) \
${TESTCMD} --label=profiler --timeout=30m make -w -C mono/profiler -k check
${TESTCMD} --label=compiler --timeout=30m make -w -C mcs/tests run-test
${TESTCMD} --label=compiler-errors --timeout=30m make -w -C mcs/errors run-test
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=System --skip; else ${TESTCMD} --label=System --timeout=10m make -w -C mcs/class/System run-test; fi
+if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=System --skip; else ${TESTCMD} --label=System --timeout=10m bash -c "export MONO_TLS_PROVIDER=legacy && make -w -C mcs/class/System run-test"; fi
+if [[ ${label} == osx-* ]]; then ${TESTCMD} --label=System-btls --timeout=10m bash -c "export MONO_TLS_PROVIDER=btls && make -w -C mcs/class/System run-test"; fi
${TESTCMD} --label=System.XML --timeout=5m make -w -C mcs/class/System.XML run-test
${TESTCMD} --label=Mono.Security --timeout=5m make -w -C mcs/class/Mono.Security run-test
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=System.Security --skip; else ${TESTCMD} --label=System.Security --timeout=5m make -w -C mcs/class/System.Security run-test; fi
+${TESTCMD} --label=System.Security --timeout=5m make -w -C mcs/class/System.Security run-test
if [[ ${label} == w* ]]
then ${TESTCMD} --label=System.Drawing --skip;
else ${TESTCMD} --label=System.Drawing --timeout=5m make -w -C mcs/class/System.Drawing run-test
${TESTCMD} --label=System.Data.OracleClient --timeout=5m make -w -C mcs/class/System.Data.OracleClient run-test;
${TESTCMD} --label=System.Design --timeout=5m make -w -C mcs/class/System.Design run-test;
if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=Mono.Posix --skip; else ${TESTCMD} --label=Mono.Posix --timeout=5m make -w -C mcs/class/Mono.Posix run-test; fi
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=System.Web --skip; else ${TESTCMD} --label=System.Web --timeout=30m make -w -C mcs/class/System.Web run-test; fi
+${TESTCMD} --label=System.Web --timeout=30m make -w -C mcs/class/System.Web run-test
${TESTCMD} --label=System.Web.Services --timeout=5m make -w -C mcs/class/System.Web.Services run-test
${TESTCMD} --label=System.Runtime.SFS --timeout=5m make -w -C mcs/class/System.Runtime.Serialization.Formatters.Soap run-test;
if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=System.Runtime.Remoting --skip; else ${TESTCMD} --label=System.Runtime.Remoting --timeout=5m make -w -C mcs/class/System.Runtime.Remoting run-test; fi
${TESTCMD} --label=I18N.West --timeout=5m make -w -C mcs/class/I18N/West run-test
${TESTCMD} --label=I18N.MidEast --timeout=5m make -w -C mcs/class/I18N/MidEast run-test
${TESTCMD} --label=System.DirectoryServices --timeout=5m make -w -C mcs/class/System.DirectoryServices run-test
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=Microsoft.Build.Engine --skip; else ${TESTCMD} --label=Microsoft.Build.Engine --timeout=5m make -w -C mcs/class/Microsoft.Build.Engine run-test; fi
+${TESTCMD} --label=Microsoft.Build.Engine --timeout=5m make -w -C mcs/class/Microsoft.Build.Engine run-test
${TESTCMD} --label=Microsoft.Build.Framework --timeout=5m make -w -C mcs/class/Microsoft.Build.Framework run-test
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=Microsoft.Build.Tasks --skip; else ${TESTCMD} --label=Microsoft.Build.Tasks --timeout=5m make -w -C mcs/class/Microsoft.Build.Tasks run-test; fi
+${TESTCMD} --label=Microsoft.Build.Tasks --timeout=5m make -w -C mcs/class/Microsoft.Build.Tasks run-test
${TESTCMD} --label=Microsoft.Build.Utilities --timeout=5m make -w -C mcs/class/Microsoft.Build.Utilities run-test
${TESTCMD} --label=Mono.C5 --timeout=5m make -w -C mcs/class/Mono.C5 run-test
${TESTCMD} --label=Mono.Tasklets --timeout=5m make -w -C mcs/class/Mono.Tasklets run-test
${TESTCMD} --label=System.Configuration --timeout=5m make -w -C mcs/class/System.Configuration run-test
${TESTCMD} --label=System.Transactions --timeout=5m make -w -C mcs/class/System.Transactions run-test
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=System.Web.Extensions --skip; else ${TESTCMD} --label=System.Web.Extensions --timeout=5m make -w -C mcs/class/System.Web.Extensions run-test; fi
+${TESTCMD} --label=System.Web.Extensions --timeout=5m make -w -C mcs/class/System.Web.Extensions run-test
if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=System.Core --skip; else ${TESTCMD} --label=System.Core --timeout=15m make -w -C mcs/class/System.Core run-test; fi
if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=symbolicate --skip; else ${TESTCMD} --label=symbolicate --timeout=60m make -w -C mcs/tools/mono-symbolicate check; fi
${TESTCMD} --label=System.Xml.Linq --timeout=5m make -w -C mcs/class/System.Xml.Linq run-test
${TESTCMD} --label=Mono.CodeContracts --timeout=5m make -w -C mcs/class/Mono.CodeContracts run-test
${TESTCMD} --label=System.Runtime.Caching --timeout=5m make -w -C mcs/class/System.Runtime.Caching run-test
${TESTCMD} --label=System.Data.Services --timeout=5m make -w -C mcs/class/System.Data.Services run-test
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=System.Web.DynamicData --skip; else ${TESTCMD} --label=System.Web.DynamicData --timeout=5m make -w -C mcs/class/System.Web.DynamicData run-test; fi
+${TESTCMD} --label=System.Web.DynamicData --timeout=5m make -w -C mcs/class/System.Web.DynamicData run-test
${TESTCMD} --label=Mono.CSharp --timeout=5m make -w -C mcs/class/Mono.CSharp run-test
if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=WindowsBase --skip; else ${TESTCMD} --label=WindowsBase --timeout=5m make -w -C mcs/class/WindowsBase run-test; fi
${TESTCMD} --label=System.Numerics --timeout=5m make -w -C mcs/class/System.Numerics run-test
${TESTCMD} --label=System.Json --timeout=5m make -w -C mcs/class/System.Json run-test
${TESTCMD} --label=System.Threading.Tasks.Dataflow --timeout=5m make -w -C mcs/class/System.Threading.Tasks.Dataflow run-test
${TESTCMD} --label=Mono.Debugger.Soft --timeout=5m make -w -C mcs/class/Mono.Debugger.Soft run-test
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=Microsoft.Build --skip; else ${TESTCMD} --label=Microsoft.Build --timeout=5m make -w -C mcs/class/Microsoft.Build run-test; fi
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=monodoc --skip; else ${TESTCMD} --label=monodoc --timeout=10m make -w -C mcs/tools/mdoc run-test; fi
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=Microsoft.Build-12 --skip; else ${TESTCMD} --label=Microsoft.Build-12 --timeout=10m make -w -C mcs/class/Microsoft.Build run-test PROFILE=xbuild_12; fi
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=Microsoft.Build.Engine-12 --skip; else ${TESTCMD} --label=Microsoft.Build.Engine-12 --timeout=60m make -w -C mcs/class/Microsoft.Build.Engine run-test PROFILE=xbuild_12; fi
+${TESTCMD} --label=Microsoft.Build --timeout=5m make -w -C mcs/class/Microsoft.Build run-test
+${TESTCMD} --label=monodoc --timeout=10m make -w -C mcs/tools/mdoc run-test
+${TESTCMD} --label=Microsoft.Build-12 --timeout=10m make -w -C mcs/class/Microsoft.Build run-test PROFILE=xbuild_12
+${TESTCMD} --label=Microsoft.Build.Engine-12 --timeout=60m make -w -C mcs/class/Microsoft.Build.Engine run-test PROFILE=xbuild_12
${TESTCMD} --label=Microsoft.Build.Framework-12 --timeout=60m make -w -C mcs/class/Microsoft.Build.Framework run-test PROFILE=xbuild_12
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=Microsoft.Build.Tasks-12 --skip; else ${TESTCMD} --label=Microsoft.Build.Tasks-12 --timeout=60m make -w -C mcs/class/Microsoft.Build.Tasks run-test PROFILE=xbuild_12; fi
+${TESTCMD} --label=Microsoft.Build.Tasks-12 --timeout=60m make -w -C mcs/class/Microsoft.Build.Tasks run-test PROFILE=xbuild_12
${TESTCMD} --label=Microsoft.Build.Utilities-12 --timeout=60m make -w -C mcs/class/Microsoft.Build.Utilities run-test PROFILE=xbuild_12
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=Microsoft.Build-14 --skip; else ${TESTCMD} --label=Microsoft.Build-14 --timeout=60m make -w -C mcs/class/Microsoft.Build run-test PROFILE=xbuild_14; fi
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=Microsoft.Build.Engine-14 --skip; else ${TESTCMD} --label=Microsoft.Build.Engine-14 --timeout=60m make -w -C mcs/class/Microsoft.Build.Engine run-test PROFILE=xbuild_14; fi
+${TESTCMD} --label=Microsoft.Build-14 --timeout=60m make -w -C mcs/class/Microsoft.Build run-test PROFILE=xbuild_14
+${TESTCMD} --label=Microsoft.Build.Engine-14 --timeout=60m make -w -C mcs/class/Microsoft.Build.Engine run-test PROFILE=xbuild_14
${TESTCMD} --label=Microsoft.Build.Framework-14 --timeout=60m make -w -C mcs/class/Microsoft.Build.Framework run-test PROFILE=xbuild_14
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=Microsoft.Build.Tasks-14 --skip; else ${TESTCMD} --label=Microsoft.Build.Tasks-14 --timeout=60m make -w -C mcs/class/Microsoft.Build.Tasks run-test PROFILE=xbuild_14; fi
+${TESTCMD} --label=Microsoft.Build.Tasks-14 --timeout=60m make -w -C mcs/class/Microsoft.Build.Tasks run-test PROFILE=xbuild_14
${TESTCMD} --label=Microsoft.Build.Utilities-14 --timeout=60m make -w -C mcs/class/Microsoft.Build.Utilities run-test PROFILE=xbuild_14
if [[ ${label} == osx-* ]]
then ${TESTCMD} --label=ms-test-suite --timeout=15m make -w -C acceptance-tests check-ms-test-suite