Merge pull request #3591 from directhex/mono_libdir_fallback
authorBernhard Urban <bernhard.urban@xamarin.com>
Thu, 13 Oct 2016 14:39:38 +0000 (16:39 +0200)
committerGitHub <noreply@github.com>
Thu, 13 Oct 2016 14:39:38 +0000 (16:39 +0200)
Handle relocatable libMonoPosixHelper.so when --libdir= isn't lib/

776 files changed:
.gitmodules
README.md
acceptance-tests/profiler-stress.mk
acceptance-tests/profiler-stress/runner.cs
appveyor.yml [deleted file]
configure.ac
eglib/configure.ac
eglib/src/gfile-win32.c
eglib/src/glib.h
eglib/src/gmisc-win32.c
eglib/src/gmodule-win32.c
eglib/src/gunicode.c
eglib/test/driver.c
eglib/winconfig.h
external/boringssl [new submodule]
external/corefx [new submodule]
external/ikvm
man/mkbundle.1
man/mono.1
man/mprof-report.1
mcs/build/common/basic-profile-check.cs
mcs/build/profiles/basic.make
mcs/build/profiles/monotouch_watch.make
mcs/build/profiles/monotouch_watch_runtime.make
mcs/class/Facades/System.Reflection.Emit.Lightweight/DynamicMethod.cs
mcs/class/Facades/System.Reflection.Emit.Lightweight/TypeForwarders.cs
mcs/class/Facades/subdirs.make
mcs/class/Makefile
mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/PredefinedPropertyFunctionsTest.cs
mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/TargetTest.cs
mcs/class/Microsoft.Build.Engine/Test/various/Properties.cs
mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/Vbc.cs
mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/AssignTargetPathTest.cs
mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/CopyTest.cs
mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/WriteLinesToFileTest.cs
mcs/class/Microsoft.Build/Test/Microsoft.Build.Evaluation/ProjectItemTest.cs
mcs/class/Microsoft.Build/Test/Microsoft.Build.Execution/BuildSubmissionTest.cs
mcs/class/Microsoft.CSharp/Microsoft.CSharp.RuntimeBinder/DynamicContext.cs
mcs/class/Mono.Btls.Interface/Makefile [new file with mode: 0644]
mcs/class/Mono.Btls.Interface/Mono.Btls.Interface.dll.sources [new file with mode: 0644]
mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsObject.cs [new file with mode: 0644]
mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsProvider.cs [new file with mode: 0644]
mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509.cs [new file with mode: 0644]
mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509Chain.cs [new file with mode: 0644]
mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509Error.cs [new file with mode: 0644]
mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509Format.cs [new file with mode: 0644]
mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509Lookup.cs [new file with mode: 0644]
mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509Name.cs [new file with mode: 0644]
mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509Purpose.cs [new file with mode: 0644]
mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509Store.cs [new file with mode: 0644]
mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509StoreCtx.cs [new file with mode: 0644]
mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509StoreManager.cs [new file with mode: 0644]
mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509StoreType.cs [new file with mode: 0644]
mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509TrustKind.cs [new file with mode: 0644]
mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509VerifyFlags.cs [new file with mode: 0644]
mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509VerifyParam.cs [new file with mode: 0644]
mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/VersionInfo.cs [new file with mode: 0644]
mcs/class/Mono.Btls.Interface/Properties/AssemblyInfo.cs [new file with mode: 0644]
mcs/class/Mono.Btls.Interface/README.md [new file with mode: 0644]
mcs/class/Mono.Data.Sqlite/Mono.Data.Sqlite_2.0/SQLiteConvert.cs
mcs/class/Mono.Data.Sqlite/Mono.Data.Sqlite_test.dll.sources
mcs/class/Mono.Data.Sqlite/Test/Bug27864.cs
mcs/class/Mono.Data.Sqlite/Test/SqliteTests.cs [new file with mode: 0644]
mcs/class/Mono.Debugger.Soft/Makefile
mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/Connection.cs
mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/StackFrame.cs
mcs/class/Mono.Debugger.Soft/Test/TypeLoadClass.cs [new file with mode: 0644]
mcs/class/Mono.Debugger.Soft/Test/dtest-app.cs
mcs/class/Mono.Debugger.Soft/Test/dtest.cs
mcs/class/Mono.Security.Providers.DotNet/Makefile [deleted file]
mcs/class/Mono.Security.Providers.DotNet/Mono.Security.Providers.DotNet-net_4_x.csproj [deleted file]
mcs/class/Mono.Security.Providers.DotNet/Mono.Security.Providers.DotNet.dll.sources [deleted file]
mcs/class/Mono.Security.Providers.DotNet/Mono.Security.Providers.DotNet/DotNetSslStreamImpl.cs [deleted file]
mcs/class/Mono.Security.Providers.DotNet/Mono.Security.Providers.DotNet/DotNetTlsProvider.cs [deleted file]
mcs/class/Mono.Security.Providers.DotNet/Properties/AssemblyInfo.cs [deleted file]
mcs/class/Mono.Security.Providers.DotNet/README.md [deleted file]
mcs/class/Mono.Security.Providers.NewSystemSource/Makefile [deleted file]
mcs/class/Mono.Security.Providers.NewSystemSource/Mono.Security.Providers.NewSystemSource-net_4_x.csproj [deleted file]
mcs/class/Mono.Security.Providers.NewSystemSource/Mono.Security.Providers.NewSystemSource.dll.sources [deleted file]
mcs/class/Mono.Security.Providers.NewSystemSource/Properties/AssemblyInfo.cs [deleted file]
mcs/class/Mono.Security.Providers.NewSystemSource/README.md [deleted file]
mcs/class/Mono.Security.Providers.NewTls/Makefile [deleted file]
mcs/class/Mono.Security.Providers.NewTls/Mono.Security.Providers.NewTls-net_4_x.csproj [deleted file]
mcs/class/Mono.Security.Providers.NewTls/Mono.Security.Providers.NewTls.dll.sources [deleted file]
mcs/class/Mono.Security.Providers.NewTls/Mono.Security.Providers.NewTls/ITlsConfiguration.cs [deleted file]
mcs/class/Mono.Security.Providers.NewTls/Mono.Security.Providers.NewTls/ITlsContext.cs [deleted file]
mcs/class/Mono.Security.Providers.NewTls/Mono.Security.Providers.NewTls/MonoNewTlsStream.cs [deleted file]
mcs/class/Mono.Security.Providers.NewTls/Mono.Security.Providers.NewTls/MonoNewTlsStreamFactory.cs [deleted file]
mcs/class/Mono.Security.Providers.NewTls/Mono.Security.Providers.NewTls/NewTlsProvider.cs [deleted file]
mcs/class/Mono.Security.Providers.NewTls/Mono.Security.Providers.NewTls/TlsContextWrapper.cs [deleted file]
mcs/class/Mono.Security.Providers.NewTls/Mono.Security.Providers.NewTls/TlsProviderFactory.cs [deleted file]
mcs/class/Mono.Security.Providers.NewTls/Properties/AssemblyInfo.cs [deleted file]
mcs/class/Mono.Security.Providers.NewTls/mobile_Mono.Security.Providers.NewTls.dll.sources [deleted file]
mcs/class/Mono.Security.Providers.NewTls/mobile_static_Mono.Security.Providers.NewTls.dll.sources [deleted file]
mcs/class/Mono.Security.Providers.OldTls/Makefile [deleted file]
mcs/class/Mono.Security.Providers.OldTls/Mono.Security.Providers.OldTls-net_4_x.csproj [deleted file]
mcs/class/Mono.Security.Providers.OldTls/Mono.Security.Providers.OldTls.dll.sources [deleted file]
mcs/class/Mono.Security.Providers.OldTls/Mono.Security.Providers.OldTls/OldTlsProvider.cs [deleted file]
mcs/class/Mono.Security.Providers.OldTls/Properties/AssemblyInfo.cs [deleted file]
mcs/class/Mono.Security/Assembly/AssemblyInfo.cs
mcs/class/Mono.Security/Mono.Security-net_4_x.csproj
mcs/class/Mono.Security/Mono.Security.Interface/CertificateValidationHelper.cs
mcs/class/Mono.Security/Mono.Security.Interface/CipherSuiteCode.cs
mcs/class/Mono.Security/Mono.Security.Interface/IMonoTlsContext.cs [deleted file]
mcs/class/Mono.Security/Mono.Security.Interface/MonoTlsConnectionInfo.cs
mcs/class/Mono.Security/Mono.Security.Interface/MonoTlsProvider.cs
mcs/class/Mono.Security/Mono.Security.Interface/MonoTlsProviderFactory.cs
mcs/class/Mono.Security/Mono.Security.Interface/MonoTlsSettings.cs
mcs/class/Mono.Security/Mono.Security.X509/X509Store.cs
mcs/class/Mono.Security/Mono.Security.X509/X509StoreManager.cs
mcs/class/Mono.Security/Mono.Security.X509/X509Stores.cs
mcs/class/Mono.Security/Mono.Security.dll.sources
mcs/class/System.ComponentModel.Composition.4.5/Makefile
mcs/class/System.Configuration/net_4_x_System.Configuration_test.dll.config [changed from symlink to file mode: 0644]
mcs/class/System.Core/Microsoft.Win32.SafeHandles/SafeNCryptHandle.cs
mcs/class/System.Core/System.IO.MemoryMappedFiles/MemoryMappedFile.cs
mcs/class/System.Core/System.IO.Pipes/AnonymousPipeClientStream.cs
mcs/class/System.Core/System.IO.Pipes/AnonymousPipeServerStream.cs
mcs/class/System.Core/System.IO.Pipes/NamedPipeClientStream.cs
mcs/class/System.Core/System.IO.Pipes/NamedPipeServerStream.cs
mcs/class/System.Core/System.IO.Pipes/PipeStream.cs
mcs/class/System.Core/System.IO.Pipes/PipeUnix.cs
mcs/class/System.Core/System.Security.Cryptography/CngAlgorithm.cs [deleted file]
mcs/class/System.Core/System.Security.Cryptography/CngAlgorithmGroup.cs [deleted file]
mcs/class/System.Core/System.Security.Cryptography/CngExportPolicies.cs [deleted file]
mcs/class/System.Core/System.Security.Cryptography/CngKeyCreationOptions.cs [deleted file]
mcs/class/System.Core/System.Security.Cryptography/CngKeyCreationParameters.cs [deleted file]
mcs/class/System.Core/System.Security.Cryptography/CngKeyOpenOptions.cs [deleted file]
mcs/class/System.Core/System.Security.Cryptography/CngKeyUsages.cs [deleted file]
mcs/class/System.Core/System.Security.Cryptography/CngProperty.cs [deleted file]
mcs/class/System.Core/System.Security.Cryptography/CngPropertyCollection.cs [deleted file]
mcs/class/System.Core/System.Security.Cryptography/CngPropertyOptions.cs [deleted file]
mcs/class/System.Core/System.Security.Cryptography/CngProvider.cs [deleted file]
mcs/class/System.Core/System.Security.Cryptography/CngUIPolicy.cs [deleted file]
mcs/class/System.Core/System.Security.Cryptography/CngUIProtectionLevels.cs [deleted file]
mcs/class/System.Core/System.Security.Cryptography/ECDiffieHellmanKeyDerivationFunction.cs [deleted file]
mcs/class/System.Core/System.Security.Cryptography/ECKeyXmlFormat.cs [deleted file]
mcs/class/System.Data/Makefile
mcs/class/System.Data/System.Data.SqlClient/SqlBulkCopy.platformnotsupported.cs [new file with mode: 0644]
mcs/class/System.Data/System.Data.SqlClient/SqlCommand.cs
mcs/class/System.Data/System.Data.SqlClient/SqlCommand.platformnotsupported.cs [new file with mode: 0644]
mcs/class/System.Data/System.Data.SqlClient/SqlCommandBuilder.platformnotsupported.cs [new file with mode: 0644]
mcs/class/System.Data/System.Data.SqlClient/SqlConnection.cs
mcs/class/System.Data/System.Data.SqlClient/SqlConnection.platformnotsupported.cs [new file with mode: 0644]
mcs/class/System.Data/System.Data.SqlClient/SqlDataReader.platformnotsupported.cs [new file with mode: 0644]
mcs/class/System.Data/System.Data.SqlClient/SqlDependency.cs
mcs/class/System.Data/System.Data.SqlClient/SqlException.platformnotsupported.cs [new file with mode: 0644]
mcs/class/System.Data/System.Data.SqlClient/SqlParameter.cs
mcs/class/System.Data/System.Data.SqlClient/SqlParameter.platformnotsupported.cs [new file with mode: 0644]
mcs/class/System.Data/System.Data.SqlClient/SqlParameterCollection.platformnotsupported.cs [new file with mode: 0644]
mcs/class/System.Data/System.Data.SqlClient/SqlTransaction.platformnotsupported.cs [new file with mode: 0644]
mcs/class/System.Data/Test/System.Data.Common/DbDataAdapterTest.cs
mcs/class/System.Data/Test/System.Data.SqlClient/SqlBulkCopyTest.cs
mcs/class/System.Data/Test/System.Data.SqlClient/SqlCommandBuilderTest.cs
mcs/class/System.Data/Test/System.Data.SqlClient/SqlCommandTest.cs
mcs/class/System.Data/Test/System.Data.SqlClient/SqlConnectionTest.cs
mcs/class/System.Data/Test/System.Data.SqlClient/SqlDataAdapterTest.cs
mcs/class/System.Data/Test/System.Data.SqlClient/SqlParameterTest.cs
mcs/class/System.Data/Test/System.Data/DataTableReadWriteXmlTest.cs [changed mode: 0644->0755]
mcs/class/System.Data/Test/System.Data/DataTableTest.cs [changed mode: 0644->0755]
mcs/class/System.Data/Test/System.Xml/XmlDataDocumentTest.cs [changed mode: 0644->0755]
mcs/class/System.Data/monotouch_watch_System.Data.dll.exclude.sources [new file with mode: 0644]
mcs/class/System.Data/monotouch_watch_System.Data.dll.sources
mcs/class/System.IdentityModel/Makefile
mcs/class/System.Net.Http/HttpClientEx.cs
mcs/class/System.Net.Http/System.Net.Http.Headers/ContentRangeHeaderValue.cs
mcs/class/System.Net.Http/System.Net.Http/HttpClientHandler.cs
mcs/class/System.Net.Http/System.Net.Http/HttpClientHandler.platformnotsupported.cs [new file with mode: 0644]
mcs/class/System.Net.Http/Test/System.Net.Http.Headers/ContentRangeHeaderValueTest.cs
mcs/class/System.Net.Http/Test/System.Net.Http/HttpClientHandlerTest.cs
mcs/class/System.Net.Http/Test/System.Net.Http/HttpClientTest.cs
mcs/class/System.Net.Http/monotouch_watch_System.Net.Http.dll.exclude.sources [new file with mode: 0644]
mcs/class/System.Net.Http/monotouch_watch_System.Net.Http.dll.sources [new file with mode: 0644]
mcs/class/System.Runtime.Remoting/System.Runtime.Remoting.Channels.Tcp/TcpServerChannel.cs
mcs/class/System.Runtime.Serialization/ReferenceSources/SchemaExporter_mobile.cs
mcs/class/System.Runtime.Serialization/ReferenceSources/XsdDataContractExporter_mobile.cs [new file with mode: 0644]
mcs/class/System.Runtime.Serialization/mobile_System.Runtime.Serialization.dll.sources
mcs/class/System.Security/Makefile
mcs/class/System.ServiceModel.Web/Test/System.ServiceModel.Web/WebOperationContextTest.cs
mcs/class/System.ServiceModel/Test/System.ServiceModel.Dispatcher/DispatchOperationTest.cs
mcs/class/System.Web/System.Web.Compilation/AppResourcesAssemblyBuilder.cs
mcs/class/System.Web/System.Web.dll.sources
mcs/class/System.Web/Test/System.Web.UI.WebControls.Adapters/HideDisabledControlAdapterTest.cs [changed mode: 0644->0755]
mcs/class/System.Web/Test/System.Web.UI.WebControls.Adapters/MenuAdapterTest.cs [changed mode: 0644->0755]
mcs/class/System.Web/Test/System.Web.UI.WebControls.Adapters/WebControlAdapterTest.cs [changed mode: 0644->0755]
mcs/class/System.Web/Test/System.Web.UI.WebControls/WizardTest.cs [changed mode: 0644->0755]
mcs/class/System.Windows.Forms/System.Windows.Forms.dll.sources
mcs/class/System.Windows.Forms/System.Windows.Forms/Application.cs
mcs/class/System.Windows.Forms/System.Windows.Forms/DataGrid.cs
mcs/class/System.Windows.Forms/System.Windows.Forms/Hwnd.cs
mcs/class/System.Windows.Forms/System.Windows.Forms/ThemeVisualStyles.cs
mcs/class/System.XML/System.Xml.Serialization/XmlSerializationReader.cs
mcs/class/System.XML/System.Xml.Serialization/XmlSerializer.cs
mcs/class/System.XML/System.Xml.Serialization/XmlSerializerFactory.cs
mcs/class/System.XML/System.Xml.Xsl/XslCompiledTransform_Mobile.cs
mcs/class/System.XML/Test/System.Xml.Serialization/XmlReflectionImporterTests.cs [changed mode: 0644->0755]
mcs/class/System/Assembly/AssemblyInfo.cs
mcs/class/System/Makefile
mcs/class/System/Microsoft.CSharp/CSharpCodeCompiler.cs
mcs/class/System/Microsoft.VisualBasic/VBCodeCompiler.cs
mcs/class/System/Microsoft.Win32.SafeHandles/SafeX509ChainHandle.cs
mcs/class/System/Mono.Btls/MonoBtlsBio.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsContext.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsError.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsException.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsKey.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsObject.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsPkcs12.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsProvider.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsSsl.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsSslCtx.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsSslError.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsStream.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsUtils.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsX509.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsX509Chain.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsX509Crl.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsX509Error.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsX509Exception.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsX509FileType.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsX509Format.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsX509Lookup.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsX509LookupAndroid.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsX509LookupMono.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsX509LookupMonoCollection.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsX509LookupType.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsX509Name.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsX509NameEntryType.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsX509NameList.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsX509Purpose.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsX509Revoked.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsX509Store.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsX509StoreCtx.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsX509StoreManager.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsX509StoreType.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsX509TrustKind.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsX509VerifyFlags.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/MonoBtlsX509VerifyParam.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/X509CertificateImplBtls.cs [new file with mode: 0644]
mcs/class/System/Mono.Btls/X509ChainImplBtls.cs [new file with mode: 0644]
mcs/class/System/Mono.Net.Security/AsyncProtocolRequest.cs
mcs/class/System/Mono.Net.Security/ChainValidationHelper.cs
mcs/class/System/Mono.Net.Security/IMonoTlsProvider.cs
mcs/class/System/Mono.Net.Security/LegacySslStream.cs
mcs/class/System/Mono.Net.Security/LegacyTlsProvider.cs [new file with mode: 0644]
mcs/class/System/Mono.Net.Security/MobileAuthenticatedStream.cs
mcs/class/System/Mono.Net.Security/MobileTlsContext.cs
mcs/class/System/Mono.Net.Security/MonoLegacyTlsProvider.cs [deleted file]
mcs/class/System/Mono.Net.Security/MonoTlsProviderFactory.Droid.cs
mcs/class/System/Mono.Net.Security/MonoTlsProviderFactory.cs
mcs/class/System/Mono.Net.Security/MonoTlsProviderImpl.cs [deleted file]
mcs/class/System/Mono.Net.Security/MonoTlsProviderWrapper.cs
mcs/class/System/Mono.Net.Security/MonoTlsStream.cs
mcs/class/System/Mono.Net.Security/NoReflectionHelper.cs
mcs/class/System/Mono.Net.Security/SystemCertificateValidator.cs
mcs/class/System/ReferenceSources/Internal.cs [deleted file]
mcs/class/System/ReferenceSources/Logging.cs
mcs/class/System/ReferenceSources/SSPIConfiguration.cs [deleted file]
mcs/class/System/ReferenceSources/SSPISafeHandles.cs [deleted file]
mcs/class/System/ReferenceSources/SSPIWrapper.cs [deleted file]
mcs/class/System/ReferenceSources/SettingsSectionInternal.cs
mcs/class/System/ReferenceSources/Socket.cs
mcs/class/System/ReferenceSources/SslStream.cs [deleted file]
mcs/class/System/ReferenceSources/_SecureChannel.cs [deleted file]
mcs/class/System/ReferenceSources/_SslState.cs [deleted file]
mcs/class/System/ReferenceSources/_SslStream.cs [deleted file]
mcs/class/System/System-bare-net_4_x.csproj
mcs/class/System/System-net_4_x.csproj
mcs/class/System/System-secxml-net_4_x.csproj
mcs/class/System/System.Diagnostics.CodeAnalysis/ExcludeFromCodeCoverageAttribute.cs [deleted file]
mcs/class/System/System.Diagnostics/ProcessModuleCollection.cs [deleted file]
mcs/class/System/System.Diagnostics/ProcessThreadCollection.cs [deleted file]
mcs/class/System/System.IO/FileSystemWatcher_mobile.cs
mcs/class/System/System.Net.Mail/MailMessage.cs
mcs/class/System/System.Net.Mail/SmtpClient.platformnotsupported.cs [new file with mode: 0644]
mcs/class/System/System.Net.NetworkInformation/IPAddressCollection.cs
mcs/class/System/System.Net.NetworkInformation/NetworkInterface.cs
mcs/class/System/System.Net.NetworkInformation/Ping.cs
mcs/class/System/System.Net.Security/EncryptionPolicy.cs
mcs/class/System/System.Net.Security/LocalCertificateSelectionCallback.cs
mcs/class/System/System.Net.Security/NegotiateStream.cs
mcs/class/System/System.Net.Security/RemoteCertificateValidationCallback.cs
mcs/class/System/System.Net.Security/SslPolicyErrors.cs
mcs/class/System/System.Net.Security/SslStream.cs
mcs/class/System/System.Net.Security/SslStream.platformnotsupported.cs [new file with mode: 0644]
mcs/class/System/System.Net.Sockets/SendPacketsElement.cs [deleted file]
mcs/class/System/System.Net.Sockets/Socket.cs
mcs/class/System/System.Net.Sockets/SocketAsyncEventArgs.cs
mcs/class/System/System.Net.Sockets/SocketAsyncOperation.cs [deleted file]
mcs/class/System/System.Net.Sockets/SocketAsyncResult.cs
mcs/class/System/System.Net.Sockets/TcpClient.cs [deleted file]
mcs/class/System/System.Net.Sockets/TcpClient.platformnotsupported.cs [new file with mode: 0644]
mcs/class/System/System.Net.Sockets/TcpListener.cs [deleted file]
mcs/class/System/System.Net.Sockets/TcpListener.platformnotsupported.cs [new file with mode: 0644]
mcs/class/System/System.Net.Sockets/UdpClient.cs [deleted file]
mcs/class/System/System.Net.Sockets/UdpClient.platformnotsupported.cs [new file with mode: 0644]
mcs/class/System/System.Net.WebSockets/ClientWebSocket.platformnotsupported.cs [new file with mode: 0644]
mcs/class/System/System.Net/AuthenticationManager.cs
mcs/class/System/System.Net/AuthenticationManager.platformnotsupported.cs [new file with mode: 0644]
mcs/class/System/System.Net/Dns.cs
mcs/class/System/System.Net/FtpRequestCreator.platformnotsupported.cs [new file with mode: 0644]
mcs/class/System/System.Net/FtpWebRequest.cs
mcs/class/System/System.Net/FtpWebRequest.platformnotsupported.cs [new file with mode: 0644]
mcs/class/System/System.Net/FtpWebResponse.platformnotsupported.cs [new file with mode: 0644]
mcs/class/System/System.Net/HttpListener.cs
mcs/class/System/System.Net/HttpListener.platformnotsupported.cs [new file with mode: 0644]
mcs/class/System/System.Net/HttpListenerContext.cs
mcs/class/System/System.Net/HttpListenerContext.platformnotsupported.cs [new file with mode: 0644]
mcs/class/System/System.Net/HttpListenerPrefixCollection.platformnotsupported.cs [new file with mode: 0644]
mcs/class/System/System.Net/HttpListenerRequest.platformnotsupported.cs [new file with mode: 0644]
mcs/class/System/System.Net/HttpListenerResponse.cs
mcs/class/System/System.Net/HttpListenerResponse.platformnotsupported.cs [new file with mode: 0644]
mcs/class/System/System.Net/HttpListenerResponseHelper.cs [new file with mode: 0644]
mcs/class/System/System.Net/HttpListenerTimeoutManager.cs
mcs/class/System/System.Net/HttpWebRequest.cs
mcs/class/System/System.Net/HttpWebRequest.platformnotsupported.cs [new file with mode: 0644]
mcs/class/System/System.Net/HttpWebResponse.cs
mcs/class/System/System.Net/HttpWebResponse.platformnotsupported.cs [new file with mode: 0644]
mcs/class/System/System.Net/ServicePoint.platformnotsupported.cs [new file with mode: 0644]
mcs/class/System/System.Net/ServicePointManager.cs
mcs/class/System/System.Net/ServicePointManager.platformnotsupported.cs [new file with mode: 0644]
mcs/class/System/System.Net/WebConnection.cs
mcs/class/System/System.Security.Authentication.ExtendedProtection/ServiceNameCollection.cs [deleted file]
mcs/class/System/System.Security.Cryptography.X509Certificates/OSX509Certificates.cs
mcs/class/System/System.Security.Cryptography.X509Certificates/X500DistinguishedName.cs
mcs/class/System/System.Security.Cryptography.X509Certificates/X509Certificate2.cs
mcs/class/System/System.Security.Cryptography.X509Certificates/X509Certificate2Impl.cs
mcs/class/System/System.Security.Cryptography.X509Certificates/X509Certificate2ImplMono.cs
mcs/class/System/System.Security.Cryptography.X509Certificates/X509Chain.cs
mcs/class/System/System.Security.Cryptography.X509Certificates/X509ChainPolicy.cs
mcs/class/System/System.Security.Cryptography.X509Certificates/X509Helper2.cs
mcs/class/System/System.dll.sources
mcs/class/System/System/AndroidPlatform.cs
mcs/class/System/System/MonoToolsLocator.cs [new file with mode: 0755]
mcs/class/System/Test/System.Diagnostics/ProcessTest.cs
mcs/class/System/Test/System.Net.Mail/SmtpClientTest.cs
mcs/class/System/Test/System.Net.NetworkInformation/IPInterfacePropertiesTest.cs
mcs/class/System/Test/System.Net.Security/SslStreamTest.cs
mcs/class/System/Test/System.Net.Sockets/NetworkStreamTest.cs
mcs/class/System/Test/System.Net.Sockets/SocketAcceptAsyncTest.cs
mcs/class/System/Test/System.Net.Sockets/SocketAsyncTest.cs
mcs/class/System/Test/System.Net.Sockets/SocketTest.cs
mcs/class/System/Test/System.Net.Sockets/TcpClientTest.cs
mcs/class/System/Test/System.Net.Sockets/TcpListenerTest.cs
mcs/class/System/Test/System.Net.Sockets/UdpClientTest.cs
mcs/class/System/Test/System.Net.WebSockets/ClientWebSocketTest.cs
mcs/class/System/Test/System.Net/CookieParserTest.cs
mcs/class/System/Test/System.Net/DnsTest.cs
mcs/class/System/Test/System.Net/FileWebRequestTest.cs
mcs/class/System/Test/System.Net/FtpWebRequestTest.cs
mcs/class/System/Test/System.Net/HttpListener2Test.cs
mcs/class/System/Test/System.Net/HttpListenerPrefixCollectionTest.cs
mcs/class/System/Test/System.Net/HttpListenerRequestTest.cs
mcs/class/System/Test/System.Net/HttpListenerTest.cs
mcs/class/System/Test/System.Net/HttpWebRequestTest.cs
mcs/class/System/Test/System.Net/HttpWebResponseTest.cs
mcs/class/System/Test/System.Net/ServicePointManagerTest.cs
mcs/class/System/Test/System.Net/ServicePointTest.cs
mcs/class/System/Test/System.Net/WebClientTest.cs
mcs/class/System/Test/System.Net/WebHeaderCollectionTest.cs
mcs/class/System/Test/System.Net/WebRequestTest.cs
mcs/class/System/Test/System/UriTest.cs
mcs/class/System/Test/System/UriTest3.cs
mcs/class/System/mobile_System.dll.sources
mcs/class/System/monodroid_System.dll.sources
mcs/class/System/monotouch_watch_System.dll.exclude.sources [new file with mode: 0644]
mcs/class/System/monotouch_watch_System.dll.sources
mcs/class/System/monotouch_watch_runtime_System.dll.exclude.sources [new file with mode: 0644]
mcs/class/System/monotouch_watch_runtime_System.dll.sources
mcs/class/WindowsBase/System.IO.Packaging/Package.cs [changed mode: 0644->0755]
mcs/class/WindowsBase/Test/System.Windows/RectTest.cs
mcs/class/WindowsBase/WindowsBase.dll.sources
mcs/class/WindowsBase/ZipSharp/IOFunctions.cs
mcs/class/WindowsBase/ZipSharp/NativeUnzip.cs
mcs/class/WindowsBase/ZipSharp/NativeVersion.cs [new file with mode: 0755]
mcs/class/WindowsBase/ZipSharp/NativeZip.cs
mcs/class/WindowsBase/ZipSharp/UnzipArchive.cs
mcs/class/WindowsBase/ZipSharp/UnzipFileInfo.cs
mcs/class/WindowsBase/ZipSharp/UnzipReadStream.cs
mcs/class/WindowsBase/ZipSharp/ZipArchive.cs
mcs/class/WindowsBase/ZipSharp/ZipFileInfo.cs
mcs/class/WindowsBase/ZipSharp/ZipStream.cs
mcs/class/corlib/Assembly/AssemblyInfo.cs
mcs/class/corlib/CommonCrypto/SecRandom.cs
mcs/class/corlib/Documentation/s [deleted file]
mcs/class/corlib/Makefile
mcs/class/corlib/Mono/Runtime.cs
mcs/class/corlib/ReferenceSources/String.cs
mcs/class/corlib/ReferenceSources/Type.cs
mcs/class/corlib/ReferenceSources/TypeBuilderInstantiation.cs [deleted file]
mcs/class/corlib/System.Diagnostics.Tracing/EventSource.cs
mcs/class/corlib/System.Diagnostics.Tracing/EventSourceException.cs [deleted file]
mcs/class/corlib/System.Globalization/CultureInfo.cs
mcs/class/corlib/System.IO/File.cs
mcs/class/corlib/System.IO/FileStream.cs
mcs/class/corlib/System.Reflection.Emit/AssemblyBuilder.cs
mcs/class/corlib/System.Reflection.Emit/ConstructorBuilder.cs
mcs/class/corlib/System.Reflection.Emit/ConstructorOnTypeBuilderInst.cs
mcs/class/corlib/System.Reflection.Emit/DerivedTypes.cs
mcs/class/corlib/System.Reflection.Emit/EventOnTypeBuilderInst.cs
mcs/class/corlib/System.Reflection.Emit/FieldBuilder.cs
mcs/class/corlib/System.Reflection.Emit/FieldOnTypeBuilderInst.cs
mcs/class/corlib/System.Reflection.Emit/GenericTypeParameterBuilder.cs
mcs/class/corlib/System.Reflection.Emit/ILGenerator.cs
mcs/class/corlib/System.Reflection.Emit/MethodBuilder.cs
mcs/class/corlib/System.Reflection.Emit/MethodOnTypeBuilderInst.cs
mcs/class/corlib/System.Reflection.Emit/ModuleBuilder.cs
mcs/class/corlib/System.Reflection.Emit/PropertyOnTypeBuilderInst.cs
mcs/class/corlib/System.Reflection.Emit/TypeBuilder.cs
mcs/class/corlib/System.Reflection.Emit/TypeBuilderInstantiation.cs [new file with mode: 0644]
mcs/class/corlib/System.Reflection/Assembly.cs
mcs/class/corlib/System.Reflection/MonoGenericClass.cs [deleted file]
mcs/class/corlib/System.Reflection/MonoGenericMethod.cs [deleted file]
mcs/class/corlib/System.Reflection/TargetException.cs [deleted file]
mcs/class/corlib/System.Reflection/TargetInvocationException.cs [deleted file]
mcs/class/corlib/System.Reflection/TargetParameterCountException.cs [deleted file]
mcs/class/corlib/System.Runtime.InteropServices/Marshal.cs
mcs/class/corlib/System.Runtime.Remoting/RemotingConfiguration.cs
mcs/class/corlib/System.Runtime/GCLatencyMode.cs
mcs/class/corlib/System.Security.AccessControl/EventWaitHandleSecurity.cs
mcs/class/corlib/System.Security.AccessControl/NativeObjectSecurity.cs
mcs/class/corlib/System.Security.AccessControl/ObjectSecurity_T.cs
mcs/class/corlib/System.Security.Cryptography/CryptoConfig.fullaot.cs
mcs/class/corlib/System.Security.Cryptography/RNGCryptoServiceProvider.cs
mcs/class/corlib/System.Threading/Thread.cs
mcs/class/corlib/System/AppDomain.cs
mcs/class/corlib/System/Environment.cs
mcs/class/corlib/System/GC.cs [deleted file]
mcs/class/corlib/System/GCCollectionMode.cs [deleted file]
mcs/class/corlib/System/GCNotificationStatus.cs [deleted file]
mcs/class/corlib/System/TermInfoDriver.cs
mcs/class/corlib/System/TypeSpec.cs
mcs/class/corlib/Test/System.Globalization/CultureInfoTest.cs
mcs/class/corlib/Test/System.Reflection.Emit/ModuleBuilderTest.cs
mcs/class/corlib/Test/System.Reflection.Emit/TypeBuilderTest.cs
mcs/class/corlib/Test/System.Runtime.CompilerServices/RuntimeHelpersTest.cs
mcs/class/corlib/Test/System/AttributeTest.cs
mcs/class/corlib/Test/System/GCTest.cs [new file with mode: 0644]
mcs/class/corlib/Test/System/TypeTest.cs
mcs/class/corlib/corefx/SR.cs [new file with mode: 0644]
mcs/class/corlib/corlib-net_4_x.csproj
mcs/class/corlib/corlib.dll.sources
mcs/class/corlib/corlib_test.dll.sources
mcs/class/corlib/net_4_x_corlib.dll.sources [deleted file]
mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/DebugInfoGenerator.cs
mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/DelegateHelpers.cs
mcs/class/referencesource/System.Core/System/Linq/Parallel/QueryOperators/Binary/UnionQueryOperator.cs
mcs/class/referencesource/System.Core/System/Linq/Parallel/QueryOperators/Options/OrderingQueryOperator.cs
mcs/class/referencesource/System.Core/System/Linq/Parallel/QueryOperators/Unary/ConcatQueryOperator.cs
mcs/class/referencesource/System.Core/System/Linq/Parallel/QueryOperators/Unary/SortQueryOperator.cs
mcs/class/referencesource/System.Core/System/Linq/Parallel/Scheduling/OrderPreservingPipeliningSpoolingTask.cs
mcs/class/referencesource/System.Core/System/Linq/Parallel/Utils/Sorting.cs
mcs/class/referencesource/System.Core/System/Linq/SequenceQuery.cs
mcs/class/referencesource/System.Data/System/Data/Sql/SqlDataSourceEnumerator.cs
mcs/class/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/XmlSerializableServices.cs
mcs/class/referencesource/System/compmod/system/codedom/CodeNamespace.cs
mcs/class/referencesource/System/compmod/system/codedom/CodePropertyReferenceExpression.cs
mcs/class/referencesource/System/compmod/system/componentmodel/LicFileLicenseProvider.cs
mcs/class/referencesource/System/compmod/system/componentmodel/ReflectEventDescriptor.cs
mcs/class/referencesource/System/compmod/system/componentmodel/ReflectPropertyDescriptor.cs
mcs/class/referencesource/System/compmod/system/componentmodel/TypeConverter.cs
mcs/class/referencesource/System/net/System/Net/Sockets/Socket.cs
mcs/class/referencesource/System/net/System/Net/WebRequest.cs
mcs/class/referencesource/System/net/System/Net/connectionpool.cs
mcs/class/referencesource/System/net/System/Net/filewebrequest.cs
mcs/class/referencesource/System/net/System/Net/webclient.cs
mcs/class/referencesource/System/net/System/UriExt.cs
mcs/class/referencesource/System/regex/system/text/regularexpressions/Regex.cs
mcs/class/referencesource/System/regex/system/text/regularexpressions/RegexCompiler.cs
mcs/class/referencesource/System/services/monitoring/system/diagnosticts/AsyncStreamReader.cs
mcs/class/referencesource/System/services/monitoring/system/diagnosticts/Process.cs
mcs/class/referencesource/System/services/monitoring/system/diagnosticts/ProcessModuleCollection.cs
mcs/class/referencesource/System/services/monitoring/system/diagnosticts/ProcessThreadCollection.cs
mcs/class/referencesource/System/sys/system/windows/markup/ValueSerializerAttribute.cs
mcs/class/referencesource/mscorlib/system/contextboundobject.cs
mcs/class/referencesource/mscorlib/system/gc.cs
mcs/class/referencesource/mscorlib/system/globalization/compareinfo.cs
mcs/class/referencesource/mscorlib/system/io/fileinfo.cs
mcs/class/referencesource/mscorlib/system/io/filesysteminfo.cs
mcs/class/referencesource/mscorlib/system/io/stream.cs
mcs/class/referencesource/mscorlib/system/io/textreader.cs
mcs/class/referencesource/mscorlib/system/io/textwriter.cs
mcs/class/referencesource/mscorlib/system/runtime/interopservices/runtimeenvironment.cs
mcs/class/referencesource/mscorlib/system/runtime/serialization/formatters/binary/binaryformatter.cs
mcs/class/referencesource/mscorlib/system/security/attributes.cs
mcs/class/referencesource/mscorlib/system/security/cryptography/rc2cryptoserviceprovider.cs
mcs/class/referencesource/mscorlib/system/security/cryptography/rfc2898derivebytes.cs
mcs/class/referencesource/mscorlib/system/threading/threadabortexception.cs
mcs/class/test-helpers/SocketResponder.cs
mcs/errors/cs0177-15.cs [new file with mode: 0644]
mcs/errors/cs0219-7.cs [new file with mode: 0644]
mcs/ilasm/parser/ILParser.jay
mcs/mcs/context.cs
mcs/mcs/cs-tokenizer.cs
mcs/mcs/ecore.cs
mcs/mcs/generic.cs
mcs/mcs/ikvm.cs
mcs/mcs/import.cs
mcs/mcs/property.cs
mcs/mcs/statement.cs
mcs/tests/test-16628-lib.il [new file with mode: 0644]
mcs/tests/test-254.cs
mcs/tests/test-941.cs [new file with mode: 0644]
mcs/tests/test-interpolation-05.cs
mcs/tests/ver-il-net_4_x.xml
mcs/tools/Makefile
mcs/tools/btls/AssemblyInfo.cs [new file with mode: 0644]
mcs/tools/btls/Makefile [new file with mode: 0644]
mcs/tools/btls/btls-cert-sync.cs [new file with mode: 0644]
mcs/tools/btls/btls-cert-sync.exe.sources [new file with mode: 0644]
mcs/tools/commoncryptogenerator/CommonCryptorGenerator.cs
mcs/tools/commoncryptogenerator/generator.cs
mcs/tools/corcompare/mono-api-info.cs
mcs/tools/gacutil/Makefile
mcs/tools/gacutil/driver.cs
mcs/tools/gacutil/gacutil.exe.sources
mcs/tools/linker/Descriptors/mscorlib.xml
mcs/tools/linker/Mono.Linker.Steps/MarkStep.cs
mcs/tools/mdoc/Makefile
mcs/tools/mkbundle/mkbundle.cs
mcs/tools/mono-symbolicate/Makefile
mcs/tools/mono-symbolicate/mono-symbolicate.exe.sources
mcs/tools/security/cert-sync.cs
mcs/tools/xbuild/tests/Vbc/1.vbproj [new file with mode: 0644]
mcs/tools/xbuild/tests/Vbc/2.vbproj [new file with mode: 0644]
mcs/tools/xbuild/tests/Vbc/test.vb [new file with mode: 0644]
mono/Makefile.am
mono/btls/.gitignore [new file with mode: 0644]
mono/btls/CMakeLists.txt [new file with mode: 0644]
mono/btls/Makefile.am [new file with mode: 0644]
mono/btls/btls-android-utils.c [new file with mode: 0644]
mono/btls/btls-bio.c [new file with mode: 0644]
mono/btls/btls-bio.h [new file with mode: 0644]
mono/btls/btls-error.c [new file with mode: 0644]
mono/btls/btls-error.h [new file with mode: 0644]
mono/btls/btls-key.c [new file with mode: 0644]
mono/btls/btls-key.h [new file with mode: 0644]
mono/btls/btls-pkcs12.c [new file with mode: 0644]
mono/btls/btls-pkcs12.h [new file with mode: 0644]
mono/btls/btls-ssl-ctx.c [new file with mode: 0644]
mono/btls/btls-ssl-ctx.h [new file with mode: 0644]
mono/btls/btls-ssl.c [new file with mode: 0644]
mono/btls/btls-ssl.h [new file with mode: 0644]
mono/btls/btls-util.c [new file with mode: 0644]
mono/btls/btls-util.h [new file with mode: 0644]
mono/btls/btls-x509-chain.c [new file with mode: 0644]
mono/btls/btls-x509-chain.h [new file with mode: 0644]
mono/btls/btls-x509-crl.c [new file with mode: 0644]
mono/btls/btls-x509-crl.h [new file with mode: 0644]
mono/btls/btls-x509-lookup-mono.c [new file with mode: 0644]
mono/btls/btls-x509-lookup-mono.h [new file with mode: 0644]
mono/btls/btls-x509-lookup.c [new file with mode: 0644]
mono/btls/btls-x509-lookup.h [new file with mode: 0644]
mono/btls/btls-x509-name.c [new file with mode: 0644]
mono/btls/btls-x509-name.h [new file with mode: 0644]
mono/btls/btls-x509-revoked.c [new file with mode: 0644]
mono/btls/btls-x509-revoked.h [new file with mode: 0644]
mono/btls/btls-x509-store-ctx.c [new file with mode: 0644]
mono/btls/btls-x509-store-ctx.h [new file with mode: 0644]
mono/btls/btls-x509-store.c [new file with mode: 0644]
mono/btls/btls-x509-store.h [new file with mode: 0644]
mono/btls/btls-x509-verify-param.c [new file with mode: 0644]
mono/btls/btls-x509-verify-param.h [new file with mode: 0644]
mono/btls/btls-x509.c [new file with mode: 0644]
mono/btls/btls-x509.h [new file with mode: 0644]
mono/btls/create-object-library.sh [new file with mode: 0755]
mono/dis/main.c
mono/io-layer/io-layer.h
mono/io-layer/processes.c
mono/metadata/Makefile.am
mono/metadata/appdomain.c
mono/metadata/assembly-internals.h [new file with mode: 0644]
mono/metadata/assembly.c
mono/metadata/assembly.h
mono/metadata/attach.c
mono/metadata/boehm-gc.c
mono/metadata/class-internals.h
mono/metadata/class.c
mono/metadata/cominterop.c
mono/metadata/console-win32-internals.h [new file with mode: 0644]
mono/metadata/console-win32-uwp.c [new file with mode: 0644]
mono/metadata/console-win32.c
mono/metadata/coree-internals.h [new file with mode: 0644]
mono/metadata/coree-windows-uwp.c [new file with mode: 0644]
mono/metadata/coree.c
mono/metadata/custom-attrs.c
mono/metadata/debug-mono-symfile.c
mono/metadata/domain-internals.h
mono/metadata/domain.c
mono/metadata/dynamic-image.c
mono/metadata/exception.c
mono/metadata/file-io-internals.h [new file with mode: 0644]
mono/metadata/file-io-windows-internals.h [new file with mode: 0644]
mono/metadata/file-io-windows-uwp.c [new file with mode: 0644]
mono/metadata/file-io-windows.c [new file with mode: 0644]
mono/metadata/file-io.c
mono/metadata/gc-internals.h
mono/metadata/gc.c
mono/metadata/handle.c
mono/metadata/handle.h
mono/metadata/icall-def.h
mono/metadata/icall-internals.h [new file with mode: 0644]
mono/metadata/icall-windows-internals.h [new file with mode: 0644]
mono/metadata/icall-windows-uwp.c [new file with mode: 0644]
mono/metadata/icall-windows.c [new file with mode: 0644]
mono/metadata/icall.c
mono/metadata/image-internals.h
mono/metadata/image.c
mono/metadata/image.h
mono/metadata/loader.c
mono/metadata/loader.h
mono/metadata/lock-tracer.c
mono/metadata/marshal-internals.h [new file with mode: 0644]
mono/metadata/marshal-windows-internals.h [new file with mode: 0644]
mono/metadata/marshal-windows-uwp.c [new file with mode: 0644]
mono/metadata/marshal-windows.c [new file with mode: 0644]
mono/metadata/marshal.c
mono/metadata/mempool-internals.h
mono/metadata/mempool.c
mono/metadata/metadata-internals.h
mono/metadata/metadata.c
mono/metadata/mono-security-windows-internals.h [new file with mode: 0644]
mono/metadata/mono-security-windows-uwp.c [new file with mode: 0644]
mono/metadata/mono-security-windows.c [new file with mode: 0644]
mono/metadata/mono-security.c
mono/metadata/null-gc.c
mono/metadata/object-internals.h
mono/metadata/object.c
mono/metadata/process-internals.h [new file with mode: 0644]
mono/metadata/process-windows-internals.h [new file with mode: 0644]
mono/metadata/process-windows-uwp.c [new file with mode: 0644]
mono/metadata/process-windows.c [new file with mode: 0644]
mono/metadata/process.c
mono/metadata/profiler.c
mono/metadata/reflection.c
mono/metadata/remoting.c
mono/metadata/security-core-clr.c
mono/metadata/sgen-client-mono.h
mono/metadata/sgen-mono.c
mono/metadata/sgen-new-bridge.c
mono/metadata/sgen-os-coop.c
mono/metadata/sgen-os-win32.c
mono/metadata/socket-io-windows-internals.h [new file with mode: 0644]
mono/metadata/socket-io-windows.c [new file with mode: 0644]
mono/metadata/socket-io.c
mono/metadata/socket-io.h
mono/metadata/sre-encode.c
mono/metadata/sre-internals.h
mono/metadata/sre-save.c
mono/metadata/sre.c
mono/metadata/threadpool-ms.c
mono/metadata/threads-types.h
mono/metadata/threads.c
mono/metadata/w32mutex-unix.c
mono/metadata/w32mutex-utils.h [deleted file]
mono/metadata/w32mutex.h
mono/metadata/w32semaphore-unix.c
mono/metadata/w32semaphore-win32.c
mono/mini/Makefile.am.in
mono/mini/aot-compiler.c
mono/mini/aot-runtime.c
mono/mini/debugger-agent.c
mono/mini/driver.c
mono/mini/exceptions-amd64.c
mono/mini/generics.cs
mono/mini/gshared.cs
mono/mini/ir-emit.h
mono/mini/local-propagation.c
mono/mini/main.c
mono/mini/method-to-ir.c
mono/mini/mini-arm64.c
mono/mini/mini-exceptions.c
mono/mini/mini-generic-sharing.c
mono/mini/mini-llvm.c
mono/mini/mini-mips.c
mono/mini/mini-mips.h
mono/mini/mini-posix.c
mono/mini/mini-runtime.c
mono/mini/mini-trampolines.c
mono/mini/mini-windows-uwp.c [new file with mode: 0644]
mono/mini/mini-windows.c
mono/mini/mini-windows.h [new file with mode: 0644]
mono/mini/mini.c
mono/mini/mini.h
mono/mini/tramp-amd64.c
mono/profiler/Makefile.am
mono/profiler/decode.c [deleted file]
mono/profiler/mono-profiler-log.c [new file with mode: 0644]
mono/profiler/mono-profiler-log.h [new file with mode: 0644]
mono/profiler/mprof-report.c [new file with mode: 0644]
mono/profiler/proflog.c [deleted file]
mono/profiler/proflog.h [deleted file]
mono/profiler/utils.c [deleted file]
mono/profiler/utils.h [deleted file]
mono/sgen/gc-internal-agnostic.h
mono/sgen/sgen-gc.c
mono/sgen/sgen-gray.c
mono/sgen/sgen-internal.c
mono/sgen/sgen-layout-stats.c
mono/sgen/sgen-marksweep-drain-gray-stack.h
mono/sgen/sgen-memory-governor.c
mono/sgen/sgen-workers.c
mono/tests/Makefile.am
mono/tests/libtest.c
mono/tests/pinvoke2.cs
mono/tests/test-multi-netmodule-1-netmodule.cs [new file with mode: 0644]
mono/tests/test-multi-netmodule-2-dll1.cs [new file with mode: 0644]
mono/tests/test-multi-netmodule-3-dll2.cs [new file with mode: 0644]
mono/tests/test-multi-netmodule-4-exe.cs [new file with mode: 0644]
mono/tests/thread-native-exit.cs [new file with mode: 0644]
mono/utils/Makefile.am
mono/utils/atomic.c
mono/utils/checked-build.c
mono/utils/checked-build.h
mono/utils/lock-free-alloc.h
mono/utils/mono-compiler.h
mono/utils/mono-context.h
mono/utils/mono-counters.c
mono/utils/mono-dl-windows-uwp.c [new file with mode: 0644]
mono/utils/mono-dl-windows.c
mono/utils/mono-dl-windows.h [new file with mode: 0644]
mono/utils/mono-error-internals.h
mono/utils/mono-error.c
mono/utils/mono-error.h
mono/utils/mono-io-portability.c
mono/utils/mono-log-android.c [new file with mode: 0644]
mono/utils/mono-log-common.c
mono/utils/mono-log-darwin.c [new file with mode: 0644]
mono/utils/mono-log-windows.c
mono/utils/mono-logger-internals.h
mono/utils/mono-logger.c
mono/utils/mono-mmap-internals.h
mono/utils/mono-mmap-windows-uwp.c [new file with mode: 0644]
mono/utils/mono-mmap-windows.c [new file with mode: 0644]
mono/utils/mono-mmap-windows.h [new file with mode: 0644]
mono/utils/mono-mmap.c
mono/utils/mono-os-semaphore.h
mono/utils/mono-proclib-windows-uwp.c [new file with mode: 0644]
mono/utils/mono-proclib-windows.c [new file with mode: 0644]
mono/utils/mono-proclib-windows.h [new file with mode: 0644]
mono/utils/mono-proclib.c
mono/utils/mono-publib.h
mono/utils/mono-rand-windows-uwp.c [new file with mode: 0644]
mono/utils/mono-rand-windows.c [new file with mode: 0644]
mono/utils/mono-rand-windows.h [new file with mode: 0644]
mono/utils/mono-rand.c
mono/utils/mono-threads-coop.c
mono/utils/mono-threads-posix.c
mono/utils/mono-threads-windows-abort-syscall.c
mono/utils/mono-threads-windows.c
mono/utils/mono-threads.c
mono/utils/mono-threads.h
mono/utils/networking-missing.c
mono/utils/w32handle.c
msvc/libmono-static.vcxproj
msvc/libmono-static.vcxproj.filters
msvc/libmonoruntime.vcxproj
msvc/libmonoruntime.vcxproj.filters
msvc/libmonoutils.vcxproj
msvc/libmonoutils.vcxproj.filters
msvc/mono.def
msvc/monoposixhelper.def
msvc/monoposixhelper.vcxproj
msvc/monoposixhelper.vcxproj.filters
msvc/monosgen.def
msvc/pedump.vcxproj
msvc/pedump.vcxproj.filters
msvc/scripts/order.xml
net_4_x.sln
scripts/.gitignore
scripts/Makefile.am
scripts/ci/run-jenkins.sh
scripts/ci/run-test-default.sh
scripts/ci/run-test-profiler-stress-tests.sh
scripts/mono-package-runtime [new file with mode: 0644]
winconfig.h

index d084d3948e49230f088e7e875dd49c409901a7b9..1c8f76e0107dae1e948de7280f293bcd110ef7b1 100644 (file)
        path = external/cecil-legacy
        url = git://github.com/mono/cecil.git
        branch = mono-legacy-0.9.5
+[submodule "external/boringssl"]
+       path = external/boringssl
+       url = git://github.com/mono/boringssl.git
+       branch = mono
+[submodule "external/corefx"]
+       path = external/corefx
+       url = git://github.com/mono/corefx.git
index 2b583e599be14ae9ab3139c7a11d55e7a1ab574a..15e32dd886d074e63d6f8bb44d2871c34083325e 100644 (file)
--- a/README.md
+++ b/README.md
@@ -15,19 +15,22 @@ The Mono project is part of the [.NET Foundation](http://www.dotnetfoundation.or
 6. [Configuration Options](#configuration-options)
 7. [Working with Submodules](#working-with-submodules)
 
-**Build Status**
-
-Officially supported architectures:
-
-| ubuntu-1404-amd64            | ubuntu-1404-i386            | debian-8-armel            | debian-8-armhf            | debian-8-arm64              | windows-amd64              |
-|------------------------------|-----------------------------|---------------------------|---------------------------|-----------------------------|----------------------------|
-| [![ubuntu-1404-amd64][1]][2] | [![ubuntu-1404-i386][3]][4] | [![debian-8-armel][5]][6] | [![debian-8-armhf][7]][8] | [![debian-8-arm64][9]][10]  | [![windows-amd64][11]][12] |
-
-Community supported architectures:
-
-| centos-s390x              |
-|---------------------------|
-| [![centos-s390x][13]][14] |
+### Build Status
+
+| OS           | Architecture       | Status                       |
+|--------------|--------------------|------------------------------|
+| Ubuntu 14.04 | amd64              | [![ubuntu-1404-amd64][1]][2] |
+| Ubuntu 14.04 | i386               | [![ubuntu-1404-i386][3]][4]  |
+| Debian 8     | armel              | [![debian-8-armel][5]][6]    |
+| Debian 8     | armhf              | [![debian-8-armhf][7]][8]    |
+| Debian 8     | arm64              | [![debian-8-arm64][9]][10]   |
+| OS X         | amd64              | [![osx-amd64][11]][12]       |
+| OS X         | i386               | [![osx-i386][13]][14]        |
+| Windows      | amd64              | [![windows-amd64][15]][16]   |
+| Windows      | i386               | [![windows-amd64][17]][18]   |
+| CentOS       | s390x (cs)         | [![centos-s390x][19]][20]    |
+
+_(cs) = community supported architecture_
 
 [1]: https://jenkins.mono-project.com/job/test-mono-mainline-linux/label=ubuntu-1404-amd64/badge/icon
 [2]: https://jenkins.mono-project.com/job/test-mono-mainline-linux/label=ubuntu-1404-amd64
@@ -39,10 +42,16 @@ Community supported architectures:
 [8]: https://jenkins.mono-project.com/job/test-mono-mainline-linux/label=debian-8-armhf/
 [9]: https://jenkins.mono-project.com/job/test-mono-mainline-linux/label=debian-8-arm64/badge/icon
 [10]: https://jenkins.mono-project.com/job/test-mono-mainline-linux/label=debian-8-arm64/
-[11]: https://ci.appveyor.com/api/projects/status/1e61ebdfpbiei58v/branch/master?svg=true
-[12]: https://ci.appveyor.com/project/ajlennon/mono-817/branch/master
-[13]: https://jenkins.mono-project.com/job/z/label=centos-s390x/badge/icon
-[14]: https://jenkins.mono-project.com/job/z/label=centos-s390x
+[11]: https://jenkins.mono-project.com/job/test-mono-mainline/label=osx-amd64/badge/icon
+[12]: https://jenkins.mono-project.com/job/test-mono-mainline/label=osx-amd64/
+[13]: https://jenkins.mono-project.com/job/test-mono-mainline/label=osx-i386/badge/icon
+[14]: https://jenkins.mono-project.com/job/test-mono-mainline/label=osx-i386/
+[15]: https://jenkins.mono-project.com/job/z/label=w64/badge/icon
+[16]: https://jenkins.mono-project.com/job/z/label=w64/
+[17]: https://jenkins.mono-project.com/job/z/label=w32/badge/icon
+[18]: https://jenkins.mono-project.com/job/z/label=w32/
+[19]: https://jenkins.mono-project.com/job/z/label=centos-s390x/badge/icon
+[20]: https://jenkins.mono-project.com/job/z/label=centos-s390x
 
 Compilation and Installation
 ============================
index 9188b174a9541f5f966e56dd03835705cdb59f23..ff67772a1d47d4ca21296d27cbb66dfcd8162743 100644 (file)
@@ -4,7 +4,8 @@ SYS_REFS = \
        System.Data.dll \
        System.Runtime.Serialization.dll \
        System.Xml.dll \
-       System.Xml.Linq.dll
+       System.Xml.Linq.dll \
+       Mono.Posix.dll
 
 check-profiler-stress:
        @$(MAKE) validate-benchmarker RESET_VERSIONS=1
index b2638c1273a7e4deee08ec2047618bec48d669db..5ef4ab02a2eb198eeb669e3a1fed781af3376828 100644 (file)
@@ -1,7 +1,14 @@
 using System;
+using System.Collections.Generic;
 using System.Diagnostics;
+using System.Globalization;
 using System.IO;
 using System.Linq;
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Threading;
+using System.Xml;
+using Mono.Unix.Native;
 using Newtonsoft.Json;
 
 // Shut up CLS compliance warnings from Json.NET.
@@ -10,7 +17,8 @@ using Newtonsoft.Json;
 namespace Mono.Profiling.Tests.Stress {
 
        // https://github.com/xamarin/benchmarker/blob/master/tools/libdbmodel/Benchmark.cs
-       class Benchmark {
+       sealed class Benchmark {
+
                public string Name { get; set; }
                public string TestDirectory { get; set; }
                public bool OnlyExplicit { get; set; }
@@ -24,8 +32,24 @@ namespace Mono.Profiling.Tests.Stress {
                }
        }
 
+       sealed class TestResult {
+
+               public Benchmark Benchmark { get; set; }
+               public ProcessStartInfo StartInfo { get; set; }
+               public Stopwatch Stopwatch { get; set; } = new Stopwatch ();
+               public int? ExitCode { get; set; }
+               public StringBuilder StandardOutput { get; set; } = new StringBuilder ();
+               public StringBuilder StandardError { get; set; } = new StringBuilder ();
+       }
+
        static class Program {
 
+               static readonly TimeSpan _timeout = TimeSpan.FromHours (6);
+
+               static string FilterInvalidXmlChars (string text) {
+                       return Regex.Replace (text, @"[^\x09\x0A\x0D\x20-\uD7FF\uE000-\uFFFD\u10000-\u10FFFF]", string.Empty);
+               }
+
                static int Main ()
                {
                        var depDir = Path.Combine ("..", "external", "benchmarker");
@@ -44,8 +68,7 @@ namespace Mono.Profiling.Tests.Stress {
                        var rand = new Random ();
                        var cpus = Environment.ProcessorCount;
 
-                       var successes = 0;
-                       var failures = 0;
+                       var results = new List<TestResult> (benchmarks.Length);
 
                        var sw = Stopwatch.StartNew ();
 
@@ -66,6 +89,8 @@ namespace Mono.Profiling.Tests.Stress {
                                        WorkingDirectory = Path.Combine (testDir, bench.TestDirectory),
                                        FileName = monoPath,
                                        Arguments = $"--debug --profile=log:{profOptions} " + string.Join (" ", bench.CommandLine),
+                                       RedirectStandardOutput = true,
+                                       RedirectStandardError = true,
                                };
 
                                info.EnvironmentVariables.Clear ();
@@ -77,32 +102,177 @@ namespace Mono.Profiling.Tests.Stress {
                                Console.WriteLine ($"[{sw.Elapsed.ToString ("G")}] {progress} Running {bench.Name} with profiler options: {profOptions}");
                                Console.ResetColor ();
 
-                               var sw2 = Stopwatch.StartNew ();
+                               var result = new TestResult {
+                                       Benchmark = bench,
+                                       StartInfo = info,
+                               };
+
+                               using (var proc = new Process ()) {
+                                       proc.StartInfo = info;
+
+                                       proc.OutputDataReceived += (sender, args) => {
+                                               if (args.Data != null)
+                                                       result.StandardOutput.AppendLine (args.Data);
+                                       };
+
+                                       proc.ErrorDataReceived += (sender, args) => {
+                                               if (args.Data != null)
+                                                       result.StandardError.AppendLine (args.Data);
+                                       };
+
+                                       result.Stopwatch.Start ();
 
-                               using (var proc = Process.Start (info)) {
-                                       proc.WaitForExit ();
-                                       sw2.Stop ();
+                                       proc.Start ();
 
-                                       Console.WriteLine ();
+                                       proc.BeginOutputReadLine ();
+                                       proc.BeginErrorReadLine ();
 
-                                       if (proc.ExitCode != 0)
-                                               failures++;
-                                       else
-                                               successes++;
+                                       if (!proc.WaitForExit ((int) _timeout.TotalMilliseconds)) {
+                                               // Force a thread dump.
+                                               Syscall.kill (proc.Id, Signum.SIGQUIT);
+                                               Thread.Sleep (1000);
 
-                                       Console.ForegroundColor = proc.ExitCode != 0 ? ConsoleColor.Red : ConsoleColor.Green;
-                                       Console.WriteLine ($"[{sw.Elapsed.ToString ("G")}] {progress} {bench.Name} took {sw2.Elapsed.ToString ("G")} and exited with code: {proc.ExitCode}");
+                                               try {
+                                                       proc.Kill ();
+                                               } catch (Exception) {
+                                               }
+                                       } else
+                                               result.ExitCode = proc.ExitCode;
+
+                                       result.Stopwatch.Stop ();
+                               }
+
+                               var resultStr = result.ExitCode == null ? "timed out" : $"exited with code: {result.ExitCode}";
+
+                               Console.ForegroundColor = result.ExitCode != 0 ? ConsoleColor.Red : ConsoleColor.Green;
+                               Console.WriteLine ($"[{sw.Elapsed.ToString ("G")}] {progress} {bench.Name} took {result.Stopwatch.Elapsed.ToString ("G")} and {resultStr}");
+                               Console.ResetColor ();
+
+                               if (result.ExitCode != 0) {
+                                       Console.ForegroundColor = ConsoleColor.Red;
+                                       Console.WriteLine ("===== stdout =====");
                                        Console.ResetColor ();
+
+                                       Console.WriteLine (result.StandardOutput.ToString ());
+
+                                       Console.ForegroundColor = ConsoleColor.Red;
+                                       Console.WriteLine ("===== stderr =====");
+                                       Console.ResetColor ();
+
+                                       Console.WriteLine (result.StandardError.ToString ());
                                }
+
+                               results.Add (result);
                        }
 
                        sw.Stop ();
 
-                       Console.ForegroundColor = failures != 0 ? ConsoleColor.Red : ConsoleColor.Green;
-                       Console.WriteLine ($"[{sw.Elapsed.ToString ("G")}] Finished with {successes}/{benchmarks.Length} passing tests");
+                       var successes = results.Count (r => r.ExitCode == 0);
+                       var failures = results.Count (r => r.ExitCode != null && r.ExitCode != 0);
+                       var timeouts = results.Count (r => r.ExitCode == null);
+
+                       var settings = new XmlWriterSettings {
+                               NewLineOnAttributes = true,
+                               Indent = true,
+                       };
+
+                       using (var writer = XmlWriter.Create ("TestResult-profiler-stress.xml", settings)) {
+                               writer.WriteStartDocument ();
+                               writer.WriteComment ("This file represents the results of running a test suite");
+
+                               writer.WriteStartElement ("test-results");
+                               writer.WriteAttributeString ("name", "profiler-stress-tests.dummy");
+                               writer.WriteAttributeString ("total", results.Count.ToString ());
+                               writer.WriteAttributeString ("failures", failures.ToString ());
+                               writer.WriteAttributeString ("not-run", "0");
+                               writer.WriteAttributeString ("date", DateTime.Now.ToString ("yyyy-MM-dd"));
+                               writer.WriteAttributeString ("time", DateTime.Now.ToString ("HH:mm:ss"));
+
+                               writer.WriteStartElement ("environment");
+                               writer.WriteAttributeString ("nunit-version", "2.4.8.0");
+                               writer.WriteAttributeString ("clr-version", Environment.Version.ToString ());
+                               writer.WriteAttributeString ("os-version", Environment.OSVersion.ToString ());
+                               writer.WriteAttributeString ("platform", Environment.OSVersion.Platform.ToString ());
+                               writer.WriteAttributeString ("cwd", Environment.CurrentDirectory);
+                               writer.WriteAttributeString ("machine-name", Environment.MachineName);
+                               writer.WriteAttributeString ("user", Environment.UserName);
+                               writer.WriteAttributeString ("user-domain", Environment.UserDomainName);
+                               writer.WriteEndElement ();
+
+                               writer.WriteStartElement ("culture-info");
+                               writer.WriteAttributeString ("current-culture", CultureInfo.CurrentCulture.Name);
+                               writer.WriteAttributeString ("current-uiculture", CultureInfo.CurrentUICulture.Name);
+                               writer.WriteEndElement ();
+
+                               writer.WriteStartElement ("test-suite");
+                               writer.WriteAttributeString ("name", "profiler-stress-tests.dummy");
+                               writer.WriteAttributeString ("success", (failures + timeouts == 0).ToString ());
+                               writer.WriteAttributeString ("time", ((int) sw.Elapsed.TotalSeconds).ToString ());
+                               writer.WriteAttributeString ("asserts", (failures + timeouts).ToString ());
+                               writer.WriteStartElement ("results");
+
+                               writer.WriteStartElement ("test-suite");
+                               writer.WriteAttributeString ("name", "MonoTests");
+                               writer.WriteAttributeString ("success", (failures + timeouts == 0).ToString ());
+                               writer.WriteAttributeString ("time", ((int) sw.Elapsed.TotalSeconds).ToString ());
+                               writer.WriteAttributeString ("asserts", (failures + timeouts).ToString ());
+                               writer.WriteStartElement ("results");
+
+                               writer.WriteStartElement ("test-suite");
+                               writer.WriteAttributeString ("name", "profiler-stress");
+                               writer.WriteAttributeString ("success", (failures + timeouts == 0).ToString ());
+                               writer.WriteAttributeString ("time", ((int) sw.Elapsed.TotalSeconds).ToString ());
+                               writer.WriteAttributeString ("asserts", (failures + timeouts).ToString ());
+                               writer.WriteStartElement ("results");
+
+                               foreach (var result in results) {
+                                       var timeoutStr = result.ExitCode == null ? "_timeout" : string.Empty;
+
+                                       writer.WriteStartElement ("test-case");
+                                       writer.WriteAttributeString ("name", $"MonoTests.profiler-stress.{result.Benchmark.Name}{timeoutStr}");
+                                       writer.WriteAttributeString ("executed", "True");
+                                       writer.WriteAttributeString ("success", (result.ExitCode == 0).ToString ());
+                                       writer.WriteAttributeString ("time", ((int) result.Stopwatch.Elapsed.TotalSeconds).ToString ());
+                                       writer.WriteAttributeString ("asserts", result.ExitCode == 0 ? "0" : "1");
+
+                                       if (result.ExitCode != 0) {
+                                               writer.WriteStartElement ("failure");
+
+                                               writer.WriteStartElement ("message");
+                                               writer.WriteCData (FilterInvalidXmlChars (result.StandardOutput.ToString ()));
+                                               writer.WriteEndElement ();
+
+                                               writer.WriteStartElement ("stack-trace");
+                                               writer.WriteCData (FilterInvalidXmlChars (result.StandardError.ToString ()));
+                                               writer.WriteEndElement ();
+
+                                               writer.WriteEndElement ();
+                                       }
+
+                                       writer.WriteEndElement ();
+                               }
+
+                               writer.WriteEndElement ();
+                               writer.WriteEndElement ();
+
+                               writer.WriteEndElement ();
+                               writer.WriteEndElement ();
+
+                               writer.WriteEndElement ();
+                               writer.WriteEndElement ();
+
+                               writer.WriteEndElement ();
+
+                               writer.WriteEndDocument ();
+                       }
+
+                       var failureStr = failures + timeouts != 0 ? $" ({failures} failures, {timeouts} timeouts)" : string.Empty;
+
+                       Console.ForegroundColor = failures + timeouts != 0 ? ConsoleColor.Red : ConsoleColor.Green;
+                       Console.WriteLine ($"[{sw.Elapsed.ToString ("G")}] Finished with {successes}/{results.Count} passing tests{failureStr}");
                        Console.ResetColor ();
 
-                       return failures;
+                       return failures + timeouts;
                }
        }
 }
diff --git a/appveyor.yml b/appveyor.yml
deleted file mode 100644 (file)
index 8fa713a..0000000
+++ /dev/null
@@ -1,79 +0,0 @@
-#
-# Appveyor configuration file for CI build of Mono on Windows (under Cygwin)
-#
-# For further details see http://www.appveyor.com
-#
-
-#
-# Custom environment variables
-#
-environment:
-    global:
-        CYG_ROOT: C:\cygwin
-        CYG_MIRROR: http://cygwin.mirror.constant.com
-        CYG_CACHE: C:\cygwin\var\cache\setup
-        CYG_BASH: C:\cygwin\bin\bash
-
-#
-# Cache Cygwin files to speed up build
-#
-cache:
-    - '%CYG_CACHE%'
-
-#
-# Do a shallow clone of the repo to speed up build
-#
-clone_depth: 1
-
-#
-# Initialisation prior to pulling the Mono repository
-# Attempt to ensure we don't try to convert line endings to Win32 CRLF as this will cause build to fail
-#
-init:
-    - git config --global core.autocrlf input
-
-#
-# Install needed build dependencies
-# 
-install:
-    - ps: 'Start-FileDownload "http://cygwin.com/setup-x86.exe" -FileName "setup-x86.exe"'
-    - 'setup-x86.exe --quiet-mode --no-shortcuts --only-site --root "%CYG_ROOT%" --site "%CYG_MIRROR%" --local-package-dir "%CYG_CACHE%" --packages autoconf,automake,bison,gcc-core,gcc-g++,mingw-runtime,mingw-binutils,mingw-gcc-core,mingw-gcc-g++,mingw-pthreads,mingw-w32api,libtool,make,python,gettext-devel,gettext,intltool,libiconv,pkg-config,git,curl,libxslt > NUL 2>&1'
-    - '%CYG_BASH% -lc "cygcheck -dc cygwin"'
-
-# Cygwin build script
-#
-# NOTES:
-#
-# The stdin/stdout file descriptor appears not to be valid for the Appveyor
-# build which causes failures as certain functions attempt to redirect 
-# default file handles. Ensure a dummy file descriptor is opened with 'exec'.
-#
-build_script:
-    - 'echo Building...'
-    - '%CYG_BASH% -lc "cd $APPVEYOR_BUILD_FOLDER; exec 0</dev/null; ./autogen.sh --prefix=/usr/local --host=i686-pc-mingw32"'
-    - '%CYG_BASH% -lc "cd $APPVEYOR_BUILD_FOLDER; exec 0</dev/null; make get-monolite-latest"'
-    - '%CYG_BASH% -lc "cd $APPVEYOR_BUILD_FOLDER; exec 0</dev/null; make -j2"'
-    - 'echo Installing...'
-    - 'mkdir %APPVEYOR_BUILD_FOLDER%\install'
-    - '%CYG_BASH% -lc "export CYGWIN=winsymlinks:native; mount \"$APPVEYOR_BUILD_FOLDER\install\" /usr/local; cd $APPVEYOR_BUILD_FOLDER; exec 0</dev/null; make install; umount /usr/local"'
-
-#
-# Disable tests for now
-# 
-test: off
-
-#
-# Only build the master branch
-#
-branches:
-  only:
-    - master
-
-#
-# NOTE: Currently this is the Mono installation tree. In future we will create an installation package artifact.
-#       It has to be relative to the project path. Thus we have installed to within the build tree.
-#
-artifacts:
-    - path: install
-      name: mono-binaries
-      type: zip
index ca291449faa75352e992bcd53f77bdafa3bc9ecc..491e142eb5056354f8b63eaf4e4f3ad67afe6090 100644 (file)
@@ -52,6 +52,8 @@ CPPFLAGS_FOR_LIBGC=$CPPFLAGS
 CFLAGS_FOR_LIBGC=$CFLAGS
 CPPFLAGS_FOR_EGLIB=$CPPFLAGS
 CFLAGS_FOR_EGLIB=$CFLAGS
+CPPFLAGS_FOR_BTLS=$CPPFLAGS
+CFLAGS_FOR_BTLS=$CFLAGS
 
 # libgc uses some deprecated APIs
 CFLAGS_FOR_LIBGC="$CFLAGS -Wno-deprecated-declarations"
@@ -349,6 +351,10 @@ if test x$target_win32 = xyes; then
    AC_DEFINE(TARGET_WIN32, 1, [Target Platform is Win32])
 fi
 
+# Defined for all targets/platforms using classic Windows API support.
+AC_DEFINE(HAVE_CLASSIC_WINAPI_SUPPORT, 1, [Use classic Windows API support])
+AC_DEFINE(HAVE_UWP_WINAPI_SUPPORT, 0, [Don't use UWP Windows API support])
+
 AC_SUBST(extra_runtime_ldflags)
 AM_CONDITIONAL(HOST_WIN32, test x$host_win32 = xyes)
 AM_CONDITIONAL(TARGET_WIN32, test x$target_win32 = xyes)
@@ -1160,20 +1166,6 @@ AC_COMPILE_IFELSE([
    AC_MSG_RESULT(no)
 ])
 
-AC_MSG_CHECKING(for deprecated __attribute__)
-AC_TRY_COMPILE([
-     int doit (void) __attribute__ ((deprecated));
-     int doit (void) { return 0; }
-], [
-       return 0;
-], [
-   have_deprecated=yes
-   AC_MSG_RESULT(yes)
-], [
-   have_deprecated=no
-   AC_MSG_RESULT(no)
-])
-
 dnl
 dnl Boehm GC configuration
 dnl
@@ -2670,12 +2662,6 @@ fi
 
 AC_ARG_ENABLE(bcl-opt, [  --disable-bcl-opt    BCL is compiled with no optimizations (allows accurate BCL debugging)], test_bcl_opt=$enableval, test_bcl_opt=yes)
 
-AC_ARG_ENABLE(perf-events, [  --enable-perf-events Enable using `perf` for profiling on Linux], test_perf_events=$enableval, test_perf_events=no)
-if test "x$test_perf_events" = "xyes"; then
-       AC_DEFINE(ENABLE_PERF_EVENTS, 1, [Enable using `perf` for profiling on Linux])
-       AC_SUBST(ENABLE_PERF_EVENTS)
-fi
-
 AC_MSG_CHECKING([if big-arrays are to be enabled])
 AC_ARG_ENABLE(big-arrays,  [  --enable-big-arrays      Enable the allocation and indexing of arrays greater than Int32.MaxValue], enable_big_arrays=$enableval, enable_big_arrays=no)
 if test "x$enable_big_arrays" = "xyes" ; then
@@ -2951,6 +2937,8 @@ sizeof_register="SIZEOF_VOID_P"
 
 jit_wanted=true
 boehm_supported=true
+BTLS_SUPPORTED=no
+BTLS_PLATFORM=
 case "$host" in
        mips*)
                TARGET=MIPS;
@@ -3003,9 +2991,13 @@ case "$host" in
                        ;;
                  linux*)
                        AOT_SUPPORTED="yes"
+                       BTLS_SUPPORTED=yes
+                       BTLS_PLATFORM=i386
                        ;;
                  darwin*)
                        AOT_SUPPORTED="yes"
+                       BTLS_SUPPORTED=yes
+                       BTLS_PLATFORM=i386
                        ;;
                  openbsd*|freebsd*|kfreebsd-gnu*)
                        ;;
@@ -3021,9 +3013,13 @@ case "$host" in
                case $host_os in
                  linux*)
                        AOT_SUPPORTED="yes"
+                       BTLS_SUPPORTED=yes
+                       BTLS_PLATFORM=x86_64
                        ;;
                  darwin*)
                        AOT_SUPPORTED="yes"
+                       BTLS_SUPPORTED=yes
+                       BTLS_PLATFORM=x86_64
                        ;;
                  openbsd*|freebsd*|kfreebsd-gnu*)
                        ;;
@@ -3144,6 +3140,7 @@ HOST=$TARGET
 if test "x$host" != "x$target"; then
    AC_DEFINE(MONO_CROSS_COMPILE,1,[The runtime is compiled for cross-compiling mode])
    enable_mcs_build=no
+   BTLS_SUPPORTED=no
    case "$target" in
    arm*-darwin*)
                TARGET=ARM;
@@ -3429,10 +3426,12 @@ if test "x$target_mach" = "xyes"; then
          AC_DEFINE(TARGET_WATCHOS,1,[The JIT/AOT targets WatchOS])
          CPPFLAGS_FOR_LIBGC="$CPPFLAGS_FOR_LIBGC -DTARGET_WATCHOS"
          CFLAGS_FOR_LIBGC="$CFLAGS_FOR_LIBGC -DTARGET_WATCHOS"
+         BTLS_SUPPORTED=no
    elif test "x$TARGET" = "xARM" -o "x$TARGET" = "xARM64"; then
          AC_DEFINE(TARGET_IOS,1,[The JIT/AOT targets iOS])
          CPPFLAGS_FOR_LIBGC="$CPPFLAGS_FOR_LIBGC -DTARGET_IOS"
          CFLAGS_FOR_LIBGC="$CFLAGS_FOR_LIBGC -DTARGET_IOS"
+         BTLS_SUPPORTED=no
    else
        AC_TRY_COMPILE([#include "TargetConditionals.h"],[
        #if TARGET_IPHONE_SIMULATOR == 1 || TARGET_OS_IPHONE == 1
@@ -3447,6 +3446,7 @@ if test "x$target_mach" = "xyes"; then
           AC_DEFINE(TARGET_IOS,1,[The JIT/AOT targets iOS])
           CPPFLAGS_FOR_LIBGC="$CPPFLAGS_FOR_LIBGC -DTARGET_IOS"
           CFLAGS_FOR_LIBGC="$CFLAGS_FOR_LIBGC -DTARGET_IOS"
+          BTLS_SUPPORTED=no
        ])
        fi
    AC_DEFINE(TARGET_MACH,1,[The JIT/AOT targets Apple platforms])
@@ -3754,6 +3754,45 @@ if test ${TARGET} = unknown; then
        AC_MSG_WARN("mono has not been ported to $host: some things may not work.")
 fi
 
+if test "x$platform_android" = "xyes"; then
+       case "x${TARGET}" in
+       xARM)
+               case "x$arm_ver" in
+               xARMv5)
+                       BTLS_SUPPORTED=yes
+                       BTLS_PLATFORM=android-armv5
+                       ;;
+               xARMv6)
+                       BTLS_SUPPORTED=yes
+                       BTLS_PLATFORM=android-armv6
+                       ;;
+               xARMv7)
+                       BTLS_SUPPORTED=yes
+                       BTLS_PLATFORM=android-armv7
+                       ;;
+               *)
+                       BTLS_SUPPORTED=no
+                       ;;
+               esac
+               ;;
+       xARM64)
+               BTLS_SUPPORTED=yes
+               BTLS_PLATFORM=android-v8a
+               ;;
+       xX86)
+               BTLS_SUPPORTED=yes
+               BTLS_PLATFORM=android-x86
+               ;;
+       xAMD64)
+               BTLS_SUPPORTED=yes
+               BTLS_PLATFORM=android-x64
+               ;;
+       *)
+               BTLS_SUPPORTED=no
+               ;;
+       esac
+fi
+
 if test ${ACCESS_UNALIGNED} = no; then
        CPPFLAGS="$CPPFLAGS -DNO_UNALIGNED_ACCESS"
 fi
@@ -3876,6 +3915,88 @@ else
 fi
 AC_SUBST(LIBMONO_LA)
 
+dnl **************
+dnl ***  Btls  ***
+dnl **************
+
+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)
+
+btls_android=no
+if test "x$enable_btls" = "xyes"; then
+       AC_PATH_PROG(CMAKE, [cmake], [no], [$PATH:/Applications/CMake.app/Contents/bin:/usr/local/bin])
+       if test "x$CMAKE" = "xno"; then
+               AC_MSG_ERROR("cmake not found")
+       fi
+
+       BTLS_ROOT=`cd $srcdir && pwd`/external/boringssl
+       AC_SUBST(BTLS_ROOT)
+
+       btls_arch=
+       btls_cflags=
+       BTLS_CMAKE_ARGS=
+
+       case "$BTLS_PLATFORM" in
+       i386)
+               btls_arch=i386
+               btls_cflags="-m32"
+               case $host_os in
+                       darwin*)
+                               btls_cflags="$btls_cflags -arch i386"
+               esac
+               ;;
+       x86_64)
+               btls_arch=x86_64
+               ;;
+       android-armv5)
+               BTLS_CMAKE_ARGS="-DANDROID_ABI=\"armeabi\" -DANDROID_NATIVE_API_LEVEL=12"
+               ;;
+       android-armv6)
+               BTLS_CMAKE_ARGS="-DANDROID_ABI=\"armeabi\" -DANDROID_NATIVE_API_LEVEL=12"
+               ;;
+       android-armv7)
+               BTLS_CMAKE_ARGS="-DANDROID_ABI=\"armeabi-v7a\" -DANDROID_NATIVE_API_LEVEL=12"
+               ;;
+       android-v8a)
+               BTLS_CMAKE_ARGS="-DANDROID_ABI=\"arm64-v8a\" -DANDROID_NATIVE_API_LEVEL=12"
+               ;;
+       android-x86)
+               BTLS_CMAKE_ARGS="-DANDROID_ABI=\"x86\" -DANDROID_NATIVE_API_LEVEL=12"
+               ;;
+       android-x64)
+               BTLS_CMAKE_ARGS="-DANDROID_ABI=\"x86_64\" -DANDROID_NATIVE_API_LEVEL=12"
+               ;;
+       *)
+               AC_MSG_ERROR(Invalid BTLS platform)
+       esac
+
+       if test "x$platform_android" = "xyes"; then
+               btls_android=yes
+               BTLS_CMAKE_ARGS="$BTLS_CMAKE_ARGS -DCMAKE_TOOLCHAIN_FILE=$BTLS_ROOT/util/android-cmake/android.toolchain.cmake"
+               if test "x$with_btls_android_ndk" != "x"; then
+                       BTLS_CMAKE_ARGS="$BTLS_CMAKE_ARGS -DANDROID_NDK=\"$with_btls_android_ndk\""
+               fi
+       fi
+
+       if test "x$btls_arch" != "x"; then
+               BTLS_CMAKE_ARGS="$BTLS_CMAKE_ARGS -DBTLS_ARCH=\"$btls_arch\""
+       fi
+
+       BTLS_CFLAGS="$CPPFLAGS_FOR_BTLS $btls_cflags"
+       AC_SUBST(BTLS_ARCH)
+       AC_SUBST(BTLS_CFLAGS)
+       AC_SUBST(BTLS_PLATFORM)
+       AC_SUBST(BTLS_CMAKE_ARGS)
+
+       AC_DEFINE(HAVE_BTLS, 1, [BoringTls is supported])
+else
+       enable_btls=no
+fi
+
+AM_CONDITIONAL(BTLS_ANDROID, test x$btls_android = xyes)
+
 if test x$DISABLE_MCS_DOCS = xyes; then
    docs_dir=""
 else
@@ -4112,6 +4233,7 @@ llvm/Makefile
 scripts/mono-find-provides
 scripts/mono-find-requires
 mono/Makefile
+mono/btls/Makefile
 mono/utils/Makefile
 mono/metadata/Makefile
 mono/dis/Makefile
@@ -4283,6 +4405,15 @@ fi
 
 libgdiplus_msg=${libgdiplus_loc:-assumed to be installed}
 
+btls_platform_string=
+if test x$enable_btls = xyes; then
+       if test x$btls_android = xyes; then
+               btls_platform_string=" (android:$BTLS_PLATFORM)"
+       else
+               btls_platform_string=" ($BTLS_PLATFORM)"
+       fi
+fi
+
 echo "
         mcs source:    $mcsdir
 
@@ -4308,6 +4439,7 @@ echo "
        JNI support:     $jdk_headers_found
        libgdiplus:      $libgdiplus_msg
        zlib:            $zlib_msg
+       BTLS:            $enable_btls$btls_platform_string
        $disabled
 "
 if test x$with_static_mono = xno -a "x$host_win32" != "xyes"; then
index a33dcb846b2746e4f47275e54c43280cfa982e1c..89f85d18e590434088b672fc593b3f2012052ead 100644 (file)
@@ -130,6 +130,10 @@ AM_CONDITIONAL(TARGET_WIN32, test x$OS = xWIN32)
 AM_CONDITIONAL(PLATFORM_DARWIN, test x$platform_darwin = xyes)
 AM_CONDITIONAL(PLATFORM_ANDROID, test x$platform_android = xyes)
 
+# Defined for all targets/platforms using classic Windows API support.
+AC_DEFINE(HAVE_CLASSIC_WINAPI_SUPPORT, 1, [Use classic Windows API support])
+AC_DEFINE(HAVE_UWP_WINAPI_SUPPORT, 0, [Don't use UWP Windows API support])
+
 AC_CHECK_SIZEOF(int)
 AC_CHECK_SIZEOF(void *)
 AC_CHECK_SIZEOF(long)
index 2dde793dfeec7409333f5d7468a1278ae0cb5286..61e23cbe442856e8cabea65ed09ac4e6ec3d3c3c 100644 (file)
@@ -35,6 +35,7 @@
 #include <sys/stat.h>
 #include <fcntl.h>
 #include <sys/types.h>
+#include <direct.h>
 
 #ifdef G_OS_WIN32
 #include <io.h>
@@ -68,6 +69,26 @@ int mkstemp (char *tmp_template)
        return fd;
 }
 
+gchar *
+g_mkdtemp (char *tmp_template)
+{
+       gunichar2* utf16_template;
+
+       utf16_template  = u8to16 (tmp_template);
+
+       utf16_template = _wmktemp(utf16_template);
+       if (utf16_template && *utf16_template) {
+               if (_wmkdir (utf16_template) == 0){
+                       char *ret = u16to8 (utf16_template);
+                       g_free (utf16_template);
+                       return ret;
+               }
+       }
+
+       g_free (utf16_template);
+       return NULL;
+}
+            
 #ifdef _MSC_VER
 #pragma warning(disable:4701)
 #endif
index 23781c168526edd95498a3260697cbd76af23ff6..1bc8506310edfa9ea570c94ccbed620266ead00c 100644 (file)
@@ -887,6 +887,12 @@ gboolean   g_file_test (const gchar *filename, GFileTest test);
 #define g_ascii_strtod strtod
 #define g_ascii_isalnum isalnum
 
+#ifdef WIN32
+gchar *g_mkdtemp (gchar *tmpl);
+#else
+#define g_mkdtemp mkdtemp
+#endif
+
 /*
  * Pattern matching
  */
@@ -1062,6 +1068,10 @@ glong     g_utf8_pointer_to_offset (const gchar *str, const gchar *pos);
 #define _EGLIB_MINOR  0
  
 #define GLIB_CHECK_VERSION(a,b,c) ((a < _EGLIB_MAJOR) || (a == _EGLIB_MAJOR && (b < _EGLIB_MIDDLE || (b == _EGLIB_MIDDLE && c <= _EGLIB_MINOR))))
+
+#define G_HAVE_API_SUPPORT(x) (x)
+#define G_UNSUPPORTED_API "%s:%d: '%s' not supported.", __FILE__, __LINE__
+#define g_unsupported_api(name) G_STMT_START { g_warning (G_UNSUPPORTED_API, name); } G_STMT_END
  
 G_END_DECLS
 
index 5baec653c336451d8c9075dd76f69c233d4f9da3..f9fdb668f2d89d842c411e7af76d9d4a410ccfb9 100644 (file)
  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  */
 
+#include <config.h>
+
 #include <stdlib.h>
 #include <glib.h>
 
 #include <windows.h>
-#ifdef _MSC_VER
+#if _MSC_VER && G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 #include <shlobj.h>
 #endif
 #include <direct.h>
 #include <io.h>
+#include <assert.h>
 
 const gchar *
 g_getenv(const gchar *variable)
@@ -87,6 +90,7 @@ g_unsetenv(const gchar *variable)
        g_free(var);
 }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 gchar*
 g_win32_getlocale(void)
 {
@@ -98,6 +102,28 @@ g_win32_getlocale(void)
        return g_strdup (buf);
 }
 
+#else /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+gchar*
+g_win32_getlocale(void)
+{
+       gunichar2 buf[19];
+       gint ccBuf = GetLocaleInfoEx (LOCALE_NAME_USER_DEFAULT, LOCALE_SISO639LANGNAME, buf, 9);
+       assert (ccBuf <= 9);
+       if (ccBuf != 0) {
+               buf[ccBuf - 1] = L'-';
+               ccBuf = GetLocaleInfoEx (LOCALE_NAME_USER_DEFAULT, LOCALE_SISO3166CTRYNAME, buf + ccBuf, 9);
+               assert (ccBuf <= 9);
+       }
+
+       // Check for GetLocaleInfoEx failure.
+       if (ccBuf == 0)
+               buf[0] = L'\0';
+
+       return u16to8 (buf);
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
 gboolean
 g_path_is_absolute (const char *filename)
 {
@@ -121,7 +147,7 @@ g_get_home_dir (void)
 {
        gchar *home_dir = NULL;
 
-#ifdef _MSC_VER
+#if _MSC_VER && G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
        PWSTR profile_path = NULL;
        HRESULT hr = SHGetKnownFolderPath (&FOLDERID_Profile, KF_FLAG_DEFAULT, NULL, &profile_path);
        if (SUCCEEDED(hr)) {
@@ -180,4 +206,3 @@ g_get_tmp_dir (void)
        }
        return tmp_dir;
 }
-
index 24010b58915e367699e1581e9431eeefbfff310c..d1dca5303eb7d174fa98c154a35901844105dd5b 100644 (file)
@@ -28,6 +28,7 @@
  * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  */
+#include <config.h>
 #include <glib.h>
 #include <gmodule.h>
 #include <windows.h>
@@ -68,6 +69,7 @@ g_module_open (const gchar *file, GModuleFlags flags)
        return module;
 }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 static gpointer
 w32_find_symbol (const gchar *symbol_name)
 {
@@ -115,6 +117,17 @@ w32_find_symbol (const gchar *symbol_name)
        return NULL;
 }
 
+#else /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+static gpointer
+w32_find_symbol (const gchar *symbol_name)
+{
+       g_unsupported_api ("EnumProcessModules");
+       SetLastError (ERROR_NOT_SUPPORTED);
+       return NULL;
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
 gboolean
 g_module_symbol (GModule *module, const gchar *symbol_name, gpointer *symbol)
 {
@@ -134,6 +147,7 @@ g_module_symbol (GModule *module, const gchar *symbol_name, gpointer *symbol)
        }
 }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 const gchar *
 g_module_error (void)
 {
@@ -151,6 +165,35 @@ g_module_error (void)
        return ret;
 }
 
+#elif G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)   /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+const gchar *
+g_module_error (void)
+{
+       gchar* 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
+
+const gchar *
+g_module_error (void)
+{
+       g_unsupported_api ("FormatMessage");
+       SetLastError (ERROR_NOT_SUPPORTED);
+       return NULL;
+}
+
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
 gboolean
 g_module_close (GModule *module)
 {
index 36d6d4acfb76ad52a1bca0da47bbcd6def49b9cd..f979f429ff7d4306c3b4a826c2c45712d2f37af4 100644 (file)
@@ -205,16 +205,36 @@ g_filename_from_utf8 (const gchar *utf8string, gssize len, gsize *bytes_read, gs
        return res;
 }
 
+#ifdef G_OS_WIN32
+extern WINBASEAPI UINT WINAPI GetACP(void);
 gboolean
 g_get_charset (G_CONST_RETURN char **charset)
 {
        if (my_charset == NULL) {
-#ifdef G_OS_WIN32
                static char buf [14];
+#if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
+               CPINFOEXA cp_info;
+               GetCPInfoExA (CP_ACP, 0, &cp_info);
+               sprintf (buf, "CP%u", cp_info.CodePage);
+#else
                sprintf (buf, "CP%u", GetACP ());
+#endif
                my_charset = buf;
                is_utf8 = FALSE;
-#else
+       }
+       
+       if (charset != NULL)
+               *charset = my_charset;
+
+       return is_utf8;
+}
+
+#else /* G_OS_WIN32 */
+
+gboolean
+g_get_charset (G_CONST_RETURN char **charset)
+{
+       if (my_charset == NULL) {
                /* These shouldn't be heap allocated */
 #if defined(HAVE_LOCALCHARSET_H)
                my_charset = locale_charset ();
@@ -222,7 +242,6 @@ g_get_charset (G_CONST_RETURN char **charset)
                my_charset = "UTF-8";
 #endif
                is_utf8 = strcmp (my_charset, "UTF-8") == 0;
-#endif
        }
        
        if (charset != NULL)
@@ -230,6 +249,7 @@ g_get_charset (G_CONST_RETURN char **charset)
 
        return is_utf8;
 }
+#endif /* G_OS_WIN32 */
 
 gchar *
 g_locale_to_utf8 (const gchar *opsysstring, gssize len, gsize *bytes_read, gsize *bytes_written, GError **error)
index 23e7638bdbdbe9929fe7eccd6096a0faf7498596..806e8b66d3f2387f45078ae70af458bf19fca5a1 100644 (file)
 
 #include <config.h>
 #include "test.h"
+
+#ifndef DRIVER_EXTERNAL_TESTS
 #include "tests.h"
+#endif
 
 #include <stdio.h>
 #ifdef HAVE_GETOPT_H
@@ -102,7 +105,11 @@ static void print_help(char *s)
        printf("\n");
 }
 
+#ifdef DRIVER_EXTERNAL_MAIN
+gint run_tests_main(gint argc, gchar **argv)
+#else
 gint main(gint argc, gchar **argv)
+#endif
 {
        gint i, j, c, iterations = 1;
        StringArray *tests_to_run = NULL;
index 04e8d4075ce134087eb22387b8b0da242f4ab482..3a64e217ef0c7a82c260e789a8ece0c13d41cc5d 100755 (executable)
 #define VERSION "0.1"
 
 #define HAVE_STRTOK_R 1
+
+#ifndef HAVE_WINAPI_FAMILY_SUPPORT
+
+#define HAVE_WINAPI_FAMILY_SUPPORT
+
+/* WIN API Family support */
+#include <winapifamily.h>
+
+#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
+       #define HAVE_CLASSIC_WINAPI_SUPPORT 1
+       #define HAVE_UWP_WINAPI_SUPPORT 0
+#elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)
+       #define HAVE_CLASSIC_WINAPI_SUPPORT 0
+       #define HAVE_UWP_WINAPI_SUPPORT 1
+#else
+       #define HAVE_CLASSIC_WINAPI_SUPPORT 0
+       #define HAVE_UWP_WINAPI_SUPPORT 0
+#endif
+
+#endif
 #endif
diff --git a/external/boringssl b/external/boringssl
new file mode 160000 (submodule)
index 0000000..432738a
--- /dev/null
@@ -0,0 +1 @@
+Subproject commit 432738a3c938b4f751307301c6aa07f2027a8864
diff --git a/external/corefx b/external/corefx
new file mode 160000 (submodule)
index 0000000..b1aa1d9
--- /dev/null
@@ -0,0 +1 @@
+Subproject commit b1aa1d92ca33d0cb8ffbac9b6ff73b284db6bbf1
index 9f44f259bf5059df6c8019948ea75313bd09a9fb..367864ef810859ae3ce652864233b35f2dd5fdbe 160000 (submodule)
@@ -1 +1 @@
-Subproject commit 9f44f259bf5059df6c8019948ea75313bd09a9fb
+Subproject commit 367864ef810859ae3ce652864233b35f2dd5fdbe
index 95861e0aeab8e58ebbaaf64c8758ffe813b0f818..305cfcc7f7224d787f72e728310c6a0e66c49d43 100644 (file)
@@ -159,10 +159,16 @@ flag to bundle all available encodings.
 Or you can use a comma delimited list of the workds CJK, MidWest,
 Other, Rare and West to specificy which encoding assemblies to distribute.
 .TP
-.TP
 .I "-L path"
 Adds the `path' do the search list for assemblies.  The rules are the
 same as for the compiler -lib: or -L flags.
+.TP
+.I "--library [LIB,]PATH"
+Embeds the dynamic library file pointed to by `PATH' and optionally
+give it the name `LIB' into the bundled executable.   This is used to
+ship native library dependencies that are unpacked at startup and
+loaded from the runtime.
+.TP
 .I "--lists-targets"
 Lists all of the available local cross compilation targets available
 as precompiled binaries on the Mono distribution server.
index c4589ea70c7243f74525d5669f342c983f24f39b..08a93ac91823901085ca08edf8daa9d6b08b2363 100644 (file)
@@ -332,6 +332,12 @@ Currently this merely ensures that you are running either the
 \fBMONO_ENV_OPTIONS\fR environment variable to force all of your child
 processes to use one particular kind of GC with the Mono runtime.
 .TP
+\fB--gc-debug=[options]\fR
+Command line equivalent of the \fBMONO_GC_DEBUG\fR environment variable.
+.TP
+\fB--gc-params=[options]\fR
+Command line equivalent of the \fBMONO_GC_PARAMS\fR environment variable.
+.TP
 \fB--arch=32\fR, \fB--arch=64\fR
 (Mac OS X only): Selects the bitness of the Mono binary used, if
 available. If the binary used is already for the selected bitness, nothing
index c4fd545dd104c5413ea6a5bcb627a25bccf6fec1..f19a02aa14ea8679cda72518cc466f57ee5a4ad8 100644 (file)
@@ -92,7 +92,7 @@ provided by the Mono runtime and write them to a file named
 \f[I]output.mlpd\f[].
 When no option is specified, it is equivalent to using:
 .PP
-\f[B]--profile=log:calls,alloc,output=output.mlpd,maxframes=8,calldepth=100\f[]
+\f[B]--profile=log:calls,alloc,output=output.mlpd,maxframes=32,calldepth=100\f[]
 .PP
 The following options can be used to modify this default behaviour.
 Each option is separated from the next by a \f[B],\f[] character,
@@ -139,41 +139,16 @@ garbage collections
 to the control port
 .RE
 .IP \[bu] 2
-\f[I]sample[=TYPE[/FREQ]]\f[]: collect statistical samples of the
+\f[I]sample[=FREQ]\f[]: collect statistical samples of the
 program behaviour.
 The default is to collect a 100 times per second (100 Hz) the
 instruction pointer.
-This is equivalent to the value \[lq]cycles/100\[rq].
+This is equivalent to the value \[lq]100\[rq].
 A value of zero for \f[I]FREQ\f[] effectively disables sampling.
-On some systems, like with recent Linux kernels, it is possible to
-cause the sampling to happen for other events provided by the
-performance counters of the cpu.
-In this case, \f[I]TYPE\f[] can be one of:
-.RS 2
-.IP \[bu] 2
-\f[I]cycles\f[]: processor cycles
-.IP \[bu] 2
-\f[I]instr\f[]: executed instructions
-.IP \[bu] 2
-\f[I]cacherefs\f[]: cache references
-.IP \[bu] 2
-\f[I]cachemiss\f[]: cache misses
-.IP \[bu] 2
-\f[I]branches\f[]: executed branches
-.IP \[bu] 2
-\f[I]branchmiss\f[]: mispredicted branches
-.RE
-.IP \[bu] 2
-\f[I]time=TIMER\f[]: use the TIMER timestamp mode.
-TIMER can have the following values:
-.RS 2
-.IP \[bu] 2
-\f[I]fast\f[]: a usually faster but possibly more inaccurate timer
-.RE
 .IP \[bu] 2
 \f[I]maxframes=NUM\f[]: when a stack trace needs to be performed,
 collect \f[I]NUM\f[] frames at the most.
-The default is 8.
+The default is 32.
 .IP \[bu] 2
 \f[I]maxsamples=NUM\f[]: stop allocating reusable sample events
 once \f[I]NUM\f[] events have been allocated (a value of zero for
@@ -234,16 +209,15 @@ The following commands are available:
 \f[I]heapshot\f[]: perform a heapshot as soon as possible
 .RE
 .IP \[bu] 2
-\f[I]counters\f[]: sample counters values every 1 second. This allow
-a really lightweight way to have insight in some of the runtime key
-metrics. Counters displayed in non verbose mode are : Methods from AOT,
-Methods JITted using mono JIT, Methods JITted using LLVM, Total time
-spent JITting (sec), User Time, System Time, Total Time, Working Set,
-Private Bytes, Virtual Bytes, Page Faults and CPU Load Average (1min,
-5min and 15min).
+\f[I]nocounters\f[]: disables sampling of runtime and performance
+counters, which is normally done every 1 second.
 .IP \[bu] 2
 \f[I]coverage\f[]: collect code coverage data. This implies enabling
 the \f[I]calls\f[] option.
+.IP \[bu] 2
+\f[I]onlycoverage\f[]: can only be used with \f[I]coverage\f[]. This
+disables most other events so that the profiler mostly only collects
+coverage data.
 .RE
 .SS Analyzing the profile data
 .PP
@@ -274,10 +248,6 @@ with the \f[I]--maxframes=NUM\f[] option:
 The stack trace info will be available if method enter/leave events
 have been recorded or if stack trace collection wasn't explicitly
 disabled with the \f[I]maxframes=0\f[] profiler option.
-Note that the profiler will collect up to 8 frames by default at
-specific events when the \f[I]nocalls\f[] option is used, so in
-that case, if more stack frames are required in mprof-report, a
-bigger value for maxframes when profiling must be used, too.
 .PP
 The \f[I]--traces\f[] option also controls the reverse reference
 feature in the heapshot report: for each class it reports how many
@@ -487,15 +457,6 @@ option: especially if the managed heap is big, since every object
 needs to be inspected.
 The \f[I]MODE\f[] parameter of the \f[I]heapshot\f[] option can be
 used to reduce the frequency of the heap shots.
-.IP "\f[I]Reduce the timestamp overhead\f[]" 4
-.Sp
-On many operating systems or architectures what actually slows down
-profiling is the function provided by the system to get timestamp
-information.
-The \f[I]time=fast\f[] profiler option can be usually used to speed
-up this operation, but, depending on the system, time accounting
-may have some level of approximation (though statistically the data
-should be still fairly valuable).
 .SS Dealing with the size of the data files
 .PP
 When collecting a lot of information about a profiled program, huge
index b9e02f62b26855d207fe6bde66f9900f43b44d19..631b764bf9dd24608afc325f7d47d345ea34edee 100644 (file)
@@ -40,7 +40,7 @@ class X {
                if (!Version.TryParse (field.GetValue (null) as string, out version))
                        return 4;
 
-               if (version < new Version (3, 8))
+               if (version < new Version (4, 0))
                        return 5;
 
                return 0;
index b48617d66fabed49adcbffeccc0e89549afd6a8e..12b80615bdb7f0283c9127348d78b8e005c4b467 100644 (file)
@@ -65,7 +65,7 @@ do-profile-check: $(depsdir)/.stamp
                $(MAKE) -s do-profile-check-monolite ; \
            else \
                echo "*** The compiler '$(BOOTSTRAP_MCS)' doesn't appear to be usable." 1>&2; \
-                echo "*** You need Mono version 3.8 or better installed to build MCS" 1>&2 ; \
+                echo "*** You need Mono version 4.0 or better installed to build MCS" 1>&2 ; \
                 echo "*** Check mono README for information on how to bootstrap a Mono installation." 1>&2 ; \
                echo "*** The version of '$(BOOTSTRAP_MCS)' is: `$(BOOTSTRAP_MCS) --version`." 1>&2 ; \
                exit 1; fi; fi
@@ -74,17 +74,17 @@ do-profile-check: $(depsdir)/.stamp
 ifdef use_monolite
 
 do-profile-check-monolite:
-       echo "*** The contents of your 'monolite' directory may be out-of-date" 1>&2
-       echo "*** You may want to try 'make get-monolite-latest'" 1>&2
+       @echo "*** The contents of your 'monolite' directory may be out-of-date" 1>&2
+       @echo "*** You may want to try 'make get-monolite-latest'" 1>&2
        rm -f $(monolite_flag)
        exit 1
 
 else
 
 do-profile-check-monolite: $(depsdir)/.stamp
-       echo "*** The compiler '$(BOOTSTRAP_MCS)' doesn't appear to be usable." 1>&2
-       echo "*** Trying the 'monolite' directory." 1>&2
-       echo dummy > $(monolite_flag)
+       @echo "*** The compiler '$(BOOTSTRAP_MCS)' doesn't appear to be usable." 1>&2
+       @echo "*** Trying the 'monolite' directory." 1>&2
+       @echo dummy > $(monolite_flag)
        $(MAKE) do-profile-check
 
 endif
index 0242c20bf515ca05121382763c7a25f3d1d9e86d..4bba2f421ac849b4f0869f32b72a1b4d57f51e3c 100644 (file)
@@ -1,9 +1,11 @@
 include $(topdir)/build/profiles/monotouch.make
 
 PROFILE_MCS_FLAGS += \
+       -d:FEATURE_NO_BSD_SOCKETS \
        -d:MONOTOUCH_WATCH
 
 NO_THREAD_ABORT=1
 NO_THREAD_SUSPEND_RESUME=1
 NO_MULTIPLE_APPDOMAINS=1
 NO_PROCESS_START=1
+NO_MONO_SECURITY=1
index 7b3eb80a551dc7325b9cfde0edc5728899696bf2..e826c7e7e31e1b734fbd5625532536f3184d787a 100644 (file)
@@ -1,6 +1,7 @@
 include $(topdir)/build/profiles/monotouch_runtime.make
 
 PROFILE_MCS_FLAGS += \
+       -d:FEATURE_NO_BSD_SOCKETS \
        -d:MONOTOUCH_WATCH
 
 NO_THREAD_ABORT=1
@@ -8,3 +9,4 @@ NO_THREAD_SUSPEND_RESUME=1
 # The binding generator (bwatch) still needs to execute processes,
 # so we need a System.dll that can do that.
 #NO_PROCESS_START=1
+NO_MONO_SECURITY=1
index 6a0f53c9b66ec85abf6783009539ca992afb36a8..25fa02f1618cff00f166de0477247878ac456a8b 100644 (file)
@@ -26,7 +26,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if MONOTOUCH
+#if FULL_AOT_RUNTIME
 
 namespace System.Reflection.Emit
 {
index 9cc6712cb48a9aef4393ed1182f5fd9ca3ad0e4b..9fca03abafc330c36076aabe54e6c31614906bc0 100644 (file)
@@ -20,6 +20,6 @@
 // THE SOFTWARE.
 // 
 
-#if !MONOTOUCH
+#if !FULL_AOT_RUNTIME
 [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Reflection.Emit.DynamicMethod))]
 #endif
index 7c6c5d092f1d91b07ff931bff7d8b335c1838cd7..99e5ef51402044e78d1dc6c7032885e6e7edb1bf 100644 (file)
@@ -43,6 +43,12 @@ mobile_static_PARALLEL_SUBDIRS = $(monotouch_PARALLEL_SUBDIRS)
 net_4_x_SUBDIRS = $(common_DEPS_SUBDIRS) $(drawing_DEPS_SUBDIRS)
 net_4_x_PARALLEL_SUBDIRS = $(common_SUBDIRS)
 
+build_PARALLEL_SUBDIRS = System.Runtime System.Reflection System.Collections System.Resources.ResourceManager System.Globalization \
+System.Threading.Tasks System.Collections.Concurrent System.Text.Encoding System.IO System.Threading System.Diagnostics.Debug \
+System.Linq.Expressions System.Dynamic.Runtime System.Linq System.Threading.Tasks.Parallel System.Xml.ReaderWriter \
+System.Diagnostics.Tools System.Reflection.Primitives System.Runtime.Extensions System.Runtime.InteropServices System.Text.Encoding.Extensions \
+System.Runtime.Numerics System.Xml.XDocument System.Reflection.Extensions
+
 monodroid_SUBDIRS = $(monotouch_SUBDIRS)
 monodroid_PARALLEL_SUBDIRS = $(monotouch_PARALLEL_SUBDIRS)
 
index f9ff19f76daaef6fba55e1e370d13050e90cb521..45d9d4b4c832a289bd4571791ea34eb9a15cd67a 100644 (file)
@@ -1,6 +1,8 @@
 thisdir = class
 
-basic_SUBDIRS := corlib Mono.Security System System.XML System.Core 
+basic_SUBDIRS := corlib Mono.Security System System.XML System.Core
+
+pcl_facade_dirs := Facades
 
 # resgen is corlib specific so we need to wait until corlib is build
 # and build it just a step before first dll needs it
@@ -14,9 +16,11 @@ build_SUBDIRS :=  \
        Mono.Posix \
        System.Core \
        Mono.Cecil \
-       Mono.Cecil.Mdb
-
-pcl_facade_dirs := Facades
+       Mono.Cecil.Mdb \
+       System.ComponentModel.Composition.4.5 \
+       System.Numerics \
+       System.Xml.Linq \
+       $(pcl_facade_dirs)
 
 mobile_common_dirs := \
        corlib  \
@@ -51,9 +55,6 @@ mobile_common_dirs := \
        System.Xml.Serialization \
        Mono.CSharp     \
        Microsoft.CSharp \
-       Mono.Security.Providers.DotNet  \
-       Mono.Security.Providers.NewSystemSource \
-       Mono.Security.Providers.NewTls  \
        System.Runtime.InteropServices.RuntimeInformation       \
        System.Reflection.DispatchProxy \
        System.Xml.XPath.XmlDocument \
@@ -82,7 +83,7 @@ monodroid_dirs := \
 monotouch_dirs := \
        $(mobile_static_dirs)
 
-monotouch_watch_dirs := $(monotouch_dirs)
+monotouch_watch_dirs := $(filter-out Mono.Security Mono.Data.Tds,$(monotouch_dirs))
 monotouch_tv_dirs   := $(monotouch_dirs)
 
 monotouch_runtime_dirs := \
@@ -93,7 +94,7 @@ monotouch_runtime_dirs := \
        System.XML \
        Mono.CSharp
 
-monotouch_watch_runtime_dirs := $(monotouch_runtime_dirs)
+monotouch_watch_runtime_dirs := $(filter-out Mono.Security Mono.Data.Tds,$(monotouch_runtime_dirs))
 monotouch_tv_runtime_dirs := $(monotouch_runtime_dirs)
 
 xammac_4_5_dirs := \
@@ -140,10 +141,7 @@ xammac_4_5_dirs := \
        System.Data.Linq                \
        System.Net.Http \
        System.Net.Http.WebRequest \
-       Mono.Security.Providers.DotNet \
-       Mono.Security.Providers.OldTls \
-       Mono.Security.Providers.NewSystemSource \
-       Mono.Security.Providers.NewTls \
+       Mono.Btls.Interface \
        System.Runtime.InteropServices.RuntimeInformation \
        System.Reflection.Context       \
        System.Net.Http.WinHttpHandler  \
@@ -232,8 +230,6 @@ net_4_x_dirs := \
        System.Web.Http \
        System.Web.Http.SelfHost \
        System.Web.Http.WebHost \
-       Mono.Security.Providers.NewSystemSource \
-       Mono.Security.Providers.NewTls \
        System.Runtime.InteropServices.RuntimeInformation
 
 # These are the subdirs which depends on libs in net_4_x_dirs
@@ -241,6 +237,7 @@ net_4_x_dirs := \
 net_4_x_parallel_dirs := \
        PEAPI                           \
        I18N                            \
+       Mono.Btls.Interface             \
        Mono.Http                       \
        Mono.Cairo                      \
        Mono.Cecil                      \
@@ -277,8 +274,6 @@ net_4_x_parallel_dirs := \
        System.ComponentModel.Composition.4.5 \
        System.Windows \
        System.Xml.Serialization \
-       Mono.Security.Providers.DotNet \
-       Mono.Security.Providers.OldTls \
        System.DirectoryServices.Protocols      \
        RabbitMQ.Client                 \
        Microsoft.VisualC               \
@@ -349,6 +344,7 @@ DISTFILES = \
        MicrosoftAjaxLibrary/License.htm        \
        test-helpers/NetworkHelpers.cs  \
        test-helpers/SocketResponder.cs \
+       lib/$(monolite_dir)/basic.exe   \
        $(monolite_files)
 
 .PHONY: all-local $(STD_TARGETS:=-local)
@@ -357,21 +353,40 @@ all-local $(STD_TARGETS:=-local):
 
 all-local-aot:
 
-# Files needed to bootstrap C# compiler
-basic_files = basic.exe mscorlib.dll System.dll System.Xml.dll Mono.Security.dll System.Core.dll System.Security.dll System.Configuration.dll
-monolite_files = $(basic_files:%=lib/monolite/%)
+monolite_dir := monolite
 
-lib/monolite:
+# Files needed to bootstrap C# compiler
+build_files = mscorlib.dll System.dll System.Xml.dll Mono.Security.dll System.Core.dll System.Security.dll System.Configuration.dll \
+       System.Numerics.dll System.Xml.Linq.dll \
+       Facades/System.Collections.Concurrent.dll Facades/System.Linq.dll Facades/System.Runtime.dll Facades/System.Collections.dll     \
+       Facades/System.Reflection.Extensions.dll Facades/System.Text.Encoding.Extensions.dll Facades/System.Diagnostics.Debug.dll \
+       Facades/System.Reflection.Primitives.dll Facades/System.Text.Encoding.dll Facades/System.Diagnostics.Tools.dll Facades/System.Reflection.dll \
+       Facades/System.Threading.Tasks.Parallel.dll Facades/System.Dynamic.Runtime.dll Facades/System.Resources.ResourceManager.dll \
+       Facades/System.Threading.Tasks.dll Facades/System.Globalization.dll Facades/System.Runtime.Extensions.dll Facades/System.Threading.dll \
+       Facades/System.IO.dll Facades/System.Runtime.InteropServices.dll Facades/System.Xml.ReaderWriter.dll Facades/System.Linq.Expressions.dll \
+       Facades/System.Runtime.Numerics.dll Facades/System.Xml.XDocument.dll
+
+monolite_files = $(build_files:%=lib/$(monolite_dir)/%)
+
+lib/$(monolite_dir):
+lib/$(monolite_dir)/Facades:
        $(MKINSTALLDIRS) $@
 
-$(monolite_files): | lib/monolite
-$(monolite_files): lib/monolite/%: lib/basic/%
+$(monolite_files): | lib/$(monolite_dir)
+$(monolite_files): | lib/$(monolite_dir)/Facades
+$(monolite_files): lib/$(monolite_dir)/%: lib/build/%
        cp -p $< $@
 
-$(basic_files:%=lib/basic/%):
-       cd $(topdir) && $(MAKE) profile-do--basic--all NO_DIR_CHECK=1 SKIP_AOT=1
+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) lib/$(monolite_dir)/basic.exe
+
+dist-default: dist-monolite
 
-dist-default: $(monolite_files)
 dist-local: dist-default
 
 csproj-local:
index 1a4e4317421d460b5a13cc638b1514cddf5db232..2398184df6d706fb5fc9aefc0d9bfb3f4c8c4666 100644 (file)
@@ -24,6 +24,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
 using System;
+using System.IO;
 using Microsoft.Build.BuildEngine;
 using NUnit.Framework;
 
@@ -61,6 +62,11 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
                                </Project>
                        ";
 
+                       if (Path.DirectorySeparatorChar == '\\') {
+                               documentString = documentString.Replace ("/home", "c:/home");
+                               documentString = documentString.Replace ("/tmp", "c:/tmp");
+                       }
+
                        var engine = new Engine (Consts.BinPath);
                        var project = engine.CreateNewProject ();
                        project.LoadXml (documentString);
index 6c7919e6ae7db4d7c36cc02ad79cc4ceebc10ab3..459bb66e6d5cd3cde9d2007433d0e8aaecb1a480 100644 (file)
@@ -40,6 +40,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
        [TestFixture]
        public class TargetTest {
                
+               static bool isMono = Type.GetType ("Mono.Runtime", false) != null;
                Engine                  engine;
                Project                 project;
                
@@ -351,16 +352,16 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
 
                bool Build (string projectXml, ILogger logger)
                {
-                       if (Environment.OSVersion.Platform == PlatformID.Win32NT) {
+                       if (!isMono) {
                                var reader = new StringReader (projectXml);
                                var xml = XmlReader.Create (reader);
-                               return BuildOnWindows (xml, logger);
+                               return BuildOnDotNet (xml, logger);
                        } else {
-                               return BuildOnLinux (projectXml, logger);
+                               return BuildOnMono (projectXml, logger);
                        }
                }
 
-               bool BuildOnWindows (XmlReader reader, ILogger logger)
+               bool BuildOnDotNet (XmlReader reader, ILogger logger)
                {
                        var type = Type.GetType ("Microsoft.Build.Evaluation.ProjectCollection, Microsoft.Build, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
 
@@ -376,7 +377,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
                        return ret;
                }
 
-               bool BuildOnLinux (string projectXml, ILogger logger)
+               bool BuildOnMono (string projectXml, ILogger logger)
                {
                        var engine = new Engine (Consts.BinPath);
                        var project = engine.CreateNewProject ();
index 54f1c8a94cc2c935c49a573869ba9799aa6568df..144a6d72ea2e134bcfd4cdd96369be9b377fc66c 100644 (file)
@@ -129,6 +129,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine.Various {
                }
 
                [Test]
+               [SetCulture ("en-us")]
                public void AllowedFrameworkMembers ()
                {
                        string documentString = @"
@@ -202,6 +203,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine.Various {
                }
 
                [Test]
+               [SetCulture ("en-us")]
                public void MSBuildPropertyFunctions ()
                {
                        string documentString = @"
index cf56b148f117e2427363568d8a2be911ea64e807..ae6d75bf406fd3dfe9260b5a16feb4c4d3ead083 100644 (file)
@@ -153,7 +153,10 @@ namespace Microsoft.Build.Tasks {
                {
                        if (!string.IsNullOrEmpty (ToolPath))
                                return Path.Combine (ToolPath, ToolExe);
-                       return ToolLocationHelper.GetPathToDotNetFrameworkFile (ToolExe, TargetDotNetFrameworkVersion.VersionLatest);
+                       var possibleToolPath = ToolLocationHelper.GetPathToDotNetFrameworkFile (ToolExe, TargetDotNetFrameworkVersion.VersionLatest);
+                       if (!string.IsNullOrEmpty(possibleToolPath))
+                               return  possibleToolPath;
+                       return ToolLocationHelper.GetPathToDotNetFrameworkBinFile(ToolExe); 
                }
                
                [MonoTODO]
index 43917b03e340b8917fac8248808ced3b00b13c5c..19649dadf86b904503eeaa8835d2a4dcca5fa1c9 100755 (executable)
@@ -158,11 +158,11 @@ namespace MonoTests.Microsoft.Build.Tasks
                        Assert.AreEqual(files.Length, include.Count, id + "2");
 
                        for (int i = 0; i < files.Length; i++) {
-                               Assert.AreEqual (files [i], include [i].FinalItemSpec, id + "3, file #" + i);
+                               Assert.AreEqual (files [i], include [i].FinalItemSpec.Replace ("\\", "/"), id + "3, file #" + i);
                                Assert.IsTrue (include[i].HasMetadata ("TargetPath"), id + "4, file #" + i + ", TargetPath metadata missing");
                                Assert.AreEqual (assignedFiles [i], include[i].GetMetadata("TargetPath"), id + "5, file #" + i);
                                Assert.IsTrue (include [i].HasMetadata ("Child"), id + "6, file #" + i + ", Child metadata missing");
-                               Assert.AreEqual ("C" + files [i], include [i].GetMetadata ("Child"), id + "7, file #" + i + ", Child metadata value incorrect");
+                               Assert.AreEqual ("C" + files [i], include [i].GetMetadata ("Child").Replace ("\\", "/"), id + "7, file #" + i + ", Child metadata value incorrect");
                        }
                }
 
index ad7ca03ba5a6ebb9b3fcb611f695492d0a673a3e..dab6adaf7a3aac4ff02f42ee0c16ca3f43590a5f 100644 (file)
@@ -301,7 +301,11 @@ namespace MonoTests.Microsoft.Build.Tasks {
                                Assert.Fail ("Build failed");
                        }
                        Assert.IsTrue (File.Exists (target_file), "A2");
-                       Assert.AreEqual (FileAttributes.Normal, File.GetAttributes (target_file), "A3");                                        
+                       if (Environment.OSVersion.Platform == PlatformID.Unix)
+                               Assert.AreEqual (FileAttributes.Normal, File.GetAttributes (target_file), "A3");
+                       else
+                               // On Windows the Archive attribute will be set, not the Normal attribute.
+                               Assert.AreEqual (FileAttributes.Archive, File.GetAttributes (target_file), "A3");
                }
 
                [Test]
@@ -349,7 +353,12 @@ namespace MonoTests.Microsoft.Build.Tasks {
                                Assert.Fail ("Build failed " + sb.ToString ());
                        }
                        Assert.IsTrue (File.Exists (target_file), "A2");
-                       Assert.AreEqual (FileAttributes.Normal, File.GetAttributes (target_file), "A3");                                        
+                       var target_file_attrs = File.GetAttributes (target_file);
+                       if (Environment.OSVersion.Platform == PlatformID.Unix)
+                               Assert.AreEqual (FileAttributes.Normal, File.GetAttributes (target_file), "A3");
+                       else
+                               // On Windows the Archive attribute will be set, not the Normal attribute.
+                               Assert.AreEqual (FileAttributes.Archive, File.GetAttributes (target_file), "A3");
                }
 
                [Test]
index 3342c003e8bf890d8df77900cb32aee9f6d3eb0f..41c8d8e4f103a7bebdd6737de846e8f57b4654c4 100755 (executable)
@@ -115,6 +115,9 @@ namespace MonoTests.Microsoft.Build.Tasks {
                [Test]
                public void TestLineWithEscapedQuote ()
                {
+                       if (Environment.OSVersion.Platform != PlatformID.Unix) {
+                               Assert.Ignore ("Throws \"Illegal characters in path\" on Windows since \" is not a legal Windows path character");
+                       }
                        string[] lines = new string[] { "%22abc test%22 123 %22def%22" };
                        CreateProjectAndCheck (full_filepath, lines, false, true, delegate () {
                                CheckFileExists (full_filepath, true);
index 61973b7ceb48f80a4f2b7c64eac02b7f11934e25..f3b3524ba81277d944e710e63f7c0760c31786ba 100644 (file)
@@ -90,7 +90,7 @@ namespace MonoTests.Microsoft.Build.Evaluation
                {
                        string project_xml = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
   <ItemGroup>
-    <Foo Include='Test/ProjectItemTestTemporary/parent/dir*/a*.cs;Test/ProjectItemTestTemporary/x.cs' />
+    <Foo Include='" + "Test/ProjectItemTestTemporary/parent/dir*/a*.cs;Test/ProjectItemTestTemporary/x.cs".Replace ('/', Path.DirectorySeparatorChar) + @"' />
   </ItemGroup>
 </Project>";
                        try {
@@ -106,7 +106,7 @@ namespace MonoTests.Microsoft.Build.Evaluation
                {
                        string project_xml = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
   <ItemGroup>
-    <Foo Include='Test/ProjectItemTestTemporary/parent/**/a*.cs;Test/ProjectItemTestTemporary/x.cs' />
+    <Foo Include='" + "Test/ProjectItemTestTemporary/parent/**/a*.cs;Test/ProjectItemTestTemporary/x.cs".Replace ('/', Path.DirectorySeparatorChar) + @"' />
   </ItemGroup>
 </Project>";
                        try {
@@ -127,23 +127,23 @@ namespace MonoTests.Microsoft.Build.Evaluation
                        // sort is needed because they are only sorted by ItemType.
                        var items = proj.Items.OrderBy (p => p.EvaluatedInclude).ToArray ();
                        Assert.AreEqual (5, items.Length, "#1");
-                       Assert.AreEqual (string.Format ("Test/ProjectItemTestTemporary/parent/dir1{0}a.cs", Path.DirectorySeparatorChar), items [0].EvaluatedInclude, "#2");
+                       Assert.AreEqual ("Test/ProjectItemTestTemporary/parent/dir1/a.cs", items [0].EvaluatedInclude.Replace (Path.DirectorySeparatorChar, '/'), "#2");
                        Assert.AreEqual ("a", items [0].GetMetadataValue ("Filename"), "#3");
                        if (hasRecursiveDir)
                                Assert.AreEqual ("dir1" + sep, items [0].GetMetadataValue ("RecursiveDir"), "#3.2");
-                       Assert.AreEqual (string.Format ("Test/ProjectItemTestTemporary/parent/dir1{0}a1.cs", Path.DirectorySeparatorChar), items [1].EvaluatedInclude, "#4");
+                       Assert.AreEqual ("Test/ProjectItemTestTemporary/parent/dir1/a1.cs", items [1].EvaluatedInclude.Replace (Path.DirectorySeparatorChar, '/'), "#4");
                        Assert.AreEqual ("a1", items [1].GetMetadataValue ("Filename"), "#5");
                        if (hasRecursiveDir)
                                Assert.AreEqual ("dir1" + sep, items [1].GetMetadataValue ("RecursiveDir"), "#5.2");
-                       Assert.AreEqual (string.Format ("Test/ProjectItemTestTemporary/parent/dir2{0}a.cs", Path.DirectorySeparatorChar), items [2].EvaluatedInclude, "#6");
+                       Assert.AreEqual ("Test/ProjectItemTestTemporary/parent/dir2/a.cs", items [2].EvaluatedInclude.Replace (Path.DirectorySeparatorChar, '/'), "#6");
                        Assert.AreEqual ("a", items [2].GetMetadataValue ("Filename"), "#7");
                        if (hasRecursiveDir)
                                Assert.AreEqual ("dir2" + sep, items [2].GetMetadataValue ("RecursiveDir"), "#7.2");
-                       Assert.AreEqual (string.Format ("Test/ProjectItemTestTemporary/parent/dir2{0}a2.cs", Path.DirectorySeparatorChar), items [3].EvaluatedInclude, "#8");
+                       Assert.AreEqual ("Test/ProjectItemTestTemporary/parent/dir2/a2.cs", items [3].EvaluatedInclude.Replace (Path.DirectorySeparatorChar, '/'), "#8");
                        Assert.AreEqual ("a2", items [3].GetMetadataValue ("Filename"), "#9");
                        if (hasRecursiveDir)
                                Assert.AreEqual ("dir2" + sep, items [3].GetMetadataValue ("RecursiveDir"), "#9.2");
-                       Assert.AreEqual ("Test/ProjectItemTestTemporary/x.cs", items [4].EvaluatedInclude, "#10");
+                       Assert.AreEqual ("Test/ProjectItemTestTemporary/x.cs", items [4].EvaluatedInclude.Replace (Path.DirectorySeparatorChar, '/'), "#10");
                        for (int i = 0; i < items.Length; i++)
                                Assert.AreEqual (xitem, items [i].Xml, "#11:" + i);
                }
index 9723191bf164f6643724dcc990d59e609bf35003..f14bcd864ac75839762a8220b18f9fb9090fc187 100644 (file)
@@ -108,7 +108,8 @@ namespace MonoTests.Microsoft.Build.Execution
                        Assert.IsTrue (sub.BuildResult.OverallResult == BuildResultCode.Success, "#1");
                        DateTime endBuildDone = DateTime.Now;
                        Assert.IsTrue (endBuildDone - beforeExec >= TimeSpan.FromSeconds (1), "#2");
-                       Assert.IsTrue (endBuildDone > waitDone, "#3");
+                       Assert.IsTrue (waitDone >= beforeExec, "#3");
+                       Assert.IsTrue (endBuildDone >= waitDone, "#4");
                }
                
                [Test]
index 9c466c5ed9c9875b31f69f0f0ec9654075f3ac37..d03145e0df346c783650a15ff080a963e4ddcbda 100644 (file)
@@ -93,7 +93,8 @@ namespace Microsoft.CSharp.RuntimeBinder
                                module.SetDeclaringAssembly (temp);
 
                                var importer = new Compiler.ReflectionImporter (module, cc.BuiltinTypes) {
-                                       IgnorePrivateMembers = false
+                                       IgnorePrivateMembers = false,
+                                       IgnoreCompilerGeneratedField = false
                                };
 
                                // Import all currently loaded assemblies
diff --git a/mcs/class/Mono.Btls.Interface/Makefile b/mcs/class/Mono.Btls.Interface/Makefile
new file mode 100644 (file)
index 0000000..ea7e128
--- /dev/null
@@ -0,0 +1,12 @@
+thisdir = class/Mono.Btls.Interface
+SUBDIRS = 
+include ../../build/rules.make
+
+LIBRARY = Mono.Btls.Interface.dll
+LIB_REFS = System Mono.Security
+LIB_MCS_FLAGS = -unsafe -nowarn:1030 -keyfile:../mono.pub -delaysign -d:SECURITY_DEP
+
+include ../../build/library.make
+
+$(the_lib): ../Mono.Security/Makefile
+
diff --git a/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface.dll.sources b/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface.dll.sources
new file mode 100644 (file)
index 0000000..710e06d
--- /dev/null
@@ -0,0 +1,22 @@
+./Properties/AssemblyInfo.cs
+../../build/common/Consts.cs
+../../build/common/Locale.cs
+../../build/common/MonoTODOAttribute.cs
+
+Mono.Btls.Interface/BtlsObject.cs
+Mono.Btls.Interface/BtlsProvider.cs
+Mono.Btls.Interface/BtlsX509.cs
+Mono.Btls.Interface/BtlsX509Chain.cs
+Mono.Btls.Interface/BtlsX509Error.cs
+Mono.Btls.Interface/BtlsX509Format.cs
+Mono.Btls.Interface/BtlsX509Lookup.cs
+Mono.Btls.Interface/BtlsX509Name.cs
+Mono.Btls.Interface/BtlsX509Purpose.cs
+Mono.Btls.Interface/BtlsX509Store.cs
+Mono.Btls.Interface/BtlsX509StoreCtx.cs
+Mono.Btls.Interface/BtlsX509StoreManager.cs
+Mono.Btls.Interface/BtlsX509StoreType.cs
+Mono.Btls.Interface/BtlsX509TrustKind.cs
+Mono.Btls.Interface/BtlsX509VerifyFlags.cs
+Mono.Btls.Interface/BtlsX509VerifyParam.cs
+Mono.Btls.Interface/VersionInfo.cs
diff --git a/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsObject.cs b/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsObject.cs
new file mode 100644 (file)
index 0000000..b2e607c
--- /dev/null
@@ -0,0 +1,73 @@
+//
+// BtlsObject.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+
+namespace Mono.Btls.Interface
+{
+       public abstract class BtlsObject : IDisposable
+       {
+               MonoBtlsObject instance;
+
+               internal MonoBtlsObject Instance {
+                       get {
+                               if (!IsValid)
+                                       throw new ObjectDisposedException (GetType ().Name);
+                               return instance;
+                       }
+               }
+
+               internal BtlsObject (MonoBtlsObject instance)
+               {
+                       this.instance = instance;
+               }
+
+               public bool IsValid {
+                       get { return instance != null && instance.IsValid; }
+               }
+
+               protected void Dispose (bool disposing)
+               {
+                       if (disposing) {
+                               if (instance != null) {
+                                       instance.Dispose ();
+                                       instance = null;
+                               }
+                       }
+               }
+
+               public void Dispose ()
+               {
+                       Dispose (true);
+                       GC.SuppressFinalize (this);
+               }
+
+               ~BtlsObject ()
+               {
+                       Dispose (false);
+               }
+       }
+}
+
diff --git a/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsProvider.cs b/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsProvider.cs
new file mode 100644 (file)
index 0000000..0959dd0
--- /dev/null
@@ -0,0 +1,107 @@
+//
+// BtlsProvider.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using Mono.Security.Interface;
+using System.Security.Cryptography.X509Certificates;
+using MNS = Mono.Net.Security;
+
+namespace Mono.Btls.Interface
+{
+       public static class BtlsProvider
+       {
+               public static bool IsSupported ()
+               {
+                       return MNS.MonoTlsProviderFactory.IsBtlsSupported ();
+               }
+
+               public static MonoTlsProvider GetProvider ()
+               {
+                       return new MonoBtlsProvider ();
+               }
+
+               public static BtlsX509 CreateNative (byte[] data, BtlsX509Format format)
+               {
+                       var x509 = MonoBtlsX509.LoadFromData (data, (MonoBtlsX509Format)format);
+                       return new BtlsX509 (x509);
+               }
+
+               public static X509Certificate CreateCertificate (byte[] data, BtlsX509Format format, bool disallowFallback = false)
+               {
+                       return MonoBtlsProvider.CreateCertificate (data, (MonoBtlsX509Format)format, disallowFallback);
+               }
+
+               public static X509Certificate2 CreateCertificate2 (byte[] data, BtlsX509Format format, bool disallowFallback = false)
+               {
+                       return MonoBtlsProvider.CreateCertificate2 (data, (MonoBtlsX509Format)format, disallowFallback);
+               }
+
+               public static X509Certificate2 CreateCertificate2 (byte[] data, string password, bool disallowFallback = false)
+               {
+                       return MonoBtlsProvider.CreateCertificate2 (data, password, disallowFallback);
+               }
+
+               public static BtlsX509Chain CreateNativeChain ()
+               {
+                       return new BtlsX509Chain (new MonoBtlsX509Chain ());
+               }
+
+               public static BtlsX509Store CreateNativeStore ()
+               {
+                       return new BtlsX509Store (new MonoBtlsX509Store ());
+               }
+
+               public static BtlsX509StoreCtx CreateNativeStoreCtx ()
+               {
+                       return new BtlsX509StoreCtx (new MonoBtlsX509StoreCtx ());
+               }
+
+               public static X509Chain CreateChain ()
+               {
+                       return MonoBtlsProvider.CreateChain ();
+               }
+
+               public static string GetSystemStoreLocation ()
+               {
+                       return MonoBtlsProvider.GetSystemStoreLocation ();
+               }
+
+               public static BtlsX509VerifyParam GetVerifyParam_SslClient ()
+               {
+                       return new BtlsX509VerifyParam (MonoBtlsX509VerifyParam.GetSslClient ());
+               }
+
+               public static BtlsX509VerifyParam GetVerifyParam_SslServer ()
+               {
+                       return new BtlsX509VerifyParam (MonoBtlsX509VerifyParam.GetSslServer ());
+               }
+
+               public static X509Chain GetManagedChain (BtlsX509Chain chain)
+               {
+                       return MonoBtlsProvider.GetManagedChain (chain.Instance);
+               }
+       }
+}
+
diff --git a/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509.cs b/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509.cs
new file mode 100644 (file)
index 0000000..abcdafb
--- /dev/null
@@ -0,0 +1,132 @@
+//
+// BtlsX509.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.IO;
+using System.Security.Cryptography;
+
+namespace Mono.Btls.Interface
+{
+       public class BtlsX509 : BtlsObject
+       {
+               new internal MonoBtlsX509 Instance {
+                       get { return (MonoBtlsX509)base.Instance; }
+               }
+
+               internal BtlsX509 (MonoBtlsX509 x509)
+                       : base (x509)
+               {
+               }
+
+               public BtlsX509Name GetSubjectName ()
+               {
+                       return new BtlsX509Name (Instance.GetSubjectName ());
+               }
+
+               public BtlsX509Name GetIssuerName ()
+               {
+                       return new BtlsX509Name (Instance.GetIssuerName ());
+               }
+
+               public string GetSubjectNameString ()
+               {
+                       return Instance.GetSubjectNameString ();
+               }
+
+               public string GetIssuerNameString ()
+               {
+                       return Instance.GetIssuerNameString ();
+               }
+
+               public byte[] GetRawData (BtlsX509Format format)
+               {
+                       return Instance.GetRawData ((MonoBtlsX509Format)format);
+               }
+
+               public byte[] GetCertHash ()
+               {
+                       return Instance.GetCertHash ();
+               }
+
+               public DateTime GetNotBefore ()
+               {
+                       return Instance.GetNotBefore ();
+               }
+
+               public DateTime GetNotAfter ()
+               {
+                       return Instance.GetNotAfter ();
+               }
+
+               public byte[] GetPublicKeyData ()
+               {
+                       return Instance.GetPublicKeyData ();
+               }
+
+               public byte[] GetSerialNumber (bool mono_style)
+               {
+                       return Instance.GetSerialNumber (mono_style);
+               }
+
+               public int GetVersion ()
+               {
+                       return Instance.GetVersion ();
+               }
+
+               public Oid GetSignatureAlgorithm ()
+               {
+                       return Instance.GetSignatureAlgorithm ();
+               }
+
+               public AsnEncodedData GetPublicKeyAsn1 ()
+               {
+                       return Instance.GetPublicKeyAsn1 ();
+               }
+
+               public AsnEncodedData GetPublicKeyParameters ()
+               {
+                       return Instance.GetPublicKeyParameters (); 
+               }
+
+               public long GetSubjectNameHash ()
+               {
+                       using (var name = GetSubjectName ())
+                               return name.GetHash ();
+               }
+
+               public void Print (Stream stream)
+               {
+                       using (var bio = MonoBtlsBio.CreateMonoStream (stream))
+                               Instance.Print (bio);
+               }
+
+               public void ExportAsPEM (Stream stream, bool includeHumanReadableForm)
+               {
+                       using (var bio = MonoBtlsBio.CreateMonoStream (stream))
+                               Instance.ExportAsPEM (bio, includeHumanReadableForm);
+               }
+       }
+}
+
diff --git a/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509Chain.cs b/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509Chain.cs
new file mode 100644 (file)
index 0000000..38e9ec5
--- /dev/null
@@ -0,0 +1,58 @@
+//
+// BtlsX509Chain.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+
+namespace Mono.Btls.Interface
+{
+       public class BtlsX509Chain : BtlsObject
+       {
+               new internal MonoBtlsX509Chain Instance {
+                       get { return (MonoBtlsX509Chain)base.Instance; }
+               }
+
+               internal BtlsX509Chain (MonoBtlsX509Chain chain)
+                       : base (chain)
+               {
+               }
+
+               public int Count {
+                       get { return Instance.Count; }
+               }
+
+               public BtlsX509 this[int index] {
+                       get {
+                               var x509 = Instance.GetCertificate (index);
+                               return new BtlsX509 (x509.Copy ());
+                       }
+               }
+
+               public void Add (BtlsX509 x509)
+               {
+                       Instance.AddCertificate (x509.Instance);
+               }
+       }
+}
+
diff --git a/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509Error.cs b/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509Error.cs
new file mode 100644 (file)
index 0000000..089b4f2
--- /dev/null
@@ -0,0 +1,110 @@
+//
+// BtlsX509Error.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+namespace Mono.Btls.Interface
+{
+       // Keep in sync with NativeBoringX509Error
+       public enum BtlsX509Error
+       {
+               OK = 0,
+               /* illegal error (for uninitialized values, to avoid X509_V_OK): 1 */
+
+               UNABLE_TO_GET_ISSUER_CERT = 2,
+               UNABLE_TO_GET_CRL = 3,
+               UNABLE_TO_DECRYPT_CERT_SIGNATURE = 4,
+               UNABLE_TO_DECRYPT_CRL_SIGNATURE = 5,
+               UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY = 6,
+               CERT_SIGNATURE_FAILURE = 7,
+               CRL_SIGNATURE_FAILURE = 8,
+               CERT_NOT_YET_VALID = 9,
+               CERT_HAS_EXPIRED = 10,
+               CRL_NOT_YET_VALID = 11,
+               CRL_HAS_EXPIRED = 12,
+               ERROR_IN_CERT_NOT_BEFORE_FIELD = 13,
+               ERROR_IN_CERT_NOT_AFTER_FIELD = 14,
+               ERROR_IN_CRL_LAST_UPDATE_FIELD = 15,
+               ERROR_IN_CRL_NEXT_UPDATE_FIELD = 16,
+               OUT_OF_MEM = 17,
+               DEPTH_ZERO_SELF_SIGNED_CERT = 18,
+               SELF_SIGNED_CERT_IN_CHAIN = 19,
+               UNABLE_TO_GET_ISSUER_CERT_LOCALLY = 20,
+               UNABLE_TO_VERIFY_LEAF_SIGNATURE = 21,
+               CERT_CHAIN_TOO_LONG = 22,
+               CERT_REVOKED = 23,
+               INVALID_CA = 24,
+               PATH_LENGTH_EXCEEDED = 25,
+               INVALID_PURPOSE = 26,
+               CERT_UNTRUSTED = 27,
+               CERT_REJECTED = 28,
+               /* These are 'informational' when looking for issuer cert */
+               SUBJECT_ISSUER_MISMATCH = 29,
+               AKID_SKID_MISMATCH = 30,
+               AKID_ISSUER_SERIAL_MISMATCH = 31,
+               KEYUSAGE_NO_CERTSIGN = 32,
+
+               UNABLE_TO_GET_CRL_ISSUER = 33,
+               UNHANDLED_CRITICAL_EXTENSION = 34,
+               KEYUSAGE_NO_CRL_SIGN = 35,
+               UNHANDLED_CRITICAL_CRL_EXTENSION = 36,
+               INVALID_NON_CA = 37,
+               PROXY_PATH_LENGTH_EXCEEDED = 38,
+               KEYUSAGE_NO_DIGITAL_SIGNATURE = 39,
+               PROXY_CERTIFICATES_NOT_ALLOWED = 40,
+
+               INVALID_EXTENSION = 41,
+               INVALID_POLICY_EXTENSION = 42,
+               NO_EXPLICIT_POLICY = 43,
+               DIFFERENT_CRL_SCOPE = 44,
+               UNSUPPORTED_EXTENSION_FEATURE = 45,
+
+               UNNESTED_RESOURCE = 46,
+
+               PERMITTED_VIOLATION = 47,
+               EXCLUDED_VIOLATION = 48,
+               SUBTREE_MINMAX = 49,
+               UNSUPPORTED_CONSTRAINT_TYPE = 51,
+               UNSUPPORTED_CONSTRAINT_SYNTAX = 52,
+               UNSUPPORTED_NAME_SYNTAX = 53,
+               CRL_PATH_VALIDATION_ERROR = 54,
+
+               /* Suite B mode algorithm violation */
+               SUITE_B_INVALID_VERSION = 56,
+               SUITE_B_INVALID_ALGORITHM = 57,
+               SUITE_B_INVALID_CURVE = 58,
+               SUITE_B_INVALID_SIGNATURE_ALGORITHM = 59,
+               SUITE_B_LOS_NOT_ALLOWED = 60,
+               SUITE_B_CANNOT_SIGN_P_384_WITH_P_256 = 61,
+
+               /* Host, email and IP check errors */
+               HOSTNAME_MISMATCH = 62,
+               EMAIL_MISMATCH = 63,
+               IP_ADDRESS_MISMATCH = 64,
+
+               /* The application is not happy */
+               APPLICATION_VERIFICATION = 50
+       }
+}
+
diff --git a/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509Format.cs b/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509Format.cs
new file mode 100644 (file)
index 0000000..6ff63ce
--- /dev/null
@@ -0,0 +1,37 @@
+//
+// BtlsX509Format.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+
+namespace Mono.Btls.Interface
+{
+       // Keep in sync with NativeBoringX509Format
+       public enum BtlsX509Format
+       {
+               DER = 1,
+               PEM = 2
+       }
+}
+
diff --git a/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509Lookup.cs b/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509Lookup.cs
new file mode 100644 (file)
index 0000000..836088f
--- /dev/null
@@ -0,0 +1,72 @@
+//
+// BtlsX509Lookup.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.IO;
+using System.Security.Cryptography;
+
+namespace Mono.Btls.Interface
+{
+       public class BtlsX509Lookup : BtlsObject
+       {
+               new internal MonoBtlsX509Lookup Instance {
+                       get { return (MonoBtlsX509Lookup)base.Instance; }
+               }
+
+               internal BtlsX509Lookup (MonoBtlsX509Lookup lookup)
+                       : base (lookup)
+               {
+               }
+
+               public void Initialize ()
+               {
+                       Instance.Initialize ();
+               }
+
+               public void Shutdown ()
+               {
+                       Instance.Shutdown ();
+               }
+
+               public BtlsX509 LookupBySubject (BtlsX509Name name)
+               {
+                       var x509 = Instance.LookupBySubject (name.Instance);
+                       if (x509 == null)
+                               return null;
+
+                       return new BtlsX509 (x509);
+               }
+
+               public void LoadFile (string file, BtlsX509Format type)
+               {
+                       Instance.LoadFile (file, (MonoBtlsX509FileType)type);
+               }
+
+               public void AddDirectory (string dir, BtlsX509Format type)
+               {
+                       Instance.AddDirectory (dir, (MonoBtlsX509FileType)type);
+               }
+       }
+}
diff --git a/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509Name.cs b/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509Name.cs
new file mode 100644 (file)
index 0000000..69ca5a9
--- /dev/null
@@ -0,0 +1,62 @@
+//
+// BtlsX509Name.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+
+namespace Mono.Btls.Interface
+{
+       public class BtlsX509Name : BtlsObject
+       {
+               new internal MonoBtlsX509Name Instance {
+                       get { return (MonoBtlsX509Name)base.Instance; }
+               }
+
+               internal BtlsX509Name (MonoBtlsX509Name name)
+                       : base (name)
+               {
+               }
+
+               public string GetString ()
+               {
+                       return Instance.GetString ();
+               }
+
+               public byte[] GetRawData (bool use_canon_enc)
+               {
+                       return Instance.GetRawData (use_canon_enc);
+               }
+
+               public long GetHash ()
+               {
+                       return Instance.GetHash ();
+               }
+
+               public long GetHashOld ()
+               {
+                       return Instance.GetHashOld ();
+               }
+       }
+}
+
diff --git a/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509Purpose.cs b/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509Purpose.cs
new file mode 100644 (file)
index 0000000..ac906df
--- /dev/null
@@ -0,0 +1,43 @@
+//
+// BtlsX509Purpose.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+namespace Mono.Btls.Interface
+{
+       // Keep in sync with NativeBoringX509Purpose
+       public enum BtlsX509Purpose
+       {
+               SSL_CLIENT = 1,
+               SSL_SERVER = 2,
+               NS_SSL_SERVER = 3,
+               SMIME_SIGN = 4,
+               SMIME_ENCRYPT = 5,
+               CRL_SIGN = 6,
+               ANY = 7,
+               OCSP_HELPER = 8,
+               TIMESTAMP_SIGN = 9,
+       }
+}
+
diff --git a/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509Store.cs b/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509Store.cs
new file mode 100644 (file)
index 0000000..7b8f03f
--- /dev/null
@@ -0,0 +1,91 @@
+//
+// BtlsX509Store.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Security.Cryptography.X509Certificates;
+
+namespace Mono.Btls.Interface
+{
+       public class BtlsX509Store : BtlsObject
+       {
+               new internal MonoBtlsX509Store Instance {
+                       get { return (MonoBtlsX509Store)base.Instance; }
+               }
+
+               internal BtlsX509Store (MonoBtlsX509Store store)
+                       : base (store)
+               {
+               }
+
+               public void LoadLocations (string file, string path)
+               {
+                       Instance.LoadLocations (file, path);
+               }
+
+               public void AddTrustedRoots ()
+               {
+                       Instance.AddTrustedRoots ();
+               }
+
+               public void AddCertificate (BtlsX509 x509)
+               {
+                       Instance.AddCertificate (x509.Instance);
+               }
+
+               public int GetCount ()
+               {
+                       return Instance.GetCount ();
+               }
+
+               public void AddLookup (X509CertificateCollection certificates, BtlsX509TrustKind trust)
+               {
+                       Instance.AddCollection (certificates, (MonoBtlsX509TrustKind)trust);
+               }
+
+               static MonoBtlsX509FileType GetFileType (BtlsX509Format format)
+               {
+                       switch (format) {
+                       case BtlsX509Format.DER:
+                               return MonoBtlsX509FileType.ASN1;
+                       case BtlsX509Format.PEM:
+                               return MonoBtlsX509FileType.PEM;
+                       default:
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public void AddDirectoryLookup (string dir, BtlsX509Format format)
+               {
+                       Instance.AddDirectoryLookup (dir, GetFileType (format));
+               }
+
+               public void AddFileLookup (string file, BtlsX509Format format)
+               {
+                       Instance.AddFileLookup (file, GetFileType (format));
+               }
+
+       }
+}
+
diff --git a/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509StoreCtx.cs b/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509StoreCtx.cs
new file mode 100644 (file)
index 0000000..97d4a06
--- /dev/null
@@ -0,0 +1,71 @@
+//
+// BtlsX509StoreCtx.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+namespace Mono.Btls.Interface
+{
+       public class BtlsX509StoreCtx : BtlsObject
+       {
+               new internal MonoBtlsX509StoreCtx Instance {
+                       get { return (MonoBtlsX509StoreCtx)base.Instance; }
+               }
+
+               internal BtlsX509StoreCtx (MonoBtlsX509StoreCtx ctx)
+                       : base (ctx)
+               {
+               }
+
+               public void Initialize (BtlsX509Store store, BtlsX509Chain chain)
+               {
+                       Instance.Initialize (store.Instance, chain.Instance);
+               }
+
+               public void SetVerifyParam (BtlsX509VerifyParam param)
+               {
+                       Instance.SetVerifyParam (param.Instance);
+               }
+
+               public int Verify ()
+               {
+                       return Instance.Verify ();
+               }
+
+               public BtlsX509Error GetError ()
+               {
+                       return (BtlsX509Error)Instance.GetError ();
+               }
+
+               public Exception GetException ()
+               {
+                       return Instance.GetException ();
+               }
+
+               public BtlsX509Chain GetChain ()
+               {
+                       return new BtlsX509Chain (Instance.GetChain ());
+               }
+       }
+}
+
diff --git a/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509StoreManager.cs b/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509StoreManager.cs
new file mode 100644 (file)
index 0000000..1989ff4
--- /dev/null
@@ -0,0 +1,44 @@
+//
+// BtlsX509StoreManager.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.IO;
+using System.Security.Cryptography;
+
+namespace Mono.Btls.Interface
+{
+       public static class BtlsX509StoreManager
+       {
+               public static bool HasStore (BtlsX509StoreType type)
+               {
+                       return MonoBtlsX509StoreManager.HasStore ((MonoBtlsX509StoreType)type);
+               }
+
+               public static string GetStorePath (BtlsX509StoreType type)
+               {
+                       return MonoBtlsX509StoreManager.GetStorePath ((MonoBtlsX509StoreType)type);
+               }
+       }
+}
diff --git a/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509StoreType.cs b/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509StoreType.cs
new file mode 100644 (file)
index 0000000..acdfb98
--- /dev/null
@@ -0,0 +1,43 @@
+//
+// BtlsX509StoreType.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.IO;
+using System.Security.Cryptography;
+
+namespace Mono.Btls.Interface
+{
+       // Keep in sync with MonoBtlsX509StoreType
+       public enum BtlsX509StoreType
+       {
+               Custom,
+               MachineTrustedRoots,
+               MachineIntermediateCA,
+               MachineUntrusted,
+               UserTrustedRoots,
+               UserIntermediateCA,
+               UserUntrusted
+       }
+}
diff --git a/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509TrustKind.cs b/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509TrustKind.cs
new file mode 100644 (file)
index 0000000..9338ec6
--- /dev/null
@@ -0,0 +1,42 @@
+//
+// BtlsX509TrustKind.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+namespace Mono.Btls.Interface
+{
+       // Keep in sync with MonoBtlsX509TrustKind
+       [Flags]
+       public enum BtlsX509TrustKind
+       {
+               DEFAULT         = 0,
+               TRUST_CLIENT    = 1,
+               TRUST_SERVER    = 2,
+               TRUST_ALL       = 4,
+               REJECT_CLIENT   = 32,
+               REJECT_SERVER   = 64,
+               REJECT_ALL      = 128
+       }
+}
+
diff --git a/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509VerifyFlags.cs b/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509VerifyFlags.cs
new file mode 100644 (file)
index 0000000..02640c8
--- /dev/null
@@ -0,0 +1,38 @@
+//
+// BtlsX509VerifyFlags.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+namespace Mono.Btls.Interface
+{
+       // Keep in sync with NativeBoringX509VerifyFlags
+       public enum BtlsX509VerifyFlags
+       {
+               DEFAULT = 0,
+               CRL_CHECK = 1,
+               CRL_CHECK_ALL = 2,
+               X509_STRIC = 4
+       }
+}
+
diff --git a/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509VerifyParam.cs b/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/BtlsX509VerifyParam.cs
new file mode 100644 (file)
index 0000000..8d4e5eb
--- /dev/null
@@ -0,0 +1,91 @@
+//
+// BtlsX509VerifyParam.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+namespace Mono.Btls.Interface
+{
+       public class BtlsX509VerifyParam : BtlsObject
+       {
+               new internal MonoBtlsX509VerifyParam Instance {
+                       get { return (MonoBtlsX509VerifyParam)base.Instance; }
+               }
+
+               internal BtlsX509VerifyParam (MonoBtlsX509VerifyParam param)
+                       : base (param)
+               {
+               }
+
+               public BtlsX509VerifyParam Copy ()
+               {
+                       return new BtlsX509VerifyParam (Instance.Copy ());
+               }
+
+               public void SetName (string name)
+               {
+                       Instance.SetName (name);
+               }
+
+               public void SetHost (string name)
+               {
+                       Instance.SetHost (name);
+               }
+
+               public void AddHost (string name)
+               {
+                       Instance.AddHost (name);
+               }
+
+               public BtlsX509VerifyFlags GetFlags ()
+               {
+                       return (BtlsX509VerifyFlags)Instance.GetFlags ();
+               }
+
+               public void SetFlags (BtlsX509VerifyFlags flags)
+               {
+                       Instance.SetFlags ((ulong)flags);
+               }
+
+               public void SetPurpose (BtlsX509Purpose purpose)
+               {
+                       Instance.SetPurpose ((MonoBtlsX509Purpose)purpose);
+               }
+
+               public int GetDepth ()
+               {
+                       return Instance.GetDepth ();
+               }
+
+               public void SetDepth (int depth)
+               {
+                       Instance.SetDepth (depth);
+               }
+
+               public void SetTime (DateTime time)
+               {
+                       Instance.SetTime (time);
+               }
+       }
+}
+
diff --git a/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/VersionInfo.cs b/mcs/class/Mono.Btls.Interface/Mono.Btls.Interface/VersionInfo.cs
new file mode 100644 (file)
index 0000000..726c4ba
--- /dev/null
@@ -0,0 +1,34 @@
+//
+// VersionInfo.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+namespace Mono.Btls.Interface
+{
+       public static class VersionInfo
+       {
+               public const string Version = "1.0.0";
+       }
+}
+
diff --git a/mcs/class/Mono.Btls.Interface/Properties/AssemblyInfo.cs b/mcs/class/Mono.Btls.Interface/Properties/AssemblyInfo.cs
new file mode 100644 (file)
index 0000000..5ff0bcb
--- /dev/null
@@ -0,0 +1,47 @@
+//
+// AssemblyInfo.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Reflection;
+using System.Resources;
+using System.Security;
+using System.Security.Permissions;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about the system assembly
+
+[assembly: AssemblyVersion (Consts.FxVersion)]
+
+[assembly: AssemblyCompany ("MONO development team")]
+[assembly: AssemblyCopyright ("(c) 2016 Xamarin")]
+[assembly: AssemblyDescription ("Mono.Btls.Interface")]
+[assembly: AssemblyProduct ("MONO CLI")]
+[assembly: AssemblyTitle ("Mono.Btls.Interface")]
+[assembly: CLSCompliant (true)]
+[assembly: ComVisible (false)]
+[assembly: NeutralResourcesLanguage ("en-US")]
+
diff --git a/mcs/class/Mono.Btls.Interface/README.md b/mcs/class/Mono.Btls.Interface/README.md
new file mode 100644 (file)
index 0000000..81e169c
--- /dev/null
@@ -0,0 +1,9 @@
+Mono.Btls.Interface
+===================
+
+The purpose of this assembly is to allow test suites such as xamarin/web-tests
+(https://github.com/xamarin/web-tests/tree/stable) to test parts of BTLS without
+making System.dll internals visible.
+
+It should not be considered a stable and maintained API for third parties.
+
index 7f35914d241f72792d3667671bf8add783dd3dca..45b2db176875cbf3a4dc9fc0811ae180b64a71d3 100644 (file)
@@ -221,7 +221,7 @@ namespace Mono.Data.Sqlite
         case SQLiteDateFormats.UnixEpoch:\r
           return ((long)(dateValue.Subtract(UnixEpoch).Ticks / TimeSpan.TicksPerSecond)).ToString();\r
         default:\r
-          return dateValue.ToString(_datetimeFormats[7], CultureInfo.InvariantCulture);\r
+          return dateValue.ToString(_datetimeFormats[5], CultureInfo.InvariantCulture);\r
       }\r
     }\r
 \r
index 0a02896ef8ddaa01b2ebec83459d4cfeadc88807..643c40a86da80e8ac3d3afd94d1d04c4cf43d7f2 100644 (file)
@@ -6,4 +6,4 @@ SqliteExceptionUnitTests.cs
 SqliteParameterUnitTests.cs
 SqliteFunctionTests.cs
 Bug27864.cs
-
+SqliteTests.cs
index d64d3055b999b36e07e8ba66aeed04a5aba275c0..b381e1fde72bbdc7d29dd4ffdb482cb863bd5a9c 100644 (file)
@@ -9,7 +9,6 @@
 // Copyright 2015 Xamarin Inc.
 //
 
-#if MONOTOUCH
 using System;
 using System.Data;
 using System.IO;
@@ -96,13 +95,14 @@ namespace MonoTests.Mono.Data.Sqlite {
                                        }
                                }
                        } catch (SqliteException ex) {
+#if MONOTOUCH
                                // Expected Exception from iOS 8.2 (broken) to 9.0 (fixed)
                                if (BCL.Tests.TestRuntime.CheckSystemVersion (8,2) && !BCL.Tests.TestRuntime.CheckSystemVersion (9,0)) 
                                        Assert.That (ex.Message.Contains ("no such column: com.Name"));
                                else
-                                       throw new AssertionException ("Unexpected Sqlite Error", ex); // This should not happen
+                                       throw;
+#endif
                        }
                }
        }
 }
-#endif
\ No newline at end of file
diff --git a/mcs/class/Mono.Data.Sqlite/Test/SqliteTests.cs b/mcs/class/Mono.Data.Sqlite/Test/SqliteTests.cs
new file mode 100644 (file)
index 0000000..1533945
--- /dev/null
@@ -0,0 +1,102 @@
+//
+// SqliteTests.cs
+//
+// Authors:
+//     Marek Safar  <marek.safar@gmail.com>
+//
+// Copyright (C) 2016 Xamarin Inc (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Data;
+using System.IO;
+using System.Text;
+using Mono.Data.Sqlite;
+using NUnit.Framework;
+
+namespace MonoTests.Mono.Data.Sqlite
+{
+       [TestFixture]
+       public class SqliteTests
+       {
+               string _databasePath;
+
+               [SetUp]
+               public void Setup ()
+               {
+                       var dataFolder = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), "SqlTest");
+
+                       _databasePath = Path.Combine (dataFolder, "database.db");
+
+                       if (!Directory.Exists (dataFolder)) {
+                               Directory.CreateDirectory (dataFolder);
+                       }
+
+                       File.Delete (_databasePath);
+               }
+
+               [TearDown]
+               public void TearDown ()
+               {
+                       try {
+                               File.Delete (_databasePath);
+                       } catch {
+                       }
+               }
+
+               [Test]
+               public void DateTimeConvert ()
+               {
+                       var dateTime = new DateTime (2016, 9, 15, 12, 1, 53);
+                       var guid = Guid.NewGuid ();
+
+                       using (var connection = new SqliteConnection ("Data Source=" + _databasePath)) {
+                               connection.Open ();
+
+                               var sqlCreate = "CREATE TABLE TestTable (ID uniqueidentifier PRIMARY KEY, Modified datetime)";
+                               using (var cmd = new SqliteCommand (sqlCreate, connection)) {
+                                       cmd.ExecuteNonQuery ();
+                               }
+
+                               var sqlInsert = "INSERT INTO TestTable (ID, Modified) VALUES (@id, @mod)";
+                               using (var cmd = new SqliteCommand (sqlInsert, connection)) {
+                                       cmd.Parameters.Add (new SqliteParameter ("@id", guid));
+                                       cmd.Parameters.Add (new SqliteParameter ("@mod", dateTime));
+                                       cmd.ExecuteNonQuery ();
+                               }
+                       }
+
+                       using (var connection = new SqliteConnection ("Data Source=" + _databasePath)) {
+                               connection.Open ();
+
+                               var sqlSelect = "SELECT * from TestTable";
+                               using (var cmd = new SqliteCommand (sqlSelect, connection))
+                               using (var reader = cmd.ExecuteReader ()) {
+                                       while (reader.Read ()) {
+                                               Assert.AreEqual (guid, reader.GetGuid (0), "#1");
+                                               Assert.AreEqual (dateTime, reader.GetDateTime (1), "#2");
+                                       }
+                               }
+                       }
+               }
+       }
+}
index 1f20c1f89c63b6dceeb793a7241f8a2d4a6d34c2..e2fa98dcebe04e7629af935ed7847e9df90bfd16 100644 (file)
@@ -16,7 +16,8 @@ VALID_TEST_PROFILE := $(filter net_4_x, $(PROFILE))
 ifdef VALID_TEST_PROFILE
 
 TEST_HELPERS_SOURCES = \
-       ../test-helpers/NetworkHelpers.cs
+       ../test-helpers/NetworkHelpers.cs \
+       Test/TypeLoadClass.cs
 
 test-local: dtest-app.exe dtest-excfilter.exe
 
index 93e9a959eee4900912bf6f521a86a3acd01e9d31..a5b902db57322eaff402889d0becf162902b735b 100644 (file)
@@ -420,7 +420,7 @@ namespace Mono.Debugger.Soft
                 * with newer runtimes, and vice versa.
                 */
                internal const int MAJOR_VERSION = 2;
-               internal const int MINOR_VERSION = 43;
+               internal const int MINOR_VERSION = 44;
 
                enum WPSuspendPolicy {
                        NONE = 0,
@@ -590,6 +590,7 @@ namespace Mono.Debugger.Soft
                        GET_THIS = 2,
                        SET_VALUES = 3,
                        GET_DOMAIN = 4,
+                       SET_THIS = 5,
                }
 
                enum CmdArrayRef {
@@ -2410,6 +2411,10 @@ namespace Mono.Debugger.Soft
                        return SendReceive (CommandSet.STACK_FRAME, (int)CmdStackFrame.GET_DOMAIN, new PacketWriter ().WriteId (thread_id).WriteId (id)).ReadId ();
                }
 
+               internal void StackFrame_SetThis (long thread_id, long id, ValueImpl value) {
+                       SendReceive (CommandSet.STACK_FRAME, (int)CmdStackFrame.SET_THIS, new PacketWriter ().WriteId (thread_id).WriteId (id).WriteValue (value));
+               }
+
                /*
                 * ARRAYS
                 */
index f160c4a37a716890c6619877aaff762374e10395..c92f2240ef8036b0d2a162a82846dba70c082bfb 100644 (file)
@@ -166,6 +166,15 @@ namespace Mono.Debugger.Soft
                        return vm.DecodeValue (vm.conn.StackFrame_GetThis (thread.Id, Id));
                }
 
+               // Since protocol version 2.44
+               public void SetThis (Value value) {
+                       if (value == null)
+                               throw new ArgumentNullException ("value");
+                       if (Method.IsStatic || !Method.DeclaringType.IsValueType)
+                               throw new InvalidOperationException ("The frame's method needs to be a valuetype instance method.");
+                       vm.conn.StackFrame_SetThis (thread.Id, Id, vm.EncodeValue (value));
+               }
+
                public void SetValue (LocalVariable var, Value value) {
                        if (var == null)
                                throw new ArgumentNullException ("var");
diff --git a/mcs/class/Mono.Debugger.Soft/Test/TypeLoadClass.cs b/mcs/class/Mono.Debugger.Soft/Test/TypeLoadClass.cs
new file mode 100644 (file)
index 0000000..dfe4c3e
--- /dev/null
@@ -0,0 +1,11 @@
+
+class TypeLoadClass
+{
+       static TypeLoadClass ()
+       {
+       }
+}
+
+class TypeLoadClass2
+{
+}
\ No newline at end of file
index cc2ab66960fa5f3ed36e6e70c52278f6a27d6fac..532a6b207a1183216167b4439aed53d7db5e1465 100644 (file)
@@ -1589,12 +1589,6 @@ public class Tests : TestsBase, ITest2
        }
 }
 
-class TypeLoadClass {
-}
-
-class TypeLoadClass2 {
-}
-
 public class SentinelClass : MarshalByRefObject {
 }
 
@@ -1620,6 +1614,25 @@ public class Foo
        public ProcessStartInfo info;
 }
 
+class LocalReflectClass
+{
+       public static void RunMe ()
+       {
+               var reflectMe = new someClass ();
+               var temp = reflectMe; // Breakpoint location
+               reflectMe.someMethod ();
+       }
+
+       class someClass : ContextBoundObject
+       {
+               public object someField;
+
+               public void someMethod ()
+               {
+               }
+       }
+}
+
 // Class used for line number info testing, don't change its layout
 public class LineNumbers
 {
@@ -1643,22 +1656,5 @@ public class LineNumbers
        }
 }
 
-class LocalReflectClass
-{
-       public static void RunMe ()
-       {
-               var reflectMe = new someClass ();
-               reflectMe.someMethod ();
-       }
-
-       class someClass : ContextBoundObject
-       {
-               public object someField;
-
-               public void someMethod ()
-               {
-               }
-       }
-}
 
 
index 1933fc5e827372129731655297986401622ff064..af994790ea00b44e9eedcf6e4d6af2467ee3e232 100644 (file)
@@ -69,9 +69,17 @@ public class DebuggerTests
                if (!listening) {
                        var pi = new Diag.ProcessStartInfo ();
 
-                       if (runtime != null)
+                       if (runtime != null) {
                                pi.FileName = runtime;
-                       else
+                       } else if (Path.DirectorySeparatorChar == '\\') {
+                               string processExe = Diag.Process.GetCurrentProcess ().MainModule.FileName;
+                               if (processExe != null) {
+                                       string fileName = Path.GetFileName (processExe);
+                                       if (fileName.StartsWith ("mono") && fileName.EndsWith (".exe"))
+                                               pi.FileName = processExe;
+                               }
+                       }
+                       if (string.IsNullOrEmpty (pi.FileName))
                                pi.FileName = "mono";
                        pi.Arguments = String.Join (" ", args);
                        vm = VirtualMachineManager.Launch (pi, new LaunchOptions { AgentArgs = agent_args });
@@ -550,7 +558,11 @@ public class DebuggerTests
                MethodMirror m = entry_point.DeclaringType.Assembly.GetType ("LocalReflectClass").GetMethod ("RunMe");
 
                Assert.IsNotNull (m);
-               //Console.WriteLine ("X: " + name + " " + m.ILOffsets.Count + " " + m.Locations.Count);
+
+//             foreach (var x in m.Locations) {
+//                     Console.WriteLine (x);
+//             }
+
                var offset = -1;
                int method_base_linum = m.Locations [0].LineNumber;
                foreach (var location in m.Locations)
@@ -578,7 +590,11 @@ public class DebuggerTests
                e = single_step (e.Thread);
 
                var frame = e.Thread.GetFrames ()[0];
-               Value variable = frame.GetValue (frame.Method.GetLocal ("reflectMe"));
+
+               Assert.IsNotNull (frame);
+               var field = frame.Method.GetLocal ("reflectMe");
+               Assert.IsNotNull (field);
+               Value variable = frame.GetValue (field);
 
                ObjectMirror thisObj = (ObjectMirror)variable;
                TypeMirror thisType = thisObj.Type;
@@ -1767,6 +1783,16 @@ public class DebuggerTests
                AssertValue ("T", s ["s"]);
                AssertValue (45, s ["k"]);
 
+               // Test SetThis ()
+               s ["i"] = vm.CreateValue (55);
+               frame.SetThis (s);
+               obj = frame.GetThis ();
+               Assert.IsTrue (obj is StructMirror);
+               s = obj as StructMirror;
+               AssertValue (55, s ["i"]);
+               AssertValue ("T", s ["s"]);
+               AssertValue (45, s ["k"]);
+
                // this on static vtype methods
                e = run_until ("vtypes3");
                e = step_until (e.Thread, "static_foo");
@@ -3575,6 +3601,8 @@ public class DebuggerTests
                        return;
 
                string srcfile = (e as BreakpointEvent).Method.DeclaringType.GetSourceFiles (true)[0];
+               srcfile = srcfile.Replace ("dtest-app.cs", "TypeLoadClass.cs");
+               Assert.IsTrue (srcfile.Contains ("TypeLoadClass.cs"));
 
                var req = vm.CreateTypeLoadRequest ();
                req.SourceFileFilter = new string [] { srcfile.ToUpper () };
diff --git a/mcs/class/Mono.Security.Providers.DotNet/Makefile b/mcs/class/Mono.Security.Providers.DotNet/Makefile
deleted file mode 100644 (file)
index a42b8c5..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-thisdir = class/Mono.Security.Providers.DotNet
-SUBDIRS = 
-include ../../build/rules.make
-
-LIBRARY = Mono.Security.Providers.DotNet.dll
-LIB_REFS = System Mono.Security
-LIB_MCS_FLAGS = -unsafe -nowarn:1030 -keyfile:../mono.pub -delaysign
-
-EXTRA_DISTFILES = README.md
-
-include ../../build/library.make
-
-$(the_lib): ../Mono.Security/Makefile
-
diff --git a/mcs/class/Mono.Security.Providers.DotNet/Mono.Security.Providers.DotNet-net_4_x.csproj b/mcs/class/Mono.Security.Providers.DotNet/Mono.Security.Providers.DotNet-net_4_x.csproj
deleted file mode 100644 (file)
index 115c3f2..0000000
+++ /dev/null
@@ -1,101 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>\r
-<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
-  <PropertyGroup>\r
-    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
-    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
-    <ProductVersion>9.0.30729</ProductVersion>\r
-    <SchemaVersion>2.0</SchemaVersion>\r
-    <ProjectGuid>{391EDD2B-85AC-4FCA-B607-AAD6C51E6799}</ProjectGuid>\r
-    <OutputType>Library</OutputType>\r
-    <NoWarn>1699,1030</NoWarn>\r
-    <OutputPath>./../../class/lib/net_4_x</OutputPath>\r
-    <IntermediateOutputPath>obj-net_4_x</IntermediateOutputPath>\r
-    <GenerateTargetFrameworkAttribute>false</GenerateTargetFrameworkAttribute>\r
-    <NoStdLib>True</NoStdLib>\r
-    \r
-    <NoConfig>True</NoConfig>\r
-    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\r
-    <AppDesignerFolder>Properties</AppDesignerFolder>\r
-    <RootNamespace>\r
-    </RootNamespace>\r
-    <AssemblyName>Mono.Security.Providers.DotNet</AssemblyName>\r
-    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>\r
-    <FileAlignment>512</FileAlignment>\r
-  </PropertyGroup>\r
-    <PropertyGroup>\r
-    <SignAssembly>true</SignAssembly>\r
-    <DelaySign>true</DelaySign>\r
-  </PropertyGroup>\r
-  <PropertyGroup>\r
-    <AssemblyOriginatorKeyFile>../mono.pub</AssemblyOriginatorKeyFile>\r
-  </PropertyGroup>\r
-  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
-    <DebugSymbols>true</DebugSymbols>\r
-    <DebugType>full</DebugType>\r
-    <NoWarn>1699,1030</NoWarn>\r
-    <Optimize>false</Optimize>\r
-    <DefineConstants>TRACE;NET_4_0;NET_4_5;NET_4_6;MONO;DISABLE_CAS_USE</DefineConstants>\r
-    <ErrorReport>prompt</ErrorReport>\r
-    <WarningLevel>4</WarningLevel>\r
-  </PropertyGroup>\r
-  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
-    <DebugType>pdbonly</DebugType>\r
-    <NoWarn>1699,1030</NoWarn>\r
-    <Optimize>true</Optimize>\r
-    <DefineConstants>NET_4_0;NET_4_5;NET_4_6;MONO;DISABLE_CAS_USE</DefineConstants>\r
-    <ErrorReport>prompt</ErrorReport>\r
-    <WarningLevel>4</WarningLevel>\r
-  </PropertyGroup>\r
-  <!-- Set AddAdditionalExplicitAssemblyReferences to false, otherwise if targetting .NET4.0, \r
-  Microsoft.NETFramework.props will force a dependency on the assembly System.Core. This\r
-  is a problem to compile the Mono mscorlib.dll -->\r
-  <PropertyGroup>\r
-    <AddAdditionalExplicitAssemblyReferences>false</AddAdditionalExplicitAssemblyReferences>\r
-  </PropertyGroup>\r
-  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
-  <ItemGroup>\r
-    <Compile Include="..\..\build\common\Consts.cs" />\r
-    <Compile Include="..\..\build\common\Locale.cs" />\r
-    <Compile Include=".\Mono.Security.Providers.DotNet\DotNetSslStreamImpl.cs" />\r
-    <Compile Include=".\Mono.Security.Providers.DotNet\DotNetTlsProvider.cs" />\r
-    <Compile Include=".\Properties\AssemblyInfo.cs" />\r  </ItemGroup>\r
-  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r
-       Other similar extension points exist, see Microsoft.Common.targets.\r
-  <Target Name="BeforeBuild">\r
-  </Target>\r
-  <Target Name="AfterBuild">\r
-  </Target>\r
-  -->\r
-  <PropertyGroup>\r
-    <PreBuildEvent Condition=" '$(OS)' != 'Windows_NT' ">
-
-    </PreBuildEvent>\r
-    <PreBuildEvent Condition=" '$(OS)' == 'Windows_NT' ">\r
-\r
-    </PreBuildEvent>\r
-    <PostBuildEvent Condition=" '$(OS)' != 'Windows_NT' ">
-
-    </PostBuildEvent>\r
-    <PostBuildEvent Condition=" '$(OS)' == 'Windows_NT' ">\r
-\r
-    </PostBuildEvent>\r
-  </PropertyGroup>\r
-  <ItemGroup>\r
-    <ProjectReference Include="../corlib/corlib-net_4_x.csproj">\r
-      <Project>{2CA6026B-2DC8-4C4C-A12C-1E8234049DB7}</Project>\r
-      <Name>corlib-net_4_x</Name>\r
-    </ProjectReference>\r
-    <ProjectReference Include="../System/System-net_4_x.csproj">\r
-      <Project>{2762E921-91A8-4C87-91E9-BA628013F753}</Project>\r
-      <Name>System-net_4_x</Name>\r
-    </ProjectReference>\r
-    <ProjectReference Include="../Mono.Security/Mono.Security-net_4_x.csproj">\r
-      <Project>{42D59DE7-586F-4ACF-BDD5-E7869E39E3EF}</Project>\r
-      <Name>Mono.Security-net_4_x</Name>\r
-    </ProjectReference>\r
-  </ItemGroup>\r
-  <ItemGroup>\r
-    <Folder Include="Properties\" />\r
-  </ItemGroup>\r
-</Project>\r
-
diff --git a/mcs/class/Mono.Security.Providers.DotNet/Mono.Security.Providers.DotNet.dll.sources b/mcs/class/Mono.Security.Providers.DotNet/Mono.Security.Providers.DotNet.dll.sources
deleted file mode 100644 (file)
index 7afb9f3..0000000
+++ /dev/null
@@ -1,6 +0,0 @@
-./Properties/AssemblyInfo.cs
-../../build/common/Consts.cs
-../../build/common/Locale.cs
-
-./Mono.Security.Providers.DotNet/DotNetTlsProvider.cs
-./Mono.Security.Providers.DotNet/DotNetSslStreamImpl.cs
diff --git a/mcs/class/Mono.Security.Providers.DotNet/Mono.Security.Providers.DotNet/DotNetSslStreamImpl.cs b/mcs/class/Mono.Security.Providers.DotNet/Mono.Security.Providers.DotNet/DotNetSslStreamImpl.cs
deleted file mode 100644 (file)
index c6be703..0000000
+++ /dev/null
@@ -1,317 +0,0 @@
-//
-// DotNetSslStreamImpl.cs
-//
-// Author:
-//       Martin Baulig <martin.baulig@xamarin.com>
-//
-// Copyright (c) 2015 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.IO;
-using System.Net;
-using System.Net.Security;
-using System.Threading.Tasks;
-using System.Security.Authentication;
-using System.Security.Cryptography.X509Certificates;
-using System.Security.Principal;
-using System.Security.Cryptography;
-using MSI = Mono.Security.Interface;
-
-namespace Mono.Security.Providers.DotNet
-{
-       class DotNetSslStreamImpl : MSI.IMonoSslStream
-       {
-               DotNetTlsProvider provider;
-               SslStream impl;
-
-               internal SslStream Impl {
-                       get {
-                               CheckDisposed ();
-                               return impl;
-                       }
-               }
-
-               public DotNetSslStreamImpl (
-                       Stream innerStream, bool leaveInnerStreamOpen, DotNetTlsProvider provider,
-                       RemoteCertificateValidationCallback userCertificateValidationCallback,
-                       LocalCertificateSelectionCallback userCertificateSelectionCallback)
-               {
-                       this.provider = provider;
-                       impl = new SslStream (
-                               innerStream, leaveInnerStreamOpen,
-                               userCertificateValidationCallback,
-                               userCertificateSelectionCallback);
-               }
-
-               public void AuthenticateAsClient (string targetHost)
-               {
-                       Impl.AuthenticateAsClient (targetHost);
-               }
-
-               public void AuthenticateAsClient (string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
-               {
-                       Impl.AuthenticateAsClient (targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation);
-               }
-
-               public IAsyncResult BeginAuthenticateAsClient (string targetHost, AsyncCallback asyncCallback, object asyncState)
-               {
-                       return Impl.BeginAuthenticateAsClient (targetHost, asyncCallback, asyncState);
-               }
-
-               public IAsyncResult BeginAuthenticateAsClient (string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
-               {
-                       return Impl.BeginAuthenticateAsClient (targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation, asyncCallback, asyncState);
-               }
-
-               public void EndAuthenticateAsClient (IAsyncResult asyncResult)
-               {
-                       Impl.EndAuthenticateAsClient (asyncResult);
-               }
-
-               public void AuthenticateAsServer (X509Certificate serverCertificate)
-               {
-                       Impl.AuthenticateAsServer (serverCertificate);
-               }
-
-               public void AuthenticateAsServer (X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
-               {
-                       Impl.AuthenticateAsServer (serverCertificate, clientCertificateRequired, enabledSslProtocols, checkCertificateRevocation);
-               }
-
-               public IAsyncResult BeginAuthenticateAsServer (X509Certificate serverCertificate, AsyncCallback asyncCallback, object asyncState)
-               {
-                       return Impl.BeginAuthenticateAsServer (serverCertificate, asyncCallback, asyncState);
-               }
-
-               public IAsyncResult BeginAuthenticateAsServer (X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
-               {
-                       return Impl.BeginAuthenticateAsServer (serverCertificate, clientCertificateRequired, enabledSslProtocols, checkCertificateRevocation, asyncCallback, asyncState);
-               }
-
-               public void EndAuthenticateAsServer (IAsyncResult asyncResult)
-               {
-                       Impl.EndAuthenticateAsServer (asyncResult);
-               }
-
-               public Task AuthenticateAsClientAsync (string targetHost)
-               {
-                       return Impl.AuthenticateAsClientAsync (targetHost);
-               }
-
-               public Task AuthenticateAsClientAsync (string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
-               {
-                       return Impl.AuthenticateAsClientAsync (targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation);
-               }
-
-               public Task AuthenticateAsServerAsync (X509Certificate serverCertificate)
-               {
-                       return Impl.AuthenticateAsServerAsync (serverCertificate);
-               }
-
-               public Task AuthenticateAsServerAsync (X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
-               {
-                       return Impl.AuthenticateAsServerAsync (serverCertificate, clientCertificateRequired, enabledSslProtocols, checkCertificateRevocation);
-               }
-
-               public void Flush ()
-               {
-                       Impl.Flush ();
-               }
-
-               public int Read (byte[] buffer, int offset, int count)
-               {
-                       return Impl.Read (buffer, offset, count);
-               }
-
-               public void Write (byte[] buffer)
-               {
-                       Impl.Write (buffer);
-               }
-
-               public void Write (byte[] buffer, int offset, int count)
-               {
-                       Impl.Write (buffer, offset, count);
-               }
-
-               public IAsyncResult BeginRead (byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
-               {
-                       return Impl.BeginRead (buffer, offset, count, asyncCallback, asyncState);
-               }
-
-               public int EndRead (IAsyncResult asyncResult)
-               {
-                       return Impl.EndRead (asyncResult);
-               }
-
-               public IAsyncResult BeginWrite (byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
-               {
-                       return Impl.BeginWrite (buffer, offset, count, asyncCallback, asyncState);
-               }
-
-               public void EndWrite (IAsyncResult asyncResult)
-               {
-                       Impl.EndWrite (asyncResult);
-               }
-
-               public TransportContext TransportContext {
-                       get { throw new NotSupportedException (); }
-               }
-
-               public bool IsAuthenticated {
-                       get { return Impl.IsAuthenticated; }
-               }
-
-               public bool IsMutuallyAuthenticated {
-                       get { return Impl.IsMutuallyAuthenticated; }
-               }
-
-               public bool IsEncrypted {
-                       get { return Impl.IsEncrypted; }
-               }
-
-               public bool IsSigned {
-                       get { return Impl.IsSigned; }
-               }
-
-               public bool IsServer {
-                       get { return Impl.IsServer; }
-               }
-
-               public CipherAlgorithmType CipherAlgorithm {
-                       get { return Impl.CipherAlgorithm; }
-               }
-
-               public int CipherStrength {
-                       get { return Impl.CipherStrength; }
-               }
-
-               public HashAlgorithmType HashAlgorithm {
-                       get { return Impl.HashAlgorithm; }
-               }
-
-               public int HashStrength {
-                       get { return Impl.HashStrength; }
-               }
-
-               public ExchangeAlgorithmType KeyExchangeAlgorithm {
-                       get { return Impl.KeyExchangeAlgorithm; }
-               }
-
-               public int KeyExchangeStrength {
-                       get { return KeyExchangeStrength; }
-               }
-
-               public bool CanRead {
-                       get { return Impl.CanRead; }
-               }
-
-               public bool CanTimeout {
-                       get { return Impl.CanTimeout; }
-               }
-
-               public bool CanWrite {
-                       get { return Impl.CanWrite; }
-               }
-
-               public long Length {
-                       get { return Impl.Length; }
-               }
-
-               public long Position {
-                       get { return Impl.Position; }
-               }
-
-               public void SetLength (long value)
-               {
-                       Impl.SetLength (value);
-               }
-
-               public AuthenticatedStream AuthenticatedStream {
-                       get { return Impl; }
-               }
-
-               public int ReadTimeout {
-                       get { return Impl.ReadTimeout; }
-                       set { Impl.ReadTimeout = value; }
-               }
-
-               public int WriteTimeout {
-                       get { return Impl.WriteTimeout; }
-                       set { Impl.WriteTimeout = value; }
-               }
-
-               public bool CheckCertRevocationStatus {
-                       get { return Impl.CheckCertRevocationStatus; }
-               }
-
-               public X509Certificate InternalLocalCertificate {
-                       get {
-                               try {
-                                       return LocalCertificate;
-                               } catch {
-                                       return null;
-                               }
-                       }
-               }
-
-               public X509Certificate LocalCertificate {
-                       get { return Impl.LocalCertificate; }
-               }
-
-               public X509Certificate RemoteCertificate {
-                       get { return Impl.RemoteCertificate; }
-               }
-
-               public SslProtocols SslProtocol {
-                       get { return Impl.SslProtocol; }
-               }
-
-               MSI.MonoTlsProvider MSI.IMonoSslStream.Provider {
-                       get { return provider; }
-               }
-
-               MSI.MonoTlsConnectionInfo MSI.IMonoSslStream.GetConnectionInfo ()
-               {
-                       return null;
-               }
-
-               void CheckDisposed ()
-               {
-                       if (impl == null)
-                               throw new ObjectDisposedException ("MonoSslStream");
-               }
-
-               public void Dispose ()
-               {
-                       Dispose (true);
-                       GC.SuppressFinalize (this);
-               }
-
-               protected void Dispose (bool disposing)
-               {
-                       if (impl != null && disposing) {
-                               impl.Dispose ();
-                               impl = null;
-                       }
-               }
-       }
-}
-
diff --git a/mcs/class/Mono.Security.Providers.DotNet/Mono.Security.Providers.DotNet/DotNetTlsProvider.cs b/mcs/class/Mono.Security.Providers.DotNet/Mono.Security.Providers.DotNet/DotNetTlsProvider.cs
deleted file mode 100644 (file)
index 3be685a..0000000
+++ /dev/null
@@ -1,118 +0,0 @@
-//
-// MonoDefaultTlsProvider.cs
-//
-// Author:
-//       Martin Baulig <martin.baulig@xamarin.com>
-//
-// Copyright (c) 2015 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.IO;
-using System.Net;
-using System.Net.Security;
-using System.Security.Authentication;
-using System.Security.Cryptography.X509Certificates;
-using Mono.Security.Interface;
-
-namespace Mono.Security.Providers.DotNet
-{
-       /*
-        * This provider only uses the public .NET APIs from System.dll.
-        * 
-        * It is primarily intended for testing.
-        */
-       public class DotNetTlsProvider : MonoTlsProvider
-       {
-               static readonly Guid id = new Guid ("3a7b3a26-0dbd-4572-a5b8-fdce766bf0dd");
-
-               public override Guid ID {
-                       get { return id; }
-               }
-
-               public override string Name {
-                       get { return "dotnet"; }
-               }
-
-               public override bool SupportsSslStream {
-                       get { return true; }
-               }
-
-               public override bool SupportsConnectionInfo {
-                       get { return false; }
-               }
-
-               public override bool SupportsMonoExtensions {
-                       get { return false; }
-               }
-
-               internal override bool SupportsTlsContext {
-                       get { return false; }
-               }
-
-               public override SslProtocols SupportedProtocols {
-                       get { return (SslProtocols)ServicePointManager.SecurityProtocol; }
-               }
-
-               public override IMonoSslStream CreateSslStream (
-                       Stream innerStream, bool leaveInnerStreamOpen,
-                       MonoTlsSettings settings = null)
-               {
-                       if (settings != null)
-                               throw new NotSupportedException ("Mono-specific API Extensions not available.");
-
-                       RemoteCertificateValidationCallback validation_callback = null;
-                       LocalCertificateSelectionCallback selection_callback = null;
-
-                       if (settings != null) {
-                               validation_callback = ConvertCallback (settings.RemoteCertificateValidationCallback);
-                               selection_callback = ConvertCallback (settings.ClientCertificateSelectionCallback);
-                       }
-
-                       return new DotNetSslStreamImpl (innerStream, leaveInnerStreamOpen, this, validation_callback, selection_callback);
-               }
-
-               internal override IMonoTlsContext CreateTlsContext (
-                       string hostname, bool serverMode, TlsProtocols protocolFlags,
-                       X509Certificate serverCertificate, X509CertificateCollection clientCertificates,
-                       bool remoteCertRequired, MonoEncryptionPolicy encryptionPolicy,
-                       MonoTlsSettings settings)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               internal static RemoteCertificateValidationCallback ConvertCallback (MonoRemoteCertificateValidationCallback callback)
-               {
-                       if (callback == null)
-                               return null;
-
-                       return (s, c, ch, e) => callback (null, c, ch, (MonoSslPolicyErrors)e);
-               }
-
-               internal static LocalCertificateSelectionCallback ConvertCallback (MonoLocalCertificateSelectionCallback callback)
-               {
-                       if (callback == null)
-                               return null;
-
-                       return (s, t, lc, rc, ai) => callback (t, lc, rc, ai);
-               }
-
-       }
-}
-
diff --git a/mcs/class/Mono.Security.Providers.DotNet/Properties/AssemblyInfo.cs b/mcs/class/Mono.Security.Providers.DotNet/Properties/AssemblyInfo.cs
deleted file mode 100644 (file)
index cbbd002..0000000
+++ /dev/null
@@ -1,46 +0,0 @@
-//
-// AssemblyInfo.cs
-//
-// Author:
-//       Martin Baulig <martin.baulig@xamarin.com>
-//
-// Copyright (c) 2015 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.Reflection;
-using System.Resources;
-using System.Security;
-using System.Security.Permissions;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-
-// General Information about the system assembly
-
-[assembly: AssemblyVersion (Consts.FxVersion)]
-
-[assembly: AssemblyCompany ("MONO development team")]
-[assembly: AssemblyCopyright ("(c) 2015 Xamarin")]
-[assembly: AssemblyDescription ("Mono.Security.Providers.DotNet.dll")]
-[assembly: AssemblyProduct ("MONO CLI")]
-[assembly: AssemblyTitle ("Mono.Security.Providers.DotNet.dll")]
-[assembly: CLSCompliant (true)]
-[assembly: ComVisible (false)]
-[assembly: NeutralResourcesLanguage ("en-US")]
-
diff --git a/mcs/class/Mono.Security.Providers.DotNet/README.md b/mcs/class/Mono.Security.Providers.DotNet/README.md
deleted file mode 100644 (file)
index 4c47efd..0000000
+++ /dev/null
@@ -1 +0,0 @@
-See mcs/class/Mono.Security.Providers.NewSystemSource/README.md for a detailed README.
diff --git a/mcs/class/Mono.Security.Providers.NewSystemSource/Makefile b/mcs/class/Mono.Security.Providers.NewSystemSource/Makefile
deleted file mode 100644 (file)
index 61beeb4..0000000
+++ /dev/null
@@ -1,24 +0,0 @@
-thisdir = class/Mono.Security.Providers.NewSystemSource
-SUBDIRS = 
-include ../../build/rules.make
-
-LIB_REFS = System
-
-LIBRARY = Mono.Security.Providers.NewSystemSource.dll
-
-LIB_MCS_FLAGS = -d:SECURITY_DEP \
-       -unsafe -nowarn:1030 -keyfile:../mono.pub -delaysign -d:MONO -d:FEATURE_PAL -d:MONO_FEATURE_NEW_TLS \
-       -d:MONO_FEATURE_NEW_SYSTEM_SOURCE -d:DISABLE_CAS_USE
-
-ifdef MOBILE_PROFILE
-LIB_REFS += Mono.Security
-else
-LIB_REFS += MonoSecurity=Mono.Security
-LIB_MCS_FLAGS += -d:MONO_SECURITY_ALIAS
-endif
-
-EXTRA_DISTFILES = README.md
-
-include ../../build/library.make
-
-$(the_lib): ../Mono.Security/Makefile
diff --git a/mcs/class/Mono.Security.Providers.NewSystemSource/Mono.Security.Providers.NewSystemSource-net_4_x.csproj b/mcs/class/Mono.Security.Providers.NewSystemSource/Mono.Security.Providers.NewSystemSource-net_4_x.csproj
deleted file mode 100644 (file)
index 771d99f..0000000
+++ /dev/null
@@ -1,126 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>\r
-<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
-  <PropertyGroup>\r
-    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
-    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
-    <ProductVersion>9.0.30729</ProductVersion>\r
-    <SchemaVersion>2.0</SchemaVersion>\r
-    <ProjectGuid>{0BB4541F-9B1A-4CBC-BEB1-00B31B37F74E}</ProjectGuid>\r
-    <OutputType>Library</OutputType>\r
-    <NoWarn>1699,1030</NoWarn>\r
-    <OutputPath>./../../class/lib/net_4_x</OutputPath>\r
-    <IntermediateOutputPath>obj-net_4_x</IntermediateOutputPath>\r
-    <GenerateTargetFrameworkAttribute>false</GenerateTargetFrameworkAttribute>\r
-    <NoStdLib>True</NoStdLib>\r
-    \r
-    <NoConfig>True</NoConfig>\r
-    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\r
-    <AppDesignerFolder>Properties</AppDesignerFolder>\r
-    <RootNamespace>\r
-    </RootNamespace>\r
-    <AssemblyName>Mono.Security.Providers.NewSystemSource</AssemblyName>\r
-    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>\r
-    <FileAlignment>512</FileAlignment>\r
-  </PropertyGroup>\r
-    <PropertyGroup>\r
-    <SignAssembly>true</SignAssembly>\r
-    <DelaySign>true</DelaySign>\r
-  </PropertyGroup>\r
-  <PropertyGroup>\r
-    <AssemblyOriginatorKeyFile>../mono.pub</AssemblyOriginatorKeyFile>\r
-  </PropertyGroup>\r
-  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
-    <DebugSymbols>true</DebugSymbols>\r
-    <DebugType>full</DebugType>\r
-    <NoWarn>1699,1030</NoWarn>\r
-    <Optimize>false</Optimize>\r
-    <DefineConstants>TRACE;NET_4_0;NET_4_5;NET_4_6;MONO;DISABLE_CAS_USE;SECURITY_DEP;MONO;FEATURE_PAL;MONO_FEATURE_NEW_TLS;MONO_FEATURE_NEW_SYSTEM_SOURCE;DISABLE_CAS_USE;MONO_SECURITY_ALIAS</DefineConstants>\r
-    <ErrorReport>prompt</ErrorReport>\r
-    <WarningLevel>4</WarningLevel>\r
-  </PropertyGroup>\r
-  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
-    <DebugType>pdbonly</DebugType>\r
-    <NoWarn>1699,1030</NoWarn>\r
-    <Optimize>true</Optimize>\r
-    <DefineConstants>NET_4_0;NET_4_5;NET_4_6;MONO;DISABLE_CAS_USE;SECURITY_DEP;MONO;FEATURE_PAL;MONO_FEATURE_NEW_TLS;MONO_FEATURE_NEW_SYSTEM_SOURCE;DISABLE_CAS_USE;MONO_SECURITY_ALIAS</DefineConstants>\r
-    <ErrorReport>prompt</ErrorReport>\r
-    <WarningLevel>4</WarningLevel>\r
-  </PropertyGroup>\r
-  <!-- Set AddAdditionalExplicitAssemblyReferences to false, otherwise if targetting .NET4.0, \r
-  Microsoft.NETFramework.props will force a dependency on the assembly System.Core. This\r
-  is a problem to compile the Mono mscorlib.dll -->\r
-  <PropertyGroup>\r
-    <AddAdditionalExplicitAssemblyReferences>false</AddAdditionalExplicitAssemblyReferences>\r
-  </PropertyGroup>\r
-  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
-  <ItemGroup>\r
-    <Compile Include="..\..\build\common\Consts.cs" />\r
-    <Compile Include="..\..\build\common\Locale.cs" />\r
-    <Compile Include="..\..\build\common\SR.cs" />\r
-    <Compile Include="..\referencesource\mscorlib\InternalApis\NDP_Common\inc\PinnableBufferCache.cs" />\r
-    <Compile Include="..\referencesource\System\net\System\Net\_LazyAsyncResult.cs" />\r
-    <Compile Include="..\referencesource\System\net\System\Net\_LoggingObject.cs" />\r
-    <Compile Include="..\referencesource\System\net\System\Net\_NTAuthentication.cs" />\r
-    <Compile Include="..\referencesource\System\net\System\Net\_SecureChannel.cs" />\r
-    <Compile Include="..\referencesource\System\net\System\Net\_SslSessionsCache.cs" />\r
-    <Compile Include="..\referencesource\System\net\System\Net\Logging.cs" />\r
-    <Compile Include="..\referencesource\System\net\System\Net\SecureProtocols\_FixedSizeReader.cs" />\r
-    <Compile Include="..\referencesource\System\net\System\Net\SecureProtocols\_HelperAsyncResults.cs" />\r
-    <Compile Include="..\referencesource\System\net\System\Net\SecureProtocols\_SslState.cs" />\r
-    <Compile Include="..\referencesource\System\net\System\Net\SecureProtocols\_SslStream.cs" />\r
-    <Compile Include="..\referencesource\System\net\System\Net\SecureProtocols\SslStream.cs" />\r
-    <Compile Include="..\System\Mono.Net.Security\CallbackHelpers.cs" />\r
-    <Compile Include="..\System\Mono.Net.Security\IMonoTlsProvider.cs" />\r
-    <Compile Include="..\System\Mono.Net.Security\MonoTlsProviderFactory.cs" />\r
-    <Compile Include="..\System\Mono.Net.Security\MonoTlsProviderWrapper.cs" />\r
-    <Compile Include="..\System\ReferenceSources\_SecureChannel.cs" />\r
-    <Compile Include="..\System\ReferenceSources\_SslState.cs" />\r
-    <Compile Include="..\System\ReferenceSources\_SslStream.cs" />\r
-    <Compile Include="..\System\ReferenceSources\Internal.cs" />\r
-    <Compile Include="..\System\ReferenceSources\SR.cs" />\r
-    <Compile Include="..\System\ReferenceSources\SR2.cs" />\r
-    <Compile Include="..\System\ReferenceSources\SslStream.cs" />\r
-    <Compile Include="..\System\ReferenceSources\SSPIConfiguration.cs" />\r
-    <Compile Include="..\System\ReferenceSources\SSPISafeHandles.cs" />\r
-    <Compile Include="..\System\ReferenceSources\SSPIWrapper.cs" />\r
-    <Compile Include=".\Properties\AssemblyInfo.cs" />\r  </ItemGroup>\r
-  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r
-       Other similar extension points exist, see Microsoft.Common.targets.\r
-  <Target Name="BeforeBuild">\r
-  </Target>\r
-  <Target Name="AfterBuild">\r
-  </Target>\r
-  -->\r
-  <PropertyGroup>\r
-    <PreBuildEvent Condition=" '$(OS)' != 'Windows_NT' ">
-
-    </PreBuildEvent>\r
-    <PreBuildEvent Condition=" '$(OS)' == 'Windows_NT' ">\r
-\r
-    </PreBuildEvent>\r
-    <PostBuildEvent Condition=" '$(OS)' != 'Windows_NT' ">
-
-    </PostBuildEvent>\r
-    <PostBuildEvent Condition=" '$(OS)' == 'Windows_NT' ">\r
-\r
-    </PostBuildEvent>\r
-  </PropertyGroup>\r
-  <ItemGroup>\r
-    <ProjectReference Include="../corlib/corlib-net_4_x.csproj">\r
-      <Project>{2CA6026B-2DC8-4C4C-A12C-1E8234049DB7}</Project>\r
-      <Name>corlib-net_4_x</Name>\r
-    </ProjectReference>\r
-    <ProjectReference Include="../System/System-net_4_x.csproj">\r
-      <Project>{2762E921-91A8-4C87-91E9-BA628013F753}</Project>\r
-      <Name>System-net_4_x</Name>\r
-    </ProjectReference>\r
-    <ProjectReference Include="../Mono.Security/Mono.Security-net_4_x.csproj">\r
-      <Project>{42D59DE7-586F-4ACF-BDD5-E7869E39E3EF}</Project>\r
-      <Name>Mono.Security-net_4_x</Name>\r
-      <Aliases>MonoSecurity</Aliases>    </ProjectReference>\r
-  </ItemGroup>\r
-  <ItemGroup>\r
-    <Folder Include="Properties\" />\r
-  </ItemGroup>\r
-</Project>\r
-
diff --git a/mcs/class/Mono.Security.Providers.NewSystemSource/Mono.Security.Providers.NewSystemSource.dll.sources b/mcs/class/Mono.Security.Providers.NewSystemSource/Mono.Security.Providers.NewSystemSource.dll.sources
deleted file mode 100644 (file)
index c0765d5..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-./Properties/AssemblyInfo.cs
-../../build/common/SR.cs
-../../build/common/Consts.cs
-../../build/common/Locale.cs
-
-../referencesource/System/net/System/Net/Logging.cs
-../referencesource/System/net/System/Net/_SslSessionsCache.cs
-../referencesource/System/net/System/Net/_LazyAsyncResult.cs
-../referencesource/System/net/System/Net/_LoggingObject.cs
-../referencesource/System/net/System/Net/_NTAuthentication.cs
-../referencesource/System/net/System/Net/_SecureChannel.cs
-../referencesource/System/net/System/Net/SecureProtocols/SslStream.cs
-../referencesource/System/net/System/Net/SecureProtocols/_SslState.cs
-../referencesource/System/net/System/Net/SecureProtocols/_SslStream.cs
-../referencesource/System/net/System/Net/SecureProtocols/_FixedSizeReader.cs
-../referencesource/System/net/System/Net/SecureProtocols/_HelperAsyncResults.cs
-../referencesource/mscorlib/InternalApis/NDP_Common/inc/PinnableBufferCache.cs
-
-../System/ReferenceSources/SR.cs
-../System/ReferenceSources/SR2.cs
-../System/ReferenceSources/Internal.cs
-../System/ReferenceSources/SSPIWrapper.cs
-../System/ReferenceSources/SSPISafeHandles.cs
-../System/ReferenceSources/SslStream.cs
-../System/ReferenceSources/_SslState.cs
-../System/ReferenceSources/_SslStream.cs
-../System/ReferenceSources/_SecureChannel.cs
-../System/ReferenceSources/SSPIConfiguration.cs
-../System/Mono.Net.Security/CallbackHelpers.cs
-../System/Mono.Net.Security/IMonoTlsProvider.cs
-../System/Mono.Net.Security/MonoTlsProviderFactory.cs
-../System/Mono.Net.Security/MonoTlsProviderWrapper.cs
-
diff --git a/mcs/class/Mono.Security.Providers.NewSystemSource/Properties/AssemblyInfo.cs b/mcs/class/Mono.Security.Providers.NewSystemSource/Properties/AssemblyInfo.cs
deleted file mode 100644 (file)
index 23ba5bb..0000000
+++ /dev/null
@@ -1,48 +0,0 @@
-//
-// AssemblyInfo.cs
-//
-// Author:
-//       Martin Baulig <martin.baulig@xamarin.com>
-//
-// Copyright (c) 2015 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.Reflection;
-using System.Resources;
-using System.Security;
-using System.Security.Permissions;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-
-// General Information about the system assembly
-
-[assembly: AssemblyVersion (Consts.FxVersion)]
-
-[assembly: AssemblyCompany ("MONO development team")]
-[assembly: AssemblyCopyright ("(c) 2015 Xamarin")]
-[assembly: AssemblyDescription ("Mono.Security.Providers.NewSystemSource.dll")]
-[assembly: AssemblyProduct ("MONO CLI")]
-[assembly: AssemblyTitle ("Mono.Security.Providers.NewSystemSource.dll")]
-[assembly: CLSCompliant (true)]
-[assembly: ComVisible (false)]
-[assembly: NeutralResourcesLanguage ("en-US")]
-
-[assembly: InternalsVisibleTo ("Mono.Security.Providers.NewTls, PublicKey=002400000480000094000000060200000024000052534131000400001100000003336d6aed41624ca156ab579881fe90a576f1dfec48378fc94e4e440f4556776224e2d70c18996d91f36227f539fdb44340e07651f1455a489b29a7e6219a8f85e52b0f8588b4f8a857746a8468d37b556223d1452f3fcbaf0f269cdf1900ceb68f69485dc5887750d19571030c732331e00387d9b813a9ad52891087301793")]
-[assembly: InternalsVisibleTo ("Mono.Security.Providers.NewTls, PublicKey=002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df")]
diff --git a/mcs/class/Mono.Security.Providers.NewSystemSource/README.md b/mcs/class/Mono.Security.Providers.NewSystemSource/README.md
deleted file mode 100644 (file)
index 03447c0..0000000
+++ /dev/null
@@ -1,95 +0,0 @@
-Mono.Security.Interface / Mono.Security.Providers
-=================================================
-
-This is not a public API yet, but will eventually become public.
-
-
-Mono.Security.Interface
------------------------
-
-`Mono.Security.Interface` provides an abstraction layer for the TLS
-APIs that are currently being used by Mono's class libraries.
-
-The main API entry points are `MonoTlsProviderFactory.GetProvider()`
-and `MonoTlsProviderFactory.InstallProvider()`.
-
-Mono.Net.Security
------------------
-
-`Mono.Net.Security` provides the internal implementation and lives
-inside `System.dll` as private and internal APIs.  `Mono.Security.dll`
-uses reflection to access these.
-
-On Mobile, the `Mono.Security.Interface` APIs are included as public
-APIs in `System.dll`.
-
-Mono.Security.Providers
------------------------
-
-Implementations of the `Mono.Security.Interface.MonoTlsProvider` class
-to provide TLS functionality.
-
-The default provider is inside `System.dll` - it will be used automatically
-if you don't explicitly install a custom provider, so simply call
-`MonoTlsProviderFactory.GetProvider()` to use it.
-
-* DotNet:
-  Provides the default `SslStream` implementation from `System.dll`, only using
-  public .NET types.
-  
-* NewSystemSource:
-  Compiles several referencesource files which would normally live inside
-  `System.dll` if we compiled it with their `SslStream` implementation.
-  
-  This allows to keep the code in `System.dll` as-is, while still providing the
-  new `SslStream`, which will be required by the new TLS code.
-  
-  `System.dll` needs to make its internals visible and we're using several compiler /
-  external alias tricks in here to make this work.
-  
-  In this configuration, `MONO_SYSTEM_ALIAS`, `MONO_FEATURE_NEW_TLS` and
-  `MONO_FEATURE_NEW_SYSTEM_SOURCE` (defining conditional for this configuration)
-  are defined.  We do not define `MONO_X509_ALIAS here`.
-  
-The `Mono.Security.Providers.DotNet` and `Mono.Security.Providers.NewSystemSource` directory is currently
-enabled in the top-level `Makefile`, but the resulting binaries should only be used to test the new TLS
-code and not shipped as stable APIs.
-
-Pending changes
----------------
-
-This code is not actually being used in `System.dll` yet.  I have some
-local changes which will switch the existing code in `WebClient`,
-`SmptClient` and `FtpWebRequest` over, but these need to be carefully
-tested.
-
-At the moment, this work branch only provides new code and build
-changes, which shuffle some stuff around.  There are also several
-new files which are conditional and not actually being built by
-default.
-
-Build Configurations
---------------------
-
-* Normal build:
-  Builds everything as before with some new APIs added, but without
-  modifying any existing functionality.
-  
-* Build with the `newtls` profile:
-  Builds `System.dll` with the new `SslStream` implementation from the
-  referencesource.  This is currently a "build then throw away" profile
-  and not enabled from the top-level Makefile.  The resulting `System.dll`
-  won't actually work at runtime since it's missing the new TLS code;
-  building it helps find problems and ensures that it will actually
-  be possible to build this once we deploy it.
-
-* Mono.Security.Providers:
-  The new TLS code requires the newly built `System` and `Mono.Security.Providers.NewSystemSource`
-  from this branch installed in the system.  It is recommended to install it
-  into a custom prefix and set that as custom runtime in Xamarin Studio.
-
-
-Last changed March 07th, 2015,
-Martin Baulig <martin.baulig@xamarin.com>
-
-
diff --git a/mcs/class/Mono.Security.Providers.NewTls/Makefile b/mcs/class/Mono.Security.Providers.NewTls/Makefile
deleted file mode 100644 (file)
index 54270bc..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-thisdir = class/Mono.Security.Providers.NewTls
-SUBDIRS = 
-include ../../build/rules.make
-
-LIBRARY = Mono.Security.Providers.NewTls.dll
-LIB_REFS = System NewSystemSource=Mono.Security.Providers.NewSystemSource Mono.Security
-LIB_MCS_FLAGS = -unsafe -nowarn:1030 -keyfile:../mono.pub -delaysign
-
-include ../../build/library.make
-
-$(the_lib): ../Mono.Security/Makefile
-
diff --git a/mcs/class/Mono.Security.Providers.NewTls/Mono.Security.Providers.NewTls-net_4_x.csproj b/mcs/class/Mono.Security.Providers.NewTls/Mono.Security.Providers.NewTls-net_4_x.csproj
deleted file mode 100644 (file)
index 158b095..0000000
+++ /dev/null
@@ -1,111 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>\r
-<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
-  <PropertyGroup>\r
-    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
-    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
-    <ProductVersion>9.0.30729</ProductVersion>\r
-    <SchemaVersion>2.0</SchemaVersion>\r
-    <ProjectGuid>{C8B8E524-BB3A-44E2-8C22-E3313E9F477C}</ProjectGuid>\r
-    <OutputType>Library</OutputType>\r
-    <NoWarn>1699,1030</NoWarn>\r
-    <OutputPath>./../../class/lib/net_4_x</OutputPath>\r
-    <IntermediateOutputPath>obj-net_4_x</IntermediateOutputPath>\r
-    <GenerateTargetFrameworkAttribute>false</GenerateTargetFrameworkAttribute>\r
-    <NoStdLib>True</NoStdLib>\r
-    \r
-    <NoConfig>True</NoConfig>\r
-    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\r
-    <AppDesignerFolder>Properties</AppDesignerFolder>\r
-    <RootNamespace>\r
-    </RootNamespace>\r
-    <AssemblyName>Mono.Security.Providers.NewTls</AssemblyName>\r
-    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>\r
-    <FileAlignment>512</FileAlignment>\r
-  </PropertyGroup>\r
-    <PropertyGroup>\r
-    <SignAssembly>true</SignAssembly>\r
-    <DelaySign>true</DelaySign>\r
-  </PropertyGroup>\r
-  <PropertyGroup>\r
-    <AssemblyOriginatorKeyFile>../mono.pub</AssemblyOriginatorKeyFile>\r
-  </PropertyGroup>\r
-  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
-    <DebugSymbols>true</DebugSymbols>\r
-    <DebugType>full</DebugType>\r
-    <NoWarn>1699,1030</NoWarn>\r
-    <Optimize>false</Optimize>\r
-    <DefineConstants>TRACE;NET_4_0;NET_4_5;NET_4_6;MONO;DISABLE_CAS_USE</DefineConstants>\r
-    <ErrorReport>prompt</ErrorReport>\r
-    <WarningLevel>4</WarningLevel>\r
-  </PropertyGroup>\r
-  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
-    <DebugType>pdbonly</DebugType>\r
-    <NoWarn>1699,1030</NoWarn>\r
-    <Optimize>true</Optimize>\r
-    <DefineConstants>NET_4_0;NET_4_5;NET_4_6;MONO;DISABLE_CAS_USE</DefineConstants>\r
-    <ErrorReport>prompt</ErrorReport>\r
-    <WarningLevel>4</WarningLevel>\r
-  </PropertyGroup>\r
-  <!-- Set AddAdditionalExplicitAssemblyReferences to false, otherwise if targetting .NET4.0, \r
-  Microsoft.NETFramework.props will force a dependency on the assembly System.Core. This\r
-  is a problem to compile the Mono mscorlib.dll -->\r
-  <PropertyGroup>\r
-    <AddAdditionalExplicitAssemblyReferences>false</AddAdditionalExplicitAssemblyReferences>\r
-  </PropertyGroup>\r
-  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
-  <ItemGroup>\r
-    <Compile Include="..\..\build\common\Consts.cs" />\r
-    <Compile Include="..\..\build\common\Locale.cs" />\r
-    <Compile Include="..\..\build\common\SR.cs" />\r
-    <Compile Include=".\Mono.Security.Providers.NewTls\ITlsConfiguration.cs" />\r
-    <Compile Include=".\Mono.Security.Providers.NewTls\ITlsContext.cs" />\r
-    <Compile Include=".\Mono.Security.Providers.NewTls\MonoNewTlsStream.cs" />\r
-    <Compile Include=".\Mono.Security.Providers.NewTls\MonoNewTlsStreamFactory.cs" />\r
-    <Compile Include=".\Mono.Security.Providers.NewTls\NewTlsProvider.cs" />\r
-    <Compile Include=".\Mono.Security.Providers.NewTls\TlsContextWrapper.cs" />\r
-    <Compile Include=".\Mono.Security.Providers.NewTls\TlsProviderFactory.cs" />\r
-    <Compile Include=".\Properties\AssemblyInfo.cs" />\r  </ItemGroup>\r
-  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r
-       Other similar extension points exist, see Microsoft.Common.targets.\r
-  <Target Name="BeforeBuild">\r
-  </Target>\r
-  <Target Name="AfterBuild">\r
-  </Target>\r
-  -->\r
-  <PropertyGroup>\r
-    <PreBuildEvent Condition=" '$(OS)' != 'Windows_NT' ">
-
-    </PreBuildEvent>\r
-    <PreBuildEvent Condition=" '$(OS)' == 'Windows_NT' ">\r
-\r
-    </PreBuildEvent>\r
-    <PostBuildEvent Condition=" '$(OS)' != 'Windows_NT' ">
-
-    </PostBuildEvent>\r
-    <PostBuildEvent Condition=" '$(OS)' == 'Windows_NT' ">\r
-\r
-    </PostBuildEvent>\r
-  </PropertyGroup>\r
-  <ItemGroup>\r
-    <ProjectReference Include="../corlib/corlib-net_4_x.csproj">\r
-      <Project>{2CA6026B-2DC8-4C4C-A12C-1E8234049DB7}</Project>\r
-      <Name>corlib-net_4_x</Name>\r
-    </ProjectReference>\r
-    <ProjectReference Include="../System/System-net_4_x.csproj">\r
-      <Project>{2762E921-91A8-4C87-91E9-BA628013F753}</Project>\r
-      <Name>System-net_4_x</Name>\r
-    </ProjectReference>\r
-    <ProjectReference Include="../Mono.Security/Mono.Security-net_4_x.csproj">\r
-      <Project>{42D59DE7-586F-4ACF-BDD5-E7869E39E3EF}</Project>\r
-      <Name>Mono.Security-net_4_x</Name>\r
-    </ProjectReference>\r
-    <ProjectReference Include="../Mono.Security.Providers.NewSystemSource/Mono.Security.Providers.NewSystemSource-net_4_x.csproj">\r
-      <Project>{0BB4541F-9B1A-4CBC-BEB1-00B31B37F74E}</Project>\r
-      <Name>Mono.Security.Providers.NewSystemSource-net_4_x</Name>\r
-      <Aliases>NewSystemSource</Aliases>    </ProjectReference>\r
-  </ItemGroup>\r
-  <ItemGroup>\r
-    <Folder Include="Properties\" />\r
-  </ItemGroup>\r
-</Project>\r
-
diff --git a/mcs/class/Mono.Security.Providers.NewTls/Mono.Security.Providers.NewTls.dll.sources b/mcs/class/Mono.Security.Providers.NewTls/Mono.Security.Providers.NewTls.dll.sources
deleted file mode 100644 (file)
index 12d8a20..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-./Properties/AssemblyInfo.cs
-../../build/common/SR.cs
-../../build/common/Consts.cs
-../../build/common/Locale.cs
-
-./Mono.Security.Providers.NewTls/ITlsConfiguration.cs
-./Mono.Security.Providers.NewTls/ITlsContext.cs
-
-./Mono.Security.Providers.NewTls/MonoNewTlsStream.cs
-./Mono.Security.Providers.NewTls/MonoNewTlsStreamFactory.cs
-./Mono.Security.Providers.NewTls/NewTlsProvider.cs
-./Mono.Security.Providers.NewTls/TlsContextWrapper.cs
-./Mono.Security.Providers.NewTls/TlsProviderFactory.cs
diff --git a/mcs/class/Mono.Security.Providers.NewTls/Mono.Security.Providers.NewTls/ITlsConfiguration.cs b/mcs/class/Mono.Security.Providers.NewTls/Mono.Security.Providers.NewTls/ITlsConfiguration.cs
deleted file mode 100644 (file)
index 401afd7..0000000
+++ /dev/null
@@ -1,47 +0,0 @@
-//
-// ITlsContext.cs
-//
-// Author:
-//       Martin Baulig <martin.baulig@xamarin.com>
-//
-// Copyright (c) 2015-2016 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.Security.Cryptography;
-
-using Mono.Security.Interface;
-using MX = Mono.Security.X509;
-
-namespace Mono.Security.Providers.NewTls
-{
-       interface ITlsConfiguration
-       {
-               bool HasCredentials {
-                       get;
-               }
-
-               void SetCertificate (MX.X509Certificate certificate, AsymmetricAlgorithm privateKey);
-
-               bool? AskForClientCertificate {
-                       get; set;
-               }
-       }
-}
diff --git a/mcs/class/Mono.Security.Providers.NewTls/Mono.Security.Providers.NewTls/ITlsContext.cs b/mcs/class/Mono.Security.Providers.NewTls/Mono.Security.Providers.NewTls/ITlsContext.cs
deleted file mode 100644 (file)
index 0d69805..0000000
+++ /dev/null
@@ -1,70 +0,0 @@
-//
-// ITlsContext.cs
-//
-// Author:
-//       Martin Baulig <martin.baulig@xamarin.com>
-//
-// Copyright (c) 2015-2016 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.
-
-extern alias NewSystemSource;
-
-using System;
-using System.Security.Cryptography;
-
-using Mono.Security.Interface;
-using MX = Mono.Security.X509;
-
-namespace Mono.Security.Providers.NewTls
-{
-       interface ITlsContext : IDisposable
-       {
-               bool IsValid {
-                       get;
-               }
-
-               TlsException LastError {
-                       get;
-               }
-
-               bool ReceivedCloseNotify {
-                       get;
-               }
-
-               MonoTlsConnectionInfo ConnectionInfo {
-                       get;
-               }
-
-               MX.X509Certificate GetRemoteCertificate (out MX.X509CertificateCollection remoteCertificateStore);
-
-               bool VerifyRemoteCertificate ();
-
-               int GenerateNextToken (TlsBuffer incoming, TlsMultiBuffer outgoing);
-
-               int DecryptMessage (ref TlsBuffer incoming);
-
-               int EncryptMessage (ref TlsBuffer incoming);
-
-               byte[] CreateAlert (Alert alert);
-
-               byte[] CreateHelloRequest ();
-       }
-}
-
diff --git a/mcs/class/Mono.Security.Providers.NewTls/Mono.Security.Providers.NewTls/MonoNewTlsStream.cs b/mcs/class/Mono.Security.Providers.NewTls/Mono.Security.Providers.NewTls/MonoNewTlsStream.cs
deleted file mode 100644 (file)
index 6117f0f..0000000
+++ /dev/null
@@ -1,93 +0,0 @@
-//
-// MonoNewTlsStream.cs
-//
-// Author:
-//       Martin Baulig <martin.baulig@xamarin.com>
-//
-// Copyright (c) 2015 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.
-
-extern alias NewSystemSource;
-
-using EncryptionPolicy = NewSystemSource::System.Net.Security.EncryptionPolicy;
-using LocalCertificateSelectionCallback = NewSystemSource::System.Net.Security.LocalCertificateSelectionCallback;
-using RemoteCertificateValidationCallback = NewSystemSource::System.Net.Security.RemoteCertificateValidationCallback;
-using SslStream = NewSystemSource::System.Net.Security.SslStream;
-
-using System;
-using System.IO;
-using System.Threading.Tasks;
-
-using MSI = Mono.Security.Interface;
-
-using XAuthenticatedStream = System.Net.Security.AuthenticatedStream;
-using System.Security.Cryptography.X509Certificates;
-
-namespace Mono.Security.Providers.NewTls
-{
-       public class MonoNewTlsStream : SslStream, MSI.IMonoSslStream
-       {
-               MSI.MonoTlsProvider provider;
-
-               internal MonoNewTlsStream (Stream innerStream, MSI.MonoTlsProvider provider, MSI.MonoTlsSettings settings)
-                       : this (innerStream, false, provider, settings)
-               {
-               }
-
-               internal MonoNewTlsStream (Stream innerStream, bool leaveOpen, MSI.MonoTlsProvider provider, MSI.MonoTlsSettings settings)
-                       : base (innerStream, leaveOpen, EncryptionPolicy.RequireEncryption, provider, settings)
-               {
-                       this.provider = provider;
-               }
-
-               public MSI.MonoTlsProvider Provider {
-                       get { return provider; }
-               }
-
-               new public bool IsClosed {
-                       get { return base.IsClosed; }
-               }
-
-               public MSI.MonoTlsConnectionInfo GetConnectionInfo ()
-               {
-                       return GetMonoConnectionInfo ();
-               }
-
-               public Task Shutdown ()
-               {
-                       return Task.Factory.FromAsync ((state, result) => BeginShutdown (state, result), EndShutdown, null);
-               }
-
-               public Task RequestRenegotiation ()
-               {
-                       return Task.Factory.FromAsync ((state, result) => BeginRenegotiate (state, result), EndRenegotiate, null);
-               }
-
-                X509Certificate MSI.IMonoSslStream.InternalLocalCertificate {
-                       get { return InternalLocalCertificate; }
-               }
-
-               XAuthenticatedStream MSI.IMonoSslStream.AuthenticatedStream {
-                       get { return this; }
-               }
-       }
-}
-
-
diff --git a/mcs/class/Mono.Security.Providers.NewTls/Mono.Security.Providers.NewTls/MonoNewTlsStreamFactory.cs b/mcs/class/Mono.Security.Providers.NewTls/Mono.Security.Providers.NewTls/MonoNewTlsStreamFactory.cs
deleted file mode 100644 (file)
index d39f1bb..0000000
+++ /dev/null
@@ -1,91 +0,0 @@
-//
-// MonoNewTlsStreamFactory.cs
-//
-// Author:
-//       Martin Baulig <martin.baulig@xamarin.com>
-//
-// Copyright (c) 2015 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.
-
-extern alias NewSystemSource;
-
-using XEncryptionPolicy = NewSystemSource::System.Net.Security.EncryptionPolicy;
-using XSslPolicyErrors = NewSystemSource::System.Net.Security.SslPolicyErrors;
-using XLocalCertificateSelectionCallback = NewSystemSource::System.Net.Security.LocalCertificateSelectionCallback;
-using XRemoteCertificateValidationCallback = NewSystemSource::System.Net.Security.RemoteCertificateValidationCallback;
-
-using System;
-using System.IO;
-using System.Net.Security;
-using System.Security.Authentication;
-
-using Mono.Security.Interface;
-
-using PSSCX = System.Security.Cryptography.X509Certificates;
-using SSCX = System.Security.Cryptography.X509Certificates;
-
-namespace Mono.Security.Providers.NewTls
-{
-       public static class MonoNewTlsStreamFactory
-       {
-               internal static IMonoSslStream CreateSslStream (
-                       Stream innerStream, bool leaveInnerStreamOpen,
-                       MonoTlsProvider provider, MonoTlsSettings settings = null)
-               {
-                       return new MonoNewTlsStream (innerStream, leaveInnerStreamOpen, provider, settings);
-               }
-
-               public static MonoNewTlsStream CreateServer (
-                       Stream innerStream, bool leaveOpen, MonoTlsProvider provider, MonoTlsSettings settings,
-                       SSCX.X509Certificate serverCertificate, bool clientCertificateRequired,
-                       SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
-               {
-                       var stream = new MonoNewTlsStream (innerStream, leaveOpen, provider, settings);
-
-                       try {
-                               stream.AuthenticateAsServer (serverCertificate, clientCertificateRequired, enabledSslProtocols, checkCertificateRevocation);
-                       } catch (Exception ex) {
-                               var tlsEx = stream.LastError;
-                               if (tlsEx != null)
-                                       throw new AggregateException (ex, tlsEx);
-                               throw;
-                       }
-
-                       return stream;
-               }
-
-               public static MonoNewTlsStream CreateClient (
-                       Stream innerStream, bool leaveOpen, MonoTlsProvider provider, MonoTlsSettings settings,
-                       string targetHost, PSSCX.X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
-               {
-                       var stream = new MonoNewTlsStream (innerStream, leaveOpen, provider, settings);
-
-                       try {
-                               stream.AuthenticateAsClient (targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation);
-                       } catch (Exception ex) {
-                               var tlsEx = stream.LastError;
-                               if (tlsEx != null)
-                                       throw new AggregateException (ex, tlsEx);
-                               throw;
-                       }
-                       return stream;
-               }
-       }
-}
diff --git a/mcs/class/Mono.Security.Providers.NewTls/Mono.Security.Providers.NewTls/NewTlsProvider.cs b/mcs/class/Mono.Security.Providers.NewTls/Mono.Security.Providers.NewTls/NewTlsProvider.cs
deleted file mode 100644 (file)
index e2b347f..0000000
+++ /dev/null
@@ -1,95 +0,0 @@
-//
-// NewTlsProvider.cs
-//
-// Author:
-//       Martin Baulig <martin.baulig@xamarin.com>
-//
-// Copyright (c) 2015 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.
-
-extern alias NewSystemSource;
-
-using System;
-using System.IO;
-using System.Net;
-using System.Net.Security;
-using System.Security.Authentication;
-
-using MSI = Mono.Security.Interface;
-using MX = Mono.Security.X509;
-
-using PSSCX = System.Security.Cryptography.X509Certificates;
-using SSCX = System.Security.Cryptography.X509Certificates;
-
-namespace Mono.Security.Providers.NewTls
-{
-       public class NewTlsProvider : MSI.MonoTlsProvider
-       {
-               static readonly Guid id = new Guid ("e5ff34f1-8b7a-4aa6-aff9-24719d709693");
-
-               public override Guid ID {
-                       get { return id; }
-               }
-
-               public override string Name {
-                       get { return "newtls"; }
-               }
-
-               public override bool SupportsSslStream {
-                       get { return true; }
-               }
-
-               public override bool SupportsConnectionInfo {
-                       get { return true; }
-               }
-
-               public override bool SupportsMonoExtensions {
-                       get { return true; }
-               }
-
-               internal override bool SupportsTlsContext {
-                       get { return true; }
-               }
-
-               public override SslProtocols SupportedProtocols {
-                       get { return SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls; }
-               }
-
-               public override MSI.IMonoSslStream CreateSslStream (
-                       Stream innerStream, bool leaveInnerStreamOpen,
-                       MSI.MonoTlsSettings settings = null)
-               {
-                       return MonoNewTlsStreamFactory.CreateSslStream (innerStream, leaveInnerStreamOpen, this, settings);
-               }
-
-               internal override MSI.IMonoTlsContext CreateTlsContext (
-                       string hostname, bool serverMode, MSI.TlsProtocols protocolFlags,
-                       SSCX.X509Certificate serverCertificate, PSSCX.X509CertificateCollection clientCertificates,
-                       bool remoteCertRequired, MSI.MonoEncryptionPolicy encryptionPolicy,
-                       MSI.MonoTlsSettings settings)
-               {
-                       var config = TlsProviderFactory.CreateTlsConfiguration (
-                               hostname, serverMode, protocolFlags, serverCertificate,
-                               remoteCertRequired, settings);
-                       return new TlsContextWrapper (config, serverMode);
-               }
-       }
-}
-
diff --git a/mcs/class/Mono.Security.Providers.NewTls/Mono.Security.Providers.NewTls/TlsContextWrapper.cs b/mcs/class/Mono.Security.Providers.NewTls/Mono.Security.Providers.NewTls/TlsContextWrapper.cs
deleted file mode 100644 (file)
index 389dd1a..0000000
+++ /dev/null
@@ -1,221 +0,0 @@
-//
-// TlsContextWrapper.cs
-//
-// Author:
-//       Martin Baulig <martin.baulig@xamarin.com>
-//
-// Copyright (c) 2015 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.
-
-extern alias NewSystemSource;
-
-using System;
-using System.Security.Cryptography;
-
-using SSCX = System.Security.Cryptography.X509Certificates;
-using PSSCX = System.Security.Cryptography.X509Certificates;
-
-using MSI = Mono.Security.Interface;
-using MX = Mono.Security.X509;
-
-namespace Mono.Security.Providers.NewTls
-{
-       class TlsContextWrapper : IDisposable, MSI.IMonoTlsContext
-       {
-               ITlsConfiguration config;
-               ITlsContext context;
-               bool serverMode;
-
-               public TlsContextWrapper (ITlsConfiguration config, bool serverMode)
-               {
-                       this.config = config;
-                       this.serverMode = serverMode;
-               }
-
-               public bool IsServer {
-                       get { return serverMode; }
-               }
-
-               public bool IsValid {
-                       get { return context != null && context.IsValid; }
-               }
-
-               public void Initialize (MSI.IMonoTlsEventSink eventSink)
-               {
-                       if (context != null)
-                               throw new InvalidOperationException ();
-                       context = TlsProviderFactory.CreateTlsContext (config, serverMode, eventSink);
-               }
-
-               void Clear ()
-               {
-                       if (context != null) {
-                               context.Dispose ();
-                               context = null;
-                       }
-               }
-
-               public ITlsConfiguration Configuration {
-                       get {
-                               if (config == null)
-                                       throw new ObjectDisposedException ("TlsConfiguration");
-                               return config;
-                       }
-               }
-
-               public ITlsContext Context {
-                       get {
-                               if (!IsValid)
-                                       throw new ObjectDisposedException ("TlsContext");
-                               return context;
-                       }
-               }
-
-               public bool HasCredentials {
-                       get { return Configuration.HasCredentials; }
-               }
-
-               public void SetCertificate (SSCX.X509Certificate certificate, AsymmetricAlgorithm privateKey)
-               {
-                       var monoCert = new MX.X509Certificate (certificate.GetRawCertData ());
-                       Configuration.SetCertificate (monoCert, privateKey);
-               }
-
-               public int GenerateNextToken (MSI.IBufferOffsetSize incoming, out MSI.IBufferOffsetSize outgoing)
-               {
-                       var input = incoming != null ? new MSI.TlsBuffer (BOSWrapper.Wrap (incoming)) : null;
-                       var output = new MSI.TlsMultiBuffer ();
-                       var retval = Context.GenerateNextToken (input, output);
-                       if (output.IsEmpty)
-                               outgoing = null;
-                       outgoing = BOSWrapper.Wrap (output.StealBuffer ());
-                       return (int)retval;
-               }
-
-               public int EncryptMessage (ref MSI.IBufferOffsetSize incoming)
-               {
-                       var buffer = new MSI.TlsBuffer (BOSWrapper.Wrap (incoming));
-                       var retval = Context.EncryptMessage (ref buffer);
-                       incoming = BOSWrapper.Wrap (buffer.GetRemaining ());
-                       return (int)retval;
-               }
-
-               public int DecryptMessage (ref MSI.IBufferOffsetSize incoming)
-               {
-                       var buffer = new MSI.TlsBuffer (BOSWrapper.Wrap (incoming));
-                       var retval = Context.DecryptMessage (ref buffer);
-                       incoming = buffer != null ? BOSWrapper.Wrap (buffer.GetRemaining ()) : null;
-                       return (int)retval;
-               }
-
-               class BOSWrapper : MSI.IBufferOffsetSize
-               {
-                       public byte[] Buffer {
-                               get;
-                               private set;
-                       }
-
-                       public int Offset {
-                               get;
-                               private set;
-                       }
-
-                       public int Size {
-                               get;
-                               private set;
-                       }
-
-                       BOSWrapper (byte[] buffer, int offset, int size)
-                       {
-                               Buffer = buffer;
-                               Offset = offset;
-                               Size = size;
-                       }
-
-                       public static BOSWrapper Wrap (MSI.IBufferOffsetSize bos)
-                       {
-                               return bos != null ? new BOSWrapper (bos.Buffer, bos.Offset, bos.Size) : null;
-                       }
-               }
-
-               public byte[] CreateCloseNotify ()
-               {
-                       return Context.CreateAlert (new MSI.Alert (MSI.AlertLevel.Warning, MSI.AlertDescription.CloseNotify));
-               }
-
-               public byte[] CreateHelloRequest ()
-               {
-                       return Context.CreateHelloRequest ();
-               }
-
-               public SSCX.X509Certificate GetRemoteCertificate (out PSSCX.X509CertificateCollection remoteCertificateStore)
-               {
-                       MX.X509CertificateCollection monoCollection;
-                       var remoteCert = Context.GetRemoteCertificate (out monoCollection);
-                       if (remoteCert == null) {
-                               remoteCertificateStore = null;
-                               return null;
-                       }
-
-                       remoteCertificateStore = new PSSCX.X509CertificateCollection ();
-                       foreach (var cert in monoCollection) {
-                               remoteCertificateStore.Add (new PSSCX.X509Certificate2 (cert.RawData));
-                       }
-                       return new PSSCX.X509Certificate2 (remoteCert.RawData);
-
-               }
-
-               public bool VerifyRemoteCertificate ()
-               {
-                       return Context.VerifyRemoteCertificate ();
-               }
-
-               public Exception LastError {
-                       get {
-                               if (context != null)
-                                       return context.LastError;
-                               return null;
-                       }
-               }
-
-               public bool ReceivedCloseNotify {
-                       get {
-                               return Context.ReceivedCloseNotify;
-                       }
-               }
-
-               public MSI.MonoTlsConnectionInfo GetConnectionInfo ()
-               {
-                       return Context.ConnectionInfo;
-               }
-
-               public void Dispose ()
-               {
-                       Dispose (true);
-                       GC.SuppressFinalize (this);
-               }
-
-               void Dispose (bool disposing)
-               {
-                       Clear ();
-               }
-       }
-}
-
diff --git a/mcs/class/Mono.Security.Providers.NewTls/Mono.Security.Providers.NewTls/TlsProviderFactory.cs b/mcs/class/Mono.Security.Providers.NewTls/Mono.Security.Providers.NewTls/TlsProviderFactory.cs
deleted file mode 100644 (file)
index 92d8ab0..0000000
+++ /dev/null
@@ -1,97 +0,0 @@
-//
-// TlsProviderFactory.cs
-//
-// Author:
-//       Martin Baulig <martin.baulig@xamarin.com>
-//
-// Copyright (c) 2015-2016 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.
-
-extern alias NewSystemSource;
-
-using System;
-using System.IO;
-
-using System.Net;
-using System.Net.Security;
-using System.Security.Authentication;
-
-using MSI = Mono.Security.Interface;
-using MX = Mono.Security.X509;
-
-using PSSCX = System.Security.Cryptography.X509Certificates;
-using SSCX = System.Security.Cryptography.X509Certificates;
-
-namespace Mono.Security.Providers.NewTls
-{
-       static class TlsProviderFactory
-       {
-               const string assemblyName = "Mono.Security.NewTls, Version=4.0.0.0, Culture=neutral, PublicKeyToken=84e3aee7225169c2";
-               const string tlsConfigTypeName = "Mono.Security.NewTls.TlsConfiguration";
-               const string tlsContextTypeName = "Mono.Security.NewTls.TlsContext";
-
-               static object CreateInstance (string typeName, object[] args)
-               {
-                       var type = Type.GetType (typeName + ", " + assemblyName);
-                       return Activator.CreateInstance (type, args);
-               }
-
-               internal static ITlsConfiguration CreateTlsConfiguration (
-                       string hostname, bool serverMode, MSI.TlsProtocols protocolFlags,
-                       SSCX.X509Certificate serverCertificate, bool remoteCertRequired,
-                       MSI.MonoTlsSettings settings)
-               {
-                       object[] args;
-                       ITlsConfiguration config;
-                       if (serverMode) {
-                               var cert = (PSSCX.X509Certificate2)serverCertificate;
-                               var monoCert = new MX.X509Certificate (cert.RawData);
-                               args = new object[] {
-                                       (MSI.TlsProtocols)protocolFlags,
-                                       (MSI.MonoTlsSettings)settings,
-                                       monoCert,
-                                       cert.PrivateKey
-                               };
-                       } else {
-                               args = new object[] {
-                                       (MSI.TlsProtocols)protocolFlags,
-                                       (MSI.MonoTlsSettings)settings,
-                                       hostname
-                               };
-                       }
-
-                       config = (ITlsConfiguration)CreateInstance (tlsConfigTypeName, args);
-
-                       if (serverMode && remoteCertRequired)
-                               config.AskForClientCertificate = true;
-
-                       return config;
-               }
-
-               internal static ITlsContext CreateTlsContext (
-                       ITlsConfiguration config, bool serverMode,
-                       MSI.IMonoTlsEventSink eventSink)
-               {
-                       return (ITlsContext)CreateInstance (
-                               tlsContextTypeName,
-                               new object[] { config, serverMode, eventSink });
-               }
-       }
-}
diff --git a/mcs/class/Mono.Security.Providers.NewTls/Properties/AssemblyInfo.cs b/mcs/class/Mono.Security.Providers.NewTls/Properties/AssemblyInfo.cs
deleted file mode 100644 (file)
index e369093..0000000
+++ /dev/null
@@ -1,47 +0,0 @@
-//
-// AssemblyInfo.cs
-//
-// Author:
-//       Martin Baulig <martin.baulig@xamarin.com>
-//
-// Copyright (c) 2015 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.Reflection;
-using System.Resources;
-using System.Security;
-using System.Security.Permissions;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-
-// General Information about the system assembly
-
-[assembly: AssemblyVersion (Consts.FxVersion)]
-
-[assembly: AssemblyCompany ("Xamarin")]
-[assembly: AssemblyCopyright ("(c) 2015 Xamarin")]
-[assembly: AssemblyDescription ("Mono.Security.Providers.NewTls.dll")]
-[assembly: AssemblyProduct ("MONO CLI")]
-[assembly: AssemblyTitle ("Mono.Security.Providers.NewTls.dll")]
-[assembly: CLSCompliant (false)]
-[assembly: ComVisible (false)]
-[assembly: NeutralResourcesLanguage ("en-US")]
-
-[assembly: InternalsVisibleTo ("Mono.Security.NewTls, PublicKey=002400000480000094000000060200000024000052534131000400001100000003336d6aed41624ca156ab579881fe90a576f1dfec48378fc94e4e440f4556776224e2d70c18996d91f36227f539fdb44340e07651f1455a489b29a7e6219a8f85e52b0f8588b4f8a857746a8468d37b556223d1452f3fcbaf0f269cdf1900ceb68f69485dc5887750d19571030c732331e00387d9b813a9ad52891087301793")]
diff --git a/mcs/class/Mono.Security.Providers.NewTls/mobile_Mono.Security.Providers.NewTls.dll.sources b/mcs/class/Mono.Security.Providers.NewTls/mobile_Mono.Security.Providers.NewTls.dll.sources
deleted file mode 100644 (file)
index 7218dab..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-Properties/AssemblyInfo.cs
-
-Mono.Security.Providers.NewTls/ITlsConfiguration.cs
-Mono.Security.Providers.NewTls/ITlsContext.cs
-
-Mono.Security.Providers.NewTls/MonoNewTlsStream.cs
-Mono.Security.Providers.NewTls/MonoNewTlsStreamFactory.cs
diff --git a/mcs/class/Mono.Security.Providers.NewTls/mobile_static_Mono.Security.Providers.NewTls.dll.sources b/mcs/class/Mono.Security.Providers.NewTls/mobile_static_Mono.Security.Providers.NewTls.dll.sources
deleted file mode 100644 (file)
index baded51..0000000
+++ /dev/null
@@ -1 +0,0 @@
-#include mobile_Mono.Security.Providers.NewTls.dll.sources
diff --git a/mcs/class/Mono.Security.Providers.OldTls/Makefile b/mcs/class/Mono.Security.Providers.OldTls/Makefile
deleted file mode 100644 (file)
index 5dc06c0..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-thisdir = class/Mono.Security.Providers.OldTls
-SUBDIRS = 
-include ../../build/rules.make
-
-LIBRARY = Mono.Security.Providers.OldTls.dll
-LIB_REFS = System Mono.Security
-LIB_MCS_FLAGS = -unsafe -nowarn:1030 -keyfile:../mono.pub -delaysign -d:SECURITY_DEP
-
-include ../../build/library.make
-
-$(the_lib): ../Mono.Security/Makefile
-
diff --git a/mcs/class/Mono.Security.Providers.OldTls/Mono.Security.Providers.OldTls-net_4_x.csproj b/mcs/class/Mono.Security.Providers.OldTls/Mono.Security.Providers.OldTls-net_4_x.csproj
deleted file mode 100644 (file)
index 32ceb30..0000000
+++ /dev/null
@@ -1,167 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>\r
-<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
-  <PropertyGroup>\r
-    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
-    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
-    <ProductVersion>9.0.30729</ProductVersion>\r
-    <SchemaVersion>2.0</SchemaVersion>\r
-    <ProjectGuid>{E485E885-59B1-4081-BC66-56AAAFD8771A}</ProjectGuid>\r
-    <OutputType>Library</OutputType>\r
-    <NoWarn>1699,1030</NoWarn>\r
-    <OutputPath>./../../class/lib/net_4_x</OutputPath>\r
-    <IntermediateOutputPath>obj-net_4_x</IntermediateOutputPath>\r
-    <GenerateTargetFrameworkAttribute>false</GenerateTargetFrameworkAttribute>\r
-    <NoStdLib>True</NoStdLib>\r
-    \r
-    <NoConfig>True</NoConfig>\r
-    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\r
-    <AppDesignerFolder>Properties</AppDesignerFolder>\r
-    <RootNamespace>\r
-    </RootNamespace>\r
-    <AssemblyName>Mono.Security.Providers.OldTls</AssemblyName>\r
-    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>\r
-    <FileAlignment>512</FileAlignment>\r
-  </PropertyGroup>\r
-    <PropertyGroup>\r
-    <SignAssembly>true</SignAssembly>\r
-    <DelaySign>true</DelaySign>\r
-  </PropertyGroup>\r
-  <PropertyGroup>\r
-    <AssemblyOriginatorKeyFile>../mono.pub</AssemblyOriginatorKeyFile>\r
-  </PropertyGroup>\r
-  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
-    <DebugSymbols>true</DebugSymbols>\r
-    <DebugType>full</DebugType>\r
-    <NoWarn>1699,1030</NoWarn>\r
-    <Optimize>false</Optimize>\r
-    <DefineConstants>TRACE;NET_4_0;NET_4_5;NET_4_6;MONO;DISABLE_CAS_USE;SECURITY_DEP</DefineConstants>\r
-    <ErrorReport>prompt</ErrorReport>\r
-    <WarningLevel>4</WarningLevel>\r
-  </PropertyGroup>\r
-  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
-    <DebugType>pdbonly</DebugType>\r
-    <NoWarn>1699,1030</NoWarn>\r
-    <Optimize>true</Optimize>\r
-    <DefineConstants>NET_4_0;NET_4_5;NET_4_6;MONO;DISABLE_CAS_USE;SECURITY_DEP</DefineConstants>\r
-    <ErrorReport>prompt</ErrorReport>\r
-    <WarningLevel>4</WarningLevel>\r
-  </PropertyGroup>\r
-  <!-- Set AddAdditionalExplicitAssemblyReferences to false, otherwise if targetting .NET4.0, \r
-  Microsoft.NETFramework.props will force a dependency on the assembly System.Core. This\r
-  is a problem to compile the Mono mscorlib.dll -->\r
-  <PropertyGroup>\r
-    <AddAdditionalExplicitAssemblyReferences>false</AddAdditionalExplicitAssemblyReferences>\r
-  </PropertyGroup>\r
-  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
-  <ItemGroup>\r
-    <Compile Include="..\..\build\common\Consts.cs" />\r
-    <Compile Include="..\..\build\common\Locale.cs" />\r
-    <Compile Include="..\..\build\common\MonoTODOAttribute.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Cryptography\MD5SHA1.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Cryptography\TlsHMAC.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls.Handshake.Client\TlsClientCertificate.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls.Handshake.Client\TlsClientCertificateVerify.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls.Handshake.Client\TlsClientFinished.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls.Handshake.Client\TlsClientHello.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls.Handshake.Client\TlsClientKeyExchange.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls.Handshake.Client\TlsServerCertificate.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls.Handshake.Client\TlsServerCertificateRequest.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls.Handshake.Client\TlsServerFinished.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls.Handshake.Client\TlsServerHello.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls.Handshake.Client\TlsServerHelloDone.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls.Handshake.Client\TlsServerKeyExchange.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls.Handshake.Server\TlsClientCertificate.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls.Handshake.Server\TlsClientCertificateVerify.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls.Handshake.Server\TlsClientFinished.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls.Handshake.Server\TlsClientHello.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls.Handshake.Server\TlsClientKeyExchange.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls.Handshake.Server\TlsServerCertificate.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls.Handshake.Server\TlsServerCertificateRequest.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls.Handshake.Server\TlsServerFinished.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls.Handshake.Server\TlsServerHello.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls.Handshake.Server\TlsServerHelloDone.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls.Handshake.Server\TlsServerKeyExchange.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls.Handshake\ClientCertificateType.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls.Handshake\HandshakeMessage.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls.Handshake\HandshakeType.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\Alert.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\CipherAlgorithmType.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\CipherSuite.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\CipherSuiteCollection.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\CipherSuiteFactory.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\ClientContext.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\ClientRecordProtocol.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\ClientSessionCache.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\ContentType.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\Context.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\DebugHelper.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\ExchangeAlgorithmType.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\HandshakeState.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\HashAlgorithmType.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\HttpsClientStream.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\RecordProtocol.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\RSASslSignatureDeformatter.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\RSASslSignatureFormatter.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\SecurityCompressionType.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\SecurityParameters.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\SecurityProtocolType.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\ServerContext.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\ServerRecordProtocol.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\SslCipherSuite.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\SslClientStream.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\SslHandshakeHash.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\SslServerStream.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\SslStreamBase.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\TlsCipherSuite.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\TlsClientSettings.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\TlsException.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\TlsServerSettings.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.Protocol.Tls\TlsStream.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.X509.Extensions\AuthorityKeyIdentifierExtension.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.X509.Extensions\ExtendedKeyUsageExtension.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.X509.Extensions\GeneralNames.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.X509.Extensions\NetscapeCertTypeExtension.cs" />\r
-    <Compile Include="..\Mono.Security\Mono.Security.X509.Extensions\SubjectAltNameExtension.cs" />\r
-    <Compile Include="..\System\Mono.Net.Security\LegacySslStream.cs" />\r
-    <Compile Include=".\Mono.Security.Providers.OldTls\OldTlsProvider.cs" />\r
-    <Compile Include=".\Properties\AssemblyInfo.cs" />\r  </ItemGroup>\r
-  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r
-       Other similar extension points exist, see Microsoft.Common.targets.\r
-  <Target Name="BeforeBuild">\r
-  </Target>\r
-  <Target Name="AfterBuild">\r
-  </Target>\r
-  -->\r
-  <PropertyGroup>\r
-    <PreBuildEvent Condition=" '$(OS)' != 'Windows_NT' ">
-
-    </PreBuildEvent>\r
-    <PreBuildEvent Condition=" '$(OS)' == 'Windows_NT' ">\r
-\r
-    </PreBuildEvent>\r
-    <PostBuildEvent Condition=" '$(OS)' != 'Windows_NT' ">
-
-    </PostBuildEvent>\r
-    <PostBuildEvent Condition=" '$(OS)' == 'Windows_NT' ">\r
-\r
-    </PostBuildEvent>\r
-  </PropertyGroup>\r
-  <ItemGroup>\r
-    <ProjectReference Include="../corlib/corlib-net_4_x.csproj">\r
-      <Project>{2CA6026B-2DC8-4C4C-A12C-1E8234049DB7}</Project>\r
-      <Name>corlib-net_4_x</Name>\r
-    </ProjectReference>\r
-    <ProjectReference Include="../System/System-net_4_x.csproj">\r
-      <Project>{2762E921-91A8-4C87-91E9-BA628013F753}</Project>\r
-      <Name>System-net_4_x</Name>\r
-    </ProjectReference>\r
-    <ProjectReference Include="../Mono.Security/Mono.Security-net_4_x.csproj">\r
-      <Project>{42D59DE7-586F-4ACF-BDD5-E7869E39E3EF}</Project>\r
-      <Name>Mono.Security-net_4_x</Name>\r
-    </ProjectReference>\r
-  </ItemGroup>\r
-  <ItemGroup>\r
-    <Folder Include="Properties\" />\r
-  </ItemGroup>\r
-</Project>\r
-
diff --git a/mcs/class/Mono.Security.Providers.OldTls/Mono.Security.Providers.OldTls.dll.sources b/mcs/class/Mono.Security.Providers.OldTls/Mono.Security.Providers.OldTls.dll.sources
deleted file mode 100644 (file)
index 13653b8..0000000
+++ /dev/null
@@ -1,73 +0,0 @@
-./Properties/AssemblyInfo.cs
-../../build/common/Consts.cs
-../../build/common/Locale.cs
-../../build/common/MonoTODOAttribute.cs
-
-./Mono.Security.Providers.OldTls/OldTlsProvider.cs
-../System/Mono.Net.Security/LegacySslStream.cs
-
-../Mono.Security/Mono.Security.Cryptography/MD5SHA1.cs
-../Mono.Security/Mono.Security.Cryptography/TlsHMAC.cs
-../Mono.Security/Mono.Security.Protocol.Tls/Alert.cs
-../Mono.Security/Mono.Security.Protocol.Tls/CipherAlgorithmType.cs
-../Mono.Security/Mono.Security.Protocol.Tls/CipherSuite.cs
-../Mono.Security/Mono.Security.Protocol.Tls/CipherSuiteCollection.cs
-../Mono.Security/Mono.Security.Protocol.Tls/CipherSuiteFactory.cs
-../Mono.Security/Mono.Security.Protocol.Tls/ClientContext.cs
-../Mono.Security/Mono.Security.Protocol.Tls/ClientRecordProtocol.cs
-../Mono.Security/Mono.Security.Protocol.Tls/ClientSessionCache.cs
-../Mono.Security/Mono.Security.Protocol.Tls/ContentType.cs
-../Mono.Security/Mono.Security.Protocol.Tls/Context.cs
-../Mono.Security/Mono.Security.Protocol.Tls/DebugHelper.cs
-../Mono.Security/Mono.Security.Protocol.Tls/ExchangeAlgorithmType.cs
-../Mono.Security/Mono.Security.Protocol.Tls/HandshakeState.cs
-../Mono.Security/Mono.Security.Protocol.Tls/HashAlgorithmType.cs
-../Mono.Security/Mono.Security.Protocol.Tls/HttpsClientStream.cs
-../Mono.Security/Mono.Security.Protocol.Tls/RecordProtocol.cs
-../Mono.Security/Mono.Security.Protocol.Tls/RSASslSignatureDeformatter.cs
-../Mono.Security/Mono.Security.Protocol.Tls/RSASslSignatureFormatter.cs
-../Mono.Security/Mono.Security.Protocol.Tls/SecurityCompressionType.cs
-../Mono.Security/Mono.Security.Protocol.Tls/SecurityParameters.cs
-../Mono.Security/Mono.Security.Protocol.Tls/SecurityProtocolType.cs
-../Mono.Security/Mono.Security.Protocol.Tls/ServerContext.cs
-../Mono.Security/Mono.Security.Protocol.Tls/ServerRecordProtocol.cs
-../Mono.Security/Mono.Security.Protocol.Tls/SslClientStream.cs
-../Mono.Security/Mono.Security.Protocol.Tls/SslCipherSuite.cs
-../Mono.Security/Mono.Security.Protocol.Tls/SslHandshakeHash.cs
-../Mono.Security/Mono.Security.Protocol.Tls/SslServerStream.cs
-../Mono.Security/Mono.Security.Protocol.Tls/SslStreamBase.cs
-../Mono.Security/Mono.Security.Protocol.Tls/TlsCipherSuite.cs
-../Mono.Security/Mono.Security.Protocol.Tls/TlsClientSettings.cs
-../Mono.Security/Mono.Security.Protocol.Tls/TlsException.cs
-../Mono.Security/Mono.Security.Protocol.Tls/TlsServerSettings.cs
-../Mono.Security/Mono.Security.Protocol.Tls/TlsStream.cs
-../Mono.Security/Mono.Security.Protocol.Tls.Handshake/ClientCertificateType.cs
-../Mono.Security/Mono.Security.Protocol.Tls.Handshake/HandshakeMessage.cs
-../Mono.Security/Mono.Security.Protocol.Tls.Handshake/HandshakeType.cs
-../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsClientCertificate.cs
-../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsClientCertificateVerify.cs
-../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsClientFinished.cs
-../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsClientHello.cs
-../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsClientKeyExchange.cs
-../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerCertificate.cs
-../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerCertificateRequest.cs
-../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerFinished.cs
-../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerHello.cs
-../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerHelloDone.cs
-../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerKeyExchange.cs
-../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientCertificate.cs
-../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientCertificateVerify.cs
-../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientFinished.cs
-../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientHello.cs
-../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientKeyExchange.cs
-../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerCertificate.cs
-../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerCertificateRequest.cs
-../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerFinished.cs
-../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerHello.cs
-../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerHelloDone.cs
-../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerKeyExchange.cs
-../Mono.Security/Mono.Security.X509.Extensions/AuthorityKeyIdentifierExtension.cs
-../Mono.Security/Mono.Security.X509.Extensions/ExtendedKeyUsageExtension.cs
-../Mono.Security/Mono.Security.X509.Extensions/GeneralNames.cs
-../Mono.Security/Mono.Security.X509.Extensions/NetscapeCertTypeExtension.cs
-../Mono.Security/Mono.Security.X509.Extensions/SubjectAltNameExtension.cs
diff --git a/mcs/class/Mono.Security.Providers.OldTls/Mono.Security.Providers.OldTls/OldTlsProvider.cs b/mcs/class/Mono.Security.Providers.OldTls/Mono.Security.Providers.OldTls/OldTlsProvider.cs
deleted file mode 100644 (file)
index 4532a17..0000000
+++ /dev/null
@@ -1,87 +0,0 @@
-//
-// OldTlsProvider.cs
-//
-// Author:
-//       Martin Baulig <martin.baulig@xamarin.com>
-//
-// Copyright (c) 2015 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.IO;
-using System.Net;
-using System.Net.Security;
-using System.Security.Authentication;
-using System.Security.Cryptography.X509Certificates;
-using Mono.Security.Interface;
-using MNS = Mono.Net.Security;
-
-namespace Mono.Security.Providers.OldTls
-{
-       public class OldTlsProvider : MonoTlsProvider
-       {
-               static readonly Guid id = new Guid ("cf8baa0d-c6ed-40ae-b512-dec8d097e9af");
-
-               public override Guid ID {
-                       get { return id; }
-               }
-
-               public override string Name {
-                       get { return "old"; }
-               }
-
-               public override bool SupportsSslStream {
-                       get { return true; }
-               }
-
-               public override bool SupportsMonoExtensions {
-                       get { return false; }
-               }
-
-               public override bool SupportsConnectionInfo {
-                       get { return false; }
-               }
-
-               internal override bool SupportsTlsContext {
-                       get { return false; }
-               }
-
-               public override SslProtocols SupportedProtocols {
-                       get { return SslProtocols.Tls; }
-               }
-
-               public override IMonoSslStream CreateSslStream (
-                       Stream innerStream, bool leaveInnerStreamOpen,
-                       MonoTlsSettings settings = null)
-               {
-                       var impl = new MNS.Private.LegacySslStream (innerStream, leaveInnerStreamOpen, this, settings);
-                       return new MNS.Private.MonoSslStreamImpl (impl);
-               }
-
-               internal override IMonoTlsContext CreateTlsContext (
-                       string hostname, bool serverMode, TlsProtocols protocolFlags,
-                       X509Certificate serverCertificate, X509CertificateCollection clientCertificates,
-                       bool remoteCertRequired, MonoEncryptionPolicy encryptionPolicy,
-                       MonoTlsSettings settings)
-               {
-                       throw new NotSupportedException ();
-               }
-       }
-}
-
diff --git a/mcs/class/Mono.Security.Providers.OldTls/Properties/AssemblyInfo.cs b/mcs/class/Mono.Security.Providers.OldTls/Properties/AssemblyInfo.cs
deleted file mode 100644 (file)
index 923beca..0000000
+++ /dev/null
@@ -1,46 +0,0 @@
-//
-// AssemblyInfo.cs
-//
-// Author:
-//       Martin Baulig <martin.baulig@xamarin.com>
-//
-// Copyright (c) 2015 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.Reflection;
-using System.Resources;
-using System.Security;
-using System.Security.Permissions;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-
-// General Information about the system assembly
-
-[assembly: AssemblyVersion (Consts.FxVersion)]
-
-[assembly: AssemblyCompany ("MONO development team")]
-[assembly: AssemblyCopyright ("(c) 2015 Xamarin")]
-[assembly: AssemblyDescription ("Mono.Security.Providers.OldTls.dll")]
-[assembly: AssemblyProduct ("MONO CLI")]
-[assembly: AssemblyTitle ("Mono.Security.Providers.OldTls.dll")]
-[assembly: CLSCompliant (true)]
-[assembly: ComVisible (false)]
-[assembly: NeutralResourcesLanguage ("en-US")]
-
index 3e79d28a8fe09fc504f1cba2557b16b862df859c..eeccc251f7d6ed12f515024c5183ee374d19e6e4 100644 (file)
@@ -66,8 +66,3 @@ using System.Runtime.InteropServices;
 [assembly: InternalsVisibleTo ("System, PublicKey=00000000000000000400000000000000")]
 #endif
 
-[assembly: InternalsVisibleTo ("Mono.Security.Providers.NewTls, PublicKey=002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df")]
-[assembly: InternalsVisibleTo ("Mono.Security.Providers.OldTls, PublicKey=002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df")]
-[assembly: InternalsVisibleTo ("Mono.Security.Providers.DotNet, PublicKey=002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df")]
-[assembly: InternalsVisibleTo ("Mono.Security.Providers.NewSystemSource, PublicKey=002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df")]
-[assembly: InternalsVisibleTo ("Xamarin.BoringTls, PublicKey=002400000480000094000000060200000024000052534131000400001100000099dd12eda85767ae6f06023ee28e711c7e5a212462095c83868c29db75eddf6d8e296e03824c14fedd5f55553fed0b6173be3cc985a4b7f9fb7c83ccff8ba3938563b3d1f45a81122f12a1bcb73edcaad61a8456c7595a6da5184b4dd9d10f011b949ef1391fccfeab1ba62aa51c267ef8bd57ef1b6ba5a4c515d0badb81a78f")]
index e6e48767bf6173f7e82fe65dc206f5ef05123932..70678d2f0ca39e3d36eefc4f9dcf8c88446b46f3 100644 (file)
@@ -92,7 +92,6 @@
     <Compile Include=".\Mono.Security.Interface\HashAlgorithmType.cs" />\r
     <Compile Include=".\Mono.Security.Interface\IBufferOffsetSize.cs" />\r
     <Compile Include=".\Mono.Security.Interface\IMonoSslStream.cs" />\r
-    <Compile Include=".\Mono.Security.Interface\IMonoTlsContext.cs" />\r
     <Compile Include=".\Mono.Security.Interface\IMonoTlsEventSink.cs" />\r
     <Compile Include=".\Mono.Security.Interface\MonoTlsConnectionInfo.cs" />\r
     <Compile Include=".\Mono.Security.Interface\MonoTlsProvider.cs" />\r
index fd392b409e5a4bef6de68f174911b79f638997be..98805605c08ba236deee6556e1a31dcca5cd9989 100644 (file)
@@ -103,13 +103,6 @@ namespace Mono.Security.Interface
                 * Internal use only.
                 */
                ValidationResult ValidateCertificate (string targetHost, bool serverMode, X509Certificate leaf, X509Chain chain);
-
-               /*
-                * On OS X and Mobile, the @chain will be initialized with the @certificates, but not actually built.
-                */
-               bool InvokeSystemValidator (
-                       string targetHost, bool serverMode, X509CertificateCollection certificates,
-                       X509Chain chain, ref MonoSslPolicyErrors errors, ref int status11);
        }
 
        public static class CertificateValidationHelper
@@ -148,17 +141,23 @@ namespace Mono.Security.Interface
                /*
                 * Internal API, intended to be used by MonoTlsProvider implementations.
                 */
+               internal static ICertificateValidator2 GetInternalValidator (MonoTlsSettings settings, MonoTlsProvider provider)
+               {
+                       return (ICertificateValidator2)NoReflectionHelper.GetInternalValidator (provider, settings);
+               }
+
+               [Obsolete ("Use GetInternalValidator")]
                internal static ICertificateValidator2 GetDefaultValidator (MonoTlsSettings settings, MonoTlsProvider provider)
                {
-                       return (ICertificateValidator2)NoReflectionHelper.GetDefaultCertificateValidator (provider, settings);
+                       return GetInternalValidator (settings, provider);
                }
 
                /*
                 * Use this overloaded version in user code.
                 */
-               public static ICertificateValidator GetValidator (MonoTlsSettings settings, MonoTlsProvider provider = null)
+               public static ICertificateValidator GetValidator (MonoTlsSettings settings)
                {
-                       return GetDefaultValidator (settings, provider);
+                       return (ICertificateValidator)NoReflectionHelper.GetDefaultValidator (settings);
                }
        }
 }
index 66980df81a6ab254278b5c6a057681128fa431ba..1060677c59401a0666c75cac1cc844348f3a60be 100644 (file)
@@ -31,6 +31,7 @@ namespace Mono.Security.Interface
        /// <summary>
        /// RFC 2246 A.5
        /// </summary>
+       [CLSCompliant (false)]
        public enum CipherSuiteCode : ushort
        {
                TLS_NULL_WITH_NULL_NULL = 0x0000,
diff --git a/mcs/class/Mono.Security/Mono.Security.Interface/IMonoTlsContext.cs b/mcs/class/Mono.Security/Mono.Security.Interface/IMonoTlsContext.cs
deleted file mode 100644 (file)
index d1ac4e2..0000000
+++ /dev/null
@@ -1,71 +0,0 @@
-//
-// IMonoTlsContext.cs
-//
-// Author:
-//       Martin Baulig <martin.baulig@xamarin.com>
-//
-// Copyright (c) 2015 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.Security.Cryptography;
-using System.Security.Cryptography.X509Certificates;
-
-namespace Mono.Security.Interface
-{
-       interface IMonoTlsContext : IDisposable
-       {
-               bool IsServer {
-                       get;
-               }
-
-               bool IsValid {
-                       get;
-               }
-
-               void Initialize (IMonoTlsEventSink eventSink);
-
-               bool HasCredentials {
-                       get;
-               }
-
-               void SetCertificate (X509Certificate certificate, AsymmetricAlgorithm privateKey);
-
-               int GenerateNextToken (IBufferOffsetSize incoming, out IBufferOffsetSize outgoing);
-
-               int EncryptMessage (ref IBufferOffsetSize incoming);
-
-               int DecryptMessage (ref IBufferOffsetSize incoming);
-
-               bool ReceivedCloseNotify {
-                       get;
-               }
-
-               byte[] CreateCloseNotify ();
-
-               byte[] CreateHelloRequest ();
-
-               X509Certificate GetRemoteCertificate (out X509CertificateCollection remoteCertificateStore);
-
-               bool VerifyRemoteCertificate ();
-
-               MonoTlsConnectionInfo GetConnectionInfo ();
-       }
-}
-
index 4bc5f436f454b6bb8e2e7e1896524836ddcc728f..120d885eaf07985e921eae567a3ef56bfa63177a 100644 (file)
@@ -29,6 +29,7 @@ namespace Mono.Security.Interface
 {
        public class MonoTlsConnectionInfo
        {
+               [CLSCompliant (false)]
                public CipherSuiteCode CipherSuiteCode {
                        get; set;
                }
@@ -49,6 +50,10 @@ namespace Mono.Security.Interface
                        get; set;
                }
 
+               public string PeerDomainName {
+                       get; set;
+               }
+
                public override string ToString ()
                {
                        return string.Format ("[MonoTlsConnectionInfo: {0}:{1}]", ProtocolVersion, CipherSuiteCode);
index 089d8447a78993d3a4015cf4ad40b6a47cb6f6ed..0d7a7512d6a758659c5d10268874eaae2e726b02 100644 (file)
@@ -145,14 +145,6 @@ namespace Mono.Security.Interface
 #endregion
 
 #region Certificate Validation
-
-               /*
-                * Allows a TLS provider to provide a custom system certificiate validator.
-                */
-               internal virtual bool HasCustomSystemCertificateValidator {
-                       get { return false; }
-               }
-
                /*
                 * If @serverMode is true, then we're a server and want to validate a certificate
                 * that we received from a client.
@@ -162,32 +154,10 @@ namespace Mono.Security.Interface
                 * Returns `true` if certificate validation has been performed and `false` to invoke the
                 * default system validator.
                 */
-               internal virtual bool InvokeSystemCertificateValidator (
+               internal abstract bool ValidateCertificate (
                        ICertificateValidator2 validator, string targetHost, bool serverMode,
                        X509CertificateCollection certificates, bool wantsChain, ref X509Chain chain,
-                       out bool success, ref MonoSslPolicyErrors errors, ref int status11)
-               {
-                       throw new InvalidOperationException ();
-               }
-
-#endregion
-
-#region Manged SSPI
-
-               /*
-                * The managed SSPI implementation from the new TLS code.
-                */
-
-               internal abstract bool SupportsTlsContext {
-                       get;
-               }
-
-               internal abstract IMonoTlsContext CreateTlsContext (
-                       string hostname, bool serverMode, TlsProtocols protocolFlags,
-                       X509Certificate serverCertificate, X509CertificateCollection clientCertificates,
-                       bool remoteCertRequired, MonoEncryptionPolicy encryptionPolicy,
-                       MonoTlsSettings settings);
-
+                       ref MonoSslPolicyErrors errors, ref int status11);
 #endregion
        }
 }
index 557d024da21f8495e0dfdc804c3f030f641c13af..a9983f129077b3e9e21bb19f3a533bdda60df04e 100644 (file)
@@ -39,7 +39,37 @@ namespace Mono.Security.Interface
        public static partial class MonoTlsProviderFactory
        {
                /*
-                * Returns the currently installed @MonoTlsProvider, falling back to the default one.
+                * TLS Provider Initialization
+                * ===========================
+                * 
+                * The "global" TLS Provider (returned by GetProvider()) may only be modified at
+                * application startup (before any of the TLS / Certificate code has been used).
+                * 
+                * On mobile, the default provider is specified at compile time using a property
+                * in the .csproj file (which can be set from the IDE).  When using the linker, all
+                * other providers will be linked-out, so you won't be able to choose a different
+                * provider at run-time.
+                * 
+                * On desktop, the default provider can be specified with the MONO_TLS_PROVIDER
+                * environment variable.  The following options are currently supported:
+                * 
+                *    "default" - let Mono pick the best one for you (recommended)
+                *    "old" or "legacy" - Mono's old managed TLS implementation
+                *    "appletls" (currently XamMac only, set via .csproj property)
+                *    "btls" - the new boringssl based provider (coming soon).
+                * 
+                * On all platforms (except mobile with linker), you can call
+                * 
+                *     MonoTlsProviderFactory.Initialize(string)
+                * 
+                * to use a different provider.
+                * 
+                */
+
+               #region Provider Initialization
+
+               /*
+                * Returns the global @MonoTlsProvider, initializing the TLS Subsystem if necessary.
                 *
                 * This method throws @NotSupportedException if no TLS Provider can be found.
                 */
@@ -49,42 +79,64 @@ namespace Mono.Security.Interface
                }
 
                /*
-                * Returns the default @MonoTlsProvider.
-                *
-                * This method throws @NotSupportedException if no TLS Provider can be found.
+                * Check whether the TLS Subsystem is initialized.
                 */
-               public static MonoTlsProvider GetDefaultProvider ()
+               public static bool IsInitialized {
+                       get {
+                               return NoReflectionHelper.IsInitialized;
+                       }
+               }
+
+               /*
+                * Initialize the TLS Subsystem.
+                * 
+                * This method may be called at any time.  It ensures that the TLS Subsystem is
+                * initialized and a provider available.
+                */
+               public static void Initialize ()
                {
-                       return (MonoTlsProvider)NoReflectionHelper.GetDefaultProvider ();
+                       NoReflectionHelper.Initialize ();
                }
 
                /*
-                * GetProvider() attempts to load and install the default provider and throws on error.
-                *
-                * This property checks whether a provider has previously been installed by a call
-                * to either GetProvider() or InstallProvider().
-                *
+                * Initialize the TLS Subsystem with a specific provider.
+                * 
+                * May only be called at application startup (before any of the TLS / Certificate
+                * APIs have been used).
+                * 
+                * Throws @NotSupportedException if the TLS Subsystem is already initialized
+                * (@IsInitialized returns true) or the requested provider is not supported.
+                * 
+                * On mobile, this will always throw @NotSupportedException when using the linker.
                 */
-               public static bool HasProvider {
-                       get {
-                               return NoReflectionHelper.HasProvider;
-                       }
+               public static void Initialize (string provider)
+               {
+                       NoReflectionHelper.Initialize (provider);
                }
 
                /*
-                * Selects the default TLS Provider.
+                * Checks whether @provider is supported.
                 *
-                * May only be called at application startup and will throw
-                * @InvalidOperationException if a provider has already been installed.
+                * On mobile, this will always return false when using the linker.
                 */
-               public static void SetDefaultProvider (string name)
+               public static bool IsProviderSupported (string provider)
                {
-                       NoReflectionHelper.SetDefaultProvider (name);
+                       return NoReflectionHelper.IsProviderSupported (provider);
                }
 
-               public static MonoTlsProvider GetProvider (string name)
+               #endregion
+
+               #region Call-by-call selection
+
+               /*
+                * Returns the requested TLS Provider, for use with the call-by-call APIs below.
+                * 
+                * Throw @NotSupportedException if the requested provider is not supported or
+                * when using the linker on mobile.
+                */
+               public static MonoTlsProvider GetProvider (string provider)
                {
-                       return (MonoTlsProvider)NoReflectionHelper.GetProvider (name);
+                       return (MonoTlsProvider)NoReflectionHelper.GetProvider (provider);
                }
 
                /*
@@ -108,6 +160,24 @@ namespace Mono.Security.Interface
                {
                        return (IMonoSslStream)NoReflectionHelper.GetMonoSslStream (stream);
                }
+
+               #endregion
+
+               #region Obsolete APIs
+
+               [Obsolete]
+               public static MonoTlsProvider GetDefaultProvider ()
+               {
+                       return GetProvider ();
+               }
+
+               [Obsolete]
+               public static void SetDefaultProvider (string name)
+               {
+                       Initialize (name);
+               }
+
+               #endregion
        }
 }
 
index 24b28a790efd6398311b34e526a8b9fb395bce0c..7721bb00a51d6add53e50ce177ef3dacbdcf8803 100644 (file)
@@ -82,6 +82,7 @@ namespace Mono.Security.Interface
                        get; set;
                }
 
+               [CLSCompliant (false)]
                public CipherSuiteCode[] EnabledCiphers {
                        get; set;
                }
index cb96ce12e4626fcb93c168b0d84a461f2b3a5a57..e74c7be0dd9773ce6f048fadc031d3178e8cc40e 100644 (file)
@@ -38,6 +38,8 @@ using System.Security.Cryptography;
 using Mono.Security.Cryptography;
 using Mono.Security.X509.Extensions;
 
+using SSCX = System.Security.Cryptography.X509Certificates;
+
 namespace Mono.Security.X509 {
 
 #if INSIDE_CORLIB
@@ -51,12 +53,14 @@ namespace Mono.Security.X509 {
                private X509CertificateCollection _certificates;
                private ArrayList _crls;
                private bool _crl;
+               private bool _newFormat;
                private string _name;
 
-               internal X509Store (string path, bool crl
+               internal X509Store (string path, bool crl, bool newFormat)
                {
                        _storePath = path;
                        _crl = crl;
+                       _newFormat = newFormat;
                }
 
                // properties
@@ -126,6 +130,11 @@ namespace Mono.Security.X509 {
                {
                        CheckStore (_storePath, true);
 
+                       if (_newFormat) {
+                               ImportNewFormat (certificate);
+                               return;
+                       }
+
                        string filename = Path.Combine (_storePath, GetUniqueName (certificate));
                        if (!File.Exists (filename)) {
                                filename = Path.Combine (_storePath, GetUniqueNameWithSerial (certificate));
@@ -165,6 +174,9 @@ namespace Mono.Security.X509 {
                {
                        CheckStore (_storePath, true);
 
+                       if (_newFormat)
+                               throw new NotSupportedException ();
+
                        string filename = Path.Combine (_storePath, GetUniqueName (crl));
                        if (!File.Exists (filename)) {
                                using (FileStream fs = File.Create (filename)) {
@@ -177,6 +189,11 @@ namespace Mono.Security.X509 {
 
                public void Remove (X509Certificate certificate) 
                {
+                       if (_newFormat) {
+                               RemoveNewFormat (certificate);
+                               return;
+                       }
+
                        string filename = Path.Combine (_storePath, GetUniqueNameWithSerial (certificate));
                        if (File.Exists (filename)) {
                                File.Delete (filename);
@@ -192,6 +209,9 @@ namespace Mono.Security.X509 {
 
                public void Remove (X509Crl crl) 
                {
+                       if (_newFormat)
+                               throw new NotSupportedException ();
+
                        string filename = Path.Combine (_storePath, GetUniqueName (crl));
                        if (File.Exists (filename)) {
                                File.Delete (filename);
@@ -199,6 +219,41 @@ namespace Mono.Security.X509 {
                        }
                }
 
+               // new format
+
+               void ImportNewFormat (X509Certificate certificate)
+               {
+#if INSIDE_CORLIB
+                       throw new NotSupportedException ();
+#else
+                       using (var sscxCert = new SSCX.X509Certificate (certificate.RawData)) {
+                               var hash = SSCX.X509Helper2.GetSubjectNameHash (sscxCert);
+                               var filename = Path.Combine (_storePath, string.Format ("{0:x8}.0", hash));
+                               if (!File.Exists (filename)) {
+                                       using (FileStream fs = File.Create (filename))
+                                               SSCX.X509Helper2.ExportAsPEM (sscxCert, fs, true);
+                                       ClearCertificates ();
+                               }
+                       }
+#endif
+               }
+
+               void RemoveNewFormat (X509Certificate certificate)
+               {
+#if INSIDE_CORLIB
+                       throw new NotSupportedException ();
+#else
+                       using (var sscxCert = new SSCX.X509Certificate (certificate.RawData)) {
+                               var hash = SSCX.X509Helper2.GetSubjectNameHash (sscxCert);
+                               var filename = Path.Combine (_storePath, string.Format ("{0:x8}.0", hash));
+                               if (File.Exists (filename)) {
+                                       File.Delete (filename);
+                                       ClearCertificates ();
+                               }
+                       }
+#endif
+               }
+
                // private stuff
 
                private string GetUniqueNameWithSerial (X509Certificate certificate)
index db735834acd4ca39c0310cca71612eeadac7a7c9..7f31713b1b226e6aed757774cbd181afb28c159a 100644 (file)
@@ -45,8 +45,12 @@ namespace Mono.Security.X509 {
 
                static private string _userPath;
                static private string _localMachinePath;
+               static private string _newUserPath;
+               static private string _newLocalMachinePath;
                static private X509Stores _userStore;
                static private X509Stores _machineStore;
+               static private X509Stores _newUserStore;
+               static private X509Stores _newMachineStore;
 
                private X509StoreManager ()
                {
@@ -55,10 +59,10 @@ namespace Mono.Security.X509 {
                internal static string CurrentUserPath {
                        get {
                                if (_userPath == null) {
-                                       _userPath = Path.Combine(
-                                                       Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
+                                       _userPath = Path.Combine (
+                                                       Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData),
                                                        ".mono");
-                                       _userPath = Path.Combine(_userPath, "certs");
+                                       _userPath = Path.Combine (_userPath, "certs");
                                }
                                return _userPath;
                        }
@@ -76,10 +80,34 @@ namespace Mono.Security.X509 {
                        }
                }
 
+               internal static string NewCurrentUserPath {
+                       get {
+                               if (_newUserPath == null) {
+                                       _newUserPath = Path.Combine (
+                                                       Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData),
+                                                       ".mono");
+                                       _newUserPath = Path.Combine (_newUserPath, "new-certs");
+                               }
+                               return _newUserPath;
+                       }
+               }
+
+               internal static string NewLocalMachinePath {
+                       get {
+                               if (_newLocalMachinePath == null) {
+                                       _newLocalMachinePath = Path.Combine (
+                                               Environment.GetFolderPath (Environment.SpecialFolder.CommonApplicationData),
+                                               ".mono");
+                                       _newLocalMachinePath = Path.Combine (_newLocalMachinePath, "new-certs");
+                               }
+                               return _newLocalMachinePath;
+                       }
+               }
+
                static public X509Stores CurrentUser {
                        get { 
                                if (_userStore == null)
-                                       _userStore = new X509Stores(CurrentUserPath);
+                                       _userStore = new X509Stores (CurrentUserPath, false);
                                
                                return _userStore;
                        }
@@ -88,12 +116,30 @@ namespace Mono.Security.X509 {
                static public X509Stores LocalMachine {
                        get {
                                if (_machineStore == null) 
-                                       _machineStore = new X509Stores (LocalMachinePath);
+                                       _machineStore = new X509Stores (LocalMachinePath, false);
 
                                return _machineStore;
                        }
                }
 
+               static public X509Stores NewCurrentUser {
+                       get {
+                               if (_newUserStore == null)
+                                       _newUserStore = new X509Stores (NewCurrentUserPath, true);
+
+                               return _newUserStore;
+                       }
+               }
+
+               static public X509Stores NewLocalMachine {
+                       get {
+                               if (_newMachineStore == null)
+                                       _newMachineStore = new X509Stores (NewLocalMachinePath, true);
+
+                               return _newMachineStore;
+                       }
+               }
+
                // Merged stores collections
                // we need to look at both the user and the machine (entreprise)
                // certificates/CRLs when building/validating a chain
index bfe7451b5dee1c229ac4ff2ae990ff92a60af0b8..071faa70dddefdf8aa7c6f8f7b33f2f80dad92e4 100644 (file)
@@ -44,15 +44,17 @@ namespace Mono.Security.X509 {
        class X509Stores {
 
                private string _storePath;
+               private bool _newFormat;
                private X509Store _personal;
                private X509Store _other;
                private X509Store _intermediate;
                private X509Store _trusted;
                private X509Store _untrusted;
 
-               internal X509Stores (string path
+               internal X509Stores (string path, bool newFormat)
                {
                        _storePath = path;
+                       _newFormat = newFormat;
                }
 
                // properties
@@ -61,7 +63,7 @@ namespace Mono.Security.X509 {
                        get { 
                                if (_personal == null) {
                                        string path = Path.Combine (_storePath, Names.Personal);
-                                       _personal = new X509Store (path, false);
+                                       _personal = new X509Store (path, false, false);
                                }
                                return _personal; 
                        }
@@ -71,7 +73,7 @@ namespace Mono.Security.X509 {
                        get { 
                                if (_other == null) {
                                        string path = Path.Combine (_storePath, Names.OtherPeople);
-                                       _other = new X509Store (path, false);
+                                       _other = new X509Store (path, false, false);
                                }
                                return _other; 
                        }
@@ -81,7 +83,7 @@ namespace Mono.Security.X509 {
                        get { 
                                if (_intermediate == null) {
                                        string path = Path.Combine (_storePath, Names.IntermediateCA);
-                                       _intermediate = new X509Store (path, true);
+                                       _intermediate = new X509Store (path, true, _newFormat);
                                }
                                return _intermediate; 
                        }
@@ -91,7 +93,7 @@ namespace Mono.Security.X509 {
                        get { 
                                if (_trusted == null) {
                                        string path = Path.Combine (_storePath, Names.TrustedRoot);
-                                       _trusted = new X509Store (path, true);
+                                       _trusted = new X509Store (path, true, _newFormat);
                                }
                                return _trusted; 
                        }
@@ -101,7 +103,7 @@ namespace Mono.Security.X509 {
                        get { 
                                if (_untrusted == null) {
                                        string path = Path.Combine (_storePath, Names.Untrusted);
-                                       _untrusted = new X509Store (path, false);
+                                       _untrusted = new X509Store (path, false, _newFormat);
                                }
                                return _untrusted; 
                        }
@@ -138,7 +140,7 @@ namespace Mono.Security.X509 {
                        if (!create && !Directory.Exists (path))
                                return null;
 
-                       return new X509Store (path, true);
+                       return new X509Store (path, true, false);
                }
 
                // names
@@ -151,7 +153,7 @@ namespace Mono.Security.X509 {
                        public const string IntermediateCA = "CA";
                        public const string TrustedRoot = "Trust";
                        public const string Untrusted = "Disallowed";
-                       
+
                        public Names () {}
                }
        }
index 652115f85a3b524b73977d9143b9aba4d30f45e1..65d146e17e50d7f944ec03e44f1b8080fbd53f43 100644 (file)
 ./Mono.Security.Interface/HashAlgorithmType.cs
 ./Mono.Security.Interface/IBufferOffsetSize.cs
 ./Mono.Security.Interface/IMonoTlsEventSink.cs
-./Mono.Security.Interface/IMonoTlsContext.cs
 ./Mono.Security.Interface/IMonoSslStream.cs
 ./Mono.Security.Interface/MonoTlsConnectionInfo.cs
 ./Mono.Security.Interface/MonoTlsProvider.cs
index 9c35c71ec5627798b735f29e46db1c9224af615b..6c6a5b5d52a5dcb1f7ee606f3a8aa309da4e9ea9 100644 (file)
@@ -5,7 +5,11 @@ include ../../build/rules.make
 LIBRARY = System.ComponentModel.Composition.dll
 LIB_REFS = System System.Core
 
-RESOURCE_DEFS = Microsoft.Internal.Strings,src/ComponentModel/Strings.resx
+NO_RESGEN := $(filter basic build, $(PROFILE))
+ifndef NO_RESGEN
+  RESOURCE_DEFS = Microsoft.Internal.Strings,src/ComponentModel/Strings.resx
+endif
+
 LIB_MCS_FLAGS = -d:CLR40 -d:USE_ECMA_KEY,FEATURE_REFLECTIONCONTEXT,FEATURE_REFLECTIONFILEIO,FEATURE_SERIALIZATION,FEATURE_SLIMLOCK -nowarn:219,414
 
 
deleted file mode 120000 (symlink)
index 6f31b34dcaa52c7157fab9560cc6a6b5e6f14c7c..0000000000000000000000000000000000000000
+++ /dev/null
@@ -1 +0,0 @@
-Test/App.config
\ No newline at end of file
new file mode 100644 (file)
index 0000000000000000000000000000000000000000..d07b4f882f8fea25edf772d4619e88847ae2cb95
--- /dev/null
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<configuration>
+       <connectionStrings>
+               <add name="test-connstring"
+                       connectionString="Server=(local);Initial Catalog=someDb;User Id=someUser;Password=somePassword;Application Name=someAppName;Min Pool Size=5;Max Pool Size=500;Connect Timeout=10;Connection Lifetime=29;" />
+       </connectionStrings>
+  <appSettings file="Test/appSettings.config" />
+</configuration>
index 873ce5782aa4d48a2f32f86ee01e91746d8b9f9e..cbf1491612fcb12ef9a378c26e6cf214b0d30835 100644 (file)
@@ -30,10 +30,10 @@ using System;
 
 namespace Microsoft.Win32.SafeHandles
 {
-       public abstract class SafeNCryptHandle : System.Runtime.InteropServices.SafeHandle
+       public abstract class SafeNCryptHandle : SafeHandleZeroOrMinusOneIsInvalid
        {
                protected SafeNCryptHandle ()
-                       : base (IntPtr.Zero, true)
+                       : base (true)
                {
                }
 
index 18bfca4934c79d7c257bd8a1f4f0451049da4e7b..fbc55fd73b5e62c356363f97aeb51b14fe2dbdc8 100644 (file)
@@ -111,9 +111,9 @@ namespace System.IO.MemoryMappedFiles
 
 
        public class MemoryMappedFile : IDisposable {
-               MemoryMappedFileAccess fileAccess;
-               string name;
-               long fileCapacity;
+               // MemoryMappedFileAccess fileAccess;
+               // string name;
+               // long fileCapacity;
 
                //
                // We allow the use of either the FileStream/keepOpen combo
@@ -144,8 +144,8 @@ namespace System.IO.MemoryMappedFiles
 
                        return new MemoryMappedFile () {
                                handle = handle,
-                               fileAccess = MemoryMappedFileAccess.ReadWrite,
-                               fileCapacity = capacity
+                               // fileAccess = MemoryMappedFileAccess.ReadWrite,
+                               // fileCapacity = capacity
                        };
                }
 
@@ -176,9 +176,9 @@ namespace System.IO.MemoryMappedFiles
                        
                        return new MemoryMappedFile () {
                                handle = handle,
-                               fileAccess = access,
-                               name = mapName,
-                               fileCapacity = capacity
+                               // fileAccess = access,
+                               // name = mapName,
+                               // fileCapacity = capacity
                        };
                }
 
@@ -193,15 +193,15 @@ namespace System.IO.MemoryMappedFiles
                        if ((!MonoUtil.IsUnix && capacity == 0 && fileStream.Length == 0) || (capacity > fileStream.Length))
                                throw new ArgumentException ("capacity");
 
-                       IntPtr handle = MemoryMapImpl.OpenHandle (fileStream.Handle, mapName, out capacity, access, MemoryMappedFileOptions.DelayAllocatePages);
+                       IntPtr handle = MemoryMapImpl.OpenHandle (fileStream.SafeFileHandle.DangerousGetHandle (), mapName, out capacity, access, MemoryMappedFileOptions.DelayAllocatePages);
                        
                        MemoryMapImpl.ConfigureHandleInheritability (handle, inheritability);
                                
                        return new MemoryMappedFile () {
                                handle = handle,
-                               fileAccess = access,
-                               name = mapName,
-                               fileCapacity = capacity,
+                               // fileAccess = access,
+                               // name = mapName,
+                               // fileCapacity = capacity,
 
                                stream = fileStream,
                                keepOpen = leaveOpen
@@ -220,15 +220,15 @@ namespace System.IO.MemoryMappedFiles
                        if ((!MonoUtil.IsUnix && capacity == 0 && fileStream.Length == 0) || (capacity > fileStream.Length))
                                throw new ArgumentException ("capacity");
 
-                       IntPtr handle = MemoryMapImpl.OpenHandle (fileStream.Handle, mapName, out capacity, access, MemoryMappedFileOptions.DelayAllocatePages);
+                       IntPtr handle = MemoryMapImpl.OpenHandle (fileStream.SafeFileHandle.DangerousGetHandle (), mapName, out capacity, access, MemoryMappedFileOptions.DelayAllocatePages);
                        
                        MemoryMapImpl.ConfigureHandleInheritability (handle, inheritability);
                                
                        return new MemoryMappedFile () {
                                handle = handle,
-                               fileAccess = access,
-                               name = mapName,
-                               fileCapacity = capacity,
+                               // fileAccess = access,
+                               // name = mapName,
+                               // fileCapacity = capacity,
 
                                stream = fileStream,
                                keepOpen = leaveOpen
@@ -249,9 +249,9 @@ namespace System.IO.MemoryMappedFiles
                        
                        return new MemoryMappedFile () {
                                handle = handle,
-                               fileAccess = access,
-                               name = mapName,
-                               fileCapacity = capacity
+                               // fileAccess = access,
+                               // name = mapName,
+                               // fileCapacity = capacity
                        };                      
                }
 
index 23bf26f7482bb7654e1e5043f8381c937000f460..a4818f76049ea471ba429953552c602269a8a6b3 100644 (file)
@@ -77,8 +77,8 @@ namespace System.IO.Pipes
                        throw new NotImplementedException ();
 #else
                        InitializeHandle (safePipeHandle, false, false);
-#endif
                        IsConnected = true;
+#endif
                }
 
                ~AnonymousPipeClientStream ()
index 97455f30cdab55d78766508ad566684a21674a3b..18c82aeac3123a789d24b4f03217d087ec1429bf 100644 (file)
@@ -70,13 +70,15 @@ namespace System.IO.Pipes
                }
 #endif
 
-#if !MOBILE
                public AnonymousPipeServerStream (PipeDirection direction, HandleInheritability inheritability, int bufferSize, PipeSecurity pipeSecurity)
                        : base (direction, bufferSize)
                {
                        if (direction == PipeDirection.InOut)
                                throw new NotSupportedException ("Anonymous pipe direction can only be either in or out.");
 
+#if MOBILE
+                       throw new NotImplementedException ();
+#else
                        if (IsWindows)
                                impl = new Win32AnonymousPipeServer (this, direction, inheritability, bufferSize, pipeSecurity);
                        else
@@ -84,8 +86,8 @@ namespace System.IO.Pipes
 
                        InitializeHandle (impl.Handle, false, false);
                        IsConnected = true;
-               }
 #endif
+               }
 
                [MonoTODO]
                public AnonymousPipeServerStream (PipeDirection direction, SafePipeHandle serverSafePipeHandle, SafePipeHandle clientSafePipeHandle)
index a5a9ebd3fbc698acd1801824f8ac2d37fc21ab3b..a27c4dc0b4d3697f8aca9edf8f2cad7bf8d10499 100644 (file)
@@ -100,26 +100,30 @@ namespace System.IO.Pipes
 #endif
                }
 
-#if !MOBILE
                public NamedPipeClientStream (string serverName, string pipeName, PipeAccessRights desiredAccessRights, PipeOptions options, TokenImpersonationLevel impersonationLevel, HandleInheritability inheritability)
                        : base (ToDirection (desiredAccessRights), DefaultBufferSize)
                {
                        if (impersonationLevel != TokenImpersonationLevel.None ||
                            inheritability != HandleInheritability.None)
                                throw ThrowACLException ();
-
+#if MOBILE
+                       throw new NotImplementedException ();
+#else
                        if (IsWindows)
                                impl = new Win32NamedPipeClient (this, serverName, pipeName, desiredAccessRights, options, inheritability);
                        else
                                impl = new UnixNamedPipeClient (this, serverName, pipeName, desiredAccessRights, options, inheritability);
-               }
 #endif
 
+               }
+
                ~NamedPipeClientStream () {
                        Dispose (false);
                }
-               
+
+#if !MOBILE
                INamedPipeClient impl;
+#endif
 
                public void Connect ()
                {
@@ -163,10 +167,18 @@ namespace System.IO.Pipes
                        throw new NotImplementedException ();
                }
 
+               protected override internal void CheckPipePropertyOperations () {
+                       base.CheckPipePropertyOperations();
+               }
+
                public int NumberOfServerInstances {
                        get {
                                CheckPipePropertyOperations ();
+#if MOBILE
+                               throw new NotImplementedException ();
+#else
                                return impl.NumberOfServerInstances;
+#endif
                        }
                }
        }
index 3ffe89436727acf71c4a3be5afbd61aed7d9712f..d4d02ade208f4f415a2a1d817ac3c6598b103895 100644 (file)
@@ -83,7 +83,6 @@ namespace System.IO.Pipes
                }
 #endif
 
-#if !MOBILE
                public NamedPipeServerStream (string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize, PipeSecurity pipeSecurity)
                        : this (pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize, outBufferSize, pipeSecurity, HandleInheritability.None)
                {
@@ -98,6 +97,9 @@ namespace System.IO.Pipes
                public NamedPipeServerStream (string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize, PipeSecurity pipeSecurity, HandleInheritability inheritability, PipeAccessRights additionalAccessRights)
                        : base (direction, transmissionMode, outBufferSize)
                {
+#if MOBILE
+                       throw new NotImplementedException ();
+#else
                        var rights = ToAccessRights (direction) | additionalAccessRights;
                        // FIXME: reject some rights declarations (for ACL).
 
@@ -110,8 +112,8 @@ namespace System.IO.Pipes
                                                                rights, options, inBufferSize, outBufferSize, inheritability);
 
                        InitializeHandle (impl.Handle, false, (options & PipeOptions.Asynchronous) != PipeOptions.None);
-               }
 #endif
+               }
 
                public NamedPipeServerStream (PipeDirection direction, bool isAsync, bool isConnected, SafePipeHandle safePipeHandle)
                        : base (direction, DefaultBufferSize)
@@ -140,14 +142,12 @@ namespace System.IO.Pipes
                        impl.Disconnect ();
                }
 
-#if !MOBILE
                [MonoTODO]
                [SecurityPermission (SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPrincipal)]
                public void RunAsClient (PipeStreamImpersonationWorker impersonationWorker)
                {
                        throw new NotImplementedException ();
                }
-#endif
 
                public void WaitForConnection ()
                {
@@ -173,7 +173,6 @@ namespace System.IO.Pipes
                        throw new NotImplementedException ();
                }
 
-#if !MOBILE
                // async operations
 
                Action wait_connect_delegate;
@@ -190,7 +189,6 @@ namespace System.IO.Pipes
                {
                        wait_connect_delegate.EndInvoke (asyncResult);
                }
-#endif
        }
 }
 
index 20b7e7ec09cb8fa3a7f17df609d7f240237f2434..8dea76a2cacf96b9ff3010364d82008dbf7e31dd 100644 (file)
@@ -57,7 +57,6 @@ namespace System.IO.Pipes
                        return new NotImplementedException ("ACL is not supported in Mono");
                }
 
-#if !MOBILE
                internal static PipeAccessRights ToAccessRights (PipeDirection direction)
                {
                        switch (direction) {
@@ -88,7 +87,6 @@ namespace System.IO.Pipes
                                        throw new ArgumentOutOfRangeException ();
                        }
                }
-#endif
 
                protected PipeStream (PipeDirection direction, int bufferSize)
                        : this (direction, PipeTransmissionMode.Byte, bufferSize)
@@ -144,9 +142,7 @@ namespace System.IO.Pipes
                        set { stream = value; }
                }
 
-#if !MOBILE
                protected bool IsHandleExposed { get; private set; }
-#endif
 
                [MonoTODO]
                public bool IsMessageComplete { get; private set; }
@@ -182,19 +178,7 @@ namespace System.IO.Pipes
                }
 
                // initialize/dispose/state check
-#if MOBILE
-               internal static void CheckPipePropertyOperations ()
-               {
-               }
-
-               static void CheckReadOperations ()
-               {
-               }
 
-               static void CheckWriteOperations ()
-               {
-               }
-#else
                [MonoTODO]
                protected internal virtual void CheckPipePropertyOperations ()
                {
@@ -224,7 +208,6 @@ namespace System.IO.Pipes
                        this.IsHandleExposed = isExposed;
                        this.IsAsync = isAsync;
                }
-#endif
 
                protected override void Dispose (bool disposing)
                {
@@ -253,23 +236,29 @@ namespace System.IO.Pipes
                        throw new NotSupportedException ();
                }
 
-#if !MOBILE
                public PipeSecurity GetAccessControl ()
                {
+#if MOBILE
+                       throw new PlatformNotSupportedException ();
+#else
                        return new PipeSecurity (SafePipeHandle,
                                                 AccessControlSections.Owner |
                                                 AccessControlSections.Group |
                                                 AccessControlSections.Access);
+#endif
                }
 
                public void SetAccessControl (PipeSecurity pipeSecurity)
                {
+#if MOBILE
+                       throw new PlatformNotSupportedException ();
+#else
                        if (pipeSecurity == null)
                                throw new ArgumentNullException ("pipeSecurity");
                                
                        pipeSecurity.Persist (SafePipeHandle);
-               }
 #endif
+               }
 
                // pipe I/O
 
@@ -319,7 +308,6 @@ namespace System.IO.Pipes
 
                // async
 
-#if !MOBILE
                Func<byte [],int,int,int> read_delegate;
 
                [HostProtection (SecurityAction.LinkDemand, ExternalThreading = true)]
@@ -349,7 +337,6 @@ namespace System.IO.Pipes
                {
                        write_delegate.EndInvoke (asyncResult);
                }
-#endif
        }
 }
 
index 2f06df8949a4e2d2efc15a07fd8d581f7be49880..a1c7e22d8c49a07fe5b4e6ac31482a3a8a887449 100644 (file)
@@ -205,7 +205,7 @@ namespace System.IO.Pipes
                        opener = delegate {
                                var fs = new FileStream (name, FileMode.Open, RightsToFileAccess (desiredAccessRights), FileShare.ReadWrite);
                                owner.Stream = fs;
-                               handle = new SafePipeHandle (fs.Handle, false);
+                               handle = new SafePipeHandle (fs.SafeFileHandle.DangerousGetHandle (), false);
                        };
                }
 
@@ -271,7 +271,7 @@ namespace System.IO.Pipes
                        // FIXME: maxNumberOfServerInstances, modes, sizes, handle inheritability
                        
                        var fs = new FileStream (name, FileMode.Open, RightsToFileAccess (rights), FileShare.ReadWrite);
-                       handle = new SafePipeHandle (fs.Handle, false);
+                       handle = new SafePipeHandle (fs.SafeFileHandle.DangerousGetHandle (), false);
                        owner.Stream = fs;
                        should_close_handle = true;
                }
diff --git a/mcs/class/System.Core/System.Security.Cryptography/CngAlgorithm.cs b/mcs/class/System.Core/System.Security.Cryptography/CngAlgorithm.cs
deleted file mode 100644 (file)
index ea87b30..0000000
+++ /dev/null
@@ -1,192 +0,0 @@
-//
-// System.Security.Cryptography.CngAlgorithm
-//
-// Authors:
-//     Sebastien Pouliot  <sebastien@ximian.com>
-//
-// Copyright (C) 2008 Novell, Inc (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace System.Security.Cryptography {
-
-       // note: CNG stands for "Cryptography API: Next Generation"
-
-       [Serializable]
-       public sealed class CngAlgorithm : IEquatable<CngAlgorithm> {
-
-               private string m_algorithm;
-
-               public CngAlgorithm (string algorithm)
-               {
-                       if (algorithm == null)
-                               throw new ArgumentNullException ("algorithm");
-                       if (algorithm.Length == 0)
-                               throw new ArgumentException ("algorithm");
-
-                       m_algorithm = algorithm;
-               }
-
-               public string Algorithm {
-                       get { return m_algorithm; }
-               }
-
-               public bool Equals (CngAlgorithm other)
-               {
-                       if (other == null)
-                               return false;
-                       return m_algorithm == other.m_algorithm;
-               }
-
-               public override bool Equals (object obj)
-               {
-                       return Equals (obj as CngAlgorithm);
-               }
-
-               public override int GetHashCode ()
-               {
-                       return m_algorithm.GetHashCode ();
-               }
-
-               public override string ToString ()
-               {
-                       return m_algorithm;
-               }
-
-               // static
-
-               static CngAlgorithm dh256;
-               static CngAlgorithm dh384;
-               static CngAlgorithm dh521;
-               static CngAlgorithm dsa256;
-               static CngAlgorithm dsa384;
-               static CngAlgorithm dsa521;
-               static CngAlgorithm md5;
-               static CngAlgorithm sha1;
-               static CngAlgorithm sha256;
-               static CngAlgorithm sha384;
-               static CngAlgorithm sha512;
-
-               public static CngAlgorithm ECDiffieHellmanP256 {
-                       get {
-                               if (dh256 == null)
-                                       dh256 = new CngAlgorithm ("ECDH_P256");
-                               return dh256;
-                       }
-               }
-
-               public static CngAlgorithm ECDiffieHellmanP384 {
-                       get {
-                               if (dh384 == null)
-                                       dh384 = new CngAlgorithm ("ECDH_P384");
-                               return dh384;
-                       }
-               }
-
-               public static CngAlgorithm ECDiffieHellmanP521 {
-                       get {
-                               if (dh521 == null)
-                                       dh521 = new CngAlgorithm ("ECDH_P521");
-                               return dh521;
-                       }
-               }
-
-               public static CngAlgorithm ECDsaP256 {
-                       get {
-                               if (dsa256 == null)
-                                       dsa256 = new CngAlgorithm ("ECDSA_P256");
-                               return dsa256;
-                       }
-               }
-
-               public static CngAlgorithm ECDsaP384 {
-                       get {
-                               if (dsa384 == null)
-                                       dsa384 = new CngAlgorithm ("ECDSA_P384");
-                               return dsa384;
-                       }
-               }
-
-               public static CngAlgorithm ECDsaP521 {
-                       get {
-                               if (dsa521 == null)
-                                       dsa521 = new CngAlgorithm ("ECDSA_P521");
-                               return dsa521;
-                       }
-               }
-
-               public static CngAlgorithm MD5 {
-                       get {
-                               if (md5 == null)
-                                       md5 = new CngAlgorithm ("MD5");
-                               return md5;
-                       }
-               }
-
-               public static CngAlgorithm Sha1 {
-                       get {
-                               if (sha1 == null)
-                                       sha1 = new CngAlgorithm ("SHA1");
-                               return sha1;
-                       }
-               }
-
-               public static CngAlgorithm Sha256 {
-                       get {
-                               if (sha256 == null)
-                                       sha256 = new CngAlgorithm ("SHA256");
-                               return sha256;
-                       }
-               }
-
-               public static CngAlgorithm Sha384 {
-                       get {
-                               if (sha384 == null)
-                                       sha384 = new CngAlgorithm ("SHA384");
-                               return sha384;
-                       }
-               }
-
-               public static CngAlgorithm Sha512 {
-                       get {
-                               if (sha512 == null)
-                                       sha512 = new CngAlgorithm ("SHA512");
-                               return sha512;
-                       }
-               }
-
-               public static bool operator == (CngAlgorithm left, CngAlgorithm right)
-               {
-                       if ((object)left == null)
-                               return ((object)right == null);
-                       return left.Equals (right);
-               }
-
-               public static bool operator != (CngAlgorithm left, CngAlgorithm right)
-               {
-                       if ((object)left == null)
-                               return ((object)right != null);
-                       return !left.Equals (right);
-               }
-       }
-}
diff --git a/mcs/class/System.Core/System.Security.Cryptography/CngAlgorithmGroup.cs b/mcs/class/System.Core/System.Security.Cryptography/CngAlgorithmGroup.cs
deleted file mode 100644 (file)
index fa43965..0000000
+++ /dev/null
@@ -1,138 +0,0 @@
-//
-// System.Security.Cryptography.CngAlgorithmGroup
-//
-// Authors:
-//     Sebastien Pouliot  <sebastien@ximian.com>
-//
-// Copyright (C) 2008 Novell, Inc (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace System.Security.Cryptography {
-
-       // note: CNG stands for "Cryptography API: Next Generation"
-
-       [Serializable]
-       public sealed class CngAlgorithmGroup : IEquatable<CngAlgorithmGroup> {
-
-               private string m_algorithmGroup;
-
-               public CngAlgorithmGroup (string algorithmGroup)
-               {
-                       if (algorithmGroup == null)
-                               throw new ArgumentNullException ("algorithmGroup");
-                       if (algorithmGroup.Length == 0)
-                               throw new ArgumentException ("algorithmGroup");
-
-                       m_algorithmGroup = algorithmGroup;
-               }
-
-               public string AlgorithmGroup {
-                       get { return m_algorithmGroup; }
-               }
-
-               public bool Equals (CngAlgorithmGroup other)
-               {
-                       if (other == null)
-                               return false;
-                       return m_algorithmGroup == other.m_algorithmGroup;
-               }
-
-               public override bool Equals (object obj)
-               {
-                       return Equals (obj as CngAlgorithmGroup);
-               }
-
-               public override int GetHashCode ()
-               {
-                       return m_algorithmGroup.GetHashCode ();
-               }
-
-               public override string ToString ()
-               {
-                       return m_algorithmGroup;
-               }
-
-               // static
-
-               private static CngAlgorithmGroup dh;
-               private static CngAlgorithmGroup dsa;
-               private static CngAlgorithmGroup ecdh;
-               private static CngAlgorithmGroup ecdsa;
-               private static CngAlgorithmGroup rsa;
-
-               public static CngAlgorithmGroup DiffieHellman {
-                       get {
-                               if (dh == null)
-                                       dh = new CngAlgorithmGroup ("DH");
-                               return dh;
-                       }
-               }
-
-               public static CngAlgorithmGroup Dsa {
-                       get {
-                               if (dsa == null)
-                                       dsa = new CngAlgorithmGroup ("DSA");
-                               return dsa;
-                       }
-               }
-
-               public static CngAlgorithmGroup ECDiffieHellman {
-                       get {
-                               if (ecdh == null)
-                                       ecdh = new CngAlgorithmGroup ("ECDH");
-                               return ecdh;
-                       }
-               }
-
-               public static CngAlgorithmGroup ECDsa {
-                       get {
-                               if (ecdsa == null)
-                                       ecdsa = new CngAlgorithmGroup ("ECDSA");
-                               return ecdsa;
-                       }
-               }
-
-               public static CngAlgorithmGroup Rsa {
-                       get {
-                               if (rsa == null)
-                                       rsa = new CngAlgorithmGroup ("RSA");
-                               return rsa;
-                       }
-               }
-
-               public static bool operator == (CngAlgorithmGroup left, CngAlgorithmGroup right)
-               {
-                       if ((object)left == null)
-                               return ((object)right == null);
-                       return left.Equals (right);
-               }
-
-               public static bool operator != (CngAlgorithmGroup left, CngAlgorithmGroup right)
-               {
-                       if ((object)left == null)
-                               return ((object)right != null);
-                       return !left.Equals (right);
-               }
-       }
-}
diff --git a/mcs/class/System.Core/System.Security.Cryptography/CngExportPolicies.cs b/mcs/class/System.Core/System.Security.Cryptography/CngExportPolicies.cs
deleted file mode 100644 (file)
index 90a1aa5..0000000
+++ /dev/null
@@ -1,40 +0,0 @@
-//
-// System.Security.Cryptography.CngExportPolicies
-//
-// Copyright (C) 2011 Juho Vähä-Herttua
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace System.Security.Cryptography {
-
-       // note: CNG stands for "Cryptography API: Next Generation"
-
-       [Flags]
-       public enum CngExportPolicies {
-               None,
-               AllowExport,
-               AllowPlaintextExport,
-               AllowArchiving,
-               AllowPlaintextArchiving
-       }
-}
diff --git a/mcs/class/System.Core/System.Security.Cryptography/CngKeyCreationOptions.cs b/mcs/class/System.Core/System.Security.Cryptography/CngKeyCreationOptions.cs
deleted file mode 100644 (file)
index da28e7b..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-//
-// System.Security.Cryptography.CngKeyCreationOptions
-//
-// Copyright (C) 2011 Juho Vähä-Herttua
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace System.Security.Cryptography {
-
-       // note: CNG stands for "Cryptography API: Next Generation"
-
-       [Flags]
-       public enum CngKeyCreationOptions {
-               None                 = 0x00,
-               MachineKey           = 0x20,
-               OverwriteExistingKey = 0x80
-       }
-}
diff --git a/mcs/class/System.Core/System.Security.Cryptography/CngKeyCreationParameters.cs b/mcs/class/System.Core/System.Security.Cryptography/CngKeyCreationParameters.cs
deleted file mode 100644 (file)
index 8963324..0000000
+++ /dev/null
@@ -1,92 +0,0 @@
-//
-// System.Security.Cryptography.CngKeyCreationParameters
-//
-// Copyright (C) 2011 Juho Vähä-Herttua
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace System.Security.Cryptography {
-
-       // note: CNG stands for "Cryptography API: Next Generation"
-
-       public class CngKeyCreationParameters {
-               private Nullable<CngExportPolicies> exportPolicy;
-               private CngKeyCreationOptions keyCreationOptions;
-               private Nullable<CngKeyUsages> keyUsage;
-               private CngPropertyCollection parameters;
-               private IntPtr parentWindowHandle;
-               private CngProvider provider;
-               private CngUIPolicy uiPolicy;
-
-               public CngKeyCreationParameters ()
-               {
-                       parameters = new CngPropertyCollection ();
-                       provider = CngProvider.MicrosoftSoftwareKeyStorageProvider;
-               }
-
-               public Nullable<CngExportPolicies> ExportPolicy
-               {
-                       get { return exportPolicy; }
-                       set { exportPolicy = value; }
-               }
-
-               public CngKeyCreationOptions KeyCreationOptions
-               {
-                       get { return keyCreationOptions; }
-                       set { keyCreationOptions = value; }
-               }
-
-               public Nullable<CngKeyUsages> KeyUsage
-               {
-                       get { return keyUsage; }
-                       set { keyUsage = value; }
-               }
-
-               public CngPropertyCollection Parameters
-               {
-                       get { return parameters; }
-               }
-
-               public IntPtr ParentWindowHandle
-               {
-                       get { return parentWindowHandle; }
-                       set { parentWindowHandle = value; }
-               }
-
-               public CngProvider Provider
-               {
-                       get { return provider; }
-                       set {
-                               if (value == null)
-                                       throw new ArgumentNullException ("value");
-                               provider = value;
-                       }
-               }
-
-               public CngUIPolicy UIPolicy
-               {
-                       get { return uiPolicy; }
-                       set { uiPolicy = value; }
-               }
-       }
-}
diff --git a/mcs/class/System.Core/System.Security.Cryptography/CngKeyOpenOptions.cs b/mcs/class/System.Core/System.Security.Cryptography/CngKeyOpenOptions.cs
deleted file mode 100644 (file)
index dcc3289..0000000
+++ /dev/null
@@ -1,39 +0,0 @@
-//
-// System.Security.Cryptography.CngKeyOpenOptions
-//
-// Copyright (C) 2011 Juho Vähä-Herttua
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace System.Security.Cryptography {
-
-       // note: CNG stands for "Cryptography API: Next Generation"
-
-       [Flags]
-       public enum CngKeyOpenOptions {
-               None       = 0x00,
-               UserKey    = 0x00,
-               MachineKey = 0x20,
-               Silent     = 0x40
-       }
-}
diff --git a/mcs/class/System.Core/System.Security.Cryptography/CngKeyUsages.cs b/mcs/class/System.Core/System.Security.Cryptography/CngKeyUsages.cs
deleted file mode 100644 (file)
index 35f1d43..0000000
+++ /dev/null
@@ -1,40 +0,0 @@
-//
-// System.Security.Cryptography.CngKeyUsages
-//
-// Copyright (C) 2011 Juho Vähä-Herttua
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace System.Security.Cryptography {
-
-       // note: CNG stands for "Cryptography API: Next Generation"
-
-       [Flags]
-       public enum CngKeyUsages {
-               None,
-               Decryption,
-               Signing,
-               KeyAgreement,
-               AllUsages = 0xffffff
-       }
-}
diff --git a/mcs/class/System.Core/System.Security.Cryptography/CngProperty.cs b/mcs/class/System.Core/System.Security.Cryptography/CngProperty.cs
deleted file mode 100644 (file)
index f0948bb..0000000
+++ /dev/null
@@ -1,115 +0,0 @@
-//
-// System.Security.Cryptography.CngProperty
-//
-// Copyright (C) 2011 Juho Vähä-Herttua
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace System.Security.Cryptography {
-
-       // note: CNG stands for "Cryptography API: Next Generation"
-
-       public struct CngProperty : IEquatable<CngProperty> {
-               private string name;
-               private byte[] val;
-               private CngPropertyOptions opts;
-
-               public CngProperty(string name, byte[] value, CngPropertyOptions options)
-               {
-                       if (name == null)
-                               throw new ArgumentNullException("name");
-
-                       this.name = name;
-                       this.val = (value != null) ? (byte[]) value.Clone () : null;
-                       this.opts = options;
-               }
-
-               public string Name {
-                       get { return name; }
-               }
-
-               public CngPropertyOptions Options {
-                       get { return opts; }
-               }
-
-               public byte[] GetValue ()
-               {
-                       if (val == null)
-                               return null;
-                       return (byte[]) val.Clone ();
-               }
-
-               public bool Equals (CngProperty other)
-               {
-                       if (this.name != other.name || this.opts != other.opts)
-                               return false;
-                       if (this.val == null && other.val == null)
-                               return true;
-                       if (this.val == null || other.val == null)
-                               return false;
-                       if (this.val.Length != other.val.Length)
-                               return false;
-
-                       for (int i=0; i<val.Length; i++) {
-                               if (this.val[i] != other.val[i])
-                                       return false;
-                       }
-                       return true;
-               }
-
-               public override bool Equals (object obj)
-               {
-                       if (obj == null)
-                               return false;
-                       if (!(obj is CngProperty))
-                               return false;
-                       return Equals ((CngProperty) obj);
-               }
-
-               public override int GetHashCode ()
-               {
-                       int ret = name.GetHashCode () ^ opts.GetHashCode ();
-                       if (val == null)
-                               return ret;
-
-                       for (int i=0; i<val.Length; i++) {
-                               // Handle each 4 bytes of byte array as a little-endian
-                               // integer and XOR it with the resulting hash code value
-                               ret ^= val[i] << 8*(i % 4);
-                       }
-                       return ret;
-               }
-
-               // static
-
-               public static bool operator == (CngProperty left, CngProperty right)
-               {
-                       return left.Equals (right);
-               }
-
-               public static bool operator != (CngProperty left, CngProperty right)
-               {
-                       return !left.Equals (right);
-               }
-       }
-}
diff --git a/mcs/class/System.Core/System.Security.Cryptography/CngPropertyCollection.cs b/mcs/class/System.Core/System.Security.Cryptography/CngPropertyCollection.cs
deleted file mode 100644 (file)
index afc5269..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-//
-// System.Security.Cryptography.CngPropertyCollection
-//
-// Copyright (C) 2011 Juho Vähä-Herttua
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Collections.ObjectModel;
-
-namespace System.Security.Cryptography {
-
-       // note: CNG stands for "Cryptography API: Next Generation"
-
-       public sealed class CngPropertyCollection : Collection<CngProperty> {
-               public CngPropertyCollection ()
-               {
-               }
-       }
-}
diff --git a/mcs/class/System.Core/System.Security.Cryptography/CngPropertyOptions.cs b/mcs/class/System.Core/System.Security.Cryptography/CngPropertyOptions.cs
deleted file mode 100644 (file)
index 336d26a..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-//
-// System.Security.Cryptography.CngPropertyOptions
-//
-// Copyright (C) 2011 Juho Vähä-Herttua
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace System.Security.Cryptography {
-
-       // note: CNG stands for "Cryptography API: Next Generation"
-
-       [Flags]
-       public enum CngPropertyOptions {
-               None           = 0x00 << 24,
-               CustomProperty = 0x40 << 24,
-               Persist        = 0x80 << 24
-       }
-}
diff --git a/mcs/class/System.Core/System.Security.Cryptography/CngProvider.cs b/mcs/class/System.Core/System.Security.Cryptography/CngProvider.cs
deleted file mode 100644 (file)
index 8c868a7..0000000
+++ /dev/null
@@ -1,112 +0,0 @@
-//
-// System.Security.Cryptography.CngProvider
-//
-// Authors:
-//      Sebastien Pouliot  <sebastien@ximian.com>
-//
-// Copyright (C) 2008 Novell, Inc (http://www.novell.com)
-// Copyright (C) 2011 Juho Vähä-Herttua
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace System.Security.Cryptography {
-
-       // note: CNG stands for "Cryptography API: Next Generation"
-
-       [Serializable]
-       public sealed class CngProvider : IEquatable<CngProvider> {
-
-               private string m_Provider;
-
-               public CngProvider (string provider)
-               {
-                       if (provider == null)
-                               throw new ArgumentNullException ("provider");
-                       if (provider.Length == 0)
-                               throw new ArgumentException ("provider");
-
-                       m_Provider = provider;
-               }
-
-               public string Provider {
-                       get { return m_Provider; }
-               }
-
-               public bool Equals (CngProvider other)
-               {
-                       if (other == null)
-                               return false;
-                       return m_Provider == other.m_Provider;
-               }
-
-               public override bool Equals (object obj)
-               {
-                       return Equals (obj as CngProvider);
-               }
-
-               public override int GetHashCode ()
-               {
-                       return m_Provider.GetHashCode ();
-               }
-
-               public override string ToString ()
-               {
-                       return m_Provider;
-               }
-
-               // static
-
-               private static CngProvider microsoftSmartCardKeyStorageProvider;
-               private static CngProvider microsoftSoftwareKeyStorageProvider;
-
-               public static CngProvider MicrosoftSmartCardKeyStorageProvider {
-                       get {
-                               if (microsoftSmartCardKeyStorageProvider == null)
-                                       microsoftSmartCardKeyStorageProvider = new CngProvider ("Microsoft Smart Card Key Storage Provider");
-                               return microsoftSmartCardKeyStorageProvider;
-                       }
-               }
-
-               public static CngProvider MicrosoftSoftwareKeyStorageProvider {
-                       get {
-                               if (microsoftSoftwareKeyStorageProvider == null)
-                                       microsoftSoftwareKeyStorageProvider = new CngProvider ("Microsoft Software Key Storage Provider");
-                               return microsoftSoftwareKeyStorageProvider;
-                       }
-               }
-
-               public static bool operator == (CngProvider left, CngProvider right)
-               {
-                       if ((object)left == null)
-                               return ((object)right == null);
-                       return left.Equals (right);
-               }
-
-               public static bool operator != (CngProvider left, CngProvider right)
-               {
-                       if ((object)left == null)
-                               return ((object)right != null);
-                       return !left.Equals (right);
-               }
-       }
-}
diff --git a/mcs/class/System.Core/System.Security.Cryptography/CngUIPolicy.cs b/mcs/class/System.Core/System.Security.Cryptography/CngUIPolicy.cs
deleted file mode 100644 (file)
index 4e0c36c..0000000
+++ /dev/null
@@ -1,98 +0,0 @@
-//
-// System.Security.Cryptography.CngUIPolicy
-//
-// Copyright (C) 2011 Juho Vähä-Herttua
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace System.Security.Cryptography {
-
-       // note: CNG stands for "Cryptography API: Next Generation"
-
-       public sealed class CngUIPolicy {
-               private CngUIProtectionLevels level;
-               private string name;
-               private string desc;
-               private string context;
-               private string title;
-
-               public CngUIPolicy (CngUIProtectionLevels protectionLevel)
-                       : this (protectionLevel, null)
-               {
-               }
-
-               public CngUIPolicy (CngUIProtectionLevels protectionLevel,
-                                   string friendlyName)
-                       : this (protectionLevel, friendlyName, null)
-               {
-               }
-
-               public CngUIPolicy (CngUIProtectionLevels protectionLevel,
-                                   string friendlyName,
-                                   string description)
-                       : this (protectionLevel, friendlyName, description, null)
-               {
-               }
-
-               public CngUIPolicy (CngUIProtectionLevels protectionLevel,
-                                   string friendlyName,
-                                   string description,
-                                   string useContext)
-                       : this (protectionLevel, friendlyName, description, useContext, null)
-               {
-               }
-
-               public CngUIPolicy (CngUIProtectionLevels protectionLevel,
-                                   string friendlyName,
-                                   string description,
-                                   string useContext,
-                                   string creationTitle)
-               {
-                       level = protectionLevel;
-                       name = friendlyName;
-                       desc = description;
-                       context = useContext;
-                       title = creationTitle;
-               }
-
-               public CngUIProtectionLevels ProtectionLevel {
-                       get { return level; }
-               }
-
-               public string FriendlyName {
-                       get { return name; }
-               }
-
-               public string Description {
-                       get { return desc; }
-               }
-
-               public string UseContext {
-                       get { return context; }
-               }
-
-               public string CreationTitle {
-                       get { return title; }
-               }
-       }
-}
diff --git a/mcs/class/System.Core/System.Security.Cryptography/CngUIProtectionLevels.cs b/mcs/class/System.Core/System.Security.Cryptography/CngUIProtectionLevels.cs
deleted file mode 100644 (file)
index 22f4178..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-//
-// System.Security.Cryptography.CngUIProtectionLevels
-//
-// Copyright (C) 2011 Juho Vähä-Herttua
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace System.Security.Cryptography {
-
-       // note: CNG stands for "Cryptography API: Next Generation"
-
-       [Flags]
-       public enum CngUIProtectionLevels {
-               None,
-               ProtectKey,
-               ForceHighProtection
-       }
-}
diff --git a/mcs/class/System.Core/System.Security.Cryptography/ECDiffieHellmanKeyDerivationFunction.cs b/mcs/class/System.Core/System.Security.Cryptography/ECDiffieHellmanKeyDerivationFunction.cs
deleted file mode 100644 (file)
index a2a9880..0000000
+++ /dev/null
@@ -1,35 +0,0 @@
-//
-// System.Security.Cryptography.ECDiffieHellmanKeyDerivationFunction
-//
-// Copyright (C) 2011 Juho Vähä-Herttua
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace System.Security.Cryptography {
-
-       public enum ECDiffieHellmanKeyDerivationFunction {
-               Hash,
-               Hmac,
-               Tls
-       }
-}
diff --git a/mcs/class/System.Core/System.Security.Cryptography/ECKeyXmlFormat.cs b/mcs/class/System.Core/System.Security.Cryptography/ECKeyXmlFormat.cs
deleted file mode 100644 (file)
index 3ed2910..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-//
-// System.Security.Cryptography.ECKeyXmlFormat
-//
-// Copyright (C) 2011 Juho Vähä-Herttua
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace System.Security.Cryptography {
-
-       public enum ECKeyXmlFormat {
-               Rfc4050
-       }
-}
index b5bd23a7cbe8cb79f73e38af70f4a38447fa87ee..e8a641299b351597bbcaaa4cfc549055fa665dbc 100644 (file)
@@ -6,17 +6,23 @@ LIBRARY = System.Data.dll
 
 LIB_REFS = System System.Xml System.Core System.Numerics
 LIB_MCS_FLAGS = \
-       -nowarn:169,219,414,649 \
+       -nowarn:219,414,649 \
        -d:PLATFORM_UNIX \
        -d:USEOFFSET \
        -d:MONO_PARTIAL_DATA_IMPORT \
        -unsafe
 
+ifdef NO_MONO_SECURITY
+MONO_DATA_TDS=
+else
+MONO_DATA_TDS=Mono.Data.Tds
+endif
+
 ifdef MOBILE_PROFILE
-LIB_REFS += Mono.Data.Tds System.Transactions
+LIB_REFS += $(MONO_DATA_TDS) System.Transactions
 LIB_MCS_FLAGS += -d:NO_CODEDOM -d:NO_OLEDB -d:NO_ODBC -d:NO_CONFIGURATION
 else
-LIB_REFS += System.EnterpriseServices Mono.Data.Tds System.Configuration System.Transactions
+LIB_REFS += System.EnterpriseServices $(MONO_DATA_TDS) System.Configuration System.Transactions
 BUILT_SOURCES = \
        gen_OdbcConnection.cs \
        gen_OleDbConnection.cs \
diff --git a/mcs/class/System.Data/System.Data.SqlClient/SqlBulkCopy.platformnotsupported.cs b/mcs/class/System.Data/System.Data.SqlClient/SqlBulkCopy.platformnotsupported.cs
new file mode 100644 (file)
index 0000000..95d6801
--- /dev/null
@@ -0,0 +1,136 @@
+//
+// SqlBulkCopy.cs
+//
+// Author:
+//       Rolf Bjarne Kvinge <rolf@xamarin.com>
+//
+// Copyright (c) 2016 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.Data.Common;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace System.Data.SqlClient {
+       public sealed class SqlBulkCopy : IDisposable
+       {
+               const string EXCEPTION_MESSAGE = "System.Data.SqlClient.SqlBulkCopy is not supported on the current platform.";
+
+               public SqlBulkCopy (SqlConnection connection)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public SqlBulkCopy (string connectionString)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public SqlBulkCopy (string connectionString, SqlBulkCopyOptions copyOptions)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public SqlBulkCopy (SqlConnection connection, SqlBulkCopyOptions copyOptions, SqlTransaction externalTransaction)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public int BatchSize {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public int BulkCopyTimeout {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public SqlBulkCopyColumnMappingCollection ColumnMappings  {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string DestinationTableName {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool EnableStreaming {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public int NotifyAfter {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public void Close ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void WriteToServer (DataRow [] rows)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void WriteToServer (DataTable table)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void WriteToServer (IDataReader reader)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void WriteToServer (DataTable table, DataRowState rowState)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void WriteToServer (DbDataReader reader)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public Task WriteToServerAsync (DbDataReader reader)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public Task WriteToServerAsync (DbDataReader reader, CancellationToken cancellationToken)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               private void RowsCopied (long rowsCopied)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public event SqlRowsCopiedEventHandler SqlRowsCopied;
+
+               void IDisposable.Dispose ()
+               {
+               }
+       }
+}
index c6dc7712baea19fa4846ae2da30eb5529c284944..1fd5443df85192ea7e3fcffd5461c19356952b59 100644 (file)
@@ -510,40 +510,104 @@ namespace System.Data.SqlClient {
                        }
                }
 
-               [MonoTODO]
                public new Task<SqlDataReader> ExecuteReaderAsync ()
                {
-                       throw new NotImplementedException ();
+                       return ExecuteReaderAsync (CommandBehavior.Default, CancellationToken.None);
                }
 
-               [MonoTODO]
                public new Task<SqlDataReader> ExecuteReaderAsync (CancellationToken cancellationToken)
                {
-                       throw new NotImplementedException ();
+                       return ExecuteReaderAsync (behavior, CancellationToken.None);
                }
 
-               [MonoTODO]
                public new Task<SqlDataReader> ExecuteReaderAsync (CommandBehavior behavior)
                {
-                       throw new NotImplementedException ();
+                       return ExecuteReaderAsync (CommandBehavior.Default, CancellationToken.None);
                }
 
-               [MonoTODO]
                public new Task<SqlDataReader> ExecuteReaderAsync (CommandBehavior behavior, CancellationToken cancellationToken)
                {
-                       throw new NotImplementedException ();
+                       TaskCompletionSource<SqlDataReader> source = new TaskCompletionSource<SqlDataReader>();
+
+                       CancellationTokenRegistration registration = new CancellationTokenRegistration();
+                       if (cancellationToken.CanBeCanceled) {
+                               if (cancellationToken.IsCancellationRequested) {
+                                       source.SetCanceled();
+                                       return source.Task;
+                               }
+                               registration = cancellationToken.Register(CancelIgnoreFailure);
+                       }
+
+                       Task<SqlDataReader> returnedTask = source.Task;
+                       try {
+                               // TODO: RegisterForConnectionCloseNotification(ref returnedTask);
+
+                               Task<SqlDataReader>.Factory.FromAsync(BeginExecuteReaderAsync, EndExecuteReader, behavior, null).ContinueWith((t) => {
+                                       registration.Dispose();
+                                       if (t.IsFaulted) {
+                                               Exception e = t.Exception.InnerException;
+                                               source.SetException(e);
+                                       }
+                                       else {
+                                               if (t.IsCanceled) {
+                                                       source.SetCanceled();
+                                               }
+                                               else {
+                                                       source.SetResult(t.Result);
+                                               }
+                                       }
+                               }, TaskScheduler.Default);
+                       }
+                       catch (Exception e) {
+                               source.SetException(e);
+                       }
+
+                       return returnedTask;
                }
 
-               [MonoTODO]
                public Task<XmlReader> ExecuteXmlReaderAsync ()
                {
-                       throw new NotImplementedException ();
+                       return ExecuteXmlReaderAsync (CancellationToken.None);
                }
  
-               [MonoTODO]
                public Task<XmlReader> ExecuteXmlReaderAsync (CancellationToken cancellationToken)
                {
-                       throw new NotImplementedException ();
+                       TaskCompletionSource<XmlReader> source = new TaskCompletionSource<XmlReader>();
+
+                       CancellationTokenRegistration registration = new CancellationTokenRegistration();
+                       if (cancellationToken.CanBeCanceled) {
+                               if (cancellationToken.IsCancellationRequested) {
+                                       source.SetCanceled();
+                                       return source.Task;
+                               }
+                               registration = cancellationToken.Register(CancelIgnoreFailure);
+                       }
+
+                       Task<XmlReader> returnedTask = source.Task;
+                       try {
+                               // TODO: RegisterForConnectionCloseNotification(ref returnedTask);
+
+                               Task<XmlReader>.Factory.FromAsync(BeginExecuteXmlReader, EndExecuteXmlReader, null).ContinueWith((t) => {
+                                       registration.Dispose();
+                                       if (t.IsFaulted) {
+                                               Exception e = t.Exception.InnerException;
+                                               source.SetException(e);
+                                       }
+                                       else {
+                                               if (t.IsCanceled) {
+                                                       source.SetCanceled();
+                                               }
+                                               else {
+                                                       source.SetResult(t.Result);
+                                               }
+                                       }
+                               }, TaskScheduler.Default);
+                       }
+                       catch (Exception e) {
+                               source.SetException(e);
+                       }
+
+                       return returnedTask;
                }
 
                public
@@ -846,6 +910,11 @@ namespace System.Data.SqlClient {
                        return BeginExecuteReader (callback, stateObject, CommandBehavior.Default);
                }
 
+               IAsyncResult BeginExecuteReaderAsync(CommandBehavior behavior, AsyncCallback callback, object stateObject)
+               {
+                       return BeginExecuteReader (callback, stateObject, behavior);
+               }
+
                public IAsyncResult BeginExecuteReader (AsyncCallback callback, object stateObject, CommandBehavior behavior)
                {
                        ValidateCommand ("BeginExecuteReader", true);
@@ -925,6 +994,9 @@ namespace System.Data.SqlClient {
 
                #endregion // Asynchronous Methods
 
+#pragma warning disable 0067
+               // TODO: Not implemented
                public event StatementCompletedEventHandler StatementCompleted;
+#pragma warning restore
        }
 }
diff --git a/mcs/class/System.Data/System.Data.SqlClient/SqlCommand.platformnotsupported.cs b/mcs/class/System.Data/System.Data.SqlClient/SqlCommand.platformnotsupported.cs
new file mode 100644 (file)
index 0000000..491483e
--- /dev/null
@@ -0,0 +1,277 @@
+//
+// SqlCommand.cs
+//
+// Author:
+//       Rolf Bjarne Kvinge <rolf@xamarin.com>
+//
+// Copyright (c) 2016 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.Data.Common;
+using System.Data.Sql;
+using System.Threading.Tasks;
+using System.Threading;
+using System.Xml;
+
+namespace System.Data.SqlClient {
+       public sealed class SqlCommand : DbCommand, IDbCommand, ICloneable
+       {
+               const string EXCEPTION_MESSAGE = "System.Data.SqlClient.SqlCommand is not supported on the current platform.";
+
+               public SqlCommand()
+                       : this (String.Empty, null, null)
+               {
+               }
+
+               public SqlCommand (string cmdText)
+                       : this (cmdText, null, null)
+               {
+               }
+
+               public SqlCommand (string cmdText, SqlConnection connection)
+                       : this (cmdText, connection, null)
+               {
+               }
+
+               public SqlCommand (string cmdText, SqlConnection connection, SqlTransaction transaction)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override string CommandText {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override int CommandTimeout {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override CommandType CommandType {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public new SqlConnection Connection {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override bool DesignTimeVisible {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public new SqlParameterCollection Parameters {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public new SqlTransaction Transaction {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override UpdateRowSource UpdatedRowSource {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public SqlNotificationRequest Notification {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool NotificationAutoEnlist {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override void Cancel ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public SqlCommand Clone ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public new SqlParameter CreateParameter ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override int ExecuteNonQuery ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public new SqlDataReader ExecuteReader ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public new SqlDataReader ExecuteReader (CommandBehavior behavior)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public new Task<SqlDataReader> ExecuteReaderAsync ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public new Task<SqlDataReader> ExecuteReaderAsync (CancellationToken cancellationToken)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public new Task<SqlDataReader> ExecuteReaderAsync (CommandBehavior behavior)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public new Task<SqlDataReader> ExecuteReaderAsync (CommandBehavior behavior, CancellationToken cancellationToken)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public Task<XmlReader> ExecuteXmlReaderAsync ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public Task<XmlReader> ExecuteXmlReaderAsync (CancellationToken cancellationToken)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override object ExecuteScalar ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public XmlReader ExecuteXmlReader ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               object ICloneable.Clone ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected override void Dispose (bool disposing)
+               {
+               }
+
+               public override void Prepare ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void ResetCommandTimeout ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected override DbParameter CreateDbParameter ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected override DbDataReader ExecuteDbDataReader (CommandBehavior behavior)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected override DbConnection DbConnection {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               protected override DbParameterCollection DbParameterCollection {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               protected override DbTransaction DbTransaction {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public IAsyncResult BeginExecuteNonQuery ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public IAsyncResult BeginExecuteNonQuery (AsyncCallback callback, object stateObject)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public int EndExecuteNonQuery (IAsyncResult asyncResult)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public IAsyncResult BeginExecuteReader ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public IAsyncResult BeginExecuteReader (CommandBehavior behavior)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public IAsyncResult BeginExecuteReader (AsyncCallback callback, object stateObject)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public IAsyncResult BeginExecuteReader (AsyncCallback callback, object stateObject, CommandBehavior behavior)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public SqlDataReader EndExecuteReader (IAsyncResult asyncResult)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public IAsyncResult BeginExecuteXmlReader (AsyncCallback callback, object stateObject)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public IAsyncResult BeginExecuteXmlReader ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public XmlReader EndExecuteXmlReader (IAsyncResult asyncResult)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public event StatementCompletedEventHandler StatementCompleted;
+       }
+}
diff --git a/mcs/class/System.Data/System.Data.SqlClient/SqlCommandBuilder.platformnotsupported.cs b/mcs/class/System.Data/System.Data.SqlClient/SqlCommandBuilder.platformnotsupported.cs
new file mode 100644 (file)
index 0000000..155ddab
--- /dev/null
@@ -0,0 +1,158 @@
+//
+// SqlCommandBuilder.cs
+//
+// Author:
+//       Rolf Bjarne Kvinge <rolf@xamarin.com>
+//
+// Copyright (c) 2016 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.Data;
+using System.Data.Common;
+using System.Data.SqlClient;
+
+namespace System.Data.SqlClient
+{
+       public class SqlCommandBuilder : DbCommandBuilder 
+       {
+               const string EXCEPTION_MESSAGE = "System.Data.SqlClient.SqlCommandBuilder is not supported on the current platform.";
+
+               public SqlCommandBuilder ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public SqlCommandBuilder (SqlDataAdapter adapter)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public static void DeriveParameters (SqlCommand command)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public SqlCommand GetDeleteCommand ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public SqlCommand GetInsertCommand ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public SqlCommand GetUpdateCommand ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public SqlCommand GetUpdateCommand (bool useColumnsForParameterNames)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public SqlCommand GetDeleteCommand (bool useColumnsForParameterNames)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public SqlCommand GetInsertCommand (bool useColumnsForParameterNames)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override string QuoteIdentifier (string unquotedIdentifier)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override string UnquoteIdentifier (string quotedIdentifier)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected override void ApplyParameterInfo (DbParameter parameter, DataRow datarow, StatementType statementType, bool whereClause)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected override string GetParameterName (int parameterOrdinal)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected override string GetParameterName (string parameterName)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected override string GetParameterPlaceholder (int parameterOrdinal)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected override void SetRowUpdatingHandler (DbDataAdapter adapter)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected override DataTable GetSchemaTable (DbCommand srcCommand)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected override DbCommand InitializeCommand (DbCommand command)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public SqlDataAdapter DataAdapter {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override string QuotePrefix {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override string QuoteSuffix {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override string CatalogSeparator {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override string SchemaSeparator {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override CatalogLocation CatalogLocation {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+       }
+}
index 9af24e650543168cb7543aee345b08dafcf815a9..f7248acb6bcc5dd554bf5b75c6c64609d52a1261 100644 (file)
@@ -138,7 +138,9 @@ namespace System.Data.SqlClient
 
                [DefaultValue ("")]
                [EditorAttribute ("Microsoft.VSDesigner.Data.SQL.Design.SqlConnectionStringEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
-               [RecommendedAsConfigurable (true)]
+#pragma warning disable 618 // ignore obsolete warning about RecommendedAsConfigurable to use SettingsBindableAttribute
+               [RecommendedAsConfigurable(true)]
+#pragma warning restore 618
                [RefreshProperties (RefreshProperties.All)]
                public override string ConnectionString {
                        get {
@@ -928,7 +930,11 @@ namespace System.Data.SqlClient
 
                                if (Client.Available <= 0)
                                        return -1; // Error
-                               IPEndPoint endpoint = new IPEndPoint (Dns.GetHostEntry ("localhost").AddressList [0], 0);
+
+                               IPEndPoint endpoint = CreateLocalEndpoint ();
+                               if (endpoint == null)
+                                       return -1;
+
                                Byte [] rawrs;
 
                                rawrs = Receive (ref endpoint);
@@ -953,6 +959,16 @@ namespace System.Data.SqlClient
 
                                return SqlServerTcpPort;
                        }
+
+                       IPEndPoint CreateLocalEndpoint ()
+                       {
+                               foreach (var addr in Dns.GetHostEntry ("localhost").AddressList) {
+                                       if (addr.AddressFamily == Client.AddressFamily)
+                                               return new IPEndPoint (addr, 0);
+                               }
+
+                               return null;
+                       }
                }
 
                struct ColumnInfo
diff --git a/mcs/class/System.Data/System.Data.SqlClient/SqlConnection.platformnotsupported.cs b/mcs/class/System.Data/System.Data.SqlClient/SqlConnection.platformnotsupported.cs
new file mode 100644 (file)
index 0000000..bb35026
--- /dev/null
@@ -0,0 +1,214 @@
+//
+// SqlConnection.cs
+//
+// Author:
+//       Rolf Bjarne Kvinge <rolf@xamarin.com>
+//
+// Copyright (c) 2016 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.Collections;
+using System.Data.Common;
+
+namespace System.Data.SqlClient
+{
+       public sealed class SqlConnection : DbConnection, IDbConnection, ICloneable
+       {
+               const string EXCEPTION_MESSAGE = "System.Data.SqlClient.SqlConnection is not supported on the current platform.";
+
+               public SqlConnection () : this (null)
+               {
+               }
+
+               public SqlConnection (string connectionString)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public SqlConnection (string connectionString, SqlCredential cred)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override string ConnectionString {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public SqlCredential Credentials {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public Guid ClientConnectionId {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override int ConnectionTimeout {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override string Database {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override string DataSource {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public int PacketSize {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override string ServerVersion {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override ConnectionState State {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string WorkstationId {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool FireInfoMessageEventOnUserErrors {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool StatisticsEnabled {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               protected override DbProviderFactory DbProviderFactory {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public event SqlInfoMessageEventHandler InfoMessage;
+
+               public new SqlTransaction BeginTransaction ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public new SqlTransaction BeginTransaction (IsolationLevel iso)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public SqlTransaction BeginTransaction (string transactionName)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public SqlTransaction BeginTransaction (IsolationLevel iso, string transactionName)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override void ChangeDatabase (string database)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override void Close ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public new SqlCommand CreateCommand ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected override void Dispose (bool disposing)
+               {
+               }
+
+#if !MOBILE
+               public void EnlistDistributedTransaction (ITransaction transaction)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+#endif
+
+               object ICloneable.Clone ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected override DbTransaction BeginDbTransaction (IsolationLevel isolationLevel)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected override DbCommand CreateDbCommand ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override void Open ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override DataTable GetSchema ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override DataTable GetSchema (String collectionName)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override DataTable GetSchema (String collectionName, string [] restrictionValues)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public static void ChangePassword (string connectionString, string newPassword)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public static void ClearAllPools ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public static void ClearPool (SqlConnection connection)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void ResetStatistics ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public IDictionary RetrieveStatistics ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+       }
+}
diff --git a/mcs/class/System.Data/System.Data.SqlClient/SqlDataReader.platformnotsupported.cs b/mcs/class/System.Data/System.Data.SqlClient/SqlDataReader.platformnotsupported.cs
new file mode 100644 (file)
index 0000000..395e97a
--- /dev/null
@@ -0,0 +1,363 @@
+//
+// SqlDataReader.cs
+//
+// Author:
+//       Rolf Bjarne Kvinge <rolf@xamarin.com>
+//
+// Copyright (c) 2016 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.Collections;
+using System.Data.Common;
+using System.Data.SqlClient;
+using System.Data.SqlTypes;
+using System.Data;
+using System.IO;
+using System.Threading.Tasks;
+using System.Threading;
+using System.Xml;
+
+
+namespace System.Data.SqlClient
+{
+       public class SqlDataReader : DbDataReader , IDataReader, IDisposable, IDataRecord
+       {
+               const string EXCEPTION_MESSAGE = "System.Data.SqlClient.SqlDataReader is not supported on the current platform.";
+
+               SqlDataReader () {}
+
+               protected bool IsCommandBehavior (CommandBehavior condition)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override void Close ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override bool GetBoolean (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override byte GetByte (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override long GetBytes (int i, long dataIndex, byte [] buffer, int bufferIndex, int length)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override char GetChar (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override long GetChars (int i, long dataIndex, char [] buffer, int bufferIndex, int length)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override string GetDataTypeName (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override DateTime GetDateTime (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual DateTimeOffset GetDateTimeOffset (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual TimeSpan GetTimeSpan (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual SqlChars GetSqlChars (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override Decimal GetDecimal (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override Double GetDouble (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override Type GetFieldType (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override Single GetFloat (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override Guid GetGuid (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override short GetInt16 (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override int GetInt32 (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override long GetInt64 (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override string GetName (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override int GetOrdinal (string name)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override DataTable GetSchemaTable ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual SqlBinary GetSqlBinary (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual SqlBoolean GetSqlBoolean (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual SqlByte GetSqlByte (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual SqlDateTime GetSqlDateTime (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual SqlDecimal GetSqlDecimal (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual SqlDouble GetSqlDouble (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual SqlGuid GetSqlGuid (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual SqlInt16 GetSqlInt16 (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual SqlInt32 GetSqlInt32 (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual SqlInt64 GetSqlInt64 (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual SqlMoney GetSqlMoney (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual SqlSingle GetSqlSingle (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual SqlString GetSqlString (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual SqlXml GetSqlXml (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual object GetSqlValue (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual int GetSqlValues (object [] values)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override string GetString (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override object GetValue (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override int GetValues (object [] values)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override IEnumerator GetEnumerator ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override bool IsDBNull (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override bool NextResult ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override bool Read ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override Type GetProviderSpecificFieldType (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override object GetProviderSpecificValue (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override int GetProviderSpecificValues (object [] values)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual SqlBytes GetSqlBytes (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override T GetFieldValue<T> (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual XmlReader GetXmlReader (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override Task<T> GetFieldValueAsync<T> (int i, CancellationToken cancellationToken)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override Stream GetStream (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override TextReader GetTextReader (int i)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override Task<bool> IsDBNullAsync (int i, CancellationToken cancellationToken)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override int Depth {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override int FieldCount {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override bool IsClosed {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override object this [int i] {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override object this [string name] {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override int RecordsAffected {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override bool HasRows {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override int VisibleFieldCount {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               protected SqlConnection Connection {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+       }
+}
index 3962bf4f55c9fa193525a4f35a2e51b7d4a617d5..5cb920c0e9a0beaf226613ae01367810f81c3603 100644 (file)
@@ -65,8 +65,11 @@ namespace System.Data.SqlClient
                public bool HasChanges {
                        get { return true; }
                }
-               
+
+#pragma warning disable 0067
+               [MonoTODO]
                public event OnChangeEventHandler OnChange;
+#pragma warning restore
 
                [MonoTODO]
                public void AddCommandDependency(SqlCommand command)
diff --git a/mcs/class/System.Data/System.Data.SqlClient/SqlException.platformnotsupported.cs b/mcs/class/System.Data/System.Data.SqlClient/SqlException.platformnotsupported.cs
new file mode 100644 (file)
index 0000000..24d102d
--- /dev/null
@@ -0,0 +1,102 @@
+//
+// SqlException.cs
+//
+// Author:
+//       Rolf Bjarne Kvinge <rolf@xamarin.com>
+//
+// Copyright (c) 2016 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.Data.Common;
+using System.Data.SqlClient;
+using System.Runtime.Serialization;
+
+namespace System.Data.SqlClient
+{
+       public class SqlException : DbException 
+       {
+               const string EXCEPTION_MESSAGE = "System.Data.SqlClient.SqlException is not supported on the current platform.";
+
+               internal bool _doNotReconnect;
+
+               static internal SqlException CreateException(SqlErrorCollection errorCollection, string serverVersion)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               static internal SqlException CreateException(SqlErrorCollection errorCollection, string serverVersion, SqlInternalConnectionTds internalConnection, Exception innerException = null)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               static internal SqlException CreateException(SqlErrorCollection errorCollection, string serverVersion, Guid conId, Exception innerException = null)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               SqlException () {}
+
+               public override void GetObjectData (SerializationInfo si, StreamingContext context)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public byte Class {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public Guid ClientConnectionId {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public SqlErrorCollection Errors {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public int LineNumber {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override string Message {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public int Number {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string Procedure {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string Server {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override string Source {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public byte State {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+       }
+}
index f6153fb60b55074b71511c3baae109d00f466b7f..33531b7c1fff5de910f931d1aa6f872d8e67bd04 100644 (file)
@@ -361,13 +361,13 @@ namespace System.Data.SqlClient {
                }
 
                [DefaultValue (0)]
-               public byte Precision {
+               public new byte Precision {
                        get { return metaParameter.Precision; }
                        set { metaParameter.Precision = value; }
                }
 
                [DefaultValue (0)]
-               public byte Scale {
+               public new byte Scale {
                        get { return metaParameter.Scale; }
                        set { metaParameter.Scale = value; }
                }
diff --git a/mcs/class/System.Data/System.Data.SqlClient/SqlParameter.platformnotsupported.cs b/mcs/class/System.Data/System.Data.SqlClient/SqlParameter.platformnotsupported.cs
new file mode 100644 (file)
index 0000000..79f6f95
--- /dev/null
@@ -0,0 +1,198 @@
+//
+// SqlParameter.cs
+//
+// Author:
+//       Rolf Bjarne Kvinge <rolf@xamarin.com>
+//
+// Copyright (c) 2016 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.Data;
+using System.Data.Common;
+using System.Data.SqlTypes;
+
+namespace System.Data.SqlClient
+{
+       public class SqlParameter : DbParameter , IDbDataParameter, IDataParameter, ICloneable
+       {
+               const string EXCEPTION_MESSAGE = "System.Data.SqlClient.SqlParameter is not supported on the current platform.";
+
+               public SqlParameter ()
+                       : this (String.Empty, SqlDbType.NVarChar, 0, ParameterDirection.Input, false, 0, 0, String.Empty, DataRowVersion.Current, null)
+               {
+               }
+
+               public SqlParameter (string parameterName, object value)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public SqlParameter (string parameterName, SqlDbType dbType) 
+                       : this (parameterName, dbType, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, null)
+               {
+               }
+
+               public SqlParameter (string parameterName, SqlDbType dbType, int size) 
+                       : this (parameterName, dbType, size, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, null)
+               {
+               }
+
+               public SqlParameter (string parameterName, SqlDbType dbType, int size, string sourceColumn) 
+                       : this (parameterName, dbType, size, ParameterDirection.Input, false, 0, 0, sourceColumn, DataRowVersion.Current, null)
+               {
+               }
+
+               public SqlParameter (string parameterName, SqlDbType dbType, int size, ParameterDirection direction, bool isNullable, byte precision, byte scale, string sourceColumn, DataRowVersion sourceVersion, object value) 
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public SqlParameter (string parameterName, SqlDbType dbType, int size, ParameterDirection direction, byte precision, byte scale, string sourceColumn, DataRowVersion sourceVersion, bool sourceColumnNullMapping, Object value, string xmlSchemaCollectionDatabase, string xmlSchemaCollectionOwningSchema, string xmlSchemaCollectionName)
+                       : this (parameterName, dbType, size, direction, false, precision, scale, sourceColumn, sourceVersion, value)
+               {
+               }
+
+               public override string ToString ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override void ResetDbType ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void ResetSqlDbType ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override DbType DbType {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override ParameterDirection Direction {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override bool IsNullable {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public int Offset {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override string ParameterName {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public byte Precision {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public byte Scale {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override int Size {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override string SourceColumn {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override DataRowVersion SourceVersion {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public SqlDbType SqlDbType {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override object Value {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public SqlCompareOptions CompareInfo {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public int LocaleId {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public object SqlValue {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override bool SourceColumnNullMapping {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string XmlSchemaCollectionDatabase {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string XmlSchemaCollectionName {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string XmlSchemaCollectionOwningSchema {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string UdtTypeName {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string TypeName {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               object ICloneable.Clone ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+       }
+}
diff --git a/mcs/class/System.Data/System.Data.SqlClient/SqlParameterCollection.platformnotsupported.cs b/mcs/class/System.Data/System.Data.SqlClient/SqlParameterCollection.platformnotsupported.cs
new file mode 100644 (file)
index 0000000..cc3a6ab
--- /dev/null
@@ -0,0 +1,216 @@
+//
+// SqlParameterCollection.cs
+//
+// Author:
+//       Rolf Bjarne Kvinge <rolf@xamarin.com>
+//
+// Copyright (c) 2016 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.Collections;
+using System.Data;
+using System.Data.Common;
+using System.Data.SqlClient;
+
+namespace System.Data.SqlClient
+{
+       public class SqlParameterCollection : DbParameterCollection , IDataParameterCollection, IList, ICollection, IEnumerable
+       {
+               const string EXCEPTION_MESSAGE = "System.Data.SqlClient.SqlParameterCollection is not supported on the current platform.";
+
+               SqlParameterCollection () {}
+
+               protected override DbParameter GetParameter (int index)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected override DbParameter GetParameter (string parameterName)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected override void SetParameter (int index, DbParameter value)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected override void SetParameter (string parameterName, DbParameter value)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override int Add (object value)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public SqlParameter Add (SqlParameter value)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public SqlParameter Add (string parameterName, object value)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public SqlParameter AddWithValue (string parameterName, object value)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public SqlParameter Add (string parameterName, SqlDbType sqlDbType)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public SqlParameter Add (string parameterName, SqlDbType sqlDbType, int size)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public SqlParameter Add (string parameterName, SqlDbType sqlDbType, int size, string sourceColumn)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override void Clear ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override bool Contains (object value)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override bool Contains (string value)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public bool Contains (SqlParameter value)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override void CopyTo (Array array, int index)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override IEnumerator GetEnumerator ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override int IndexOf (object value)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override int IndexOf (string parameterName)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public int IndexOf (SqlParameter value)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override void Insert (int index, object value)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void Insert (int index, SqlParameter value)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override void Remove (object value)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void Remove (SqlParameter value)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override void RemoveAt (int index)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override void RemoveAt (string parameterName)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override void AddRange (Array values)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void AddRange (SqlParameter [] values)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void CopyTo (SqlParameter [] array, int index)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override int Count {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override bool IsFixedSize {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override bool IsReadOnly {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override bool IsSynchronized {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override object SyncRoot {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public SqlParameter this [int index] {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public SqlParameter this [string parameterName] {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+       }
+}
diff --git a/mcs/class/System.Data/System.Data.SqlClient/SqlTransaction.platformnotsupported.cs b/mcs/class/System.Data/System.Data.SqlClient/SqlTransaction.platformnotsupported.cs
new file mode 100644 (file)
index 0000000..880b740
--- /dev/null
@@ -0,0 +1,77 @@
+//
+// SqlTransaction.cs
+//
+// Author:
+//       Rolf Bjarne Kvinge <rolf@xamarin.com>
+//
+// Copyright (c) 2016 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.Data;
+using System.Data.Common;
+using System.Data.SqlClient;
+
+namespace System.Data.SqlClient
+{
+       public class SqlTransaction : DbTransaction , IDbTransaction, IDisposable
+       {
+               const string EXCEPTION_MESSAGE = "System.Data.SqlClient.SqlTransaction is not supported on the current platform.";
+
+               SqlTransaction () {}
+
+               public override void Commit ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected override void Dispose (bool disposing)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override void Rollback ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void Rollback (string transactionName)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void Save (string savePointName)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public SqlConnection Connection {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override IsolationLevel IsolationLevel {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               protected override DbConnection DbConnection {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+       }
+}
index 3749af5091222bf0b8dce37071dbb1a947749f3f..a8974949973e3fc8afcd95fc9b88c3a91b5f588e 100644 (file)
@@ -96,10 +96,14 @@ namespace MonoTests.System.Data.Common
                        try {
                                da.AddToBatch (new SqlCommand ());
                                Assert.Fail ("#1");
+#if FEATURE_NO_BSD_SOCKETS
+                       } catch (PlatformNotSupportedException) {
+#else
                        } catch (NotSupportedException ex) {
                                Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
                                Assert.IsNull (ex.InnerException, "#3");
                                Assert.IsNotNull (ex.Message, "#4");
+#endif
                        }
                }
 
index b65ba7abab6fdd5c63cd9118676cf9393fc4f524..4fbbbbefe4aa6eb41f5da888b4026a4a4da4b09f 100644 (file)
@@ -39,21 +39,33 @@ namespace MonoTests.System.Data.SqlClient {
                private const string testFailParamNameMessage = "We have to provide the same parameter name as in original .NET";
                
                [Test] // .ctor(SqlConnection connection)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof(ArgumentNullException))]
+#endif
                public void ConstructorNotNull1 ()
                {
                        new SqlBulkCopy ((SqlConnection)null);
                }
                
                [Test] // .ctor(string connectionString)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof(ArgumentNullException))]
+#endif
                public void ConstructorNotNull2 ()
                {
                        new SqlBulkCopy ((string)null);
                }
                
                [Test] // .ctor(SqlConnection connection)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof(ArgumentNullException))]
+#endif
                public void ConstructorNotNull3 ()
                {
                        try {
@@ -65,7 +77,11 @@ namespace MonoTests.System.Data.SqlClient {
                }
                
                [Test] // .ctor(string connectionString)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof(ArgumentNullException))]
+#endif
                public void ConstructorNotNull4 ()
                {
                        try {
@@ -77,7 +93,11 @@ namespace MonoTests.System.Data.SqlClient {
                }
                
                [Test] // .ctor(string connectionString)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof(ArgumentNullException))]
+#endif
                public void ConstructorNotNull5 ()
                {
                        try {
@@ -89,7 +109,11 @@ namespace MonoTests.System.Data.SqlClient {
                }
                
                [Test] // .ctor(string connectionString)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof(ArgumentNullException))]
+#endif
                public void ConstructorNotNull6 ()
                {
                        try {
index c2d788bd3f54d734c82e581e0f6905f6cadd77e5..49abd6064dcead039e99b1450d308127e8f71086 100644 (file)
@@ -38,6 +38,9 @@ namespace MonoTests.System.Data.Odbc
        public class SqlCommandBuilderTest
        {
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void CatalogLocationTest ()
                {
                        SqlCommandBuilder cb = new SqlCommandBuilder ();
@@ -47,6 +50,9 @@ namespace MonoTests.System.Data.Odbc
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void CatalogLocation_Value_Invalid ()
                {
                        SqlCommandBuilder cb = new SqlCommandBuilder ();
@@ -82,6 +88,9 @@ namespace MonoTests.System.Data.Odbc
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void CatalogSeparator ()
                {
                        SqlCommandBuilder cb = new SqlCommandBuilder ();
@@ -89,6 +98,9 @@ namespace MonoTests.System.Data.Odbc
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void CatalogSeparator_Value_Invalid ()
                {
                        string [] separators = new string [] {
@@ -118,6 +130,9 @@ namespace MonoTests.System.Data.Odbc
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ConflictOptionTest ()
                {
                        SqlCommandBuilder cb = new SqlCommandBuilder ();
@@ -127,6 +142,9 @@ namespace MonoTests.System.Data.Odbc
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ConflictOption_Value_Invalid ()
                {
                        SqlCommandBuilder cb = new SqlCommandBuilder ();
@@ -147,6 +165,9 @@ namespace MonoTests.System.Data.Odbc
                }
 
                [Test] // QuoteIdentifier (String)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void QuoteIdentifier ()
                {
                        SqlCommandBuilder cb;
@@ -173,6 +194,9 @@ namespace MonoTests.System.Data.Odbc
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void QuoteIdentifier_PrefixSuffix_NoMatch ()
                {
                        SqlCommandBuilder cb;
@@ -211,6 +235,9 @@ namespace MonoTests.System.Data.Odbc
                }
 
                [Test] // QuoteIdentifier (String)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void QuoteIdentifier_UnquotedIdentifier_Null ()
                {
                        SqlCommandBuilder cb = new SqlCommandBuilder ();
@@ -226,6 +253,9 @@ namespace MonoTests.System.Data.Odbc
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void QuotePrefix ()
                {
                        SqlCommandBuilder cb = new SqlCommandBuilder ();
@@ -240,6 +270,9 @@ namespace MonoTests.System.Data.Odbc
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void QuotePrefix_Value_Invalid ()
                {
                        string [] prefixes = new string [] {
@@ -268,6 +301,9 @@ namespace MonoTests.System.Data.Odbc
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void QuoteSuffix ()
                {
                        SqlCommandBuilder cb = new SqlCommandBuilder ();
@@ -282,6 +318,9 @@ namespace MonoTests.System.Data.Odbc
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void QuoteSuffix_Value_Invalid ()
                {
                        string [] suffixes = new string [] {
@@ -310,6 +349,9 @@ namespace MonoTests.System.Data.Odbc
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SchemaSeparator ()
                {
                        SqlCommandBuilder cb = new SqlCommandBuilder ();
@@ -319,6 +361,9 @@ namespace MonoTests.System.Data.Odbc
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SchemaSeparator_Value_Invalid ()
                {
                        string [] separators = new string [] {
index d02532a45d9d0804d73ed5255084fda83cfcb1b8..be36ba383c1bcf6fec1d5d15b7f04d057c365e7d 100644 (file)
@@ -42,6 +42,9 @@ namespace MonoTests.System.Data.SqlClient
                const string COMMAND_TEXT = "SELECT * FROM Authors";
 
                [Test] // SqlCommand ()
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Constructor1 ()
                {
                        SqlCommand cmd = new SqlCommand ();
@@ -61,6 +64,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test] // SqlCommand (string)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Constructor2 ()
                {
                        SqlCommand cmd = new SqlCommand (COMMAND_TEXT);
@@ -95,6 +101,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test] // SqlCommand (string, SqlConnection)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Constructor3 ()
                {
                        SqlConnection conn = new SqlConnection ();
@@ -147,6 +156,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test] // SqlCommand (string, SqlConnection, SqlTransaction)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Constructor4 ()
                {
                        SqlConnection conn = new SqlConnection ();
@@ -199,6 +211,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Clone ()
                {
                        SqlNotificationRequest notificationReq = new SqlNotificationRequest ();
@@ -237,6 +252,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void CommandText ()
                {
                        SqlCommand cmd = new SqlCommand ();
@@ -251,6 +269,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void CommandTimeout ()
                {
                        SqlCommand cmd = new SqlCommand ();
@@ -263,6 +284,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void CommandTimeout_Value_Negative ()
                {
                        SqlCommand cmd = new SqlCommand ();
@@ -279,6 +303,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void CommandType_Value_Invalid ()
                {
                        SqlCommand cmd = new SqlCommand ();
@@ -296,6 +323,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test] // bug #324386
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Dispose ()
                {
                        string connectionString = "Initial Catalog=a;Server=b;User ID=c;"
@@ -307,6 +337,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ExecuteNonQuery_Connection_Closed ()
                {
                        string connectionString = "Initial Catalog=a;Server=b;User ID=c;"
@@ -329,6 +362,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ExecuteNonQuery_Connection_Null ()
                {
                        SqlCommand cmd = new SqlCommand ("delete from whatever");
@@ -346,6 +382,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ExecuteReader_Connection_Closed ()
                {
                        string connectionString = "Initial Catalog=a;Server=b;User ID=c;"
@@ -368,6 +407,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ExecuteReader_Connection_Null ()
                {
                        SqlCommand cmd = new SqlCommand ("select * from whatever");
@@ -385,6 +427,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ExecuteScalar_Connection_Closed ()
                {
                        string connectionString = "Initial Catalog=a;Server=b;User ID=c;"
@@ -407,6 +452,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test] // bug #412584
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ExecuteScalar_Connection_Null ()
                {
                        SqlCommand cmd = new SqlCommand ("select count(*) from whatever");
@@ -425,6 +473,9 @@ namespace MonoTests.System.Data.SqlClient
 
                // FIXME: this actually doesn't match .NET behavior. It shouldn't throw NRE.
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Prepare_Connection_Null ()
                {
                        SqlCommand cmd;
@@ -477,6 +528,9 @@ namespace MonoTests.System.Data.SqlClient
                }
                
                [Test] // bug #412586
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Prepare_Connection_Closed ()
                {
                        string connectionString = "Initial Catalog=a;Server=b;User ID=c;"
@@ -527,6 +581,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ResetCommandTimeout ()
                {
                        SqlCommand cmd = new SqlCommand ();
@@ -537,6 +594,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void UpdatedRowSource ()
                {
                        SqlCommand cmd = new SqlCommand ();
@@ -547,6 +607,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void UpdatedRowSource_Value_Invalid ()
                {
                        SqlCommand cmd = new SqlCommand ();
@@ -565,6 +628,9 @@ namespace MonoTests.System.Data.SqlClient
 
 
                [Test] // bug #381100
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ParameterCollectionTest ()
                {
                        SqlCommand cmd = new SqlCommand();
index 04a4b99871cc8f8af14614167cb6f3e35482eb5a..9511be24f7535375f8298d0c559a174d70452296 100644 (file)
@@ -39,6 +39,9 @@ namespace MonoTests.System.Data.SqlClient
        public class SqlConnectionTest\r
        {\r
                [Test] // SqlConnection ()\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void Constructor1 ()\r
                {\r
                        SqlConnection cn = new SqlConnection ();\r
@@ -57,6 +60,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test] // SqlConnection (string)\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void Constructor2 ()\r
                {\r
                        string connectionString = "server=SQLSRV; database=Mono;";\r
@@ -89,6 +95,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void Constructor2_ConnectionString_Invalid ()\r
                {\r
                        try {\r
@@ -181,6 +190,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void BeginTransaction_Connection_Closed ()\r
                {\r
                        SqlConnection cn = new SqlConnection ();\r
@@ -247,6 +259,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void ChangeDatabase_Connection_Closed ()\r
                {\r
                        SqlConnection cn = new SqlConnection ();\r
@@ -264,6 +279,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void ChangePassword_ConnectionString_Empty ()\r
                {\r
                        try {\r
@@ -279,6 +297,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void ChangePassword_ConnectionString_Null ()\r
                {\r
                        try {\r
@@ -293,7 +314,10 @@ namespace MonoTests.System.Data.SqlClient
                        }\r
                }\r
 \r
-               [Test]\r
+               \r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void ChangePassword_NewPassword_Empty ()\r
                {\r
                        try {\r
@@ -309,6 +333,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void ChangePassword_NewPassword_ExceedMaxLength ()\r
                {\r
                        try {\r
@@ -328,6 +355,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void ChangePassword_NewPassword_Null ()\r
                {\r
                        try {\r
@@ -343,6 +373,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void ClearPool_Connection_Null ()\r
                {\r
                        try {\r
@@ -357,6 +390,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void ConnectionString ()\r
                {\r
                        SqlConnection cn = new SqlConnection ();\r
@@ -371,6 +407,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void ConnectionString_Value_Invalid ()\r
                {\r
                        SqlConnection cn = new SqlConnection ();\r
@@ -403,6 +442,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void CreateCommand ()\r
                {\r
                        SqlConnection cn = new SqlConnection ();\r
@@ -424,6 +466,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void Dispose ()\r
                {\r
                        SqlConnection cn = new SqlConnection ("Server=SQLSRV;Database=master;Timeout=25;Packet Size=512;Workstation ID=DUMMY");\r
@@ -443,6 +488,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void GetSchema_Connection_Closed ()\r
                {\r
                        SqlConnection cn = new SqlConnection ();\r
@@ -519,6 +567,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void ConnectionString_AsynchronousProcessing ()\r
                {\r
                        SqlConnection cn = new SqlConnection ();\r
@@ -527,6 +578,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void ConnectionString_ConnectTimeout ()\r
                {\r
                        SqlConnection cn = new SqlConnection ();\r
@@ -543,6 +597,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void ConnectionString_ConnectTimeout_Invalid ()\r
                {\r
                        SqlConnection cn = new SqlConnection ();\r
@@ -600,6 +657,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void ConnectionString_Database_Synonyms ()\r
                {\r
                        SqlConnection cn = null;\r
@@ -614,6 +674,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void ConnectionString_DataSource_Synonyms ()\r
                {\r
                        SqlConnection cn = null;\r
@@ -640,6 +703,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void ConnectionString_MaxPoolSize ()\r
                {\r
                        SqlConnection cn = new SqlConnection ();\r
@@ -649,6 +715,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void ConnectionString_MaxPoolSize_Invalid ()\r
                {\r
                        SqlConnection cn = new SqlConnection ();\r
@@ -733,6 +802,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void ConnectionString_MinPoolSize ()\r
                {\r
                        SqlConnection cn = new SqlConnection ();\r
@@ -742,6 +814,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void ConnectionString_MinPoolSize_Invalid ()\r
                {\r
                        SqlConnection cn = new SqlConnection ();\r
@@ -799,6 +874,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void ConnectionString_MultipleActiveResultSets ()\r
                {\r
                        SqlConnection cn = new SqlConnection ();\r
@@ -806,6 +884,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void ConnectionString_MultipleActiveResultSets_Invalid ()\r
                {\r
                        SqlConnection cn = new SqlConnection ();\r
@@ -823,6 +904,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void ConnectionString_NetworkLibrary_Synonyms ()\r
                {\r
                        SqlConnection cn = new SqlConnection ();\r
@@ -832,6 +916,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void ConnectionString_PacketSize ()\r
                {\r
                        SqlConnection cn = new SqlConnection ();\r
@@ -848,6 +935,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void ConnectionString_PacketSize_Invalid ()\r
                {\r
                        SqlConnection cn = new SqlConnection ();\r
@@ -901,6 +991,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void ConnectionString_Password_Synonyms ()\r
                {\r
                        SqlConnection cn = new SqlConnection ();\r
@@ -909,6 +1002,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void ConnectionString_PersistSecurityInfo_Synonyms ()\r
                {\r
                        SqlConnection cn = new SqlConnection ();\r
@@ -917,6 +1013,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void ConnectionString_UserID_Synonyms ()\r
                {\r
                        SqlConnection cn = new SqlConnection ();\r
@@ -926,6 +1025,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void ConnectionString_UserInstance ()\r
                {\r
                        SqlConnection cn = new SqlConnection ();\r
@@ -933,6 +1035,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void ConnectionString_UserInstance_Invalid ()\r
                {\r
                        SqlConnection cn = new SqlConnection ();\r
@@ -950,6 +1055,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void ConnectionString_OtherKeywords ()\r
                {\r
                        SqlConnection cn = new SqlConnection ();\r
@@ -973,6 +1081,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void Open_ConnectionString_Empty ()\r
                {\r
                        SqlConnection cn = new SqlConnection ();\r
@@ -991,6 +1102,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void Open_ConnectionString_Null ()\r
                {\r
                        SqlConnection cn = new SqlConnection ();\r
@@ -1009,6 +1123,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void Open_ConnectionString_Whitespace ()\r
                {\r
                        SqlConnection cn = new SqlConnection ();\r
@@ -1027,6 +1144,9 @@ namespace MonoTests.System.Data.SqlClient
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void ServerVersion_Connection_Closed ()\r
                {\r
                        SqlConnection cn = new SqlConnection ();\r
@@ -1051,3 +1171,4 @@ namespace MonoTests.System.Data.SqlClient
                }\r
        }\r
 }\r
+\r
index 301f62bf7f22efba750f3a3ac4cc9d7c46183bd3..3a8b619baa1bb64e0c1525c50bf271ee41f3b6c0 100644 (file)
@@ -63,6 +63,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test] // SqlDataAdapter (SqlCommand)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Constructor2 ()
                {
                        SqlCommand cmd = new SqlCommand ();
@@ -109,6 +112,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test] // SqlDataAdapter (string, SqlConnection)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Constructor3 ()
                {
                        string selectCommandText = "SELECT * FROM Authors";
@@ -137,6 +143,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test] // SqlDataAdapter (string, SqlConnection)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Constructor3_SelectCommandText_Null ()
                {
                        SqlConnection selectConnection = new SqlConnection ();
@@ -165,6 +174,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test] // SqlDataAdapter (string, SqlConnection)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Constructor3_SelectConnection_Null ()
                {
                        string selectCommandText = "SELECT * FROM Authors";
@@ -192,6 +204,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test] // SqlDataAdapter (string, string)]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Constructor4 ()
                {
                        string selectCommandText = "SELECT * FROM Authors";
@@ -221,6 +236,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test] // SqlDataAdapter (string, string)]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Constructor4_SelectCommandText_Null ()
                {
                        string selectConnectionString = "server=SQLSRV;database=Mono";
@@ -250,6 +268,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test] // SqlDataAdapter (string, string)]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Constructor4_SelectConnectionString_Null ()
                {
                        string selectCommandText = "SELECT * FROM Authors";
@@ -278,6 +299,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void DeleteCommand ()
                {
                        SqlDataAdapter da = new SqlDataAdapter ();
@@ -293,6 +317,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Dispose ()
                {
                        SqlDataAdapter da = new SqlDataAdapter ();
@@ -311,6 +338,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void InsertCommand ()
                {
                        SqlDataAdapter da = new SqlDataAdapter ();
@@ -326,6 +356,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SelectCommand ()
                {
                        SqlDataAdapter da = new SqlDataAdapter ();
@@ -369,6 +402,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void UpdateCommand ()
                {
                        SqlDataAdapter da = new SqlDataAdapter ();
index 27e6fd1bf4ad9b4a5a884af737c5581aba5d4a71..e2048cfb9baf86b0b814c3a06f73248d0559cb1a 100644 (file)
@@ -45,6 +45,9 @@ namespace MonoTests.System.Data.SqlClient
        public class SqlParameterTest
        {
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Constructor1 ()
                {
                        SqlParameter p = new SqlParameter ();
@@ -68,6 +71,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Constructor2_Value_DateTime ()
                {
                        DateTime value = new DateTime (2004, 8, 24);
@@ -94,6 +100,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Constructor2_Value_DBNull ()
                {
                        SqlParameter p = new SqlParameter ("address", DBNull.Value);
@@ -118,6 +127,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Constructor2_Value_Null ()
                {
                        SqlParameter p = new SqlParameter ("address", (Object) null);
@@ -141,6 +153,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test] // .ctor (String, SqlDbType, Int32, ParameterDirection, Byte, Byte, String, DataRowVersion, Boolean, Object, String, String, String)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Constructor7 ()
                {
                        SqlParameter p1 = new SqlParameter ("p1Name", SqlDbType.VarChar, 20,
@@ -167,6 +182,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void CompareInfo ()
                {
                        SqlParameter parameter = new SqlParameter ();
@@ -176,6 +194,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void InferType_Byte ()
                {
                        Byte value = 0x0a;
@@ -187,6 +208,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void InferType_ByteArray ()
                {
                        Byte [] value = new Byte [] { 0x0a, 0x0d };
@@ -289,6 +313,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void InferType_DateTime ()
                {
                        DateTime value;
@@ -314,6 +341,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void InferType_Decimal ()
                {
                        Decimal value;
@@ -339,6 +369,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void InferType_Double ()
                {
                        Double value;
@@ -364,6 +397,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void InferType_Enum ()
                {
                        SqlParameter param;
@@ -380,6 +416,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void InferType_Guid ()
                {
                        Guid value = Guid.NewGuid ();
@@ -391,6 +430,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void InferType_Int16 ()
                {
                        Int16 value;
@@ -416,6 +458,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void InferType_Int32 ()
                {
                        Int32 value;
@@ -441,6 +486,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void InferType_Int64 ()
                {
                        Int64 value;
@@ -506,6 +554,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void InferType_Object ()
                {
                        Object value = new Object ();
@@ -517,6 +568,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void InferType_Single ()
                {
                        Single value = Single.MaxValue;
@@ -528,6 +582,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void InferType_String ()
                {
                        String value = "some text";
@@ -551,6 +608,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void LocaleId ()
                {
                        SqlParameter parameter = new SqlParameter ();
@@ -560,6 +620,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test] // bug #320196
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ParameterNullTest ()
                {
                        SqlParameter param = new SqlParameter ("param", SqlDbType.Decimal);
@@ -574,6 +637,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ParameterType ()
                {
                        SqlParameter p;
@@ -632,6 +698,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void InferType_Boolean ()
                {
                        Boolean value;
@@ -651,6 +720,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ParameterName ()
                {
                        SqlParameter p = new SqlParameter ();
@@ -676,6 +748,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ResetDbType ()
                {
                        SqlParameter p;
@@ -739,6 +814,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ResetSqlDbType ()
                {
                        //Parameter with an assigned value but no SqlDbType specified
@@ -779,6 +857,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SourceColumn ()
                {
                        SqlParameter p = new SqlParameter ();
@@ -804,6 +885,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SourceColumnNullMapping ()
                {
                        SqlParameter p = new SqlParameter ();
@@ -815,6 +899,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SqlDbTypeTest ()
                {
                        SqlParameter p = new SqlParameter ("zipcode", 3510);
@@ -829,6 +916,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SqlDbTypeTest_Value_Invalid ()
                {
                        SqlParameter p = new SqlParameter ("zipcode", 3510);
@@ -847,6 +937,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SqlValue ()
                {
                        SqlParameter parameter = new SqlParameter ();
@@ -970,6 +1063,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SqlTypes_SqlBinary ()
                {
                        SqlParameter parameter;
@@ -995,6 +1091,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SqlTypes_SqlBoolean ()
                {
                        SqlParameter parameter;
@@ -1020,6 +1119,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SqlTypes_SqlByte ()
                {
                        SqlParameter parameter;
@@ -1107,6 +1209,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SqlTypes_SqlDateTime ()
                {
                        SqlParameter parameter;
@@ -1132,6 +1237,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SqlTypes_SqlDecimal ()
                {
                        SqlParameter parameter;
@@ -1157,6 +1265,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SqlTypes_SqlDouble ()
                {
                        SqlParameter parameter;
@@ -1182,6 +1293,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SqlTypes_SqlGuid ()
                {
                        SqlParameter parameter;
@@ -1207,6 +1321,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SqlTypes_SqlInt16 ()
                {
                        SqlParameter parameter;
@@ -1232,6 +1349,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SqlTypes_SqlInt32 ()
                {
                        SqlParameter parameter;
@@ -1257,6 +1377,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SqlTypes_SqlInt64 ()
                {
                        SqlParameter parameter;
@@ -1282,6 +1405,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SqlTypes_SqlMoney ()
                {
                        SqlParameter parameter;
@@ -1307,6 +1433,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SqlTypes_SqlSingle ()
                {
                        SqlParameter parameter;
@@ -1332,6 +1461,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SqlTypes_SqlString ()
                {
                        SqlParameter parameter;
@@ -1357,6 +1489,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SqlTypes_SqlXml ()
                {
                        SqlParameter parameter;
@@ -1386,6 +1521,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Value ()
                {
                        SqlParameter p;
@@ -1429,6 +1567,9 @@ namespace MonoTests.System.Data.SqlClient
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void XmlSchemaTest ()
                {
                        SqlParameter p1 = new SqlParameter ();
old mode 100644 (file)
new mode 100755 (executable)
index 1993e7f..4412990
@@ -35,7 +35,6 @@ namespace MonoTests.System.Data
     [TestFixture]
     public class DataTableReadWriteXmlTest
     {
-        public static readonly string EOL = Environment.NewLine;
 
         void StandardizeXmlFormat(ref string xml)
         {
@@ -126,11 +125,11 @@ namespace MonoTests.System.Data
             // Get XML for DataSet writes.
             sw.GetStringBuilder().Length = 0;
             ds.WriteXml(sw);
-            string xmlDSNone = sw.ToString().Replace ("\n", EOL);
+            string xmlDSNone = sw.ToString();
             
             sw.GetStringBuilder().Length = 0;
             ds.WriteXml(sw, XmlWriteMode.DiffGram);
-            string xmlDSDiffGram = sw.ToString().Replace ("\n", EOL);
+            string xmlDSDiffGram = sw.ToString();
 
             sw.GetStringBuilder().Length = 0;
             ds.WriteXml(sw, XmlWriteMode.WriteSchema);
@@ -188,11 +187,11 @@ namespace MonoTests.System.Data
             
             sw.GetStringBuilder().Length = 0;
             ds.WriteXml(sw);
-            xmlDSNone = sw.ToString().Replace ("\n", EOL);
+            xmlDSNone = sw.ToString();
             
             sw.GetStringBuilder().Length = 0;
             ds.WriteXml(sw, XmlWriteMode.DiffGram);
-            xmlDSDiffGram = sw.ToString().Replace ("\n", EOL);
+            xmlDSDiffGram = sw.ToString();
 
             sw.GetStringBuilder().Length = 0;
             ds.WriteXml(sw, XmlWriteMode.WriteSchema);
old mode 100644 (file)
new mode 100755 (executable)
index 388f547..9d54c82
@@ -3236,7 +3236,6 @@ namespace MonoTests.System.Data
                        string TextString = GetNormalizedSchema (writer.ToString ());
                        //string TextString = writer.ToString ();
 
-                       EOL = "\n";
                        string substring = TextString.Substring (0, TextString.IndexOf (EOL));
                        TextString = TextString.Substring (TextString.IndexOf (EOL) + EOL.Length);
                        Assert.AreEqual ("<?xml version=\"1.0\" encoding=\"utf-16\"?>", substring, "test#01");
old mode 100644 (file)
new mode 100755 (executable)
index 053ecdb..93b0cc6
@@ -174,9 +174,9 @@ namespace MonoTests.System.Data.Xml
                        StringWriter sw = new StringWriter ();
                        XmlTextWriter xw = new XmlTextWriter (sw);
                        Doc.DataSet.WriteXml (xw);
-                       string s = sw.ToString ();
+                       string s = sw.ToString ().Replace ("\r", "").Replace ("\n", Environment.NewLine);
                        Assert.AreEqual (xml, s, "#1");
-                       Assert.AreEqual (xml, Doc.InnerXml, "#2");
+                       Assert.AreEqual (xml, Doc.InnerXml.Replace ("\r", "").Replace ("\n", Environment.NewLine), "#2");
                        Assert.AreEqual ("EndOfFile", Reader.ReadState.ToString (), "test#01");
 
                        DataSet Set = Doc.DataSet;
diff --git a/mcs/class/System.Data/monotouch_watch_System.Data.dll.exclude.sources b/mcs/class/System.Data/monotouch_watch_System.Data.dll.exclude.sources
new file mode 100644 (file)
index 0000000..2782624
--- /dev/null
@@ -0,0 +1,11 @@
+System.Data.SqlClient/SqlBulkCopy.cs
+System.Data.SqlClient/SqlCommand.cs
+System.Data.SqlClient/SqlCommandBuilder.cs
+System.Data.SqlClient/SqlConnection.cs
+System.Data.SqlClient/SqlDataReader.cs
+System.Data.SqlClient/SqlDecimalExtensions.cs
+System.Data.SqlClient/SqlException.cs
+System.Data.SqlClient/SqlParameter.cs
+System.Data.SqlClient/SqlParameterCollection.cs
+System.Data.SqlClient/SqlTransaction.cs
+System.Data.SqlClient/SqlXmlTextReader.cs
index bbc860b8cd783f47398a9a084950cde37d3e6221..f279aec80605393212efc69e5caf5703d0a8480c 100644 (file)
@@ -1 +1,10 @@
 #include mobile_System.Data.dll.sources
+System.Data.SqlClient/SqlBulkCopy.platformnotsupported.cs
+System.Data.SqlClient/SqlCommand.platformnotsupported.cs
+System.Data.SqlClient/SqlCommandBuilder.platformnotsupported.cs
+System.Data.SqlClient/SqlConnection.platformnotsupported.cs
+System.Data.SqlClient/SqlDataReader.platformnotsupported.cs
+System.Data.SqlClient/SqlException.platformnotsupported.cs
+System.Data.SqlClient/SqlParameter.platformnotsupported.cs
+System.Data.SqlClient/SqlParameterCollection.platformnotsupported.cs
+System.Data.SqlClient/SqlTransaction.platformnotsupported.cs
index 7eea754cfa905116418953dd58a636f7fbea109f..29bb7acd6ee63617f77795f248bccf18f87da3ff 100644 (file)
@@ -2,8 +2,12 @@ thisdir = class/System.IdentityModel
 SUBDIRS = 
 include ../../build/rules.make
 
+ifndef NO_MONO_SECURITY
+MONO_SECURITY=Mono.Security
+endif
+
 LIBRARY = System.IdentityModel.dll
-LIB_REFS = System System.Xml System.Security Mono.Security System.Runtime.Serialization
+LIB_REFS = System System.Xml System.Security $(MONO_SECURITY) System.Runtime.Serialization
 LIB_MCS_FLAGS = \
                /d:NET_3_0      \
                $(OTHER_LIB_MCS_FLAGS)
index 59456d6df0bb91dbaaae0de6a84b01c3e6b4ccf0..14ebd8ff85de73380a0b30f2e7c0aa41363ffeef 100644 (file)
@@ -29,7 +29,12 @@ namespace System.Net.Http {
                // but we want this to work "as expected" even if the application is not being linked
                static HttpMessageHandler GetDefaultHandler ()
                {
+#if MONOTOUCH_WATCH
+                       // There's only one valid handler type for watchOS
+                       return new NSUrlSessionHandler ();
+#else
                        return RuntimeOptions.GetHttpMessageHandler ();
+#endif
                }
        }
 #else
index ee2dbe74b67855bf0c9bf4a7210aea2df3b02c46..e90cc29f822a82c5b405de37c856f78a33a1850b 100644 (file)
@@ -147,7 +147,7 @@ namespace System.Net.Http.Headers
                        if (t != Token.Type.Token)
                                return false;
 
-                       int nvalue;
+                       long nvalue;
                        if (!lexer.IsStarStringValue (t)) {
                                if (!lexer.TryGetNumericValue (t, out nvalue)) {
                                        var s = lexer.GetStringValue (t);
@@ -158,12 +158,12 @@ namespace System.Net.Http.Headers
                                        if (sep.Length != 2)
                                                return false;
 
-                                       if (!int.TryParse (sep[0], NumberStyles.None, CultureInfo.InvariantCulture, out nvalue))
+                                       if (!long.TryParse (sep[0], NumberStyles.None, CultureInfo.InvariantCulture, out nvalue))
                                                return false;
 
                                        value.From = nvalue;
 
-                                       if (!int.TryParse (sep[1], NumberStyles.None, CultureInfo.InvariantCulture, out nvalue))
+                                       if (!long.TryParse (sep[1], NumberStyles.None, CultureInfo.InvariantCulture, out nvalue))
                                                return false;
 
                                        value.To = nvalue;
index 78f2fafcc83284e5e87abfbcbfb13e4935abbd1a..a3335ea5506ffe67aafedba5773301d48b9cee77 100644 (file)
@@ -380,7 +380,9 @@ namespace System.Net.Http
                                }
                        } catch (WebException we) {
                                if (we.Status != WebExceptionStatus.RequestCanceled)
-                                       throw;
+                                       throw new HttpRequestException ("An error occurred while sending the request", we);
+                       } catch (System.IO.IOException ex) {
+                               throw new HttpRequestException ("An error occurred while sending the request", ex);
                        }
 
                        if (cancellationToken.IsCancellationRequested) {
diff --git a/mcs/class/System.Net.Http/System.Net.Http/HttpClientHandler.platformnotsupported.cs b/mcs/class/System.Net.Http/System.Net.Http/HttpClientHandler.platformnotsupported.cs
new file mode 100644 (file)
index 0000000..eb5b7ff
--- /dev/null
@@ -0,0 +1,175 @@
+//
+// System.Net.Http/HttpClientHandler.cs
+//
+// Author:
+//     Rolf Bjarne Kvinge <rolf@xamarin.com>
+//
+// Copyright (C) 2016 Xamarin Inc (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.Collections.Generic;
+using System.Net.Security;
+using System.Security.Authentication;
+using System.Security.Cryptography.X509Certificates;
+using System.Threading.Tasks;
+using System.Threading;
+
+namespace System.Net.Http
+{
+       public class HttpClientHandler : HttpMessageHandler
+       {
+               const string EXCEPTION_MESSAGE = "System.Net.Http.HttpClientHandler is not supported on the current platform.";
+
+               public HttpClientHandler ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public bool AllowAutoRedirect {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public DecompressionMethods AutomaticDecompression {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public ClientCertificateOption ClientCertificateOptions {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public CookieContainer CookieContainer {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public ICredentials Credentials {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public int MaxAutomaticRedirections {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public long MaxRequestContentBufferSize {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool PreAuthenticate {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public IWebProxy Proxy {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public virtual bool SupportsAutomaticDecompression {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public virtual bool SupportsProxy {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public virtual bool SupportsRedirectConfiguration {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool UseCookies {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool UseDefaultCredentials {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool UseProxy {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               protected override void Dispose (bool disposing)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               HttpResponseMessage CreateResponseMessage (HttpWebResponse wr, HttpRequestMessage requestMessage, CancellationToken cancellationToken)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected internal async override Task<HttpResponseMessage> SendAsync (HttpRequestMessage request, CancellationToken cancellationToken)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+#if NETSTANDARD
+               public bool CheckCertificateRevocationList {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public X509CertificateCollection ClientCertificates {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public ICredentials DefaultProxyCredentials {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public int MaxConnectionsPerServer {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public int MaxResponseHeadersLength {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public IDictionary<string,object> Properties {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public Func<HttpRequestMessage,X509Certificate2,X509Chain,SslPolicyErrors,bool> ServerCertificateCustomValidationCallback {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public SslProtocols SslProtocols {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+#endif
+       }
+}
index 62b740c33cd5b9ba2ee05a5ab7741938037be95a..7522def2d7b2999527d732a93cc3006bac2b0d24 100644 (file)
@@ -101,6 +101,12 @@ namespace MonoTests.System.Net.Http.Headers
                        Assert.IsNull (res.To, "#22");
                        Assert.IsNull (res.Length, "#23");
                        Assert.AreEqual ("by */*", res.ToString (), "#24");
+
+                       res = ContentRangeHeaderValue.Parse("bytes  199999999999999999 - 999999999999999999/ 9223372036854775807");
+                       Assert.AreEqual (199999999999999999, res.From, "#31");
+                       Assert.AreEqual (999999999999999999, res.To, "#32");
+                       Assert.AreEqual (9223372036854775807, res.Length, "#33");
+                       Assert.AreEqual ("bytes 199999999999999999-999999999999999999/9223372036854775807", res.ToString (), "#34");
                }
 
                [Test]
index 78f8a0c225d5eb089658e94aa3aa821bc1706f42..3f06e1c316da8440c0a8701439deb9e5ee18b770 100644 (file)
@@ -61,6 +61,9 @@ namespace MonoTests.System.Net.Http
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Properties_Defaults ()
                {
                        var h = new HttpClientHandler ();
@@ -83,6 +86,9 @@ namespace MonoTests.System.Net.Http
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Properties_Invalid ()
                {
                        var h = new HttpClientHandler ();
@@ -107,6 +113,9 @@ namespace MonoTests.System.Net.Http
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Properties_AfterClientCreation ()
                {
                        var h = new HttpClientHandler ();
@@ -119,6 +128,9 @@ namespace MonoTests.System.Net.Http
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Disposed ()
                {
                        var h = new HttpClientHandler ();
index f1af864e214943a61321e2cf20cf93ff4a215cc7..d9aab417dfa00762ff0848ae78385316ada5a7e3 100644 (file)
@@ -263,6 +263,10 @@ namespace MonoTests.System.Net.Http
 
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               // Using HttpClientHandler, which indirectly requires BSD sockets.
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void CancelRequestViaProxy ()
                {
                        var handler = new HttpClientHandler {
@@ -321,7 +325,9 @@ namespace MonoTests.System.Net.Http
                }
 
                [Test]
-               [Category ("RequiresBSDSockets")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Proxy_Disabled ()
                {
                        var pp = WebRequest.DefaultWebProxy;
@@ -398,7 +404,9 @@ namespace MonoTests.System.Net.Http
                }
 
                [Test]
-               [Category ("RequiresBSDSockets")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Send_Complete_Default ()
                {
                        bool? failed = null;
@@ -443,7 +451,9 @@ namespace MonoTests.System.Net.Http
                }
 
                [Test]
-               [Category ("RequiresBSDSockets")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Send_Complete_Version_1_0 ()
                {
                        bool? failed = null;
@@ -491,7 +501,9 @@ namespace MonoTests.System.Net.Http
                }
 
                [Test]
-               [Category ("RequiresBSDSockets")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Send_Complete_ClientHandlerSettings ()
                {
                        bool? failed = null;
@@ -556,7 +568,9 @@ namespace MonoTests.System.Net.Http
                }
 
                [Test]
-               [Category ("RequiresBSDSockets")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Send_Complete_CustomHeaders ()
                {
                        bool? failed = null;
@@ -621,7 +635,9 @@ namespace MonoTests.System.Net.Http
                }
 
                [Test]
-               [Category ("RequiresBSDSockets")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Send_Complete_CustomHeaders_SpecialSeparators ()
                {
                        bool? failed = null;
@@ -656,7 +672,9 @@ namespace MonoTests.System.Net.Http
                }
 
                [Test]
-               [Category ("RequiresBSDSockets")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Send_Complete_CustomHeaders_Host ()
                {
                        bool? failed = null;
@@ -690,7 +708,9 @@ namespace MonoTests.System.Net.Http
                }
 
                [Test]
-               [Category ("RequiresBSDSockets")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Send_Transfer_Encoding_Chunked ()
                {
                        bool? failed = null;
@@ -720,7 +740,9 @@ namespace MonoTests.System.Net.Http
                }
 
                [Test]
-               [Category ("RequiresBSDSockets")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Send_Transfer_Encoding_Custom ()
                {
                        bool? failed = null;
@@ -749,7 +771,9 @@ namespace MonoTests.System.Net.Http
                }
 
                [Test]
-               [Category ("RequiresBSDSockets")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Send_Complete_Content ()
                {
                        var listener = CreateListener (l => {
@@ -777,7 +801,9 @@ namespace MonoTests.System.Net.Http
                }
 
                [Test]
-               [Category ("RequiresBSDSockets")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Send_Complete_Content_MaxResponseContentBufferSize ()
                {
                        var listener = CreateListener (l => {
@@ -800,7 +826,9 @@ namespace MonoTests.System.Net.Http
                }
 
                [Test]
-               [Category ("RequiresBSDSockets")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Send_Complete_Content_MaxResponseContentBufferSize_Error ()
                {
                        var listener = CreateListener (l => {
@@ -827,7 +855,9 @@ namespace MonoTests.System.Net.Http
                }
 
                [Test]
-               [Category ("RequiresBSDSockets")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Send_Complete_NoContent ()
                {
                        foreach (var method in new HttpMethod[] { HttpMethod.Post, HttpMethod.Put, HttpMethod.Delete }) {
@@ -860,7 +890,9 @@ namespace MonoTests.System.Net.Http
                }
 
                [Test]
-               [Category ("RequiresBSDSockets")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Send_Complete_Error ()
                {
                        var listener = CreateListener (l => {
@@ -881,7 +913,9 @@ namespace MonoTests.System.Net.Http
                }
 
                [Test]
-               [Category ("RequiresBSDSockets")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Send_Content_Get ()
                {
                        var listener = CreateListener (l => {
@@ -901,7 +935,9 @@ namespace MonoTests.System.Net.Http
                }
 
                [Test]
-               [Category ("RequiresBSDSockets")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Send_Content_BomEncoding ()
                {
                        var listener = CreateListener (l => {
@@ -926,7 +962,9 @@ namespace MonoTests.System.Net.Http
                }
 
                [Test]
-               [Category ("RequiresBSDSockets")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Send_Content_Put ()
                {
                        bool passed = false;
@@ -952,7 +990,9 @@ namespace MonoTests.System.Net.Http
                }
 
                [Test]
-               [Category ("RequiresBSDSockets")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Send_Content_Put_CustomStream ()
                {
                        bool passed = false;
@@ -1055,7 +1095,9 @@ namespace MonoTests.System.Net.Http
 
                [Test]
                [Category ("MobileNotWorking")] // Missing encoding
-               [Category ("RequiresBSDSockets")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void GetString_Many ()
                {
                        Action<HttpListenerContext> context = (HttpListenerContext l) => {
@@ -1085,7 +1127,9 @@ namespace MonoTests.System.Net.Http
                }
 
                [Test]
-               [Category ("RequiresBSDSockets")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void GetByteArray_ServerError ()
                {
                        var listener = CreateListener (l => {
@@ -1108,7 +1152,9 @@ namespace MonoTests.System.Net.Http
                }
 
                [Test]
-               [Category ("RequiresBSDSockets")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void DisallowAutoRedirect ()
                {
                        var listener = CreateListener (l => {
@@ -1137,7 +1183,9 @@ namespace MonoTests.System.Net.Http
                }
 
                [Test]
-               [Category ("RequiresBSDSockets")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void RequestUriAfterRedirect ()
                {
                        var listener = CreateListener (l => {
@@ -1178,7 +1226,9 @@ namespace MonoTests.System.Net.Http
                }
 
                [Test]
-               [Category ("RequiresBSDSockets")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                /*
                 * Properties may only be modified before sending the first request.
                 */
@@ -1209,6 +1259,10 @@ namespace MonoTests.System.Net.Http
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               // Using HttpClientHandler, which indirectly requires BSD sockets.
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                /*
                 * However, this policy is not enforced for custom handlers and there
                 * is also no way a derived class could tell its HttpClientHandler parent
diff --git a/mcs/class/System.Net.Http/monotouch_watch_System.Net.Http.dll.exclude.sources b/mcs/class/System.Net.Http/monotouch_watch_System.Net.Http.dll.exclude.sources
new file mode 100644 (file)
index 0000000..5c2ff8a
--- /dev/null
@@ -0,0 +1 @@
+System.Net.Http/HttpClientHandler.cs
diff --git a/mcs/class/System.Net.Http/monotouch_watch_System.Net.Http.dll.sources b/mcs/class/System.Net.Http/monotouch_watch_System.Net.Http.dll.sources
new file mode 100644 (file)
index 0000000..a9d766e
--- /dev/null
@@ -0,0 +1,2 @@
+#include System.Net.Http.dll.sources
+System.Net.Http/HttpClientHandler.platformnotsupported.cs
index cab5d34208680ac5f12accbe69744d2238c513cc..2ca12fb601a69ce9e90cc073953f6e34ac86690c 100644 (file)
@@ -71,7 +71,12 @@ namespace System.Runtime.Remoting.Channels.Tcp
                                        else {
                                                IPHostEntry he = Dns.Resolve (Dns.GetHostName());
                                                if (he.AddressList.Length == 0) throw new RemotingException ("IP address could not be determined for this host");
-                                               host = he.AddressList [0].ToString ();
+                                               AddressFamily addressFamily = (Socket.OSSupportsIPv4) ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6;
+                                               IPAddress addr = GetMachineAddress (he, addressFamily);
+                                               if (addr != null)
+                                                       host = addr.ToString ();
+                                               else
+                                                       host = he.AddressList [0].ToString ();
                                        }
                                }
                                else
@@ -259,6 +264,22 @@ namespace System.Runtime.Remoting.Channels.Tcp
                        server_thread.Join ();
                        server_thread = null;                   
                }
+
+               private static IPAddress GetMachineAddress (IPHostEntry host, AddressFamily addressFamily)
+               {
+                       IPAddress result = null;
+                       if (host != null) {
+                               IPAddress[] addressList = host.AddressList;
+                               for (int i = 0; i < addressList.Length; i++) {
+                                       if (addressList[i].AddressFamily == addressFamily) {
+                                               result = addressList[i];
+                                               break;
+                                       }
+                               }
+                       }
+
+                       return result;
+               }
        }
 
        class ClientConnection
index 74ed3335acb89306584341d1642cb1371a64b870..19da4ee2235bf1c77971ebe32cb77cf6e94aa002 100644 (file)
@@ -55,6 +55,11 @@ namespace System.Runtime.Serialization
             return false;
         }
 
+        internal static void AddDefaultXmlType(XmlSchemaSet schemas, string localName, string ns)
+        {
+            throw new NotImplementedException();
+        }
+
         static bool InvokeSchemaProviderMethod(Type clrType, XmlSchemaSet schemas, out XmlQualifiedName stableName, out XmlSchemaType xsdType, out bool hasRoot)
         {
             xsdType = null;
diff --git a/mcs/class/System.Runtime.Serialization/ReferenceSources/XsdDataContractExporter_mobile.cs b/mcs/class/System.Runtime.Serialization/ReferenceSources/XsdDataContractExporter_mobile.cs
new file mode 100644 (file)
index 0000000..bc1bf43
--- /dev/null
@@ -0,0 +1,54 @@
+//
+// XsdDataContractExporter_mobile.cs
+//
+// Authors:
+//     Alexander Köplinger <alexander.koeplinger@xamarin.com>
+//
+// Copyright (C) 2016 Xamarin Inc (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Xml;
+using System.Xml.Schema;
+
+namespace System.Runtime.Serialization
+{
+       public class XsdDataContractExporter
+       {
+               public XsdDataContractExporter () { throw new NotImplementedException (); }
+               public XsdDataContractExporter (XmlSchemaSet schemas) { throw new NotImplementedException (); }
+               public ExportOptions Options { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } }
+               public XmlSchemaSet Schemas { get { throw new NotImplementedException (); } }
+               public bool CanExport (ICollection<Assembly> assemblies) { throw new NotImplementedException ();}
+               public bool CanExport (ICollection<Type> types) { throw new NotImplementedException (); }
+               public bool CanExport (Type type) { throw new NotImplementedException (); }
+               public void Export (ICollection<Assembly> assemblies) { throw new NotImplementedException (); }
+               public void Export (ICollection<Type> types) { throw new NotImplementedException (); }
+               public void Export (Type type) { throw new NotImplementedException (); }
+               public XmlQualifiedName GetRootElementName (Type type) { throw new NotImplementedException (); }
+               public XmlSchemaType GetSchemaType (Type type) { throw new NotImplementedException (); }
+               public XmlQualifiedName GetSchemaTypeName (Type type) { throw new NotImplementedException (); }
+       }
+}
+
index c0c73b07ad060fd22023aa3448912020fa0071df..bc4259a994c55a6d42e1e290835bd9f7dd7ebfac 100644 (file)
@@ -2,4 +2,5 @@
 #include ReferenceSource.common.sources
 
 ReferenceSources/SchemaExporter_mobile.cs
+ReferenceSources/XsdDataContractExporter_mobile.cs
 ReferenceSources/SimplifiedCodeTypeReference.cs
index 5c009acb56608c1d391e86faea97071af7e3f33e..145f30f4b6ccd9d7acf6a9c1650b765c85b89d6e 100644 (file)
@@ -2,8 +2,13 @@ thisdir = class/System.Security
 SUBDIRS = 
 include ../../build/rules.make
 
+ifndef NO_MONO_SECURITY
+MONO_SECURITY_DLL=$(the_libdir_base)/Mono.Security.dll
+MONO_SECURITY=Mono.Security
+endif
+
 LIBRARY = System.Security.dll
-LIB_REFS = secxml/System bare/System.Xml Mono.Security
+LIB_REFS = secxml/System bare/System.Xml $(MONO_SECURITY)
 LIB_MCS_FLAGS = -nowarn:618 \
        -d:SECURITY_DEP \
        -nowarn:414
@@ -22,7 +27,7 @@ EXTRA_DISTFILES = \
 
 include ../../build/library.make
 
-$(build_lib): $(secxml_libdir)/System.dll $(the_libdir_base)/Mono.Security.dll
+$(build_lib): $(secxml_libdir)/System.dll $(MONO_SECURITY_DLL)
 
 $(secxml_libdir)/System.dll:
        (cd ../System; $(MAKE) $@)
index f25171f793f2c5b909b603bc30be8f6d48af81a5..909ae4f9cf04cc9c2cd483dfbe4d5e906e94e0bc 100644 (file)
@@ -48,7 +48,7 @@ namespace MonoTests.System.ServiceModel.Web
        public class WebOperationContextTest
        {
 // MonoTouch does not support dynamic proxy code generation.
-#if !MONOTOUCH
+#if !MONOTOUCH && !MOBILE_STATIC
                [Test]
 #endif
                public void Current ()
index 641a95852ee198c0bfd2d652495f9de556f8c91a..f7d30c63c3466ab403f9033814f6cfcc12eaa892 100644 (file)
@@ -105,23 +105,53 @@ namespace MonoTests.System.ServiceModel.Dispatcher
                                        Assert.AreEqual (5, p.ErrorCode, "#2");
                                        Assert.AreEqual ("foobarerror", p.Text, "#3");
                                }
+                       } finally {
+                               host.Close ();
+                       }
+               }
+
+               [Test]
+               public void FaultContractInfos_2 ()
+               {
+                       var host = new ServiceHost (typeof (TestFaultContract));
+                       int port = NetworkHelpers.FindFreePort ();
+                       host.Description.Behaviors.Find<ServiceDebugBehavior> ().IncludeExceptionDetailInFaults = false;
+                       host.AddServiceEndpoint (typeof (ITestFaultContract), new BasicHttpBinding (), new Uri ("http://localhost:" + port));
+                       host.Open ();
+                       try {
+                               var cf = new ChannelFactory<ITestFaultContract> (new BasicHttpBinding (), new EndpointAddress ("http://localhost:" + port));
+                               var cli = cf.CreateChannel ();
 
                                try {
                                        cli.Run ("deriveddata");
                                        Assert.Fail ("#4");
-                               } catch (Exception ex) {
+                               } catch (FaultException ex) {
                                        // The type must be explicitly listed in the [FaultContract],
                                        // it is not allowed to use a subclass of the exception data type.
-                                       Assert.AreEqual (typeof (FaultException), ex.GetType (), "#5");
                                }
+                       } finally {
+                               host.Close ();
+                       }
+               }
 
+               [Test]
+               public void FaultContractInfos_3 ()
+               {
+                       var host = new ServiceHost (typeof (TestFaultContract));
+                       int port = NetworkHelpers.FindFreePort ();
+                       host.Description.Behaviors.Find<ServiceDebugBehavior> ().IncludeExceptionDetailInFaults = false;
+                       host.AddServiceEndpoint (typeof (ITestFaultContract), new BasicHttpBinding (), new Uri ("http://localhost:" + port));
+                       host.Open ();
+                       try {
+                               var cf = new ChannelFactory<ITestFaultContract> (new BasicHttpBinding (), new EndpointAddress ("http://localhost:" + port));
+                               var cli = cf.CreateChannel ();
+                               
                                try {
                                        cli.Run ("derivedexception");
                                        Assert.Fail ("#6");
-                               } catch (Exception ex) {
+                               } catch (FaultException<PrivateAffairError> ex) {
                                        // However, it is allowed to derive from FaultException<T>, provided
                                        // that T is explicitly listed in [FaultContract].  Bug #7177.
-                                       Assert.AreEqual (typeof (FaultException<PrivateAffairError>), ex.GetType (), "#7");
                                }
                        } finally {
                                host.Close ();
index 895440d3a6a8ec33f843523b24777261e37e3014..15c0393412b8635cf4f59d61b10e3bd32799544e 100644 (file)
@@ -47,8 +47,6 @@ namespace System.Web.Compilation
 {
        class AppResourcesAssemblyBuilder
        {
-               static string framework_version = "4.5";
-               static string profile_path = "net_4_x";
                CompilationSection config;
                CompilerInfo ci;
                CodeDomProvider _provider;
@@ -233,36 +231,14 @@ namespace System.Web.Compilation
                string SetAlPath (ProcessStartInfo info)
                {                       
                        if (RuntimeHelpers.RunningOnWindows) {
-                               string alPath;
-                               string monoPath;
-                               PropertyInfo gac = typeof (Environment).GetProperty ("GacPath", BindingFlags.Static|BindingFlags.NonPublic);
-                                MethodInfo get_gac = gac.GetGetMethod (true);
-                                string p = Path.GetDirectoryName ((string) get_gac.Invoke (null, null));
-                               monoPath = Path.Combine (Path.GetDirectoryName (Path.GetDirectoryName (p)), "bin\\mono.bat");
-                                if (!File.Exists (monoPath)) {
-                                        monoPath = Path.Combine (Path.GetDirectoryName (Path.GetDirectoryName (p)), "bin\\mono.exe");
-                                       if (!File.Exists (monoPath)) {
-                                               monoPath = Path.Combine (Path.GetDirectoryName (Path.GetDirectoryName (Path.GetDirectoryName (p))), "mono\\mono\\mini\\mono.exe");
-                                               if (!File.Exists (monoPath))
-                                                       throw new FileNotFoundException ("Windows mono path not found: " + monoPath);
-                                       }
-                               }
-                               alPath = Path.Combine (p, framework_version + "\\al.exe");
-                               
-                                if (!File.Exists (alPath)) {
-                                       alPath = Path.Combine (Path.GetDirectoryName (p), "lib\\" + profile_path + "\\al.exe");
-                                       if (!File.Exists (alPath))
-                                               throw new FileNotFoundException ("Windows al path not found: " + alPath);
-                               }
-
-                               info.FileName = monoPath;
-                               return alPath + " ";
+                               info.FileName = MonoToolsLocator.Mono;
+                               return MonoToolsLocator.AssemblyLinker + " ";
                        } else {
-                               info.FileName = "al";
+                               info.FileName = MonoToolsLocator.AssemblyLinker;
                                return String.Empty;
                        }
                }
-               
+
                string BuildAssemblyPath (string cultureName)
                {
                        string baseDir = Path.Combine (baseAssemblyDirectory, cultureName);
index 248b80f3537526f9501de642c6f69698a20bcf75..46f3627f416fa5f5342ba4ef05c35b8a56e65ba1 100644 (file)
@@ -2,6 +2,7 @@ Assembly/AssemblyInfo.cs
 ../../build/common/Consts.cs
 ../../build/common/Locale.cs
 ../../build/common/MonoTODOAttribute.cs
+../System/System/MonoToolsLocator.cs
 ../System.Windows.Forms/System.Resources/AssemblyNamesTypeResolutionService.cs
 ../System.Windows.Forms/System.Resources/ByteArrayFromResXHandler.cs
 ../System.Windows.Forms/System.Resources/ResXNullRef.cs
old mode 100644 (file)
new mode 100755 (executable)
index 0e1bb04..5e07845
@@ -57,7 +57,7 @@ namespace MonoTests.System.Web.UI.WebControls.Adapters
                        sw = new StringWriter();
                        w = new HtmlTextWriter(sw);
                        a.Render (w);
-                       Assert.AreEqual ("RenderBeginTag\nRenderContents\nRenderEndTag\n", sw.ToString(), "Render #1");
+                       Assert.AreEqual ("RenderBeginTag\nRenderContents\nRenderEndTag\n", sw.ToString().Replace ("\r", ""), "Render #1");
                        
                        
                        sw = new StringWriter();
old mode 100644 (file)
new mode 100755 (executable)
index fe1cb73..a40764b
@@ -91,21 +91,21 @@ namespace MonoTests.System.Web.UI.WebControls.Adapters
                public void RenderBeginTag ()
                {
                        a.RenderBeginTag (w);
-                       Assert.AreEqual ("RenderBeginTag\n", sw.ToString (), "RenderBeginTag #1");
+                       Assert.AreEqual ("RenderBeginTag\n", sw.ToString ().Replace ("\r", ""), "RenderBeginTag #1");
                }
 
                [Test]
                public void RenderContentsTag ()
                {
                        a.RenderContents (w);
-                       Assert.AreEqual ("RenderContents\n", sw.ToString (), "RenderContents #1");
+                       Assert.AreEqual ("RenderContents\n", sw.ToString ().Replace ("\r", ""), "RenderContents #1");
                }
 
                [Test]
                public void RenderEndTag ()
                {
                        a.RenderEndTag (w);
-                       Assert.AreEqual ("RenderEndTag\n", sw.ToString (), "RenderEndTag #1");
+                       Assert.AreEqual ("RenderEndTag\n", sw.ToString ().Replace ("\r", ""), "RenderEndTag #1");
                }
 
                [Test]
old mode 100644 (file)
new mode 100755 (executable)
index 12b2d0f..85f5040
@@ -63,28 +63,28 @@ namespace MonoTests.System.Web.UI.WebControls.Adapters
                public void RenderBeginTag ()
                {
                        a.RenderBeginTag (w);
-                       Assert.AreEqual ("RenderBeginTag\n", sw.ToString (), "RenderBeginTag #1");
+                       Assert.AreEqual ("RenderBeginTag\n", sw.ToString ().Replace ("\r", ""), "RenderBeginTag #1");
                }
 
                [Test]
                public void RenderContentsTag ()
                {
                        a.RenderContents (w);
-                       Assert.AreEqual ("RenderContents\n", sw.ToString (), "RenderContents #1");
+                       Assert.AreEqual ("RenderContents\n", sw.ToString ().Replace ("\r", ""), "RenderContents #1");
                }
 
                [Test]
                public void RenderEndTag ()
                {
                        a.RenderEndTag (w);
-                       Assert.AreEqual ("RenderEndTag\n", sw.ToString (), "RenderEndTag #1");
+                       Assert.AreEqual ("RenderEndTag\n", sw.ToString ().Replace ("\r", ""), "RenderEndTag #1");
                }
 
                [Test]
                public void Render ()
                {
                        a.Render (w);
-                       Assert.AreEqual ("RenderBeginTag\nRenderContents\nRenderEndTag\n", sw.ToString (), "Render #1");
+                       Assert.AreEqual ("RenderBeginTag\nRenderContents\nRenderEndTag\n", sw.ToString ().Replace ("\r", ""), "Render #1");
                }
                
                [Test]
old mode 100644 (file)
new mode 100755 (executable)
index f81a3a8..df2d711
@@ -1538,7 +1538,7 @@ namespace MonoTests.System.Web.UI.WebControls
                        Console.WriteLine ("----------------------------");
                        Console.WriteLine (renderedHtml);
                        
-                       Assert.AreEqual (origHtml, renderedHtml, "#A1");
+                       Assert.AreEqual (origHtml.Replace ("\r", ""), renderedHtml.Replace ("\r", ""), "#A1");
                }
 
                [Test]
@@ -1566,13 +1566,13 @@ namespace MonoTests.System.Web.UI.WebControls
                        string origHtml = "Header<table cellspacing=\"5\" cellpadding=\"5\">\r\n\t<tr>\r\n\t\t<td align=\"right\"><input type=\"submit\" name=\"MyWizard$StepNavigationTemplateContainerID$StepPreviousButton\" value=\"Previous\" id=\"MyWizard_StepNavigationTemplateContainerID_StepPreviousButton\" /></td><td align=\"right\"><input type=\"submit\" name=\"MyWizard$StepNavigationTemplateContainerID$StepNextButton\" value=\"Next\" id=\"MyWizard_StepNavigationTemplateContainerID_StepNextButton\" /></td>\n\t</tr>\n</table>Step";
                        string renderedHtml = HtmlDiff.GetControlFromPageHtml (result);
 
-                       Assert.AreEqual (origHtml, renderedHtml, "#A1");
+                       Assert.AreEqual (origHtml.Replace ("\r", ""), renderedHtml.Replace ("\r", ""), "#A1");
 
                        t.UserData = "RenderHeader_InSpan";
                        result = t.Run ();
                        origHtml = "Header<table cellspacing=\"5\" cellpadding=\"5\">\r\n\t<tr>\r\n\t\t<td align=\"right\"><input type=\"submit\" name=\"MyWizard$StepNavigationTemplateContainerID$StepPreviousButton\" value=\"Previous\" id=\"MyWizard_StepNavigationTemplateContainerID_StepPreviousButton\" /></td><td align=\"right\"><input type=\"submit\" name=\"MyWizard$StepNavigationTemplateContainerID$StepNextButton\" value=\"Next\" id=\"MyWizard_StepNavigationTemplateContainerID_StepNextButton\" /></td>\n\t</tr>\n</table>Step";
                        renderedHtml = HtmlDiff.GetControlFromPageHtml (result);
-                       Assert.AreEqual (origHtml, renderedHtml, "#A2");
+                       Assert.AreEqual (origHtml.Replace ("\r", ""), renderedHtml.Replace ("\r", ""), "#A2");
                }
 
                [Test]
index 90e91d144e12ba407ecd5e9c6ea1a357532dc3d0..5774443e80666a890065b83dba4e9165cb0e6b7a 100644 (file)
@@ -2,6 +2,7 @@
 ../../build/common/MonoTODOAttribute.cs
 Assembly/AssemblyInfo.cs
 Assembly/Locale.cs
+../System/System/MonoToolsLocator.cs
 System.Resources/AssemblyNamesTypeResolutionService.cs
 System.Resources/ByteArrayFromResXHandler.cs
 System.Resources/ResXNullRef.cs
index e4f980e60df8a82c6a80b770f933bdea8f0f7be2..07353efcb7a4dca16fa76fec7e5c817fc8828c4a 100644 (file)
@@ -560,35 +560,7 @@ namespace System.Windows.Forms
                        if (Assembly.GetEntryAssembly () == null)
                                throw new NotSupportedException ("The method 'Restart' is not supported by this application type.");
 
-                       string mono_path = null;
-
-                       //Get mono path
-                       PropertyInfo gac = typeof (Environment).GetProperty ("GacPath", BindingFlags.Static | BindingFlags.NonPublic);
-                       MethodInfo get_gac = null;
-                       if (gac != null)
-                               get_gac = gac.GetGetMethod (true);
-
-                       if (get_gac != null) {
-                               string gac_path = Path.GetDirectoryName ((string)get_gac.Invoke (null, null));
-                               string mono_prefix = Path.GetDirectoryName (Path.GetDirectoryName (gac_path));
-
-                               if (XplatUI.RunningOnUnix) {
-                                       mono_path = Path.Combine (mono_prefix, "bin/mono");
-                                       if (!File.Exists (mono_path))
-                                               mono_path = "mono";
-                               } else {
-                                       mono_path = Path.Combine (mono_prefix, "bin\\mono.bat");
-
-                                       if (!File.Exists (mono_path))
-                                               mono_path = Path.Combine (mono_prefix, "bin\\mono.exe");
-
-                                       if (!File.Exists (mono_path))
-                                               mono_path = Path.Combine (mono_prefix, "mono\\mono\\mini\\mono.exe");
-
-                                       if (!File.Exists (mono_path))
-                                               throw new FileNotFoundException (string.Format ("Windows mono path not found: '{0}'", mono_path));
-                               }
-                       }
+                       string mono_path = MonoToolsLocator.Mono;
 
                        //Get command line arguments
                        StringBuilder argsBuilder = new StringBuilder ();
index 23e29ad314fb504be3ae89b22b5efcab070cfbc0..70a1c6e2bfe4c0b06401403132ad3aaa02cb049e 100644 (file)
@@ -2222,7 +2222,7 @@ namespace System.Windows.Forms
 
                protected virtual bool ShouldSerializeLinkHoverColor ()
                {
-                       return grid_style.LinkHoverColor != grid_style.LinkHoverColor;
+                       return grid_style.LinkHoverColor != default_style.LinkHoverColor;
                }
 
                protected virtual bool ShouldSerializeParentRowsBackColor ()
index 505a41a0449b6d1c23dabd6e790f4add37288d88..b926e4ed1a8052054703a59723d0aefc3887c534 100644 (file)
@@ -596,7 +596,7 @@ namespace System.Windows.Forms {
 
                                if (this.title_style == TitleStyle.Normal)  {
                                        pt.Y += caption_height;
-                               } else if (this.title_style == TitleStyle.Normal)  {
+                               } else if (this.title_style == TitleStyle.Tool)  {
                                        pt.Y += tool_caption_height;
                                }
 
index 3e087ef5ac6bb9ecad20206ee909ee8c405743e3..72034979fdb48590c5b9a550f2624f15e2b2e4cb 100644 (file)
@@ -2138,7 +2138,7 @@ namespace System.Windows.Forms
                static bool AreEqual (VisualStyleElement value1, VisualStyleElement value2)
                {
                        return
-                               value1.ClassName == value1.ClassName &&
+                               value1.ClassName == value2.ClassName &&
                                value1.Part == value2.Part &&
                                value1.State == value2.State;
                }
index 32593bc4e016164b22b2f5942fc4db6aa3f09afd..de6710af0a5f3fd9b95fecbe7b12e41c486311c3 100644 (file)
@@ -729,6 +729,29 @@ namespace System.Xml.Serialization
                        return serializable;
                }
 
+               protected IXmlSerializable ReadSerializable (IXmlSerializable serializable, bool wrappedAny)
+               {
+                       string name = null;
+                       string ns = null;
+
+                       if (wrappedAny) {
+                               name = reader.LocalName;
+                               ns = reader.NamespaceURI;
+                               reader.Read ();
+                               reader.MoveToContent ();
+                       }
+                       serializable.ReadXml (reader);
+
+                       if (wrappedAny) {
+                               while (reader.NodeType == XmlNodeType.Whitespace) reader.Skip ();
+                               if (reader.NodeType == XmlNodeType.None) reader.Skip ();
+                               if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == name && reader.NamespaceURI == ns) {
+                                       reader.Read ();
+                               }
+                       }
+                       return serializable;
+               }
+
                protected string ReadString (string value)
                {
                        readCount++;
index 0805d7f61a6d71d000a41ddb1474e7200e67ec11..60bbc316699e378070fa9628ddd884b9e818f2da 100644 (file)
@@ -204,6 +204,11 @@ namespace System.Xml.Serialization
                {
                }
 
+               public XmlSerializer (Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, string location)
+                       : this (type, overrides, extraTypes, root, defaultNamespace, location, null)
+               {
+               }
+
                public XmlSerializer (Type type, XmlAttributeOverrides overrides)
                        : this (type, overrides, null, null, null)
                {
index 204b67f71c943000e00b32deb54bf72ea6c037fb..02c86fd7e62febdee00ab74f114d16e88a322304 100644 (file)
@@ -61,6 +61,11 @@ namespace System.Xml.Serialization
                        }
                }
 
+               public XmlSerializer CreateSerializer (Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, string location)
+               {
+                       return CreateSerializer (type, overrides, extraTypes, root, defaultNamespace, location, null);
+               }
+
                public XmlSerializer CreateSerializer (Type type, string defaultNamespace)
                {
                        return CreateSerializer (type, null, null, null, defaultNamespace);
index 94dcc0285baf146428ccc8cb596d6777d8f015de..e2b3432b0ae877efc26dc6ec8dd503af3ed33856 100644 (file)
@@ -32,6 +32,7 @@ using System.CodeDom.Compiler;
 using System.Collections;
 using System.IO;
 using System.Text;
+using System.Reflection;
 using System.Runtime.InteropServices;
 using System.Security;
 using System.Security.Policy;
@@ -136,6 +137,11 @@ namespace System.Xml.Xsl
                        Transform (input.CreateNavigator (), arguments, results, null);
                }
 
+               public void Transform (IXPathNavigable input, XsltArgumentList arguments, XmlWriter results, XmlResolver documentResolver)
+               {
+                       Transform (input.CreateNavigator (), arguments, results, documentResolver);
+               }
+
                public void Transform (XmlReader input, XsltArgumentList arguments, XmlWriter results, XmlResolver documentResolver)
                {
                        Transform (new XPathDocument (input, XmlSpace.Preserve).CreateNavigator (), arguments, results, documentResolver);
@@ -203,6 +209,15 @@ namespace System.Xml.Xsl
                        Load (new XPathDocument (stylesheetUri, XmlSpace.Preserve).CreateNavigator (), settings, stylesheetResolver);
                }
 
+               public void Load (MethodInfo executeMethod, byte[] queryData, Type[] earlyBoundTypes)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void Load (Type compiledStylesheet)
+               {
+                       throw new NotImplementedException ();
+               }
                #endregion
        }
 
old mode 100644 (file)
new mode 100755 (executable)
index 98942e5..bec6232
@@ -2052,8 +2052,8 @@ namespace MonoTests.System.XmlSerialization
                                serializer.Serialize (writer, obj);
                                writer.Close ();
 
-                               Assert.AreEqual (@"<?xml version=""1.0"" encoding=""utf-16""?>
-<Bug594490Class xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xml:lang=""hello world"" />",
+                               Assert.AreEqual (@"<?xml version=""1.0"" encoding=""utf-16""?>" + Environment.NewLine +
+                                                @"<Bug594490Class xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xml:lang=""hello world"" />",
                                        writer.ToString (),
                                        "Novell bug #594490 (https://bugzilla.novell.com/show_bug.cgi?id=594490) not fixed.");
                        }
index 3388150cf10fba174c9be43736c3cc1f233e82a5..6ed83d7c1e03020ffe63c8d68f4d129ec468b6bd 100644 (file)
@@ -74,10 +74,7 @@ using System.Runtime.InteropServices;
        [assembly: StringFreezing]
        [assembly: DefaultDependency (LoadHint.Always)]
 
-       [assembly: InternalsVisibleTo ("Mono.Security.Providers.NewSystemSource, PublicKey=002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df")]
-       [assembly: InternalsVisibleTo ("Mono.Security.Providers.OldTls, PublicKey=002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df")]
-       [assembly: InternalsVisibleTo ("Mono.Security.Providers.NewTls, PublicKey=002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df")]
-       [assembly: InternalsVisibleTo ("Mono.Security.Providers.DotNet, PublicKey=002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df")]
+       [assembly: InternalsVisibleTo ("btls-cert-sync, PublicKey=002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df")]
+       [assembly: InternalsVisibleTo ("Mono.Btls.Interface, PublicKey=002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df")]
        [assembly: InternalsVisibleTo ("Mono.Security, PublicKey=002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df")]
 
-       [assembly: InternalsVisibleTo ("Xamarin.BoringTls, PublicKey=002400000480000094000000060200000024000052534131000400001100000099dd12eda85767ae6f06023ee28e711c7e5a212462095c83868c29db75eddf6d8e296e03824c14fedd5f55553fed0b6173be3cc985a4b7f9fb7c83ccff8ba3938563b3d1f45a81122f12a1bcb73edcaad61a8456c7595a6da5184b4dd9d10f011b949ef1391fccfeab1ba62aa51c267ef8bd57ef1b6ba5a4c515d0badb81a78f")]
index fe01d7e4317c78eaa7a368f31ccd41952da83cb4..fdfb7c293a4ecd9d2bff6567df57c55c2a693683 100644 (file)
@@ -19,10 +19,16 @@ TEST_RESOURCES = \
        Test/System/test-uri-props-manual.txt \
        Test/System/test-uri-relative-props.txt
 
+ifndef NO_MONO_SECURITY
+MONO_SECURITY=Mono.Security
+MONO_SECURITY_REF=MonoSecurity=Mono.Security
+MONO_SECURITY_DLL=$(the_libdir_base)Mono.Security.dll
+endif
+
 ifndef MOBILE_PROFILE
-TEST_LIB_REFS = System.Drawing Mono.Security System.Data System.Xml System.Core System.Configuration
+TEST_LIB_REFS = System.Drawing $(MONO_SECURITY) System.Data System.Xml System.Core System.Configuration
 else
-TEST_LIB_REFS = Mono.Security System.Data System.Xml System.Core
+TEST_LIB_REFS = $(MONO_SECURITY) System.Data System.Xml System.Core
 endif
 
 TEST_MCS_FLAGS = -nowarn:618,672,219,67,169,612 \
@@ -67,7 +73,7 @@ endif
 #
 ifeq (secxml/, $(intermediate))
 LOCAL_MCS_FLAGS =
-LIB_REFS += bare/System.Xml MonoSecurity=Mono.Security
+LIB_REFS += bare/System.Xml $(MONO_SECURITY_REF)
 LIB_MCS_FLAGS += -d:SECURITY_DEP -d:XML_DEP $(EXTERN_ALIAS_FLAGS)
 endif
 
@@ -75,7 +81,7 @@ endif
 # Flags used to build the final version of System (when intermediate is not defined)
 #
 ifndef intermediate
-LIB_REFS += System.Xml MonoSecurity=Mono.Security
+LIB_REFS += System.Xml $(MONO_SECURITY_REF)
 LIB_MCS_FLAGS += -d:SECURITY_DEP -d:XML_DEP $(EXTERN_ALIAS_FLAGS)
 
 ifndef MOBILE_PROFILE
@@ -99,7 +105,7 @@ include ../../build/library.make
 system_library_deps := \
        $(secxml_libdir)/System.dll             \
        $(the_libdir_base)System.Xml.dll        \
-       $(the_libdir_base)Mono.Security.dll     \
+       $(MONO_SECURITY_DLL)                            \
        $(bare_libdir)/System.dll
 
 ifndef MOBILE_PROFILE
@@ -108,7 +114,7 @@ endif
 
 artifacts = $(system_library_deps)                     \
        $(bare_libdir)/System.Xml.dll                   \
-       $(the_libdir_base)Mono.Security.dll             \
+       $(MONO_SECURITY_DLL)                            \
        $(the_libdir_base)System.Configuration.dll
 
 .NOTPARALLEL: $(system_library_deps)
@@ -123,7 +129,7 @@ $(bare_libdir)/System.dll:
 endif
 
 ifneq (secxml/,$(intermediate))
-$(secxml_libdir)/System.dll: $(bare_libdir)/System.dll $(bare_libdir)/System.Xml.dll $(the_libdir_base)Mono.Security.dll $(bare_libdir)/System.dll
+$(secxml_libdir)/System.dll: $(bare_libdir)/System.dll $(bare_libdir)/System.Xml.dll $(MONO_SECURITY_DLL) $(bare_libdir)/System.dll
        $(MAKE) intermediate=secxml/ $(secxml_libdir)/System.dll
 else
 build-sec:
index 00424bd70f370d8cc10be4b2e2ddeec4ead96442..c41240fab9e280d5ace8c1e9527f4a5ab080254b 100644 (file)
@@ -48,54 +48,9 @@ namespace Mono.CSharp
        
        internal class CSharpCodeCompiler : CSharpCodeGenerator, ICodeCompiler
        {
-               static string windowsMcsPath;
-               static string windowsMonoPath;
-               static string unixMcsCommand;
-
                Mutex mcsOutMutex;
                StringCollection mcsOutput;
                
-               static CSharpCodeCompiler ()
-               {
-                       if (Path.DirectorySeparatorChar == '\\') {
-                               PropertyInfo gac = typeof (Environment).GetProperty ("GacPath", BindingFlags.Static|BindingFlags.NonPublic);
-                               MethodInfo get_gac = gac.GetGetMethod (true);
-                               string p = Path.GetDirectoryName (
-                                       (string) get_gac.Invoke (null, null));
-                               windowsMonoPath = Path.Combine (
-                                       Path.GetDirectoryName (
-                                               Path.GetDirectoryName (p)),
-                                       "bin\\mono.bat");
-                               if (!File.Exists (windowsMonoPath))
-                                       windowsMonoPath = Path.Combine (
-                                               Path.GetDirectoryName (
-                                                       Path.GetDirectoryName (p)),
-                                               "bin\\mono.exe");
-                               if (!File.Exists (windowsMonoPath))
-                                       windowsMonoPath = Path.Combine (
-                                               Path.GetDirectoryName (
-                                                       Path.GetDirectoryName (
-                                                               Path.GetDirectoryName (p))),
-                                               "mono\\mono\\mini\\mono.exe");
-                               if (!File.Exists (windowsMonoPath))
-                                       throw new FileNotFoundException ("Windows mono path not found: " + windowsMonoPath);
-
-                               windowsMcsPath = Path.Combine (p, "4.5\\mcs.exe");
-                               if (!File.Exists (windowsMcsPath))
-                                       windowsMcsPath = Path.Combine(Path.GetDirectoryName (p), "lib\\build\\mcs.exe");
-                               
-                               if (!File.Exists (windowsMcsPath))
-                                       throw new FileNotFoundException ("Windows mcs path not found: " + windowsMcsPath);
-                       } else {
-                               var mscorlibPath = new Uri (typeof (object).Assembly.CodeBase).LocalPath;
-                               var unixMcsPath = Path.GetFullPath (Path.Combine (mscorlibPath, "..", "..", "..", "..", "bin", "mcs"));
-                               if (File.Exists (unixMcsPath))
-                                       unixMcsCommand = unixMcsPath;
-                               else
-                                       unixMcsCommand = "mcs";
-                       }
-               }
-
                //
                // Constructors
                //
@@ -177,14 +132,14 @@ namespace Mono.CSharp
 
                        // FIXME: these lines had better be platform independent.
                        if (Path.DirectorySeparatorChar == '\\') {
-                               mcs.StartInfo.FileName = windowsMonoPath;
-                               mcs.StartInfo.Arguments = "\"" + windowsMcsPath + "\" " +
-                                       BuildArgs (options, fileNames, ProviderOptions);
+                               mcs.StartInfo.FileName = MonoToolsLocator.Mono;
+                               mcs.StartInfo.Arguments = "\"" + MonoToolsLocator.CSharpCompiler + "\" ";
                        } else {
-                               mcs.StartInfo.FileName=unixMcsCommand;
-                               mcs.StartInfo.Arguments=BuildArgs(options, fileNames, ProviderOptions);
+                               mcs.StartInfo.FileName = MonoToolsLocator.CSharpCompiler;
                        }
 
+                       mcs.StartInfo.Arguments += BuildArgs (options, fileNames, ProviderOptions);
+
                        mcsOutput = new StringCollection ();
                        mcsOutMutex = new Mutex ();
 /*                    
index bdb08db595adb849f3cea1b849b7b8a12fb9917a..907acebaa66f7ece769bbe4a359af68ba0a328dd 100644 (file)
@@ -48,38 +48,6 @@ namespace Microsoft.VisualBasic
 {
        internal class VBCodeCompiler : VBCodeGenerator, ICodeCompiler
        {
-               static string windowsMonoPath;
-               static string windowsvbncPath;
-               static string unixVbncCommand;
-
-               static VBCodeCompiler ()
-               {
-                       if (Path.DirectorySeparatorChar == '\\') {
-                               PropertyInfo gac = typeof (Environment).GetProperty ("GacPath", BindingFlags.Static | BindingFlags.NonPublic);
-                               MethodInfo get_gac = gac.GetGetMethod (true);
-                               string p = Path.GetDirectoryName (
-                                       (string) get_gac.Invoke (null, null));
-                               windowsMonoPath = Path.Combine (
-                                       Path.GetDirectoryName (
-                                               Path.GetDirectoryName (p)),
-                                       "bin\\mono.bat");
-                               if (!File.Exists (windowsMonoPath))
-                                       windowsMonoPath = Path.Combine (
-                                               Path.GetDirectoryName (
-                                                       Path.GetDirectoryName (p)),
-                                               "bin\\mono.exe");
-                               windowsvbncPath =
-                                       Path.Combine (p, "2.0\\vbnc.exe");
-                       } else {
-                               var mscorlibPath = new Uri (typeof (object).Assembly.CodeBase).LocalPath;
-                               var unixMcsPath = Path.GetFullPath (Path.Combine (mscorlibPath, "..", "..", "..", "..", "bin", "vbnc"));
-                               if (File.Exists (unixMcsPath))
-                                       unixVbncCommand = unixMcsPath;
-                               else
-                                       unixVbncCommand = "vbnc";
-                       }
-               }
-
                public CompilerResults CompileAssemblyFromDom (CompilerParameters options, CodeCompileUnit e)
                {
                        return CompileAssemblyFromDomBatch (options, new CodeCompileUnit[] { e });
@@ -248,10 +216,10 @@ namespace Microsoft.VisualBasic
                        string[] vbnc_output_lines;
                        // FIXME: these lines had better be platform independent.
                        if (Path.DirectorySeparatorChar == '\\') {
-                               vbnc.StartInfo.FileName = windowsMonoPath;
-                               vbnc.StartInfo.Arguments = windowsvbncPath + ' ' + BuildArgs (options, fileNames);
+                               vbnc.StartInfo.FileName = MonoToolsLocator.Mono;
+                               vbnc.StartInfo.Arguments = MonoToolsLocator.VBCompiler + ' ' + BuildArgs (options, fileNames);
                        } else {
-                               vbnc.StartInfo.FileName = "vbnc";
+                               vbnc.StartInfo.FileName = MonoToolsLocator.VBCompiler;
                                vbnc.StartInfo.Arguments = BuildArgs (options, fileNames);
                        }
                        //Console.WriteLine (vbnc.StartInfo.Arguments);
index f3091aa38bc1de43829a03ffeb0b886659949df0..9bad4ea25dd9ae03b4f64426bdfec98f006228fa 100644 (file)
@@ -34,25 +34,16 @@ using System.Security;
 
 namespace Microsoft.Win32.SafeHandles
 {
-       public sealed class SafeX509ChainHandle : SafeHandle
+       public sealed class SafeX509ChainHandle : SafeHandleZeroOrMinusOneIsInvalid
        {
-               [MonoTODO]
-               public override bool IsInvalid
-               {
-                       get
-                       {
-                               throw new NotImplementedException ();
-                       }
-               }
-
-               [MonoTODO]
-               internal SafeX509ChainHandle() : base ((IntPtr)0, false)
+               internal SafeX509ChainHandle (IntPtr handle)
+                       : base (true)
                {
                        throw new NotImplementedException ();
                }
 
                [MonoTODO]
-               protected override bool ReleaseHandle()
+               protected override bool ReleaseHandle ()
                {
                        throw new NotImplementedException ();
                }
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsBio.cs b/mcs/class/System/Mono.Btls/MonoBtlsBio.cs
new file mode 100644 (file)
index 0000000..1fbe471
--- /dev/null
@@ -0,0 +1,449 @@
+//
+// MonoBtlsBio.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+using System;
+using System.IO;
+using System.Text;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+#if MONOTOUCH
+using MonoTouch;
+#endif
+
+namespace Mono.Btls
+{
+       class MonoBtlsBio : MonoBtlsObject
+       {
+               internal MonoBtlsBio (BoringBioHandle handle)
+                       : base (handle)
+               {
+               }
+
+               new protected internal BoringBioHandle Handle {
+                       get { return (BoringBioHandle)base.Handle; }
+               }
+
+               protected internal class BoringBioHandle : MonoBtlsHandle
+               {
+                       public BoringBioHandle (IntPtr handle)
+                               : base (handle, true)
+                       {
+                       }
+
+                       protected override bool ReleaseHandle ()
+                       {
+                               if (handle != IntPtr.Zero) {
+                                       mono_btls_bio_free (handle);
+                                       handle = IntPtr.Zero;
+                               }
+                               return true;
+                       }
+
+               }
+
+               public static MonoBtlsBio CreateMonoStream (Stream stream)
+               {
+                       return MonoBtlsBioMono.CreateStream (stream, false);
+               }
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_bio_read (IntPtr bio, IntPtr data, int len);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_bio_write (IntPtr bio, IntPtr data, int len);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_bio_flush (IntPtr bio);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_bio_indent (IntPtr bio, uint indent, uint max_indent);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_bio_hexdump (IntPtr bio, IntPtr data, int len, uint indent);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_bio_print_errors (IntPtr bio);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_bio_free (IntPtr handle);
+
+               public int Read (byte[] buffer, int offset, int size)
+               {
+                       CheckThrow ();
+                       var data = Marshal.AllocHGlobal (size);
+                       if (data == IntPtr.Zero)
+                               throw new OutOfMemoryException ();
+
+                       bool release = false;
+                       try {
+                               Handle.DangerousAddRef (ref release);
+                               var ret = mono_btls_bio_read (Handle.DangerousGetHandle (), data, size);
+                               if (ret > 0)
+                                       Marshal.Copy (data, buffer,offset, ret);
+                               return ret;
+                       } finally {
+                               if (release)
+                                       Handle.DangerousRelease ();
+                               Marshal.FreeHGlobal (data);
+                       }
+               }
+
+               public int Write (byte[] buffer, int offset, int size)
+               {
+                       CheckThrow ();
+                       var data = Marshal.AllocHGlobal (size);
+                       if (data == IntPtr.Zero)
+                               throw new OutOfMemoryException ();
+
+                       bool release = false;
+                       try {
+                               Handle.DangerousAddRef (ref release);
+                               Marshal.Copy (buffer, offset, data, size);
+                               return mono_btls_bio_write (Handle.DangerousGetHandle (), data, size);
+                       } finally {
+                               if (release)
+                                       Handle.DangerousRelease ();
+                               Marshal.FreeHGlobal (data);
+                       }
+               }
+
+               public int Flush ()
+               {
+                       CheckThrow ();
+                       bool release = false;
+                       try {
+                               Handle.DangerousAddRef (ref release);
+                               return mono_btls_bio_flush (Handle.DangerousGetHandle ());
+                       } finally {
+                               if (release)
+                                       Handle.DangerousRelease ();
+                       }
+               }
+
+               public int Indent (uint indent, uint max_indent)
+               {
+                       CheckThrow ();
+                       bool release = false;
+                       try {
+                               Handle.DangerousAddRef (ref release);
+                               return mono_btls_bio_indent (Handle.DangerousGetHandle (), indent, max_indent);
+                       } finally {
+                               if (release)
+                                       Handle.DangerousRelease ();
+                       }
+               }
+
+               public int HexDump (byte[] buffer, uint indent)
+               {
+                       CheckThrow ();
+                       var data = Marshal.AllocHGlobal (buffer.Length);
+                       if (data == IntPtr.Zero)
+                               throw new OutOfMemoryException ();
+
+                       bool release = false;
+                       try {
+                               Handle.DangerousAddRef (ref release);
+                               Marshal.Copy (buffer, 0, data, buffer.Length);
+                               return mono_btls_bio_hexdump (Handle.DangerousGetHandle (), data, buffer.Length, indent);
+                       } finally {
+                               if (release)
+                                       Handle.DangerousRelease ();
+                               Marshal.FreeHGlobal (data);
+                       }
+               }
+
+               public void PrintErrors ()
+               {
+                       CheckThrow ();
+                       bool release = false;
+                       try {
+                               Handle.DangerousAddRef (ref release);
+                               mono_btls_bio_print_errors (Handle.DangerousGetHandle ());
+                       } finally {
+                               if (release)
+                                       Handle.DangerousRelease ();
+                       }
+               }
+       }
+
+       class MonoBtlsBioMemory : MonoBtlsBio
+       {
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_bio_mem_new ();
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_bio_mem_get_data (IntPtr handle, out IntPtr data);
+
+               public MonoBtlsBioMemory ()
+                       : base (new BoringBioHandle (mono_btls_bio_mem_new ()))
+               {
+               }
+
+               public byte[] GetData ()
+               {
+                       IntPtr data;
+                       bool release = false;
+                       try {
+                               Handle.DangerousAddRef (ref release);
+                               var size = mono_btls_bio_mem_get_data (Handle.DangerousGetHandle (), out data);
+                               CheckError (size > 0);
+                               var buffer = new byte[size];
+                               Marshal.Copy (data, buffer, 0, size);
+                               return buffer;
+                       } finally {
+                               if (release)
+                                       Handle.DangerousRelease ();
+                       }
+               }
+       }
+
+       interface IMonoBtlsBioMono
+       {
+               int Read (byte[] buffer, int offset, int size, out bool wantMore);
+
+               bool Write (byte[] buffer, int offset, int size);
+
+               void Flush ();
+
+               void Close ();
+       }
+
+       class MonoBtlsBioMono : MonoBtlsBio
+       {
+               GCHandle handle;
+               IntPtr instance;
+               BioReadFunc readFunc;
+               BioWriteFunc writeFunc;
+               BioControlFunc controlFunc;
+               IntPtr readFuncPtr;
+               IntPtr writeFuncPtr;
+               IntPtr controlFuncPtr;
+               IMonoBtlsBioMono backend;
+
+               public MonoBtlsBioMono (IMonoBtlsBioMono backend)
+                       : base (new BoringBioHandle (mono_btls_bio_mono_new ()))
+               {
+                       this.backend = backend;
+                       handle = GCHandle.Alloc (this);
+                       instance = GCHandle.ToIntPtr (handle);
+                       readFunc = OnRead;
+                       writeFunc = OnWrite;
+                       controlFunc = Control;
+                       readFuncPtr = Marshal.GetFunctionPointerForDelegate (readFunc);
+                       writeFuncPtr = Marshal.GetFunctionPointerForDelegate (writeFunc);
+                       controlFuncPtr = Marshal.GetFunctionPointerForDelegate (controlFunc);
+                       mono_btls_bio_mono_initialize (Handle.DangerousGetHandle (), instance, readFuncPtr, writeFuncPtr, controlFuncPtr);
+               }
+
+               public static MonoBtlsBioMono CreateStream (Stream stream, bool ownsStream)
+               {
+                       return new MonoBtlsBioMono (new StreamBackend (stream, ownsStream));
+               }
+
+               public static MonoBtlsBioMono CreateString (StringWriter writer)
+               {
+                       return new MonoBtlsBioMono (new StringBackend (writer));
+               }
+
+               enum ControlCommand
+               {
+                       Flush = 1
+               }
+
+               delegate int BioReadFunc (IntPtr bio, IntPtr data, int dataLength, out int wantMore);
+               delegate int BioWriteFunc (IntPtr bio, IntPtr data, int dataLength);
+               delegate long BioControlFunc (IntPtr bio, ControlCommand command, long arg);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_bio_mono_new ();
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_bio_mono_initialize (IntPtr handle, IntPtr instance, IntPtr readFunc, IntPtr writeFunc, IntPtr controlFunc);
+
+               long Control (ControlCommand command, long arg)
+               {
+                       switch (command) {
+                       case ControlCommand.Flush:
+                               backend.Flush ();
+                               return 1;
+
+                       default:
+                               throw new NotImplementedException ();
+                       }
+               }
+
+               int OnRead (IntPtr data, int dataLength, out int wantMore)
+               {
+                       bool wantMoreBool;
+                       var buffer = new byte[dataLength];
+                       var ret = backend.Read (buffer, 0, dataLength, out wantMoreBool);
+                       wantMore = wantMoreBool ? 1 : 0;
+                       if (ret <= 0)
+                               return ret;
+                       Marshal.Copy (buffer, 0, data, ret);
+                       return ret;
+               }
+
+#if MONOTOUCH
+               [MonoPInvokeCallback (typeof (BioReadFunc))]
+#endif
+               static int OnRead (IntPtr instance, IntPtr data, int dataLength, out int wantMore)
+               {
+                       var c = (MonoBtlsBioMono)GCHandle.FromIntPtr (instance).Target;
+                       try {
+                               return c.OnRead (data, dataLength, out wantMore);
+                       } catch (Exception ex) {
+                               c.SetException (ex);
+                               wantMore = 0;
+                               return -1;
+                       }
+               }
+
+               int OnWrite (IntPtr data, int dataLength)
+               {
+                       var buffer = new byte[dataLength];
+                       Marshal.Copy (data, buffer, 0, dataLength);
+                       var ok = backend.Write (buffer, 0, dataLength);
+                       return ok ? dataLength : -1;
+               }
+
+#if MONOTOUCH
+               [MonoPInvokeCallback (typeof (BioWriteFunc))]
+#endif
+               static int OnWrite (IntPtr instance, IntPtr data, int dataLength)
+               {
+                       var c = (MonoBtlsBioMono)GCHandle.FromIntPtr (instance).Target;
+                       try {
+                               return c.OnWrite (data, dataLength);
+                       } catch (Exception ex) {
+                               c.SetException (ex);
+                               return -1;
+                       }
+               }
+
+#if MONOTOUCH
+               [MonoPInvokeCallback (typeof (BioControlFunc))]
+#endif
+               static long Control (IntPtr instance, ControlCommand command, long arg)
+               {
+                       var c = (MonoBtlsBioMono)GCHandle.FromIntPtr (instance).Target;
+                       try {
+                               return c.Control (command, arg);
+                       } catch (Exception ex) {
+                               c.SetException (ex);
+                               return -1;
+                       }
+               }
+
+               protected override void Close ()
+               {
+                       try {
+                               if (backend != null) {
+                                       backend.Close ();
+                                       backend = null;
+                               }
+                               if (handle.IsAllocated)
+                                       handle.Free ();
+                       } finally {
+                               base.Close ();
+                       }
+               }
+
+               class StreamBackend : IMonoBtlsBioMono
+               {
+                       Stream stream;
+                       bool ownsStream;
+
+                       public Stream InnerStream {
+                               get { return stream; }
+                       }
+
+                       public StreamBackend (Stream stream, bool ownsStream)
+                       {
+                               this.stream = stream;
+                               this.ownsStream = ownsStream;
+                       }
+
+                       public int Read (byte[] buffer, int offset, int size, out bool wantMore)
+                       {
+                               wantMore = false;
+                               return stream.Read (buffer, offset, size);
+                       }
+
+                       public bool Write (byte[] buffer, int offset, int size)
+                       {
+                               stream.Write (buffer, offset, size);
+                               return true;
+                       }
+
+                       public void Flush ()
+                       {
+                               stream.Flush ();
+                       }
+
+                       public void Close ()
+                       {
+                               if (ownsStream && stream != null)
+                                       stream.Dispose ();
+                               stream = null;
+                       }
+               }
+
+               class StringBackend : IMonoBtlsBioMono
+               {
+                       StringWriter writer;
+                       Encoding encoding = new UTF8Encoding ();
+
+                       public StringBackend (StringWriter writer)
+                       {
+                               this.writer = writer;
+                       }
+
+                       public int Read (byte[] buffer, int offset, int size, out bool wantMore)
+                       {
+                               wantMore = false;
+                               return -1;
+                       }
+
+                       public bool Write (byte[] buffer, int offset, int size)
+                       {
+                               var text = encoding.GetString (buffer, offset, size);
+                               writer.Write (text);
+                               return true;
+                       }
+
+                       public void Flush ()
+                       {
+                       }
+
+                       public void Close ()
+                       {
+                       }
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsContext.cs b/mcs/class/System/Mono.Btls/MonoBtlsContext.cs
new file mode 100644 (file)
index 0000000..c06688d
--- /dev/null
@@ -0,0 +1,454 @@
+//
+// MonoBtlsContext.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+#if MONO_SECURITY_ALIAS
+extern alias MonoSecurity;
+#endif
+
+using System;
+using System.IO;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Security.Cryptography.X509Certificates;
+using System.Security.Authentication;
+using System.Runtime.InteropServices;
+
+#if MONO_SECURITY_ALIAS
+using MonoSecurity::Mono.Security.Interface;
+#else
+using Mono.Security.Interface;
+#endif
+
+using MNS = Mono.Net.Security;
+
+namespace Mono.Btls
+{
+       class MonoBtlsContext : MNS.MobileTlsContext, IMonoBtlsBioMono
+       {
+               X509Certificate remoteCertificate;
+               X509Certificate clientCertificate;
+               X509CertificateImplBtls nativeServerCertificate;
+               X509CertificateImplBtls nativeClientCertificate;
+               MonoBtlsSslCtx ctx;
+               MonoBtlsSsl ssl;
+               MonoBtlsBio bio;
+               MonoBtlsBio errbio;
+
+               MonoTlsConnectionInfo connectionInfo;
+               bool certificateValidated;
+               bool isAuthenticated;
+               bool connected;
+
+               public MonoBtlsContext (
+                       MNS.MobileAuthenticatedStream parent,
+                       bool serverMode, string targetHost,
+                       SslProtocols enabledProtocols, X509Certificate serverCertificate,
+                       X509CertificateCollection clientCertificates, bool askForClientCert)
+                       : base (parent, serverMode, targetHost, enabledProtocols,
+                               serverCertificate, clientCertificates, askForClientCert)
+               {
+                       if (serverMode)
+                               nativeServerCertificate = GetPrivateCertificate (serverCertificate);
+               }
+
+               static X509CertificateImplBtls GetPrivateCertificate (X509Certificate certificate)
+               {
+                       var impl = certificate.Impl as X509CertificateImplBtls;
+                       if (impl != null)
+                               return (X509CertificateImplBtls)impl.Clone ();
+
+                       var password = Guid.NewGuid ().ToString ();
+                       var buffer = certificate.Export (X509ContentType.Pfx, password);
+
+                       impl = new X509CertificateImplBtls ();
+                       impl.Import (buffer, password, X509KeyStorageFlags.DefaultKeySet);
+                       return impl;
+               }
+
+               new public MonoBtlsProvider Provider {
+                       get { return (MonoBtlsProvider)base.Provider; }
+               }
+
+               int VerifyCallback (MonoBtlsX509StoreCtx storeCtx)
+               {
+                       using (var chainImpl = new X509ChainImplBtls (storeCtx))
+                       using (var managedChain = new X509Chain (chainImpl)) {
+                               var leaf = managedChain.ChainElements[0].Certificate;
+                               var result = ValidateCertificate (leaf, managedChain);
+                               certificateValidated = true;
+                               return result ? 1 : 0;
+                       }
+               }
+
+               int SelectCallback ()
+               {
+                       Debug ("SELECT CALLBACK!");
+
+                       GetPeerCertificate ();
+                       if (remoteCertificate == null)
+                               throw new TlsException (AlertDescription.InternalError, "Cannot request client certificate before receiving one from the server.");
+
+                       var clientCert = SelectClientCertificate (remoteCertificate, null);
+                       Debug ("SELECT CALLBACK #1: {0}", clientCert);
+                       if (clientCert == null)
+                               return 1;
+
+                       nativeClientCertificate = GetPrivateCertificate (clientCert);
+                       Debug ("SELECT CALLBACK #2: {0}", nativeClientCertificate);
+                       clientCertificate = new X509Certificate (nativeClientCertificate);
+                       SetPrivateCertificate (nativeClientCertificate);
+                       return 1;
+               }
+
+               public override void StartHandshake ()
+               {
+                       InitializeConnection ();
+
+                       ssl = new MonoBtlsSsl (ctx);
+
+                       bio = new MonoBtlsBioMono (this);
+                       ssl.SetBio (bio);
+
+                       if (IsServer) {
+                               SetPrivateCertificate (nativeServerCertificate);
+                       } else {
+                               ssl.SetServerName (TargetHost);
+                       }
+               }
+
+               void SetPrivateCertificate (X509CertificateImplBtls privateCert)
+               {
+                       Debug ("SetPrivateCertificate: {0}", privateCert);
+                       ssl.SetCertificate (privateCert.X509);
+                       ssl.SetPrivateKey (privateCert.NativePrivateKey);
+                       var intermediate = privateCert.IntermediateCertificates;
+                       if (intermediate == null)
+                               return;
+                       for (int i = 0; i < intermediate.Count; i++) {
+                               var impl = (X509CertificateImplBtls)intermediate [i];
+                               Debug ("SetPrivateCertificate - add intermediate: {0}", impl);
+                               ssl.AddIntermediateCertificate (impl.X509);
+                       }
+               }
+
+               Exception GetException (MonoBtlsSslError status)
+               {
+                       var error = MonoBtlsError.GetError ();
+                       if (error == null)
+                               return new MonoBtlsException (status);
+
+                       var text = MonoBtlsError.GetErrorString (error);
+                       return new MonoBtlsException ("{0} {1}", status, text);
+               }
+
+               public override bool ProcessHandshake ()
+               {
+                       var done = false;
+                       while (!done) {
+                               Debug ("ProcessHandshake");
+                               MonoBtlsError.ClearError ();
+                               var status = DoProcessHandshake ();
+                               Debug ("ProcessHandshake #1: {0}", status);
+
+                               switch (status) {
+                               case MonoBtlsSslError.None:
+                                       if (connected)
+                                               done = true;
+                                       else
+                                               connected = true;
+                                       break;
+                               case MonoBtlsSslError.WantRead:
+                               case MonoBtlsSslError.WantWrite:
+                                       return false;
+                               default:
+                                       throw GetException (status);
+                               }
+                       }
+
+                       ssl.PrintErrors ();
+
+                       return true;
+               }
+
+               MonoBtlsSslError DoProcessHandshake ()
+               {
+                       if (connected)
+                               return ssl.Handshake ();
+                       else if (IsServer)
+                               return ssl.Accept ();
+                       else
+                               return ssl.Connect ();
+               }
+
+               public override void FinishHandshake ()
+               {
+                       InitializeSession ();
+
+                       isAuthenticated = true;
+               }
+
+               void SetupCertificateStore ()
+               {
+                       MonoBtlsProvider.SetupCertificateStore (ctx.CertificateStore);
+
+                       if (Settings != null && Settings.TrustAnchors != null) {
+                               var trust = IsServer ? MonoBtlsX509TrustKind.TRUST_CLIENT : MonoBtlsX509TrustKind.TRUST_SERVER;
+                               ctx.CertificateStore.AddCollection (Settings.TrustAnchors, trust);
+                       }
+               }
+
+               void InitializeConnection ()
+               {
+                       ctx = new MonoBtlsSslCtx ();
+
+#if MARTIN_DEBUG
+                       errbio = MonoBtlsBio.CreateMonoStream (Console.OpenStandardError ());
+                       ctx.SetDebugBio (errbio);
+#endif
+
+                       SetupCertificateStore ();
+
+                       if (!IsServer || AskForClientCertificate)
+                               ctx.SetVerifyCallback (VerifyCallback, false);
+                       if (!IsServer)
+                               ctx.SetSelectCallback (SelectCallback);
+
+                       var host = TargetHost;
+                       if (!string.IsNullOrEmpty (host)) {
+                               var pos = TargetHost.IndexOf (':');
+                               if (pos > 0)
+                                       host = host.Substring (0, pos);
+                       }
+
+                       ctx.SetVerifyParam (MonoBtlsProvider.GetVerifyParam (host, IsServer));
+
+                       TlsProtocolCode minProtocol, maxProtocol;
+                       GetProtocolVersions (out minProtocol, out maxProtocol);
+
+                       ctx.SetMinVersion ((int)minProtocol);
+                       ctx.SetMaxVersion ((int)maxProtocol);
+
+                       if (Settings != null && Settings.EnabledCiphers != null) {
+                               var ciphers = new short [Settings.EnabledCiphers.Length];
+                               for (int i = 0; i < ciphers.Length; i++)
+                                       ciphers [i] = (short)Settings.EnabledCiphers [i];
+                               ctx.SetCiphers (ciphers, true);
+                       }
+               }
+
+               void GetPeerCertificate ()
+               {
+                       if (remoteCertificate != null)
+                               return;
+                       using (var remoteCert = ssl.GetPeerCertificate ()) {
+                               if (remoteCert != null)
+                                       remoteCertificate = MonoBtlsProvider.CreateCertificate (remoteCert);
+                       }
+               }
+
+               void InitializeSession ()
+               {
+                       GetPeerCertificate ();
+
+                       if (IsServer && AskForClientCertificate && !certificateValidated) {
+                               if (!ValidateCertificate (null, null))
+                                       throw new TlsException (AlertDescription.CertificateUnknown);
+                       }
+
+                       var cipher = (CipherSuiteCode)ssl.GetCipher ();
+                       var protocol = (TlsProtocolCode)ssl.GetVersion ();
+                       Debug ("GET CONNECTION INFO: {0:x}:{0} {1:x}:{1} {2}", cipher, protocol, (TlsProtocolCode)protocol);
+
+                       connectionInfo = new MonoTlsConnectionInfo {
+                               CipherSuiteCode = cipher,
+                               ProtocolVersion = GetProtocol (protocol)
+                       };
+               }
+
+               static TlsProtocols GetProtocol (TlsProtocolCode protocol)
+               {
+                       switch (protocol) {
+                       case TlsProtocolCode.Tls10:
+                               return TlsProtocols.Tls10;
+                       case TlsProtocolCode.Tls11:
+                               return TlsProtocols.Tls11;
+                       case TlsProtocolCode.Tls12:
+                               return TlsProtocols.Tls12;
+                       default:
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override void Flush ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public override int Read (byte[] buffer, int offset, int size, out bool wantMore)
+               {
+                       Debug ("Read: {0} {1} {2}", buffer.Length, offset, size);
+
+                       var data = Marshal.AllocHGlobal (size);
+                       if (data == IntPtr.Zero)
+                               throw new OutOfMemoryException ();
+
+                       try {
+                               MonoBtlsError.ClearError ();
+                               var status = ssl.Read (data, ref size);
+                               Debug ("Read done: {0} {1}", status, size);
+
+                               if (status == MonoBtlsSslError.WantRead) {
+                                       wantMore = true;
+                                       return 0;
+                               } else if (status != MonoBtlsSslError.None) {
+                                       throw GetException (status);
+                               }
+
+                               if (size > 0)
+                                       Marshal.Copy (data, buffer, offset, size);
+
+                               wantMore = false;
+                               return size;
+                       } finally {
+                               Marshal.FreeHGlobal (data);
+                       }
+               }
+
+               public override int Write (byte[] buffer, int offset, int size, out bool wantMore)
+               {
+                       Debug ("Write: {0} {1} {2}", buffer.Length, offset, size);
+
+                       var data = Marshal.AllocHGlobal (size);
+                       if (data == IntPtr.Zero)
+                               throw new OutOfMemoryException ();
+
+                       try {
+                               MonoBtlsError.ClearError ();
+                               Marshal.Copy (buffer, offset, data, size);
+                               var status = ssl.Write (data, ref size);
+                               Debug ("Write done: {0} {1}", status, size);
+
+                               if (status == MonoBtlsSslError.WantWrite) {
+                                       wantMore = true;
+                                       return 0;
+                               } else if (status != MonoBtlsSslError.None) {
+                                       throw GetException (status);
+                               }
+
+                               wantMore = false;
+                               return size;
+                       } finally {
+                               Marshal.FreeHGlobal (data);
+                       }
+               }
+
+               public override void Close ()
+               {
+                       Debug ("Close!");
+                       ssl.Dispose ();
+               }
+
+               void Dispose<T> (ref T disposable)
+                       where T : class, IDisposable
+               {
+                       try {
+                               if (disposable != null)
+                                       disposable.Dispose ();
+                       } catch {
+                               ;
+                       } finally {
+                               disposable = null;
+                       }
+               }
+
+               protected override void Dispose (bool disposing)
+               {
+                       try {
+                               if (disposing) {
+                                       Dispose (ref remoteCertificate);
+                                       Dispose (ref nativeServerCertificate);
+                                       Dispose (ref nativeClientCertificate);
+                                       Dispose (ref clientCertificate);
+                                       Dispose (ref ctx);
+                                       Dispose (ref ssl);
+                                       Dispose (ref bio);
+                                       Dispose (ref errbio);
+                               }
+                       } finally {
+                               base.Dispose (disposing);
+                       }
+               }
+
+               int IMonoBtlsBioMono.Read (byte[] buffer, int offset, int size, out bool wantMore)
+               {
+                       Debug ("InternalRead: {0} {1}", offset, size);
+                       var ret = Parent.InternalRead (buffer, offset, size, out wantMore);
+                       Debug ("InternalReadDone: {0} {1}", ret, wantMore);
+                       return ret;
+               }
+
+               bool IMonoBtlsBioMono.Write (byte[] buffer, int offset, int size)
+               {
+                       Debug ("InternalWrite: {0} {1}", offset, size);
+                       var ret = Parent.InternalWrite (buffer, offset, size);
+                       Debug ("InternalWrite done: {0}", ret);
+                       return ret;
+               }
+
+               void IMonoBtlsBioMono.Flush ()
+               {
+                       ;
+               }
+
+               void IMonoBtlsBioMono.Close ()
+               {
+                       ;
+               }
+
+               public override bool HasContext {
+                       get { return ssl != null && ssl.IsValid; }
+               }
+               public override bool IsAuthenticated {
+                       get { return isAuthenticated; }
+               }
+               public override MonoTlsConnectionInfo ConnectionInfo {
+                       get { return connectionInfo; }
+               }
+               internal override bool IsRemoteCertificateAvailable {
+                       get { return remoteCertificate != null; }
+               }
+               internal override X509Certificate LocalClientCertificate {
+                       get { return clientCertificate; }
+               }
+               public override X509Certificate RemoteCertificate {
+                       get { return remoteCertificate; }
+               }
+               public override TlsProtocols NegotiatedProtocol {
+                       get { return connectionInfo.ProtocolVersion; }
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsError.cs b/mcs/class/System/Mono.Btls/MonoBtlsError.cs
new file mode 100644 (file)
index 0000000..2645a92
--- /dev/null
@@ -0,0 +1,83 @@
+//
+// MonoBtlsError.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2015 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+// #if SECURITY_DEP
+using System;
+using System.IO;
+using System.Text;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+
+#if MONOTOUCH
+using MonoTouch;
+#endif
+
+namespace Mono.Btls
+{
+       static class MonoBtlsError
+       {
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_error_peek_error ();
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_error_get_error ();
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_error_clear_error ();
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_error_get_error_string_n (int error, IntPtr buf, int len);
+
+               public static int PeekError ()
+               {
+                       return mono_btls_error_peek_error ();
+               }
+
+               public static int GetError ()
+               {
+                       return mono_btls_error_get_error ();
+               }
+
+               public static void ClearError ()
+               {
+                       mono_btls_error_clear_error ();
+               }
+
+               public static string GetErrorString (int error)
+               {
+                       var size = 1024;
+                       var buffer = Marshal.AllocHGlobal (size);
+                       if (buffer == IntPtr.Zero)
+                               throw new OutOfMemoryException ();
+                       try {
+                               mono_btls_error_get_error_string_n (error, buffer, size);
+                               return Marshal.PtrToStringAnsi (buffer);
+                       } finally {
+                               Marshal.FreeHGlobal (buffer);
+                       }
+               }
+       }
+}
+// #endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsException.cs b/mcs/class/System/Mono.Btls/MonoBtlsException.cs
new file mode 100644 (file)
index 0000000..bf6b163
--- /dev/null
@@ -0,0 +1,53 @@
+//
+// MonoBtlsException.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+using System;
+
+namespace Mono.Btls
+{
+       class MonoBtlsException : Exception
+       {
+               public MonoBtlsException ()
+               {
+               }
+
+               public MonoBtlsException (MonoBtlsSslError error)
+                       : base (error.ToString ())
+               {
+               }
+
+               public MonoBtlsException (string message)
+                       : base (message)
+               {
+               }
+
+               public MonoBtlsException (string format, params object[] args)
+                       : base (string.Format (format, args))
+               {
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsKey.cs b/mcs/class/System/Mono.Btls/MonoBtlsKey.cs
new file mode 100644 (file)
index 0000000..81280b5
--- /dev/null
@@ -0,0 +1,104 @@
+//
+// MonoBtlsKey.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+using System;
+using System.IO;
+using System.Text;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+
+namespace Mono.Btls
+{
+       class MonoBtlsKey : MonoBtlsObject
+       {
+               internal class BoringKeyHandle : MonoBtlsHandle
+               {
+                       internal BoringKeyHandle (IntPtr handle)
+                               : base (handle, true)
+                       {
+                       }
+
+                       protected override bool ReleaseHandle ()
+                       {
+                               mono_btls_key_free (handle);
+                               return true;
+                       }
+               }
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_key_free (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_key_up_ref (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_key_get_bytes (IntPtr handle, out IntPtr data, out int size, int include_private_bits);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_key_get_bits (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_key_is_rsa (IntPtr handle);
+
+               new internal BoringKeyHandle Handle {
+                       get { return (BoringKeyHandle)base.Handle; }
+               }
+
+               internal MonoBtlsKey (BoringKeyHandle handle)
+                       : base (handle)
+               {
+               }
+
+               public byte[] GetBytes (bool include_private_bits)
+               {
+                       int size;
+                       IntPtr data;
+
+                       var ret = mono_btls_key_get_bytes (Handle.DangerousGetHandle (), out data, out size, include_private_bits ? 1 : 0);
+                       CheckError (ret);
+
+                       var buffer = new byte [size];
+                       Marshal.Copy (data, buffer, 0, size);
+                       FreeDataPtr (data);
+                       return buffer;
+               }
+
+               public bool IsRsa {
+                       get {
+                               return mono_btls_key_is_rsa (Handle.DangerousGetHandle ()) != 0;
+                       }
+               }
+
+               public MonoBtlsKey Copy ()
+               {
+                       CheckThrow ();
+                       var copy = mono_btls_key_up_ref (Handle.DangerousGetHandle ());
+                       CheckError (copy != IntPtr.Zero);
+                       return new MonoBtlsKey (new BoringKeyHandle (copy));
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsObject.cs b/mcs/class/System/Mono.Btls/MonoBtlsObject.cs
new file mode 100644 (file)
index 0000000..8f30543
--- /dev/null
@@ -0,0 +1,143 @@
+//
+// MonoBtlsObject.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+using System;
+using System.Threading;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+
+namespace Mono.Btls
+{
+       abstract class MonoBtlsObject : IDisposable
+       {
+               internal MonoBtlsObject (MonoBtlsHandle handle)
+               {
+                       this.handle = handle;
+               }
+
+               protected internal abstract class MonoBtlsHandle : SafeHandle
+               {
+                       internal MonoBtlsHandle ()
+                               : base (IntPtr.Zero, true)
+                       {
+                       }
+
+                       internal MonoBtlsHandle (IntPtr handle, bool ownsHandle)
+                               : base (handle, ownsHandle)
+                       {
+                       }
+
+                       public override bool IsInvalid {
+                               get { return handle == IntPtr.Zero; }
+                       }
+               }
+
+               internal MonoBtlsHandle Handle {
+                       get {
+                               CheckThrow ();
+                               return handle;
+                       }
+               }
+
+               public bool IsValid {
+                       get { return handle != null && !handle.IsInvalid; }
+               }
+
+               MonoBtlsHandle handle;
+               Exception lastError;
+
+               protected void CheckThrow ()
+               {
+                       if (lastError != null)
+                               throw lastError;
+                       if (handle == null || handle.IsInvalid)
+                               throw new ObjectDisposedException ("MonoBtlsSsl");
+               }
+
+               protected Exception SetException (Exception ex)
+               {
+                       if (lastError == null)
+                               lastError = ex;
+                       return ex;
+               }
+
+               protected void CheckError (bool ok, [CallerMemberName] string callerName = null)
+               {
+                       if (!ok) {
+                               if (callerName != null)
+                                       throw new MonoBtlsException ("{0}.{1} failed.", GetType ().Name, callerName);
+                               else
+                                       throw new MonoBtlsException ();
+                       }
+
+               }
+
+               protected void CheckError (int ret, [CallerMemberName] string callerName = null)
+               {
+                       CheckError (ret == 1, callerName);
+               }
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_free (IntPtr data);
+
+               protected void FreeDataPtr (IntPtr data)
+               {
+                       mono_btls_free (data);
+               }
+
+               protected virtual void Close ()
+               {
+               }
+
+               protected void Dispose (bool disposing)
+               {
+                       if (disposing) {
+                               try {
+                                       if (handle != null) {
+                                               Close ();
+                                               handle.Dispose ();
+                                               handle = null;
+                                       }
+                               } finally {
+                                       var disposedExc = new ObjectDisposedException (GetType ().Name);
+                                       Interlocked.CompareExchange (ref lastError, disposedExc, null);
+                               }
+                       }
+               }
+
+               public void Dispose ()
+               {
+                       Dispose (true);
+                       GC.SuppressFinalize (this);
+               }
+
+               ~MonoBtlsObject ()
+               {
+                       Dispose (false);
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsPkcs12.cs b/mcs/class/System/Mono.Btls/MonoBtlsPkcs12.cs
new file mode 100644 (file)
index 0000000..a7d42a1
--- /dev/null
@@ -0,0 +1,145 @@
+//
+// MonoBtlsPkcs12.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2015 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+using System;
+using System.IO;
+using System.Security.Cryptography.X509Certificates;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+namespace Mono.Btls
+{
+       class MonoBtlsPkcs12 : MonoBtlsObject
+       {
+               internal class BoringPkcs12Handle : MonoBtlsHandle
+               {
+                       public BoringPkcs12Handle (IntPtr handle)
+                               : base (handle, true)
+                       {
+                       }
+
+                       protected override bool ReleaseHandle ()
+                       {
+                               mono_btls_pkcs12_free (handle);
+                               return true;
+                       }
+               }
+
+               new internal BoringPkcs12Handle Handle {
+                       get { return (BoringPkcs12Handle)base.Handle; }
+               }
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_pkcs12_free (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_pkcs12_new ();
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_pkcs12_get_count (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_pkcs12_get_cert (IntPtr Handle, int index);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_pkcs12_add_cert (IntPtr chain, IntPtr x509);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern unsafe static int mono_btls_pkcs12_import (IntPtr chain, void* data, int len, IntPtr password);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_pkcs12_has_private_key (IntPtr pkcs12);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_pkcs12_get_private_key (IntPtr pkcs12);
+
+               internal MonoBtlsPkcs12 ()
+                       : base (new BoringPkcs12Handle (mono_btls_pkcs12_new ()))
+               {
+               }
+
+               internal MonoBtlsPkcs12 (BoringPkcs12Handle handle)
+                       : base (handle)
+               {
+               }
+
+               MonoBtlsKey privateKey;
+
+               public int Count {
+                       get { return mono_btls_pkcs12_get_count (Handle.DangerousGetHandle ()); }
+               }
+
+               public MonoBtlsX509 GetCertificate (int index)
+               {
+                       if (index >= Count)
+                               throw new IndexOutOfRangeException ();
+                       var handle = mono_btls_pkcs12_get_cert (Handle.DangerousGetHandle (), index);
+                       CheckError (handle != IntPtr.Zero);
+                       return new MonoBtlsX509 (new MonoBtlsX509.BoringX509Handle (handle));
+               }
+
+               public void AddCertificate (MonoBtlsX509 x509)
+               {
+                       mono_btls_pkcs12_add_cert (
+                               Handle.DangerousGetHandle (),
+                               x509.Handle.DangerousGetHandle ());
+               }
+
+               public unsafe void Import (byte[] buffer, string password)
+               {
+                       var passptr = IntPtr.Zero;
+                       fixed (void* ptr = buffer)
+                       try {
+                               if (password != null)
+                                       passptr = Marshal.StringToHGlobalAnsi (password);
+                               var ret = mono_btls_pkcs12_import (
+                                       Handle.DangerousGetHandle (), ptr,
+                                       buffer.Length, passptr);
+                               CheckError (ret);
+                       } finally {
+                               if (passptr != IntPtr.Zero)
+                                       Marshal.FreeHGlobal (passptr);
+                       }
+               }
+
+               public bool HasPrivateKey {
+                       get { return mono_btls_pkcs12_has_private_key (Handle.DangerousGetHandle ()) != 0; }
+               }
+
+               public MonoBtlsKey GetPrivateKey ()
+               {
+                       if (!HasPrivateKey)
+                               throw new InvalidOperationException ();
+                       if (privateKey == null) {
+                               var handle = mono_btls_pkcs12_get_private_key (Handle.DangerousGetHandle ());
+                               CheckError (handle != IntPtr.Zero);
+                               privateKey = new MonoBtlsKey (new MonoBtlsKey.BoringKeyHandle (handle));
+                       }
+                       return privateKey;
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsProvider.cs b/mcs/class/System/Mono.Btls/MonoBtlsProvider.cs
new file mode 100644 (file)
index 0000000..147f53e
--- /dev/null
@@ -0,0 +1,295 @@
+//
+// MonoBtlsProvider.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+#if MONO_SECURITY_ALIAS
+extern alias MonoSecurity;
+#endif
+
+using System;
+using System.IO;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Security.Cryptography.X509Certificates;
+using System.Security.Authentication;
+
+#if MONO_SECURITY_ALIAS
+using MonoSecurity::Mono.Security.Interface;
+using MX = MonoSecurity::Mono.Security.X509;
+#else
+using Mono.Security.Interface;
+using MX = Mono.Security.X509;
+#endif
+
+using MNS = Mono.Net.Security;
+
+namespace Mono.Btls
+{
+       class MonoBtlsProvider : MonoTlsProvider
+       {
+               static readonly Guid id = new Guid ("432d18c9-9348-4b90-bfbf-9f2a10e1f15b");
+
+               public override Guid ID {
+                       get { return id; }
+               }
+               public override string Name {
+                       get { return "btls"; }
+               }
+
+               internal MonoBtlsProvider ()
+               {
+                       if (!MNS.MonoTlsProviderFactory.IsBtlsSupported ())
+                               throw new NotSupportedException ("BTLS is not supported in this runtime.");
+               }
+
+               public override bool SupportsSslStream {
+                       get { return true; }
+               }
+
+               public override bool SupportsMonoExtensions {
+                       get { return true; }
+               }
+
+               public override bool SupportsConnectionInfo {
+                       get { return true; }
+               }
+
+               public override SslProtocols SupportedProtocols {
+                       get { return SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls; }
+               }
+
+               public override IMonoSslStream CreateSslStream (
+                       Stream innerStream, bool leaveInnerStreamOpen,
+                       MonoTlsSettings settings = null)
+               {
+                       return new MonoBtlsStream (
+                               innerStream, leaveInnerStreamOpen, settings, this);
+               }
+
+               internal override bool HasNativeCertificates {
+                       get { return true; }
+               }
+
+               internal override X509Certificate2Impl GetNativeCertificate (
+                       byte[] data, string password, X509KeyStorageFlags flags)
+               {
+                       var impl = new X509CertificateImplBtls (false);
+                       impl.Import (data, password, flags);
+                       return impl;
+               }
+
+               internal override X509Certificate2Impl GetNativeCertificate (
+                       X509Certificate certificate)
+               {
+                       var impl = certificate.Impl as X509CertificateImplBtls;
+                       if (impl != null)
+                               return (X509Certificate2Impl)impl.Clone ();
+
+                       var data = certificate.GetRawCertData ();
+                       return new X509CertificateImplBtls (data, MonoBtlsX509Format.DER, false);
+               }
+
+               internal static MonoBtlsX509VerifyParam GetVerifyParam (string targetHost, bool serverMode)
+               {
+                       MonoBtlsX509VerifyParam param;
+                       if (serverMode)
+                               param = MonoBtlsX509VerifyParam.GetSslClient ();
+                       else
+                               param = MonoBtlsX509VerifyParam.GetSslServer ();
+
+                       if (string.IsNullOrEmpty (targetHost))
+                               return param;
+
+                       try {
+                               var copy = param.Copy ();
+                               copy.SetHost (targetHost);
+                               return copy;
+                       } finally {
+                               param.Dispose ();
+                       }
+               }
+
+               internal override bool ValidateCertificate (
+                       ICertificateValidator2 validator, string targetHost, bool serverMode,
+                       X509CertificateCollection certificates, bool wantsChain, ref X509Chain chain,
+                       ref MonoSslPolicyErrors errors, ref int status11)
+               {
+                       if (chain != null) {
+                               var chainImpl = (X509ChainImplBtls)chain.Impl;
+                               var success = chainImpl.StoreCtx.VerifyResult == 1;
+                               CheckValidationResult (
+                                       validator, targetHost, serverMode, certificates,
+                                       wantsChain, chain, chainImpl.StoreCtx,
+                                       success, ref errors, ref status11);
+                               return success;
+                       }
+
+                       using (var store = new MonoBtlsX509Store ())
+                       using (var nativeChain = MonoBtlsProvider.GetNativeChain (certificates))
+                       using (var param = GetVerifyParam (targetHost, serverMode))
+                       using (var storeCtx = new MonoBtlsX509StoreCtx ()) {
+                               SetupCertificateStore (store);
+
+                               storeCtx.Initialize (store, nativeChain);
+
+                               storeCtx.SetVerifyParam (param);
+
+                               var ret = storeCtx.Verify ();
+
+                               var success = ret == 1;
+
+                               if (wantsChain && chain == null) {
+                                       chain = GetManagedChain (nativeChain);
+                               }
+
+                               CheckValidationResult (
+                                       validator, targetHost, serverMode, certificates,
+                                       wantsChain, null, storeCtx,
+                                       success, ref errors, ref status11);
+                               return success;
+                       }
+               }
+
+               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,
+                       X509Chain chain, MonoBtlsX509StoreCtx storeCtx,
+                       bool success, ref MonoSslPolicyErrors errors, ref int status11)
+               {
+                       if (!success) {
+                               errors = MonoSslPolicyErrors.RemoteCertificateChainErrors;
+                               status11 = unchecked((int)0x800B010B);
+                       }
+               }
+
+               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
+                       return "/system/etc/security/cacerts";
+#else
+                       var appData = Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData);
+                       var path = Path.Combine (appData, ".mono", "certs", "NewTrust");
+                       return path;
+#endif
+               }
+
+               public static X509Certificate CreateCertificate (byte[] data, MonoBtlsX509Format format, bool disallowFallback = false)
+               {
+                       using (var impl = new X509CertificateImplBtls (data, format, disallowFallback)) {
+                               return new X509Certificate (impl);
+                       }
+               }
+
+               public static X509Certificate2 CreateCertificate2 (byte[] data, MonoBtlsX509Format format, bool disallowFallback = false)
+               {
+                       using (var impl = new X509CertificateImplBtls (data, format, disallowFallback)) {
+                               return new X509Certificate2 (impl);
+                       }
+               }
+
+               public static X509Certificate2 CreateCertificate2 (byte[] data, string password, bool disallowFallback = false)
+               {
+                       using (var impl = new X509CertificateImplBtls (disallowFallback)) {
+                               impl.Import (data, password, X509KeyStorageFlags.DefaultKeySet);
+                               return new X509Certificate2 (impl);
+                       }
+               }
+
+               public static X509Certificate CreateCertificate (MonoBtlsX509 x509)
+               {
+                       using (var impl = new X509CertificateImplBtls (x509, true))
+                               return new X509Certificate (impl);
+               }
+
+               public static X509Chain CreateChain ()
+               {
+                       using (var impl = new X509ChainImplBtls ())
+                               return new X509Chain (impl);
+               }
+
+               public static X509Chain GetManagedChain (MonoBtlsX509Chain chain)
+               {
+                       var impl = new X509ChainImplBtls (chain);
+                       return new X509Chain (impl);
+               }
+
+               public static MonoBtlsX509 GetBtlsCertificate (X509Certificate certificate)
+               {
+                       var impl = certificate.Impl as X509CertificateImplBtls;
+                       if (impl != null)
+                               return impl.X509.Copy ();
+
+                       return MonoBtlsX509.LoadFromData (certificate.GetRawCertData (), MonoBtlsX509Format.DER);
+               }
+
+               public static MonoBtlsX509Chain GetNativeChain (X509CertificateCollection certificates)
+               {
+                       var chain = new MonoBtlsX509Chain ();
+                       try {
+                               foreach (var cert in certificates) {
+                                       using (var x509 = GetBtlsCertificate (cert))
+                                               chain.AddCertificate (x509);
+                               }
+                               return chain;
+                       } catch {
+                               chain.Dispose ();
+                               throw;
+                       }
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsSsl.cs b/mcs/class/System/Mono.Btls/MonoBtlsSsl.cs
new file mode 100644 (file)
index 0000000..b24ed07
--- /dev/null
@@ -0,0 +1,418 @@
+//
+// MonoBtlsSsl.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2015 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+using System;
+using System.IO;
+using System.Text;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+
+#if MONOTOUCH
+using MonoTouch;
+#endif
+
+namespace Mono.Btls
+{
+       delegate int MonoBtlsVerifyCallback (MonoBtlsX509StoreCtx ctx);
+       delegate int MonoBtlsSelectCallback ();
+
+       class MonoBtlsSsl : MonoBtlsObject
+       {
+               internal class BoringSslHandle : MonoBtlsHandle
+               {
+                       public BoringSslHandle (IntPtr handle)
+                               : base (handle, true)
+                       {
+                       }
+
+                       protected override bool ReleaseHandle ()
+                       {
+                               mono_btls_ssl_destroy (handle);
+                               return true;
+                       }
+               }
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_ssl_destroy (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_ssl_new (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_ssl_use_certificate (IntPtr handle, IntPtr x509);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_ssl_use_private_key (IntPtr handle, IntPtr key);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_ssl_add_chain_certificate (IntPtr handle, IntPtr x509);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_ssl_accept (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_ssl_connect (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_ssl_handshake (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_ssl_close (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_ssl_set_bio (IntPtr handle, IntPtr bio);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_ssl_read (IntPtr handle, IntPtr data, int len);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_ssl_write (IntPtr handle, IntPtr data, int len);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_ssl_get_error (IntPtr handle, int ret_code);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_ssl_get_version (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_ssl_set_min_version (IntPtr handle, int version);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_ssl_set_max_version (IntPtr handle, int version);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_ssl_get_cipher (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_ssl_get_ciphers (IntPtr handle, out IntPtr data);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_ssl_get_peer_certificate (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_ssl_set_cipher_list (IntPtr handle, IntPtr str);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_ssl_print_errors_cb (IntPtr func, IntPtr ctx);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_ssl_set_verify_param (IntPtr handle, IntPtr param);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_ssl_set_server_name (IntPtr handle, IntPtr name);
+
+               static BoringSslHandle Create_internal (MonoBtlsSslCtx ctx)
+               {
+                       var handle = mono_btls_ssl_new (ctx.Handle.DangerousGetHandle ());
+                       if (handle == IntPtr.Zero)
+                               throw new MonoBtlsException ();
+                       return new BoringSslHandle (handle);
+               }
+
+               PrintErrorsCallbackFunc printErrorsFunc;
+               IntPtr printErrorsFuncPtr;
+
+               public MonoBtlsSsl (MonoBtlsSslCtx ctx)
+                       : base (Create_internal (ctx))
+               {
+                       printErrorsFunc = PrintErrorsCallback;
+                       printErrorsFuncPtr = Marshal.GetFunctionPointerForDelegate (printErrorsFunc);
+               }
+
+               new internal BoringSslHandle Handle {
+                       get { return (BoringSslHandle)base.Handle; }
+               }
+
+               public void SetBio (MonoBtlsBio bio)
+               {
+                       CheckThrow ();
+                       mono_btls_ssl_set_bio (
+                               Handle.DangerousGetHandle (),
+                               bio.Handle.DangerousGetHandle ());
+               }
+
+               Exception ThrowError ([CallerMemberName] string callerName = null)
+               {
+                       string errors;
+                       try {
+                               if (callerName == null)
+                                       callerName = GetType ().Name;
+                               errors = GetErrors ();
+                       } catch {
+                               errors = null;
+                       }
+
+                       if (errors != null) {
+                               Console.Error.WriteLine ("ERROR: {0} failed: {1}", callerName, errors);
+                               throw new MonoBtlsException ("{0} failed: {1}.", callerName, errors);
+                       } else {
+                               Console.Error.WriteLine ("ERROR: {0} failed.", callerName);
+                               throw new MonoBtlsException ("{0} failed.", callerName);
+                       }
+               }
+
+               MonoBtlsSslError GetError (int ret_code)
+               {
+                       CheckThrow ();
+                       var error = mono_btls_ssl_get_error (
+                               Handle.DangerousGetHandle (), ret_code);
+                       return (MonoBtlsSslError)error;
+               }
+
+               public void SetCertificate (MonoBtlsX509 x509)
+               {
+                       CheckThrow ();
+
+                       var ret = mono_btls_ssl_use_certificate (
+                               Handle.DangerousGetHandle (),
+                               x509.Handle.DangerousGetHandle ());
+                       if (ret <= 0)
+                               throw ThrowError ();
+               }
+
+               public void SetPrivateKey (MonoBtlsKey key)
+               {
+                       CheckThrow ();
+
+                       var ret = mono_btls_ssl_use_private_key (
+                               Handle.DangerousGetHandle (),
+                               key.Handle.DangerousGetHandle ());
+                       if (ret <= 0)
+                               throw ThrowError ();
+               }
+
+               public void AddIntermediateCertificate (MonoBtlsX509 x509)
+               {
+                       CheckThrow ();
+
+                       var ret = mono_btls_ssl_add_chain_certificate (
+                               Handle.DangerousGetHandle (),
+                               x509.Handle.DangerousGetHandle ());
+                       if (ret <= 0)
+                               throw ThrowError ();
+               }
+
+               public MonoBtlsSslError Accept ()
+               {
+                       CheckThrow ();
+
+                       var ret = mono_btls_ssl_accept (Handle.DangerousGetHandle ());
+
+                       var error = GetError (ret);
+                       return error;
+               }
+
+               public MonoBtlsSslError Connect ()
+               {
+                       CheckThrow ();
+
+                       var ret = mono_btls_ssl_connect (Handle.DangerousGetHandle ());
+
+                       var error = GetError (ret);
+                       return error;
+               }
+
+               public MonoBtlsSslError Handshake ()
+               {
+                       CheckThrow ();
+
+                       var ret = mono_btls_ssl_handshake (Handle.DangerousGetHandle ());
+
+                       var error = GetError (ret);
+                       return error;
+               }
+
+               delegate int PrintErrorsCallbackFunc (IntPtr str, IntPtr len, IntPtr ctx);
+
+#if MONOTOUCH
+               [MonoPInvokeCallback (typeof (PrintErrorsCallbackFunc))]
+#endif
+               static int PrintErrorsCallback (IntPtr str, IntPtr len, IntPtr ctx)
+               {
+                       var sb = (StringBuilder)GCHandle.FromIntPtr (ctx).Target;
+                       try {
+                               var text = Marshal.PtrToStringAnsi (str, (int)len);
+                               sb.Append (text);
+                               return 1;
+                       } catch {
+                               return 0;
+                       }
+               }
+
+               public string GetErrors ()
+               {
+                       var text = new StringBuilder ();
+                       var handle = GCHandle.Alloc (text);
+
+                       try {
+                               mono_btls_ssl_print_errors_cb (printErrorsFuncPtr, GCHandle.ToIntPtr (handle));
+                               return text.ToString ();
+                       } finally {
+                               if (handle.IsAllocated)
+                                       handle.Free ();
+                       }
+               }
+
+               public void PrintErrors ()
+               {
+                       var errors = GetErrors ();
+                       if (string.IsNullOrEmpty (errors))
+                               return;
+                       Console.Error.WriteLine (errors);
+               }
+
+               public MonoBtlsSslError Read (IntPtr data, ref int dataSize)
+               {
+                       CheckThrow ();
+                       var ret = mono_btls_ssl_read (
+                               Handle.DangerousGetHandle (), data, dataSize);
+
+                       if (ret >= 0) {
+                               dataSize = ret;
+                               return MonoBtlsSslError.None;
+                       }
+
+                       var error = mono_btls_ssl_get_error (
+                               Handle.DangerousGetHandle (), ret);
+                       dataSize = 0;
+                       return (MonoBtlsSslError)error;
+               }
+
+               public MonoBtlsSslError Write (IntPtr data, ref int dataSize)
+               {
+                       CheckThrow ();
+                       var ret = mono_btls_ssl_write (
+                               Handle.DangerousGetHandle (), data, dataSize);
+
+                       if (ret >= 0) {
+                               dataSize = ret;
+                               return MonoBtlsSslError.None;
+                       }
+
+                       var error = mono_btls_ssl_get_error (
+                               Handle.DangerousGetHandle (), ret);
+                       dataSize = 0;
+                       return (MonoBtlsSslError)error;
+               }
+
+               public int GetVersion ()
+               {
+                       CheckThrow ();
+                       return mono_btls_ssl_get_version (Handle.DangerousGetHandle ());
+               }
+
+               public void SetMinVersion (int version)
+               {
+                       CheckThrow ();
+                       mono_btls_ssl_set_min_version (Handle.DangerousGetHandle (), version);
+               }
+
+               public void SetMaxVersion (int version)
+               {
+                       CheckThrow ();
+                       mono_btls_ssl_set_max_version (Handle.DangerousGetHandle (), version);
+               }
+
+               public int GetCipher ()
+               {
+                       CheckThrow ();
+                       var cipher = mono_btls_ssl_get_cipher (Handle.DangerousGetHandle ());
+                       CheckError (cipher > 0);
+                       return cipher;
+               }
+
+               public short[] GetCiphers ()
+               {
+                       CheckThrow ();
+                       IntPtr data;
+                       var count = mono_btls_ssl_get_ciphers (
+                               Handle.DangerousGetHandle (), out data);
+                       CheckError (count > 0);
+                       try {
+                               short[] ciphers = new short[count];
+                               Marshal.Copy (data, ciphers, 0, count);
+                               return ciphers;
+                       } finally {
+                               FreeDataPtr (data);
+                       }
+               }
+
+               public void SetCipherList (string str)
+               {
+                       CheckThrow ();
+                       IntPtr strPtr = IntPtr.Zero;
+                       try {
+                               strPtr = Marshal.StringToHGlobalAnsi (str);
+                               var ret = mono_btls_ssl_set_cipher_list (
+                                       Handle.DangerousGetHandle (), strPtr);
+                               CheckError (ret);
+                       } finally {
+                               if (strPtr != IntPtr.Zero)
+                                       Marshal.FreeHGlobal (strPtr);
+                       }
+               }
+
+               public MonoBtlsX509 GetPeerCertificate ()
+               {
+                       CheckThrow ();
+                       var x509 = mono_btls_ssl_get_peer_certificate (
+                               Handle.DangerousGetHandle ());
+                       if (x509 == IntPtr.Zero)
+                               return null;
+                       return new MonoBtlsX509 (new MonoBtlsX509.BoringX509Handle (x509));
+               }
+
+               public void SetVerifyParam (MonoBtlsX509VerifyParam param)
+               {
+                       CheckThrow ();
+                       var ret = mono_btls_ssl_set_verify_param (
+                               Handle.DangerousGetHandle (),
+                               param.Handle.DangerousGetHandle ());
+                       CheckError (ret);
+               }
+
+               public void SetServerName (string name)
+               {
+                       CheckThrow ();
+                       IntPtr namePtr = IntPtr.Zero;
+                       try {
+                               namePtr = Marshal.StringToHGlobalAnsi (name);
+                               var ret = mono_btls_ssl_set_server_name (
+                                       Handle.DangerousGetHandle (), namePtr);
+                               CheckError (ret);
+                       } finally {
+                               if (namePtr != IntPtr.Zero)
+                                       Marshal.FreeHGlobal (namePtr);
+                       }
+               }
+
+               protected override void Close ()
+               {
+                       mono_btls_ssl_close (Handle.DangerousGetHandle ());
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsSslCtx.cs b/mcs/class/System/Mono.Btls/MonoBtlsSslCtx.cs
new file mode 100644 (file)
index 0000000..517b158
--- /dev/null
@@ -0,0 +1,260 @@
+//
+// MonoBtlsSslCtx.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+using System;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+#if MONOTOUCH
+using MonoTouch;
+#endif
+
+namespace Mono.Btls
+{
+       class MonoBtlsSslCtx : MonoBtlsObject
+       {
+               internal class BoringSslCtxHandle : MonoBtlsHandle
+               {
+                       public BoringSslCtxHandle (IntPtr handle)
+                               : base (handle, true)
+                       {
+                       }
+
+                       protected override bool ReleaseHandle ()
+                       {
+                               mono_btls_ssl_ctx_free (handle);
+                               return true;
+                       }
+               }
+
+               new internal BoringSslCtxHandle Handle {
+                       get { return (BoringSslCtxHandle)base.Handle; }
+               }
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_ssl_ctx_new ();
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_ssl_ctx_free (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_ssl_ctx_up_ref (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_ssl_ctx_initialize (IntPtr handle, IntPtr instance);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_ssl_ctx_set_debug_bio (IntPtr handle, IntPtr bio);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_ssl_ctx_set_cert_verify_callback (IntPtr handle, IntPtr func, int cert_required);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_ssl_ctx_set_cert_select_callback (IntPtr handle, IntPtr func);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_ssl_ctx_set_min_version (IntPtr handle, int version);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_ssl_ctx_set_max_version (IntPtr handle, int version);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_ssl_ctx_is_cipher_supported (IntPtr handle, short value);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_ssl_ctx_set_ciphers (IntPtr handle, int count, IntPtr data, int allow_unsupported);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_ssl_ctx_set_verify_param (IntPtr handle, IntPtr param);
+
+               delegate int NativeVerifyFunc (IntPtr instance, int preverify_ok, IntPtr ctx);
+               delegate int NativeSelectFunc (IntPtr instance);
+
+               NativeVerifyFunc verifyFunc;
+               NativeSelectFunc selectFunc;
+               IntPtr verifyFuncPtr;
+               IntPtr selectFuncPtr;
+               MonoBtlsVerifyCallback verifyCallback;
+               MonoBtlsSelectCallback selectCallback;
+               MonoBtlsX509Store store;
+               GCHandle instance;
+               IntPtr instancePtr;
+
+               public MonoBtlsSslCtx ()
+                       : this (new BoringSslCtxHandle (mono_btls_ssl_ctx_new ()))
+               {
+               }
+
+               internal MonoBtlsSslCtx (BoringSslCtxHandle handle)
+                       : base (handle)
+               {
+                       instance = GCHandle.Alloc (this);
+                       instancePtr = GCHandle.ToIntPtr (instance);
+                       mono_btls_ssl_ctx_initialize (
+                               handle.DangerousGetHandle (), instancePtr);
+
+                       verifyFunc = NativeVerifyCallback;
+                       selectFunc = NativeSelectCallback;
+                       verifyFuncPtr = Marshal.GetFunctionPointerForDelegate (verifyFunc);
+                       selectFuncPtr = Marshal.GetFunctionPointerForDelegate (selectFunc);
+
+                       store = new MonoBtlsX509Store (Handle);
+               }
+
+               internal MonoBtlsSslCtx Copy ()
+               {
+                       var copy = mono_btls_ssl_ctx_up_ref (Handle.DangerousGetHandle ());
+                       return new MonoBtlsSslCtx (new BoringSslCtxHandle (copy));
+               }
+
+               public MonoBtlsX509Store CertificateStore {
+                       get { return store; }
+               }
+
+               int VerifyCallback (bool preverify_ok, MonoBtlsX509StoreCtx ctx)
+               {
+                       if (verifyCallback != null)
+                               return verifyCallback (ctx);
+                       return 0;
+               }
+
+#if MONOTOUCH
+               [MonoPInvokeCallback (typeof (NativeVerifyFunc))]
+#endif
+               static int NativeVerifyCallback (IntPtr instance, int preverify_ok, IntPtr store_ctx)
+               {
+                       var c = (MonoBtlsSslCtx)GCHandle.FromIntPtr (instance).Target;
+                       using (var ctx = new MonoBtlsX509StoreCtx (preverify_ok, store_ctx)) {
+                               try {
+                                       return c.VerifyCallback (preverify_ok != 0, ctx);
+                               } catch (Exception ex) {
+                                       c.SetException (ex);
+                               }
+                       }
+                       return 0;
+               }
+
+               int SelectCallback ()
+               {
+                       if (selectCallback != null)
+                               return selectCallback ();
+                       return 1;
+               }
+
+#if MONOTOUCH
+               [MonoPInvokeCallback (typeof (NativeSelectFunc))]
+#endif
+               static int NativeSelectCallback (IntPtr instance)
+               {
+                       var c = (MonoBtlsSslCtx)GCHandle.FromIntPtr (instance).Target;
+                       try {
+                               return c.SelectCallback ();
+                       } catch (Exception ex) {
+                               c.SetException (ex);
+                               return 0;
+                       }
+               }
+
+               public void SetDebugBio (MonoBtlsBio bio)
+               {
+                       CheckThrow ();
+                       mono_btls_ssl_ctx_set_debug_bio (Handle.DangerousGetHandle (), bio.Handle.DangerousGetHandle ());
+               }
+
+               public void SetVerifyCallback (MonoBtlsVerifyCallback callback, bool client_cert_required)
+               {
+                       CheckThrow ();
+
+                       verifyCallback = callback;
+                       mono_btls_ssl_ctx_set_cert_verify_callback (
+                               Handle.DangerousGetHandle (), verifyFuncPtr,
+                               client_cert_required ? 1 : 0);
+               }
+
+               public void SetSelectCallback (MonoBtlsSelectCallback callback)
+               {
+                       CheckThrow ();
+
+                       selectCallback = callback;
+                       mono_btls_ssl_ctx_set_cert_select_callback (
+                               Handle.DangerousGetHandle (), selectFuncPtr);
+               }
+
+               public void SetMinVersion (int version)
+               {
+                       CheckThrow ();
+                       mono_btls_ssl_ctx_set_min_version (Handle.DangerousGetHandle (), version);
+               }
+
+               public void SetMaxVersion (int version)
+               {
+                       CheckThrow ();
+                       mono_btls_ssl_ctx_set_max_version (Handle.DangerousGetHandle (), version);
+               }
+
+               public bool IsCipherSupported (short value)
+               {
+                       CheckThrow ();
+                       return mono_btls_ssl_ctx_is_cipher_supported (Handle.DangerousGetHandle (), value) != 0;
+               }
+
+               public void SetCiphers (short[] ciphers, bool allow_unsupported)
+               {
+                       CheckThrow ();
+                       var data = Marshal.AllocHGlobal (ciphers.Length * 2);
+                       try {
+                               Marshal.Copy (ciphers, 0, data, ciphers.Length);
+                               var ret = mono_btls_ssl_ctx_set_ciphers (
+                                       Handle.DangerousGetHandle (),
+                                       ciphers.Length, data, allow_unsupported ? 1 : 0);
+                               CheckError (ret > 0);
+                       } finally {
+                               Marshal.FreeHGlobal (data);
+                       }
+               }
+
+               public void SetVerifyParam (MonoBtlsX509VerifyParam param)
+               {
+                       CheckThrow ();
+                       var ret = mono_btls_ssl_ctx_set_verify_param (
+                               Handle.DangerousGetHandle (),
+                               param.Handle.DangerousGetHandle ());
+                       CheckError (ret);
+               }
+
+               protected override void Close ()
+               {
+                       if (store != null) {
+                               store.Dispose ();
+                               store = null;
+                       }
+                       if (instance.IsAllocated)
+                               instance.Free ();
+                       base.Close ();
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsSslError.cs b/mcs/class/System/Mono.Btls/MonoBtlsSslError.cs
new file mode 100644 (file)
index 0000000..38f6f4f
--- /dev/null
@@ -0,0 +1,47 @@
+//
+// MonoBtlsSslError.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2015 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+namespace Mono.Btls
+{
+       // keep in sync with boringssl/include/ssl.h
+       enum MonoBtlsSslError
+       {
+               None = 0,
+               Ssl = 1,
+               WantRead = 2,
+               WantWrite = 3,
+               WantX509Lookup = 4,
+               Syscall = 5,
+               ZeroReturn = 6,
+               WantConnect = 7,
+               WantAccept = 8,
+               WantChannelIdLookup = 9,
+               PendingSession = 11,
+               PendingCertificate = 12,
+               WantPrivateKeyOperation = 13
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsStream.cs b/mcs/class/System/Mono.Btls/MonoBtlsStream.cs
new file mode 100644 (file)
index 0000000..d2f32e9
--- /dev/null
@@ -0,0 +1,65 @@
+//
+// MonoBtlsStream.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+#if MONO_SECURITY_ALIAS
+extern alias MonoSecurity;
+#endif
+
+using System;
+using System.IO;
+using System.Security.Authentication;
+using System.Security.Cryptography.X509Certificates;
+
+#if MONO_SECURITY_ALIAS
+using MonoSecurity::Mono.Security.Interface;
+#else
+using Mono.Security.Interface;
+#endif
+
+using MNS = Mono.Net.Security;
+
+namespace Mono.Btls
+{
+       class MonoBtlsStream : MNS.MobileAuthenticatedStream
+       {
+               public MonoBtlsStream (Stream innerStream, bool leaveInnerStreamOpen, MonoTlsSettings settings, MonoTlsProvider provider)
+                       : base (innerStream, leaveInnerStreamOpen, settings, provider)
+               {
+               }
+
+               protected override MNS.MobileTlsContext CreateContext (
+                       MNS.MobileAuthenticatedStream parent, bool serverMode, string targetHost,
+                       SslProtocols enabledProtocols, X509Certificate serverCertificate,
+                       X509CertificateCollection clientCertificates, bool askForClientCert)
+               {
+                       return new MonoBtlsContext (
+                               parent, serverMode, targetHost,
+                               enabledProtocols, serverCertificate,
+                               clientCertificates, askForClientCert);
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsUtils.cs b/mcs/class/System/Mono.Btls/MonoBtlsUtils.cs
new file mode 100644 (file)
index 0000000..63dba5d
--- /dev/null
@@ -0,0 +1,187 @@
+//
+// MonoBtlsUtils.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+using System;
+using System.Text;
+using System.Security.Cryptography.X509Certificates;
+
+namespace Mono.Btls
+{
+       static class MonoBtlsUtils
+       {
+               static byte[] emailOid = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01 };
+
+               public static bool Compare (byte[] a, byte[] b)
+               {
+                       if (a.Length != b.Length)
+                               return false;
+                       for (int i = 0; i < a.Length; i++) {
+                               if (a[i] != b[i])
+                                       return false;
+                       }
+                       return true;
+               }
+
+               static bool AppendEntry (StringBuilder sb, MonoBtlsX509Name name, int index, string separator, bool quotes)
+               {
+                       var type = name.GetEntryType (index);
+                       if (type < 0)
+                               return false;
+                       else if (type == 0) {
+                               var oidValue = name.GetEntryOidData (index);
+                               if (Compare (oidValue, emailOid))
+                                       type = MonoBtlsX509NameEntryType.Email;
+                       }
+                       int tag;
+                       var text = name.GetEntryValue (index, out tag);
+                       if (text == null)
+                               return false;
+                       var oid = name.GetEntryOid (index);
+                       if (oid == null)
+                               return false;
+
+                       if (sb.Length > 0)
+                               sb.Append (separator);
+
+                       switch (type) {
+                       case MonoBtlsX509NameEntryType.CountryName:
+                               sb.Append ("C=");
+                               break;
+                       case MonoBtlsX509NameEntryType.OrganizationName:
+                               sb.Append ("O=");
+                               break;
+                       case MonoBtlsX509NameEntryType.OrganizationalUnitName:
+                               sb.Append ("OU=");
+                               break;
+                       case MonoBtlsX509NameEntryType.CommonName:
+                               sb.Append ("CN=");
+                               break;
+                       case MonoBtlsX509NameEntryType.LocalityName:
+                               sb.Append ("L=");
+                               break;
+                       case MonoBtlsX509NameEntryType.StateOrProvinceName:
+                               sb.Append ("S=");       // NOTE: RFC2253 uses ST=
+                               break;
+                       case MonoBtlsX509NameEntryType.StreetAddress:
+                               sb.Append ("STREET=");
+                               break;
+                       case MonoBtlsX509NameEntryType.DomainComponent:
+                               sb.Append ("DC=");
+                               break;
+                       case MonoBtlsX509NameEntryType.UserId:
+                               sb.Append ("UID=");
+                               break;
+                       case MonoBtlsX509NameEntryType.Email:
+                               sb.Append ("E=");       // NOTE: Not part of RFC2253
+                               break;
+                       case MonoBtlsX509NameEntryType.DnQualifier:
+                               sb.Append ("dnQualifier=");
+                               break;
+                       case MonoBtlsX509NameEntryType.Title:
+                               sb.Append ("T=");
+                               break;
+                       case MonoBtlsX509NameEntryType.Surname:
+                               sb.Append ("SN=");
+                               break;
+                       case MonoBtlsX509NameEntryType.GivenName:
+                               sb.Append ("G=");
+                               break;
+                       case MonoBtlsX509NameEntryType.Initial:
+                               sb.Append ("I=");
+                               break;
+                       default:
+                               // unknown OID
+                               sb.Append ("OID.");     // NOTE: Not present as RFC2253
+                               sb.Append (oid);
+                               sb.Append ("=");
+                               break;
+                       }
+
+                       // 16bits or 8bits string ? TODO not complete (+special chars!)
+                       char[] specials = { ',', '+', '"', '\\', '<', '>', ';' };
+                       if (quotes && tag != 0x1E) {
+                               if ((text.IndexOfAny (specials, 0, text.Length) > 0) ||
+                                   text.StartsWith (" ") || (text.EndsWith (" ")))
+                                       text = "\"" + text + "\"";
+                       }
+
+                       sb.Append (text);
+                       return true;
+               }
+
+               const X500DistinguishedNameFlags AllFlags = X500DistinguishedNameFlags.Reversed |
+                       X500DistinguishedNameFlags.UseSemicolons | X500DistinguishedNameFlags.DoNotUsePlusSign |
+                       X500DistinguishedNameFlags.DoNotUseQuotes | X500DistinguishedNameFlags.UseCommas |
+                       X500DistinguishedNameFlags.UseNewLines | X500DistinguishedNameFlags.UseUTF8Encoding |
+                       X500DistinguishedNameFlags.UseT61Encoding | X500DistinguishedNameFlags.ForceUTF8Encoding;
+
+               static string GetSeparator (X500DistinguishedNameFlags flag)
+               {
+                       if ((flag & X500DistinguishedNameFlags.UseSemicolons) != 0)
+                               return "; ";
+                       if ((flag & X500DistinguishedNameFlags.UseCommas) != 0)
+                               return ", ";
+                       if ((flag & X500DistinguishedNameFlags.UseNewLines) != 0)
+                               return Environment.NewLine;
+                       return ", "; //default
+               }
+
+               public static string FormatName (MonoBtlsX509Name name, X500DistinguishedNameFlags flag)
+               {
+                       if ((flag != 0) && ((flag & AllFlags) == 0))
+                               throw new ArgumentException ("flag");
+
+                       if (name.GetEntryCount () == 0)
+                               return String.Empty;
+
+                       // Mono.Security reversed isn't the same as fx 2.0 (which is the reverse of 1.x)
+                       bool reversed = ((flag & X500DistinguishedNameFlags.Reversed) != 0);
+                       bool quotes = ((flag & X500DistinguishedNameFlags.DoNotUseQuotes) == 0);
+                       string separator = GetSeparator (flag);
+
+                       return FormatName (name, reversed, separator, quotes);
+               }
+
+               public static string FormatName (MonoBtlsX509Name name, bool reversed, string separator, bool quotes)
+               {
+                       var count = name.GetEntryCount ();
+                       StringBuilder sb = new StringBuilder ();
+
+                       if (reversed) {
+                               for (int i = count - 1; i >= 0; i--) {
+                                       AppendEntry (sb, name, i, separator, quotes);
+                               }
+                       } else {
+                               for (int i = 0; i < count; i++) {
+                                       AppendEntry (sb, name, i, separator, quotes);
+                               }
+                       }
+
+                       return sb.ToString ();
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsX509.cs b/mcs/class/System/Mono.Btls/MonoBtlsX509.cs
new file mode 100644 (file)
index 0000000..31ec458
--- /dev/null
@@ -0,0 +1,465 @@
+//
+// MonoBtlsX509.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+using System;
+using System.IO;
+using System.Text;
+using System.Threading;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security.Cryptography.X509Certificates;
+using System.Security.Cryptography;
+
+namespace Mono.Btls
+{
+       class MonoBtlsX509 : MonoBtlsObject
+       {
+               internal class BoringX509Handle : MonoBtlsHandle
+               {
+                       public BoringX509Handle (IntPtr handle)
+                               : base (handle, true)
+                       {
+                       }
+
+                       protected override bool ReleaseHandle ()
+                       {
+                               if (handle != IntPtr.Zero)
+                                       mono_btls_x509_free (handle);
+                               return true;
+                       }
+
+                       public IntPtr StealHandle ()
+                       {
+                               var retval = Interlocked.Exchange (ref handle, IntPtr.Zero);
+                               return retval;
+                       }
+               }
+
+               new internal BoringX509Handle Handle {
+                       get { return (BoringX509Handle)base.Handle; }
+               }
+
+               internal MonoBtlsX509 (BoringX509Handle handle) 
+                       : base (handle)
+               {
+               }
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_up_ref (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_from_data (IntPtr data, int len, MonoBtlsX509Format format);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_get_subject_name (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_get_issuer_name (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_get_subject_name_string (IntPtr handle, IntPtr buffer, int size);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_get_issuer_name_string (IntPtr handle, IntPtr buffer, int size);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_get_raw_data (IntPtr handle, IntPtr bio, MonoBtlsX509Format format);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_cmp (IntPtr a, IntPtr b);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_get_hash (IntPtr handle, out IntPtr data);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static long mono_btls_x509_get_not_before (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static long mono_btls_x509_get_not_after (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_get_public_key (IntPtr handle, IntPtr bio);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_get_serial_number (IntPtr handle, IntPtr data, int size, int mono_style);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_get_version (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_get_signature_algorithm (IntPtr handle, IntPtr buffer, int size);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_get_public_key_asn1 (IntPtr handle, IntPtr oid, int oid_size, out IntPtr data, out int size);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_get_public_key_parameters (IntPtr handle, IntPtr oid, int oid_size, out IntPtr data, out int size);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_get_pubkey (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_get_subject_key_identifier (IntPtr handle, out IntPtr data, out int size);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_print (IntPtr handle, IntPtr bio);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_x509_free (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_dup (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_add_trust_object (IntPtr handle, MonoBtlsX509Purpose purpose);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_add_reject_object (IntPtr handle, MonoBtlsX509Purpose purpose);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_add_explicit_trust (IntPtr handle, MonoBtlsX509TrustKind kind);
+
+               internal MonoBtlsX509 Copy ()
+               {
+                       var copy = mono_btls_x509_up_ref (Handle.DangerousGetHandle ());
+                       CheckError (copy != IntPtr.Zero);
+                       return new MonoBtlsX509 (new BoringX509Handle (copy));
+               }
+
+               // This will actually duplicate the underlying 'X509 *' object instead of
+               // simply increasing the reference count.
+               internal MonoBtlsX509 Duplicate ()
+               {
+                       var copy = mono_btls_x509_dup (Handle.DangerousGetHandle ());
+                       CheckError (copy != IntPtr.Zero);
+                       return new MonoBtlsX509 (new BoringX509Handle (copy));
+               }
+
+               public static MonoBtlsX509 LoadFromData (byte[] buffer, MonoBtlsX509Format format)
+               {
+                       var data = Marshal.AllocHGlobal (buffer.Length);
+                       if (data == IntPtr.Zero)
+                               throw new OutOfMemoryException ();
+
+                       try {
+                               Marshal.Copy (buffer, 0, data, buffer.Length);
+                               var x509 = mono_btls_x509_from_data (data, buffer.Length, format);
+                               if (x509 == IntPtr.Zero)
+                                       throw new MonoBtlsException ("Failed to read certificate from data.");
+
+                               return new MonoBtlsX509 (new BoringX509Handle (x509));
+                       } finally {
+                               Marshal.FreeHGlobal (data);
+                       }
+               }
+
+               public MonoBtlsX509Name GetSubjectName ()
+               {
+                       var handle = mono_btls_x509_get_subject_name (Handle.DangerousGetHandle ());
+                       CheckError (handle != IntPtr.Zero);
+                       return new MonoBtlsX509Name (new MonoBtlsX509Name.BoringX509NameHandle (handle, false));
+               }
+
+               public string GetSubjectNameString ()
+               {
+                       const int size = 4096;
+                       var data = Marshal.AllocHGlobal (size);
+                       try {
+                               var ret = mono_btls_x509_get_subject_name_string (
+                                       Handle.DangerousGetHandle (), data, size);
+                               CheckError (ret);
+                               return Marshal.PtrToStringAnsi (data);
+                       } finally {
+                               Marshal.FreeHGlobal (data);
+                       }
+               }
+
+               public long GetSubjectNameHash ()
+               {
+                       CheckThrow ();
+                       using (var subject = GetSubjectName ())
+                               return subject.GetHash ();
+               }
+
+               public MonoBtlsX509Name GetIssuerName ()
+               {
+                       var handle = mono_btls_x509_get_issuer_name (Handle.DangerousGetHandle ());
+                       CheckError (handle != IntPtr.Zero);
+                       return new MonoBtlsX509Name (new MonoBtlsX509Name.BoringX509NameHandle (handle, false));
+               }
+
+               public string GetIssuerNameString ()
+               {
+                       const int size = 4096;
+                       var data = Marshal.AllocHGlobal (size);
+                       try {
+                               var ret = mono_btls_x509_get_issuer_name_string (
+                                       Handle.DangerousGetHandle (), data, size);
+                               CheckError (ret);
+                               return Marshal.PtrToStringAnsi (data);
+                       } finally {
+                               Marshal.FreeHGlobal (data);
+                       }
+               }
+
+               public byte[] GetRawData (MonoBtlsX509Format format)
+               {
+                       using (var bio = new MonoBtlsBioMemory ()) {
+                               var ret = mono_btls_x509_get_raw_data (
+                                       Handle.DangerousGetHandle (),
+                                       bio.Handle.DangerousGetHandle (),
+                                       format);
+                               CheckError (ret);
+                               return bio.GetData ();
+                       }
+               }
+
+               public void GetRawData (MonoBtlsBio bio, MonoBtlsX509Format format)
+               {
+                       CheckThrow ();
+                       var ret = mono_btls_x509_get_raw_data (
+                               Handle.DangerousGetHandle (),
+                               bio.Handle.DangerousGetHandle (),
+                               format);
+                       CheckError (ret);
+               }
+
+               public static int Compare (MonoBtlsX509 a, MonoBtlsX509 b)
+               {
+                       return mono_btls_x509_cmp (
+                               a.Handle.DangerousGetHandle (),
+                               b.Handle.DangerousGetHandle ());
+               }
+
+               public byte[] GetCertHash ()
+               {
+                       IntPtr data;
+                       var ret = mono_btls_x509_get_hash (Handle.DangerousGetHandle (), out data);
+                       CheckError (ret > 0);
+                       var buffer = new byte [ret];
+                       Marshal.Copy (data, buffer, 0, ret);
+                       return buffer;
+               }
+
+               public DateTime GetNotBefore ()
+               {
+                       var ticks = mono_btls_x509_get_not_before (Handle.DangerousGetHandle ());
+                       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, 0, 0, 0, DateTimeKind.Utc).AddSeconds (ticks);
+               }
+
+               public byte[] GetPublicKeyData ()
+               {
+                       using (var bio = new MonoBtlsBioMemory ()) {
+                               var ret = mono_btls_x509_get_public_key (
+                                       Handle.DangerousGetHandle (),
+                                       bio.Handle.DangerousGetHandle ());
+                               CheckError (ret > 0);
+                               return bio.GetData ();
+                       }
+               }
+
+               public byte[] GetSerialNumber (bool mono_style)
+               {
+                       int size = 256;
+                       IntPtr data = Marshal.AllocHGlobal (size);
+                       try {
+                               var ret = mono_btls_x509_get_serial_number (
+                                       Handle.DangerousGetHandle (), data,
+                                       size, mono_style ? 1 : 0);
+                               CheckError (ret > 0);
+                               var buffer = new byte [ret];
+                               Marshal.Copy (data, buffer, 0, ret);
+                               return buffer;
+                       } finally {
+                               if (data != IntPtr.Zero)
+                                       Marshal.FreeHGlobal (data);
+                       }
+               }
+
+               public int GetVersion ()
+               {
+                       return mono_btls_x509_get_version (Handle.DangerousGetHandle ());
+               }
+
+               public Oid GetSignatureAlgorithm ()
+               {
+                       int size = 256;
+                       IntPtr data = Marshal.AllocHGlobal (size);
+                       try {
+                               var ret = mono_btls_x509_get_signature_algorithm (
+                                       Handle.DangerousGetHandle (), data, size);
+                               CheckError (ret > 0);
+                               return new Oid (Marshal.PtrToStringAnsi (data));
+                       } finally {
+                               Marshal.FreeHGlobal (data);
+                       }
+               }
+
+               public AsnEncodedData GetPublicKeyAsn1 ()
+               {
+                       int size;
+                       IntPtr data;
+
+                       int oidSize = 256;
+                       var oidData = Marshal.AllocHGlobal (256);
+                       string oid;
+
+                       try {
+                               var ret = mono_btls_x509_get_public_key_asn1 (
+                                       Handle.DangerousGetHandle (), oidData, oidSize,
+                                       out data, out size);
+                               CheckError (ret);
+                               oid = Marshal.PtrToStringAnsi (oidData);
+                       } finally {
+                               Marshal.FreeHGlobal (oidData);
+                       }
+
+                       try {
+                               var buffer = new byte[size];
+                               Marshal.Copy (data, buffer, 0, size);
+                               return new AsnEncodedData (oid.ToString (), buffer);
+                       } finally {
+                               if (data != IntPtr.Zero)
+                                       FreeDataPtr (data);
+                       }
+               }
+
+               public AsnEncodedData GetPublicKeyParameters ()
+               {
+                       int size;
+                       IntPtr data;
+
+                       int oidSize = 256;
+                       var oidData = Marshal.AllocHGlobal (256);
+                       string oid;
+
+                       try {
+                               var ret = mono_btls_x509_get_public_key_parameters (
+                                       Handle.DangerousGetHandle (), oidData, oidSize,
+                                       out data, out size);
+                               CheckError (ret);
+                               oid = Marshal.PtrToStringAnsi (oidData);
+                       } finally {
+                               Marshal.FreeHGlobal (oidData);
+                       }
+
+                       try {
+                               var buffer = new byte[size];
+                               Marshal.Copy (data, buffer, 0, size);
+                               return new AsnEncodedData (oid.ToString (), buffer);
+                       } finally {
+                               if (data != IntPtr.Zero)
+                                       FreeDataPtr (data);
+                       }
+               }
+
+               public byte[] GetSubjectKeyIdentifier ()
+               {
+                       int size;
+                       IntPtr data = IntPtr.Zero;
+
+                       try {
+                               var ret = mono_btls_x509_get_subject_key_identifier (
+                                       Handle.DangerousGetHandle (), out data, out size);
+                               CheckError (ret);
+                               var buffer = new byte[size];
+                               Marshal.Copy (data, buffer, 0, size);
+                               return buffer;
+                       } finally {
+                               if (data != IntPtr.Zero)
+                                       FreeDataPtr (data);
+                       }
+               }
+
+               public MonoBtlsKey GetPublicKey ()
+               {
+                       var handle = mono_btls_x509_get_pubkey (Handle.DangerousGetHandle ());
+                       CheckError (handle != IntPtr.Zero);
+                       return new MonoBtlsKey (new MonoBtlsKey.BoringKeyHandle (handle));
+               }
+
+               public void Print (MonoBtlsBio bio)
+               {
+                       var ret = mono_btls_x509_print (
+                               Handle.DangerousGetHandle (),
+                               bio.Handle.DangerousGetHandle ());
+                       CheckError (ret);
+               }
+
+               public void ExportAsPEM (MonoBtlsBio bio, bool includeHumanReadableForm)
+               {
+                       GetRawData (bio, MonoBtlsX509Format.PEM);
+
+                       if (!includeHumanReadableForm)
+                               return;
+
+                       Print (bio);
+
+                       var hash = GetCertHash ();
+                       var output = new StringBuilder ();
+                       output.Append ("SHA1 Fingerprint=");
+                       for (int i = 0; i < hash.Length; i++) {
+                               if (i > 0)
+                                       output.Append (":");
+                               output.AppendFormat ("{0:X2}", hash [i]);
+                       }
+                       output.AppendLine ();
+                       var outputData = Encoding.ASCII.GetBytes (output.ToString ());
+                       bio.Write (outputData, 0, outputData.Length);
+               }
+
+               public void AddTrustObject (MonoBtlsX509Purpose purpose)
+               {
+                       CheckThrow ();
+                       var ret = mono_btls_x509_add_trust_object (
+                               Handle.DangerousGetHandle (), purpose);
+                       CheckError (ret);
+               }
+
+               public void AddRejectObject (MonoBtlsX509Purpose purpose)
+               {
+                       CheckThrow ();
+                       var ret = mono_btls_x509_add_reject_object (
+                               Handle.DangerousGetHandle (), purpose);
+                       CheckError (ret);
+               }
+
+               public void AddExplicitTrust (MonoBtlsX509TrustKind kind)
+               {
+                       CheckThrow ();
+                       var ret = mono_btls_x509_add_explicit_trust (
+                               Handle.DangerousGetHandle (), kind);
+                       CheckError (ret);
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsX509Chain.cs b/mcs/class/System/Mono.Btls/MonoBtlsX509Chain.cs
new file mode 100644 (file)
index 0000000..6926ae7
--- /dev/null
@@ -0,0 +1,122 @@
+//
+// MonoBtlsX509Chain.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+using System;
+using System.IO;
+using System.Security.Cryptography.X509Certificates;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+namespace Mono.Btls
+{
+       class MonoBtlsX509Chain : MonoBtlsObject
+       {
+               internal class BoringX509ChainHandle : MonoBtlsHandle
+               {
+                       public BoringX509ChainHandle (IntPtr handle)
+                               : base (handle, true)
+                       {
+                       }
+
+                       protected override bool ReleaseHandle ()
+                       {
+                               mono_btls_x509_chain_free (handle);
+                               return true;
+                       }
+               }
+
+               new internal BoringX509ChainHandle Handle {
+                       get { return (BoringX509ChainHandle)base.Handle; }
+               }
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_chain_new ();
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_chain_get_count (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_chain_get_cert (IntPtr Handle, int index);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_chain_add_cert (IntPtr chain, IntPtr x509);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_chain_up_ref (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_x509_chain_free (IntPtr handle);
+
+               public MonoBtlsX509Chain ()
+                       : base (new BoringX509ChainHandle (mono_btls_x509_chain_new ()))
+               {
+               }
+
+               internal MonoBtlsX509Chain (BoringX509ChainHandle handle)
+                       : base (handle)
+               {
+               }
+
+               public int Count {
+                       get { return mono_btls_x509_chain_get_count (Handle.DangerousGetHandle ()); }
+               }
+
+               public MonoBtlsX509 GetCertificate (int index)
+               {
+                       if (index >= Count)
+                               throw new IndexOutOfRangeException ();
+                       var handle = mono_btls_x509_chain_get_cert (
+                               Handle.DangerousGetHandle (), index);
+                       CheckError (handle != IntPtr.Zero);
+                       return new MonoBtlsX509 (new MonoBtlsX509.BoringX509Handle (handle));
+               }
+
+               public void Dump ()
+               {
+                       Console.Error.WriteLine ("CHAIN: {0:x} {1}", Handle, Count);
+                       for (int i = 0; i < Count; i++) {
+                               using (var cert = GetCertificate (i)) {
+                                       Console.Error.WriteLine ("  CERT #{0}: {1}", i, cert.GetSubjectNameString ());
+                               }
+                       }
+               }
+
+               public void AddCertificate (MonoBtlsX509 x509)
+               {
+                       mono_btls_x509_chain_add_cert (
+                               Handle.DangerousGetHandle (),
+                               x509.Handle.DangerousGetHandle ());
+               }
+
+               internal MonoBtlsX509Chain Copy ()
+               {
+                       var copy = mono_btls_x509_chain_up_ref (Handle.DangerousGetHandle ());
+                       CheckError (copy != IntPtr.Zero);
+                       return new MonoBtlsX509Chain (new BoringX509ChainHandle (copy));
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsX509Crl.cs b/mcs/class/System/Mono.Btls/MonoBtlsX509Crl.cs
new file mode 100644 (file)
index 0000000..9d18683
--- /dev/null
@@ -0,0 +1,185 @@
+//
+// MonoBtlsX509Crl.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+using System;
+using System.IO;
+using System.Text;
+using System.Threading;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security.Cryptography.X509Certificates;
+using System.Security.Cryptography;
+
+namespace Mono.Btls
+{
+       class MonoBtlsX509Crl : MonoBtlsObject
+       {
+               internal class BoringX509CrlHandle : MonoBtlsHandle
+               {
+                       public BoringX509CrlHandle (IntPtr handle)
+                               : base (handle, true)
+                       {
+                       }
+
+                       protected override bool ReleaseHandle ()
+                       {
+                               if (handle != IntPtr.Zero)
+                                       mono_btls_x509_crl_free (handle);
+                               return true;
+                       }
+
+                       public IntPtr StealHandle ()
+                       {
+                               var retval = Interlocked.Exchange (ref handle, IntPtr.Zero);
+                               return retval;
+                       }
+               }
+
+               new internal BoringX509CrlHandle Handle {
+                       get { return (BoringX509CrlHandle)base.Handle; }
+               }
+
+               internal MonoBtlsX509Crl (BoringX509CrlHandle handle) 
+                       : base (handle)
+               {
+               }
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_crl_ref (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_crl_from_data (IntPtr data, int len, MonoBtlsX509Format format);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_crl_get_by_cert (IntPtr handle, IntPtr x509);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               unsafe extern static IntPtr mono_btls_x509_crl_get_by_serial (IntPtr handle, void *serial, int len);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_crl_get_revoked_count (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_crl_get_revoked (IntPtr handle, int index);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static long mono_btls_x509_crl_get_last_update (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static long mono_btls_x509_crl_get_next_update (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static long mono_btls_x509_crl_get_version (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_crl_get_issuer (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_x509_crl_free (IntPtr handle);
+
+               public static MonoBtlsX509Crl LoadFromData (byte[] buffer, MonoBtlsX509Format format)
+               {
+                       var data = Marshal.AllocHGlobal (buffer.Length);
+                       if (data == IntPtr.Zero)
+                               throw new OutOfMemoryException ();
+
+                       try {
+                               Marshal.Copy (buffer, 0, data, buffer.Length);
+                               var crl = mono_btls_x509_crl_from_data (data, buffer.Length, format);
+                               if (crl == IntPtr.Zero)
+                                       throw new MonoBtlsException ("Failed to read CRL from data.");
+
+                               return new MonoBtlsX509Crl (new BoringX509CrlHandle (crl));
+                       } finally {
+                               Marshal.FreeHGlobal (data);
+                       }
+               }
+
+               public MonoBtlsX509Revoked GetByCert (MonoBtlsX509 x509)
+               {
+                       var revoked = mono_btls_x509_crl_get_by_cert (
+                               Handle.DangerousGetHandle (),
+                               x509.Handle.DangerousGetHandle ());
+                       if (revoked == IntPtr.Zero)
+                               return null;
+                       return new MonoBtlsX509Revoked (new MonoBtlsX509Revoked.BoringX509RevokedHandle (revoked));
+               }
+
+               public unsafe MonoBtlsX509Revoked GetBySerial (byte[] serial)
+               {
+                       fixed (void *ptr = serial)
+                       {
+                               var revoked = mono_btls_x509_crl_get_by_serial (
+                                       Handle.DangerousGetHandle (), ptr, serial.Length);
+                               if (revoked == IntPtr.Zero)
+                                       return null;
+                               return new MonoBtlsX509Revoked (new MonoBtlsX509Revoked.BoringX509RevokedHandle (revoked));
+                       }
+               }
+
+               public int GetRevokedCount ()
+               {
+                       return mono_btls_x509_crl_get_revoked_count (Handle.DangerousGetHandle ());
+               }
+
+               public MonoBtlsX509Revoked GetRevoked (int index)
+               {
+                       if (index >= GetRevokedCount ())
+                               throw new ArgumentOutOfRangeException ();
+
+                       var revoked = mono_btls_x509_crl_get_revoked (
+                               Handle.DangerousGetHandle (), index);
+                       if (revoked == IntPtr.Zero)
+                               return null;
+                       return new MonoBtlsX509Revoked (new MonoBtlsX509Revoked.BoringX509RevokedHandle (revoked));
+               }
+
+               public DateTime GetLastUpdate ()
+               {
+                       var ticks = mono_btls_x509_crl_get_last_update (Handle.DangerousGetHandle ());
+                       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, 0, 0, 0, DateTimeKind.Utc).AddSeconds (ticks);
+               }
+
+               public long GetVersion ()
+               {
+                       return mono_btls_x509_crl_get_version (Handle.DangerousGetHandle ());
+               }
+
+               public MonoBtlsX509Name GetIssuerName ()
+               {
+                       var handle = mono_btls_x509_crl_get_issuer (Handle.DangerousGetHandle ());
+                       CheckError (handle != IntPtr.Zero);
+                       return new MonoBtlsX509Name (new MonoBtlsX509Name.BoringX509NameHandle (handle, false));
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsX509Error.cs b/mcs/class/System/Mono.Btls/MonoBtlsX509Error.cs
new file mode 100644 (file)
index 0000000..50196bf
--- /dev/null
@@ -0,0 +1,111 @@
+//
+// MonoBtlsX509Error.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+using System;
+namespace Mono.Btls
+{
+       // Keep in sync with x509_vfy.h
+       enum MonoBtlsX509Error
+       {
+               OK = 0,
+               /* illegal error (for uninitialized values, to avoid X509_V_OK): 1 */
+
+               UNABLE_TO_GET_ISSUER_CERT = 2,
+               UNABLE_TO_GET_CRL = 3,
+               UNABLE_TO_DECRYPT_CERT_SIGNATURE = 4,
+               UNABLE_TO_DECRYPT_CRL_SIGNATURE = 5,
+               UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY = 6,
+               CERT_SIGNATURE_FAILURE = 7,
+               CRL_SIGNATURE_FAILURE = 8,
+               CERT_NOT_YET_VALID = 9,
+               CERT_HAS_EXPIRED = 10,
+               CRL_NOT_YET_VALID = 11,
+               CRL_HAS_EXPIRED = 12,
+               ERROR_IN_CERT_NOT_BEFORE_FIELD = 13,
+               ERROR_IN_CERT_NOT_AFTER_FIELD = 14,
+               ERROR_IN_CRL_LAST_UPDATE_FIELD = 15,
+               ERROR_IN_CRL_NEXT_UPDATE_FIELD = 16,
+               OUT_OF_MEM = 17,
+               DEPTH_ZERO_SELF_SIGNED_CERT = 18,
+               SELF_SIGNED_CERT_IN_CHAIN = 19,
+               UNABLE_TO_GET_ISSUER_CERT_LOCALLY = 20,
+               UNABLE_TO_VERIFY_LEAF_SIGNATURE = 21,
+               CERT_CHAIN_TOO_LONG = 22,
+               CERT_REVOKED = 23,
+               INVALID_CA = 24,
+               PATH_LENGTH_EXCEEDED = 25,
+               INVALID_PURPOSE = 26,
+               CERT_UNTRUSTED = 27,
+               CERT_REJECTED = 28,
+               /* These are 'informational' when looking for issuer cert */
+               SUBJECT_ISSUER_MISMATCH = 29,
+               AKID_SKID_MISMATCH = 30,
+               AKID_ISSUER_SERIAL_MISMATCH = 31,
+               KEYUSAGE_NO_CERTSIGN = 32,
+
+               UNABLE_TO_GET_CRL_ISSUER = 33,
+               UNHANDLED_CRITICAL_EXTENSION = 34,
+               KEYUSAGE_NO_CRL_SIGN = 35,
+               UNHANDLED_CRITICAL_CRL_EXTENSION = 36,
+               INVALID_NON_CA = 37,
+               PROXY_PATH_LENGTH_EXCEEDED = 38,
+               KEYUSAGE_NO_DIGITAL_SIGNATURE = 39,
+               PROXY_CERTIFICATES_NOT_ALLOWED = 40,
+
+               INVALID_EXTENSION = 41,
+               INVALID_POLICY_EXTENSION = 42,
+               NO_EXPLICIT_POLICY = 43,
+               DIFFERENT_CRL_SCOPE = 44,
+               UNSUPPORTED_EXTENSION_FEATURE = 45,
+
+               UNNESTED_RESOURCE = 46,
+
+               PERMITTED_VIOLATION = 47,
+               EXCLUDED_VIOLATION = 48,
+               SUBTREE_MINMAX = 49,
+               UNSUPPORTED_CONSTRAINT_TYPE = 51,
+               UNSUPPORTED_CONSTRAINT_SYNTAX = 52,
+               UNSUPPORTED_NAME_SYNTAX = 53,
+               CRL_PATH_VALIDATION_ERROR = 54,
+
+               /* Suite B mode algorithm violation */
+               SUITE_B_INVALID_VERSION = 56,
+               SUITE_B_INVALID_ALGORITHM = 57,
+               SUITE_B_INVALID_CURVE = 58,
+               SUITE_B_INVALID_SIGNATURE_ALGORITHM = 59,
+               SUITE_B_LOS_NOT_ALLOWED = 60,
+               SUITE_B_CANNOT_SIGN_P_384_WITH_P_256 = 61,
+
+               /* Host, email and IP check errors */
+               HOSTNAME_MISMATCH = 62,
+               EMAIL_MISMATCH = 63,
+               IP_ADDRESS_MISMATCH = 64,
+
+               /* The application is not happy */
+               APPLICATION_VERIFICATION = 50
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsX509Exception.cs b/mcs/class/System/Mono.Btls/MonoBtlsX509Exception.cs
new file mode 100644 (file)
index 0000000..588e7a7
--- /dev/null
@@ -0,0 +1,56 @@
+//
+// MonoBtlsX509Exception.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+using System;
+
+namespace Mono.Btls
+{
+       class MonoBtlsX509Exception : Exception
+       {
+               public MonoBtlsX509Error ErrorCode {
+                       get;
+                       private set;
+               }
+
+               public string ErrorMessage {
+                       get;
+                       private set;
+               }
+
+               public MonoBtlsX509Exception (MonoBtlsX509Error code, string message)
+                       : base (message)
+               {
+                       ErrorCode = code;
+                       ErrorMessage = message;
+               }
+
+               public override string ToString ()
+               {
+                       return string.Format ("[MonoBtlsX509Exception: ErrorCode={0}, ErrorMessage={1}]", ErrorCode, ErrorMessage);
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsX509FileType.cs b/mcs/class/System/Mono.Btls/MonoBtlsX509FileType.cs
new file mode 100644 (file)
index 0000000..67d26e6
--- /dev/null
@@ -0,0 +1,37 @@
+//
+// MonoBtlsX509FileType.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+using System;
+namespace Mono.Btls
+{
+       enum MonoBtlsX509FileType
+       {
+               PEM = 1,
+               ASN1 = 2,
+               DEFAULT = 3
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsX509Format.cs b/mcs/class/System/Mono.Btls/MonoBtlsX509Format.cs
new file mode 100644 (file)
index 0000000..551da69
--- /dev/null
@@ -0,0 +1,36 @@
+//
+// MonoBtlsX509Format.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+using System;
+namespace Mono.Btls
+{
+       enum MonoBtlsX509Format
+       {
+               DER = 1,
+               PEM = 2
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsX509Lookup.cs b/mcs/class/System/Mono.Btls/MonoBtlsX509Lookup.cs
new file mode 100644 (file)
index 0000000..3e8fb29
--- /dev/null
@@ -0,0 +1,217 @@
+//
+// MonoBtlsX509Lookup.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+using System;
+using System.IO;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+using System.Collections.Generic;
+
+namespace Mono.Btls
+{
+       class MonoBtlsX509Lookup : MonoBtlsObject
+       {
+               internal class BoringX509LookupHandle : MonoBtlsHandle
+               {
+                       public BoringX509LookupHandle (IntPtr handle)
+                               : base (handle, true)
+                       {
+                       }
+
+                       protected override bool ReleaseHandle ()
+                       {
+                               mono_btls_x509_lookup_free (handle);
+                               return true;
+                       }
+               }
+
+               new internal BoringX509LookupHandle Handle {
+                       get { return (BoringX509LookupHandle)base.Handle; }
+               }
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_lookup_new (IntPtr store, MonoBtlsX509LookupType type);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_lookup_load_file (IntPtr handle, IntPtr file, MonoBtlsX509FileType type);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_lookup_add_dir (IntPtr handle, IntPtr dir, MonoBtlsX509FileType type);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_lookup_add_mono (IntPtr handle, IntPtr monoLookup);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_x509_lookup_method_mono_init (
+                       IntPtr handle, IntPtr instance, IntPtr by_subject_func);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_lookup_init (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_lookup_shutdown (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_lookup_by_subject (IntPtr handle, IntPtr name);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_lookup_by_fingerprint (IntPtr handle, IntPtr bytes, int len);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_x509_lookup_free (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_lookup_peek_lookup (IntPtr handle);
+
+               MonoBtlsX509LookupType type;
+               List<MonoBtlsX509LookupMono> monoLookups;
+
+#if FIXME
+               // Do we need this?
+               internal MonoBtlsX509Lookup (BoringX509LookupHandle handle)
+                       : base (handle)
+               {
+               }
+#endif
+
+               static BoringX509LookupHandle Create_internal (MonoBtlsX509Store store, MonoBtlsX509LookupType type)
+               {
+                       var handle = mono_btls_x509_lookup_new (
+                               store.Handle.DangerousGetHandle (), type);
+                       if (handle == IntPtr.Zero)
+                               throw new MonoBtlsException ();
+                       return new BoringX509LookupHandle (handle);
+               }
+
+               internal MonoBtlsX509Lookup (MonoBtlsX509Store store, MonoBtlsX509LookupType type)
+                       : base (Create_internal (store, type))
+               {
+                       this.type = type;
+               }
+
+               internal IntPtr GetNativeLookup ()
+               {
+                       return mono_btls_x509_lookup_peek_lookup (Handle.DangerousGetHandle ());
+               }
+
+               public void LoadFile (string file, MonoBtlsX509FileType type)
+               {
+                       IntPtr filePtr = IntPtr.Zero;
+                       try {
+                               if (file != null)
+                                       filePtr = Marshal.StringToHGlobalAnsi (file);
+                               var ret = mono_btls_x509_lookup_load_file (
+                                       Handle.DangerousGetHandle (), filePtr, type);
+                               CheckError (ret);
+                       } finally {
+                               if (filePtr != IntPtr.Zero)
+                                       Marshal.FreeHGlobal (filePtr);
+                       }
+               }
+
+               public void AddDirectory (string dir, MonoBtlsX509FileType type)
+               {
+                       IntPtr dirPtr = IntPtr.Zero;
+                       try {
+                               if (dir != null)
+                                       dirPtr = Marshal.StringToHGlobalAnsi (dir);
+                               var ret = mono_btls_x509_lookup_add_dir (
+                                       Handle.DangerousGetHandle (), dirPtr, type);
+                               CheckError (ret);
+                       } finally {
+                               if (dirPtr != IntPtr.Zero)
+                                       Marshal.FreeHGlobal (dirPtr);
+                       }
+               }
+
+               // Takes ownership of the 'monoLookup'.
+               internal void AddMono (MonoBtlsX509LookupMono monoLookup)
+               {
+                       if (type != MonoBtlsX509LookupType.MONO)
+                               throw new NotSupportedException ();
+                       var ret = mono_btls_x509_lookup_add_mono (
+                               Handle.DangerousGetHandle (), monoLookup.Handle.DangerousGetHandle ());
+                       CheckError (ret);
+
+                       if (monoLookups == null)
+                               monoLookups = new List<MonoBtlsX509LookupMono> ();
+                       monoLookups.Add (monoLookup);
+               }
+
+               public void Initialize ()
+               {
+                       var ret = mono_btls_x509_lookup_init (Handle.DangerousGetHandle ());
+                       CheckError (ret);
+               }
+
+               public void Shutdown ()
+               {
+                       var ret = mono_btls_x509_lookup_shutdown (Handle.DangerousGetHandle ());
+                       CheckError (ret);
+               }
+
+               public MonoBtlsX509 LookupBySubject (MonoBtlsX509Name name)
+               {
+                       var handle = mono_btls_x509_lookup_by_subject (
+                               Handle.DangerousGetHandle (),
+                               name.Handle.DangerousGetHandle ());
+                       if (handle == IntPtr.Zero)
+                               return null;
+                       return new MonoBtlsX509 (new MonoBtlsX509.BoringX509Handle (handle));
+               }
+
+               public MonoBtlsX509 LookupByFingerPrint (byte[] fingerprint)
+               {
+                       var bytes = Marshal.AllocHGlobal (fingerprint.Length);
+                       try {
+                               Marshal.Copy (fingerprint, 0, bytes, fingerprint.Length);
+                               var handle = mono_btls_x509_lookup_by_fingerprint (
+                                       Handle.DangerousGetHandle (),
+                                       bytes, fingerprint.Length);
+                               if (handle == IntPtr.Zero)
+                                       return null;
+                               return new MonoBtlsX509 (new MonoBtlsX509.BoringX509Handle (handle));
+                       } finally {
+                               if (bytes != IntPtr.Zero)
+                                       Marshal.FreeHGlobal (bytes);
+                       }
+               }
+
+               protected override void Close ()
+               {
+                       try {
+                               if (monoLookups != null) {
+                                       foreach (var monoLookup in monoLookups)
+                                               monoLookup.Dispose ();
+                               monoLookups = null;
+                               }
+                       } finally {
+                               base.Close ();
+                       }
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsX509LookupAndroid.cs b/mcs/class/System/Mono.Btls/MonoBtlsX509LookupAndroid.cs
new file mode 100644 (file)
index 0000000..45f365c
--- /dev/null
@@ -0,0 +1,43 @@
+//
+// MonoBtlsX509LookupAndroid.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP && MONODROID
+using System;
+using System.IO;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+using System.Security.Cryptography.X509Certificates;
+
+namespace Mono.Btls
+{
+       internal class MonoBtlsX509LookupAndroid : MonoBtlsX509LookupMono
+       {
+               protected override MonoBtlsX509 OnGetBySubject (MonoBtlsX509Name name)
+               {
+                       return AndroidPlatform.CertStoreLookup (name);
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsX509LookupMono.cs b/mcs/class/System/Mono.Btls/MonoBtlsX509LookupMono.cs
new file mode 100644 (file)
index 0000000..30b2ee3
--- /dev/null
@@ -0,0 +1,128 @@
+//
+// MonoBtlsX509LookupMono.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+using System;
+using System.IO;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+
+namespace Mono.Btls
+{
+       abstract class MonoBtlsX509LookupMono : MonoBtlsObject
+       {
+               internal class BoringX509LookupMonoHandle : MonoBtlsHandle
+               {
+                       public BoringX509LookupMonoHandle (IntPtr handle)
+                               : base (handle, true)
+                       {
+                       }
+
+                       protected override bool ReleaseHandle ()
+                       {
+                               mono_btls_x509_lookup_mono_free (handle);
+                               return true;
+                       }
+               }
+
+               new internal BoringX509LookupMonoHandle Handle {
+                       get { return (BoringX509LookupMonoHandle)base.Handle; }
+               }
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_lookup_mono_new ();
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_x509_lookup_mono_init (
+                       IntPtr handle, IntPtr instance, IntPtr by_subject_func);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_lookup_mono_free (IntPtr handle);
+
+               delegate int BySubjectFunc (IntPtr instance, IntPtr name, out IntPtr x509_ptr);
+
+               GCHandle gch;
+               IntPtr instance;
+               BySubjectFunc bySubjectFunc;
+               IntPtr bySubjectFuncPtr;
+
+               internal MonoBtlsX509LookupMono ()
+                       : base (new BoringX509LookupMonoHandle (mono_btls_x509_lookup_mono_new ()))
+               {
+                       gch = GCHandle.Alloc (this);
+                       instance = GCHandle.ToIntPtr (gch);
+                       bySubjectFunc = OnGetBySubject;
+                       bySubjectFuncPtr = Marshal.GetFunctionPointerForDelegate (bySubjectFunc);
+                       mono_btls_x509_lookup_mono_init (Handle.DangerousGetHandle (), instance, bySubjectFuncPtr);
+               }
+
+               protected abstract MonoBtlsX509 OnGetBySubject (MonoBtlsX509Name name);
+
+#if MONOTOUCH
+               [MonoTouch.MonoPInvokeCallback (typeof (BySubjectFunc))]
+#endif
+               static int OnGetBySubject (IntPtr instance, IntPtr name_ptr, out IntPtr x509_ptr)
+               {
+                       try {
+                               MonoBtlsX509LookupMono obj;
+                               MonoBtlsX509Name.BoringX509NameHandle name_handle = null;
+                               try {
+                                       obj = (MonoBtlsX509LookupMono)GCHandle.FromIntPtr (instance).Target;
+                                       name_handle = new MonoBtlsX509Name.BoringX509NameHandle (name_ptr, false);
+                                       MonoBtlsX509Name name_obj = new MonoBtlsX509Name (name_handle);
+                                       var x509 = obj.OnGetBySubject (name_obj);
+                                       if (x509 != null) {
+                                               x509_ptr = x509.Handle.StealHandle ();
+                                               return 1;
+                                       } else {
+                                               x509_ptr = IntPtr.Zero;
+                                               return 0;
+                                       }
+                               } finally {
+                                       if (name_handle != null)
+                                               name_handle.Dispose ();
+                               }
+                       } catch (Exception ex) {
+                               Console.WriteLine ("LOOKUP METHOD - GET BY SUBJECT EX: {0}", ex);
+                               x509_ptr = IntPtr.Zero;
+                               return 0;
+                       }
+               }
+
+               protected override void Close ()
+               {
+                       try {
+                               if (gch.IsAllocated)
+                                       gch.Free ();
+                       } finally {
+                               instance = IntPtr.Zero;
+                               bySubjectFunc = null;
+                               bySubjectFuncPtr = IntPtr.Zero;
+                               base.Close ();
+                       }
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsX509LookupMonoCollection.cs b/mcs/class/System/Mono.Btls/MonoBtlsX509LookupMonoCollection.cs
new file mode 100644 (file)
index 0000000..8a854f6
--- /dev/null
@@ -0,0 +1,102 @@
+//
+// MonoBtlsX509LookupMonoCollection.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+using System;
+using System.IO;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+using System.Security.Cryptography.X509Certificates;
+
+#if MONOTOUCH
+using MonoTouch;
+#endif
+
+namespace Mono.Btls
+{
+       internal class MonoBtlsX509LookupMonoCollection : MonoBtlsX509LookupMono
+       {
+               long[] hashes;
+               MonoBtlsX509[] certificates;
+               X509CertificateCollection collection;
+               MonoBtlsX509TrustKind trust;
+
+               internal MonoBtlsX509LookupMonoCollection (X509CertificateCollection collection, MonoBtlsX509TrustKind trust)
+               {
+                       this.collection = collection;
+                       this.trust = trust;
+               }
+
+               void Initialize ()
+               {
+                       if (certificates != null)
+                               return;
+
+                       hashes = new long [collection.Count];
+                       certificates = new MonoBtlsX509 [collection.Count];
+                       for (int i = 0; i < collection.Count; i++) {
+                               // Create new 'X509 *' instance since we need to modify it to add the
+                               // trust settings.
+                               var data = collection [i].GetRawCertData ();
+                               certificates [i] = MonoBtlsX509.LoadFromData (data, MonoBtlsX509Format.DER);
+                               certificates [i].AddExplicitTrust (trust);
+                               hashes [i] = certificates [i].GetSubjectNameHash ();
+                       }
+               }
+
+               protected override MonoBtlsX509 OnGetBySubject (MonoBtlsX509Name name)
+               {
+                       Console.WriteLine ("COLLECTION LOOKUP: {0:x} - {1}", name.GetHash (), name.GetString ());
+                       Initialize ();
+
+                       var hash = name.GetHash ();
+                       for (int i = 0; i < certificates.Length; i++) {
+                               if (hashes [i] == hash)
+                                       return certificates [i];
+                       }
+
+                       return null;
+               }
+
+               protected override void Close ()
+               {
+                       try {
+                               if (certificates != null) {
+                                       for (int i = 0; i < certificates.Length; i++) {
+                                               if (certificates [i] != null) {
+                                                       certificates [i].Dispose ();
+                                                       certificates [i] = null;
+                                               }
+                                       }
+                                       certificates = null;
+                                       hashes = null;
+                               }
+                       } finally {
+                               base.Close ();
+                       }
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsX509LookupType.cs b/mcs/class/System/Mono.Btls/MonoBtlsX509LookupType.cs
new file mode 100644 (file)
index 0000000..2cbdf7c
--- /dev/null
@@ -0,0 +1,39 @@
+//
+// MonoBtlsX509LookupCollection.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+using System;
+
+namespace Mono.Btls
+{
+       enum MonoBtlsX509LookupType
+       {
+               UNKNOWN = 0,
+               FILE,
+               HASH_DIR,
+               MONO
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsX509Name.cs b/mcs/class/System/Mono.Btls/MonoBtlsX509Name.cs
new file mode 100644 (file)
index 0000000..80a322c
--- /dev/null
@@ -0,0 +1,216 @@
+//
+// MonoBtlsX509Name.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+using System;
+using System.IO;
+using System.Text;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+
+namespace Mono.Btls
+{
+       class MonoBtlsX509Name : MonoBtlsObject
+       {
+               internal class BoringX509NameHandle : MonoBtlsHandle
+               {
+                       bool dontFree;
+
+                       internal BoringX509NameHandle (IntPtr handle, bool ownsHandle)
+                               : base (handle, ownsHandle)
+                       {
+                               this.dontFree = !ownsHandle;
+                       }
+
+                       protected override bool ReleaseHandle ()
+                       {
+                               if (!dontFree)
+                                       mono_btls_x509_name_free (handle);
+                               return true;
+                       }
+               }
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_name_print_bio (IntPtr handle, IntPtr bio);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_name_print_string (IntPtr handle, IntPtr buffer, int size);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_name_get_raw_data (IntPtr handle, out IntPtr buffer, int use_canon_enc);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static long mono_btls_x509_name_hash (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static long mono_btls_x509_name_hash_old (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_name_get_entry_count (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static MonoBtlsX509NameEntryType mono_btls_x509_name_get_entry_type (IntPtr name, int index);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_name_get_entry_oid (IntPtr name, int index, IntPtr buffer, int size);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               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 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);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_x509_name_free (IntPtr handle);
+
+               new internal BoringX509NameHandle Handle {
+                       get { return (BoringX509NameHandle)base.Handle; }
+               }
+
+               internal MonoBtlsX509Name (BoringX509NameHandle handle)
+                       : base (handle)
+               {
+               }
+
+               public string GetString ()
+               {
+                       const int size = 4096;
+                       var data = Marshal.AllocHGlobal (size);
+                       try {
+                               var ret = mono_btls_x509_name_print_string (
+                                       Handle.DangerousGetHandle (), data, size);
+                               CheckError (ret);
+                               return Marshal.PtrToStringAnsi (data);
+                       } finally {
+                               Marshal.FreeHGlobal (data);
+                       }
+               }
+
+               public void PrintBio (MonoBtlsBio bio)
+               {
+                       var ret = mono_btls_x509_name_print_bio (
+                               Handle.DangerousGetHandle (),
+                               bio.Handle.DangerousGetHandle ());
+                       CheckError (ret);
+               }
+
+               public byte[] GetRawData (bool use_canon_enc)
+               {
+                       IntPtr data;
+                       var ret = mono_btls_x509_name_get_raw_data (
+                               Handle.DangerousGetHandle (),
+                               out data, use_canon_enc ? 1 : 0);
+                       CheckError (ret > 0);
+                       var buffer = new byte [ret];
+                       Marshal.Copy (data, buffer, 0, ret);
+                       FreeDataPtr (data);
+                       return buffer;
+               }
+
+               public long GetHash ()
+               {
+                       return mono_btls_x509_name_hash (Handle.DangerousGetHandle ());
+               }
+
+               public long GetHashOld ()
+               {
+                       return mono_btls_x509_name_hash_old (Handle.DangerousGetHandle ());
+               }
+
+               public int GetEntryCount ()
+               {
+                       return mono_btls_x509_name_get_entry_count (Handle.DangerousGetHandle ());
+               }
+
+               public MonoBtlsX509NameEntryType GetEntryType (int index)
+               {
+                       if (index >= GetEntryCount ())
+                               throw new ArgumentOutOfRangeException ();
+                       return mono_btls_x509_name_get_entry_type (
+                               Handle.DangerousGetHandle (), index);
+               }
+
+               public string GetEntryOid (int index)
+               {
+                       if (index >= GetEntryCount ())
+                               throw new ArgumentOutOfRangeException ();
+
+                       const int size = 4096;
+                       var data = Marshal.AllocHGlobal (size);
+                       try {
+                               var ret = mono_btls_x509_name_get_entry_oid (
+                                       Handle.DangerousGetHandle (),
+                                       index, data, size);
+                               CheckError (ret > 0);
+                               return Marshal.PtrToStringAnsi (data);
+                       } finally {
+                               Marshal.FreeHGlobal (data);
+                       }
+               }
+
+               public byte[] GetEntryOidData (int index)
+               {
+                       IntPtr data;
+                       var ret = mono_btls_x509_name_get_entry_oid_data (
+                               Handle.DangerousGetHandle (), index, out data);
+                       CheckError (ret > 0);
+
+                       var bytes = new byte[ret];
+                       Marshal.Copy (data, bytes, 0, ret);
+                       return bytes;
+               }
+
+               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 tag, out data);
+                       if (ret <= 0)
+                               return null;
+                       try {
+                               return new UTF8Encoding ().GetString ((byte*)data, ret);
+                       } finally {
+                               if (data != IntPtr.Zero)
+                                       FreeDataPtr (data);
+                       }
+               }
+
+               public static unsafe MonoBtlsX509Name CreateFromData (byte[] data, bool use_canon_enc)
+               {
+                       fixed (void *ptr = data) {
+                               var handle = mono_btls_x509_name_from_data (ptr, data.Length, use_canon_enc ? 1 : 0);
+                               if (handle == IntPtr.Zero)
+                                       throw new MonoBtlsException ("mono_btls_x509_name_from_data() failed.");
+                               return new MonoBtlsX509Name (new BoringX509NameHandle (handle, false));
+                       }
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsX509NameEntryType.cs b/mcs/class/System/Mono.Btls/MonoBtlsX509NameEntryType.cs
new file mode 100644 (file)
index 0000000..781d691
--- /dev/null
@@ -0,0 +1,51 @@
+//
+// MonoBtlsX509NameEntryType.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+using System;
+namespace Mono.Btls
+{
+       enum MonoBtlsX509NameEntryType : int
+       {
+               Unknown = 0,
+               CountryName,
+               OrganizationName,
+               OrganizationalUnitName,
+               CommonName,
+               LocalityName,
+               StateOrProvinceName,
+               StreetAddress,
+               SerialNumber,
+               DomainComponent,
+               UserId,
+               Email,
+               DnQualifier,
+               Title,
+               Surname,
+               GivenName,
+               Initial
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsX509NameList.cs b/mcs/class/System/Mono.Btls/MonoBtlsX509NameList.cs
new file mode 100644 (file)
index 0000000..cccc005
--- /dev/null
@@ -0,0 +1,121 @@
+//
+// MonoBtlsX509NameList.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+using System;
+using System.IO;
+using System.Text;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+
+namespace Mono.Btls
+{
+       class MonoBtlsX509NameList : MonoBtlsObject
+       {
+               internal class BoringX509NameListHandle : MonoBtlsHandle
+               {
+                       bool dontFree;
+
+                       internal BoringX509NameListHandle (IntPtr handle, bool ownsHandle)
+                               : base (handle, ownsHandle)
+                       {
+                               this.dontFree = !ownsHandle;
+                       }
+
+                       protected override bool ReleaseHandle ()
+                       {
+                               if (!dontFree)
+                                       mono_btls_x509_name_list_free (handle);
+                               return true;
+                       }
+               }
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_name_list_new ();
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_name_list_get_count (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_name_list_add (IntPtr handle, IntPtr name);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_name_list_get_item (IntPtr handle, int index);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_x509_name_list_free (IntPtr handle);
+
+               new internal BoringX509NameListHandle Handle {
+                       get { return (BoringX509NameListHandle)base.Handle; }
+               }
+
+               internal MonoBtlsX509NameList (BoringX509NameListHandle handle)
+                       : base (handle)
+               {
+               }
+
+               internal MonoBtlsX509NameList ()
+                       : this (Create_internal ())
+               {
+               }
+
+               static BoringX509NameListHandle Create_internal ()
+               {
+                       var handle = mono_btls_x509_name_list_new ();
+                       if (handle == IntPtr.Zero)
+                               throw new MonoBtlsException ();
+                       return new BoringX509NameListHandle (handle, true);
+               }
+
+               public int GetCount ()
+               {
+                       CheckThrow ();
+                       return mono_btls_x509_name_list_get_count (
+                               Handle.DangerousGetHandle ());
+               }
+
+               public MonoBtlsX509Name GetItem (int index)
+               {
+                       CheckThrow ();
+                       if (index < 0 || index >= GetCount ())
+                               throw new ArgumentOutOfRangeException ();
+                       var ptr = mono_btls_x509_name_list_get_item (
+                               Handle.DangerousGetHandle (), index);
+                       if (ptr == IntPtr.Zero)
+                               return null;
+                       return new MonoBtlsX509Name (
+                               new MonoBtlsX509Name.BoringX509NameHandle (ptr, true));
+               }
+
+               public void Add (MonoBtlsX509Name name)
+               {
+                       CheckThrow ();
+                       mono_btls_x509_name_list_add (
+                               Handle.DangerousGetHandle (),
+                               name.Handle.DangerousGetHandle ());
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsX509Purpose.cs b/mcs/class/System/Mono.Btls/MonoBtlsX509Purpose.cs
new file mode 100644 (file)
index 0000000..d80957c
--- /dev/null
@@ -0,0 +1,43 @@
+//
+// MonoBtlsX509Purpose.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+using System;
+namespace Mono.Btls
+{
+       enum MonoBtlsX509Purpose
+       {
+               SSL_CLIENT = 1,
+               SSL_SERVER = 2,
+               NS_SSL_SERVER = 3,
+               SMIME_SIGN = 4,
+               SMIME_ENCRYPT = 5,
+               CRL_SIGN = 6,
+               ANY = 7,
+               OCSP_HELPER = 8,
+               TIMESTAMP_SIGN = 9,
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsX509Revoked.cs b/mcs/class/System/Mono.Btls/MonoBtlsX509Revoked.cs
new file mode 100644 (file)
index 0000000..4f5d79b
--- /dev/null
@@ -0,0 +1,120 @@
+//
+// MonoBtlsX509Revoked.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+using System;
+using System.IO;
+using System.Text;
+using System.Threading;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security.Cryptography.X509Certificates;
+using System.Security.Cryptography;
+
+namespace Mono.Btls
+{
+       class MonoBtlsX509Revoked : MonoBtlsObject
+       {
+               internal class BoringX509RevokedHandle : MonoBtlsHandle
+               {
+                       public BoringX509RevokedHandle (IntPtr handle)
+                               : base (handle, true)
+                       {
+                       }
+
+                       protected override bool ReleaseHandle ()
+                       {
+                               if (handle != IntPtr.Zero)
+                                       mono_btls_x509_revoked_free (handle);
+                               return true;
+                       }
+
+                       public IntPtr StealHandle ()
+                       {
+                               var retval = Interlocked.Exchange (ref handle, IntPtr.Zero);
+                               return retval;
+                       }
+               }
+
+               new internal BoringX509RevokedHandle Handle {
+                       get { return (BoringX509RevokedHandle)base.Handle; }
+               }
+
+               internal MonoBtlsX509Revoked (BoringX509RevokedHandle handle)
+                       : base (handle)
+               {
+               }
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_revoked_get_serial_number (IntPtr handle, IntPtr data, int size);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static long mono_btls_x509_revoked_get_revocation_date (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_revoked_get_reason (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_revoked_get_sequence (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_x509_revoked_free (IntPtr handle);
+
+               public byte[] GetSerialNumber ()
+               {
+                       int size = 256;
+                       IntPtr data = Marshal.AllocHGlobal (size);
+                       try {
+                               var ret = mono_btls_x509_revoked_get_serial_number (
+                                       Handle.DangerousGetHandle (), data, size);
+                               CheckError (ret > 0);
+                               var buffer = new byte[ret];
+                               Marshal.Copy (data, buffer, 0, ret);
+                               return buffer;
+                       } finally {
+                               if (data != IntPtr.Zero)
+                                       Marshal.FreeHGlobal (data);
+                       }
+               }
+
+               public DateTime GetRevocationDate ()
+               {
+                       var ticks = mono_btls_x509_revoked_get_revocation_date (
+                               Handle.DangerousGetHandle ());
+                       return new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds (ticks);
+               }
+
+               public int GetReason ()
+               {
+                       return mono_btls_x509_revoked_get_reason (Handle.DangerousGetHandle ());
+               }
+
+               public int GetSequence ()
+               {
+                       return mono_btls_x509_revoked_get_sequence (Handle.DangerousGetHandle ());
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsX509Store.cs b/mcs/class/System/Mono.Btls/MonoBtlsX509Store.cs
new file mode 100644 (file)
index 0000000..2e03715
--- /dev/null
@@ -0,0 +1,230 @@
+//
+// MonoBtlsX509Store.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+using System;
+using System.IO;
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+using System.Security.Cryptography.X509Certificates;
+
+namespace Mono.Btls
+{
+       class MonoBtlsX509Store : MonoBtlsObject
+       {
+               internal class BoringX509StoreHandle : MonoBtlsHandle
+               {
+                       public BoringX509StoreHandle (IntPtr handle)
+                               : base (handle, true)
+                       {
+                       }
+
+                       protected override bool ReleaseHandle ()
+                       {
+                               mono_btls_x509_store_free (handle);
+                               return true;
+                       }
+               }
+
+               new internal BoringX509StoreHandle Handle {
+                       get { return (BoringX509StoreHandle)base.Handle; }
+               }
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_store_new ();
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_store_from_ctx (IntPtr ctx);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_store_from_ssl_ctx (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_store_load_locations (IntPtr handle, IntPtr file, IntPtr path);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_store_set_default_paths (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_store_add_cert (IntPtr handle, IntPtr x509);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_store_get_count (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_x509_store_free (IntPtr handle);
+
+               Dictionary<IntPtr,MonoBtlsX509Lookup> lookupHash;
+
+               public void LoadLocations (string file, string path)
+               {
+                       IntPtr filePtr = IntPtr.Zero;
+                       IntPtr pathPtr = IntPtr.Zero;
+                       try {
+                               if (file != null)
+                                       filePtr = Marshal.StringToHGlobalAnsi (file);
+                               if (path != null)
+                                       pathPtr = Marshal.StringToHGlobalAnsi (path);
+                               var ret = mono_btls_x509_store_load_locations (
+                                       Handle.DangerousGetHandle (), filePtr, pathPtr);
+                               CheckError (ret);
+                       } finally {
+                               if (filePtr != IntPtr.Zero)
+                                       Marshal.FreeHGlobal (filePtr);
+                               if (pathPtr != IntPtr.Zero)
+                                       Marshal.FreeHGlobal (pathPtr);
+                       }
+               }
+
+               public void SetDefaultPaths ()
+               {
+                       var ret = mono_btls_x509_store_set_default_paths (Handle.DangerousGetHandle ());
+                       CheckError (ret);
+               }
+
+               static BoringX509StoreHandle Create_internal ()
+               {
+                       var handle = mono_btls_x509_store_new ();
+                       if (handle == IntPtr.Zero)
+                               throw new MonoBtlsException ();
+                       return new BoringX509StoreHandle (handle);
+               }
+
+               static BoringX509StoreHandle Create_internal (IntPtr store_ctx)
+               {
+                       var handle = mono_btls_x509_store_from_ssl_ctx (store_ctx);
+                       if (handle == IntPtr.Zero)
+                               throw new MonoBtlsException ();
+                       return new BoringX509StoreHandle (handle);
+               }
+
+               static BoringX509StoreHandle Create_internal (MonoBtlsSslCtx.BoringSslCtxHandle ctx)
+               {
+                       var handle = mono_btls_x509_store_from_ssl_ctx (ctx.DangerousGetHandle ());
+                       if (handle == IntPtr.Zero)
+                               throw new MonoBtlsException ();
+                       return new BoringX509StoreHandle (handle);
+               }
+
+               internal MonoBtlsX509Store ()
+                       : base (Create_internal ())
+               {
+               }
+
+               internal MonoBtlsX509Store (IntPtr store_ctx)
+                       : base (Create_internal (store_ctx))
+               {
+               }
+
+               internal MonoBtlsX509Store (MonoBtlsSslCtx.BoringSslCtxHandle ctx)
+                       : base (Create_internal (ctx))
+               {
+               }
+
+               public void AddCertificate (MonoBtlsX509 x509)
+               {
+                       var ret = mono_btls_x509_store_add_cert (
+                               Handle.DangerousGetHandle (),
+                               x509.Handle.DangerousGetHandle ());
+                       CheckError (ret);
+               }
+
+               public int GetCount ()
+               {
+                       return mono_btls_x509_store_get_count (Handle.DangerousGetHandle ());
+               }
+
+               internal void AddTrustedRoots ()
+               {
+                       var systemRoot = MonoBtlsProvider.GetSystemStoreLocation ();
+                       LoadLocations (null, systemRoot);
+               }
+
+               public MonoBtlsX509Lookup AddLookup (MonoBtlsX509LookupType type)
+               {
+                       if (lookupHash == null)
+                               lookupHash = new Dictionary<IntPtr,MonoBtlsX509Lookup> ();
+
+                       /*
+                        * X509_STORE_add_lookup() returns the same 'X509_LOOKUP *' for each
+                        * unique 'X509_LOOKUP_METHOD *' (which is supposed to be a static struct)
+                        * and we want to use the same managed object for each unique 'X509_LOOKUP *'.
+                       */
+                       var lookup = new MonoBtlsX509Lookup (this, type);
+                       var nativeLookup = lookup.GetNativeLookup ();
+                       if (lookupHash.ContainsKey (nativeLookup)) {
+                               lookup.Dispose ();
+                               lookup = lookupHash [nativeLookup];
+                       } else {
+                               lookupHash.Add (nativeLookup, lookup);
+                       }
+
+                       return lookup;
+               }
+
+               public void AddDirectoryLookup (string dir, MonoBtlsX509FileType type)
+               {
+                       var lookup = AddLookup (MonoBtlsX509LookupType.HASH_DIR);
+                       lookup.AddDirectory (dir, type);
+               }
+
+               public void AddFileLookup (string file, MonoBtlsX509FileType type)
+               {
+                       var lookup = AddLookup (MonoBtlsX509LookupType.FILE);
+                       lookup.LoadFile (file, type);
+               }
+
+               public void AddCollection (X509CertificateCollection collection, MonoBtlsX509TrustKind trust)
+               {
+                       var monoLookup = new MonoBtlsX509LookupMonoCollection (collection, trust);
+                       var lookup = new MonoBtlsX509Lookup (this, MonoBtlsX509LookupType.MONO);
+                       lookup.AddMono (monoLookup);
+               }
+
+#if MONODROID
+               public void AddAndroidLookup ()
+               {
+                       var androidLookup = new MonoBtlsX509LookupAndroid ();
+                       var lookup = new MonoBtlsX509Lookup (this, MonoBtlsX509LookupType.MONO);
+                       lookup.AddMono (androidLookup);
+               }
+#endif
+
+               protected override void Close ()
+               {
+                       try {
+                               if (lookupHash != null) {
+                                       foreach (var lookup in lookupHash.Values)
+                                               lookup.Dispose ();
+                                       lookupHash = null;
+                               }
+                       } finally {
+                               base.Close ();
+                       }
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsX509StoreCtx.cs b/mcs/class/System/Mono.Btls/MonoBtlsX509StoreCtx.cs
new file mode 100644 (file)
index 0000000..41df129
--- /dev/null
@@ -0,0 +1,244 @@
+//
+// MonoBtlsX509StoreCtx.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+using System;
+using System.IO;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+
+namespace Mono.Btls
+{
+       class MonoBtlsX509StoreCtx : MonoBtlsObject
+       {
+               internal class BoringX509StoreCtxHandle : MonoBtlsHandle
+               {
+                       bool dontFree;
+
+                       internal BoringX509StoreCtxHandle (IntPtr handle, bool ownsHandle = true)
+                               : base (handle, ownsHandle)
+                       {
+                               dontFree = !ownsHandle;
+                       }
+
+                       #if FIXME
+                       internal BoringX509StoreCtxHandle (IntPtr handle)
+                               : base ()
+                       {
+                               base.handle = handle;
+                               this.dontFree = true;
+                       }
+                       #endif
+
+                       protected override bool ReleaseHandle ()
+                       {
+                               if (!dontFree)
+                                       mono_btls_x509_store_ctx_free (handle);
+                               return true;
+                       }
+               }
+
+               int? verifyResult;
+
+               new internal BoringX509StoreCtxHandle Handle {
+                       get { return (BoringX509StoreCtxHandle)base.Handle; }
+               }
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_store_ctx_new ();
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_store_ctx_from_ptr (IntPtr ctx);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static MonoBtlsX509Error mono_btls_x509_store_ctx_get_error (IntPtr handle, out IntPtr error_string);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_store_ctx_get_error_depth (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_store_ctx_get_chain (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_store_ctx_init (IntPtr handle, IntPtr store, IntPtr chain);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_store_ctx_set_param (IntPtr handle, IntPtr param);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_store_ctx_verify_cert (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_store_ctx_get_by_subject (IntPtr handle, IntPtr name);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_store_ctx_get_current_cert (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_store_ctx_get_current_issuer (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_store_ctx_get_verify_param (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_store_ctx_get_untrusted (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_store_ctx_up_ref (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_x509_store_ctx_free (IntPtr handle);
+
+               internal MonoBtlsX509StoreCtx ()
+                       : base (new BoringX509StoreCtxHandle (mono_btls_x509_store_ctx_new ()))
+               {
+               }
+
+               static BoringX509StoreCtxHandle Create_internal (IntPtr store_ctx)
+               {
+                       var handle = mono_btls_x509_store_ctx_from_ptr (store_ctx);
+                       if (handle == IntPtr.Zero)
+                               throw new MonoBtlsException ();
+                       return new BoringX509StoreCtxHandle (handle);
+               }
+
+               internal MonoBtlsX509StoreCtx (int preverify_ok, IntPtr store_ctx)
+                       : base (Create_internal (store_ctx))
+               {
+                       verifyResult = preverify_ok;
+               }
+
+               internal MonoBtlsX509StoreCtx (BoringX509StoreCtxHandle ptr, int? verifyResult)
+                       : base (ptr)
+               {
+                       this.verifyResult = verifyResult;
+               }
+
+               public MonoBtlsX509Error GetError ()
+               {
+                       IntPtr error_string_ptr;
+                       return mono_btls_x509_store_ctx_get_error (Handle.DangerousGetHandle (), out error_string_ptr);
+               }
+
+               public MonoBtlsX509Exception GetException ()
+               {
+                       IntPtr error_string_ptr;
+                       var error = mono_btls_x509_store_ctx_get_error (Handle.DangerousGetHandle (), out error_string_ptr);
+                       if (error == 0)
+                               return null;
+                       if (error_string_ptr != IntPtr.Zero) {
+                               var error_string = Marshal.PtrToStringAnsi (error_string_ptr);
+                               return new MonoBtlsX509Exception (error, error_string);
+                       }
+                       return new MonoBtlsX509Exception (error, "Unknown verify error.");
+               }
+
+               public MonoBtlsX509Chain GetChain ()
+               {
+                       var chain = mono_btls_x509_store_ctx_get_chain (Handle.DangerousGetHandle ());
+                       CheckError (chain != IntPtr.Zero);
+                       return new MonoBtlsX509Chain (new MonoBtlsX509Chain.BoringX509ChainHandle (chain));
+               }
+
+               public MonoBtlsX509Chain GetUntrusted ()
+               {
+                       var chain = mono_btls_x509_store_ctx_get_untrusted (Handle.DangerousGetHandle ());
+                       CheckError (chain != IntPtr.Zero);
+                       return new MonoBtlsX509Chain (new MonoBtlsX509Chain.BoringX509ChainHandle (chain));
+               }
+
+               public void Initialize (MonoBtlsX509Store store, MonoBtlsX509Chain chain)
+               {
+                       var ret = mono_btls_x509_store_ctx_init (
+                               Handle.DangerousGetHandle (),
+                               store.Handle.DangerousGetHandle (),
+                               chain.Handle.DangerousGetHandle ());
+                       CheckError (ret);
+               }
+
+               public void SetVerifyParam (MonoBtlsX509VerifyParam param)
+               {
+                       var ret = mono_btls_x509_store_ctx_set_param (
+                               Handle.DangerousGetHandle (),
+                               param.Handle.DangerousGetHandle ());
+                       CheckError (ret);
+               }
+
+               public int VerifyResult {
+                       get {
+                               if (verifyResult == null)
+                                       throw new InvalidOperationException ();
+                               return verifyResult.Value;
+                       }
+               }
+
+               public int Verify ()
+               {
+                       verifyResult = mono_btls_x509_store_ctx_verify_cert (Handle.DangerousGetHandle ());
+                       return verifyResult.Value;
+               }
+
+               public MonoBtlsX509 LookupBySubject (MonoBtlsX509Name name)
+               {
+                       var handle = mono_btls_x509_store_ctx_get_by_subject (
+                               Handle.DangerousGetHandle (), name.Handle.DangerousGetHandle ());
+                       if (handle == IntPtr.Zero)
+                               return null;
+                       return new MonoBtlsX509 (new MonoBtlsX509.BoringX509Handle (handle));
+               }
+
+               public MonoBtlsX509 GetCurrentCertificate ()
+               {
+                       var x509 = mono_btls_x509_store_ctx_get_current_cert (Handle.DangerousGetHandle ());
+                       if (x509 == IntPtr.Zero)
+                               return null;
+                       return new MonoBtlsX509 (new MonoBtlsX509.BoringX509Handle (x509));
+               }
+
+               public MonoBtlsX509 GetCurrentIssuer ()
+               {
+                       var x509 = mono_btls_x509_store_ctx_get_current_issuer (Handle.DangerousGetHandle ());
+                       if (x509 == IntPtr.Zero)
+                               return null;
+                       return new MonoBtlsX509 (new MonoBtlsX509.BoringX509Handle (x509));
+               }
+
+               public MonoBtlsX509VerifyParam GetVerifyParam ()
+               {
+                       var param = mono_btls_x509_store_ctx_get_verify_param (Handle.DangerousGetHandle ());
+                       if (param == IntPtr.Zero)
+                               return null;
+                       return new MonoBtlsX509VerifyParam (new MonoBtlsX509VerifyParam.BoringX509VerifyParamHandle (param));
+               }
+
+               public MonoBtlsX509StoreCtx Copy ()
+               {
+                       var copy = mono_btls_x509_store_ctx_up_ref (Handle.DangerousGetHandle ());
+                       CheckError (copy != IntPtr.Zero);
+                       return new MonoBtlsX509StoreCtx (new BoringX509StoreCtxHandle (copy), verifyResult);
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsX509StoreManager.cs b/mcs/class/System/Mono.Btls/MonoBtlsX509StoreManager.cs
new file mode 100644 (file)
index 0000000..13c92a2
--- /dev/null
@@ -0,0 +1,120 @@
+//
+// MonoBtlsX509StoreManager.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+#if MONO_SECURITY_ALIAS
+extern alias MonoSecurity;
+#endif
+
+using System;
+using System.IO;
+using System.Security.Cryptography.X509Certificates;
+
+#if MONO_SECURITY_ALIAS
+using MonoSecurity::Mono.Security.Interface;
+using MX = MonoSecurity::Mono.Security.X509;
+#else
+using Mono.Security.Interface;
+using MX = Mono.Security.X509;
+#endif
+
+namespace Mono.Btls
+{
+       static class MonoBtlsX509StoreManager
+       {
+               static bool initialized;
+               static string machineTrustedRootPath;
+               static string machineIntermediateCAPath;
+               static string machineUntrustedPath;
+               static string userTrustedRootPath;
+               static string userIntermediateCAPath;
+               static string userUntrustedPath;
+
+               static void Initialize ()
+               {
+                       if (initialized)
+                               return;
+
+                       try {
+                               DoInitialize ();
+                       } catch (Exception ex) {
+                               Console.Error.WriteLine ("MonoBtlsX509StoreManager.Initialize() threw exception: {0}", ex);
+                       } finally {
+                               initialized = true;
+                       }
+               }
+
+               static void DoInitialize ()
+               {
+#if !ANDROID
+                       var userPath = MX.X509StoreManager.NewCurrentUserPath;
+                       userTrustedRootPath = Path.Combine (userPath, MX.X509Stores.Names.TrustedRoot);
+                       userIntermediateCAPath = Path.Combine (userPath, MX.X509Stores.Names.IntermediateCA);
+                       userUntrustedPath = Path.Combine (userPath, MX.X509Stores.Names.Untrusted);
+
+                       var machinePath = MX.X509StoreManager.NewLocalMachinePath;
+                       machineTrustedRootPath = Path.Combine (userPath, MX.X509Stores.Names.TrustedRoot);
+                       machineIntermediateCAPath = Path.Combine (userPath, MX.X509Stores.Names.IntermediateCA);
+                       machineUntrustedPath = Path.Combine (userPath, MX.X509Stores.Names.Untrusted);
+#endif
+               }
+
+               public static bool HasStore (MonoBtlsX509StoreType type)
+               {
+#if ANDROID
+                       return false;
+#else
+                       var path = GetStorePath (type);
+                       return path != null && Directory.Exists (path);
+#endif
+               }
+
+               public static string GetStorePath (MonoBtlsX509StoreType type)
+               {
+#if ANDROID
+                       throw new NotSupportedException ();
+#else
+                       Initialize ();
+                       switch (type) {
+                       case MonoBtlsX509StoreType.MachineTrustedRoots:
+                               return machineTrustedRootPath;
+                       case MonoBtlsX509StoreType.MachineIntermediateCA:
+                               return machineIntermediateCAPath;
+                       case MonoBtlsX509StoreType.MachineUntrusted:
+                               return machineUntrustedPath;
+                       case MonoBtlsX509StoreType.UserTrustedRoots:
+                               return userTrustedRootPath;
+                       case MonoBtlsX509StoreType.UserIntermediateCA:
+                               return userIntermediateCAPath;
+                       case MonoBtlsX509StoreType.UserUntrusted:
+                               return userUntrustedPath;
+                       default:
+                               throw new NotSupportedException ();
+                       }
+#endif
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsX509StoreType.cs b/mcs/class/System/Mono.Btls/MonoBtlsX509StoreType.cs
new file mode 100644 (file)
index 0000000..22cc072
--- /dev/null
@@ -0,0 +1,40 @@
+//
+// MonoBtlsX509StoreType.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+namespace Mono.Btls
+{
+       enum MonoBtlsX509StoreType
+       {
+               Custom,
+               MachineTrustedRoots,
+               MachineIntermediateCA,
+               MachineUntrusted,
+               UserTrustedRoots,
+               UserIntermediateCA,
+               UserUntrusted
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsX509TrustKind.cs b/mcs/class/System/Mono.Btls/MonoBtlsX509TrustKind.cs
new file mode 100644 (file)
index 0000000..e207683
--- /dev/null
@@ -0,0 +1,42 @@
+//
+// MonoBtlsX509TrustKind.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+using System;
+namespace Mono.Btls
+{
+       [Flags]
+       enum MonoBtlsX509TrustKind
+       {
+               DEFAULT         = 0,
+               TRUST_CLIENT    = 1,
+               TRUST_SERVER    = 2,
+               TRUST_ALL       = 4,
+               REJECT_CLIENT   = 32,
+               REJECT_SERVER   = 64,
+               REJECT_ALL      = 128
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsX509VerifyFlags.cs b/mcs/class/System/Mono.Btls/MonoBtlsX509VerifyFlags.cs
new file mode 100644 (file)
index 0000000..628633b
--- /dev/null
@@ -0,0 +1,39 @@
+//
+// MonoBtlsX509VerifyFlags.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+using System;
+namespace Mono.Btls
+{
+       [Flags]
+       enum MonoBtlsX509VerifyFlags
+       {
+               DEFAULT         = 0,
+               CRL_CHECK       = 1,
+               CRL_CHECK_ALL   = 2,
+               X509_STRIC      = 4
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/MonoBtlsX509VerifyParam.cs b/mcs/class/System/Mono.Btls/MonoBtlsX509VerifyParam.cs
new file mode 100644 (file)
index 0000000..5c01238
--- /dev/null
@@ -0,0 +1,277 @@
+//
+// MonoBtlsX509VerifyParam.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+using System;
+using System.IO;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+
+namespace Mono.Btls
+{
+       class MonoBtlsX509VerifyParam : MonoBtlsObject
+       {
+               internal class BoringX509VerifyParamHandle : MonoBtlsHandle
+               {
+                       public BoringX509VerifyParamHandle (IntPtr handle)
+                               : base (handle, true)
+                       {
+                       }
+
+                       protected override bool ReleaseHandle ()
+                       {
+                               mono_btls_x509_verify_param_free (handle);
+                               return true;
+                       }
+               }
+
+               new internal BoringX509VerifyParamHandle Handle {
+                       get { return (BoringX509VerifyParamHandle)base.Handle; }
+               }
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_verify_param_new ();
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_verify_param_copy (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_verify_param_lookup (IntPtr name);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_verify_param_can_modify (IntPtr param);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_verify_param_set_name (IntPtr handle, IntPtr name);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_verify_param_set_host (IntPtr handle, IntPtr name, int namelen);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_verify_param_add_host (IntPtr handle, IntPtr name, int namelen);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static ulong mono_btls_x509_verify_param_get_flags (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_verify_param_set_flags (IntPtr handle, ulong flags);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static MonoBtlsX509VerifyFlags mono_btls_x509_verify_param_get_mono_flags (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_verify_param_set_mono_flags (IntPtr handle, MonoBtlsX509VerifyFlags flags);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_verify_param_set_purpose (IntPtr handle, MonoBtlsX509Purpose purpose);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_verify_param_get_depth (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_verify_param_set_depth (IntPtr handle, int depth);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static int mono_btls_x509_verify_param_set_time (IntPtr handle, long time);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static IntPtr mono_btls_x509_verify_param_get_peername (IntPtr handle);
+
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               extern static void mono_btls_x509_verify_param_free (IntPtr handle);
+
+               internal MonoBtlsX509VerifyParam ()
+                       : base (new BoringX509VerifyParamHandle (mono_btls_x509_verify_param_new ()))
+               {
+               }
+
+               internal MonoBtlsX509VerifyParam (BoringX509VerifyParamHandle handle)
+                       : base (handle)
+               {
+               }
+
+               public MonoBtlsX509VerifyParam Copy ()
+               {
+                       var copy = mono_btls_x509_verify_param_copy (Handle.DangerousGetHandle ());
+                       CheckError (copy != IntPtr.Zero);
+                       return new MonoBtlsX509VerifyParam (new BoringX509VerifyParamHandle (copy));
+               }
+
+               public static MonoBtlsX509VerifyParam GetSslClient ()
+               {
+                       return Lookup ("ssl_client", true);
+               }
+
+               public static MonoBtlsX509VerifyParam GetSslServer ()
+               {
+                       return Lookup ("ssl_server", true);
+               }
+
+               public static MonoBtlsX509VerifyParam Lookup (string name, bool fail = false)
+               {
+                       IntPtr namePtr = IntPtr.Zero;
+                       IntPtr handle = IntPtr.Zero;
+
+                       try {
+                               namePtr = Marshal.StringToHGlobalAnsi (name);
+                               handle = mono_btls_x509_verify_param_lookup (namePtr);
+                               if (handle == IntPtr.Zero) {
+                                       if (!fail)
+                                               return null;
+                                       throw new MonoBtlsException ("X509_VERIFY_PARAM_lookup() could not find '{0}'.", name);
+                               }
+
+                               return new MonoBtlsX509VerifyParam (new BoringX509VerifyParamHandle (handle));
+                       } finally {
+                               if (namePtr != IntPtr.Zero)
+                                       Marshal.FreeHGlobal (namePtr);
+                       }
+               }
+
+               public bool CanModify {
+                       get {
+                               return mono_btls_x509_verify_param_can_modify (Handle.DangerousGetHandle ()) != 0;
+                       }
+               }
+
+               void WantToModify ()
+               {
+                       if (!CanModify)
+                               throw new MonoBtlsException ("Attempting to modify read-only MonoBtlsX509VerifyParam instance.");
+               }
+
+               public void SetName (string name)
+               {
+                       WantToModify ();
+                       IntPtr namePtr = IntPtr.Zero;
+                       try {
+                               namePtr = Marshal.StringToHGlobalAnsi (name);
+                               var ret = mono_btls_x509_verify_param_set_name (
+                                       Handle.DangerousGetHandle (), namePtr);
+                               CheckError (ret);
+                       } finally {
+                               if (namePtr != IntPtr.Zero)
+                                       Marshal.FreeHGlobal (namePtr);
+                       }
+               }
+
+               public void SetHost (string name)
+               {
+                       WantToModify ();
+                       IntPtr namePtr = IntPtr.Zero;
+                       try {
+                               namePtr = Marshal.StringToHGlobalAnsi (name);
+                               var ret = mono_btls_x509_verify_param_set_host (
+                                       Handle.DangerousGetHandle (), namePtr, name.Length);
+                               CheckError (ret);
+                       } finally {
+                               if (namePtr != IntPtr.Zero)
+                                       Marshal.FreeHGlobal (namePtr);
+                       }
+               }
+
+               public void AddHost (string name)
+               {
+                       WantToModify ();
+                       IntPtr namePtr = IntPtr.Zero;
+                       try {
+                               namePtr = Marshal.StringToHGlobalAnsi (name);
+                               var ret = mono_btls_x509_verify_param_add_host (
+                                       Handle.DangerousGetHandle (), namePtr, name.Length);
+                               CheckError (ret);
+                       } finally {
+                               if (namePtr != IntPtr.Zero)
+                                       Marshal.FreeHGlobal (namePtr);
+                       }
+               }
+
+               public ulong GetFlags ()
+               {
+                       return mono_btls_x509_verify_param_get_flags (Handle.DangerousGetHandle ());
+               }
+
+               public void SetFlags (ulong flags)
+               {
+                       WantToModify ();
+                       var ret = mono_btls_x509_verify_param_set_flags (
+                               Handle.DangerousGetHandle (), flags);
+                       CheckError (ret);
+               }
+
+               public MonoBtlsX509VerifyFlags GetMonoFlags ()
+               {
+                       return mono_btls_x509_verify_param_get_mono_flags (
+                               Handle.DangerousGetHandle ());
+               }
+
+               public void SetMonoFlags (MonoBtlsX509VerifyFlags flags)
+               {
+                       WantToModify ();
+                       var ret = mono_btls_x509_verify_param_set_mono_flags (
+                               Handle.DangerousGetHandle (), flags);
+                       CheckError (ret);
+               }
+
+               public void SetPurpose (MonoBtlsX509Purpose purpose)
+               {
+                       WantToModify ();
+                       var ret = mono_btls_x509_verify_param_set_purpose (
+                               Handle.DangerousGetHandle (), purpose);
+                       CheckError (ret);
+               }
+
+               public int GetDepth ()
+               {
+                       return mono_btls_x509_verify_param_get_depth (Handle.DangerousGetHandle ());
+               }
+
+               public void SetDepth (int depth)
+               {
+                       WantToModify ();
+                       var ret = mono_btls_x509_verify_param_set_depth (
+                               Handle.DangerousGetHandle (), depth);
+                       CheckError (ret);
+               }
+
+               public void SetTime (DateTime time)
+               {
+                       WantToModify ();
+                       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);
+                       CheckError (ret);
+               }
+
+               public string GetPeerName ()
+               {
+                       var peer = mono_btls_x509_verify_param_get_peername (Handle.DangerousGetHandle ());
+                       if (peer == IntPtr.Zero)
+                               return null;
+                       return Marshal.PtrToStringAnsi (peer);
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/X509CertificateImplBtls.cs b/mcs/class/System/Mono.Btls/X509CertificateImplBtls.cs
new file mode 100644 (file)
index 0000000..ef077b8
--- /dev/null
@@ -0,0 +1,495 @@
+//
+// X509CertificateImplBtls.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#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 Mono.Security.Cryptography;
+
+namespace Mono.Btls
+{
+       class X509CertificateImplBtls : X509Certificate2Impl
+       {
+               MonoBtlsX509 x509;
+               MonoBtlsKey privateKey;
+               X500DistinguishedName subjectName;
+               X500DistinguishedName issuerName;
+               X509CertificateImplCollection intermediateCerts;
+               PublicKey publicKey;
+               bool archived;
+               bool disallowFallback;
+
+               internal X509CertificateImplBtls (bool disallowFallback = false)
+               {
+                       this.disallowFallback = disallowFallback;
+               }
+
+               internal X509CertificateImplBtls (MonoBtlsX509 x509, bool disallowFallback = false)
+               {
+                       this.disallowFallback = disallowFallback;
+                       this.x509 = x509.Copy ();
+               }
+
+               X509CertificateImplBtls (X509CertificateImplBtls other)
+               {
+                       disallowFallback = other.disallowFallback;
+                       x509 = other.x509 != null ? other.x509.Copy () : null;
+                       privateKey = other.privateKey != null ? other.privateKey.Copy () : null;
+                       if (other.intermediateCerts != null)
+                               intermediateCerts = other.intermediateCerts.Clone ();
+               }
+
+               internal X509CertificateImplBtls (byte[] data, MonoBtlsX509Format format, bool disallowFallback = false)
+               {
+                       this.disallowFallback = disallowFallback;
+                       x509 = MonoBtlsX509.LoadFromData (data, format);
+               }
+
+               public override bool IsValid {
+                       get { return x509 != null && x509.IsValid; }
+               }
+
+               public override IntPtr Handle {
+                       get { return x509.Handle.DangerousGetHandle (); }
+               }
+
+               public override IntPtr GetNativeAppleCertificate ()
+               {
+                       return IntPtr.Zero;
+               }
+
+               internal MonoBtlsX509 X509 {
+                       get {
+                               ThrowIfContextInvalid ();
+                               return x509;
+                       }
+               }
+
+               internal MonoBtlsKey NativePrivateKey {
+                       get {
+                               ThrowIfContextInvalid ();
+                               return privateKey;
+                       }
+               }
+
+               public override X509CertificateImpl Clone ()
+               {
+                       ThrowIfContextInvalid ();
+                       return new X509CertificateImplBtls (this);
+               }
+
+               public override bool Equals (X509CertificateImpl other, out bool result)
+               {
+                       var otherBoringImpl = other as X509CertificateImplBtls;
+                       if (otherBoringImpl == null) {
+                               result = false;
+                               return false;
+                       }
+
+                       result = MonoBtlsX509.Compare (X509, otherBoringImpl.X509) == 0;
+                       return true;
+               }
+
+               protected override byte[] GetCertHash (bool lazy)
+               {
+                       return X509.GetCertHash ();
+               }
+
+               public override byte[] GetRawCertData ()
+               {
+                       return X509.GetRawData (MonoBtlsX509Format.DER);
+               }
+
+               public override string GetSubjectName (bool legacyV1Mode)
+               {
+                       if (legacyV1Mode)
+                               return SubjectName.Decode (X500DistinguishedNameFlags.None);
+                       return SubjectName.Name;
+               }
+
+               public override string GetIssuerName (bool legacyV1Mode)
+               {
+                       if (legacyV1Mode)
+                               return IssuerName.Decode (X500DistinguishedNameFlags.None);
+                       return IssuerName.Name;
+               }
+
+               public override DateTime GetValidFrom ()
+               {
+                       return X509.GetNotBefore ().ToLocalTime ();
+               }
+
+               public override DateTime GetValidUntil ()
+               {
+                       return X509.GetNotAfter ().ToLocalTime ();
+               }
+
+               public override byte[] GetPublicKey ()
+               {
+                       return X509.GetPublicKeyData ();
+               }
+
+               public override byte[] GetSerialNumber ()
+               {
+                       return X509.GetSerialNumber (true);
+               }
+
+               public override string GetKeyAlgorithm ()
+               {
+                       return PublicKey.Oid.Value;
+               }
+
+               public override byte[] GetKeyAlgorithmParameters ()
+               {
+                       return PublicKey.EncodedParameters.RawData;
+               }
+
+               public override byte[] Export (X509ContentType contentType, byte[] password)
+               {
+                       ThrowIfContextInvalid ();
+
+                       switch (contentType) {
+                       case X509ContentType.Cert:
+                               return GetRawCertData ();
+                       case X509ContentType.Pfx: // this includes Pkcs12
+                               // TODO
+                               throw new NotSupportedException ();
+                       case X509ContentType.SerializedCert:
+                               // TODO
+                               throw new NotSupportedException ();
+                       default:
+                               string msg = Locale.GetText ("This certificate format '{0}' cannot be exported.", contentType);
+                               throw new CryptographicException (msg);
+                       }
+               }
+
+               internal override X509CertificateImplCollection IntermediateCertificates {
+                       get { return intermediateCerts; }
+               }
+
+               public override string ToString (bool full)
+               {
+                       ThrowIfContextInvalid ();
+
+                       if (!full) {
+                               var summary = GetSubjectName (false);
+                               return string.Format ("[X509Certificate: {0}]", summary);
+                       }
+
+                       string nl = Environment.NewLine;
+                       StringBuilder sb = new StringBuilder ();
+                       sb.AppendFormat ("[Subject]{0}  {1}{0}{0}", nl, GetSubjectName (false));
+
+                       sb.AppendFormat ("[Issuer]{0}  {1}{0}{0}", nl, GetIssuerName (false));
+                       sb.AppendFormat ("[Not Before]{0}  {1}{0}{0}", nl, GetValidFrom ().ToLocalTime ());
+                       sb.AppendFormat ("[Not After]{0}  {1}{0}{0}", nl, GetValidUntil ().ToLocalTime ());
+                       sb.AppendFormat ("[Thumbprint]{0}  {1}{0}", nl, X509Helper.ToHexString (GetCertHash ()));
+
+                       sb.Append (nl);
+                       return sb.ToString ();
+               }
+
+               protected override void Dispose (bool disposing)
+               {
+                       if (x509 != null) {
+                               x509.Dispose ();
+                               x509 = null;
+                       }
+               }
+
+#region X509Certificate2Impl
+
+               X509Certificate2Impl fallback;
+
+               void MustFallback ()
+               {
+                       if (disallowFallback)
+                               throw new InvalidOperationException ();
+                       if (fallback != null)
+                               return;
+                       fallback = X509Helper2.Import (GetRawCertData (), null, X509KeyStorageFlags.DefaultKeySet, true);
+               }
+
+               internal override X509Certificate2Impl FallbackImpl {
+                       get {
+                               MustFallback ();
+                               return fallback;
+                       }
+               }
+
+               [MonoTODO]
+               public override bool Archived {
+                       get {
+                               ThrowIfContextInvalid ();
+                               return archived;
+                       }
+                       set {
+                               ThrowIfContextInvalid ();
+                               archived = value;
+                       }
+               }
+
+               public override X509ExtensionCollection Extensions {
+                       get { return FallbackImpl.Extensions; }
+               }
+
+               public override bool HasPrivateKey {
+                       get { return privateKey != null; }
+               }
+
+               public override X500DistinguishedName IssuerName {
+                       get {
+                               ThrowIfContextInvalid ();
+                               if (issuerName == null) {
+                                       using (var xname = x509.GetIssuerName ()) {
+                                               var encoding = xname.GetRawData (false);
+                                               var canonEncoding = xname.GetRawData (true);
+                                               var name = MonoBtlsUtils.FormatName (xname, true, ", ", true);
+                                               issuerName = new X500DistinguishedName (encoding, canonEncoding, name);
+                                       }
+                               }
+                               return issuerName;
+                       }
+               }
+
+               public override AsymmetricAlgorithm PrivateKey {
+                       get {
+                               if (privateKey == null || !privateKey.IsRsa)
+                                       return null;
+                               var bytes = privateKey.GetBytes (true);
+                               return PKCS8.PrivateKeyInfo.DecodeRSA (bytes);
+                       }
+                       set { FallbackImpl.PrivateKey = value; }
+               }
+
+               public override PublicKey PublicKey {
+                       get {
+                               ThrowIfContextInvalid ();
+                               if (publicKey == null) {
+                                       var keyAsn = X509.GetPublicKeyAsn1 ();
+                                       var keyParamAsn = X509.GetPublicKeyParameters ();
+                                       publicKey = new PublicKey (keyAsn.Oid, keyParamAsn, keyAsn);
+                               }
+                               return publicKey;
+                       }
+               }
+
+               public override Oid SignatureAlgorithm {
+                       get {
+                               ThrowIfContextInvalid ();
+                               return X509.GetSignatureAlgorithm ();
+                       }
+               }
+
+               public override X500DistinguishedName SubjectName {
+                       get {
+                               ThrowIfContextInvalid ();
+                               if (subjectName == null) {
+                                       using (var xname = x509.GetSubjectName ()) {
+                                               var encoding = xname.GetRawData (false);
+                                               var canonEncoding = xname.GetRawData (true);
+                                               var name = MonoBtlsUtils.FormatName (xname, true, ", ", true);
+                                               subjectName = new X500DistinguishedName (encoding, canonEncoding, name);
+                                       }
+                               }
+                               return subjectName;
+                       }
+               }
+
+               public override int Version {
+                       get { return X509.GetVersion (); }
+               }
+
+               public override string GetNameInfo (X509NameType nameType, bool forIssuer)
+               {
+                       return FallbackImpl.GetNameInfo (nameType, forIssuer);
+               }
+
+               public override void Import (byte[] data, string password, X509KeyStorageFlags keyStorageFlags)
+               {
+                       if (password == null) {
+                               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 ()) {
+                               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 ();
+                               if (pkcs12.Count > 1) {
+                                       intermediateCerts = new X509CertificateImplCollection ();
+                                       for (int i = 0; i < pkcs12.Count; i++) {
+                                               using (var ic = pkcs12.GetCertificate (i)) {
+                                                       if (MonoBtlsX509.Compare (ic, x509) == 0)
+                                                               continue;
+                                                       var impl = new X509CertificateImplBtls (ic, true);
+                                                       intermediateCerts.Add (impl, true);
+                                               }
+                                       }
+                               }
+                       }
+               }
+
+               public override byte[] Export (X509ContentType contentType, string 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)
+               {
+                       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 ()
+               {
+                       if (x509 != null) {
+                               x509.Dispose ();
+                               x509 = null;
+                       }
+                       if (privateKey != null) {
+                               privateKey = null;
+                               privateKey = null;
+                       }
+                       subjectName = null;
+                       issuerName = null;
+                       archived = false;
+                       publicKey = null;
+                       intermediateCerts = null;
+                       if (fallback != null)
+                               fallback.Reset ();
+               }
+
+#endregion
+       }
+}
+#endif
diff --git a/mcs/class/System/Mono.Btls/X509ChainImplBtls.cs b/mcs/class/System/Mono.Btls/X509ChainImplBtls.cs
new file mode 100644 (file)
index 0000000..79a985c
--- /dev/null
@@ -0,0 +1,172 @@
+//
+// X509ChainImplBtls.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+#if SECURITY_DEP
+using System;
+using System.Text;
+using System.Security;
+using System.Security.Cryptography;
+using System.Security.Cryptography.X509Certificates;
+using MX = Mono.Security.X509;
+
+namespace Mono.Btls
+{
+       class X509ChainImplBtls : X509ChainImpl
+       {
+               MonoBtlsX509StoreCtx storeCtx;
+               MonoBtlsX509Chain chain;
+               MonoBtlsX509Chain untrustedChain;
+               X509ChainElementCollection elements;
+               X509Certificate2Collection untrusted;
+               X509Certificate2[] certificates;
+               X509ChainPolicy policy;
+
+               internal X509ChainImplBtls (MonoBtlsX509Chain chain)
+               {
+                       this.chain = chain.Copy ();
+                       policy = new X509ChainPolicy ();
+               }
+
+               internal X509ChainImplBtls (MonoBtlsX509StoreCtx storeCtx)
+               {
+                       this.storeCtx = storeCtx.Copy ();
+                       this.chain = storeCtx.GetChain ();
+
+                       policy = new X509ChainPolicy ();
+
+                       untrustedChain = storeCtx.GetUntrusted ();
+
+                       if (untrustedChain != null) {
+                               untrusted = new X509Certificate2Collection ();
+                               policy.ExtraStore = untrusted;
+                               for (int i = 0; i < untrustedChain.Count; i++) {
+                                       using (var cert = untrustedChain.GetCertificate (i))
+                                       using (var impl = new X509CertificateImplBtls (cert))
+                                               untrusted.Add (new X509Certificate2 (impl));
+                               }
+                       }
+               }
+
+               internal X509ChainImplBtls ()
+               {
+                       chain = new MonoBtlsX509Chain ();
+                       elements = new X509ChainElementCollection ();
+                       policy = new X509ChainPolicy ();
+               }
+
+               public override bool IsValid {
+                       get { return chain != null && chain.IsValid; }
+               }
+
+               public override IntPtr Handle {
+                       get { return chain.Handle.DangerousGetHandle (); }
+               }
+
+               internal MonoBtlsX509Chain Chain {
+                       get {
+                               ThrowIfContextInvalid ();
+                               return chain;
+                       }
+               }
+
+               internal MonoBtlsX509StoreCtx StoreCtx {
+                       get {
+                               ThrowIfContextInvalid ();
+                               return storeCtx;
+                       }
+               }
+
+               public override X509ChainElementCollection ChainElements {
+                       get {
+                               ThrowIfContextInvalid ();
+                               if (elements != null)
+                                       return elements;
+
+                               elements = new X509ChainElementCollection ();
+                               certificates = new X509Certificate2 [chain.Count];
+
+                               for (int i = 0; i < certificates.Length; i++) {
+                                       var cert = chain.GetCertificate (i);
+                                       var impl = new X509CertificateImplBtls (cert);
+                                       certificates [i] = new X509Certificate2 (impl);
+                                       elements.Add (certificates [i]);
+                               }
+
+                               return elements;
+                       }
+               }
+
+               public override X509ChainPolicy ChainPolicy {
+                       get { return policy; }
+                       set { policy = value; }
+               }
+
+               public override X509ChainStatus[] ChainStatus {
+                       get { throw new NotImplementedException (); }
+               }
+
+               public override bool Build (X509Certificate2 certificate)
+               {
+                       return false;
+               }
+
+               public override void Reset ()
+               {
+                       if (certificates != null) {
+                               foreach (var certificate in certificates)
+                                       certificate.Dispose ();
+                               certificates = null;
+                       }
+                       if (elements != null) {
+                               elements.Clear ();
+                               elements = null;
+                       }
+               }
+
+               protected override void Dispose (bool disposing)
+               {
+                       if (disposing) {
+                               if (chain != null) {
+                                       chain.Dispose ();
+                                       chain = null;
+                               }
+                               if (storeCtx != null) {
+                                       storeCtx.Dispose ();
+                                       storeCtx = null;
+                               }
+                               if (untrustedChain != null) {
+                                       untrustedChain.Dispose ();
+                                       untrustedChain = null;
+                               }
+                               if (untrusted != null) {
+                                       foreach (var cert in untrusted)
+                                               cert.Dispose ();
+                               }
+                       }
+                       base.Dispose (disposing);
+               }
+       }
+}
+#endif
index 7827d97600b108629470fa47c64858aabfae5d79..5f90ffe2b82241f4390b9c112c0c36c0e0abaeb9 100644 (file)
@@ -99,7 +99,8 @@ namespace Mono.Net.Security
                Complete,
                WantRead,
                WantWrite,
-               ReadDone
+               ReadDone,
+               FinishWrite
        }
 
        class AsyncProtocolRequest
@@ -160,9 +161,16 @@ namespace Mono.Net.Security
                        Debug ("ResetRead: {0} {1}", oldStatus, Status);
                }
 
+               internal void ResetWrite ()
+               {
+                       var oldStatus = (AsyncOperationStatus)Interlocked.CompareExchange (ref Status, (int)AsyncOperationStatus.Complete, (int)AsyncOperationStatus.WantWrite);
+                       Debug ("ResetWrite: {0} {1}", oldStatus, Status);
+               }
+
                internal void RequestWrite ()
                {
                        var oldStatus = (AsyncOperationStatus)Interlocked.CompareExchange (ref Status, (int)AsyncOperationStatus.WantWrite, (int)AsyncOperationStatus.Running);
+                       Debug ("RequestWrite: {0} {1}", oldStatus, Status);
                        if (oldStatus == AsyncOperationStatus.Running)
                                return;
                        else if (oldStatus != AsyncOperationStatus.WantRead && oldStatus != AsyncOperationStatus.WantWrite)
@@ -209,7 +217,19 @@ namespace Mono.Net.Security
 
                                status = ProcessOperation (status);
 
-                               var oldStatus = (AsyncOperationStatus)Interlocked.CompareExchange (ref Status, (int)status, (int)AsyncOperationStatus.Running);
+                               Debug ("ProcessOperation done: {0}", status);
+
+                               AsyncOperationStatus oldStatus;
+                               if (status == AsyncOperationStatus.Complete) {
+                                       oldStatus = (AsyncOperationStatus)Interlocked.CompareExchange (ref Status, (int)AsyncOperationStatus.FinishWrite, (int)AsyncOperationStatus.WantWrite);
+                                       if (oldStatus == AsyncOperationStatus.WantWrite) {
+                                               // We are done, but still need to flush the write queue.
+                                               status = AsyncOperationStatus.FinishWrite;
+                                               continue;
+                                       }
+                               }
+
+                               oldStatus = (AsyncOperationStatus)Interlocked.CompareExchange (ref Status, (int)status, (int)AsyncOperationStatus.Running);
                                Debug ("ProcessOperation done: {0} -> {1}", oldStatus, status);
 
                                if (oldStatus != AsyncOperationStatus.Running) {
@@ -243,7 +263,9 @@ namespace Mono.Net.Security
                                else
                                        return AsyncOperationStatus.WantRead;
                        } else if (status == AsyncOperationStatus.WantWrite) {
+                               Debug ("ProcessOperation - want write");
                                Parent.InnerWrite ();
+                               Debug ("ProcessOperation - want write done");
                                return AsyncOperationStatus.Continue;
                        } else if (status == AsyncOperationStatus.Initialize || status == AsyncOperationStatus.Continue) {
                                Debug ("ProcessOperation - continue");
@@ -255,6 +277,11 @@ namespace Mono.Net.Security
                                status = Operation (this, status);
                                Debug ("ProcessOperation - read done: {0}", status);
                                return status;
+                       } else if (status == AsyncOperationStatus.FinishWrite) {
+                               Debug ("ProcessOperation - finish write");
+                               Parent.InnerWrite ();
+                               Debug ("ProcessOperation - finish write done");
+                               return AsyncOperationStatus.Complete;
                        }
 
                        throw new InvalidOperationException ();
index 5d2812d2738e4c51c72af55564a3e3c95356e0c4..b1921208fc85962e2152d26a75af67518eb98e37 100644 (file)
@@ -44,8 +44,6 @@ using Mono.Security.Interface;
 using MSX = Mono.Security.X509;
 using Mono.Security.X509.Extensions;
 #endif
-using XX509CertificateCollection = System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-using XX509Chain = System.Security.Cryptography.X509Certificates.X509Chain;
 
 using System;
 using System.Net;
@@ -77,7 +75,7 @@ namespace Mono.Net.Security
                readonly MonoTlsStream tlsStream;
                readonly HttpWebRequest request;
 
-               internal static ICertificateValidator GetDefaultValidator (MonoTlsProvider provider, MonoTlsSettings settings)
+               internal static ICertificateValidator GetInternalValidator (MonoTlsProvider provider, MonoTlsSettings settings)
                {
                        if (settings == null)
                                return new ChainValidationHelper (provider, null, false, null, null);
@@ -86,6 +84,16 @@ namespace Mono.Net.Security
                        return new ChainValidationHelper (provider, settings, false, null, null);
                }
 
+               internal static ICertificateValidator GetDefaultValidator (MonoTlsSettings settings)
+               {
+                       var provider = MonoTlsProviderFactory.GetProvider ();
+                       if (settings == null)
+                               return new ChainValidationHelper (provider, null, false, null, null);
+                       if (settings.CertificateValidator != null)
+                               throw new NotSupportedException ();
+                       return new ChainValidationHelper (provider, settings, false, null, null);
+               }
+
 #region SslStream support
 
                /*
@@ -138,6 +146,8 @@ namespace Mono.Net.Security
                                settings = MonoTlsSettings.CopyDefaultSettings ();
                        if (cloneSettings)
                                settings = settings.CloneWithValidator (this);
+                       if (provider == null)
+                               provider = MonoTlsProviderFactory.GetProvider ();
 
                        this.provider = provider;
                        this.settings = settings;
@@ -172,7 +182,7 @@ namespace Mono.Net.Security
                                certValidationCallback = ServicePointManager.ServerCertValidationCallback;
                }
 
-               static X509Certificate DefaultSelectionCallback (string targetHost, XX509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers)
+               static X509Certificate DefaultSelectionCallback (string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers)
                {
                        X509Certificate clientCertificate;
                        if (localCertificates == null || localCertificates.Count == 0)
@@ -195,7 +205,7 @@ namespace Mono.Net.Security
                }
 
                public bool SelectClientCertificate (
-                       string targetHost, XX509CertificateCollection localCertificates, X509Certificate remoteCertificate,
+                       string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate,
                        string[] acceptableIssuers, out X509Certificate clientCertificate)
                {
                        if (certSelectionCallback == null) {
@@ -207,7 +217,7 @@ namespace Mono.Net.Security
                }
 
                internal X509Certificate SelectClientCertificate (
-                       string targetHost, XX509CertificateCollection localCertificates, X509Certificate remoteCertificate,
+                       string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate,
                        string[] acceptableIssuers)
                {
                        if (certSelectionCallback == null)
@@ -217,7 +227,7 @@ namespace Mono.Net.Security
 
                internal bool ValidateClientCertificate (X509Certificate certificate, MonoSslPolicyErrors errors)
                {
-                       var certs = new XX509CertificateCollection ();
+                       var certs = new X509CertificateCollection ();
                        certs.Add (new X509Certificate2 (certificate.GetRawCertData ()));
 
                        var result = ValidateChain (string.Empty, true, certificate, null, certs, (SslPolicyErrors)errors);
@@ -227,7 +237,7 @@ namespace Mono.Net.Security
                        return result.Trusted && !result.UserDenied;
                }
 
-               public ValidationResult ValidateCertificate (string host, bool serverMode, XX509CertificateCollection certs)
+               public ValidationResult ValidateCertificate (string host, bool serverMode, X509CertificateCollection certs)
                {
                        try {
                                X509Certificate leaf;
@@ -246,10 +256,9 @@ namespace Mono.Net.Security
                        }
                }
 
-               public ValidationResult ValidateCertificate (string host, bool serverMode, X509Certificate leaf, XX509Chain xchain)
+               public ValidationResult ValidateCertificate (string host, bool serverMode, X509Certificate leaf, X509Chain chain)
                {
                        try {
-                               var chain = xchain;
                                var result = ValidateChain (host, serverMode, leaf, chain, null, 0);
                                if (tlsStream != null)
                                        tlsStream.CertificateValidationFailed = result == null || !result.Trusted || result.UserDenied;
@@ -262,7 +271,7 @@ namespace Mono.Net.Security
                }
 
                ValidationResult ValidateChain (string host, bool server, X509Certificate leaf,
-                                               X509Chain chain, XX509CertificateCollection certs,
+                                               X509Chain chain, X509CertificateCollection certs,
                                                SslPolicyErrors errors)
                {
                        var oldChain = chain;
@@ -281,7 +290,7 @@ namespace Mono.Net.Security
                }
 
                ValidationResult ValidateChain (string host, bool server, X509Certificate leaf,
-                                               ref X509Chain chain, XX509CertificateCollection certs,
+                                               ref X509Chain chain, X509CertificateCollection certs,
                                                SslPolicyErrors errors)
                {
                        // user_denied is true if the user callback is called and returns false
@@ -305,6 +314,13 @@ namespace Mono.Net.Security
                                return new ValidationResult (result, user_denied, 0, (MonoSslPolicyErrors)errors);
                        }
 
+                       // Ignore port number when validating certificates.
+                       if (!string.IsNullOrEmpty (host)) {
+                               var pos = host.IndexOf (':');
+                               if (pos > 0)
+                                       host = host.Substring (0, pos);
+                       }
+
                        ICertificatePolicy policy = ServicePointManager.GetLegacyCertificatePolicy ();
 
                        int status11 = 0; // Error code passed to the obsolete ICertificatePolicy callback
@@ -315,19 +331,9 @@ namespace Mono.Net.Security
                                        wantsChain = true;
                        }
 
-                       bool providerValidated = false;
-                       if (provider != null && provider.HasCustomSystemCertificateValidator) {
-                               var xerrors = (MonoSslPolicyErrors)errors;
-                               var xchain = chain;
-                               providerValidated = provider.InvokeSystemCertificateValidator (this, host, server, certs, wantsChain, ref xchain, out result, ref xerrors, ref status11);
-                               chain = xchain;
-                               errors = (SslPolicyErrors)xerrors;
-                       } else if (wantsChain) {
-                               chain = SystemCertificateValidator.CreateX509Chain (certs);
-                       }
-
-                       if (!providerValidated)
-                               result = SystemCertificateValidator.Evaluate (settings, host, certs, chain, ref errors, ref status11);
+                       var xerrors = (MonoSslPolicyErrors)errors;
+                       result = provider.ValidateCertificate (this, host, server, certs, wantsChain, ref chain, ref xerrors, ref status11);
+                       errors = (SslPolicyErrors)xerrors;
 
                        if (policy != null && (!(policy is DefaultCertificatePolicy) || certValidationCallback == null)) {
                                ServicePoint sp = null;
@@ -353,9 +359,8 @@ namespace Mono.Net.Security
                        return new ValidationResult (result, user_denied, status11, (MonoSslPolicyErrors)errors);
                }
 
-               public bool InvokeSystemValidator (string targetHost, bool serverMode, XX509CertificateCollection certificates, XX509Chain xchain, ref MonoSslPolicyErrors xerrors, ref int status11)
+               bool InvokeSystemValidator (string targetHost, bool serverMode, X509CertificateCollection certificates, X509Chain chain, ref MonoSslPolicyErrors xerrors, ref int status11)
                {
-                       X509Chain chain = xchain;
                        var errors = (SslPolicyErrors)xerrors;
                        var result = SystemCertificateValidator.Evaluate (settings, targetHost, certificates, chain, ref errors, ref status11);
                        xerrors = (MonoSslPolicyErrors)errors;
index 50b4cd9c8c460de1aee7dd57382fe1eb0b204326..942b5065ce90cf35c4fec30c7d5371f13b73e794 100644 (file)
@@ -34,7 +34,6 @@ using MonoSecurity::Mono.Security.Interface;
 #else
 using Mono.Security.Interface;
 #endif
-using XX509CertificateCollection = System.Security.Cryptography.X509Certificates.X509CertificateCollection;
 #endif
 
 using System;
@@ -70,12 +69,6 @@ namespace Mono.Net.Security
                IMonoSslStream CreateSslStream (
                        Stream innerStream, bool leaveInnerStreamOpen,
                        MonoTlsSettings settings);
-
-               IMonoTlsContext CreateTlsContext (
-                       string hostname, bool serverMode, TlsProtocols protocolFlags,
-                       X509Certificate serverCertificate, XX509CertificateCollection clientCertificates,
-                       bool remoteCertRequired, bool checkCertName, bool checkCertRevocationStatus,
-                       MonoEncryptionPolicy encryptionPolicy, MonoTlsSettings settings);
 #endif
        }
 }
index 1a6672f6c5c36f634b575715a611d14148e86c0a..7ec9a86813977d98ddcf63b3d85b52cfdf69deb2 100644 (file)
@@ -91,7 +91,7 @@ namespace Mono.Net.Security.Private
                        : base (innerStream, leaveInnerStreamOpen)
                {
                        this.provider = provider;
-                       certificateValidator = ChainValidationHelper.GetDefaultValidator (provider, settings);
+                       certificateValidator = ChainValidationHelper.GetInternalValidator (provider, settings);
                }
                #endregion // Constructors
 
diff --git a/mcs/class/System/Mono.Net.Security/LegacyTlsProvider.cs b/mcs/class/System/Mono.Net.Security/LegacyTlsProvider.cs
new file mode 100644 (file)
index 0000000..7048f44
--- /dev/null
@@ -0,0 +1,100 @@
+//
+// LegacyTlsProvider.cs
+//
+// Author:
+//       Martin Baulig <martin.baulig@xamarin.com>
+//
+// Copyright (c) 2015 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.
+#if SECURITY_DEP
+#if MONO_SECURITY_ALIAS
+extern alias MonoSecurity;
+#endif
+
+#if MONO_SECURITY_ALIAS
+using MSI = MonoSecurity::Mono.Security.Interface;
+#else
+using MSI = Mono.Security.Interface;
+#endif
+
+using System;
+using System.IO;
+using System.Net;
+using System.Net.Security;
+using System.Security.Cryptography.X509Certificates;
+using System.Security.Authentication;
+
+namespace Mono.Net.Security
+{
+       /*
+        * Strictly private - do not use outside the Mono.Net.Security directory.
+        */
+       class LegacyTlsProvider : MSI.MonoTlsProvider
+       {
+               static readonly Guid id = new Guid ("809e77d5-56cc-4da8-b9f0-45e65ba9cceb");
+
+               public override Guid ID {
+                       get { return id; }
+               }
+
+               public override string Name {
+                       get { return "legacy"; }
+               }
+
+               public override bool SupportsSslStream {
+                       get { return true; }
+               }
+
+               public override bool SupportsConnectionInfo {
+                       get { return false; }
+               }
+
+               public override bool SupportsMonoExtensions {
+                       get { return false; }
+               }
+
+               public override SslProtocols SupportedProtocols {
+                       get { return SslProtocols.Tls; }
+               }
+
+               public override MSI.IMonoSslStream CreateSslStream (
+                       Stream innerStream, bool leaveInnerStreamOpen,
+                       MSI.MonoTlsSettings settings = null)
+               {
+                       var impl = new Private.LegacySslStream (innerStream, leaveInnerStreamOpen, this, settings);
+                       return new Private.MonoSslStreamImpl (impl);
+               }
+
+               internal override bool ValidateCertificate (
+                       MSI.ICertificateValidator2 validator, string targetHost, bool serverMode,
+                       X509CertificateCollection certificates, bool wantsChain, ref X509Chain chain,
+                       ref MSI.MonoSslPolicyErrors errors, ref int status11)
+               {
+                       if (wantsChain)
+                               chain = SystemCertificateValidator.CreateX509Chain (certificates);
+                       var xerrors = (SslPolicyErrors)errors;
+                       var result = SystemCertificateValidator.Evaluate (validator.Settings, targetHost, certificates, chain, ref xerrors, ref status11);
+                       errors = (MSI.MonoSslPolicyErrors)xerrors;
+                       return result;
+               }
+       }
+}
+#endif
+
index 8701ffe92e691624893f3f2643f2d22635bae41a..cf1082618e625432d5df952fbbe10d769f8591b5 100644 (file)
@@ -660,6 +660,7 @@ namespace Mono.Net.Security
                        if (wantMore || writeBuffer.Size > 0)
                                return AsyncOperationStatus.WantWrite;
 
+                       asyncRequest.ResetWrite ();
                        asyncRequest.UserResult = asyncRequest.CurrentSize;
                        return AsyncOperationStatus.Complete;
                }
index 677a5107697810aca010c8c16aff84d06ba8229d..f051a5fcbc2c04ca406f2edebcf63019cc0af693 100644 (file)
@@ -54,7 +54,7 @@ namespace Mono.Net.Security
                        this.clientCertificates = clientCertificates;
                        this.askForClientCert = askForClientCert;
 
-                       certificateValidator = CertificateValidationHelper.GetDefaultValidator (
+                       certificateValidator = CertificateValidationHelper.GetInternalValidator (
                                parent.Settings, parent.Provider);
                }
 
@@ -159,30 +159,35 @@ namespace Mono.Net.Security
 
                public abstract void Close ();
 
-               protected ValidationResult ValidateCertificate (X509Certificate leaf, X509Chain chain)
+               protected bool ValidateCertificate (X509Certificate leaf, X509Chain chain)
                {
-                       return certificateValidator.ValidateCertificate (
-                               targetHost, serverMode, leaf, chain);
+                       var result = certificateValidator.ValidateCertificate (TargetHost, IsServer, leaf, chain);
+                       return result != null && result.Trusted && !result.UserDenied;
                }
 
-               protected X509Certificate SelectClientCertificate (string[] acceptableIssuers)
-                {
-                        X509Certificate certificate;
-                        var selected = certificateValidator.SelectClientCertificate (
-                               targetHost, clientCertificates, serverCertificate,
-                               null, out certificate);
-                        if (selected)
-                                return certificate;
+               protected bool ValidateCertificate (X509CertificateCollection certificates)
+               {
+                       var result = certificateValidator.ValidateCertificate (TargetHost, IsServer, certificates);
+                       return result != null && result.Trusted && !result.UserDenied;
+               }
 
-                        if (clientCertificates == null || clientCertificates.Count == 0)
-                                return null;
+               protected X509Certificate SelectClientCertificate (X509Certificate serverCertificate, string[] acceptableIssuers)
+               {
+                       X509Certificate certificate;
+                       var selected = certificateValidator.SelectClientCertificate (
+                               TargetHost, ClientCertificates, serverCertificate, acceptableIssuers, out certificate);
+                       if (selected)
+                               return certificate;
 
-                        if (clientCertificates.Count == 1)
-                                return clientCertificates [0];
+                       if (clientCertificates == null || clientCertificates.Count == 0)
+                               return null;
 
-                        // FIXME: select one.
-                        throw new NotImplementedException ();
-                }
+                       if (clientCertificates.Count == 1)
+                               return clientCertificates [0];
+
+                       // FIXME: select onne.
+                       throw new NotImplementedException ();
+               }
 
                public void Dispose ()
                {
diff --git a/mcs/class/System/Mono.Net.Security/MonoLegacyTlsProvider.cs b/mcs/class/System/Mono.Net.Security/MonoLegacyTlsProvider.cs
deleted file mode 100644 (file)
index 9a97195..0000000
+++ /dev/null
@@ -1,106 +0,0 @@
-//
-// MonoLegacyTlsProvider.cs
-//
-// Author:
-//       Martin Baulig <martin.baulig@xamarin.com>
-//
-// Copyright (c) 2015 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.
-#if SECURITY_DEP
-#if MONO_SECURITY_ALIAS
-extern alias MonoSecurity;
-#endif
-
-using XHttpWebRequest = System.Net.HttpWebRequest;
-using XSslProtocols = System.Security.Authentication.SslProtocols;
-using XX509CertificateCollection = System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-
-#if MONO_SECURITY_ALIAS
-using MonoSecurity::Mono.Security.Interface;
-#else
-using Mono.Security.Interface;
-#endif
-
-using System;
-using System.IO;
-using System.Net;
-using System.Net.Security;
-using System.Security.Cryptography.X509Certificates;
-
-namespace Mono.Net.Security.Private
-{
-       /*
-        * Strictly private - do not use outside the Mono.Net.Security directory.
-        */
-       class MonoLegacyTlsProvider : MonoTlsProviderImpl
-       {
-               static readonly Guid id = new Guid ("809e77d5-56cc-4da8-b9f0-45e65ba9cceb");
-
-               public override Guid ID {
-                       get { return id; }
-               }
-
-               public override string Name {
-                       get { return "legacy"; }
-               }
-
-               public MonoTlsProvider Provider {
-                       get { return this; }
-               }
-
-               public override bool SupportsSslStream {
-                       get { return true; }
-               }
-
-               public override bool SupportsConnectionInfo {
-                       get { return false; }
-               }
-
-               public override bool SupportsMonoExtensions {
-                       get { return false; }
-               }
-
-               internal override bool SupportsTlsContext {
-                       get { return false; }
-               }
-
-               public override XSslProtocols SupportedProtocols {
-                       get { return XSslProtocols.Ssl3 | XSslProtocols.Tls; }
-               }
-
-               protected override IMonoSslStream CreateSslStreamImpl (
-                       Stream innerStream, bool leaveInnerStreamOpen,
-                       MonoTlsSettings settings)
-               {
-                       return new LegacySslStream (innerStream, leaveInnerStreamOpen, this, settings);
-               }
-
-               protected override IMonoTlsContext CreateTlsContextImpl (
-                       string hostname, bool serverMode, TlsProtocols protocolFlags,
-                       X509Certificate serverCertificate, X509CertificateCollection clientCertificates,
-                       bool remoteCertRequired, MonoEncryptionPolicy encryptionPolicy,
-                       MonoTlsSettings settings)
-               {
-                       throw new NotSupportedException ();
-               }
-       }
-}
-#endif
-
index 72390bcdd11b175f47a4611393f3669cf5d21be1..db2e81529ba7704cdfee952f59b1284cb07ac1ac 100644 (file)
@@ -2,9 +2,7 @@
 #if SECURITY_DEP
 using System;
 using MSI = Mono.Security.Interface;
-#if HAVE_BTLS
 using Mono.Btls;
-#endif
 
 namespace Mono.Net.Security
 {
@@ -18,15 +16,11 @@ namespace Mono.Net.Security
                        case null:
                        case "default":
                        case "legacy":
-                               return new Private.MonoLegacyTlsProvider ();
+                               return new LegacyTlsProvider ();
                        case "btls":
-#if HAVE_BTLS
-                               if (!MonoBtlsProvider.IsSupported ())
+                               if (!IsBtlsSupported ())
                                        throw new NotSupportedException ("BTLS in not supported!");
                                return new MonoBtlsProvider ();
-#else
-                               throw new NotSupportedException ("BTLS in not supported!");
-#endif
                        default:
                                throw new NotSupportedException (string.Format ("Invalid TLS Provider: `{0}'.", provider));
                        }
index e53b6eba4c8ee1c9e383102d0a4f548ee79ed983..071535a5c44ca31c5d8ac4fdb84d7ffdac657c3c 100644 (file)
@@ -39,6 +39,7 @@ using System.Security.Cryptography.X509Certificates;
 using System;
 using System.Net;
 using System.Collections.Generic;
+using System.Runtime.CompilerServices;
 
 #if !MOBILE
 using System.Reflection;
@@ -64,74 +65,61 @@ namespace Mono.Net.Security
 
                internal static IMonoTlsProvider GetProviderInternal ()
                {
+                       #if SECURITY_DEP
                        lock (locker) {
-                               if (currentProvider != null)
-                                       return currentProvider;
-
-                               try {
-                                       defaultProvider = GetDefaultProviderInternal ();
-                               } catch (Exception ex) {
-                                       throw new NotSupportedException ("TLS Support not available.", ex);
-                               }
-
-                               if (defaultProvider == null)
-                                       throw new NotSupportedException ("TLS Support not available.");
-
-                               currentProvider = defaultProvider;
-                               return currentProvider;
+                               InitializeInternal ();
+                               return defaultProvider;
                        }
+                       #else
+                       throw new NotSupportedException ("TLS Support not available.");
+                       #endif
                }
 
-               internal static IMonoTlsProvider GetDefaultProviderInternal ()
+#if SECURITY_DEP
+               internal static void InitializeInternal ()
                {
                        lock (locker) {
-                               if (defaultProvider != null)
-                                       return defaultProvider;
+                               if (initialized)
+                                       return;
 
+                               MSI.MonoTlsProvider provider;
                                try {
-                                       defaultProvider = CreateDefaultProvider ();
+                                       provider = CreateDefaultProviderImpl ();
                                } catch (Exception ex) {
                                        throw new NotSupportedException ("TLS Support not available.", ex);
                                }
 
-                               if (defaultProvider == null)
+                               if (provider == null)
                                        throw new NotSupportedException ("TLS Support not available.");
 
-                               return defaultProvider;
+                               defaultProvider = new Private.MonoTlsProviderWrapper (provider);
+                               initialized = true;
                        }
                }
 
-               static IMonoTlsProvider CreateDefaultProvider ()
+               internal static void InitializeInternal (string provider) 
                {
-#if SECURITY_DEP
-                       MSI.MonoTlsProvider provider = null;
-#if MONO_FEATURE_NEW_SYSTEM_SOURCE
-                       /*
-                        * This is a hack, which is used in the Mono.Security.Providers.NewSystemSource
-                        * assembly, which will provide a "fake" System.dll.  Use the public Mono.Security
-                        * API to get the "real" System.dll's provider via reflection, then wrap it with
-                        * the "fake" version's perceived view.
-                        *
-                        * NewSystemSource needs to compile MonoTlsProviderFactory.cs, IMonoTlsProvider.cs,
-                        * MonoTlsProviderWrapper.cs and CallbackHelpers.cs from this directory and only these.
-                        */
-                       provider = MSI.MonoTlsProviderFactory.GetProvider ();
-#else
-                       provider = CreateDefaultProviderImpl ();
-#endif
-                       if (provider != null)
-                               return new Private.MonoTlsProviderWrapper (provider);
-#endif
-                       return null;
+                       lock (locker) {
+                               if (initialized)
+                                       throw new NotSupportedException ("TLS Subsystem already initialized.");
+
+                               var msiProvider = LookupProvider (provider, true);
+                               defaultProvider = new Private.MonoTlsProviderWrapper (msiProvider);
+                               initialized = true;
+                       }
                }
 
+               [MethodImpl (MethodImplOptions.InternalCall)]
+               internal extern static bool IsBtlsSupported ();
+#endif
+
                static object locker = new object ();
+               static bool initialized;
                static IMonoTlsProvider defaultProvider;
-               static IMonoTlsProvider currentProvider;
 
                #endregion
 
-#if SECURITY_DEP && !MONO_FEATURE_NEW_SYSTEM_SOURCE
+#if SECURITY_DEP
 
                static Dictionary<string,string> providerRegistration;
 
@@ -171,13 +159,10 @@ namespace Mono.Net.Security
                                if (providerRegistration != null)
                                        return;
                                providerRegistration = new Dictionary<string,string> ();
-                               providerRegistration.Add ("legacy", "Mono.Net.Security.Private.MonoLegacyTlsProvider");
-                               providerRegistration.Add ("newtls", "Mono.Security.Providers.NewTls.NewTlsProvider, Mono.Security.Providers.NewTls, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756");
-                               providerRegistration.Add ("oldtls", "Mono.Security.Providers.OldTls.OldTlsProvider, Mono.Security.Providers.OldTls, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756");
-#if HAVE_BTLS
-                               if (Mono.Btls.MonoBtlsProvider.IsSupported ())
+                               providerRegistration.Add ("legacy", "Mono.Net.Security.LegacyTlsProvider");
+                               providerRegistration.Add ("default", "Mono.Net.Security.LegacyTlsProvider");
+                               if (IsBtlsSupported ())
                                        providerRegistration.Add ("btls", "Mono.Btls.MonoBtlsProvider");
-#endif
                                X509Helper2.Initialize ();
                        }
                }
@@ -186,11 +171,8 @@ namespace Mono.Net.Security
                static MSI.MonoTlsProvider TryDynamicLoad ()
                {
                        var variable = Environment.GetEnvironmentVariable ("MONO_TLS_PROVIDER");
-                       if (variable == null)
-                               return null;
-
-                       if (string.Equals (variable, "default", StringComparison.OrdinalIgnoreCase))
-                               return null;
+                       if (string.IsNullOrEmpty (variable))
+                               variable = "default";
 
                        return LookupProvider (variable, true);
                }
@@ -201,7 +183,7 @@ namespace Mono.Net.Security
                        if (provider != null)
                                return provider;
 
-                       return new Private.MonoLegacyTlsProvider ();
+                       return new LegacyTlsProvider ();
                }
 #endif
 
@@ -222,13 +204,9 @@ namespace Mono.Net.Security
                        return provider.Provider;
                }
 
-               internal static MSI.MonoTlsProvider GetDefaultProvider ()
+               internal static bool IsProviderSupported (string name)
                {
-                       var provider = GetDefaultProviderInternal ();
-                       if (provider == null)
-                               throw new NotSupportedException ("No TLS Provider available.");
-
-                       return provider.Provider;
+                       return LookupProvider (name, false) != null;
                }
 
                internal static MSI.MonoTlsProvider GetProvider (string name)
@@ -236,20 +214,30 @@ namespace Mono.Net.Security
                        return LookupProvider (name, false);
                }
 
-               internal static bool HasProvider {
+               internal static bool IsInitialized {
                        get {
                                lock (locker) {
-                                       return currentProvider != null;
+                                       return initialized;
                                }
                        }
                }
 
-               internal static void SetDefaultProvider (string name)
+               internal static void Initialize ()
                {
-                       lock (locker) {
-                               var provider = LookupProvider (name, true);
-                               currentProvider = new Private.MonoTlsProviderWrapper (provider);
-                       }
+                       #if SECURITY_DEP
+                       InitializeInternal ();
+                       #else
+                       throw new NotSupportedException ("TLS Support not available.");
+                       #endif
+               }
+
+               internal static void Initialize (string provider)
+               {
+                       #if SECURITY_DEP
+                       InitializeInternal (provider);
+                       #else
+                       throw new NotSupportedException ("TLS Support not available.");
+                       #endif
                }
 
                internal static HttpWebRequest CreateHttpsRequest (Uri requestUri, MSI.MonoTlsProvider provider, MSI.MonoTlsSettings settings)
diff --git a/mcs/class/System/Mono.Net.Security/MonoTlsProviderImpl.cs b/mcs/class/System/Mono.Net.Security/MonoTlsProviderImpl.cs
deleted file mode 100644 (file)
index 94f86ca..0000000
+++ /dev/null
@@ -1,108 +0,0 @@
-//
-// MonoTlsProviderImpl.cs
-//
-// Author:
-//       Martin Baulig <martin.baulig@xamarin.com>
-//
-// Copyright (c) 2015 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.
-
-#if SECURITY_DEP
-
-#if MONO_SECURITY_ALIAS
-extern alias MonoSecurity;
-#endif
-
-#if MONO_SECURITY_ALIAS
-using MSI = MonoSecurity::Mono.Security.Interface;
-#else
-using MSI = Mono.Security.Interface;
-#endif
-
-using System;
-using System.IO;
-using System.Net;
-using System.Net.Security;
-using System.Security.Cryptography.X509Certificates;
-
-namespace Mono.Net.Security.Private
-{
-       /*
-        * Strictly private - do not use outside the Mono.Net.Security directory.
-        */
-       abstract class MonoTlsProviderImpl : MSI.MonoTlsProvider, IMonoTlsProvider
-       {
-               MSI.MonoTlsProvider IMonoTlsProvider.Provider {
-                       get { return this; }
-               }
-
-               IMonoSslStream IMonoTlsProvider.CreateSslStream (
-                       Stream innerStream, bool leaveInnerStreamOpen,
-                       MSI.MonoTlsSettings settings)
-               {
-                       return CreateSslStreamImpl (innerStream, leaveInnerStreamOpen, settings);
-               }
-
-               protected abstract IMonoSslStream CreateSslStreamImpl (
-                       Stream innerStream, bool leaveInnerStreamOpen,
-                       MSI.MonoTlsSettings settings);
-
-               public override MSI.IMonoSslStream CreateSslStream (
-                       Stream innerStream, bool leaveInnerStreamOpen,
-                       MSI.MonoTlsSettings settings = null)
-               {
-                       var sslStream = CreateSslStreamImpl (innerStream, leaveInnerStreamOpen, settings);
-                       return new MonoSslStreamImpl (sslStream);
-               }
-
-               MSI.IMonoTlsContext IMonoTlsProvider.CreateTlsContext (
-                       string hostname, bool serverMode, MSI.TlsProtocols protocolFlags,
-                       X509Certificate serverCertificate, X509CertificateCollection clientCertificates,
-                       bool remoteCertRequired, bool checkCertName, bool checkCertRevocationStatus,
-                       MSI.MonoEncryptionPolicy encryptionPolicy, MSI.MonoTlsSettings settings)
-               {
-                       return CreateTlsContextImpl (
-                               hostname, serverMode, protocolFlags,
-                               serverCertificate, clientCertificates,
-                               remoteCertRequired, encryptionPolicy, settings);
-               }
-
-               protected abstract MSI.IMonoTlsContext CreateTlsContextImpl (
-                       string hostname, bool serverMode, MSI.TlsProtocols protocolFlags,
-                       X509Certificate serverCertificate, X509CertificateCollection clientCertificates,
-                       bool remoteCertRequired, MSI.MonoEncryptionPolicy encryptionPolicy,
-                       MSI.MonoTlsSettings settings);
-
-               internal override MSI.IMonoTlsContext CreateTlsContext (
-                       string hostname, bool serverMode, MSI.TlsProtocols protocolFlags,
-                       X509Certificate serverCertificate, X509CertificateCollection clientCertificates,
-                       bool remoteCertRequired, MSI.MonoEncryptionPolicy encryptionPolicy,
-                       MSI.MonoTlsSettings settings)
-               {
-                       return CreateTlsContextImpl (
-                               hostname, serverMode, (MSI.TlsProtocols)protocolFlags,
-                               serverCertificate, clientCertificates,
-                               remoteCertRequired, (MSI.MonoEncryptionPolicy)encryptionPolicy,
-                               settings);
-               }
-       }
-}
-
-#endif
index 15283200590899b85f606eb3a2acfc9a08c6a9bb..0a81f4ff932ca159d11aa89a01ca09e9bbfd5240 100644 (file)
@@ -73,19 +73,6 @@ namespace Mono.Net.Security.Private
                                return monoSslStreamImpl.Impl;
                        return new MonoSslStreamWrapper (sslStream);
                }
-
-               public MSI.IMonoTlsContext CreateTlsContext (
-                       string hostname, bool serverMode, MSI.TlsProtocols protocolFlags,
-                       X509Certificate serverCertificate, X509CertificateCollection clientCertificates,
-                       bool remoteCertRequired, bool checkCertName, bool checkCertRevocationStatus,
-                       MSI.MonoEncryptionPolicy encryptionPolicy, MSI.MonoTlsSettings settings)
-               {
-                       return provider.CreateTlsContext (
-                               hostname, serverMode, protocolFlags,
-                               serverCertificate, clientCertificates,
-                               remoteCertRequired, (MSI.MonoEncryptionPolicy)encryptionPolicy,
-                               settings);
-               }
        }
 }
 
index 79e4fbf68451cdcdd881891c2a7a223fcfe0f0ed..4625f2f53c20faf9bd5e30386aed0cbee5d5733f 100644 (file)
@@ -34,7 +34,6 @@ using MonoSecurity::Mono.Security.Interface;
 #else
 using Mono.Security.Interface;
 #endif
-using XX509CertificateCollection = System.Security.Cryptography.X509Certificates.X509CertificateCollection;
 #endif
 
 using System;
@@ -76,7 +75,7 @@ namespace Mono.Net.Security
                }
 
 #if SECURITY_DEP
-               readonly ChainValidationHelper validationHelper;
+//             readonly ChainValidationHelper validationHelper;
                readonly MonoTlsSettings settings;
 
                public MonoTlsStream (HttpWebRequest request, NetworkStream networkStream)
@@ -88,7 +87,7 @@ namespace Mono.Net.Security
                        provider = request.TlsProvider ?? MonoTlsProviderFactory.GetProviderInternal ();
                        status = WebExceptionStatus.SecureChannelFailure;
 
-                       validationHelper = ChainValidationHelper.Create (provider.Provider, ref settings, this);
+                       /*validationHelper =*/ ChainValidationHelper.Create (provider.Provider, ref settings, this);
                }
 
                internal Stream CreateStream (byte[] buffer)
index 6de1cd2599345f6e857e342f6cb88f008ce8bdf8..2787775d30204014f088f82f644ced144f584b02 100644 (file)
@@ -47,47 +47,56 @@ namespace Mono.Net.Security
        //
        internal static class NoReflectionHelper
        {
-               internal static object GetDefaultCertificateValidator (object provider, object settings)
+               internal static object GetInternalValidator (object provider, object settings)
                {
                        #if SECURITY_DEP
-                       return ChainValidationHelper.GetDefaultValidator ((MSI.MonoTlsProvider)provider, (MSI.MonoTlsSettings)settings);
+                       return ChainValidationHelper.GetInternalValidator ((MSI.MonoTlsProvider)provider, (MSI.MonoTlsSettings)settings);
                        #else
                        throw new NotSupportedException ();
                        #endif
                }
 
-               internal static object GetProvider ()
+               internal static object GetDefaultValidator (object settings)
                {
                        #if SECURITY_DEP
-                       return MonoTlsProviderFactory.GetProvider ();
+                       return ChainValidationHelper.GetDefaultValidator ((MSI.MonoTlsSettings)settings);
                        #else
                        throw new NotSupportedException ();
                        #endif
                }
 
-               internal static object GetDefaultProvider ()
+               internal static object GetProvider ()
                {
                        #if SECURITY_DEP
-                       return MonoTlsProviderFactory.GetDefaultProvider ();
+                       return MonoTlsProviderFactory.GetProvider ();
                        #else
                        throw new NotSupportedException ();
                        #endif
                }
 
-               internal static bool HasProvider {
+               internal static bool IsInitialized {
                        get {
                                #if SECURITY_DEP
-                               return MonoTlsProviderFactory.HasProvider;
+                               return MonoTlsProviderFactory.IsInitialized;
                                #else
                                throw new NotSupportedException ();
                                #endif
                        }
                }
 
-               internal static void SetDefaultProvider (string name)
+               internal static void Initialize ()
+               {
+                       #if SECURITY_DEP
+                       MonoTlsProviderFactory.Initialize ();
+                       #else
+                       throw new NotSupportedException ();
+                       #endif
+               }
+
+               internal static void Initialize (string provider)
                {
                        #if SECURITY_DEP
-                       MonoTlsProviderFactory.SetDefaultProvider (name);
+                       MonoTlsProviderFactory.Initialize (provider);
                        #else
                        throw new NotSupportedException ();
                        #endif
@@ -120,6 +129,15 @@ namespace Mono.Net.Security
                        #endif
                }
 
+               internal static bool IsProviderSupported (string name)
+               {
+                       #if SECURITY_DEP
+                       return MonoTlsProviderFactory.IsProviderSupported (name);
+                       #else
+                       throw new NotSupportedException ();
+                       #endif
+               }
+
                internal static object GetProvider (string name)
                {
                        #if SECURITY_DEP
index e900c22bfeaab4f99b6b5b94728eb66d166b1a8a..42c17de3ce66ec827f7aeea29b5a481438054ebe 100644 (file)
@@ -13,8 +13,6 @@ using Mono.Security.Interface;
 using MSX = Mono.Security.X509;
 using Mono.Security.X509.Extensions;
 #endif
-using XX509CertificateCollection = System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-using XX509Chain = System.Security.Cryptography.X509Certificates.X509Chain;
 
 using System;
 using System.Net;
@@ -62,7 +60,7 @@ namespace Mono.Net.Security
 #endif
                }
 
-               public static X509Chain CreateX509Chain (XX509CertificateCollection certs)
+               public static X509Chain CreateX509Chain (X509CertificateCollection certs)
                {
                        var chain = new X509Chain ();
                        chain.ChainPolicy = new X509ChainPolicy ((X509CertificateCollection)(object)certs);
@@ -74,7 +72,7 @@ namespace Mono.Net.Security
                        return chain;
                }
 
-               static bool BuildX509Chain (XX509CertificateCollection certs, X509Chain chain, ref SslPolicyErrors errors, ref int status11)
+               static bool BuildX509Chain (X509CertificateCollection certs, X509Chain chain, ref SslPolicyErrors errors, ref int status11)
                {
 #if MOBILE
                        return false;
@@ -106,7 +104,7 @@ namespace Mono.Net.Security
 #endif
                }
 
-               static bool CheckUsage (XX509CertificateCollection certs, string host, ref SslPolicyErrors errors, ref int status11)
+               static bool CheckUsage (X509CertificateCollection certs, string host, ref SslPolicyErrors errors, ref int status11)
                {
 #if !MONOTOUCH
                        var leaf = certs[0] as X509Certificate2;
@@ -130,7 +128,7 @@ namespace Mono.Net.Security
                        return true;
                }
 
-               static bool EvaluateSystem (XX509CertificateCollection certs, XX509CertificateCollection anchors, string host, X509Chain chain, ref SslPolicyErrors errors, ref int status11)
+               static bool EvaluateSystem (X509CertificateCollection certs, X509CertificateCollection anchors, string host, X509Chain chain, ref SslPolicyErrors errors, ref int status11)
                {
                        var leaf = certs [0];
                        bool result;
@@ -191,7 +189,7 @@ namespace Mono.Net.Security
                }
 
                public static bool Evaluate (
-                       MonoTlsSettings settings, string host, XX509CertificateCollection certs,
+                       MonoTlsSettings settings, string host, X509CertificateCollection certs,
                        X509Chain chain, ref SslPolicyErrors errors, ref int status11)
                {
                        if (!CheckUsage (certs, host, ref errors, ref status11))
diff --git a/mcs/class/System/ReferenceSources/Internal.cs b/mcs/class/System/ReferenceSources/Internal.cs
deleted file mode 100644 (file)
index 6c50450..0000000
+++ /dev/null
@@ -1,80 +0,0 @@
-//
-// Internal.cs
-//
-// Author:
-//       Martin Baulig <martin.baulig@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://www.xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-using System.Runtime.InteropServices;
-using System.Security.Cryptography.X509Certificates;
-
-namespace System.Net.Security
-{
-       //From Schannel.h
-       [Flags]
-       internal enum SchProtocols
-       {
-               Zero = 0,
-               PctClient = 0x00000002,
-               PctServer = 0x00000001,
-               Pct = (PctClient | PctServer),
-               Ssl2Client = 0x00000008,
-               Ssl2Server = 0x00000004,
-               Ssl2 = (Ssl2Client | Ssl2Server),
-               Ssl3Client = 0x00000020,
-               Ssl3Server = 0x00000010,
-               Ssl3 = (Ssl3Client | Ssl3Server),
-               Tls10Client = 0x00000080,
-               Tls10Server = 0x00000040,
-               Tls10 = (Tls10Client | Tls10Server),
-               Tls11Client = 0x00000200,
-               Tls11Server = 0x00000100,
-               Tls11 = (Tls11Client | Tls11Server),
-               Tls12Client = 0x00000800,
-               Tls12Server = 0x00000400,
-               Tls12 = (Tls12Client | Tls12Server),
-               Ssl3Tls = (Ssl3 | Tls10),
-               UniClient = unchecked((int)0x80000000),
-               UniServer = 0x40000000,
-               Unified = (UniClient | UniServer),
-               ClientMask = (PctClient | Ssl2Client | Ssl3Client | Tls10Client | Tls11Client | Tls12Client | UniClient),
-               ServerMask = (PctServer | Ssl2Server | Ssl3Server | Tls10Server | Tls11Server | Tls12Server | UniServer)
-       }
-
-       //From Schannel.h
-       [StructLayout (LayoutKind.Sequential)]
-       internal class SslConnectionInfo
-       {
-               public readonly int Protocol;
-               public readonly int DataCipherAlg;
-               public readonly int DataKeySize;
-               public readonly int DataHashAlg;
-               public readonly int DataHashKeySize;
-               public readonly int KeyExchangeAlg;
-               public readonly int KeyExchKeySize;
-
-               internal SslConnectionInfo (int protocol)
-               {
-                       Protocol = protocol;
-               }
-       }
-}
index b5b773e28c4f186888e9a03b710e7524d4c66c23..8eb5e066d02487b08f300b15d1d6b1a7ccee2ad7 100644 (file)
@@ -1,21 +1,23 @@
-#if !MONO_FEATURE_NEW_TLS
 using System.Diagnostics;
 
 namespace System.Net {
-       class Logging {
-               internal static bool On {
+       static class Logging
+       {
+               internal static readonly bool On = false;
+
+               internal static TraceSource Web {
                        get {
-                               return false;
+                               return null;
                        }
                }
 
-               internal static TraceSource Web {
+               internal static TraceSource HttpListener {
                        get {
                                return null;
                        }
                }
 
-               internal static TraceSource HttpListener {
+               internal static TraceSource Sockets {
                        get {
                                return null;
                        }
@@ -29,6 +31,10 @@ namespace System.Net {
                internal static void Enter(TraceSource traceSource, string msg) {
                }
 
+               [Conditional ("TRACE")]
+               internal static void Enter(TraceSource traceSource, string msg, string parameters) {
+               }
+
                [Conditional ("TRACE")]
                internal static void Exception(TraceSource traceSource, object obj, string method, Exception e) {
                }
@@ -41,6 +47,10 @@ namespace System.Net {
                internal static void Exit(TraceSource traceSource, string msg) {
                }
 
+               [Conditional ("TRACE")]
+               internal static void Exit(TraceSource traceSource, string msg, string parameters) {
+               }
+
                [Conditional ("TRACE")]
                internal static void PrintInfo(TraceSource traceSource, object obj, string method, string msg) {
                }
@@ -75,4 +85,3 @@ namespace System.Net {
 
 #endif
 }
-#endif
diff --git a/mcs/class/System/ReferenceSources/SSPIConfiguration.cs b/mcs/class/System/ReferenceSources/SSPIConfiguration.cs
deleted file mode 100644 (file)
index 3ab4138..0000000
+++ /dev/null
@@ -1,53 +0,0 @@
-//
-// SSPIConfiguration.cs
-//
-// Author:
-//       Martin Baulig <martin.baulig@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://www.xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-#if MONO_FEATURE_NEW_TLS && SECURITY_DEP
-#if MONO_SECURITY_ALIAS
-extern alias MonoSecurity;
-using MonoSecurity::Mono.Security.Interface;
-#else
-using Mono.Security.Interface;
-#endif
-using Mono.Net.Security;
-
-namespace System.Net.Security
-{
-       internal interface SSPIConfiguration
-       {
-               IMonoTlsProvider Provider {
-                       get;
-               }
-
-               MonoTlsSettings Settings {
-                       get;
-               }
-
-               IMonoTlsEventSink EventSink {
-                       get;
-               }
-       }
-}
-#endif
diff --git a/mcs/class/System/ReferenceSources/SSPISafeHandles.cs b/mcs/class/System/ReferenceSources/SSPISafeHandles.cs
deleted file mode 100644 (file)
index a12e395..0000000
+++ /dev/null
@@ -1,209 +0,0 @@
-//
-// SafeHandles.cs
-//
-// Author:
-//       Martin Baulig <martin.baulig@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://www.xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-#if MONO_FEATURE_NEW_TLS && SECURITY_DEP
-#if MONO_SECURITY_ALIAS
-extern alias MonoSecurity;
-using IMonoTlsContext = MonoSecurity::Mono.Security.Interface.IMonoTlsContext;
-#else
-using IMonoTlsContext = Mono.Security.Interface.IMonoTlsContext;
-#endif
-
-using System.Runtime.InteropServices;
-using System.Security.Cryptography.X509Certificates;
-
-namespace System.Net.Security
-{
-       class DummySafeHandle : SafeHandle
-       {
-               protected DummySafeHandle ()
-                       : base ((IntPtr)(-1), true)
-               {
-               }
-
-               protected override bool ReleaseHandle ()
-               {
-                       return true;
-               }
-
-               public override bool IsInvalid {
-                       get { return handle == (IntPtr)(-1); }
-               }
-       }
-
-       class SafeFreeCertContext : DummySafeHandle
-       {
-       }
-
-       class SafeFreeCredentials : DummySafeHandle
-       {
-               SecureCredential credential;
-
-               public X509Certificate2 Certificate {
-                       get {
-                               if (IsInvalid)
-                                       throw new ObjectDisposedException ("Certificate");
-                               return credential.certificate;
-                       }
-               }
-
-               public SafeFreeCredentials (SecureCredential credential)
-               {
-                       this.credential = credential;
-                       bool success = true;
-                       DangerousAddRef (ref success);
-               }
-
-               public override bool IsInvalid {
-                       get {
-                               return credential.certificate == null;
-                       }
-               }
-
-               protected override bool ReleaseHandle ()
-               {
-                       credential.Clear ();
-                       return base.ReleaseHandle ();
-               }
-       }
-
-       class SafeDeleteContext : DummySafeHandle
-       {
-               IMonoTlsContext context;
-
-               public IMonoTlsContext Context {
-                       get {
-                               if (IsInvalid)
-                                       throw new ObjectDisposedException ("TlsContext");
-                               return context;
-                       }
-               }
-
-               public SafeDeleteContext (IMonoTlsContext context)
-               {
-                       this.context = context;
-               }
-
-               public override bool IsInvalid {
-                       get {
-                               return context == null || !context.IsValid;
-                       }
-               }
-
-               protected override bool ReleaseHandle ()
-               {
-                       context.Dispose ();
-                       context = null;
-                       return base.ReleaseHandle ();
-               }
-       }
-
-       struct SecureCredential
-       {
-               public const int CurrentVersion = 0x4;
-
-               [Flags]
-               public enum Flags
-               {
-                       Zero = 0,
-                       NoSystemMapper = 0x02,
-                       NoNameCheck = 0x04,
-                       ValidateManual = 0x08,
-                       NoDefaultCred = 0x10,
-                       ValidateAuto = 0x20,
-                       SendAuxRecord = 0x00200000,
-                       UseStrongCrypto = 0x00400000
-               }
-
-               int version;
-               internal X509Certificate2 certificate;
-               SchProtocols protocols;
-               EncryptionPolicy policy;
-
-               public SecureCredential (int version, X509Certificate2 certificate, SecureCredential.Flags flags, SchProtocols protocols, EncryptionPolicy policy)
-               {
-                       this.version = version;
-                       this.certificate = certificate;
-                       this.protocols = protocols;
-                       this.policy = policy;
-               }
-
-               public void Clear ()
-               {
-                       certificate = null;
-               }
-       }
-
-       internal class SafeCredentialReference : DummySafeHandle
-       {
-               //
-               // Static cache will return the target handle if found the reference in the table.
-               //
-               internal SafeFreeCredentials _Target;
-
-               //
-               //
-               internal static SafeCredentialReference CreateReference (SafeFreeCredentials target)
-               {
-                       SafeCredentialReference result = new SafeCredentialReference (target);
-                       if (result.IsInvalid)
-                               return null;
-
-                       return result;
-               }
-
-               private SafeCredentialReference (SafeFreeCredentials target)
-                       : base ()
-               {
-                       // Bumps up the refcount on Target to signify that target handle is statically cached so
-                       // its dispose should be postponed
-                       bool b = false;
-                       try {
-                               target.DangerousAddRef (ref b);
-                       } catch {
-                               if (b) {
-                                       target.DangerousRelease ();
-                                       b = false;
-                               }
-                       } finally {
-                               if (b) {
-                                       _Target = target;
-                                       SetHandle (new IntPtr (0));   // make this handle valid
-                               }
-                       }
-               }
-
-               override protected bool ReleaseHandle ()
-               {
-                       SafeFreeCredentials target = _Target;
-                       if (target != null)
-                               target.DangerousRelease ();
-                       _Target = null;
-                       return true;
-               }
-       }
-
-}
-#endif
diff --git a/mcs/class/System/ReferenceSources/SSPIWrapper.cs b/mcs/class/System/ReferenceSources/SSPIWrapper.cs
deleted file mode 100644 (file)
index a0cb8d5..0000000
+++ /dev/null
@@ -1,303 +0,0 @@
-//
-// SSPIWrapper.cs
-//
-// Author:
-//       Martin Baulig <martin.baulig@xamarin.com>
-//
-// Copyright (c) 2015 Xamarin Inc. (http://www.xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-#if MONO_FEATURE_NEW_TLS && SECURITY_DEP
-#if MONO_SECURITY_ALIAS
-extern alias MonoSecurity;
-#endif
-
-#if MONO_SECURITY_ALIAS
-using MX = MonoSecurity::Mono.Security.X509;
-using MonoSecurity::Mono.Security.Interface;
-#else
-using MX = Mono.Security.X509;
-using Mono.Security.Interface;
-#endif
-
-using System.Runtime.InteropServices;
-using System.Security.Authentication.ExtendedProtection;
-using System.Security.Cryptography.X509Certificates;
-using MNS = Mono.Net.Security;
-
-namespace System.Net.Security
-{
-       internal class SSPIInterface
-       {
-               public IMonoTlsContext Context {
-                       get;
-                       private set;
-               }
-
-               public IMonoTlsEventSink EventSink {
-                       get;
-                       private set;
-               }
-
-               public SSPIInterface (IMonoTlsContext context, IMonoTlsEventSink eventSink)
-               {
-                       Context = context;
-                       EventSink = eventSink;
-               }
-       }
-
-       internal static class GlobalSSPI
-       {
-               internal static SSPIInterface Create (string hostname, bool serverMode, SchProtocols protocolFlags, X509Certificate serverCertificate, X509CertificateCollection clientCertificates,
-                                                          bool remoteCertRequired, bool checkCertName, bool checkCertRevocationStatus, EncryptionPolicy encryptionPolicy,
-                                                          LocalCertSelectionCallback certSelectionDelegate, RemoteCertValidationCallback remoteValidationCallback, SSPIConfiguration userConfig)
-               {
-                       if (userConfig.Settings != null && remoteValidationCallback != null)
-                               throw new InvalidOperationException ();
-                       var context = userConfig.Provider.CreateTlsContext (
-                               hostname, serverMode, (TlsProtocols)protocolFlags, serverCertificate, clientCertificates,
-                               remoteCertRequired, checkCertName, checkCertRevocationStatus,
-                               (MonoEncryptionPolicy)encryptionPolicy, userConfig.Settings);
-                       return new SSPIInterface (context, userConfig.EventSink);
-               }
-       }
-
-       /*
-        * SSPIWrapper _is a _class that provides a managed implementation of the equivalent
-        * _class _in Microsofts .NET Framework.   
-        * 
-        * The SSPIWrapper class is used by the TLS/SSL stack to implement both the 
-        * protocol handshake as well as the encryption and decryption of messages.
-        * 
-        * Microsoft's implementation of this class is merely a P/Invoke wrapper
-        * around the native SSPI APIs on Windows.   This implementation instead, 
-        * provides a managed implementation that uses the cross platform Mono.Security 
-        * to provide the equivalent functionality.
-        * 
-        * Ideally, this should be abstracted with a different name, and decouple
-        * the naming from the SSPIWrapper name, but this allows Mono to reuse
-        * the .NET code with minimal changes.
-        * 
-        * The "internal" methods here are the API that is consumed by the class
-        * libraries.
-        */
-       internal static class SSPIWrapper
-       {
-               static void SetCredentials (SSPIInterface secModule, SafeFreeCredentials credentials)
-               {
-                       if (credentials != null && !credentials.IsInvalid) {
-                               if (!secModule.Context.HasCredentials && credentials.Certificate != null) {
-                                       var cert = new X509Certificate2 (credentials.Certificate.RawData);
-                                       secModule.Context.SetCertificate (cert, credentials.Certificate.PrivateKey);
-                               }
-                               bool success = true;
-                               credentials.DangerousAddRef (ref success);
-                       }
-               }
-
-               /*
-                * @safecontext is null on the first use, but it will become non-null for invocations 
-                * where the connection is being re-negotiated.
-                * 
-               */
-               internal static int AcceptSecurityContext (SSPIInterface secModule, ref SafeFreeCredentials credentials, ref SafeDeleteContext safeContext, ContextFlags inFlags, Endianness endianness, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, ref ContextFlags outFlags)
-               {
-                       if (endianness != Endianness.Native)
-                               throw new NotSupportedException ();
-
-                       if (safeContext == null) {
-                               if (credentials == null || credentials.IsInvalid)
-                                       return (int)SecurityStatus.CredentialsNeeded;
-
-                               secModule.Context.Initialize (secModule.EventSink);
-                               safeContext = new SafeDeleteContext (secModule.Context);
-                       }
-
-                       SetCredentials (secModule, credentials);
-
-                       var incoming = GetInputBuffer (inputBuffer);
-                       IBufferOffsetSize outgoing;
-
-                       var retval = (int)safeContext.Context.GenerateNextToken (incoming, out outgoing);
-                       UpdateOutput (outgoing, outputBuffer);
-                       return retval;
-               }
-
-               internal static int InitializeSecurityContext (SSPIInterface secModule, ref SafeFreeCredentials credentials, ref SafeDeleteContext safeContext, string targetName, ContextFlags inFlags, Endianness endianness, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, ref ContextFlags outFlags)
-               {
-                       if (inputBuffer != null)
-                               throw new InvalidOperationException ();
-
-                       if (safeContext == null) {
-                               secModule.Context.Initialize (secModule.EventSink);
-                               safeContext = new SafeDeleteContext (secModule.Context);
-                       }
-
-                       return InitializeSecurityContext (secModule, credentials, ref safeContext, targetName, inFlags, endianness, null, outputBuffer, ref outFlags);
-               }
-
-               internal static int InitializeSecurityContext (SSPIInterface secModule, SafeFreeCredentials credentials, ref SafeDeleteContext safeContext, string targetName, ContextFlags inFlags, Endianness endianness, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer, ref ContextFlags outFlags)
-               {
-                       if (endianness != Endianness.Native)
-                               throw new NotSupportedException ();
-
-                       SetCredentials (secModule, credentials);
-
-                       SecurityBuffer inputBuffer = null;
-                       if (inputBuffers != null) {
-                               if (inputBuffers.Length != 2 || inputBuffers [1].type != BufferType.Empty)
-                                       throw new NotSupportedException ();
-                               inputBuffer = inputBuffers [0];
-                       }
-
-                       var incoming = GetInputBuffer (inputBuffer);
-                       IBufferOffsetSize outgoing = null;
-
-                       var retval = (int)safeContext.Context.GenerateNextToken (incoming, out outgoing);
-                       UpdateOutput (outgoing, outputBuffer);
-                       return retval;
-               }
-
-               internal static int EncryptMessage (SSPIInterface secModule, SafeDeleteContext safeContext, SecurityBuffer securityBuffer, uint sequenceNumber)
-               {
-                       var incoming = GetInputBuffer (securityBuffer);
-                       var retval = (int)safeContext.Context.EncryptMessage (ref incoming);
-                       UpdateOutput (incoming, securityBuffer);
-                       return retval;
-               }
-
-               internal static int DecryptMessage (SSPIInterface secModule, SafeDeleteContext safeContext, SecurityBuffer securityBuffer, uint sequenceNumber)
-               {
-                       var incoming = GetInputBuffer (securityBuffer);
-                       var retval = (int)safeContext.Context.DecryptMessage (ref incoming);
-                       UpdateOutput (incoming, securityBuffer);
-                       return retval;
-               }
-
-               internal static byte[] CreateShutdownMessage (SSPIInterface secModule, SafeDeleteContext safeContext)
-               {
-                       return safeContext.Context.CreateCloseNotify ();
-               }
-
-               internal static byte[] CreateHelloRequestMessage (SSPIInterface secModule, SafeDeleteContext safeContext)
-               {
-                       return safeContext.Context.CreateHelloRequest ();
-               }
-
-               internal static bool IsClosed (SSPIInterface secModule, SafeDeleteContext safeContext)
-               {
-                       return safeContext.Context.ReceivedCloseNotify;
-               }
-
-               internal static SafeFreeCredentials AcquireCredentialsHandle (SSPIInterface SecModule, string package, CredentialUse intent, SecureCredential scc)
-               {
-                       return new SafeFreeCredentials (scc);
-               }
-
-               public static ChannelBinding QueryContextChannelBinding (SSPIInterface SecModule, SafeDeleteContext securityContext, ContextAttribute contextAttribute)
-               {
-                       return null;
-               }
-
-               internal static X509Certificate2 GetRemoteCertificate (SafeDeleteContext safeContext, out X509Certificate2Collection remoteCertificateStore)
-               {
-                       X509CertificateCollection monoCollection;
-                       if (safeContext == null || safeContext.IsInvalid) {
-                               remoteCertificateStore = null;
-                               return null;
-                       }
-                       var monoCert = safeContext.Context.GetRemoteCertificate (out monoCollection);
-                       if (monoCert == null) {
-                               remoteCertificateStore = null;
-                               return null;
-                       }
-
-                       remoteCertificateStore = new X509Certificate2Collection ();
-                       foreach (var cert in monoCollection) {
-                               remoteCertificateStore.Add (cert);
-                       }
-                       return (X509Certificate2)monoCert;
-               }
-
-               internal static bool CheckRemoteCertificate (SafeDeleteContext safeContext)
-               {
-                       return safeContext.Context.VerifyRemoteCertificate ();
-               }
-
-               internal static MonoTlsConnectionInfo GetMonoConnectionInfo (SSPIInterface SecModule, SafeDeleteContext securityContext)
-               {
-                       return securityContext.Context.GetConnectionInfo ();
-               }
-
-               internal static SslConnectionInfo GetConnectionInfo (SSPIInterface SecModule, SafeDeleteContext securityContext)
-               {
-                       var info = securityContext.Context.GetConnectionInfo ();
-                       if (info == null)
-                               return null;
-
-                       return new SslConnectionInfo ((int)info.ProtocolVersion);
-               }
-
-               class InputBuffer : IBufferOffsetSize
-               {
-                       public byte[] Buffer {
-                               get;
-                               private set;
-                       }
-
-                       public int Offset {
-                               get;
-                               private set;
-                       }
-
-                       public int Size {
-                               get;
-                               private set;
-                       }
-
-                       public InputBuffer (byte[] buffer, int offset, int size)
-                       {
-                               Buffer = buffer;
-                               Offset = offset;
-                               Size = size;
-                       }
-               }
-
-               static IBufferOffsetSize GetInputBuffer (SecurityBuffer incoming)
-               {
-                       return incoming != null ? new InputBuffer (incoming.token, incoming.offset, incoming.size) : null;
-               }
-
-               static void UpdateOutput (IBufferOffsetSize buffer, SecurityBuffer outputBuffer)
-               {
-                       if (buffer != null) {
-                               outputBuffer.token = buffer.Buffer;
-                               outputBuffer.offset = buffer.Offset;
-                               outputBuffer.size = buffer.Size;
-                               outputBuffer.type = BufferType.Token;
-                       } else {
-                               outputBuffer.token = null;
-                               outputBuffer.size = outputBuffer.offset = 0;
-                               outputBuffer.type = BufferType.Empty;
-                       }
-               }
-       }
-}
-#endif
index afe34459bbb58f8ae30911fd6b10b158757feed1..e7719c1afaadb5c134af12056a6613077c4fd021 100644 (file)
@@ -1,4 +1,5 @@
 using System.Net.Security;
+using System.Net.Sockets;
 
 namespace System.Net.Configuration {
        sealed class SettingsSectionInternal
@@ -16,8 +17,8 @@ namespace System.Net.Configuration {
                internal UnicodeDecodingConformance WebUtilityUnicodeDecodingConformance = UnicodeDecodingConformance.Auto;
 #endif
 
-               internal bool HttpListenerUnescapeRequestUrl = true;
-
+               internal readonly bool HttpListenerUnescapeRequestUrl = true;
+               internal readonly IPProtectionLevel IPProtectionLevel = IPProtectionLevel.Unspecified;
 
                internal bool UseNagleAlgorithm { get; set; }
                internal bool Expect100Continue { get; set; }
@@ -26,5 +27,20 @@ namespace System.Net.Configuration {
                internal bool EnableDnsRoundRobin { get; set; }
                internal bool CheckCertificateRevocationList { get; set; }
                internal EncryptionPolicy EncryptionPolicy { get; private set; }
+
+               internal bool Ipv6Enabled {
+                       get {
+#if CONFIGURATION_DEP && !MOBILE
+                               try {
+                                       var config = (SettingsSection) System.Configuration.ConfigurationManager.GetSection ("system.net/settings");
+                                       if (config != null)
+                                               return config.Ipv6.Enabled;
+                               } catch {
+                               }
+#endif
+
+                               return true;
+                       }
+               }
        }
 }
index 8c1d12b8aaaeea6744f18260c9f1db19986b9c64..b5fa6ee09e5f1dee58880f9f7a7a837a06aa7261 100644 (file)
@@ -37,10 +37,10 @@ namespace System.Net.Sockets
                // this version does not throw.
                internal void InternalShutdown (SocketShutdown how)
                {
-                       if (!is_connected || is_disposed)
+                       if (!is_connected || CleanedUp)
                                return;
                        int error;
-                       Shutdown_internal (safe_handle, how, out error);
+                       Shutdown_internal (m_Handle, how, out error);
                }
 
                internal IAsyncResult UnsafeBeginConnect (EndPoint remoteEP, AsyncCallback callback, object state)
@@ -86,7 +86,7 @@ namespace System.Net.Sockets
 
                internal void SetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue, bool silent)
                {
-                       if (is_disposed && is_closed) {
+                       if (CleanedUp && is_closed) {
                                if (silent)
                                        return;
                                throw new ObjectDisposedException (GetType ().ToString ());
@@ -94,7 +94,7 @@ namespace System.Net.Sockets
 
                        int error;
 
-                       SetSocketOption_internal (safe_handle, optionLevel, optionName, null,
+                       SetSocketOption_internal (m_Handle, optionLevel, optionName, null,
                                null, optionValue, out error);
 
                        if (!silent && error != 0)
diff --git a/mcs/class/System/ReferenceSources/SslStream.cs b/mcs/class/System/ReferenceSources/SslStream.cs
deleted file mode 100644 (file)
index fea8922..0000000
+++ /dev/null
@@ -1,141 +0,0 @@
-//
-// Mono-specific additions to Microsoft's SslStream.cs
-//
-#if MONO_FEATURE_NEW_TLS && SECURITY_DEP
-#if MONO_SECURITY_ALIAS
-extern alias MonoSecurity;
-using MonoSecurity::Mono.Security.Interface;
-#else
-using Mono.Security.Interface;
-#endif
-using System.Threading;
-using System.Security.Cryptography.X509Certificates;
-using MNS = Mono.Net.Security;
-
-namespace System.Net.Security
-{
-       using System.Net.Sockets;
-       using System.IO;
-
-       partial class SslStream : IMonoTlsEventSink
-       {
-               #if SECURITY_DEP
-               SSPIConfiguration _Configuration;
-
-               internal SslStream (Stream innerStream, bool leaveInnerStreamOpen, EncryptionPolicy encryptionPolicy, MonoTlsProvider provider, MonoTlsSettings settings)
-                       : base (innerStream, leaveInnerStreamOpen)
-               {
-                       if (encryptionPolicy != EncryptionPolicy.RequireEncryption && encryptionPolicy != EncryptionPolicy.AllowNoEncryption && encryptionPolicy != EncryptionPolicy.NoEncryption)
-                               throw new ArgumentException (SR.GetString (SR.net_invalid_enum, "EncryptionPolicy"), "encryptionPolicy");
-
-                       var validationHelper = MNS.ChainValidationHelper.CloneWithCallbackWrapper (provider, ref settings, myUserCertValidationCallbackWrapper);
-
-                       LocalCertSelectionCallback selectionCallback = null;
-                       if (validationHelper.HasCertificateSelectionCallback)
-                               selectionCallback = validationHelper.SelectClientCertificate;
-
-                       var internalProvider = new MNS.Private.MonoTlsProviderWrapper (provider);
-                       _Configuration = new MyConfiguration (internalProvider, settings, this);
-                       _SslState = new SslState (innerStream, null, selectionCallback, encryptionPolicy, _Configuration);
-               }
-
-               /*
-                * Mono-specific version of 'userCertValidationCallbackWrapper'; we're called from ChainValidationHelper.ValidateChain() here.
-                *
-                * Since we're built without the PrebuiltSystem alias, we can't use 'SslPolicyErrors' here.  This prevents us from creating a subclass of 'ChainValidationHelper'
-                * as well as providing a custom 'ServerCertValidationCallback'.
-                */
-               bool myUserCertValidationCallbackWrapper (ServerCertValidationCallback callback, X509Certificate certificate, X509Chain chain, MonoSslPolicyErrors sslPolicyErrors)
-               {
-                       m_RemoteCertificateOrBytes = certificate == null ? null : certificate.GetRawCertData ();
-                       if (callback == null) {
-                               if (!_SslState.RemoteCertRequired)
-                                       sslPolicyErrors &= ~MonoSslPolicyErrors.RemoteCertificateNotAvailable;
-
-                               return (sslPolicyErrors == MonoSslPolicyErrors.None);
-                       }
-
-                       return MNS.ChainValidationHelper.InvokeCallback (callback, this, certificate, chain, sslPolicyErrors);
-               }
-
-               class MyConfiguration : SSPIConfiguration
-               {
-                       MNS.IMonoTlsProvider provider;
-                       MonoTlsSettings settings;
-                       IMonoTlsEventSink eventSink;
-
-                       public MyConfiguration (MNS.IMonoTlsProvider provider, MonoTlsSettings settings, IMonoTlsEventSink eventSink)
-                       {
-                               this.provider = provider;
-                               this.settings = settings;
-                               this.eventSink = eventSink;
-                       }
-
-                       public MNS.IMonoTlsProvider Provider {
-                               get { return provider; }
-                       }
-
-                       public MonoTlsSettings Settings {
-                               get { return settings; }
-                       }
-
-                       public IMonoTlsEventSink EventSink {
-                               get { return eventSink; }
-                       }
-               }
-               #endif
-
-               internal bool IsClosed {
-                       get { return _SslState.IsClosed; }
-               }
-
-               internal Exception LastError {
-                       get { return lastError; }
-               }
-
-               #region IMonoTlsEventSink
-
-               Exception lastError;
-
-               void IMonoTlsEventSink.Error (Exception exception)
-               {
-                       Interlocked.CompareExchange<Exception> (ref lastError, exception, null);
-               }
-
-               void IMonoTlsEventSink.ReceivedCloseNotify ()
-               {
-               }
-
-               #endregion
-
-               internal IAsyncResult BeginShutdown (AsyncCallback asyncCallback, object asyncState)
-               {
-                       return _SslState.BeginShutdown (asyncCallback, asyncState);
-               }
-
-               internal void EndShutdown (IAsyncResult asyncResult)
-               {
-                       _SslState.EndShutdown (asyncResult);
-               }
-
-               internal IAsyncResult BeginRenegotiate (AsyncCallback asyncCallback, object asyncState)
-               {
-                       return _SslState.BeginRenegotiate (asyncCallback, asyncState);
-               }
-
-               internal void EndRenegotiate (IAsyncResult asyncResult)
-               {
-                       _SslState.EndRenegotiate (asyncResult);
-               }
-
-               internal X509Certificate InternalLocalCertificate {
-                       get { return _SslState.InternalLocalCertificate; }
-               }
-
-               internal MonoTlsConnectionInfo GetMonoConnectionInfo ()
-               {
-                       return _SslState.GetMonoConnectionInfo ();
-               }
-       }
-}
-#endif
diff --git a/mcs/class/System/ReferenceSources/_SecureChannel.cs b/mcs/class/System/ReferenceSources/_SecureChannel.cs
deleted file mode 100644 (file)
index f920353..0000000
+++ /dev/null
@@ -1,41 +0,0 @@
-//
-// Mono-specific additions to Microsoft's _SecureChannel.cs
-//
-#if MONO_FEATURE_NEW_TLS && SECURITY_DEP
-#if MONO_SECURITY_ALIAS
-extern alias MonoSecurity;
-using MonoSecurity::Mono.Security.Interface;
-#else
-using Mono.Security.Interface;
-#endif
-namespace System.Net.Security
-{
-       partial class SecureChannel
-       {
-               internal MonoTlsConnectionInfo GetMonoConnectionInfo ()
-               {
-                       return SSPIWrapper.GetMonoConnectionInfo (m_SecModule, m_SecurityContext);
-               }
-
-               internal ProtocolToken CreateShutdownMessage ()
-               {
-                       var buffer = SSPIWrapper.CreateShutdownMessage (m_SecModule, m_SecurityContext);
-                       return new ProtocolToken (buffer, SecurityStatus.ContinueNeeded);
-               }
-
-               internal ProtocolToken CreateHelloRequestMessage ()
-               {
-                       var buffer = SSPIWrapper.CreateHelloRequestMessage (m_SecModule, m_SecurityContext);
-                       return new ProtocolToken (buffer, SecurityStatus.ContinueNeeded);
-               }
-
-               internal bool IsClosed {
-                       get {
-                               if (m_SecModule == null || m_SecurityContext == null || m_SecurityContext.IsClosed)
-                                       return true;
-                               return SSPIWrapper.IsClosed (m_SecModule, m_SecurityContext);
-                       }
-               }
-       }
-}
-#endif
diff --git a/mcs/class/System/ReferenceSources/_SslState.cs b/mcs/class/System/ReferenceSources/_SslState.cs
deleted file mode 100644 (file)
index 8d5ae3f..0000000
+++ /dev/null
@@ -1,141 +0,0 @@
-//
-// Mono-specific additions to Microsoft's _SslState.cs
-//
-#if MONO_FEATURE_NEW_TLS && SECURITY_DEP
-#if MONO_SECURITY_ALIAS
-extern alias MonoSecurity;
-using MonoSecurity::Mono.Security.Interface;
-#else
-using Mono.Security.Interface;
-#endif
-namespace System.Net.Security
-{
-       using System.IO;
-       using System.Threading;
-       using System.Net.Sockets;
-
-       partial class SslState
-       {
-               int _SentShutdown;
-
-               internal MonoTlsConnectionInfo GetMonoConnectionInfo ()
-               {
-                       return Context.GetMonoConnectionInfo ();
-               }
-
-               internal bool IsClosed {
-                       get { return Context.IsClosed; }
-               }
-
-               internal ProtocolToken CreateShutdownMessage ()
-               {
-                       return Context.CreateShutdownMessage ();
-               }
-
-               internal ProtocolToken CreateHelloRequestMessage ()
-               {
-                       return Context.CreateHelloRequestMessage ();
-               }
-
-               internal IAsyncResult BeginShutdown (AsyncCallback asyncCallback, object asyncState)
-               {
-                       var shutdownResult = new ShutdownAsyncResult (this, asyncState, asyncCallback);
-
-                       if (Interlocked.CompareExchange (ref _SentShutdown, 1, 0) == 1) {
-                               shutdownResult.InvokeCallback ();
-                               return shutdownResult;
-                       }
-
-                       try
-                       {
-                               CheckThrow (false);
-                               shutdownResult.SentShutdown = true;
-                               SecureStream.BeginShutdown (shutdownResult);
-                               return shutdownResult;
-                       } catch (Exception e) {
-                               if (e is IOException)
-                                       throw;
-                               throw new IOException (SR.GetString (SR.mono_net_io_shutdown), e);
-                       }
-               }
-
-               internal void EndShutdown (IAsyncResult asyncResult)
-               {
-                       if (asyncResult == null)
-                               throw new ArgumentNullException ("asyncResult");
-
-                       var shutdownResult = asyncResult as ShutdownAsyncResult;
-                       if (shutdownResult == null)
-                               throw new ArgumentException (SR.GetString (SR.net_io_async_result, asyncResult.GetType ().FullName), "asyncResult");
-
-                       if (shutdownResult.SentShutdown)
-                               SecureStream.EndShutdown (shutdownResult);
-               }
-
-               internal IAsyncResult BeginRenegotiate (AsyncCallback asyncCallback, object asyncState)
-               {
-                       var lazyResult = new LazyAsyncResult (this, asyncState, asyncCallback);
-
-                       if (Interlocked.Exchange (ref _NestedAuth, 1) == 1)
-                               throw new InvalidOperationException (SR.GetString (SR.net_io_invalidnestedcall, "BeginRenegotiate", "renegotiate"));
-                       if (Interlocked.CompareExchange (ref _PendingReHandshake, 1, 0) == 1)
-                               throw new InvalidOperationException (SR.GetString (SR.net_io_invalidnestedcall, "BeginRenegotiate", "renegotiate"));
-
-                       try {
-                               CheckThrow (false);
-                               SecureStream.BeginRenegotiate (lazyResult);
-                               return lazyResult;
-                       } catch (Exception e) {
-                               _NestedAuth = 0;
-                               if (e is IOException)
-                                       throw;
-                               throw new IOException (SR.GetString (SR.mono_net_io_renegotiate), e);
-                       }
-               }
-
-               internal void EndRenegotiate (IAsyncResult result)
-               {
-                       if (result == null)
-                               throw new ArgumentNullException ("asyncResult");
-
-                       LazyAsyncResult lazyResult = result as LazyAsyncResult;
-                       if (lazyResult == null)
-                               throw new ArgumentException (SR.GetString (SR.net_io_async_result, result.GetType ().FullName), "asyncResult");
-
-                       if (Interlocked.Exchange (ref _NestedAuth, 0) == 0)
-                               throw new InvalidOperationException (SR.GetString (SR.net_io_invalidendcall, "EndRenegotiate"));
-
-                       SecureStream.EndRenegotiate (lazyResult);
-               }
-
-               internal bool CheckEnqueueHandshakeWrite (byte[] buffer, AsyncProtocolRequest asyncRequest)
-               {
-                       return CheckEnqueueHandshake (buffer, asyncRequest);
-               }
-
-               internal void StartReHandshake (AsyncProtocolRequest asyncRequest)
-               {
-                       if (IsServer) {
-                               byte[] buffer = null;
-                               if (CheckEnqueueHandshakeRead (ref buffer, asyncRequest))
-                                       return;
-
-                               StartReceiveBlob (buffer, asyncRequest);
-                               return;
-                       }
-
-                       ForceAuthentication (false, null, asyncRequest);
-               }
-
-               class ShutdownAsyncResult : LazyAsyncResult
-               {
-                       public bool SentShutdown;
-
-                       internal ShutdownAsyncResult (SslState instance, object userState, AsyncCallback callback)
-                               : base (instance, userState, callback)
-                       {
-                       }
-               }
-       }
-}
-#endif
diff --git a/mcs/class/System/ReferenceSources/_SslStream.cs b/mcs/class/System/ReferenceSources/_SslStream.cs
deleted file mode 100644 (file)
index 591b74a..0000000
+++ /dev/null
@@ -1,230 +0,0 @@
-//
-// Mono-specific additions to Microsoft's _SslStream.cs
-//
-#if MONO_FEATURE_NEW_TLS && SECURITY_DEP
-namespace System.Net.Security
-{
-       using System.IO;
-       using System.Threading;
-       using System.Net.Sockets;
-
-       partial class _SslStream
-       {
-               static readonly AsyncCallback _HandshakeWriteCallback = new AsyncCallback (HandshakeWriteCallback);
-               static readonly HandshakeProtocolCallback _ResumeHandshakeWriteCallback = new HandshakeProtocolCallback (ResumeHandshakeWriteCallback);
-
-               internal void BeginShutdown (LazyAsyncResult lazyResult)
-               {
-                       HandshakeProtocolRequest asyncRequest = new HandshakeProtocolRequest (lazyResult);
-
-                       if (Interlocked.Exchange (ref _NestedWrite, 1) == 1)
-                               throw new NotSupportedException (SR.GetString (SR.net_io_invalidnestedcall, (asyncRequest != null ? "BeginShutdown" : "Shutdown"), "shutdown"));
-
-                       bool failed = false;
-                       try
-                       {
-                               ProtocolToken message = _SslState.CreateShutdownMessage ();
-                               asyncRequest.SetNextRequest (HandshakeProtocolState.Shutdown, message, _ResumeHandshakeWriteCallback);
-
-                               StartHandshakeWrite (asyncRequest);
-                       } catch (Exception e) {
-                               _SslState.FinishWrite ();
-                               failed = true;
-                               throw;
-                       } finally {
-                               if (failed)
-                                       _NestedWrite = 0;
-                       }
-               }
-
-               internal void EndShutdown (LazyAsyncResult lazyResult)
-               {
-                       if (Interlocked.Exchange (ref _NestedWrite, 0) == 0)
-                               throw new InvalidOperationException (SR.GetString (SR.net_io_invalidendcall, "EndShutdown"));
-
-                       // No "artificial" timeouts implemented so far, InnerStream controls timeout.
-                       lazyResult.InternalWaitForCompletion ();
-
-                       if (lazyResult.Result is Exception) {
-                               if (lazyResult.Result is IOException)
-                                       throw (Exception)lazyResult.Result;
-                               throw new IOException (SR.GetString (SR.mono_net_io_shutdown), (Exception)lazyResult.Result);
-                       }
-               }
-
-               internal void BeginRenegotiate (LazyAsyncResult lazyResult)
-               {
-                       HandshakeProtocolRequest asyncRequest = new HandshakeProtocolRequest (lazyResult);
-
-                       if (Interlocked.Exchange (ref _NestedWrite, 1) == 1)
-                               throw new NotSupportedException (SR.GetString (SR.net_io_invalidnestedcall, (asyncRequest != null ? "BeginRenegotiate" : "Renegotiate"), "renegotiate"));
-
-                       bool failed = false;
-                       try
-                       {
-                               if (_SslState.IsServer) {
-                                       ProtocolToken message = _SslState.CreateHelloRequestMessage ();
-                                       asyncRequest.SetNextRequest (HandshakeProtocolState.SendHelloRequest, message, _ResumeHandshakeWriteCallback);
-                               } else {
-                                       asyncRequest.SetNextRequest (HandshakeProtocolState.ClientRenegotiation, null, _ResumeHandshakeWriteCallback);
-                               }
-
-                               StartHandshakeWrite (asyncRequest);
-                       } catch (Exception e) {
-                               _SslState.FinishWrite ();
-                               failed = true;
-                               throw;
-                       } finally {
-                               if (failed)
-                                       _NestedWrite = 0;
-                       }
-               }
-
-               internal void EndRenegotiate (LazyAsyncResult lazyResult)
-               {
-                       if (Interlocked.Exchange (ref _NestedWrite, 0) == 0)
-                               throw new InvalidOperationException (SR.GetString (SR.net_io_invalidendcall, "EndRenegotiate"));
-
-                       // No "artificial" timeouts implemented so far, InnerStream controls timeout.
-                       lazyResult.InternalWaitForCompletion();
-
-                       if (lazyResult.Result is Exception) {
-                               if (lazyResult.Result is IOException)
-                                       throw (Exception)lazyResult.Result;
-                               throw new IOException (SR.GetString (SR.mono_net_io_renegotiate), (Exception)lazyResult.Result);
-                       }
-               }
-
-               void StartHandshakeWrite (HandshakeProtocolRequest asyncRequest)
-               {
-                       byte[] buffer = null;
-                       if (asyncRequest.Message != null) {
-                               buffer = asyncRequest.Message.Payload;
-                               if (buffer.Length != asyncRequest.Message.Size) {
-                                       buffer = new byte [asyncRequest.Message.Size];
-                                       Buffer.BlockCopy (asyncRequest.Message.Payload, 0, buffer, 0, buffer.Length);
-                               }
-                       }
-
-                       switch (asyncRequest.State) {
-                       case HandshakeProtocolState.ClientRenegotiation:
-                       case HandshakeProtocolState.ServerRenegotiation:
-                               _SslState.StartReHandshake (asyncRequest);
-                               return;
-
-                       case HandshakeProtocolState.SendHelloRequest:
-                               if (_SslState.CheckEnqueueHandshakeWrite (buffer, asyncRequest)) {
-                                       // operation is async and has been queued, return.
-                                       return;
-                               }
-                               break;
-
-                       case HandshakeProtocolState.Shutdown:
-                               if (_SslState.CheckEnqueueWrite (asyncRequest)) {
-                                       // operation is async and has been queued, return.
-                                       return;
-                               }
-                               break;
-
-                       default:
-                               throw new InvalidOperationException ();
-                       }
-
-                       if (_SslState.LastPayload != null)
-                               throw new InvalidOperationException ();
-
-                       // prepare for the next request
-                       IAsyncResult ar = ((NetworkStream)_SslState.InnerStream).BeginWrite (buffer, 0, buffer.Length, _HandshakeWriteCallback, asyncRequest);
-                       if (!ar.CompletedSynchronously)
-                               return;
-
-                       HandshakeWriteCallback (asyncRequest, ar);
-               }
-
-               static void HandshakeWriteCallback (IAsyncResult transportResult)
-               {
-                       if (transportResult.CompletedSynchronously)
-                               return;
-
-                       HandshakeProtocolRequest asyncRequest = (HandshakeProtocolRequest)transportResult.AsyncState;
-
-                       SslState sslState = (SslState)asyncRequest.AsyncObject;
-                       sslState.SecureStream.HandshakeWriteCallback (asyncRequest, transportResult);
-               }
-
-               void HandshakeWriteCallback (HandshakeProtocolRequest asyncRequest, IAsyncResult transportResult)
-               {
-                       try {
-                               _SslState.InnerStream.EndWrite (transportResult);
-                       } catch (Exception e) {
-                               _SslState.FinishWrite ();
-                               if (!asyncRequest.IsUserCompleted) {
-                                       asyncRequest.CompleteWithError (e);
-                                       return;
-                               }
-                               throw;
-                       }
-
-                       if (asyncRequest.State == HandshakeProtocolState.SendHelloRequest) {
-                               asyncRequest.SetNextRequest (HandshakeProtocolState.ServerRenegotiation, null, _ResumeHandshakeWriteCallback);
-                               StartHandshakeWrite (asyncRequest);
-                               return;
-                       }
-
-                       try {
-                               _SslState.FinishWrite ();
-                               asyncRequest.CompleteUser ();
-                       } catch (Exception e) {
-                               if (!asyncRequest.IsUserCompleted) {
-                                       asyncRequest.CompleteWithError (e);
-                                       return;
-                               }
-                               throw;
-                       }
-               }
-
-               static void ResumeHandshakeWriteCallback (HandshakeProtocolRequest asyncRequest)
-               {
-                       try {
-                               ((_SslStream)asyncRequest.AsyncObject).StartHandshakeWrite (asyncRequest);
-                       } catch (Exception e) {
-                               if (asyncRequest.IsUserCompleted) {
-                                       // This will throw on a worker thread.
-                                       throw;
-                               }
-                               ((_SslStream)asyncRequest.AsyncObject)._SslState.FinishWrite ();
-                               asyncRequest.CompleteWithError (e);
-                       }
-               }
-
-               delegate void HandshakeProtocolCallback (HandshakeProtocolRequest asyncRequest);
-
-               enum HandshakeProtocolState {
-                       None,
-                       Shutdown,
-                       SendHelloRequest,
-                       ServerRenegotiation,
-                       ClientRenegotiation
-               }
-
-               class HandshakeProtocolRequest : AsyncProtocolRequest
-               {
-                       public ProtocolToken Message;
-                       public HandshakeProtocolState State;
-
-                       public HandshakeProtocolRequest (LazyAsyncResult userAsyncResult)
-                               : base (userAsyncResult)
-                       {
-                               State = HandshakeProtocolState.None;
-                       }
-
-                       public void SetNextRequest (HandshakeProtocolState state, ProtocolToken message, HandshakeProtocolCallback callback)
-                       {
-                               State = state;
-                               Message = message;
-                               SetNextRequest (null, 0, 0, (r) => callback ((HandshakeProtocolRequest)r));
-                       }
-               }
-       }
-}
-#endif
index e748039ef2bb842653822fea1bbc110e9e04ed75..62a424bb669ffd473e05aafea342bf3713a9fabc 100644 (file)
     <Compile Include="Mono.Net.Security\MonoSslStreamImpl.cs" />\r
     <Compile Include="Mono.Net.Security\MonoSslStreamWrapper.cs" />\r
     <Compile Include="Mono.Net.Security\MonoTlsProviderFactory.cs" />\r
-    <Compile Include="Mono.Net.Security\MonoTlsProviderImpl.cs" />\r
     <Compile Include="Mono.Net.Security\MonoTlsProviderWrapper.cs" />\r
     <Compile Include="Mono.Net.Security\MonoTlsStream.cs" />\r
     <Compile Include="Mono.Net.Security\NoReflectionHelper.cs" />\r
     <Compile Include="Mono.Net.Security\SystemCertificateValidator.cs" />\r
-    <Compile Include="ReferenceSources\_SecureChannel.cs" />\r
-    <Compile Include="ReferenceSources\_SslState.cs" />\r
-    <Compile Include="ReferenceSources\_SslStream.cs" />\r
     <Compile Include="ReferenceSources\AssertWrapper.cs" />\r
     <Compile Include="ReferenceSources\AutoWebProxyScriptEngine.cs" />\r
     <Compile Include="ReferenceSources\BinaryCompatibility.cs" />\r
     <Compile Include="ReferenceSources\EnvironmentHelpers.cs" />\r
     <Compile Include="ReferenceSources\HttpApi.cs" />\r
     <Compile Include="ReferenceSources\HttpSysSettings.cs" />\r
-    <Compile Include="ReferenceSources\Internal.cs" />\r
     <Compile Include="ReferenceSources\Logging.cs" />\r
     <Compile Include="ReferenceSources\NativeMethods.cs" />\r
     <Compile Include="ReferenceSources\RequestCacheProtocol.cs" />\r
     <Compile Include="ReferenceSources\SR.cs" />\r
     <Compile Include="ReferenceSources\SR2.cs" />\r
     <Compile Include="ReferenceSources\SRCategoryAttribute.cs" />\r
-    <Compile Include="ReferenceSources\SslStream.cs" />\r
-    <Compile Include="ReferenceSources\SSPIConfiguration.cs" />\r
-    <Compile Include="ReferenceSources\SSPISafeHandles.cs" />\r
-    <Compile Include="ReferenceSources\SSPIWrapper.cs" />\r
     <Compile Include="ReferenceSources\Win32Exception.cs" />\r
     <Compile Include="System.CodeDom.Compiler\CodeCompiler.cs" />\r
     <Compile Include="System.CodeDom.Compiler\CodeDomConfigurationHandler.cs" />\r
index fbd51bbfd99f4a6fd2f5a0ffd49d191a29b2e70d..bd89dd5b2868dc0c1f469f9e68cc97e41f7c6fd3 100644 (file)
     <Compile Include="Mono.Net.Security\MonoSslStreamImpl.cs" />\r
     <Compile Include="Mono.Net.Security\MonoSslStreamWrapper.cs" />\r
     <Compile Include="Mono.Net.Security\MonoTlsProviderFactory.cs" />\r
-    <Compile Include="Mono.Net.Security\MonoTlsProviderImpl.cs" />\r
     <Compile Include="Mono.Net.Security\MonoTlsProviderWrapper.cs" />\r
     <Compile Include="Mono.Net.Security\MonoTlsStream.cs" />\r
     <Compile Include="Mono.Net.Security\NoReflectionHelper.cs" />\r
     <Compile Include="Mono.Net.Security\SystemCertificateValidator.cs" />\r
-    <Compile Include="ReferenceSources\_SecureChannel.cs" />\r
-    <Compile Include="ReferenceSources\_SslState.cs" />\r
-    <Compile Include="ReferenceSources\_SslStream.cs" />\r
     <Compile Include="ReferenceSources\AssertWrapper.cs" />\r
     <Compile Include="ReferenceSources\AutoWebProxyScriptEngine.cs" />\r
     <Compile Include="ReferenceSources\BinaryCompatibility.cs" />\r
     <Compile Include="ReferenceSources\EnvironmentHelpers.cs" />\r
     <Compile Include="ReferenceSources\HttpApi.cs" />\r
     <Compile Include="ReferenceSources\HttpSysSettings.cs" />\r
-    <Compile Include="ReferenceSources\Internal.cs" />\r
     <Compile Include="ReferenceSources\Logging.cs" />\r
     <Compile Include="ReferenceSources\NativeMethods.cs" />\r
     <Compile Include="ReferenceSources\RequestCacheProtocol.cs" />\r
     <Compile Include="ReferenceSources\SR.cs" />\r
     <Compile Include="ReferenceSources\SR2.cs" />\r
     <Compile Include="ReferenceSources\SRCategoryAttribute.cs" />\r
-    <Compile Include="ReferenceSources\SslStream.cs" />\r
-    <Compile Include="ReferenceSources\SSPIConfiguration.cs" />\r
-    <Compile Include="ReferenceSources\SSPISafeHandles.cs" />\r
-    <Compile Include="ReferenceSources\SSPIWrapper.cs" />\r
     <Compile Include="ReferenceSources\Win32Exception.cs" />\r
     <Compile Include="System.CodeDom.Compiler\CodeCompiler.cs" />\r
     <Compile Include="System.CodeDom.Compiler\CodeDomConfigurationHandler.cs" />\r
index 16f5809c7082d25214ec7087fe319d915e2bc3f0..29567cd320bf9946eb614e97f6b90f44804b1779 100644 (file)
     <Compile Include="Mono.Net.Security\MonoSslStreamImpl.cs" />\r
     <Compile Include="Mono.Net.Security\MonoSslStreamWrapper.cs" />\r
     <Compile Include="Mono.Net.Security\MonoTlsProviderFactory.cs" />\r
-    <Compile Include="Mono.Net.Security\MonoTlsProviderImpl.cs" />\r
     <Compile Include="Mono.Net.Security\MonoTlsProviderWrapper.cs" />\r
     <Compile Include="Mono.Net.Security\MonoTlsStream.cs" />\r
     <Compile Include="Mono.Net.Security\NoReflectionHelper.cs" />\r
diff --git a/mcs/class/System/System.Diagnostics.CodeAnalysis/ExcludeFromCodeCoverageAttribute.cs b/mcs/class/System/System.Diagnostics.CodeAnalysis/ExcludeFromCodeCoverageAttribute.cs
deleted file mode 100644 (file)
index 38371ca..0000000
+++ /dev/null
@@ -1,49 +0,0 @@
-//
-// ExcludeFromCodeCoverageAttribute.cs
-//
-// Authors:
-//  Jb Evain  <jbevain@novell.com>
-//
-// Copyright (C) 2010 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.Diagnostics.CodeAnalysis {
-
-       [AttributeUsage (AttributeTargets.Class
-               | AttributeTargets.Struct
-               | AttributeTargets.Constructor
-               | AttributeTargets.Method
-               | AttributeTargets.Property
-               | AttributeTargets.Event,
-               AllowMultiple = false,
-               Inherited = false)]
-       public sealed class ExcludeFromCodeCoverageAttribute : Attribute
-       {
-               public ExcludeFromCodeCoverageAttribute ()
-               {
-               }
-       }
-}
-
diff --git a/mcs/class/System/System.Diagnostics/ProcessModuleCollection.cs b/mcs/class/System/System.Diagnostics/ProcessModuleCollection.cs
deleted file mode 100644 (file)
index c608bfe..0000000
+++ /dev/null
@@ -1,87 +0,0 @@
-//
-// System.Diagnostics.ProcessModuleCollection.cs
-//
-// Authors:
-//   Dick Porter (dick@ximian.com)
-//   Andreas Nahr (ClassDevelopment@A-SoftTech.com)
-//
-// (C) 2002 Ximian, Inc.  http://www.ximian.com
-//
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System.Collections;
-
-namespace System.Diagnostics 
-{
-#if MOBILE
-       public class ProcessModuleCollectionBase : System.Collections.Generic.List<ProcessModule>
-       {
-               protected ProcessModuleCollectionBase InnerList {
-                       get { return this; }
-               }
-
-               public System.Collections.IEnumerator GetEnumerator ()
-               {
-                       return ((System.Collections.IEnumerable)InnerList).GetEnumerator ();
-               }
-       }
-#endif
-
-       public class ProcessModuleCollection :
-#if !MOBILE    
-               ReadOnlyCollectionBase
-#else
-               ProcessModuleCollectionBase
-#endif
-       {
-               protected ProcessModuleCollection() 
-               {
-               }
-
-               public ProcessModuleCollection(ProcessModule[] processModules) 
-               {
-                       InnerList.AddRange (processModules);
-               }
-               
-               public ProcessModule this[int index] {
-                       get {
-                               return (ProcessModule)InnerList[index];
-                       }
-               }
-
-               public bool Contains(ProcessModule module) 
-               {
-                       return InnerList.Contains (module);
-               }
-
-               public void CopyTo(ProcessModule[] array, int index) 
-               {
-                       InnerList.CopyTo (array, index);
-               }
-
-               public int IndexOf(ProcessModule module) 
-               {
-                       return InnerList.IndexOf (module);
-               }
-       }
-}
diff --git a/mcs/class/System/System.Diagnostics/ProcessThreadCollection.cs b/mcs/class/System/System.Diagnostics/ProcessThreadCollection.cs
deleted file mode 100644 (file)
index 141b182..0000000
+++ /dev/null
@@ -1,113 +0,0 @@
-//
-// System.Diagnostics.ProcessThreadCollection.cs
-//
-// Authors:
-//   Dick Porter (dick@ximian.com)
-//   Andreas Nahr (ClassDevelopment@A-SoftTech.com)
-//
-// (C) 2002 Ximian, Inc.  http://www.ximian.com
-//
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System.Collections;
-
-namespace System.Diagnostics 
-{
-#if MOBILE
-       public class ProcessThreadCollectionBase : System.Collections.Generic.List<ProcessThread>
-       {
-               protected ProcessThreadCollectionBase InnerList {
-                       get { return this; }
-               }
-
-               public new int Add (ProcessThread thread)
-               {
-                       base.Add (thread);
-                       return Count - 1;
-               }
-
-               public System.Collections.IEnumerator GetEnumerator ()
-               {
-                       return ((System.Collections.IEnumerable)InnerList).GetEnumerator ();
-               }
-       }
-#endif
-
-       public class ProcessThreadCollection :
-#if !MOBILE
-               ReadOnlyCollectionBase
-#else
-               ProcessThreadCollectionBase
-#endif
-       {
-               protected ProcessThreadCollection() 
-               {
-               }
-
-               internal static ProcessThreadCollection GetEmpty ()
-               {
-                       return new ProcessThreadCollection ();
-               }
-               
-               public ProcessThreadCollection(ProcessThread[] processThreads) 
-               {
-                       InnerList.AddRange (processThreads);
-               }
-
-               public ProcessThread this[int index] {
-                       get {
-                               return (ProcessThread)InnerList[index];
-                       }
-               }
-
-               public int Add(ProcessThread thread) 
-               {
-                       return InnerList.Add (thread);
-               }
-
-               public bool Contains(ProcessThread thread) 
-               {
-                       return InnerList.Contains (thread);
-               }
-
-               public void CopyTo(ProcessThread[] array, int index) 
-               {
-                       InnerList.CopyTo (array, index);
-               }
-
-               public int IndexOf(ProcessThread thread) 
-               {
-                       return InnerList.IndexOf (thread);
-               }
-
-               public void Insert(int index, ProcessThread thread) 
-               {
-                       InnerList.Insert (index, thread);
-               }
-
-               public void Remove(ProcessThread thread) 
-               {
-                       InnerList.Remove (thread);
-               }
-       }
-}
index 3b274e0599e3bb53e849adfb400d0b3904118e18..04bd35a142f7a54ca212fb25b2faa7cebe938cdd 100644 (file)
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
+using System.ComponentModel;
+
 namespace System.IO
 {
-    public class FileSystemWatcher : IDisposable
+    public class FileSystemWatcher : Component, IDisposable, ISupportInitialize
     {
         public FileSystemWatcher () { throw new NotImplementedException (); }
         public FileSystemWatcher (string path) { throw new NotImplementedException (); }
@@ -39,11 +41,15 @@ namespace System.IO
         public int InternalBufferSize { get { throw new NotImplementedException (); } set { } }
         public NotifyFilters NotifyFilter { get { throw new NotImplementedException (); } set { } }
         public string Path { get { throw new NotImplementedException (); } set { } }
+        public override ISite Site { get { throw new NotImplementedException (); } set { } }
+        public ISynchronizeInvoke SynchronizingObject { get { throw new NotImplementedException (); } set { } }
         public event FileSystemEventHandler Changed;
         public event FileSystemEventHandler Created;
         public event FileSystemEventHandler Deleted;
         public event ErrorEventHandler Error;
         public event RenamedEventHandler Renamed;
+        public void BeginInit() { throw new NotImplementedException (); }
+        public void EndInit() { throw new NotImplementedException (); }
         protected void OnChanged (FileSystemEventArgs e) { throw new NotImplementedException (); }
         protected void OnCreated (FileSystemEventArgs e) { throw new NotImplementedException (); }
         protected void OnDeleted (System.IO.FileSystemEventArgs e) { throw new NotImplementedException (); }
@@ -51,13 +57,7 @@ namespace System.IO
         protected void OnRenamed (RenamedEventArgs e) { throw new NotImplementedException (); }
         public WaitForChangedResult WaitForChanged (WatcherChangeTypes changeType) { throw new NotImplementedException (); }
         public WaitForChangedResult WaitForChanged (WatcherChangeTypes changeType, int timeout) { throw new NotImplementedException (); }
-
-        public virtual void Dispose ()
-        {
-        }
-
-        protected virtual void Dispose (bool disposing)
-        {
-        }
+        public virtual void Dispose () { throw new NotImplementedException (); }
+        protected override void Dispose (bool disposing) { throw new NotImplementedException (); }
     }
 }
\ No newline at end of file
index 40ee139b7a02fd18e26d688b314cd231dcd51318..b5a58d86b8160caadfdf41d028408ffe441e0983 100644 (file)
@@ -153,6 +153,11 @@ namespace System.Net.Mail {
                        set { bodyEncoding = value; }
                }
 
+               public TransferEncoding BodyTransferEncoding {
+                       get { return GuessTransferEncoding (BodyEncoding); }
+                       set { throw new NotImplementedException (); }
+               }
+
                public MailAddressCollection CC {
                        get { return cc; }
                }
diff --git a/mcs/class/System/System.Net.Mail/SmtpClient.platformnotsupported.cs b/mcs/class/System/System.Net.Mail/SmtpClient.platformnotsupported.cs
new file mode 100644 (file)
index 0000000..92ef97d
--- /dev/null
@@ -0,0 +1,167 @@
+//
+// System.Net.Mail.SmtpClient.cs
+//
+// Author:
+//     Rolf Bjarne Kvinge <rolf@xamarin.com>
+//
+// Copyright (C) 2016 Xamarin Inc (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.ComponentModel;
+using System.Security.Cryptography.X509Certificates;
+using System.Threading.Tasks;
+
+namespace System.Net.Mail {
+       public class SmtpClient
+               : IDisposable
+       {
+               const string EXCEPTION_MESSAGE = "System.Net.Mail.SmtpClient is not supported on the current platform.";
+
+               public SmtpClient ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public SmtpClient (string host)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public SmtpClient (string host, int port)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+#if SECURITY_DEP
+               [MonoTODO("Client certificates not used")]
+               public X509CertificateCollection ClientCertificates {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+#endif
+
+               public string TargetName { get; set; }
+
+               public ICredentialsByHost Credentials {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public SmtpDeliveryMethod DeliveryMethod {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool EnableSsl {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string Host {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string PickupDirectoryLocation {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public int Port {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+               
+               public SmtpDeliveryFormat DeliveryFormat {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+               
+               public ServicePoint ServicePoint {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public int Timeout {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool UseDefaultCredentials {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+#pragma warning disable 0067 // The event `System.Net.Mail.SmtpClient.SendCompleted' is never used
+               public event SendCompletedEventHandler SendCompleted;
+#pragma warning restore 0067
+
+               public void Dispose ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected virtual void Dispose (bool disposing)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected void OnSendCompleted (AsyncCompletedEventArgs e)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void Send (MailMessage message)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void Send (string from, string to, string subject, string body)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public Task SendMailAsync (MailMessage message)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public Task SendMailAsync (string from, string recipients, string subject, string body)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void SendAsync (MailMessage message, object userToken)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void SendAsync (string from, string to, string subject, string body, object userToken)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void SendAsyncCancel ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+       }
+}
+
index 2b39ff8311c427735dc99ddcab36b62839b8590b..e07ff90804ecae13d0afac89c5e9a2082d280110 100644 (file)
@@ -39,8 +39,6 @@ namespace System.Net.NetworkInformation {
        {
                public static readonly Win32IPAddressCollection Empty = new Win32IPAddressCollection (IntPtr.Zero);
 
-               bool is_readonly;
-
                // for static methods
                Win32IPAddressCollection ()
                {
@@ -50,7 +48,6 @@ namespace System.Net.NetworkInformation {
                {
                        foreach (IntPtr head in heads)
                                AddSubsequentlyString (head);
-                       is_readonly = true;
                }
 
                public Win32IPAddressCollection (params Win32_IP_ADDR_STRING [] al)
@@ -58,10 +55,9 @@ namespace System.Net.NetworkInformation {
                        foreach (Win32_IP_ADDR_STRING a in al) {
                                if (String.IsNullOrEmpty (a.IpAddress))
                                        continue;
-                               Add (IPAddress.Parse (a.IpAddress));
+                               InternalAdd (IPAddress.Parse (a.IpAddress));
                                AddSubsequentlyString (a.Next);
                        }
-                       is_readonly = true;
                }
 
                public static Win32IPAddressCollection FromAnycast (IntPtr ptr)
@@ -70,9 +66,8 @@ namespace System.Net.NetworkInformation {
                        Win32_IP_ADAPTER_ANYCAST_ADDRESS a;
                        for (IntPtr p = ptr; p != IntPtr.Zero; p = a.Next) {
                                a = (Win32_IP_ADAPTER_ANYCAST_ADDRESS) Marshal.PtrToStructure (p, typeof (Win32_IP_ADAPTER_ANYCAST_ADDRESS));
-                               c.Add (a.Address.GetIPAddress ());
+                               c.InternalAdd (a.Address.GetIPAddress ());
                        }
-                       c.is_readonly = true;
                        return c;
                }
 
@@ -84,9 +79,8 @@ namespace System.Net.NetworkInformation {
                                a = (Win32_IP_ADAPTER_DNS_SERVER_ADDRESS) Marshal.PtrToStructure (p, typeof (Win32_IP_ADAPTER_DNS_SERVER_ADDRESS));
 // FIXME: It somehow fails here. Looks like there is something wrong.
 //if (a.Address.Sockaddr == IntPtr.Zero) throw new Exception ("pointer " + p + " a.length " + a.Address.SockaddrLength);
-                               c.Add (a.Address.GetIPAddress ());
+                               c.InternalAdd (a.Address.GetIPAddress ());
                        }
-                       c.is_readonly = true;
                        return c;
                }
 
@@ -95,13 +89,9 @@ namespace System.Net.NetworkInformation {
                        Win32_IP_ADDR_STRING a;
                        for (IntPtr p = head; p != IntPtr.Zero; p = a.Next) {
                                a = (Win32_IP_ADDR_STRING) Marshal.PtrToStructure (p, typeof (Win32_IP_ADDR_STRING));
-                               Add (IPAddress.Parse (a.IpAddress));
+                               InternalAdd (IPAddress.Parse (a.IpAddress));
                        }
                }
-
-               public override bool IsReadOnly {
-                       get { return is_readonly; }
-               }
        }
 #endif
 }
index ece698af2b45ee2714a2c52e822ce4a09c90083d..d1bf2e763b08f02eb55c7bd576b58c423bbacf9d 100644 (file)
@@ -438,9 +438,14 @@ namespace System.Net.NetworkInformation {
 #if !MOBILE
                class Win32NetworkInterfaceAPI : NetworkInterfaceFactory
                {
-                       [DllImport ("iphlpapi.dll", SetLastError = true)]
+                       private const string IPHLPAPI = "iphlpapi.dll";
+
+                       [DllImport (IPHLPAPI, SetLastError = true)]
                        static extern int GetAdaptersAddresses (uint family, uint flags, IntPtr reserved, byte [] info, ref int size);
 
+                       [DllImport (IPHLPAPI)]
+                       static extern uint GetBestInterfaceEx (byte[] ipAddress, out int index);
+
                        unsafe static Win32_IP_ADAPTER_ADDRESSES [] GetAdaptersAddresses ()
                        {
                                byte [] bytes = null;
@@ -473,9 +478,20 @@ namespace System.Net.NetworkInformation {
                                return ret;
                        }
 
+                       private static int GetBestInterfaceForAddress (IPAddress addr) {
+                               int index;
+                               SocketAddress address = new SocketAddress (addr);
+                               int error = (int) GetBestInterfaceEx (address.m_Buffer, out index);
+                               if (error != 0) {
+                                       throw new NetworkInformationException (error);
+                               }
+
+                               return index;
+                       }
+
                        public override int GetLoopbackInterfaceIndex ()
                        {
-                               throw new NotImplementedException ();
+                               return GetBestInterfaceForAddress (IPAddress.Loopback);
                        }
 
                        public override IPAddress GetNetMask (IPAddress address)
index 72645bcd3a712796e6c935af1280e12d887907b9..8232a9eaac445c5a035e6bff57ab6ef45357b3ff 100644 (file)
@@ -262,12 +262,12 @@ namespace System.Net.NetworkInformation {
                                bytes = new byte [100];
                                do {
                                        EndPoint endpoint = client;
-                                       int error = 0;
-                                       int rc = s.ReceiveFrom_nochecks_exc (bytes, 0, 100, SocketFlags.None,
-                                                       ref endpoint, false, out error);
+                                       SocketError error = 0;
+                                       int rc = s.ReceiveFrom (bytes, 0, 100, SocketFlags.None,
+                                                       ref endpoint, out error);
 
-                                       if (error != 0) {
-                                               if (error == (int) SocketError.TimedOut) {
+                                       if (error != SocketError.Success) {
+                                               if (error == SocketError.TimedOut) {
                                                        return new PingReply (null, new byte [0], options, 0, IPStatus.TimedOut);
                                                }
                                                throw new NotSupportedException (String.Format ("Unexpected socket error during ping request: {0}", error));
index f9cb48fc731b07da8b83cabcb4cbc23210ccf733..d58a0e261fc7121c38abf31ba0a3f1847e4a4883 100644 (file)
@@ -25,7 +25,6 @@
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
-#if !MONO_FEATURE_NEW_TLS
 namespace System.Net.Security
 {
        public enum EncryptionPolicy
@@ -35,4 +34,3 @@ namespace System.Net.Security
                NoEncryption
        }
 }
-#endif
index 9b77646d7b1502b669d501fcd04bd3e9197c687c..f71585c0f00590751d0cf31b4dcc030cec20e7d7 100644 (file)
@@ -28,7 +28,7 @@
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
-#if SECURITY_DEP && !MONO_FEATURE_NEW_TLS
+#if SECURITY_DEP
 
 using System.Security.Cryptography.X509Certificates;
 
index ad9e3526ff740c4e1a682f38592ab6529ddcf54d..0ee2c7b8258f7f4fc72038ca3c99e8d243507aee 100644 (file)
@@ -148,6 +148,12 @@ namespace System.Net.Security
                        throw new NotImplementedException ();
                }
 
+               [MonoTODO]
+               public virtual IAsyncResult BeginAuthenticateAsClient (NetworkCredential credential, ChannelBinding binding, string targetName, AsyncCallback asyncCallback, object asyncState)
+               {
+                       throw new NotImplementedException ();
+               }
+
                [MonoTODO]
                public virtual IAsyncResult BeginAuthenticateAsClient (NetworkCredential credential, string targetName, AsyncCallback asyncCallback, object asyncState)
                {
@@ -160,6 +166,12 @@ namespace System.Net.Security
                        throw new NotImplementedException ();
                }
 
+               [MonoTODO]
+               public virtual IAsyncResult BeginAuthenticateAsClient (NetworkCredential credential, ChannelBinding binding, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel, AsyncCallback asyncCallback, object asyncState)
+               {
+                       throw new NotImplementedException ();
+               }
+
                [MonoTODO]
                public override IAsyncResult BeginRead (byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
                {
@@ -172,12 +184,24 @@ namespace System.Net.Security
                        throw new NotImplementedException ();
                }
 
+               [MonoTODO]
+               public virtual IAsyncResult BeginAuthenticateAsServer (NetworkCredential credential, ExtendedProtectionPolicy policy, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel, AsyncCallback asyncCallback, object asyncState)
+               {
+                       throw new NotImplementedException ();
+               }
+
                [MonoTODO]
                public virtual IAsyncResult BeginAuthenticateAsServer (NetworkCredential credential, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel, AsyncCallback asyncCallback, object asyncState)
                {
                        throw new NotImplementedException ();
                }
 
+               [MonoTODO]
+               public virtual IAsyncResult BeginAuthenticateAsServer (ExtendedProtectionPolicy policy, AsyncCallback asyncCallback, object asyncState)
+               {
+                       throw new NotImplementedException ();
+               }
+
                [MonoTODO]
                public override IAsyncResult BeginWrite (byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
                {
@@ -196,6 +220,18 @@ namespace System.Net.Security
                        throw new NotImplementedException ();
                }
 
+               [MonoTODO]
+               public virtual void AuthenticateAsClient (NetworkCredential credential, ChannelBinding binding, string targetName)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               [MonoTODO]
+               public virtual void AuthenticateAsClient (NetworkCredential credential, ChannelBinding binding, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel)
+               {
+                       throw new NotImplementedException ();
+               }
+
                [MonoTODO]
                public virtual void AuthenticateAsClient (NetworkCredential credential, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel)
                {
@@ -208,6 +244,18 @@ namespace System.Net.Security
                        throw new NotImplementedException ();
                }
 
+               [MonoTODO]
+               public virtual void AuthenticateAsServer (ExtendedProtectionPolicy policy)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               [MonoTODO]
+               public virtual void AuthenticateAsServer (NetworkCredential credential, ExtendedProtectionPolicy policy, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel)
+               {
+                       throw new NotImplementedException ();
+               }
+
                [MonoTODO]
                public virtual void AuthenticateAsServer (NetworkCredential credential, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel)
                {
index 9238428b1f3841de180dc5f09f3944336a9d82d1..3db9e6b4ad47c8e51a1db1dbfa77934a2e3a8339 100644 (file)
@@ -28,8 +28,6 @@
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
-#if !MONO_FEATURE_NEW_TLS
-
 using System.Security.Cryptography.X509Certificates;
 
 namespace System.Net.Security 
@@ -40,4 +38,3 @@ namespace System.Net.Security
                X509Chain chain,
                SslPolicyErrors sslPolicyErrors);
 }
-#endif
index 5a88d88e8bfdaea77a4023501075882b706e0e50..0da167c71b87cbef0408fe84de46667b1f328d0b 100644 (file)
@@ -25,7 +25,6 @@
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
-#if !MONO_FEATURE_NEW_TLS
 namespace System.Net.Security 
 {
        [Flags]
@@ -37,4 +36,3 @@ namespace System.Net.Security
                RemoteCertificateChainErrors = 4,
        }
 }
-#endif
index 3e7320e3cd160e259773efe54cece0fe38250afa..bf483016db3025211c0293aa96997b51d9e4320f 100644 (file)
@@ -24,7 +24,6 @@
 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 // THE SOFTWARE.
 
-#if !MONO_FEATURE_NEW_TLS
 #if SECURITY_DEP
 
 #if MONO_SECURITY_ALIAS
@@ -410,5 +409,3 @@ namespace System.Net.Security
        }
 }
 #endif
-
-#endif
diff --git a/mcs/class/System/System.Net.Security/SslStream.platformnotsupported.cs b/mcs/class/System/System.Net.Security/SslStream.platformnotsupported.cs
new file mode 100644 (file)
index 0000000..1d3f040
--- /dev/null
@@ -0,0 +1,287 @@
+//
+// SslStream.cs
+//
+// Author:
+//       Rolf Bjarne Kvinge <rolf@xamarin.com>
+//
+// Copyright (c) 2016 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.IO;
+using System.Security.Authentication;
+using System.Security.Cryptography.X509Certificates;
+using System.Threading.Tasks;
+
+namespace System.Net.Security
+{
+       public class SslStream : AuthenticatedStream
+       {
+               const string EXCEPTION_MESSAGE = "System.Net.Security.SslStream is not supported on the current platform.";
+
+               public SslStream (Stream innerStream)
+                       : this (innerStream, false, null, null)
+               {
+               }
+
+               public SslStream (Stream innerStream, bool leaveInnerStreamOpen)
+                       : this (innerStream, leaveInnerStreamOpen, null, null)
+               {
+               }
+
+               public SslStream (Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback)
+                       : this (innerStream, leaveInnerStreamOpen, userCertificateValidationCallback, null)
+               {
+               }
+
+               public SslStream (Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback, LocalCertificateSelectionCallback userCertificateSelectionCallback)
+                       : base (innerStream, leaveInnerStreamOpen)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public SslStream (Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback, LocalCertificateSelectionCallback userCertificateSelectionCallback, EncryptionPolicy encryptionPolicy)
+                       : this (innerStream, leaveInnerStreamOpen, userCertificateValidationCallback, userCertificateSelectionCallback)
+               {
+               }
+
+               public virtual void AuthenticateAsClient (string targetHost)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual void AuthenticateAsClient (string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual IAsyncResult BeginAuthenticateAsClient (string targetHost, AsyncCallback asyncCallback, object asyncState)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual IAsyncResult BeginAuthenticateAsClient (string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual void EndAuthenticateAsClient (IAsyncResult asyncResult)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual void AuthenticateAsServer (X509Certificate serverCertificate)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual void AuthenticateAsServer (X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual IAsyncResult BeginAuthenticateAsServer (X509Certificate serverCertificate, AsyncCallback asyncCallback, object asyncState)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual IAsyncResult BeginAuthenticateAsServer (X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual void EndAuthenticateAsServer (IAsyncResult asyncResult)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public TransportContext TransportContext {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public virtual Task AuthenticateAsClientAsync (string targetHost)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual Task AuthenticateAsClientAsync (string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual Task AuthenticateAsServerAsync (X509Certificate serverCertificate)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public virtual Task AuthenticateAsServerAsync (X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override bool IsAuthenticated {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override bool IsMutuallyAuthenticated {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override bool IsEncrypted {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override bool IsSigned {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override bool IsServer {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public virtual SslProtocols SslProtocol {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public virtual bool CheckCertRevocationStatus {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public virtual X509Certificate LocalCertificate {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public virtual X509Certificate RemoteCertificate {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public virtual CipherAlgorithmType CipherAlgorithm {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public virtual int CipherStrength {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public virtual HashAlgorithmType HashAlgorithm {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public virtual int HashStrength {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public virtual ExchangeAlgorithmType KeyExchangeAlgorithm {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public virtual int KeyExchangeStrength {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override bool CanSeek {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override bool CanRead {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override bool CanTimeout {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override bool CanWrite {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override int ReadTimeout {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override int WriteTimeout {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override long Length {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override long Position {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override void SetLength (long value)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override long Seek (long offset, SeekOrigin origin)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override void Flush ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected override void Dispose (bool disposing)
+               {
+               }
+
+               public override int Read (byte[] buffer, int offset, int count)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void Write (byte[] buffer)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override void Write (byte[] buffer, int offset, int count)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override IAsyncResult BeginRead (byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override int EndRead (IAsyncResult asyncResult)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override IAsyncResult BeginWrite (byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override void EndWrite (IAsyncResult asyncResult)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+       }
+}
diff --git a/mcs/class/System/System.Net.Sockets/SendPacketsElement.cs b/mcs/class/System/System.Net.Sockets/SendPacketsElement.cs
deleted file mode 100644 (file)
index 983faa9..0000000
+++ /dev/null
@@ -1,89 +0,0 @@
-// System.Net.Sockets.SocketAsyncEventArgs.cs
-//
-// Authors:
-//     Marek Habersack (mhabersack@novell.com)
-//
-// Copyright (c) 2008 Novell, Inc. (http://www.novell.com)
-//
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-using System;
-
-namespace System.Net.Sockets
-{
-       public class SendPacketsElement
-       {
-               public byte[] Buffer { get; private set; }
-               public int Count { get; private set; }
-               public bool EndOfPacket { get; private set; }
-               public string FilePath { get; private set; }
-               public int Offset { get; private set; }
-
-               public SendPacketsElement (byte[] buffer) : this (buffer, 0, buffer != null ? buffer.Length : 0)
-               {
-               }
-
-               public SendPacketsElement (byte[] buffer, int offset, int count) : this (buffer, offset, count, false)
-               {
-               }
-
-               public SendPacketsElement (byte[] buffer, int offset, int count, bool endOfPacket)
-               {
-                       if (buffer == null)
-                               throw new ArgumentNullException ("buffer");
-
-                       int buflen = buffer.Length;
-                       if (offset < 0 || offset >= buflen)
-                               throw new ArgumentOutOfRangeException ("offset");
-
-                       if (count < 0 || offset + count >= buflen)
-                               throw new ArgumentOutOfRangeException ("count");
-
-                       Buffer = buffer;
-                       Offset = offset;
-                       Count = count;
-                       EndOfPacket = endOfPacket;
-                       FilePath = null;
-               }
-               
-               public SendPacketsElement (string filepath) : this (filepath, 0, 0, false)
-               {
-               }
-
-               public SendPacketsElement (string filepath, int offset, int count) : this (filepath, offset, count, false)
-               {
-               }
-
-               // LAME SPEC: only ArgumentNullException for filepath is thrown
-               public SendPacketsElement (string filepath, int offset, int count, bool endOfPacket)
-               {
-                       if (filepath == null)
-                               throw new ArgumentNullException ("filepath");
-
-                       Buffer = null;
-                       Offset = offset;
-                       Count = count;
-                       EndOfPacket = endOfPacket;
-                       FilePath = filepath;
-               }
-       }
-}
index 396b16f4c5416c06b77b6666e47c6404ea198e26..9857fc27ed0b86ef0d14695a00a541a21784f888 100644 (file)
@@ -55,27 +55,20 @@ namespace System.Net.Sockets
                const string TIMEOUT_EXCEPTION_MSG = "A connection attempt failed because the connected party did not properly respond" +
                        "after a period of time, or established connection failed because connected host has failed to respond";
 
-               /*
-                *      These two fields are looked up by name by the runtime, don't change
-                *  their name without also updating the runtime code.
-                */
-               static int ipv4_supported = -1;
-               static int ipv6_supported = -1;
-
                /* true if we called Close_internal */
                bool is_closed;
 
                bool is_listening;
-               bool use_overlapped_io;
+               bool useOverlappedIO;
 
                int linger_timeout;
 
-               AddressFamily address_family;
-               SocketType socket_type;
-               ProtocolType protocol_type;
+               AddressFamily addressFamily;
+               SocketType socketType;
+               ProtocolType protocolType;
 
-               /* the field "safe_handle" is looked up by name by the runtime */
-               internal SafeSocketHandle safe_handle;
+               /* the field "m_Handle" is looked up by name by the runtime */
+               internal SafeSocketHandle m_Handle;
 
                /*
                 * This EndPoint is used when creating new endpoints. Because
@@ -86,8 +79,8 @@ namespace System.Net.Sockets
                 */
                internal EndPoint seed_endpoint = null;
 
-               internal Queue<KeyValuePair<IntPtr, IOSelectorJob>> readQ = new Queue<KeyValuePair<IntPtr, IOSelectorJob>> (2);
-               internal Queue<KeyValuePair<IntPtr, IOSelectorJob>> writeQ = new Queue<KeyValuePair<IntPtr, IOSelectorJob>> (2);
+               internal SemaphoreSlim ReadSem = new SemaphoreSlim (1, 1);
+               internal SemaphoreSlim WriteSem = new SemaphoreSlim (1, 1);
 
                internal bool is_blocking = true;
                internal bool is_bound;
@@ -95,143 +88,59 @@ namespace System.Net.Sockets
                /* When true, the socket was connected at the time of the last IO operation */
                internal bool is_connected;
 
-               internal bool is_disposed;
+               int m_IntCleanedUp;
                internal bool connect_in_progress;
 
 #region Constructors
 
-               static Socket ()
-               {
-                       if (ipv4_supported == -1) {
-                               try {
-                                       Socket tmp = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
-                                       tmp.Close();
-
-                                       ipv4_supported = 1;
-                               } catch {
-                                       ipv4_supported = 0;
-                               }
-                       }
-
-                       if (ipv6_supported == -1) {
-                               // We need to put a try/catch around ConfigurationManager methods as will always throw an exception 
-                               // when run in a mono embedded application.  This occurs as embedded applications do not have a setup
-                               // for application config.  The exception is not thrown when called from a normal .NET application. 
-                               //
-                               // We, then, need to guard calls to the ConfigurationManager.  If the config is not found or throws an
-                               // exception, will fall through to the existing Socket / API directly below in the code.
-                               //
-                               // Also note that catching ConfigurationErrorsException specifically would require library dependency
-                               // System.Configuration, and wanted to avoid that.
-#if !MOBILE
-#if CONFIGURATION_DEP
-                               try {
-                                       SettingsSection config;
-                                       config = (SettingsSection) System.Configuration.ConfigurationManager.GetSection ("system.net/settings");
-                                       if (config != null)
-                                               ipv6_supported = config.Ipv6.Enabled ? -1 : 0;
-                               } catch {
-                                       ipv6_supported = -1;
-                               }
-#else
-                               try {
-                                       NetConfig config = System.Configuration.ConfigurationSettings.GetConfig("system.net/settings") as NetConfig;
-                                       if (config != null)
-                                               ipv6_supported = config.ipv6Enabled ? -1 : 0;
-                               } catch {
-                                       ipv6_supported = -1;
-                               }
-#endif
-#endif
-                               if (ipv6_supported != 0) {
-                                       try {
-                                               Socket tmp = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
-                                               tmp.Close();
-
-                                               ipv6_supported = 1;
-                                       } catch {
-                                               ipv6_supported = 0;
-                                       }
-                               }
-                       }
-               }
-
-               //
-               // This constructor is used by servers that want to listen for instance on both
-               // ipv4 and ipv6.   Mono has historically done that if you use InterNetworkV6 (at
-               // least on Unix), because that is the default behavior unless the IPV6_V6ONLY
-               // option is explicitly set by using setsockopt (sock, IPPROTO_IPV6, IPV6_ONLY)
-               //
-               public Socket (SocketType socketType, ProtocolType protocolType)
-                       : this (AddressFamily.InterNetworkV6, socketType, protocolType)
-               {
-                       DualMode = true;
-               }
-               
-               public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
-               {
-                       this.address_family = addressFamily;
-                       this.socket_type = socketType;
-                       this.protocol_type = protocolType;
-
-                       int error;
-                       this.safe_handle = new SafeSocketHandle (Socket_internal (addressFamily, socketType, protocolType, out error), true);
-
-                       if (error != 0)
-                               throw new SocketException (error);
-
-                       SocketDefaults ();
-               }
 
-#if !MOBILE
                public Socket (SocketInformation socketInformation)
                {
                        this.is_listening      = (socketInformation.Options & SocketInformationOptions.Listening) != 0;
                        this.is_connected      = (socketInformation.Options & SocketInformationOptions.Connected) != 0;
                        this.is_blocking       = (socketInformation.Options & SocketInformationOptions.NonBlocking) == 0;
-                       this.use_overlapped_io = (socketInformation.Options & SocketInformationOptions.UseOnlyOverlappedIO) != 0;
+                       this.useOverlappedIO = (socketInformation.Options & SocketInformationOptions.UseOnlyOverlappedIO) != 0;
 
                        var result = Mono.DataConverter.Unpack ("iiiil", socketInformation.ProtocolInformation, 0);
 
-                       this.address_family = (AddressFamily) (int) result [0];
-                       this.socket_type = (SocketType) (int) result [1];
-                       this.protocol_type = (ProtocolType) (int) result [2];
+                       this.addressFamily = (AddressFamily) (int) result [0];
+                       this.socketType = (SocketType) (int) result [1];
+                       this.protocolType = (ProtocolType) (int) result [2];
                        this.is_bound = (ProtocolType) (int) result [3] != 0;
-                       this.safe_handle = new SafeSocketHandle ((IntPtr) (long) result [4], true);
+                       this.m_Handle = new SafeSocketHandle ((IntPtr) (long) result [4], true);
+
+                       InitializeSockets ();
 
                        SocketDefaults ();
                }
-#endif
 
                /* private constructor used by Accept, which already has a socket handle to use */
                internal Socket(AddressFamily family, SocketType type, ProtocolType proto, SafeSocketHandle safe_handle)
                {
-                       this.address_family = family;
-                       this.socket_type = type;
-                       this.protocol_type = proto;
+                       this.addressFamily = family;
+                       this.socketType = type;
+                       this.protocolType = proto;
                        
-                       this.safe_handle = safe_handle;
+                       this.m_Handle = safe_handle;
                        this.is_connected = true;
-               }
 
-               ~Socket ()
-               {
-                       Dispose (false);
+                       InitializeSockets ();   
                }
 
                void SocketDefaults ()
                {
                        try {
                                /* Need to test IPv6 further */
-                               if (address_family == AddressFamily.InterNetwork
-                                       // || address_family == AddressFamily.InterNetworkV6
+                               if (addressFamily == AddressFamily.InterNetwork
+                                       // || addressFamily == AddressFamily.InterNetworkV6
                                ) {
                                        /* This is the default, but it probably has nasty side
                                         * effects on Linux, as the socket option is kludged by
                                         * turning on or off PMTU discovery... */
                                        this.DontFragment = false;
-                                       this.NoDelay = false;
-                               } else if (address_family == AddressFamily.InterNetworkV6) {
+                                       if (protocolType == ProtocolType.Tcp)
+                                               this.NoDelay = false;
+                               } else if (addressFamily == AddressFamily.InterNetworkV6) {
                                        this.DualMode = true;
                                }
 
@@ -252,60 +161,12 @@ namespace System.Net.Sockets
 
 #region Properties
 
-               [ObsoleteAttribute ("Use OSSupportsIPv4 instead")]
-               public static bool SupportsIPv4 {
-                       get { return ipv4_supported == 1; }
-               }
-
-               [ObsoleteAttribute ("Use OSSupportsIPv6 instead")]
-               public static bool SupportsIPv6 {
-                       get { return ipv6_supported == 1; }
-               }
-
-#if MOBILE
-               public static bool OSSupportsIPv4 {
-                       get { return ipv4_supported == 1; }
-               }
-#else
-               public static bool OSSupportsIPv4 {
-                       get {
-                               NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces ();
-
-                               foreach (NetworkInterface adapter in nics) {
-                                       if (adapter.Supports (NetworkInterfaceComponent.IPv4))
-                                               return true;
-                               }
-
-                               return false;
-                       }
-               }
-#endif
-
-#if MOBILE
-               public static bool OSSupportsIPv6 {
-                       get { return ipv6_supported == 1; }
-               }
-#else
-               public static bool OSSupportsIPv6 {
-                       get {
-                               NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces ();
-
-                               foreach (NetworkInterface adapter in nics) {
-                                       if (adapter.Supports (NetworkInterfaceComponent.IPv6))
-                                               return true;
-                               }
-
-                               return false;
-                       }
-               }
-#endif
-
                public int Available {
                        get {
                                ThrowIfDisposedAndClosed ();
 
                                int ret, error;
-                               ret = Available_internal (safe_handle, out error);
+                               ret = Available_internal (m_Handle, out error);
 
                                if (error != 0)
                                        throw new SocketException (error);
@@ -330,40 +191,12 @@ namespace System.Net.Sockets
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
                extern static int Available_internal (IntPtr socket, out int error);
 
-               public bool DontFragment {
-                       get {
-                               ThrowIfDisposedAndClosed ();
-
-                               switch (address_family) {
-                               case AddressFamily.InterNetwork:
-                                       return ((int) GetSocketOption (SocketOptionLevel.IP, SocketOptionName.DontFragment)) != 0;
-                               case AddressFamily.InterNetworkV6:
-                                       return ((int) GetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.DontFragment)) != 0;
-                               default:
-                                       throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
-                               }
-                       }
-                       set {
-                               ThrowIfDisposedAndClosed ();
-
-                               switch (address_family) {
-                               case AddressFamily.InterNetwork:
-                                       SetSocketOption (SocketOptionLevel.IP, SocketOptionName.DontFragment, value ? 1 : 0);
-                                       break;
-                               case AddressFamily.InterNetworkV6:
-                                       SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.DontFragment, value ? 1 : 0);
-                                       break;
-                               default:
-                                       throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
-                               }
-                       }
-               }
-
+               // FIXME: import from referencesource
                public bool EnableBroadcast {
                        get {
                                ThrowIfDisposedAndClosed ();
 
-                               if (protocol_type != ProtocolType.Udp)
+                               if (protocolType != ProtocolType.Udp)
                                        throw new SocketException ((int) SocketError.ProtocolOption);
 
                                return ((int) GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Broadcast)) != 0;
@@ -371,47 +204,20 @@ namespace System.Net.Sockets
                        set {
                                ThrowIfDisposedAndClosed ();
 
-                               if (protocol_type != ProtocolType.Udp)
+                               if (protocolType != ProtocolType.Udp)
                                        throw new SocketException ((int) SocketError.ProtocolOption);
 
                                SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Broadcast, value ? 1 : 0);
                        }
                }
 
-               public bool ExclusiveAddressUse {
-                       get {
-                               ThrowIfDisposedAndClosed ();
-
-                               return ((int) GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse)) != 0;
-                       }
-                       set {
-                               ThrowIfDisposedAndClosed ();
-
-                               if (is_bound)
-                                       throw new InvalidOperationException ("Bind has already been called for this socket");
-
-                               SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, value ? 1 : 0);
-                       }
-               }
-
                public bool IsBound {
                        get {
                                return is_bound;
                        }
                }
 
-               public LingerOption LingerState {
-                       get {
-                               ThrowIfDisposedAndClosed ();
-
-                               return (LingerOption) GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Linger);
-                       }
-                       set {
-                               ThrowIfDisposedAndClosed ();
-                               SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Linger, value);
-                       }
-               }
-
+               // FIXME: import from referencesource
                public bool MulticastLoopback {
                        get {
                                ThrowIfDisposedAndClosed ();
@@ -421,10 +227,10 @@ namespace System.Net.Sockets
                                 * "Setting this property on a Transmission Control Protocol (TCP)
                                 * socket will have no effect." but the MS runtime throws the
                                 * exception...) */
-                               if (protocol_type == ProtocolType.Tcp)
+                               if (protocolType == ProtocolType.Tcp)
                                        throw new SocketException ((int)SocketError.ProtocolOption);
 
-                               switch (address_family) {
+                               switch (addressFamily) {
                                case AddressFamily.InterNetwork:
                                        return ((int) GetSocketOption (SocketOptionLevel.IP, SocketOptionName.MulticastLoopback)) != 0;
                                case AddressFamily.InterNetworkV6:
@@ -441,10 +247,10 @@ namespace System.Net.Sockets
                                 * "Setting this property on a Transmission Control Protocol (TCP)
                                 * socket will have no effect." but the MS runtime throws the
                                 * exception...) */
-                               if (protocol_type == ProtocolType.Tcp)
+                               if (protocolType == ProtocolType.Tcp)
                                        throw new SocketException ((int)SocketError.ProtocolOption);
 
-                               switch (address_family) {
+                               switch (addressFamily) {
                                case AddressFamily.InterNetwork:
                                        SetSocketOption (SocketOptionLevel.IP, SocketOptionName.MulticastLoopback, value ? 1 : 0);
                                        break;
@@ -457,37 +263,6 @@ namespace System.Net.Sockets
                        }
                }
 
-               public bool DualMode {
-                       get {
-                               if (AddressFamily != AddressFamily.InterNetworkV6) 
-                                       throw new NotSupportedException("This protocol version is not supported");
-
-                               return ((int)GetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only) == 0);
-                       }
-                       set {
-                               if (AddressFamily != AddressFamily.InterNetworkV6) 
-                                       throw new NotSupportedException("This protocol version is not supported");
-
-                               SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, value ? 0 : 1);
-                       }
-               }
-
-               private bool IsDualMode {
-                       get {
-                               return AddressFamily == AddressFamily.InterNetworkV6 && DualMode;
-                       }
-               }
-
-               [MonoTODO ("This doesn't do anything on Mono yet")]
-               public bool UseOnlyOverlappedIO {
-                       get { return use_overlapped_io; }
-                       set { use_overlapped_io = value; }
-               }
-
-               public IntPtr Handle {
-                       get { return safe_handle.DangerousGetHandle (); }
-               }
-
                // Wish:  support non-IP endpoints.
                public EndPoint LocalEndPoint {
                        get {
@@ -499,7 +274,7 @@ namespace System.Net.Sockets
                                        return null;
 
                                int error;
-                               SocketAddress sa = LocalEndPoint_internal (safe_handle, (int) address_family, out error);
+                               SocketAddress sa = LocalEndPoint_internal (m_Handle, (int) addressFamily, out error);
 
                                if (error != 0)
                                        throw new SocketException (error);
@@ -524,61 +299,13 @@ namespace System.Net.Sockets
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
                extern static SocketAddress LocalEndPoint_internal (IntPtr socket, int family, out int error);
 
-               public SocketType SocketType {
-                       get { return socket_type; }
-               }
-
-               public int SendTimeout {
-                       get {
-                               ThrowIfDisposedAndClosed ();
-
-                               return (int) GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.SendTimeout);
-                       }
-                       set {
-                               ThrowIfDisposedAndClosed ();
-
-                               if (value < -1)
-                                       throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than -1");
-
-                               /* According to the MSDN docs we should adjust values between 1 and
-                                * 499 to 500, but the MS runtime doesn't do this. */
-                               if (value == -1)
-                                       value = 0;
-
-                               SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, value);
-                       }
-               }
-
-               public int ReceiveTimeout {
-                       get {
-                               ThrowIfDisposedAndClosed ();
-
-                               return (int) GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout);
-                       }
-                       set {
-                               ThrowIfDisposedAndClosed ();
-
-                               if (value < -1)
-                                       throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than -1");
-
-                               if (value == -1)
-                                       value = 0;
-
-                               SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, value);
-                       }
-               }
-
-               public AddressFamily AddressFamily {
-                       get { return address_family; }
-               }
-
                public bool Blocking {
                        get { return is_blocking; }
                        set {
                                ThrowIfDisposedAndClosed ();
 
                                int error;
-                               Blocking_internal (safe_handle, value, out error);
+                               Blocking_internal (m_Handle, value, out error);
 
                                if (error != 0)
                                        throw new SocketException (error);
@@ -607,10 +334,7 @@ namespace System.Net.Sockets
                        internal set { is_connected = value; }
                }
 
-               public ProtocolType ProtocolType {
-                       get { return protocol_type; }
-               }
-
+               // FIXME: import from referencesource
                public bool NoDelay {
                        get {
                                ThrowIfDisposedAndClosed ();
@@ -622,75 +346,10 @@ namespace System.Net.Sockets
                        set {
                                ThrowIfDisposedAndClosed ();
                                ThrowIfUdp ();
-
                                SetSocketOption (SocketOptionLevel.Tcp, SocketOptionName.NoDelay, value ? 1 : 0);
                        }
                }
 
-               public int ReceiveBufferSize {
-                       get {
-                               ThrowIfDisposedAndClosed ();
-
-                               return (int) GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer);
-                       }
-                       set {
-                               ThrowIfDisposedAndClosed ();
-
-                               if (value < 0)
-                                       throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than zero");
-
-                               SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, value);
-                       }
-               }
-
-               public int SendBufferSize {
-                       get {
-                               ThrowIfDisposedAndClosed ();
-
-                               return (int) GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.SendBuffer);
-                       }
-                       set {
-                               ThrowIfDisposedAndClosed ();
-
-                               if (value < 0)
-                                       throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than zero");
-
-                               SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.SendBuffer, value);
-                       }
-               }
-
-               public short Ttl {
-                       get {
-                               ThrowIfDisposedAndClosed ();
-
-                               switch (address_family) {
-                               case AddressFamily.InterNetwork:
-                                       return (short) (int) GetSocketOption (SocketOptionLevel.IP, SocketOptionName.IpTimeToLive);
-                               case AddressFamily.InterNetworkV6:
-                                       return (short) (int) GetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.HopLimit);
-                               default:
-                                       throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
-                               }
-                       }
-                       set {
-                               ThrowIfDisposedAndClosed ();
-
-                               if (value < 0 || value > 255)
-                                       throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than zero or greater than 255.");
-
-                               switch (address_family) {
-                               case AddressFamily.InterNetwork:
-                                       SetSocketOption (SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, value);
-                                       break;
-                               case AddressFamily.InterNetworkV6:
-                                       SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.HopLimit, value);
-                                       break;
-                               default:
-                                       throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
-                               }
-                       }
-               }
-
                public EndPoint RemoteEndPoint {
                        get {
                                ThrowIfDisposedAndClosed ();
@@ -701,7 +360,7 @@ namespace System.Net.Sockets
                                        return null;
 
                                int error;
-                               SocketAddress sa = RemoteEndPoint_internal (safe_handle, (int) address_family, out error);
+                               SocketAddress sa = RemoteEndPoint_internal (m_Handle, (int) addressFamily, out error);
 
                                if (error != 0)
                                        throw new SocketException (error);
@@ -822,7 +481,7 @@ namespace System.Net.Sockets
                                throw new NotSupportedException ("'mode' parameter is not valid.");
 
                        int error;
-                       bool result = Poll_internal (safe_handle, mode, microSeconds, out error);
+                       bool result = Poll_internal (m_Handle, mode, microSeconds, out error);
 
                        if (error != 0)
                                throw new SocketException (error);
@@ -861,7 +520,7 @@ namespace System.Net.Sockets
                        ThrowIfDisposedAndClosed ();
 
                        int error = 0;
-                       SafeSocketHandle safe_handle = Accept_internal (this.safe_handle, out error, is_blocking);
+                       SafeSocketHandle safe_handle = Accept_internal (this.m_Handle, out error, is_blocking);
 
                        if (error != 0) {
                                if (is_closed)
@@ -882,7 +541,7 @@ namespace System.Net.Sockets
                        ThrowIfDisposedAndClosed ();
 
                        int error = 0;
-                       SafeSocketHandle safe_handle = Accept_internal (this.safe_handle, out error, is_blocking);
+                       SafeSocketHandle safe_handle = Accept_internal (this.m_Handle, out error, is_blocking);
 
                        if (error != 0) {
                                if (is_closed)
@@ -890,10 +549,10 @@ namespace System.Net.Sockets
                                throw new SocketException (error);
                        }
 
-                       acceptSocket.address_family = this.AddressFamily;
-                       acceptSocket.socket_type = this.SocketType;
-                       acceptSocket.protocol_type = this.ProtocolType;
-                       acceptSocket.safe_handle = safe_handle;
+                       acceptSocket.addressFamily = this.AddressFamily;
+                       acceptSocket.socketType = this.SocketType;
+                       acceptSocket.protocolType = this.ProtocolType;
+                       acceptSocket.m_Handle = safe_handle;
                        acceptSocket.is_connected = true;
                        acceptSocket.seed_endpoint = this.seed_endpoint;
                        acceptSocket.Blocking = this.Blocking;
@@ -924,7 +583,7 @@ namespace System.Net.Sockets
 
                        InitSocketAsyncEventArgs (e, AcceptAsyncCallback, e, SocketOperation.Accept);
 
-                       QueueIOSelectorJob (readQ, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Read, BeginAcceptCallback, e.socket_async_result));
+                       QueueIOSelectorJob (ReadSem, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Read, BeginAcceptCallback, e.socket_async_result));
 
                        return true;
                }
@@ -957,7 +616,7 @@ namespace System.Net.Sockets
 
                        SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Accept);
 
-                       QueueIOSelectorJob (readQ, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginAcceptCallback, sockares));
+                       QueueIOSelectorJob (ReadSem, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginAcceptCallback, sockares));
 
                        return sockares;
                }
@@ -980,25 +639,6 @@ namespace System.Net.Sockets
                        sockares.Complete (acc_socket);
                });
 
-               public IAsyncResult BeginAccept (int receiveSize, AsyncCallback callback, object state)
-               {
-                       ThrowIfDisposedAndClosed ();
-
-                       if (receiveSize < 0)
-                               throw new ArgumentOutOfRangeException ("receiveSize", "receiveSize is less than zero");
-
-                       SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.AcceptReceive) {
-                               Buffer = new byte [receiveSize],
-                               Offset = 0,
-                               Size = receiveSize,
-                               SockFlags = SocketFlags.None,
-                       };
-
-                       QueueIOSelectorJob (readQ, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginAcceptReceiveCallback, sockares));
-
-                       return sockares;
-               }
-
                public IAsyncResult BeginAccept (Socket acceptSocket, int receiveSize, AsyncCallback callback, object state)
                {
                        ThrowIfDisposedAndClosed ();
@@ -1029,7 +669,7 @@ namespace System.Net.Sockets
                                AcceptSocket = acceptSocket,
                        };
 
-                       QueueIOSelectorJob (readQ, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginAcceptReceiveCallback, sockares));
+                       QueueIOSelectorJob (ReadSem, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginAcceptReceiveCallback, sockares));
 
                        return sockares;
                }
@@ -1055,7 +695,7 @@ namespace System.Net.Sockets
                        if (sockares.Size > 0) {
                                try {
                                        SocketError error;
-                                       total = acc_socket.Receive_nochecks (sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, out error);
+                                       total = acc_socket.Receive (sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, out error);
                                        if (error != 0) {
                                                sockares.Complete (new SocketException ((int) error));
                                                return;
@@ -1076,12 +716,6 @@ namespace System.Net.Sockets
                        return EndAccept (out buffer, out bytes, result);
                }
 
-               public Socket EndAccept (out byte[] buffer, IAsyncResult asyncResult)
-               {
-                       int bytes;
-                       return EndAccept (out buffer, out bytes, asyncResult);
-               }
-
                public Socket EndAccept (out byte[] buffer, out int bytesTransferred, IAsyncResult asyncResult)
                {
                        ThrowIfDisposedAndClosed ();
@@ -1120,6 +754,9 @@ namespace System.Net.Sockets
 
                public void Bind (EndPoint localEP)
                {
+#if FEATURE_NO_BSD_SOCKETS
+                       throw new PlatformNotSupportedException ("System.Net.Sockets.Socket:Bind is not supported on this platform.");
+#else
                        ThrowIfDisposedAndClosed ();
 
                        if (localEP == null)
@@ -1131,7 +768,7 @@ namespace System.Net.Sockets
                        }
                        
                        int error;
-                       Bind_internal (safe_handle, localEP.Serialize(), out error);
+                       Bind_internal (m_Handle, localEP.Serialize(), out error);
 
                        if (error != 0)
                                throw new SocketException (error);
@@ -1139,6 +776,7 @@ namespace System.Net.Sockets
                                is_bound = true;
 
                        seed_endpoint = localEP;
+#endif // FEATURE_NO_BSD_SOCKETS
                }
 
                private static void Bind_internal (SafeSocketHandle safeHandle, SocketAddress sa, out int error)
@@ -1169,7 +807,7 @@ namespace System.Net.Sockets
                                throw new SocketException ((int) SocketError.InvalidArgument);
 
                        int error;
-                       Listen_internal(safe_handle, backlog, out error);
+                       Listen_internal(m_Handle, backlog, out error);
 
                        if (error != 0)
                                throw new SocketException (error);
@@ -1224,7 +862,7 @@ namespace System.Net.Sockets
                                
                                iep = RemapIPEndPoint (iep);
 
-                               Connect_internal (safe_handle, iep.Serialize (), out error);
+                               Connect_internal (m_Handle, iep.Serialize (), out error, is_blocking);
                                if (error == 0) {
                                        is_connected = true;
                                        is_bound = true;
@@ -1260,7 +898,7 @@ namespace System.Net.Sockets
 
                        IPEndPoint ep = remoteEP as IPEndPoint;
                        /* Dgram uses Any to 'disconnect' */
-                       if (ep != null && socket_type != SocketType.Dgram) {
+                       if (ep != null && socketType != SocketType.Dgram) {
                                if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any))
                                        throw new SocketException ((int) SocketError.AddressNotAvailable);
                        }
@@ -1275,7 +913,7 @@ namespace System.Net.Sockets
                        SocketAddress serial = remoteEP.Serialize ();
 
                        int error = 0;
-                       Connect_internal (safe_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
@@ -1286,7 +924,7 @@ namespace System.Net.Sockets
                                throw new SocketException (error);
                        }
 
-                       is_connected = !(socket_type == SocketType.Dgram && ep != null && (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)));
+                       is_connected = !(socketType == SocketType.Dgram && ep != null && (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)));
                        is_bound = true;
                }
 
@@ -1361,29 +999,13 @@ namespace System.Net.Sockets
                        }
                });
 
-               public IAsyncResult BeginConnect (IPAddress address, int port, AsyncCallback callback, object state)
-               {
-                       ThrowIfDisposedAndClosed ();
-
-                       if (address == null)
-                               throw new ArgumentNullException ("address");
-                       if (address.ToString ().Length == 0)
-                               throw new ArgumentException ("The length of the IP address is zero");
-                       if (port <= 0 || port > 65535)
-                               throw new ArgumentOutOfRangeException ("port", "Must be > 0 and < 65536");
-                       if (is_listening)
-                               throw new InvalidOperationException ();
-
-                       return BeginConnect (new IPEndPoint (address, port), callback, state);
-               }
-
                public IAsyncResult BeginConnect (string host, int port, AsyncCallback callback, object state)
                {
                        ThrowIfDisposedAndClosed ();
 
                        if (host == null)
                                throw new ArgumentNullException ("host");
-                       if (address_family != AddressFamily.InterNetwork && address_family != AddressFamily.InterNetworkV6)
+                       if (addressFamily != AddressFamily.InterNetwork && addressFamily != AddressFamily.InterNetworkV6)
                                throw new NotSupportedException ("This method is valid only for sockets in the InterNetwork and InterNetworkV6 families");
                        if (port <= 0 || port > 65535)
                                throw new ArgumentOutOfRangeException ("port", "Must be > 0 and < 65536");
@@ -1399,6 +1021,8 @@ namespace System.Net.Sockets
 
                        if (end_point == null)
                                throw new ArgumentNullException ("end_point");
+                       if (is_listening)
+                               throw new InvalidOperationException ();
 
                        SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Connect) {
                                EndPoint = end_point,
@@ -1422,8 +1046,8 @@ namespace System.Net.Sockets
                                // Calling connect() again will reset the connection attempt and cause
                                // an error. Better to just close the socket and move on.
                                connect_in_progress = false;
-                               safe_handle.Dispose ();
-                               safe_handle = new SafeSocketHandle (Socket_internal (address_family, socket_type, protocol_type, out error), true);
+                               m_Handle.Dispose ();
+                               m_Handle = new SafeSocketHandle (Socket_internal (addressFamily, socketType, protocolType, out error), true);
                                if (error != 0)
                                        throw new SocketException (error);
                        }
@@ -1431,7 +1055,7 @@ namespace System.Net.Sockets
                        bool blk = is_blocking;
                        if (blk)
                                Blocking = false;
-                       Connect_internal (safe_handle, end_point.Serialize (), out error);
+                       Connect_internal (m_Handle, end_point.Serialize (), out error, false);
                        if (blk)
                                Blocking = true;
 
@@ -1581,11 +1205,11 @@ namespace System.Net.Sockets
                        sockares.CheckIfThrowDelayedException();
                }
 
-               static void Connect_internal (SafeSocketHandle safeHandle, SocketAddress sa, out int error)
+               static void Connect_internal (SafeSocketHandle safeHandle, SocketAddress sa, out int error, bool blocking)
                {
                        try {
                                safeHandle.RegisterForBlockingSyscall ();
-                               Connect_internal (safeHandle.DangerousGetHandle (), sa, out error);
+                               Connect_internal (safeHandle.DangerousGetHandle (), sa, out error, blocking);
                        } finally {
                                safeHandle.UnRegisterForBlockingSyscall ();
                        }
@@ -1593,7 +1217,7 @@ namespace System.Net.Sockets
 
                /* Connects to the remote address */
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
-               extern static void Connect_internal(IntPtr sock, SocketAddress sa, out int error);
+               extern static void Connect_internal(IntPtr sock, SocketAddress sa, out int error, bool blocking);
 
                /* Returns :
                 *  - false when it is ok to use RemoteEndPoint
@@ -1626,7 +1250,7 @@ namespace System.Net.Sockets
                        ThrowIfDisposedAndClosed ();
 
                        int error = 0;
-                       Disconnect_internal (safe_handle, reuseSocket, out error);
+                       Disconnect_internal (m_Handle, reuseSocket, out error);
 
                        if (error != 0) {
                                if (error == 50) {
@@ -1730,108 +1354,37 @@ namespace System.Net.Sockets
 
 #region Receive
 
-               public int Receive (byte [] buffer)
-               {
-                       return Receive (buffer, SocketFlags.None);
-               }
-
-               public int Receive (byte [] buffer, SocketFlags socketFlags)
+               public int Receive (byte [] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode)
                {
                        ThrowIfDisposedAndClosed ();
                        ThrowIfBufferNull (buffer);
-                       ThrowIfBufferOutOfRange (buffer, 0, buffer.Length);
+                       ThrowIfBufferOutOfRange (buffer, offset, size);
 
-                       SocketError error;
-                       int ret = Receive_nochecks (buffer, 0, buffer.Length, socketFlags, out error);
+                       int nativeError;
+                       int ret = Receive_internal (m_Handle, buffer, offset, size, socketFlags, out nativeError, is_blocking);
 
-                       if (error != SocketError.Success) {
-                               if (error == SocketError.WouldBlock && is_blocking) // This might happen when ReceiveTimeout is set
-                                       throw new SocketException ((int) error, TIMEOUT_EXCEPTION_MSG);
-                               throw new SocketException ((int) error);
+                       errorCode = (SocketError) nativeError;
+                       if (errorCode != SocketError.Success && errorCode != SocketError.WouldBlock && errorCode != SocketError.InProgress) {
+                               is_connected = false;
+                               is_bound = false;
+                       } else {
+                               is_connected = true;
                        }
 
                        return ret;
                }
 
-               public int Receive (byte [] buffer, int size, SocketFlags socketFlags)
+               [CLSCompliant (false)]
+               public int Receive (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
                {
                        ThrowIfDisposedAndClosed ();
-                       ThrowIfBufferNull (buffer);
-                       ThrowIfBufferOutOfRange (buffer, 0, size);
-
-                       SocketError error;
-                       int ret = Receive_nochecks (buffer, 0, size, socketFlags, out error);
 
-                       if (error != SocketError.Success) {
-                               if (error == SocketError.WouldBlock && is_blocking) // This might happen when ReceiveTimeout is set
-                                       throw new SocketException ((int) error, TIMEOUT_EXCEPTION_MSG);
-                               throw new SocketException ((int) error);
-                       }
+                       if (buffers == null || buffers.Count == 0)
+                               throw new ArgumentNullException ("buffers");
 
-                       return ret;
-               }
-
-               public int Receive (byte [] buffer, int offset, int size, SocketFlags socketFlags)
-               {
-                       ThrowIfDisposedAndClosed ();
-                       ThrowIfBufferNull (buffer);
-                       ThrowIfBufferOutOfRange (buffer, offset, size);
-
-                       SocketError error;
-                       int ret = Receive_nochecks (buffer, offset, size, socketFlags, out error);
-
-                       if (error != SocketError.Success) {
-                               if (error == SocketError.WouldBlock && is_blocking) // This might happen when ReceiveTimeout is set
-                                       throw new SocketException ((int) error, TIMEOUT_EXCEPTION_MSG);
-                               throw new SocketException ((int) error);
-                       }
-
-                       return ret;
-               }
-
-               public int Receive (byte [] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode)
-               {
-                       ThrowIfDisposedAndClosed ();
-                       ThrowIfBufferNull (buffer);
-                       ThrowIfBufferOutOfRange (buffer, offset, size);
-
-                       return Receive_nochecks (buffer, offset, size, socketFlags, out errorCode);
-               }
-
-               public int Receive (IList<ArraySegment<byte>> buffers)
-               {
-                       SocketError error;
-                       int ret = Receive (buffers, SocketFlags.None, out error);
-
-                       if (error != SocketError.Success)
-                               throw new SocketException ((int) error);
-
-                       return ret;
-               }
-
-               [CLSCompliant (false)]
-               public int Receive (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
-               {
-                       SocketError error;
-                       int ret = Receive (buffers, socketFlags, out error);
-
-                       if (error != SocketError.Success)
-                               throw new SocketException ((int) error);
-
-                       return(ret);
-               }
-
-               [CLSCompliant (false)]
-               public int Receive (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
-               {
-                       ThrowIfDisposedAndClosed ();
-
-                       if (buffers == null || buffers.Count == 0)
-                               throw new ArgumentNullException ("buffers");
-
-                       int numsegments = buffers.Count;
-                       int nativeError;
-                       int ret;
+                       int numsegments = buffers.Count;
+                       int nativeError;
+                       int ret;
 
                        /* Only example I can find of sending a byte array reference directly into an internal
                         * call is in System.Runtime.Remoting/System.Runtime.Remoting.Channels.Ipc.Win32/NamedPipeSocket.cs,
@@ -1851,7 +1404,7 @@ namespace System.Net.Sockets
                        }
 
                        try {
-                               ret = Receive_internal (safe_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)
@@ -1881,7 +1434,7 @@ namespace System.Net.Sockets
 
                                e.socket_async_result.Buffers = e.BufferList;
 
-                               QueueIOSelectorJob (readQ, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveGenericCallback, e.socket_async_result));
+                               QueueIOSelectorJob (ReadSem, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveGenericCallback, e.socket_async_result));
                        } else {
                                InitSocketAsyncEventArgs (e, ReceiveAsyncCallback, e, SocketOperation.Receive);
 
@@ -1889,7 +1442,7 @@ namespace System.Net.Sockets
                                e.socket_async_result.Offset = e.Offset;
                                e.socket_async_result.Size = e.Count;
 
-                               QueueIOSelectorJob (readQ, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveCallback, e.socket_async_result));
+                               QueueIOSelectorJob (ReadSem, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveCallback, e.socket_async_result));
                        }
 
                        return true;
@@ -1912,39 +1465,35 @@ namespace System.Net.Sockets
                        }
                });
 
-               public IAsyncResult BeginReceive (byte[] buffer, int offset, int size, SocketFlags socket_flags, AsyncCallback callback, object state)
+               public IAsyncResult BeginReceive (byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
                {
                        ThrowIfDisposedAndClosed ();
                        ThrowIfBufferNull (buffer);
                        ThrowIfBufferOutOfRange (buffer, offset, size);
 
+                       /* As far as I can tell from the docs and from experimentation, a pointer to the
+                        * SocketError parameter is not supposed to be saved for the async parts.  And as we don't
+                        * set any socket errors in the setup code, we just have to set it to Success. */
+                       errorCode = SocketError.Success;
+
                        SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Receive) {
                                Buffer = buffer,
                                Offset = offset,
                                Size = size,
-                               SockFlags = socket_flags,
+                               SockFlags = socketFlags,
                        };
 
-                       QueueIOSelectorJob (readQ, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveCallback, sockares));
+                       QueueIOSelectorJob (ReadSem, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveCallback, sockares));
 
                        return sockares;
                }
 
-               public IAsyncResult BeginReceive (byte[] buffer, int offset, int size, SocketFlags flags, out SocketError error, AsyncCallback callback, object state)
-               {
-                       /* As far as I can tell from the docs and from experimentation, a pointer to the
-                        * SocketError parameter is not supposed to be saved for the async parts.  And as we don't
-                        * set any socket errors in the setup code, we just have to set it to Success. */
-                       error = SocketError.Success;
-                       return BeginReceive (buffer, offset, size, flags, callback, state);
-               }
-
                static IOAsyncCallback BeginReceiveCallback = new IOAsyncCallback (ares => {
                        SocketAsyncResult sockares = (SocketAsyncResult) ares;
                        int total = 0;
 
                        try {
-                               total = Receive_internal (sockares.socket.safe_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;
@@ -1954,31 +1503,26 @@ namespace System.Net.Sockets
                });
 
                [CLSCompliant (false)]
-               public IAsyncResult BeginReceive (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, AsyncCallback callback, object state)
+               public IAsyncResult BeginReceive (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
                {
                        ThrowIfDisposedAndClosed ();
 
                        if (buffers == null)
                                throw new ArgumentNullException ("buffers");
 
+                       /* I assume the same SocketError semantics as above */
+                       errorCode = SocketError.Success;
+
                        SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.ReceiveGeneric) {
                                Buffers = buffers,
                                SockFlags = socketFlags,
                        };
 
-                       QueueIOSelectorJob (readQ, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveGenericCallback, sockares));
+                       QueueIOSelectorJob (ReadSem, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveGenericCallback, sockares));
 
                        return sockares;
                }
 
-               [CLSCompliant (false)]
-               public IAsyncResult BeginReceive (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
-               {
-                       /* I assume the same SocketError semantics as above */
-                       errorCode = SocketError.Success;
-                       return BeginReceive (buffers, socketFlags, callback, state);
-               }
-
                static IOAsyncCallback BeginReceiveGenericCallback = new IOAsyncCallback (ares => {
                        SocketAsyncResult sockares = (SocketAsyncResult) ares;
                        int total = 0;
@@ -1993,20 +1537,6 @@ namespace System.Net.Sockets
                        sockares.Complete (total);
                });
 
-               public int EndReceive (IAsyncResult result)
-               {
-                       SocketError error;
-                       int bytesReceived = EndReceive (result, out error);
-
-                       if (error != SocketError.Success) {
-                               if (error != SocketError.WouldBlock && error != SocketError.InProgress)
-                                       is_connected = false;
-                               throw new SocketException ((int)error);
-                       }
-
-                       return bytesReceived;
-               }
-
                public int EndReceive (IAsyncResult asyncResult, out SocketError errorCode)
                {
                        ThrowIfDisposedAndClosed ();
@@ -2016,96 +1546,98 @@ namespace System.Net.Sockets
                        if (!sockares.IsCompleted)
                                sockares.AsyncWaitHandle.WaitOne ();
 
+                       errorCode = sockares.ErrorCode;
+
+                       if (errorCode != SocketError.Success && errorCode != SocketError.WouldBlock && errorCode != SocketError.InProgress)
+                               is_connected = false;
+
                        // If no socket error occurred, call CheckIfThrowDelayedException in case there are other
                        // kinds of exceptions that should be thrown.
-                       if ((errorCode = sockares.ErrorCode) == SocketError.Success)
+                       if (errorCode == SocketError.Success)
                                sockares.CheckIfThrowDelayedException();
 
                        return sockares.Total;
                }
 
-               int Receive_nochecks (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
-               {
-                       int nativeError;
-                       int ret = Receive_internal (safe_handle, buf, offset, size, flags, out nativeError);
-
-                       error = (SocketError) nativeError;
-                       if (error != SocketError.Success && error != SocketError.WouldBlock && error != SocketError.InProgress) {
-                               is_connected = false;
-                               is_bound = false;
-                       } else {
-                               is_connected = true;
-                       }
-
-                       return ret;
-               }
-
-               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
 
 #region ReceiveFrom
 
-               public int ReceiveFrom (byte [] buffer, ref EndPoint remoteEP)
+               public int ReceiveFrom (byte [] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP)
                {
                        ThrowIfDisposedAndClosed ();
                        ThrowIfBufferNull (buffer);
+                       ThrowIfBufferOutOfRange (buffer, offset, size);
 
-                       return ReceiveFrom (buffer, 0, buffer.Length, SocketFlags.None, ref remoteEP);
-               }
+                       if (remoteEP == null)
+                               throw new ArgumentNullException ("remoteEP");
 
-               public int ReceiveFrom (byte [] buffer, SocketFlags socketFlags, ref EndPoint remoteEP)
-               {
-                       ThrowIfDisposedAndClosed ();
-                       ThrowIfBufferNull (buffer);
+                       SocketError errorCode;
+                       int ret = ReceiveFrom (buffer, offset, size, socketFlags, ref remoteEP, out errorCode);
+
+                       if (errorCode != SocketError.Success)
+                               throw new SocketException (errorCode);
 
-                       return ReceiveFrom (buffer, 0, buffer.Length, socketFlags, ref remoteEP);
+                       return ret;
                }
 
-               public int ReceiveFrom (byte [] buffer, int size, SocketFlags socketFlags, ref EndPoint remoteEP)
+               internal int ReceiveFrom (byte [] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, out SocketError errorCode)
                {
-                       ThrowIfDisposedAndClosed ();
-                       ThrowIfBufferNull (buffer);
-                       ThrowIfBufferOutOfRange (buffer, 0, size);
+                       SocketAddress sockaddr = remoteEP.Serialize();
 
-                       return ReceiveFrom (buffer, 0, size, socketFlags, ref remoteEP);
-               }
+                       int nativeError;
+                       int cnt = ReceiveFrom_internal (m_Handle, buffer, offset, size, socketFlags, ref sockaddr, out nativeError, is_blocking);
 
-               public int ReceiveFrom (byte [] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP)
-               {
-                       ThrowIfDisposedAndClosed ();
-                       ThrowIfBufferNull (buffer);
-                       ThrowIfBufferOutOfRange (buffer, offset, size);
+                       errorCode = (SocketError) nativeError;
+                       if (errorCode != SocketError.Success) {
+                               if (errorCode != SocketError.WouldBlock && errorCode != SocketError.InProgress) {
+                                       is_connected = false;
+                               } else if (errorCode == SocketError.WouldBlock && is_blocking) { // This might happen when ReceiveTimeout is set
+                                       errorCode = SocketError.TimedOut;
+                               }
 
-                       if (remoteEP == null)
-                               throw new ArgumentNullException ("remoteEP");
+                               return 0;
+                       }
 
-                       int error;
-                       return ReceiveFrom_nochecks_exc (buffer, offset, size, socketFlags, ref remoteEP, true, out error);
+                       is_connected = true;
+                       is_bound = true;
+
+                       /* If sockaddr is null then we're a connection oriented protocol and should ignore the
+                        * remoteEP parameter (see MSDN documentation for Socket.ReceiveFrom(...) ) */
+                       if (sockaddr != null) {
+                               /* Stupidly, EndPoint.Create() is an instance method */
+                               remoteEP = remoteEP.Create (sockaddr);
+                       }
+
+                       seed_endpoint = remoteEP;
+
+                       return cnt;
                }
 
                public bool ReceiveFromAsync (SocketAsyncEventArgs e)
@@ -2126,7 +1658,7 @@ namespace System.Net.Sockets
                        e.socket_async_result.EndPoint = e.RemoteEndPoint;
                        e.socket_async_result.SockFlags = e.SocketFlags;
 
-                       QueueIOSelectorJob (readQ, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveFromCallback, e.socket_async_result));
+                       QueueIOSelectorJob (ReadSem, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveFromCallback, e.socket_async_result));
 
                        return true;
                }
@@ -2165,7 +1697,7 @@ namespace System.Net.Sockets
                                EndPoint = remote_end,
                        };
 
-                       QueueIOSelectorJob (readQ, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveFromCallback, sockares));
+                       QueueIOSelectorJob (ReadSem, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveFromCallback, sockares));
 
                        return sockares;
                }
@@ -2175,8 +1707,13 @@ namespace System.Net.Sockets
                        int total = 0;
 
                        try {
-                               int error;
-                               total = sockares.socket.ReceiveFrom_nochecks_exc (sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, ref sockares.EndPoint, true, out error);
+                               SocketError errorCode;
+                               total = sockares.socket.ReceiveFrom (sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, ref sockares.EndPoint, out errorCode);
+
+                               if (errorCode != SocketError.Success) {
+                                       sockares.Complete (new SocketException (errorCode));
+                                       return;
+                               }
                        } catch (Exception e) {
                                sockares.Complete (e);
                                return;
@@ -2204,56 +1741,20 @@ namespace System.Net.Sockets
                        return sockares.Total;
                }
 
-               internal int ReceiveFrom_nochecks_exc (byte [] buf, int offset, int size, SocketFlags flags, ref EndPoint remote_end, bool throwOnError, out int error)
-               {
-                       SocketAddress sockaddr = remote_end.Serialize();
-
-                       int cnt = ReceiveFrom_internal (safe_handle, buf, offset, size, flags, ref sockaddr, out error);
-
-                       SocketError err = (SocketError) error;
-                       if (err != 0) {
-                               if (err != SocketError.WouldBlock && err != SocketError.InProgress) {
-                                       is_connected = false;
-                               } else if (err == SocketError.WouldBlock && is_blocking) { // This might happen when ReceiveTimeout is set
-                                       if (throwOnError)       
-                                               throw new SocketException ((int) SocketError.TimedOut, TIMEOUT_EXCEPTION_MSG);
-                                       error = (int) SocketError.TimedOut;
-                                       return 0;
-                               }
-
-                               if (throwOnError)
-                                       throw new SocketException (error);
-
-                               return 0;
-                       }
-
-                       is_connected = true;
-                       is_bound = true;
-
-                       /* If sockaddr is null then we're a connection oriented protocol and should ignore the
-                        * remote_end parameter (see MSDN documentation for Socket.ReceiveFrom(...) ) */
-                       if (sockaddr != null) {
-                               /* Stupidly, EndPoint.Create() is an instance method */
-                               remote_end = remote_end.Create (sockaddr);
-                       }
 
-                       seed_endpoint = remote_end;
 
-                       return cnt;
-               }
-
-               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
 
@@ -2313,97 +1814,33 @@ namespace System.Net.Sockets
 
 #region Send
 
-               public int Send (byte [] buffer)
-               {
-                       ThrowIfDisposedAndClosed ();
-                       ThrowIfBufferNull (buffer);
-                       ThrowIfBufferOutOfRange (buffer, 0, buffer.Length);
-
-                       SocketError error;
-                       int ret = Send_nochecks (buffer, 0, buffer.Length, SocketFlags.None, out error);
-
-                       if (error != SocketError.Success)
-                               throw new SocketException ((int) error);
-
-                       return ret;
-               }
-
-               public int Send (byte [] buffer, SocketFlags socketFlags)
-               {
-                       ThrowIfDisposedAndClosed ();
-                       ThrowIfBufferNull (buffer);
-                       ThrowIfBufferOutOfRange (buffer, 0, buffer.Length);
-
-                       SocketError error;
-                       int ret = Send_nochecks (buffer, 0, buffer.Length, socketFlags, out error);
-
-                       if (error != SocketError.Success)
-                               throw new SocketException ((int) error);
-
-                       return ret;
-               }
-
-               public int Send (byte [] buffer, int size, SocketFlags socketFlags)
-               {
-                       ThrowIfDisposedAndClosed ();
-                       ThrowIfBufferNull (buffer);
-                       ThrowIfBufferOutOfRange (buffer, 0, size);
-
-                       SocketError error;
-                       int ret = Send_nochecks (buffer, 0, size, socketFlags, out error);
-
-                       if (error != SocketError.Success)
-                               throw new SocketException ((int) error);
-
-                       return ret;
-               }
-
-               public int Send (byte [] buffer, int offset, int size, SocketFlags socketFlags)
-               {
-                       ThrowIfDisposedAndClosed ();
-                       ThrowIfBufferNull (buffer);
-                       ThrowIfBufferOutOfRange (buffer, offset, size);
-
-                       SocketError error;
-                       int ret = Send_nochecks (buffer, offset, size, socketFlags, out error);
-
-                       if (error != SocketError.Success)
-                               throw new SocketException ((int) error);
-
-                       return ret;
-               }
-
                public int Send (byte [] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode)
                {
                        ThrowIfDisposedAndClosed ();
                        ThrowIfBufferNull (buffer);
                        ThrowIfBufferOutOfRange (buffer, offset, size);
 
-                       return Send_nochecks (buffer, offset, size, socketFlags, out errorCode);
-               }
-
-               public
-               int Send (IList<ArraySegment<byte>> buffers)
-               {
-                       SocketError error;
-                       int ret = Send (buffers, SocketFlags.None, out error);
-
-                       if (error != SocketError.Success)
-                               throw new SocketException ((int) error);
-
-                       return ret;
-               }
-
-               public
-               int Send (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
-               {
-                       SocketError error;
-                       int ret = Send (buffers, socketFlags, out error);
+                       if (size == 0) {
+                               errorCode = SocketError.Success;
+                               return 0;
+                       }
 
-                       if (error != SocketError.Success)
-                               throw new SocketException ((int) error);
+                       int nativeError;
+                       int sent = 0;
+                       do {
+                               sent += Send_internal (
+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;
+                                       is_bound = false;
+                                       break;
+                               } else {
+                                       is_connected = true;
+                               }
+                       } while (sent < size);
 
-                       return ret;
+                       return sent;
                }
 
                [CLSCompliant (false)]
@@ -2435,7 +1872,7 @@ namespace System.Net.Sockets
                        }
 
                        try {
-                               ret = Send_internal (safe_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) {
@@ -2449,28 +1886,6 @@ namespace System.Net.Sockets
                        return ret;
                }
 
-               int Send_nochecks (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
-               {
-                       if (size == 0) {
-                               error = SocketError.Success;
-                               return 0;
-                       }
-
-                       int nativeError;
-                       int ret = Send_internal (safe_handle, buf, offset, size, flags, out nativeError);
-
-                       error = (SocketError)nativeError;
-
-                       if (error != SocketError.Success && error != SocketError.WouldBlock && error != SocketError.InProgress) {
-                               is_connected = false;
-                               is_bound = false;
-                       } else {
-                               is_connected = true;
-                       }
-
-                       return ret;
-               }
-
                public bool SendAsync (SocketAsyncEventArgs e)
                {
                        // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
@@ -2485,7 +1900,7 @@ namespace System.Net.Sockets
 
                                e.socket_async_result.Buffers = e.BufferList;
 
-                               QueueIOSelectorJob (writeQ, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Write, BeginSendGenericCallback, e.socket_async_result));
+                               QueueIOSelectorJob (WriteSem, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Write, BeginSendGenericCallback, e.socket_async_result));
                        } else {
                                InitSocketAsyncEventArgs (e, SendAsyncCallback, e, SocketOperation.Send);
 
@@ -2493,7 +1908,7 @@ namespace System.Net.Sockets
                                e.socket_async_result.Offset = e.Offset;
                                e.socket_async_result.Size = e.Count;
 
-                               QueueIOSelectorJob (writeQ, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendCallback ((SocketAsyncResult) s, 0), e.socket_async_result));
+                               QueueIOSelectorJob (WriteSem, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendCallback ((SocketAsyncResult) s, 0), e.socket_async_result));
                        }
 
                        return true;
@@ -2518,32 +1933,25 @@ namespace System.Net.Sockets
 
                public IAsyncResult BeginSend (byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
                {
+                       ThrowIfDisposedAndClosed ();
+                       ThrowIfBufferNull (buffer);
+                       ThrowIfBufferOutOfRange (buffer, offset, size);
+
                        if (!is_connected) {
                                errorCode = SocketError.NotConnected;
-                               throw new SocketException ((int) errorCode);
+                               return null;
                        }
 
                        errorCode = SocketError.Success;
-                       return BeginSend (buffer, offset, size, socketFlags, callback, state);
-               }
-
-               public IAsyncResult BeginSend (byte[] buffer, int offset, int size, SocketFlags socket_flags, AsyncCallback callback, object state)
-               {
-                       ThrowIfDisposedAndClosed ();
-                       ThrowIfBufferNull (buffer);
-                       ThrowIfBufferOutOfRange (buffer, offset, size);
-
-                       if (!is_connected)
-                               throw new SocketException ((int)SocketError.NotConnected);
 
                        SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Send) {
                                Buffer = buffer,
                                Offset = offset,
                                Size = size,
-                               SockFlags = socket_flags,
+                               SockFlags = socketFlags,
                        };
 
-                       QueueIOSelectorJob (writeQ, sockares.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendCallback ((SocketAsyncResult) s, 0), sockares));
+                       QueueIOSelectorJob (WriteSem, sockares.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendCallback ((SocketAsyncResult) s, 0), sockares));
 
                        return sockares;
                }
@@ -2553,7 +1961,7 @@ namespace System.Net.Sockets
                        int total = 0;
 
                        try {
-                               total = Socket.Send_internal (sockares.socket.safe_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;
@@ -2564,7 +1972,7 @@ namespace System.Net.Sockets
                                sockares.Offset += total;
                                sockares.Size -= total;
 
-                               if (sockares.socket.is_disposed) {
+                               if (sockares.socket.CleanedUp) {
                                        sockares.Complete (total);
                                        return;
                                }
@@ -2580,37 +1988,31 @@ namespace System.Net.Sockets
                        sockares.Complete (total);
                }
 
-               public IAsyncResult BeginSend (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, AsyncCallback callback, object state)
+               [CLSCompliant (false)]
+               public IAsyncResult BeginSend (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
                {
                        ThrowIfDisposedAndClosed ();
 
                        if (buffers == null)
                                throw new ArgumentNullException ("buffers");
-                       if (!is_connected)
-                               throw new SocketException ((int)SocketError.NotConnected);
+
+                       if (!is_connected) {
+                               errorCode = SocketError.NotConnected;
+                               return null;
+                       }
+
+                       errorCode = SocketError.Success;
 
                        SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.SendGeneric) {
                                Buffers = buffers,
                                SockFlags = socketFlags,
                        };
 
-                       QueueIOSelectorJob (writeQ, sockares.Handle, new IOSelectorJob (IOOperation.Write, BeginSendGenericCallback, sockares));
+                       QueueIOSelectorJob (WriteSem, sockares.Handle, new IOSelectorJob (IOOperation.Write, BeginSendGenericCallback, sockares));
 
                        return sockares;
                }
 
-               [CLSCompliant (false)]
-               public IAsyncResult BeginSend (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
-               {
-                       if (!is_connected) {
-                               errorCode = SocketError.NotConnected;
-                               throw new SocketException ((int)errorCode);
-                       }
-
-                       errorCode = SocketError.Success;
-                       return BeginSend (buffers, socketFlags, callback, state);
-               }
-
                static IOAsyncCallback BeginSendGenericCallback = new IOAsyncCallback (ares => {
                        SocketAsyncResult sockares = (SocketAsyncResult) ares;
                        int total = 0;
@@ -2625,20 +2027,6 @@ namespace System.Net.Sockets
                        sockares.Complete (total);
                });
 
-               public int EndSend (IAsyncResult result)
-               {
-                       SocketError error;
-                       int bytesSent = EndSend (result, out error);
-
-                       if (error != SocketError.Success) {
-                               if (error != SocketError.WouldBlock && error != SocketError.InProgress)
-                                       is_connected = false;
-                               throw new SocketException ((int)error);
-                       }
-
-                       return bytesSent;
-               }
-
                public int EndSend (IAsyncResult asyncResult, out SocketError errorCode)
                {
                        ThrowIfDisposedAndClosed ();
@@ -2648,67 +2036,49 @@ namespace System.Net.Sockets
                        if (!sockares.IsCompleted)
                                sockares.AsyncWaitHandle.WaitOne ();
 
+                       errorCode = sockares.ErrorCode;
+
+                       if (errorCode != SocketError.Success && errorCode != SocketError.WouldBlock && errorCode != SocketError.InProgress)
+                               is_connected = false;
+
                        /* If no socket error occurred, call CheckIfThrowDelayedException in
                         * case there are other kinds of exceptions that should be thrown.*/
-                       if ((errorCode = sockares.ErrorCode) == SocketError.Success)
+                       if (errorCode == SocketError.Success)
                                sockares.CheckIfThrowDelayedException ();
 
                        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
 
 #region SendTo
 
-               public int SendTo (byte [] buffer, EndPoint remoteEP)
-               {
-                       ThrowIfDisposedAndClosed ();
-                       ThrowIfBufferNull (buffer);
-
-                       return SendTo (buffer, 0, buffer.Length, SocketFlags.None, remoteEP);
-               }
-
-               public int SendTo (byte [] buffer, SocketFlags socketFlags, EndPoint remoteEP)
-               {
-                       ThrowIfDisposedAndClosed ();
-                       ThrowIfBufferNull (buffer);
-
-                       return SendTo (buffer, 0, buffer.Length, socketFlags, remoteEP);
-               }
-
-               public int SendTo (byte [] buffer, int size, SocketFlags socketFlags, EndPoint remoteEP)
-               {
-                       return SendTo (buffer, 0, size, socketFlags, remoteEP);
-               }
-
                public int SendTo (byte [] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP)
                {
                        ThrowIfDisposedAndClosed ();
@@ -2718,7 +2088,21 @@ namespace System.Net.Sockets
                        if (remoteEP == null)
                                throw new ArgumentNullException("remoteEP");
 
-                       return SendTo_nochecks (buffer, offset, size, socketFlags, remoteEP);
+                       int error;
+                       int ret = SendTo_internal (m_Handle, buffer, offset, size, socketFlags, remoteEP.Serialize (), out error, is_blocking);
+
+                       SocketError err = (SocketError) error;
+                       if (err != 0) {
+                               if (err != SocketError.WouldBlock && err != SocketError.InProgress)
+                                       is_connected = false;
+                               throw new SocketException (error);
+                       }
+
+                       is_connected = true;
+                       is_bound = true;
+                       seed_endpoint = remoteEP;
+
+                       return ret;
                }
 
                public bool SendToAsync (SocketAsyncEventArgs e)
@@ -2740,7 +2124,7 @@ namespace System.Net.Sockets
                        e.socket_async_result.SockFlags = e.SocketFlags;
                        e.socket_async_result.EndPoint = e.RemoteEndPoint;
 
-                       QueueIOSelectorJob (writeQ, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendToCallback ((SocketAsyncResult) s, 0), e.socket_async_result));
+                       QueueIOSelectorJob (WriteSem, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendToCallback ((SocketAsyncResult) s, 0), e.socket_async_result));
 
                        return true;
                }
@@ -2776,7 +2160,7 @@ namespace System.Net.Sockets
                                EndPoint = remote_end,
                        };
 
-                       QueueIOSelectorJob (writeQ, sockares.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendToCallback ((SocketAsyncResult) s, 0), sockares));
+                       QueueIOSelectorJob (WriteSem, sockares.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendToCallback ((SocketAsyncResult) s, 0), sockares));
 
                        return sockares;
                }
@@ -2785,7 +2169,7 @@ namespace System.Net.Sockets
                {
                        int total = 0;
                        try {
-                               total = sockares.socket.SendTo_nochecks (sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, sockares.EndPoint);
+                               total = sockares.socket.SendTo (sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, sockares.EndPoint);
 
                                if (sockares.error == 0) {
                                        sent_so_far += total;
@@ -2821,54 +2205,23 @@ namespace System.Net.Sockets
                        return sockares.Total;
                }
 
-               int SendTo_nochecks (byte [] buffer, int offset, int size, SocketFlags flags, EndPoint remote_end)
-               {
-                       int error;
-                       int ret = SendTo_internal (safe_handle, buffer, offset, size, flags, remote_end.Serialize (), out error);
-
-                       SocketError err = (SocketError) error;
-                       if (err != 0) {
-                               if (err != SocketError.WouldBlock && err != SocketError.InProgress)
-                                       is_connected = false;
-                               throw new SocketException (error);
-                       }
-
-                       is_connected = true;
-                       is_bound = true;
-                       seed_endpoint = remote_end;
-
-                       return ret;
-               }
-
-               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
 
 #region SendFile
 
-               public void SendFile (string fileName)
-               {
-                       ThrowIfDisposedAndClosed ();
-
-                       if (!is_connected)
-                               throw new NotSupportedException ();
-                       if (!is_blocking)
-                               throw new InvalidOperationException ();
-
-                       SendFile (fileName, null, null, 0);
-               }
-
                public void SendFile (string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
                {
                        ThrowIfDisposedAndClosed ();
@@ -2878,26 +2231,15 @@ namespace System.Net.Sockets
                        if (!is_blocking)
                                throw new InvalidOperationException ();
 
-                       if (!SendFile_internal (safe_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;
                        }
                }
 
-               public IAsyncResult BeginSendFile (string fileName, AsyncCallback callback, object state)
-               {
-                       ThrowIfDisposedAndClosed ();
-
-                       if (!is_connected)
-                               throw new NotSupportedException ();
-                       if (!File.Exists (fileName))
-                               throw new FileNotFoundException ();
-
-                       return BeginSendFile (fileName, null, null, 0, callback, state);
-               }
-
                public IAsyncResult BeginSendFile (string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, AsyncCallback callback, object state)
                {
                        ThrowIfDisposedAndClosed ();
@@ -2926,18 +2268,18 @@ namespace System.Net.Sockets
                        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);
 
@@ -2994,7 +2336,6 @@ namespace System.Net.Sockets
 
 #region DuplicateAndClose
 
-#if !MOBILE
                [MonoLimitation ("We do not support passing sockets across processes, we merely allow this API to pass the socket across AppDomains")]
                public SocketInformation DuplicateAndClose (int targetProcessId)
                {
@@ -3003,14 +2344,13 @@ namespace System.Net.Sockets
                                (is_listening      ? SocketInformationOptions.Listening : 0) |
                                (is_connected      ? SocketInformationOptions.Connected : 0) |
                                (is_blocking       ? 0 : SocketInformationOptions.NonBlocking) |
-                               (use_overlapped_io ? SocketInformationOptions.UseOnlyOverlappedIO : 0);
+                               (useOverlappedIO ? SocketInformationOptions.UseOnlyOverlappedIO : 0);
 
-                       si.ProtocolInformation = Mono.DataConverter.Pack ("iiiil", (int)address_family, (int)socket_type, (int)protocol_type, is_bound ? 1 : 0, (long)Handle);
-                       safe_handle = null;
+                       si.ProtocolInformation = Mono.DataConverter.Pack ("iiiil", (int)addressFamily, (int)socketType, (int)protocolType, is_bound ? 1 : 0, (long)Handle);
+                       m_Handle = null;
 
                        return si;
                }
-#endif
 
 #endregion
 
@@ -3024,7 +2364,7 @@ namespace System.Net.Sockets
                                throw new SocketException ((int) SocketError.Fault, "Error trying to dereference an invalid pointer");
 
                        int error;
-                       GetSocketOption_arr_internal (safe_handle, optionLevel, optionName, ref optionValue, out error);
+                       GetSocketOption_arr_internal (m_Handle, optionLevel, optionName, ref optionValue, out error);
 
                        if (error != 0)
                                throw new SocketException (error);
@@ -3036,7 +2376,7 @@ namespace System.Net.Sockets
 
                        int error;
                        byte[] byte_val = new byte [optionLength];
-                       GetSocketOption_arr_internal (safe_handle, optionLevel, optionName, ref byte_val, out error);
+                       GetSocketOption_arr_internal (m_Handle, optionLevel, optionName, ref byte_val, out error);
 
                        if (error != 0)
                                throw new SocketException (error);
@@ -3050,7 +2390,7 @@ namespace System.Net.Sockets
 
                        int error;
                        object obj_val;
-                       GetSocketOption_obj_internal (safe_handle, optionLevel, optionName, out obj_val, out error);
+                       GetSocketOption_obj_internal (m_Handle, optionLevel, optionName, out obj_val, out error);
 
                        if (error != 0)
                                throw new SocketException (error);
@@ -3108,7 +2448,7 @@ namespace System.Net.Sockets
                                throw new SocketException ((int) SocketError.Fault, "Error trying to dereference an invalid pointer");
 
                        int error;
-                       SetSocketOption_internal (safe_handle, optionLevel, optionName, null, optionValue, 0, out error);
+                       SetSocketOption_internal (m_Handle, optionLevel, optionName, null, optionValue, 0, out error);
 
                        if (error != 0) {
                                if (error == (int) SocketError.InvalidArgument)
@@ -3131,17 +2471,17 @@ namespace System.Net.Sockets
                                LingerOption linger = optionValue as LingerOption;
                                if (linger == null)
                                        throw new ArgumentException ("A 'LingerOption' value must be specified.", "optionValue");
-                               SetSocketOption_internal (safe_handle, optionLevel, optionName, linger, null, 0, out error);
+                               SetSocketOption_internal (m_Handle, optionLevel, optionName, linger, null, 0, out error);
                        } else if (optionLevel == SocketOptionLevel.IP && (optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership)) {
                                MulticastOption multicast = optionValue as MulticastOption;
                                if (multicast == null)
                                        throw new ArgumentException ("A 'MulticastOption' value must be specified.", "optionValue");
-                               SetSocketOption_internal (safe_handle, optionLevel, optionName, multicast, null, 0, out error);
+                               SetSocketOption_internal (m_Handle, optionLevel, optionName, multicast, null, 0, out error);
                        } else if (optionLevel == SocketOptionLevel.IPv6 && (optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership)) {
                                IPv6MulticastOption multicast = optionValue as IPv6MulticastOption;
                                if (multicast == null)
                                        throw new ArgumentException ("A 'IPv6MulticastOption' value must be specified.", "optionValue");
-                               SetSocketOption_internal (safe_handle, optionLevel, optionName, multicast, null, 0, out error);
+                               SetSocketOption_internal (m_Handle, optionLevel, optionName, multicast, null, 0, out error);
                        } else {
                                throw new ArgumentException ("Invalid value specified.", "optionValue");
                        }
@@ -3164,11 +2504,11 @@ namespace System.Net.Sockets
                {
                        ThrowIfDisposedAndClosed ();
 
-                       if (optionLevel == SocketOptionLevel.Socket && optionName == SocketOptionName.ReuseAddress && optionValue != 0 && !SupportsPortReuse (protocol_type))
+                       if (optionLevel == SocketOptionLevel.Socket && optionName == SocketOptionName.ReuseAddress && optionValue != 0 && !SupportsPortReuse (protocolType))
                                throw new SocketException ((int) SocketError.OperationNotSupported, "Operating system sockets do not support ReuseAddress.\nIf your socket is not intended to bind to the same address and port multiple times remove this option, otherwise you should ignore this exception inside a try catch and check that ReuseAddress is true before binding to the same address and port multiple times.");
 
                        int error;
-                       SetSocketOption_internal (safe_handle, optionLevel, optionName, null, null, optionValue, out error);
+                       SetSocketOption_internal (m_Handle, optionLevel, optionName, null, null, optionValue, out error);
 
                        if (error != 0) {
                                if (error == (int) SocketError.InvalidArgument)
@@ -3198,11 +2538,11 @@ namespace System.Net.Sockets
 
                public int IOControl (int ioControlCode, byte [] optionInValue, byte [] optionOutValue)
                {
-                       if (is_disposed)
+                       if (CleanedUp)
                                throw new ObjectDisposedException (GetType ().ToString ());
 
                        int error;
-                       int result = IOControl_internal (safe_handle, ioControlCode, optionInValue, optionOutValue, out error);
+                       int result = IOControl_internal (m_Handle, ioControlCode, optionInValue, optionOutValue, out error);
 
                        if (error != 0)
                                throw new SocketException (error);
@@ -3212,11 +2552,6 @@ namespace System.Net.Sockets
                        return result;
                }
 
-               public int IOControl (IOControlCode ioControlCode, byte[] optionInValue, byte[] optionOutValue)
-               {
-                       return IOControl ((int) ioControlCode, optionInValue, optionOutValue);
-               }
-
                static int IOControl_internal (SafeSocketHandle safeHandle, int ioctl_code, byte [] input, byte [] output, out int error)
                {
                        bool release = false;
@@ -3266,7 +2601,7 @@ namespace System.Net.Sockets
                                throw new SocketException (10057); // Not connected
 
                        int error;
-                       Shutdown_internal (safe_handle, how, out error);
+                       Shutdown_internal (m_Handle, how, out error);
 
                        if (error != 0)
                                throw new SocketException (error);
@@ -3293,30 +2628,24 @@ namespace System.Net.Sockets
 
                protected virtual void Dispose (bool disposing)
                {
-                       if (is_disposed)
+                       if (CleanedUp)
                                return;
 
-                       is_disposed = true;
+                       m_IntCleanedUp = 1;
                        bool was_connected = is_connected;
                        is_connected = false;
 
-                       if (safe_handle != null) {
+                       if (m_Handle != null) {
                                is_closed = true;
                                IntPtr x = Handle;
 
                                if (was_connected)
                                        Linger (x);
 
-                               safe_handle.Dispose ();
+                               m_Handle.Dispose ();
                        }
                }
 
-               public void Dispose ()
-               {
-                       Dispose (true);
-                       GC.SuppressFinalize (this);
-               }
-
                void Linger (IntPtr handle)
                {
                        if (!is_connected || linger_timeout <= 0)
@@ -3351,13 +2680,13 @@ namespace System.Net.Sockets
 
                void ThrowIfDisposedAndClosed (Socket socket)
                {
-                       if (socket.is_disposed && socket.is_closed)
+                       if (socket.CleanedUp && socket.is_closed)
                                throw new ObjectDisposedException (socket.GetType ().ToString ());
                }
 
                void ThrowIfDisposedAndClosed ()
                {
-                       if (is_disposed && is_closed)
+                       if (CleanedUp && is_closed)
                                throw new ObjectDisposedException (GetType ().ToString ());
                }
 
@@ -3381,7 +2710,7 @@ namespace System.Net.Sockets
 
                void ThrowIfUdp ()
                {
-                       if (protocol_type == ProtocolType.Udp)
+                       if (protocolType == ProtocolType.Udp)
                                throw new SocketException ((int)SocketError.ProtocolOption);
                }
 
@@ -3399,16 +2728,16 @@ namespace System.Net.Sockets
                        return sockares;
                }
 
-               void QueueIOSelectorJob (Queue<KeyValuePair<IntPtr, IOSelectorJob>> queue, IntPtr handle, IOSelectorJob job)
+               void QueueIOSelectorJob (SemaphoreSlim sem, IntPtr handle, IOSelectorJob job)
                {
-                       int count;
-                       lock (queue) {
-                               queue.Enqueue (new KeyValuePair<IntPtr, IOSelectorJob> (handle, job));
-                               count = queue.Count;
-                       }
+                       sem.WaitAsync ().ContinueWith (t => {
+                               if (CleanedUp) {
+                                       job.MarkDisposed ();
+                                       return;
+                               }
 
-                       if (count == 1)
                                IOSelector.Add (handle, job);
+                       });
                }
 
                void InitSocketAsyncEventArgs (SocketAsyncEventArgs e, AsyncCallback callback, object state, SocketOperation operation)
@@ -3466,6 +2795,41 @@ namespace System.Net.Sockets
 
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
                internal static extern bool SupportsPortReuse (ProtocolType proto);
+
+               internal static int FamilyHint {
+                       get {
+                               // Returns one of
+                               //      MONO_HINT_UNSPECIFIED           = 0,
+                               //      MONO_HINT_IPV4                          = 1,
+                               //      MONO_HINT_IPV6                          = 2,
+
+                               int hint = 0;
+                               if (OSSupportsIPv4) {
+                                       hint = 1;
+                               }
+
+                               if (OSSupportsIPv6) {
+                                       hint = hint == 0 ? 2 : 0;
+                               }
+
+                               return hint;
+                       }
+               }
+
+               static bool IsProtocolSupported (NetworkInterfaceComponent networkInterface)
+               {
+#if MOBILE
+                       return true;
+#else
+                       var nics = NetworkInterface.GetAllNetworkInterfaces ();
+                       foreach (var adapter in nics) {
+                               if (adapter.Supports (networkInterface))
+                                       return true;
+                       }
+
+                       return false;
+#endif
+               }
        }
 }
 
index 361f55ec929b450e147b04dbfb7a07794b36f485..438d4bc31e9a3dcf97f763d3ba444272030d218d 100644 (file)
@@ -111,12 +111,10 @@ namespace System.Net.Sockets
                        set;
                }
 
-#if !MOBILE
                public TransmitFileOptions SendPacketsFlags {
                        get;
                        set;
                }
-#endif
 
                [MonoTODO ("unused property")]
                public int SendPacketsSendSize {
diff --git a/mcs/class/System/System.Net.Sockets/SocketAsyncOperation.cs b/mcs/class/System/System.Net.Sockets/SocketAsyncOperation.cs
deleted file mode 100644 (file)
index 87d6de5..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-// System.Net.Sockets.SocketAsyncOperation.cs
-//
-// Authors:
-//     Marek Habersack (mhabersack@novell.com)
-//
-// Copyright (c) 2008 Novell, Inc. (http://www.novell.com)
-//
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-namespace System.Net.Sockets
-{
-       public enum SocketAsyncOperation
-       {
-               None,
-               Accept,
-               Connect,
-               Disconnect,
-               Receive,
-               ReceiveFrom,
-               ReceiveMessageFrom,
-               Send,
-               SendPackets,
-               SendTo
-       }
-}
index 980ad06e5b2f909333222afba5fea6ea9da6ead2..c63b1781660d77a48c9dd8b8f77dc1aae07f7a8a 100644 (file)
@@ -140,7 +140,7 @@ namespace System.Net.Sockets
 
                public void Complete ()
                {
-                       if (operation != SocketOperation.Receive && socket.is_disposed)
+                       if (operation != SocketOperation.Receive && socket.CleanedUp)
                                DelayedException = new ObjectDisposedException (socket.GetType ().ToString ());
 
                        IsCompleted = true;
@@ -150,42 +150,20 @@ namespace System.Net.Sockets
                                ThreadPool.UnsafeQueueUserWorkItem (_ => callback (this), null);
                        }
 
-                       Queue<KeyValuePair<IntPtr, IOSelectorJob>> queue = null;
                        switch (operation) {
                        case SocketOperation.Receive:
                        case SocketOperation.ReceiveFrom:
                        case SocketOperation.ReceiveGeneric:
                        case SocketOperation.Accept:
-                               queue = socket.readQ;
+                               socket.ReadSem.Release ();
                                break;
                        case SocketOperation.Send:
                        case SocketOperation.SendTo:
                        case SocketOperation.SendGeneric:
-                               queue = socket.writeQ;
+                               socket.WriteSem.Release ();
                                break;
                        }
 
-                       if (queue != null) {
-                               lock (queue) {
-                                       /* queue.Count will only be 0 if the socket is closed while receive/send/accept
-                                        * operation(s) are pending and at least one call to this method is waiting
-                                        * on the lock while another one calls CompleteAllOnDispose() */
-                                       if (queue.Count > 0)
-                                               queue.Dequeue (); /* remove ourselves */
-                                       if (queue.Count > 0) {
-                                               if (!socket.is_disposed) {
-                                                       IOSelector.Add (queue.Peek ().Key, queue.Peek ().Value);
-                                               } else {
-                                                       /* CompleteAllOnDispose */
-                                                       KeyValuePair<IntPtr, IOSelectorJob> [] jobs = queue.ToArray ();
-                                                       for (int i = 0; i < jobs.Length; i++)
-                                                               ThreadPool.QueueUserWorkItem (j => ((IOSelectorJob) j).MarkDisposed (), jobs [i].Value);
-                                                       queue.Clear ();
-                                               }
-                                       }
-                               }
-                       }
-
                        // IMPORTANT: 'callback', if any is scheduled from unmanaged code
                }
 
diff --git a/mcs/class/System/System.Net.Sockets/TcpClient.cs b/mcs/class/System/System.Net.Sockets/TcpClient.cs
deleted file mode 100644 (file)
index bbdb034..0000000
+++ /dev/null
@@ -1,450 +0,0 @@
-// TcpClient.cs
-//
-// Author:
-//     Phillip Pearson (pp@myelin.co.nz)
-//     Gonzalo Paniagua Javier (gonzalo@novell.com)
-//     Sridhar Kulkarni (sridharkulkarni@gmail.com)
-//     Marek Safar (marek.safar@gmail.com)
-//
-// Copyright (C) 2001, Phillip Pearson http://www.myelin.co.nz
-// Copyright (c) 2006 Novell, Inc. (http://www.novell.com)
-// Copyright 2011 Xamarin Inc.
-//
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Net;
-using System.Threading.Tasks;
-
-namespace System.Net.Sockets
-{
-       public class TcpClient : IDisposable {
-               enum Properties : uint {
-                       LingerState = 1,
-                       NoDelay = 2,
-                       ReceiveBufferSize = 4,
-                       ReceiveTimeout = 8,
-                       SendBufferSize = 16,
-                       SendTimeout = 32
-               }
-
-               // private data
-               NetworkStream stream;
-               bool active;
-               Socket client;
-               bool disposed;
-               Properties values;
-               int recv_timeout, send_timeout;
-               int recv_buffer_size, send_buffer_size;
-               LingerOption linger_state;
-               bool no_delay;
-               
-               private void Init (AddressFamily family)
-               {
-                       active = false;
-
-                       if(client != null) {
-                               client.Close();
-                               client = null;
-                       }
-
-                       client = new Socket(family, SocketType.Stream, ProtocolType.Tcp);
-               }
-
-               public TcpClient ()
-               {
-                       Init(AddressFamily.InterNetwork);
-                       client.Bind(new IPEndPoint(IPAddress.Any, 0));
-               }
-
-               internal TcpClient (Socket s)
-               {
-                       client = s;
-               }
-       
-               public TcpClient (AddressFamily family)
-               {
-                       if (family != AddressFamily.InterNetwork &&
-                           family != AddressFamily.InterNetworkV6) {
-                               throw new ArgumentException ("Family must be InterNetwork or InterNetworkV6", "family");
-                       }
-                       
-                       Init (family);
-                       IPAddress any = IPAddress.Any;
-                       if (family == AddressFamily.InterNetworkV6)
-                               any = IPAddress.IPv6Any;
-                       client.Bind (new IPEndPoint (any, 0));
-               }
-
-               public TcpClient (IPEndPoint localEP)
-               {
-                       Init (localEP.AddressFamily);
-                       client.Bind (localEP);
-               }
-               
-               public TcpClient (string hostname, int port)
-               {
-                       Connect(hostname, port);
-               }
-                               
-               protected bool Active {
-                       get { return active; }
-                       set { active = value; }
-               }
-               
-               public Socket Client {
-                       get { return client; }
-                       set {
-                               client = value;
-                               stream = null;
-                       }
-               }
-
-               public int Available {
-                       get { return client.Available; }
-               }
-
-               public bool Connected {
-                       get { return client.Connected; }
-               }
-
-               public bool ExclusiveAddressUse {
-                       get {
-                               return(client.ExclusiveAddressUse);
-                       }
-                       set {
-                               client.ExclusiveAddressUse = value;
-                       }
-               }
-
-               public LingerOption LingerState {
-                       get {
-                               if ((values & Properties.LingerState) != 0)
-                                       return linger_state;
-
-                               return (LingerOption) client.GetSocketOption (SocketOptionLevel.Socket,
-                                                                       SocketOptionName.Linger);
-                       }
-                       set {
-                               if (!client.Connected) {
-                                       linger_state = value;
-                                       values |= Properties.LingerState;
-                                       return;
-                               }
-                               client.SetSocketOption(
-                                       SocketOptionLevel.Socket,
-                                       SocketOptionName.Linger, value);
-                       }
-               }
-                               
-               public bool NoDelay {
-                       get {
-                               if ((values & Properties.NoDelay) != 0)
-                                       return no_delay;
-
-                               return (bool)client.GetSocketOption(
-                                       SocketOptionLevel.Tcp,
-                                       SocketOptionName.NoDelay);
-                       }
-                       set {
-                               if (!client.Connected) {
-                                       no_delay = value;
-                                       values |= Properties.NoDelay;
-                                       return;
-                               }
-                               client.SetSocketOption(
-                                       SocketOptionLevel.Tcp,
-                                       SocketOptionName.NoDelay, value ? 1 : 0);
-                       }
-               }
-                               
-               public int ReceiveBufferSize {
-                       get {
-                               if ((values & Properties.ReceiveBufferSize) != 0)
-                                       return recv_buffer_size;
-
-                               return (int)client.GetSocketOption(
-                                       SocketOptionLevel.Socket,
-                                       SocketOptionName.ReceiveBuffer);
-                       }
-                       set {
-                               if (!client.Connected) {
-                                       recv_buffer_size = value;
-                                       values |= Properties.ReceiveBufferSize;
-                                       return;
-                               }
-                               client.SetSocketOption(
-                                       SocketOptionLevel.Socket,
-                                       SocketOptionName.ReceiveBuffer, value);
-                       }
-               }
-                       
-               public int ReceiveTimeout {
-                       get {
-                               if ((values & Properties.ReceiveTimeout) != 0)
-                                       return recv_timeout;
-
-                               return (int)client.GetSocketOption(
-                                       SocketOptionLevel.Socket,
-                                       SocketOptionName.ReceiveTimeout);
-                       }
-                       set {
-                               if (!client.Connected) {
-                                       recv_timeout = value;
-                                       values |= Properties.ReceiveTimeout;
-                                       return;
-                               }
-                               client.SetSocketOption(
-                                       SocketOptionLevel.Socket,
-                                       SocketOptionName.ReceiveTimeout, value);
-                       }
-               }
-               
-               public int SendBufferSize {
-                       get {
-                               if ((values & Properties.SendBufferSize) != 0)
-                                       return send_buffer_size;
-
-                               return (int)client.GetSocketOption(
-                                       SocketOptionLevel.Socket,
-                                       SocketOptionName.SendBuffer);
-                       }
-                       set {
-                               if (!client.Connected) {
-                                       send_buffer_size = value;
-                                       values |= Properties.SendBufferSize;
-                                       return;
-                               }
-                               client.SetSocketOption(
-                                       SocketOptionLevel.Socket,
-                                       SocketOptionName.SendBuffer, value);
-                       }
-               }
-               
-               public int SendTimeout {
-                       get {
-                               if ((values & Properties.SendTimeout) != 0)
-                                       return send_timeout;
-
-                               return (int)client.GetSocketOption(
-                                       SocketOptionLevel.Socket,
-                                       SocketOptionName.SendTimeout);
-                       }
-                       set {
-                               if (!client.Connected) {
-                                       send_timeout = value;
-                                       values |= Properties.SendTimeout;
-                                       return;
-                               }
-                               client.SetSocketOption(
-                                       SocketOptionLevel.Socket,
-                                       SocketOptionName.SendTimeout, value);
-                       }
-               }
-               
-               
-               // methods
-               
-               public void Close ()
-               {
-                       Dispose ();
-               }
-
-               public void Connect (IPEndPoint remoteEP)
-               {
-                       try {
-                               client.Connect (remoteEP);
-                               active = true;
-                       } finally {
-                               CheckDisposed ();
-                       }
-               }
-               
-               public void Connect (IPAddress address, int port)
-               {
-                       Connect(new IPEndPoint(address, port));
-               }
-
-               void SetOptions ()
-               {
-                       Properties props = values;
-                       values = 0;
-
-                       if ((props & Properties.LingerState) != 0)
-                               LingerState = linger_state;
-                       if ((props & Properties.NoDelay) != 0)
-                               NoDelay = no_delay;
-                       if ((props & Properties.ReceiveBufferSize) != 0)
-                               ReceiveBufferSize = recv_buffer_size;
-                       if ((props & Properties.ReceiveTimeout) != 0)
-                               ReceiveTimeout = recv_timeout;
-                       if ((props & Properties.SendBufferSize) != 0)
-                               SendBufferSize = send_buffer_size;
-                       if ((props & Properties.SendTimeout) != 0)
-                               SendTimeout = send_timeout;
-               }
-
-               public void Connect (string hostname, int port)
-               {
-                       IPAddress [] addresses = Dns.GetHostAddresses (hostname);
-                       Connect (addresses, port);
-               }
-
-               public void Connect (IPAddress[] ipAddresses, int port)
-               {
-                       CheckDisposed ();
-                       
-                       if (ipAddresses == null) {
-                               throw new ArgumentNullException ("ipAddresses");
-                       }
-                       
-                       for(int i = 0; i < ipAddresses.Length; i++) {
-                               try {
-                                       IPAddress address = ipAddresses[i];
-
-                                       if (address.Equals (IPAddress.Any) ||
-                                           address.Equals (IPAddress.IPv6Any)) {
-                                               throw new SocketException ((int)SocketError.AddressNotAvailable);
-                                       }
-
-                                       Init (address.AddressFamily);
-                                       
-                                       if (address.AddressFamily == AddressFamily.InterNetwork) {
-                                               client.Bind (new IPEndPoint (IPAddress.Any, 0));
-                                       } else if (address.AddressFamily == AddressFamily.InterNetworkV6) {
-                                               client.Bind (new IPEndPoint (IPAddress.IPv6Any, 0));
-                                       } else {
-                                               throw new NotSupportedException ("This method is only valid for sockets in the InterNetwork and InterNetworkV6 families");
-                                       }
-
-                                       Connect (new IPEndPoint (address, port));
-                                       
-                                       if (values != 0) {
-                                               SetOptions ();
-                                       }
-                                       
-                                       break;
-                               } catch (Exception e) {
-                                       /* Reinitialise the socket so
-                                        * other properties still work
-                                        * (see no-arg constructor)
-                                        */
-                                       Init (AddressFamily.InterNetwork);
-
-                                       /* This is the last known
-                                        * address, so re-throw the
-                                        * exception
-                                        */
-                                       if (i == ipAddresses.Length - 1) {
-                                               throw e;
-                                       }
-                               }
-                       }
-               }
-               
-               public void EndConnect (IAsyncResult asyncResult)
-               {
-                       client.EndConnect (asyncResult);
-               }
-               
-               public IAsyncResult BeginConnect (IPAddress address, int port, AsyncCallback requestCallback, object state)
-               {
-                       return client.BeginConnect (address, port, requestCallback, state);
-               }
-               
-               public IAsyncResult BeginConnect (IPAddress[] addresses, int port, AsyncCallback requestCallback, object state)
-               {
-                       return client.BeginConnect (addresses, port, requestCallback, state);
-               }
-               
-               public IAsyncResult BeginConnect (string host, int port, AsyncCallback requestCallback, object state)
-               {
-                       return client.BeginConnect (host, port, requestCallback, state);
-               }
-               
-               public void Dispose ()
-               {
-                       Dispose (true);
-                       GC.SuppressFinalize (this);
-               }
-
-               protected virtual void Dispose (bool disposing)
-               {
-                       if (disposed)
-                               return;
-                       disposed = true;
-
-                       if (disposing) {
-                               // release managed resources
-                               NetworkStream s = stream;
-                               stream = null;
-                               if (s != null) {
-                                       // This closes the socket as well, as the NetworkStream
-                                       // owns the socket.
-                                       s.Close();
-                                       active = false;
-                                       s = null;
-                               } else if (client != null){
-                                       client.Close ();
-                                       client = null;
-                               }
-                       }
-               }
-               
-               ~TcpClient ()
-               {
-                       Dispose (false);
-               }
-               
-               public NetworkStream GetStream()
-               {
-                       try {
-                               if (stream == null)
-                                       stream = new NetworkStream (client, true);
-                               return stream;
-                       }
-                       finally { CheckDisposed (); }
-               }
-
-               public Task ConnectAsync (IPAddress address, int port)
-               {
-                       return Task.Factory.FromAsync (BeginConnect, EndConnect, address, port, null);
-               }
-
-               public Task ConnectAsync (IPAddress[] addresses, int port)
-               {
-                       return Task.Factory.FromAsync (BeginConnect, EndConnect, addresses, port, null);
-               }
-
-               public Task ConnectAsync (string host, int port)
-               {
-                       return Task.Factory.FromAsync (BeginConnect, EndConnect, host, port, null);
-               }
-               private void CheckDisposed ()
-               {
-                       if (disposed)
-                               throw new ObjectDisposedException (GetType().FullName);
-               }
-       }
-}
-
diff --git a/mcs/class/System/System.Net.Sockets/TcpClient.platformnotsupported.cs b/mcs/class/System/System.Net.Sockets/TcpClient.platformnotsupported.cs
new file mode 100644 (file)
index 0000000..dd69a39
--- /dev/null
@@ -0,0 +1,191 @@
+//
+// System.Net.Sockets.TcpClient.cs
+//
+// Author:
+//     Rolf Bjarne Kvinge <rolf@xamarin.com>
+//
+// Copyright (C) 2016 Xamarin Inc (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Net;
+using System.Threading.Tasks;
+
+namespace System.Net.Sockets
+{
+       public class TcpClient : IDisposable
+       {
+               const string EXCEPTION_MESSAGE = "System.Net.Sockets.TcpClient is not supported on the current platform.";
+
+               public TcpClient ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public TcpClient (AddressFamily family)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public TcpClient (IPEndPoint localEP)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public TcpClient (string hostname, int port)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected bool Active {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public Socket Client {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public int Available {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool Connected {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool ExclusiveAddressUse {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public LingerOption LingerState {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool NoDelay {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public int ReceiveBufferSize {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public int ReceiveTimeout {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public int SendBufferSize {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public int SendTimeout {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public void Close ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void Connect (IPEndPoint remoteEP)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void Connect (IPAddress address, int port)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void Connect (string hostname, int port)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void Connect (IPAddress[] ipAddresses, int port)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void EndConnect (IAsyncResult asyncResult)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public IAsyncResult BeginConnect (IPAddress address, int port, AsyncCallback requestCallback, object state)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public IAsyncResult BeginConnect (IPAddress[] addresses, int port, AsyncCallback requestCallback, object state)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public IAsyncResult BeginConnect (string host, int port, AsyncCallback requestCallback, object state)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void Dispose ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected virtual void Dispose (bool disposing)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               ~TcpClient ()
+               {
+               }
+
+               public NetworkStream GetStream()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public Task ConnectAsync (IPAddress address, int port)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public Task ConnectAsync (IPAddress[] addresses, int port)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public Task ConnectAsync (string host, int port)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+       }
+}
diff --git a/mcs/class/System/System.Net.Sockets/TcpListener.cs b/mcs/class/System/System.Net.Sockets/TcpListener.cs
deleted file mode 100644 (file)
index 8ab582e..0000000
+++ /dev/null
@@ -1,313 +0,0 @@
-// TcpListener.cs
-//
-// Authors:
-//    Phillip Pearson (pp@myelin.co.nz)
-//    Gonzalo Paniagua Javier (gonzalo@ximian.com)
-//       Patrik Torstensson
-//    Sridhar Kulkarni (sridharkulkarni@gmail.com)
-//    Marek Safar (marek.safar@gmail.com)
-
-//
-// Copyright (C) 2001, Phillip Pearson http://www.myelin.co.nz
-//
-// (c) 2003 Ximian, Inc. (http://www.ximian.com)
-// (c) 2004-2006 Novell, Inc.
-// Copyright 2011 Xamarin Inc.
-//
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Net;
-using System.Threading.Tasks;
-
-namespace System.Net.Sockets
-{
-       /// <remarks>
-       /// A slightly more abstracted way to listen for incoming
-       /// network connections than a Socket.
-       /// </remarks>
-       public class TcpListener
-       {
-               // private data
-               
-               bool active;
-               Socket server;
-               EndPoint savedEP;
-               
-               // constructor
-
-               /// <summary>
-               /// Some code that is shared between the constructors.
-               /// </summary>
-               private void Init (AddressFamily family, EndPoint ep)
-               {
-                       active = false;
-                       server = new Socket(family, SocketType.Stream, ProtocolType.Tcp);
-                       savedEP = ep;
-               }
-               
-               /// <summary>
-               /// Constructs a new TcpListener to listen on a specified port
-               /// </summary>
-               /// <param name="port">The port to listen on, e.g. 80 if you 
-               /// are a web server</param>
-               [Obsolete ("Use TcpListener (IPAddress address, int port) instead")]
-               public TcpListener (int port)
-               {
-                       if (port < 0 || port > 65535)
-                               throw new ArgumentOutOfRangeException ("port");
-
-                       Init (AddressFamily.InterNetwork, new IPEndPoint (IPAddress.Any, port));
-               }
-
-               /// <summary>
-               /// Constructs a new TcpListener with a specified local endpoint
-               /// </summary>
-               /// <param name="local_end_point">The endpoint</param>
-               public TcpListener (IPEndPoint localEP)
-               {
-                       if (localEP == null)
-                               throw new ArgumentNullException ("localEP");
-
-                       Init (localEP.AddressFamily, localEP);
-               }
-               
-               /// <summary>
-               /// Constructs a new TcpListener, listening on a specified port
-               /// and IP (for use on a multi-homed machine)
-               /// </summary>
-               /// <param name="listen_ip">The IP to listen on</param>
-               /// <param name="port">The port to listen on</param>
-               public TcpListener (IPAddress localaddr, int port)
-               {
-                       if (localaddr == null)
-                               throw new ArgumentNullException ("localaddr");
-
-                       if (port < 0 || port > 65535)
-                               throw new ArgumentOutOfRangeException ("port");
-
-                       Init (localaddr.AddressFamily, new IPEndPoint (localaddr, port));
-               }
-
-
-               // properties
-
-               /// <summary>
-               /// A flag that is 'true' if the TcpListener is listening,
-               /// or 'false' if it is not listening
-               /// </summary>
-               protected bool Active
-               {
-                       get { return active; }
-               }
-
-               /// <summary>
-               /// The local end point
-               /// </summary>
-               public EndPoint LocalEndpoint
-               {
-                       get { 
-                               if (active)
-                                       return server.LocalEndPoint;
-
-                               return savedEP; 
-                       }
-               }
-               
-               /// <summary>
-               /// The listening socket
-               /// </summary>
-               public Socket Server
-               {
-                       get { return server; }
-               }
-
-               /// <summary>
-               /// Specifies whether the TcpListener allows only one
-               /// underlying socket to listen to a specific port
-               /// </summary>
-               public bool ExclusiveAddressUse
-               {
-                       get {
-                               if (server == null) {
-                                       throw new ObjectDisposedException (GetType ().ToString ());
-                               }
-                               if (active) {
-                                       throw new InvalidOperationException ("The TcpListener has been started");
-                               }
-
-                               return(server.ExclusiveAddressUse);
-                       }
-                       set {
-                               if (server == null) {
-                                       throw new ObjectDisposedException (GetType ().ToString ());
-                               }
-                               if (active) {
-                                       throw new InvalidOperationException ("The TcpListener has been started");
-                               }
-
-                               server.ExclusiveAddressUse = value;
-                       }
-               }
-               
-               // methods
-
-               /// <summary>
-               /// Accepts a pending connection
-               /// </summary>
-               /// <returns>A Socket object for the new connection</returns>
-               public Socket AcceptSocket ()
-               {
-                       if (!active)
-                               throw new InvalidOperationException ("Socket is not listening");
-
-                       return server.Accept();
-               }
-               
-               /// <summary>
-               /// Accepts a pending connection
-               /// </summary>
-               /// <returns>A TcpClient
-               /// object made from the new socket.</returns>
-               public TcpClient AcceptTcpClient ()
-               {
-                       if (!active)
-                               throw new InvalidOperationException ("Socket is not listening");
-
-                       Socket clientSocket = server.Accept ();
-
-                       TcpClient client = new TcpClient(clientSocket);
-                       
-                       return client;
-               }
-               
-               /// <summary>
-               /// Destructor - stops the listener listening
-               /// </summary>
-               ~TcpListener ()
-               {
-                       if (active)
-                               Stop();
-               }
-       
-               /// <returns>
-               /// Returns 'true' if there is a connection waiting to be accepted
-               /// with AcceptSocket() or AcceptTcpClient().
-               /// </returns>
-               public bool Pending ()
-               {
-                       if (!active)
-                               throw new InvalidOperationException ("Socket is not listening");
-
-                       return server.Poll(0, SelectMode.SelectRead);
-               }
-               
-               /// <summary>
-               /// Tells the TcpListener to start listening.
-               /// </summary>
-               public void Start ()
-               {
-                       // MS: sets Listen to Int32.MaxValue
-                       this.Start (5);
-                       // According to the man page some BSD and BSD-derived
-                       // systems limit the backlog to 5.  This should really be
-                       // configurable though
-               }
-
-               /// <summary>
-               /// Tells the TcpListener to start listening for max number
-               /// of pending connections.
-               /// </summary>
-
-               public void Start (int backlog)
-               {
-                       if (active) {
-                               return;
-                       }
-                       if (server == null) {
-                               throw new InvalidOperationException ("Invalid server socket");
-                       }
-                       
-                       server.Bind (savedEP);
-                       server.Listen (backlog);
-                       active = true;
-               }
-
-               public IAsyncResult BeginAcceptSocket (AsyncCallback callback,
-                                                      object state)
-               {
-                       if (server == null) {
-                               throw new ObjectDisposedException (GetType ().ToString ());
-                       }
-                       
-                       return(server.BeginAccept (callback, state));
-               }
-               
-               public IAsyncResult BeginAcceptTcpClient (AsyncCallback callback, object state)
-               {
-                       if (server == null) {
-                               throw new ObjectDisposedException (GetType ().ToString ());
-                       }
-                       
-                       return(server.BeginAccept (callback, state));
-               }
-               
-               public Socket EndAcceptSocket (IAsyncResult asyncResult) 
-               {
-                       return(server.EndAccept (asyncResult));
-               }
-               
-               public TcpClient EndAcceptTcpClient (IAsyncResult asyncResult)
-               {
-                       Socket clientSocket = server.EndAccept (asyncResult);
-                       TcpClient client = new TcpClient (clientSocket);
-                       
-                       return(client);
-               }
-               
-               /// <summary>
-               /// Tells the TcpListener to stop listening and dispose
-               /// of all managed resources.
-               /// </summary>
-               public void Stop ()
-               {
-                       if (active) 
-                       {
-                               server.Close ();
-                               server = null;
-                       }
-
-                       Init (AddressFamily.InterNetwork, savedEP);
-               }
-
-               public Task<Socket> AcceptSocketAsync ()
-               {
-                       return Task<Socket>.Factory.FromAsync (BeginAcceptSocket, EndAcceptSocket, null);
-               }
-
-               public Task<TcpClient> AcceptTcpClientAsync ()
-               {
-                       return Task<TcpClient>.Factory.FromAsync (BeginAcceptTcpClient, EndAcceptTcpClient, null);
-               }
-       }
-}
diff --git a/mcs/class/System/System.Net.Sockets/TcpListener.platformnotsupported.cs b/mcs/class/System/System.Net.Sockets/TcpListener.platformnotsupported.cs
new file mode 100644 (file)
index 0000000..7b64967
--- /dev/null
@@ -0,0 +1,135 @@
+//
+// System.Net.Sockets.TcpListener.cs
+//
+// Author:
+//     Rolf Bjarne Kvinge <rolf@xamarin.com>
+//
+// Copyright (C) 2016 Xamarin Inc (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Net;
+using System.Threading.Tasks;
+
+namespace System.Net.Sockets
+{
+       public class TcpListener
+       {
+               const string EXCEPTION_MESSAGE = "System.Net.Sockets.TcpListener is not supported on the current platform.";
+
+               public TcpListener (int port)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public TcpListener (IPEndPoint localEP)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public TcpListener (IPAddress localaddr, int port)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected bool Active {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public EndPoint LocalEndpoint {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public Socket Server {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool ExclusiveAddressUse {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public Socket AcceptSocket ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public TcpClient AcceptTcpClient ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               ~TcpListener ()
+               {
+               }
+
+               public bool Pending ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void Start ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void Start (int backlog)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public IAsyncResult BeginAcceptSocket (AsyncCallback callback, object state)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public IAsyncResult BeginAcceptTcpClient (AsyncCallback callback, object state)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public Socket EndAcceptSocket (IAsyncResult asyncResult)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public TcpClient EndAcceptTcpClient (IAsyncResult asyncResult)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void Stop ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public Task<Socket> AcceptSocketAsync ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public Task<TcpClient> AcceptTcpClientAsync ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+       }
+}
diff --git a/mcs/class/System/System.Net.Sockets/UdpClient.cs b/mcs/class/System/System.Net.Sockets/UdpClient.cs
deleted file mode 100644 (file)
index ad3c411..0000000
+++ /dev/null
@@ -1,634 +0,0 @@
-//
-// System.Net.Sockets.UdpClient.cs
-//
-// Author:
-//    Gonzalo Paniagua Javier <gonzalo@ximian.com>
-//    Sridhar Kulkarni (sridharkulkarni@gmail.com)
-//    Marek Safar (marek.safar@gmail.com)
-//
-// Copyright (C) Ximian, Inc. http://www.ximian.com
-// Copyright 2011 Xamarin Inc.
-//
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Net;
-using System.Threading.Tasks;
-
-namespace System.Net.Sockets
-{
-       public class UdpClient : IDisposable
-       {
-               private bool disposed = false;
-               private bool active = false;
-               private Socket socket;
-               private AddressFamily family = AddressFamily.InterNetwork;
-               private byte[] recvbuffer;
-       
-               public UdpClient () : this(AddressFamily.InterNetwork)
-               {
-               }
-
-               public UdpClient(AddressFamily family)
-               {
-                       if(family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6)
-                               throw new ArgumentException ("Family must be InterNetwork or InterNetworkV6", "family");
-
-                       this.family = family;
-                       InitSocket (null);
-               }
-
-               public UdpClient (int port)
-               {
-                       if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
-                               throw new ArgumentOutOfRangeException ("port");
-
-                       this.family = AddressFamily.InterNetwork;
-
-                       IPEndPoint localEP = new IPEndPoint (IPAddress.Any, port);
-                       InitSocket (localEP);
-               }
-
-               public UdpClient (IPEndPoint localEP)
-               {
-                       if (localEP == null)
-                               throw new ArgumentNullException ("localEP");
-
-                       this.family = localEP.AddressFamily;
-
-                       InitSocket (localEP);
-               }
-
-               public UdpClient (int port, AddressFamily family)
-               {
-                       if (family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6)
-                               throw new ArgumentException ("Family must be InterNetwork or InterNetworkV6", "family");
-
-                       if (port < IPEndPoint.MinPort ||
-                           port > IPEndPoint.MaxPort) {
-                               throw new ArgumentOutOfRangeException ("port");
-                       }
-
-                       this.family = family;
-
-                       IPEndPoint localEP;
-
-                       if (family == AddressFamily.InterNetwork)
-                               localEP = new IPEndPoint (IPAddress.Any, port);
-                       else
-                               localEP = new IPEndPoint (IPAddress.IPv6Any, port);
-                       InitSocket (localEP);
-               }
-
-               public UdpClient (string hostname, int port)
-               {
-                       if (hostname == null)
-                               throw new ArgumentNullException ("hostname");
-
-                       if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
-                               throw new ArgumentOutOfRangeException ("port");
-
-                       InitSocket (null);
-                       Connect (hostname, port);
-               }
-
-               private void InitSocket (EndPoint localEP)
-               {
-                       if(socket != null) {
-                               socket.Close();
-                               socket = null;
-                       }
-
-                       socket = new Socket (family, SocketType.Dgram, ProtocolType.Udp);
-
-                       if (localEP != null)
-                               socket.Bind (localEP);
-               }
-
-               public void 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);
-               }
-       }
-}
-
diff --git a/mcs/class/System/System.Net.Sockets/UdpClient.platformnotsupported.cs b/mcs/class/System/System.Net.Sockets/UdpClient.platformnotsupported.cs
new file mode 100644 (file)
index 0000000..9533501
--- /dev/null
@@ -0,0 +1,241 @@
+//
+// System.Net.Sockets.UdpClient.cs
+//
+// Author:
+//     Rolf Bjarne Kvinge <rolf@xamarin.com>
+//
+// Copyright (C) 2016 Xamarin Inc (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Threading.Tasks;
+
+namespace System.Net.Sockets
+{
+       public class UdpClient : IDisposable
+       {
+               const string EXCEPTION_MESSAGE = "System.Net.Sockets.UdpClient is not supported on the current platform.";
+
+               public UdpClient ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public UdpClient(AddressFamily family)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public UdpClient (int port)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public UdpClient (IPEndPoint localEP)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public UdpClient (int port, AddressFamily family)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public UdpClient (string hostname, int port)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void Close ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void Connect (IPEndPoint endPoint)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void Connect (IPAddress addr, int port)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void Connect (string hostname, int port)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void DropMulticastGroup (IPAddress multicastAddr)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void DropMulticastGroup (IPAddress multicastAddr, int ifindex)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void JoinMulticastGroup (IPAddress multicastAddr)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void JoinMulticastGroup (int ifindex, IPAddress multicastAddr)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void JoinMulticastGroup (IPAddress multicastAddr, int timeToLive)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void JoinMulticastGroup (IPAddress multicastAddr, IPAddress localAddress)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public byte [] Receive (ref IPEndPoint remoteEP)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public int Send (byte [] dgram, int bytes)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public int Send (byte [] dgram, int bytes, IPEndPoint endPoint)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public int Send (byte [] dgram, int bytes, string hostname, int port)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public IAsyncResult BeginSend (byte[] datagram, int bytes, AsyncCallback requestCallback, object state)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public IAsyncResult BeginSend (byte[] datagram, int bytes, IPEndPoint endPoint, AsyncCallback requestCallback, object state)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public IAsyncResult BeginSend (byte[] datagram, int bytes, string hostname, int port, AsyncCallback requestCallback, object state)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public int EndSend (IAsyncResult asyncResult)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public IAsyncResult BeginReceive (AsyncCallback requestCallback, object state)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public byte[] EndReceive (IAsyncResult asyncResult, ref IPEndPoint remoteEP)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected bool Active {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public Socket Client {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public int Available {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool DontFragment {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool EnableBroadcast {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool ExclusiveAddressUse {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool MulticastLoopback {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public short Ttl {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public void Dispose ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected virtual void Dispose (bool disposing)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               ~UdpClient ()
+               {
+               }
+
+               public Task<UdpReceiveResult> ReceiveAsync ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public Task<int> SendAsync (byte[] datagram, int bytes)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public Task<int> SendAsync (byte[] datagram, int bytes, IPEndPoint endPoint)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public Task<int> SendAsync (byte[] datagram, int bytes, string hostname, int port)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+       }
+}
diff --git a/mcs/class/System/System.Net.WebSockets/ClientWebSocket.platformnotsupported.cs b/mcs/class/System/System.Net.WebSockets/ClientWebSocket.platformnotsupported.cs
new file mode 100644 (file)
index 0000000..324ae42
--- /dev/null
@@ -0,0 +1,98 @@
+//
+// ClientWebSocket.cs
+//
+// Author:
+//     Rolf Bjarne Kvinge <rolf@xamarin.com>
+//
+// Copyright (C) 2016 Xamarin Inc (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace System.Net.WebSockets
+{
+       public class ClientWebSocket : WebSocket, IDisposable
+       {
+               const string EXCEPTION_MESSAGE = "System.Net.WebSockets.ClientWebSocket is not supported on the current platform.";
+
+               public ClientWebSocket ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override void Dispose ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override void Abort ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public ClientWebSocketOptions Options {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override WebSocketState State {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override WebSocketCloseStatus? CloseStatus {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override string CloseStatusDescription {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override string SubProtocol {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public Task ConnectAsync (Uri uri, CancellationToken cancellationToken)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override Task SendAsync (ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override Task<WebSocketReceiveResult> ReceiveAsync (ArraySegment<byte> buffer, CancellationToken cancellationToken)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override Task CloseAsync (WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override Task CloseOutputAsync (WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+       }
+}
index 1ed7dfe075f6775de58a51649bb11d06c9bf9bc9..98200b45b4a01ad613756f7d16839f978ce1e08f 100644 (file)
@@ -106,6 +106,13 @@ namespace System.Net
                        }
                }
 
+               [MonoTODO]
+               internal static bool OSSupportsExtendedProtection {
+                       get {
+                               return false;
+                       }
+               }
+
                internal static void Clear ()
                {
                        EnsureModules ();
diff --git a/mcs/class/System/System.Net/AuthenticationManager.platformnotsupported.cs b/mcs/class/System/System.Net/AuthenticationManager.platformnotsupported.cs
new file mode 100644 (file)
index 0000000..1572ce7
--- /dev/null
@@ -0,0 +1,77 @@
+//
+// AuthenticationManager.cs
+//
+// Author:
+//       Rolf Bjarne Kvinge <rolf@xamarin.com>
+//
+// Copyright (c) 2016 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.Collections;
+using System.Collections.Specialized;
+
+namespace System.Net
+{
+       public class AuthenticationManager {
+               const string EXCEPTION_MESSAGE = "System.Net.AuthenticationManager is not supported on the current platform.";
+
+               private AuthenticationManager ()
+               {
+               }
+
+               public static ICredentialPolicy CredentialPolicy {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public static StringDictionary CustomTargetNameDictionary {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public static IEnumerator RegisteredModules {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public static Authorization Authenticate (string challenge, WebRequest request, ICredentials credentials)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public static Authorization PreAuthenticate (WebRequest request, ICredentials credentials)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public static void Register (IAuthenticationModule authenticationModule)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public static void Unregister (IAuthenticationModule authenticationModule)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public static void Unregister (string authenticationScheme)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+       }
+}
index 9045052ccf7a35a917619dcc0ee4d1fdd6cb5aa8..dac834884441e8ccd8764f846dcea5289ebd073b 100644 (file)
@@ -130,6 +130,9 @@ namespace System.Net {
                [Obsolete ("Use BeginGetHostEntry instead")]
                public static IAsyncResult BeginGetHostByName (string hostName, AsyncCallback requestCallback, object stateObject)
                {
+#if FEATURE_NO_BSD_SOCKETS
+                       throw new PlatformNotSupportedException ("System.Net.Dns:BeginGetHostByName is not supported on this platform.");
+#else
                        if (hostName == null)
                                throw new ArgumentNullException ("hostName");
 
@@ -140,11 +143,15 @@ namespace System.Net {
 
                        GetHostByNameCallback c = new GetHostByNameCallback (GetHostByName);
                        return c.BeginInvoke (hostName, requestCallback, stateObject);
+#endif // FEATURE_NO_BSD_SOCKETS
                }
 
                [Obsolete ("Use BeginGetHostEntry instead")]
                public static IAsyncResult BeginResolve (string hostName, AsyncCallback requestCallback, object stateObject)
                {
+#if FEATURE_NO_BSD_SOCKETS
+                       throw new PlatformNotSupportedException ("System.Net.Dns:BeginResolve is not supported on this platform.");
+#else
                        if (hostName == null)
                                throw new ArgumentNullException ("hostName");
 
@@ -155,6 +162,7 @@ namespace System.Net {
 
                        ResolveCallback c = new ResolveCallback (Resolve);
                        return c.BeginInvoke (hostName, requestCallback, stateObject);
+#endif // FEATURE_NO_BSD_SOCKETS
                }
 
                public static IAsyncResult BeginGetHostAddresses (string hostNameOrAddress, AsyncCallback requestCallback, object state)
@@ -178,6 +186,9 @@ namespace System.Net {
 
                public static IAsyncResult BeginGetHostEntry (string hostNameOrAddress, AsyncCallback requestCallback, object stateObject)
                {
+#if FEATURE_NO_BSD_SOCKETS
+                       throw new PlatformNotSupportedException ("System.Net.Dns:GetHostEntry is not supported on this platform.");
+#else
                        if (hostNameOrAddress == null)
                                throw new ArgumentNullException ("hostName");
                        if (hostNameOrAddress == "0.0.0.0" || hostNameOrAddress == "::0")
@@ -193,10 +204,14 @@ namespace System.Net {
 
                        GetHostEntryNameCallback c = new GetHostEntryNameCallback (GetHostEntry);
                        return c.BeginInvoke (hostNameOrAddress, requestCallback, stateObject);
+#endif // FEATURE_NO_BSD_SOCKETS
                }
 
                public static IAsyncResult BeginGetHostEntry (IPAddress address, AsyncCallback requestCallback, object stateObject)
                {
+#if FEATURE_NO_BSD_SOCKETS
+                       throw new PlatformNotSupportedException ("System.Net.Dns:BeginGetHostEntry is not supported on this platform.");
+#else
                        if (address == null)
                                throw new ArgumentNullException ("address");
 
@@ -207,6 +222,7 @@ namespace System.Net {
 
                        GetHostEntryIPCallback c = new GetHostEntryIPCallback (GetHostEntry);
                        return c.BeginInvoke (address, requestCallback, stateObject);
+#endif // FEATURE_NO_BSD_SOCKETS
                }
 
                [Obsolete ("Use EndGetHostEntry instead")]
@@ -279,10 +295,10 @@ namespace System.Net {
 
 
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
-               private extern static bool GetHostByName_internal(string host, out string h_name, out string[] h_aliases, out string[] h_addr_list);
+               private extern static bool GetHostByName_internal(string host, out string h_name, out string[] h_aliases, out string[] h_addr_list, int hint);
 
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
-               private extern static bool GetHostByAddr_internal(string addr, out string h_name, out string[] h_aliases, out string[] h_addr_list);
+               private extern static bool GetHostByAddr_internal(string addr, out string h_name, out string[] h_aliases, out string[] h_addr_list, int hint);
 
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
                private extern static bool GetHostName_internal(out string h_name);
@@ -356,7 +372,7 @@ namespace System.Net {
 
                        string h_name;
                        string[] h_aliases, h_addrlist;
-                       bool ret = GetHostByAddr_internal(address, out h_name, out h_aliases, out h_addrlist);
+                       bool ret = GetHostByAddr_internal(address, out h_name, out h_aliases, out h_addrlist, Socket.FamilyHint);
                        if (!ret)
                                Error_11001 (address);
                        return (hostent_to_IPHostEntry (address, h_name, h_aliases, h_addrlist));
@@ -409,12 +425,16 @@ namespace System.Net {
                [Obsolete ("Use GetHostEntry instead")]
                public static IPHostEntry GetHostByName (string hostName)
                {
+#if FEATURE_NO_BSD_SOCKETS
+                       if (!string.IsNullOrEmpty (hostName))
+                               throw new PlatformNotSupportedException ("System.Net.Dns:GetHostByName is not supported on this platform.");
+#endif // FEATURE_NO_BSD_SOCKETS
                        if (hostName == null)
                                throw new ArgumentNullException ("hostName");
                        string h_name;
                        string[] h_aliases, h_addrlist;
 
-                       bool ret = GetHostByName_internal(hostName, out h_name, out h_aliases, out h_addrlist);
+                       bool ret = GetHostByName_internal(hostName, out h_name, out h_aliases, out h_addrlist, Socket.FamilyHint);
                        if (ret == false)
                                Error_11001 (hostName);
 
@@ -436,6 +456,9 @@ namespace System.Net {
                [Obsolete ("Use GetHostEntry instead")]
                public static IPHostEntry Resolve(string hostName) 
                {
+#if FEATURE_NO_BSD_SOCKETS
+                       throw new PlatformNotSupportedException ("System.Net.Dns:Resolve is not supported on this platform.");
+#else
                        if (hostName == null)
                                throw new ArgumentNullException ("hostName");
 
@@ -450,6 +473,7 @@ namespace System.Net {
                                ret =  GetHostByName(hostName);
 
                        return ret;
+#endif // FEATURE_NO_BSD_SOCKETS
                }
 
                public static Task<IPAddress[]> GetHostAddressesAsync (string hostNameOrAddress)
diff --git a/mcs/class/System/System.Net/FtpRequestCreator.platformnotsupported.cs b/mcs/class/System/System.Net/FtpRequestCreator.platformnotsupported.cs
new file mode 100644 (file)
index 0000000..ae365c2
--- /dev/null
@@ -0,0 +1,39 @@
+//
+// System.Net.FtpbRequestCreator.cs
+//
+// Authors:
+//     Rolf Bjarne Kvinge <rolf@xamarin.com>
+//
+// Copyright (C) 2016 Xamarin Inc (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace System.Net
+{
+       class FtpRequestCreator : IWebRequestCreate
+       {
+               internal const string EXCEPTION_MESSAGE = "System.Net.FtpRequestCreator is not supported on the current platform.";
+               public WebRequest Create (Uri uri)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+       }
+}
index 9e2c655cb2dd9842e3afde14b817fe1b32b451e2..c0ea1b551195e55dd06e5919c44646ee5548dc8e 100644 (file)
@@ -17,6 +17,7 @@ using MSI = Mono.Security.Interface;
 #endif
 
 using System;
+using System.Globalization;
 using System.IO;
 using System.Net.Sockets;
 using System.Text;
@@ -42,6 +43,7 @@ namespace System.Net
                NetworkCredential credentials;
                IPHostEntry hostEntry;
                IPEndPoint localEndPoint;
+               IPEndPoint remoteEndPoint;
                IWebProxy proxy;
                int timeout = 100000;
                int rwTimeout = 300000;
@@ -65,7 +67,9 @@ namespace System.Net
                const string PasswordCommand = "PASS";
                const string TypeCommand = "TYPE";
                const string PassiveCommand = "PASV";
+               const string ExtendedPassiveCommand = "EPSV";
                const string PortCommand = "PORT";
+               const string ExtendedPortCommand = "EPRT";
                const string AbortCommand = "ABOR";
                const string AuthCommand = "AUTH";
                const string RestCommand = "REST";
@@ -401,6 +405,7 @@ namespace System.Net
                                                State = RequestState.Scheduled;
 
                                        Thread thread = new Thread (ProcessRequest);
+                                       thread.IsBackground = true;
                                        thread.Start ();
                                }
                        }
@@ -452,6 +457,7 @@ namespace System.Net
 
                        asyncResult = new FtpAsyncResult (callback, state);
                        Thread thread = new Thread (ProcessRequest);
+                       thread.IsBackground = true;
                        thread.Start ();
 
                        return asyncResult;
@@ -775,14 +781,14 @@ namespace System.Net
                        foreach (IPAddress address in hostEntry.AddressList) {
                                sock = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
 
-                               IPEndPoint remote = new IPEndPoint (address, requestUri.Port);
+                               remoteEndPoint = new IPEndPoint (address, requestUri.Port);
 
-                               if (!ServicePoint.CallEndPointDelegate (sock, remote)) {
+                               if (!ServicePoint.CallEndPointDelegate (sock, remoteEndPoint)) {
                                        sock.Close ();
                                        sock = null;
                                } else {
                                        try {
-                                               sock.Connect (remote);
+                                               sock.Connect (remoteEndPoint);
                                                localEndPoint = (IPEndPoint) sock.LocalEndPoint;
                                                break;
                                        } catch (SocketException exc) {
@@ -837,52 +843,19 @@ namespace System.Net
                }
 
                // Probably we could do better having here a regex
-               Socket SetupPassiveConnection (string statusDescription)
+               Socket SetupPassiveConnection (string statusDescription, bool ipv6)
                {
                        // Current response string
                        string response = statusDescription;
                        if (response.Length < 4)
                                throw new WebException ("Cannot open passive data connection");
-                       
-                       // Look for first digit after code
-                       int i;
-                       for (i = 3; i < response.Length && !Char.IsDigit (response [i]); i++)
-                               ;
-                       if (i >= response.Length)
-                               throw new WebException ("Cannot open passive data connection");
-
-                       // Get six elements
-                       string [] digits = response.Substring (i).Split (new char [] {','}, 6);
-                       if (digits.Length != 6)
-                               throw new WebException ("Cannot open passive data connection");
-
-                       // Clean non-digits at the end of last element
-                       int j;
-                       for (j = digits [5].Length - 1; j >= 0 && !Char.IsDigit (digits [5][j]); j--)
-                               ;
-                       if (j < 0)
-                               throw new WebException ("Cannot open passive data connection");
-                       
-                       digits [5] = digits [5].Substring (0, j + 1);
-
-                       IPAddress ip;
-                       try {
-                               ip = IPAddress.Parse (String.Join (".", digits, 0, 4));
-                       } catch (FormatException) {
-                               throw new WebException ("Cannot open passive data connection");
-                       }
 
-                       // Get the port
-                       int p1, p2, port;
-                       if (!Int32.TryParse (digits [4], out p1) || !Int32.TryParse (digits [5], out p2))
-                               throw new WebException ("Cannot open passive data connection");
+                       int port = ipv6 ? GetPortV6 (response) : GetPortV4 (response);
 
-                       port = (p1 << 8) + p2; // p1 * 256 + p2
-                       //port = p1 * 256 + p2;
                        if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
                                throw new WebException ("Cannot open passive data connection");
 
-                       IPEndPoint ep = new IPEndPoint (ip, port);
+                       IPEndPoint ep = new IPEndPoint (remoteEndPoint.Address, port);
                        Socket sock = new Socket (ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                        try {
                                sock.Connect (ep);
@@ -894,6 +867,87 @@ namespace System.Net
                        return sock;
                }
 
+               // GetPortV4, GetPortV6, FormatAddress and FormatAddressV6 are copied from referencesource
+               // TODO: replace FtpWebRequest completely.
+               private int GetPortV4(string responseString)
+               {
+                       string [] parsedList = responseString.Split(new char [] {' ', '(', ',', ')'});
+
+                       // We need at least the status code and the port
+                       if (parsedList.Length <= 7) {
+                               throw new FormatException(SR.GetString(SR.net_ftp_response_invalid_format, responseString));
+                       }
+
+                       int index = parsedList.Length-1;
+                       // skip the last non-number token (e.g. terminating '.')
+#if MONO
+                       // the MS code expects \r\n here in parsedList[index],
+                       // but we're stripping the EOL off earlier so the array contains
+                       // an empty string here which would make Char.IsNumber throw
+                       // TODO: this can be removed once we switch FtpWebRequest to referencesource
+                       if (parsedList[index] == "" || !Char.IsNumber(parsedList[index], 0))
+#else
+                       if (!Char.IsNumber(parsedList[index], 0))
+#endif
+                               index--;
+
+                       int port = Convert.ToByte(parsedList[index--], NumberFormatInfo.InvariantInfo);
+                       port = port |
+                               (Convert.ToByte(parsedList[index--], NumberFormatInfo.InvariantInfo) << 8);
+
+                       return port;
+               }
+
+               private int GetPortV6(string responseString)
+               {
+                       int pos1 = responseString.LastIndexOf("(");
+                       int pos2 = responseString.LastIndexOf(")");
+                       if (pos1 == -1 || pos2 <= pos1) 
+                               throw new FormatException(SR.GetString(SR.net_ftp_response_invalid_format, responseString));
+
+                       // addressInfo will contain a string of format "|||<tcp-port>|"
+                       string addressInfo = responseString.Substring(pos1+1, pos2-pos1-1);
+
+                       // Although RFC2428 recommends using "|" as the delimiter,
+                       // It allows ASCII characters in range 33-126 inclusive.
+                       // We should consider allowing the full range.
+
+                       string [] parsedList = addressInfo.Split(new char [] {'|'});
+                       if (parsedList.Length < 4)
+                               throw new FormatException(SR.GetString(SR.net_ftp_response_invalid_format, responseString));
+                       
+                       return Convert.ToInt32(parsedList[3], NumberFormatInfo.InvariantInfo);
+               }
+
+               private String FormatAddress(IPAddress address, int Port )
+               {
+                       byte [] localAddressInBytes = address.GetAddressBytes();
+
+                       // produces a string in FTP IPAddress/Port encoding (a1, a2, a3, a4, p1, p2), for sending as a parameter
+                       // to the port command.
+                       StringBuilder sb = new StringBuilder(32);
+                       foreach (byte element in localAddressInBytes) {
+                               sb.Append(element);
+                               sb.Append(',');
+                       }
+                       sb.Append(Port / 256 );
+                       sb.Append(',');
+                       sb.Append(Port % 256 );
+                       return sb.ToString();
+               }
+
+               private string FormatAddressV6(IPAddress address, int port) {
+                       StringBuilder sb = new StringBuilder(43); // based on max size of IPv6 address + port + seperators
+                       String addressString = address.ToString();
+                       sb.Append("|2|");
+                       sb.Append(addressString);
+                       sb.Append('|');
+                       sb.Append(port.ToString(NumberFormatInfo.InvariantInfo));
+                       sb.Append('|');
+                       return sb.ToString();
+               }
+               //
+
                Exception CreateExceptionFromResponse (FtpStatus status)
                {
                        FtpWebResponse ftpResponse = new FtpWebResponse (this, requestUri, method, status);
@@ -932,18 +986,19 @@ namespace System.Net
                Socket InitDataConnection ()
                {
                        FtpStatus status;
-                       
+                       bool ipv6 = remoteEndPoint.AddressFamily == AddressFamily.InterNetworkV6;
+
                        if (usePassive) {
-                               status = SendCommand (PassiveCommand);
-                               if (status.StatusCode != FtpStatusCode.EnteringPassive) {
+                               status = SendCommand (ipv6 ? ExtendedPassiveCommand : PassiveCommand);
+                               if (status.StatusCode != (ipv6 ? (FtpStatusCode)229 : FtpStatusCode.EnteringPassive)) { // FtpStatusCode doesn't contain code 229 for EPSV so we need to cast...
                                        throw CreateExceptionFromResponse (status);
                                }
                                
-                               return SetupPassiveConnection (status.StatusDescription);
+                               return SetupPassiveConnection (status.StatusDescription, ipv6);
                        }
 
                        // Open a socket to listen the server's connection
-                       Socket sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+                       Socket sock = new Socket (remoteEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                        try {
                                sock.Bind (new IPEndPoint (localEndPoint.Address, 0));
                                sock.Listen (1); // We only expect a connection from server
@@ -955,12 +1010,10 @@ namespace System.Net
                        }
 
                        IPEndPoint ep = (IPEndPoint) sock.LocalEndPoint;
-                       string ipString = ep.Address.ToString ().Replace ('.', ',');
-                       int h1 = ep.Port >> 8; // ep.Port / 256
-                       int h2 = ep.Port % 256;
 
-                       string portParam = ipString + "," + h1 + "," + h2;
-                       status = SendCommand (PortCommand, portParam);
+                       var portParam = ipv6 ? FormatAddressV6 (ep.Address, ep.Port) : FormatAddress (ep.Address, ep.Port);
+
+                       status = SendCommand (ipv6 ? ExtendedPortCommand : PortCommand, portParam);
                        
                        if (status.StatusCode != FtpStatusCode.CommandOK) {
                                sock.Close ();
diff --git a/mcs/class/System/System.Net/FtpWebRequest.platformnotsupported.cs b/mcs/class/System/System.Net/FtpWebRequest.platformnotsupported.cs
new file mode 100644 (file)
index 0000000..2bb79d7
--- /dev/null
@@ -0,0 +1,182 @@
+//
+// System.Net.FtpWebRequest.cs
+//
+// Author:
+//     Rolf Bjarne Kvinge <rolf@xamarin.com>
+//
+// Copyright (C) 2016 Xamarin Inc (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.IO;
+using System.Security.Cryptography.X509Certificates;
+
+namespace System.Net
+{
+       public sealed class FtpWebRequest : WebRequest
+       {
+               const string EXCEPTION_MESSAGE = "System.Net.FtpWebRequest is not supported on the current platform.";
+
+               FtpWebRequest ()
+               {
+               }
+
+               public X509CertificateCollection ClientCertificates {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override string ConnectionGroupName {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override string ContentType {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override long ContentLength {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public long ContentOffset {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override ICredentials Credentials {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+#if !MOBILE
+               public static new RequestCachePolicy DefaultCachePolicy {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+#endif
+
+               public bool EnableSsl {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override WebHeaderCollection Headers {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool KeepAlive {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override string Method {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override bool PreAuthenticate {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override IWebProxy Proxy {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public int ReadWriteTimeout {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string RenameTo {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override Uri RequestUri {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public ServicePoint ServicePoint {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool UsePassive {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override bool UseDefaultCredentials {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool UseBinary {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override int Timeout {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override void Abort ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override WebResponse EndGetResponse (IAsyncResult asyncResult)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override WebResponse GetResponse ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override Stream EndGetRequestStream (IAsyncResult asyncResult)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override Stream GetRequestStream ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+       }
+}
diff --git a/mcs/class/System/System.Net/FtpWebResponse.platformnotsupported.cs b/mcs/class/System/System.Net/FtpWebResponse.platformnotsupported.cs
new file mode 100644 (file)
index 0000000..cd4fa71
--- /dev/null
@@ -0,0 +1,91 @@
+//
+// System.Net.FtpWebResponse.cs
+//
+// Author:
+//     Rolf Bjarne Kvinge <rolf@xamarin.com>
+//
+// Copyright (C) 2016 Xamarin Inc (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.IO;
+
+namespace System.Net
+{
+       public class FtpWebResponse : WebResponse
+       {
+               const string EXCEPTION_MESSAGE = "System.Net.FtpWebResponse is not supported on the current platform.";
+
+               FtpWebResponse ()
+               {
+               }
+
+               public override long ContentLength {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override WebHeaderCollection Headers {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override Uri ResponseUri {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public DateTime LastModified {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string BannerMessage {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string WelcomeMessage {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string ExitMessage {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public FtpStatusCode StatusCode {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override bool SupportsHeaders {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string StatusDescription {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override void Close ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override Stream GetResponseStream ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+       }
+}
index 29afc0fd84b78ceca4e33b0dfe9efa2b4f9767fd..716229d8b565b0bcc0a00b3894274f2565c3282e 100644 (file)
@@ -42,6 +42,7 @@ using System.IO;
 using System.Collections;
 using System.Threading;
 using System.Threading.Tasks;
+using System.Security.Authentication.ExtendedProtection;
 using System.Security.Cryptography;
 using System.Security.Cryptography.X509Certificates;
 
@@ -69,6 +70,12 @@ namespace System.Net {
                ArrayList wait_queue; // List<ListenerAsyncResult> wait_queue;
                Hashtable connections;
 
+               ServiceNameStore defaultServiceNames;
+               ExtendedProtectionPolicy extendedProtectionPolicy;
+               ExtendedProtectionSelector extendedProtectionSelectorDelegate;
+
+               public delegate ExtendedProtectionPolicy ExtendedProtectionSelector (HttpListenerRequest request);
+
                public HttpListener ()
                {
                        prefixes = new HttpListenerPrefixCollection (this);
@@ -77,6 +84,8 @@ namespace System.Net {
                        ctx_queue = new ArrayList ();
                        wait_queue = new ArrayList ();
                        auth_schemes = AuthenticationSchemes.Anonymous;
+                       defaultServiceNames = new ServiceNameStore ();
+                       extendedProtectionPolicy = new ExtendedProtectionPolicy (PolicyEnforcement.Never);
                }
 
                internal HttpListener (X509Certificate certificate, IMonoTlsProvider tlsProvider, MSI.MonoTlsSettings tlsSettings)
@@ -146,6 +155,21 @@ namespace System.Net {
                        }
                }
 
+               public ExtendedProtectionSelector ExtendedProtectionSelectorDelegate
+               {
+                       get { return extendedProtectionSelectorDelegate; }
+                       set {
+                               CheckDisposed();
+                               if (value == null)
+                                       throw new ArgumentNullException ();
+
+                               if (!AuthenticationManager.OSSupportsExtendedProtection)
+                                       throw new PlatformNotSupportedException (SR.GetString (SR.security_ExtendedProtection_NoOSSupport));
+
+                               extendedProtectionSelectorDelegate = value;
+                       }
+               }
+
                public bool IgnoreWriteExceptions {
                        get { return ignore_write_exceptions; }
                        set {
@@ -169,6 +193,42 @@ namespace System.Net {
                        }
                }
 
+               [MonoTODO]
+               public HttpListenerTimeoutManager TimeoutManager {
+                       get {
+                               throw new NotImplementedException ();
+                       }
+               }
+
+               [MonoTODO ("not used anywhere in the implementation")]
+               public ExtendedProtectionPolicy ExtendedProtectionPolicy
+               {
+                       get {
+                               return extendedProtectionPolicy;
+                       }
+                       set {
+                               CheckDisposed ();
+
+                               if (value == null)
+                                       throw new ArgumentNullException ("value");
+
+                               if (!AuthenticationManager.OSSupportsExtendedProtection && value.PolicyEnforcement == PolicyEnforcement.Always)
+                                       throw new PlatformNotSupportedException (SR.GetString(SR.security_ExtendedProtection_NoOSSupport));
+
+                               if (value.CustomChannelBinding != null)
+                                       throw new ArgumentException (SR.GetString (SR.net_listener_cannot_set_custom_cbt), "CustomChannelBinding");
+                               extendedProtectionPolicy = value;
+                       }
+               }
+
+               public ServiceNameCollection DefaultServiceNames
+               {
+                       get {
+                               return defaultServiceNames.ServiceNames;
+                       }
+               }
+
                // TODO: use this
                public string Realm {
                        get { return realm; }
diff --git a/mcs/class/System/System.Net/HttpListener.platformnotsupported.cs b/mcs/class/System/System.Net/HttpListener.platformnotsupported.cs
new file mode 100644 (file)
index 0000000..bffdfbc
--- /dev/null
@@ -0,0 +1,123 @@
+//
+// System.Net.HttpListener
+//
+// Author:
+//     Rolf Bjarne Kvinge <rolf@xamarin.com>
+//
+// Copyright (C) 2016 Xamarin Inc (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.Threading.Tasks;
+
+namespace System.Net {
+       public sealed class HttpListener : IDisposable
+       {
+               internal const string EXCEPTION_MESSAGE = "System.Net.HttpListener is not supported on the current platform.";
+
+               public HttpListener ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public AuthenticationSchemes AuthenticationSchemes {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public AuthenticationSchemeSelector AuthenticationSchemeSelectorDelegate {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool IgnoreWriteExceptions {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool IsListening {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public static bool IsSupported {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public HttpListenerPrefixCollection Prefixes {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string Realm {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool UnsafeConnectionNtlmAuthentication {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public void Abort ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void Close ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public IAsyncResult BeginGetContext (AsyncCallback callback, Object state)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public HttpListenerContext EndGetContext (IAsyncResult asyncResult)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public HttpListenerContext GetContext ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void Start ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void Stop ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               void IDisposable.Dispose ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public Task<HttpListenerContext> GetContextAsync ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+       }
+}
index d495e4af581e281bb88a1eceb6f4c6f4f8d1309a..5a3a2f0f445be565d7b01433dce630f5c6d7cccb 100644 (file)
@@ -137,16 +137,25 @@ namespace System.Net {
                        } 
                }
 
+               [MonoTODO]
                public Task<HttpListenerWebSocketContext> AcceptWebSocketAsync (string subProtocol)
                {
                        throw new NotImplementedException ();
                }
 
+               [MonoTODO]
+               public Task<HttpListenerWebSocketContext> AcceptWebSocketAsync (string subProtocol, TimeSpan keepAliveInterval)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               [MonoTODO]
                public Task<HttpListenerWebSocketContext> AcceptWebSocketAsync (string subProtocol, int receiveBufferSize, TimeSpan keepAliveInterval)
                {
                        throw new NotImplementedException ();
                }
 
+               [MonoTODO]
                public Task<HttpListenerWebSocketContext> AcceptWebSocketAsync (string subProtocol, int receiveBufferSize, TimeSpan keepAliveInterval, ArraySegment<byte> internalBuffer)
                {
                        throw new NotImplementedException ();
diff --git a/mcs/class/System/System.Net/HttpListenerContext.platformnotsupported.cs b/mcs/class/System/System.Net/HttpListenerContext.platformnotsupported.cs
new file mode 100644 (file)
index 0000000..4c729de
--- /dev/null
@@ -0,0 +1,68 @@
+//
+// System.Net.HttpListenerContext
+//
+// Author:
+//     Rolf Bjarne Kvinge <rolf@xamarin.com>
+//
+// Copyright (C) 2016 Xamarin Inc (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.Security.Principal;
+using System.Threading.Tasks;
+using System.Net.WebSockets;
+
+namespace System.Net {
+       public sealed class HttpListenerContext {
+               const string EXCEPTION_MESSAGE = "System.Net.HttpListenerContext is not supported on the current platform.";
+
+               HttpListenerContext ()
+               {
+               }
+
+               public HttpListenerRequest Request {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public HttpListenerResponse Response {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public IPrincipal User {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public Task<HttpListenerWebSocketContext> AcceptWebSocketAsync (string subProtocol)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public Task<HttpListenerWebSocketContext> AcceptWebSocketAsync (string subProtocol, int receiveBufferSize, TimeSpan keepAliveInterval)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public Task<HttpListenerWebSocketContext> AcceptWebSocketAsync (string subProtocol, int receiveBufferSize, TimeSpan keepAliveInterval, ArraySegment<byte> internalBuffer)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+       }
+}
diff --git a/mcs/class/System/System.Net/HttpListenerPrefixCollection.platformnotsupported.cs b/mcs/class/System/System.Net/HttpListenerPrefixCollection.platformnotsupported.cs
new file mode 100644 (file)
index 0000000..e3566c2
--- /dev/null
@@ -0,0 +1,93 @@
+//
+// System.Net.HttpListenerPrefixCollection.cs
+//
+// Author:
+//     Rolf Bjarne Kvinge <rolf@xamarin.com>
+//
+// Copyright (C) 2016 Xamarin Inc (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.Collections;
+using System.Collections.Generic;
+
+namespace System.Net {
+       public class HttpListenerPrefixCollection : ICollection<string>, IEnumerable<string>, IEnumerable
+       {
+               const string EXCEPTION_MESSAGE = "System.Net.HttpListenerPrefixCollection is not supported on the current platform.";
+
+               HttpListenerPrefixCollection ()
+               {
+               }
+
+               public int Count {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool IsReadOnly {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool IsSynchronized {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public void Add (string uriPrefix)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void Clear ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public bool Contains (string uriPrefix)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void CopyTo (string [] array, int offset)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void CopyTo (Array array, int offset)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public IEnumerator<string> GetEnumerator ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               IEnumerator IEnumerable.GetEnumerator ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public bool Remove (string uriPrefix)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+       }
+}
diff --git a/mcs/class/System/System.Net/HttpListenerRequest.platformnotsupported.cs b/mcs/class/System/System.Net/HttpListenerRequest.platformnotsupported.cs
new file mode 100644 (file)
index 0000000..32560d9
--- /dev/null
@@ -0,0 +1,180 @@
+//
+// System.Net.HttpListenerRequest
+//
+// Author:
+//     Rolf Bjarne Kvinge <rolf@xamarin.com>
+//
+// Copyright (C) 2016 Xamarin Inc (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.Collections.Specialized;
+using System.IO;
+using System.Security.Cryptography.X509Certificates;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace System.Net {
+       public sealed class HttpListenerRequest
+       {
+               const string EXCEPTION_MESSAGE = "System.Net.HttpListenerRequest is not supported on the current platform.";
+
+               HttpListenerRequest ()
+               {
+               }
+
+               public string [] AcceptTypes {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public int ClientCertificateError {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public Encoding ContentEncoding {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public long ContentLength64 {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string ContentType {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public CookieCollection Cookies {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool HasEntityBody {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public NameValueCollection Headers {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string HttpMethod {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public Stream InputStream {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool IsAuthenticated {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool IsLocal {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool IsSecureConnection {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool KeepAlive {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public IPEndPoint LocalEndPoint {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public Version ProtocolVersion {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public NameValueCollection QueryString {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string RawUrl {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public IPEndPoint RemoteEndPoint {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public Guid RequestTraceIdentifier {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public Uri Url {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public Uri UrlReferrer {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string UserAgent {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string UserHostAddress {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string UserHostName {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string [] UserLanguages {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, object state)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public X509Certificate2 GetClientCertificate ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public string ServiceName {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public TransportContext TransportContext {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool IsWebSocketRequest {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public Task<X509Certificate2> GetClientCertificateAsync ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+       }
+}
index 15ec5bb59dbf74ce6b8206c6acb1f2a0dc66eaad..73aa6396b5343e27c1ae1808bc72a7c6470053a5 100644 (file)
@@ -517,64 +517,6 @@ namespace System.Net {
                        cookies.Add (cookie);
                }
        }
-
-       // do not inline into HttpListenerResponse as this recursively brings everything that's 
-       // reachable by IDisposable.Dispose (and that's quite a lot in this case). 
-       static class HttpListenerResponseHelper {
-
-               internal static string GetStatusDescription (int code)
-               {
-                       switch (code){
-                       case 100: return "Continue";
-                       case 101: return "Switching Protocols";
-                       case 102: return "Processing";
-                       case 200: return "OK";
-                       case 201: return "Created";
-                       case 202: return "Accepted";
-                       case 203: return "Non-Authoritative Information";
-                       case 204: return "No Content";
-                       case 205: return "Reset Content";
-                       case 206: return "Partial Content";
-                       case 207: return "Multi-Status";
-                       case 300: return "Multiple Choices";
-                       case 301: return "Moved Permanently";
-                       case 302: return "Found";
-                       case 303: return "See Other";
-                       case 304: return "Not Modified";
-                       case 305: return "Use Proxy";
-                       case 307: return "Temporary Redirect";
-                       case 400: return "Bad Request";
-                       case 401: return "Unauthorized";
-                       case 402: return "Payment Required";
-                       case 403: return "Forbidden";
-                       case 404: return "Not Found";
-                       case 405: return "Method Not Allowed";
-                       case 406: return "Not Acceptable";
-                       case 407: return "Proxy Authentication Required";
-                       case 408: return "Request Timeout";
-                       case 409: return "Conflict";
-                       case 410: return "Gone";
-                       case 411: return "Length Required";
-                       case 412: return "Precondition Failed";
-                       case 413: return "Request Entity Too Large";
-                       case 414: return "Request-Uri Too Long";
-                       case 415: return "Unsupported Media Type";
-                       case 416: return "Requested Range Not Satisfiable";
-                       case 417: return "Expectation Failed";
-                       case 422: return "Unprocessable Entity";
-                       case 423: return "Locked";
-                       case 424: return "Failed Dependency";
-                       case 500: return "Internal Server Error";
-                       case 501: return "Not Implemented";
-                       case 502: return "Bad Gateway";
-                       case 503: return "Service Unavailable";
-                       case 504: return "Gateway Timeout";
-                       case 505: return "Http Version Not Supported";
-                       case 507: return "Insufficient Storage";
-                       }
-                       return "";
-               }
-       }
 }
 #endif
 
diff --git a/mcs/class/System/System.Net/HttpListenerResponse.platformnotsupported.cs b/mcs/class/System/System.Net/HttpListenerResponse.platformnotsupported.cs
new file mode 100644 (file)
index 0000000..97661d6
--- /dev/null
@@ -0,0 +1,150 @@
+//
+// System.Net.HttpListenerResponse
+//
+// Author:
+//     Rolf Bjarne Kvinge <rolf@xamarin.com>
+//
+// Copyright (C) 2016 Xamarin Inc (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.IO;
+using System.Text;
+
+namespace System.Net {
+       public sealed class HttpListenerResponse : IDisposable
+       {
+               const string EXCEPTION_MESSAGE = "System.Net.HttpListenerResponse is not supported on the current platform.";
+
+               HttpListenerResponse ()
+               {
+               }
+
+               public Encoding ContentEncoding {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public long ContentLength64 {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string ContentType {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public CookieCollection Cookies {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public WebHeaderCollection Headers {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool KeepAlive {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public Stream OutputStream {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public Version ProtocolVersion {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string RedirectLocation {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool SendChunked {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public int StatusCode {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string StatusDescription {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               void IDisposable.Dispose ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void Abort ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void AddHeader (string name, string value)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void AppendCookie (Cookie cookie)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void AppendHeader (string name, string value)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void Close ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void Close (byte [] responseEntity, bool willBlock)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void CopyFrom (HttpListenerResponse templateResponse)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void Redirect (string url)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void SetCookie (Cookie cookie)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+       }
+}
diff --git a/mcs/class/System/System.Net/HttpListenerResponseHelper.cs b/mcs/class/System/System.Net/HttpListenerResponseHelper.cs
new file mode 100644 (file)
index 0000000..7fc3c11
--- /dev/null
@@ -0,0 +1,88 @@
+//
+// System.Net.HttpListenerResponseHelper
+//
+// Author:
+//     Gonzalo Paniagua Javier (gonzalo@novell.com)
+//
+// Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
+// Copyright (C) 2016 Xamarin Inc (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace System.Net {
+       // do not inline into HttpListenerResponse as this recursively brings everything that's
+       // reachable by IDisposable.Dispose (and that's quite a lot in this case).
+       static class HttpListenerResponseHelper {
+
+               internal static string GetStatusDescription (int code)
+               {
+                       switch (code){
+                       case 100: return "Continue";
+                       case 101: return "Switching Protocols";
+                       case 102: return "Processing";
+                       case 200: return "OK";
+                       case 201: return "Created";
+                       case 202: return "Accepted";
+                       case 203: return "Non-Authoritative Information";
+                       case 204: return "No Content";
+                       case 205: return "Reset Content";
+                       case 206: return "Partial Content";
+                       case 207: return "Multi-Status";
+                       case 300: return "Multiple Choices";
+                       case 301: return "Moved Permanently";
+                       case 302: return "Found";
+                       case 303: return "See Other";
+                       case 304: return "Not Modified";
+                       case 305: return "Use Proxy";
+                       case 307: return "Temporary Redirect";
+                       case 400: return "Bad Request";
+                       case 401: return "Unauthorized";
+                       case 402: return "Payment Required";
+                       case 403: return "Forbidden";
+                       case 404: return "Not Found";
+                       case 405: return "Method Not Allowed";
+                       case 406: return "Not Acceptable";
+                       case 407: return "Proxy Authentication Required";
+                       case 408: return "Request Timeout";
+                       case 409: return "Conflict";
+                       case 410: return "Gone";
+                       case 411: return "Length Required";
+                       case 412: return "Precondition Failed";
+                       case 413: return "Request Entity Too Large";
+                       case 414: return "Request-Uri Too Long";
+                       case 415: return "Unsupported Media Type";
+                       case 416: return "Requested Range Not Satisfiable";
+                       case 417: return "Expectation Failed";
+                       case 422: return "Unprocessable Entity";
+                       case 423: return "Locked";
+                       case 424: return "Failed Dependency";
+                       case 500: return "Internal Server Error";
+                       case 501: return "Not Implemented";
+                       case 502: return "Bad Gateway";
+                       case 503: return "Service Unavailable";
+                       case 504: return "Gateway Timeout";
+                       case 505: return "Http Version Not Supported";
+                       case 507: return "Insufficient Storage";
+                       }
+                       return "";
+               }
+       }
+}
index d7e008baa0303d99aeb1635e613cb7c990a2b054..34673579632d3810fa69491483a2ac33e83155f1 100644 (file)
@@ -30,6 +30,46 @@ namespace System.Net
 {
        public class HttpListenerTimeoutManager
        {
+               [MonoTODO]
+               public TimeSpan EntityBody
+               {
+                       get { throw new NotImplementedException (); }
+                       set { throw new NotImplementedException (); }
+               }
 
+               [MonoTODO]
+               public TimeSpan DrainEntityBody
+               {
+                       get { throw new NotImplementedException (); }
+                       set { throw new NotImplementedException (); }
+               }
+
+               [MonoTODO]
+               public TimeSpan RequestQueue
+               {
+                       get { throw new NotImplementedException (); }
+                       set { throw new NotImplementedException (); }
+               }
+
+               [MonoTODO]
+               public TimeSpan IdleConnection
+               {
+                       get { throw new NotImplementedException (); }
+                       set { throw new NotImplementedException (); }
+               }
+
+               [MonoTODO]
+               public TimeSpan HeaderWait
+               {
+                       get { throw new NotImplementedException (); }
+                       set { throw new NotImplementedException (); }
+               }
+
+               [MonoTODO]
+               public long MinSendBytesPerSecond
+               {
+                       get { throw new NotImplementedException (); }
+                       set { throw new NotImplementedException (); }
+               }
        }
 }
\ No newline at end of file
index 9f94783258dfa6a4067bebd666584507334cfd6c..a57c579250ed33e6f27cb11ad04469840f3a06b3 100644 (file)
@@ -226,12 +226,12 @@ namespace System.Net
                        internal set { actualUri = value; } // Used by Ftp+proxy
                }
                
-               public bool AllowAutoRedirect {
+               public virtual bool AllowAutoRedirect {
                        get { return allowAutoRedirect; }
                        set { this.allowAutoRedirect = value; }
                }
                
-               public bool AllowWriteStreamBuffering {
+               public virtual bool AllowWriteStreamBuffering {
                        get { return allowBuffering; }
                        set { allowBuffering = value; }
                }
@@ -918,6 +918,12 @@ namespace System.Net
                        return EndGetRequestStream (asyncResult);
                }
 
+               [MonoTODO]
+               public Stream GetRequestStream (out TransportContext context)
+               {
+                       throw new NotImplementedException ();
+               }
+
                bool CheckIfForceWrite (SimpleAsyncResult result)
                {
                        if (writeStream == null || writeStream.RequestWritten || !InternalAllowBuffering)
@@ -1314,8 +1320,11 @@ namespace System.Net
                                        msg = "Error: " + status;
                                        wex = new WebException (msg, status);
                                } else {
-                                       msg = String.Format ("Error: {0} ({1})", status, exc.Message);
-                                       wex = new WebException (msg, status, WebExceptionInternalStatus.RequestFatal, exc);
+                                       wex = exc as WebException;
+                                       if (wex == null) {
+                                               msg = String.Format ("Error: {0} ({1})", status, exc.Message);
+                                               wex = new WebException (msg, status, WebExceptionInternalStatus.RequestFatal, exc);
+                                       }
                                }
                                r.SetCompleted (false, wex);
                                r.DoCallback ();
diff --git a/mcs/class/System/System.Net/HttpWebRequest.platformnotsupported.cs b/mcs/class/System/System.Net/HttpWebRequest.platformnotsupported.cs
new file mode 100644 (file)
index 0000000..3977c7b
--- /dev/null
@@ -0,0 +1,422 @@
+//
+// System.Net.HttpWebRequest
+//
+// Author:
+//     Rolf Bjarne Kvinge <rolf@xamarin.com>
+//
+// Copyright (C) 2016 Xamarin Inc (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.IO;
+using System.Net.Security;
+using System.Runtime.Serialization;
+using System.Security.Cryptography.X509Certificates;
+
+namespace System.Net
+{
+       [Serializable]
+       public class HttpWebRequest : WebRequest, ISerializable
+       {
+               internal const string EXCEPTION_MESSAGE = "System.Net.HttpWebRequest is not supported on the current platform.";
+
+#if MOBILE
+               public
+#else
+               internal
+#endif
+               HttpWebRequest (Uri uri)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               internal HttpWebRequest (Uri uri, object /* IMonoTlsProvider */ tlsProvider, object /* MonoTlsSettings */ settings = null)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected HttpWebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public string Accept {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public Uri Address {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool AllowAutoRedirect {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool AllowWriteStreamBuffering {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public virtual bool AllowReadStreamBuffering {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public DecompressionMethods AutomaticDecompression {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               internal bool InternalAllowBuffering {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public X509CertificateCollection ClientCertificates {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string Connection {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override string ConnectionGroupName {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override long ContentLength {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               internal long InternalContentLength {
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override string ContentType {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public HttpContinueDelegate ContinueDelegate {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public virtual CookieContainer CookieContainer {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override ICredentials Credentials {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public DateTime Date {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+#if !MOBILE
+               public static new RequestCachePolicy DefaultCachePolicy {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+#endif
+
+               public static int DefaultMaximumErrorResponseLength {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string Expect {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public virtual bool HaveResponse {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override WebHeaderCollection Headers {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string Host {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public DateTime IfModifiedSince {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool KeepAlive {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public int MaximumAutomaticRedirections {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public int MaximumResponseHeadersLength {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public static int DefaultMaximumResponseHeadersLength {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public int ReadWriteTimeout {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public int ContinueTimeout {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string MediaType {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override string Method {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool Pipelined {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override bool PreAuthenticate {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public Version ProtocolVersion {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override IWebProxy Proxy {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string Referer {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override Uri RequestUri {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool SendChunked {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public ServicePoint ServicePoint {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               internal ServicePoint ServicePointNoLock {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public virtual bool SupportsCookieContainer {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override int Timeout {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string TransferEncoding {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override bool UseDefaultCredentials {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string UserAgent {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool UnsafeAuthenticatedConnectionSharing {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               internal bool ExpectContinue {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               internal ServerCertValidationCallback ServerCertValidationCallback {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               internal Uri AuthUri {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public RemoteCertificateValidationCallback ServerCertificateValidationCallback {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public void AddRange (int range)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void AddRange (int from, int to)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void AddRange (string rangeSpecifier, int range)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void AddRange (string rangeSpecifier, int from, int to)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void AddRange (long range)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void AddRange (long from, long to)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void AddRange (string rangeSpecifier, long range)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public void AddRange (string rangeSpecifier, long from, long to)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override Stream EndGetRequestStream (IAsyncResult asyncResult)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override Stream GetRequestStream()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override WebResponse EndGetResponse (IAsyncResult asyncResult)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public Stream EndGetRequestStream (IAsyncResult asyncResult, out TransportContext transportContext)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override WebResponse GetResponse()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               internal bool FinishedReading {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               internal bool Aborted {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override void Abort ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               void ISerializable.GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected override void GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               internal void SetWriteStreamError (WebExceptionStatus status, Exception exc)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               internal byte[] GetRequestHeaders ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+       }
+}
index 6a73ae0f167c2b5217a06293eb2f90d54b370e5b..5402d58f522a0f413aac15f2dc281e19a66d4827 100644 (file)
@@ -106,7 +106,7 @@ namespace System.Net
                        version = (Version) info.GetValue ("version", typeof (Version));
                        statusCode = (HttpStatusCode) info.GetValue ("statusCode", typeof (HttpStatusCode));
                }
-               
+
                // Properties
                
                public string CharacterSet {
@@ -225,7 +225,7 @@ namespace System.Net
                public string Server {
                        get {
                                CheckDisposed ();
-                               return webHeaders ["Server"]
+                               return webHeaders ["Server"] ?? "";
                        }
                }
                
diff --git a/mcs/class/System/System.Net/HttpWebResponse.platformnotsupported.cs b/mcs/class/System/System.Net/HttpWebResponse.platformnotsupported.cs
new file mode 100644 (file)
index 0000000..300d5d4
--- /dev/null
@@ -0,0 +1,147 @@
+//
+// System.Net.HttpWebResponse
+//
+// Author:
+//     Rolf Bjarne Kvinge <rolf@xamarin.com>
+//
+// Copyright (C) 2016 Xamarin Inc (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.IO;
+using System.Runtime.Serialization;
+
+namespace System.Net
+{
+       [Serializable]
+       public class HttpWebResponse : WebResponse, ISerializable, IDisposable
+       {
+               const string EXCEPTION_MESSAGE = "System.Net.HttpWebResponse is not supported on the current platform.";
+
+               [Obsolete ("Serialization is obsoleted for this type", false)]
+               protected HttpWebResponse (SerializationInfo serializationInfo, StreamingContext streamingContext)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public string CharacterSet {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string ContentEncoding {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override long ContentLength {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override string ContentType {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public virtual CookieCollection Cookies {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override WebHeaderCollection Headers {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               [MonoTODO]
+               public override bool IsMutuallyAuthenticated {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public DateTime LastModified {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public virtual string Method {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public Version ProtocolVersion {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override Uri ResponseUri {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string Server {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public virtual HttpStatusCode StatusCode {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public virtual string StatusDescription {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public override bool SupportsHeaders {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string GetResponseHeader (string headerName)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               internal void ReadAll ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override Stream GetResponseStream ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               void ISerializable.GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected override void GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public override void Close ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               void IDisposable.Dispose ()
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               protected override void Dispose (bool disposing)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+       }
+}
diff --git a/mcs/class/System/System.Net/ServicePoint.platformnotsupported.cs b/mcs/class/System/System.Net/ServicePoint.platformnotsupported.cs
new file mode 100644 (file)
index 0000000..d744a55
--- /dev/null
@@ -0,0 +1,127 @@
+//
+// ServicePoint.cs
+//
+// Author:
+//       Rolf Bjarne Kvinge <rolf@xamarin.com>
+//
+// Copyright (c) 2016 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.Net.Sockets;
+using System.Security.Cryptography.X509Certificates;
+
+namespace System.Net
+{
+       public class ServicePoint
+       {
+               const string EXCEPTION_MESSAGE = "System.Net.ServicePoint is not supported on the current platform.";
+
+               ServicePoint () {}
+
+               public Uri Address {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               static Exception GetMustImplement ()
+               {
+                       return new NotImplementedException ();
+               }
+
+               public BindIPEndPoint BindIPEndPointDelegate
+               {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public int ConnectionLeaseTimeout {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public int ConnectionLimit {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public string ConnectionName {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public int CurrentConnections {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public DateTime IdleSince {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public int MaxIdleTime {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public virtual Version ProtocolVersion {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public int ReceiveBufferSize {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool SupportsPipelining {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool Expect100Continue {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public bool UseNagleAlgorithm {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public void SetTcpKeepAlive (bool enabled, int keepAliveTime, int keepAliveInterval)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public bool CloseConnectionGroup (string connectionGroupName)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public  X509Certificate Certificate {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public  X509Certificate ClientCertificate {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               // For reference source
+               internal Socket GetConnection(PooledStream PooledStream, object owner, bool async, out IPAddress address, ref Socket abortSocket, ref Socket abortSocket6)
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+}
index 17308253af502c5f6d2c134ba11acb2a0e4be2c8..d379526e80b9cb0510bd1619ad782d4d339d5fa3 100644 (file)
@@ -256,6 +256,12 @@ namespace System.Net
                        }
                }
 
+               [MonoTODO]
+               public static bool ReusePort {
+                       get { return false; }
+                       set { throw new NotImplementedException (); }
+               }
+
                public static SecurityProtocolType SecurityProtocol {
                        get { return _securityProtocol; }
                        set { _securityProtocol = value; }
@@ -280,6 +286,13 @@ namespace System.Net
                        }
                }
 
+               [MonoTODO ("Always returns EncryptionPolicy.RequireEncryption.")]
+               public static EncryptionPolicy EncryptionPolicy {
+                       get {
+                               return EncryptionPolicy.RequireEncryption;
+                       }
+               }
+
                public static bool Expect100Continue {
                        get { return expectContinue; }
                        set { expectContinue = value; }
diff --git a/mcs/class/System/System.Net/ServicePointManager.platformnotsupported.cs b/mcs/class/System/System.Net/ServicePointManager.platformnotsupported.cs
new file mode 100644 (file)
index 0000000..49c02e5
--- /dev/null
@@ -0,0 +1,129 @@
+//
+// ServicePointManager.cs
+//
+// Author:
+//       Rolf Bjarne Kvinge <rolf@xamarin.com>
+//
+// Copyright (c) 2016 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.Net.Security;
+
+namespace System.Net
+{
+       public partial class ServicePointManager {
+               const string EXCEPTION_MESSAGE = "System.Net.ServicePointManager is not supported on the current platform.";
+
+               public const int DefaultNonPersistentConnectionLimit = 4;
+#if MOBILE
+               public const int DefaultPersistentConnectionLimit = 10;
+#else
+               public const int DefaultPersistentConnectionLimit = 2;
+#endif
+
+               private ServicePointManager ()
+               {
+               }
+
+               public static ICertificatePolicy CertificatePolicy {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public static bool CheckCertificateRevocationList {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public static int DefaultConnectionLimit {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public static int DnsRefreshTimeout {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public static bool EnableDnsRoundRobin {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public static int MaxServicePointIdleTime {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public static int MaxServicePoints {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public static bool ReusePort {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public static SecurityProtocolType SecurityProtocol {
+                       get;
+                       set;
+               } = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
+
+               public static RemoteCertificateValidationCallback ServerCertificateValidationCallback {
+                       get;
+                       set;
+               }
+
+               public static EncryptionPolicy EncryptionPolicy {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public static bool Expect100Continue {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public static bool UseNagleAlgorithm {
+                       get { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+                       set { throw new PlatformNotSupportedException (EXCEPTION_MESSAGE); }
+               }
+
+               public static void SetTcpKeepAlive (bool enabled, int keepAliveTime, int keepAliveInterval)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public static ServicePoint FindServicePoint (Uri address)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public static ServicePoint FindServicePoint (string uriString, IWebProxy proxy)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+
+               public static ServicePoint FindServicePoint (Uri address, IWebProxy proxy)
+               {
+                       throw new PlatformNotSupportedException (EXCEPTION_MESSAGE);
+               }
+       }
+}
index c1bd5271adf78ba7dbb25aac7638d8cb7a676378..0a36e21004943427b937884ef9993d703c7a2c9c 100644 (file)
@@ -83,7 +83,6 @@ namespace System.Net
                HttpWebRequest connect_request;
 
                Exception connect_exception;
-               static object classLock = new object ();
                MonoTlsStream tlsStream;
 
 #if MONOTOUCH && !MONOTOUCH_TV && !MONOTOUCH_WATCH
@@ -257,14 +256,16 @@ namespace System.Net
                                        connect_request.Credentials = creds;
                                }
 
-                               for (int i = 0; i < challenge.Length; i++) {
-                                       var auth = AuthenticationManager.Authenticate (challenge [i], connect_request, creds);
-                                       if (auth == null)
-                                               continue;
-                                       ntlm = (auth.ModuleAuthenticationType == "NTLM");
-                                       sb.Append ("\r\nProxy-Authorization: ");
-                                       sb.Append (auth.Message);
-                                       break;
+                               if (creds != null) {
+                                       for (int i = 0; i < challenge.Length; i++) {
+                                               var auth = AuthenticationManager.Authenticate (challenge [i], connect_request, creds);
+                                               if (auth == null)
+                                                       continue;
+                                               ntlm = (auth.ModuleAuthenticationType == "NTLM");
+                                               sb.Append ("\r\nProxy-Authorization: ");
+                                               sb.Append (auth.Message);
+                                               break;
+                                       }
                                }
                        }
 
@@ -292,11 +293,14 @@ namespace System.Net
                                }
 
                                Data.StatusCode = status;
-                               Data.Challenge = result.GetValues ("Proxy-Authentic");
+                               Data.Challenge = result.GetValues ("Proxy-Authenticate");
+                               Data.Headers = result;
                                return false;
-                       } else if (status != 200) {
-                               string msg = String.Format ("The remote server returned a {0} status code.", status);
-                               HandleError (WebExceptionStatus.SecureChannelFailure, null, msg);
+                       }
+
+                       if (status != 200) {
+                               Data.StatusCode = status;
+                               Data.Headers = result;
                                return false;
                        }
 
@@ -368,6 +372,9 @@ namespace System.Net
                                        }
 
                                        status = (int)UInt32.Parse (parts [1]);
+                                       if (parts.Length >= 3)
+                                               Data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
+
                                        gotStatus = true;
                                }
                        }
@@ -738,7 +745,11 @@ namespace System.Net
                                Exception cnc_exc = connect_exception;
                                if (cnc_exc == null && (Data.StatusCode == 401 || Data.StatusCode == 407)) {
                                        st = WebExceptionStatus.ProtocolError;
-                                       cnc_exc = new WebException (Data.StatusCode == 407 ? "(407) Proxy Authentication Required" : "(401) Unauthorized" , st);
+                                       if (Data.Headers == null)
+                                               Data.Headers = new WebHeaderCollection ();
+
+                                       var webResponse = new HttpWebResponse (sPoint.Address, "CONNECT", Data, null);
+                                       cnc_exc = new WebException (Data.StatusCode == 407 ? "(407) Proxy Authentication Required" : "(401) Unauthorized", null, st, webResponse);
                                }
                        
                                connect_exception = null;
diff --git a/mcs/class/System/System.Security.Authentication.ExtendedProtection/ServiceNameCollection.cs b/mcs/class/System/System.Security.Authentication.ExtendedProtection/ServiceNameCollection.cs
deleted file mode 100644 (file)
index 3fa9b3f..0000000
+++ /dev/null
@@ -1,60 +0,0 @@
-//
-// ServiceNameCollection.cs
-//
-// Authors:
-//      Atsushi Enomoto  <atsushi@ximian.com>
-//
-
-//
-// Copyright (C) 2010 Novell, Inc (http://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;
-using System.Collections;
-
-namespace System.Security.Authentication.ExtendedProtection
-{
-       [MonoTODO]
-       [Serializable]
-       public class ServiceNameCollection : ReadOnlyCollectionBase
-       {
-               public ServiceNameCollection (ICollection items)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public ServiceNameCollection Merge (IEnumerable serviceNames)
-               {
-                       throw new NotImplementedException ();
-               }
-               
-               public ServiceNameCollection Merge (string serviceName)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public bool Contains (string searchServiceName)
-               {
-                       throw new NotImplementedException ();
-               }
-       }
-}
-
index 98f5dfc4ab5ff882f16b55cab3d03f937dde8611..b26263a75a5a788c510fce489e1f4708a4926d56 100644 (file)
 //
 #if SECURITY_DEP
 
-using XX509CertificateCollection = System.Security.Cryptography.X509Certificates.X509CertificateCollection;
-
 using System;
 using System.Runtime.InteropServices;
+using System.Security.Cryptography.X509Certificates;
 
 namespace System.Security.Cryptography.X509Certificates {
 
@@ -107,7 +106,7 @@ namespace System.Security.Cryptography.X509Certificates {
                        return handle;
                }
                
-               public static SecTrustResult TrustEvaluateSsl (XX509CertificateCollection certificates, XX509CertificateCollection anchors, string host)
+               public static SecTrustResult TrustEvaluateSsl (X509CertificateCollection certificates, X509CertificateCollection anchors, string host)
                {
                        if (certificates == null)
                                return SecTrustResult.Deny;
@@ -119,7 +118,7 @@ namespace System.Security.Cryptography.X509Certificates {
                        }
                }
 
-               static SecTrustResult _TrustEvaluateSsl (XX509CertificateCollection certificates, XX509CertificateCollection anchors, string hostName)
+               static SecTrustResult _TrustEvaluateSsl (X509CertificateCollection certificates, X509CertificateCollection anchors, string hostName)
                {
                        int certCount = certificates.Count;
                        int anchorCount = anchors != null ? anchors.Count : 0;
index 795f0d04b21acfabb51a09db288cfa3ccfecd274..78a87057ce7e65b89198e52ddbd940bd4c514246 100644 (file)
@@ -124,7 +124,6 @@ namespace System.Security.Cryptography.X509Certificates {
                }
 
                internal X500DistinguishedName (byte[] encoded, byte[] canonEncoding, string name)
-                       : this (encoded)
                {
                        this.canonEncoding = canonEncoding;
                        this.name = name;
@@ -234,7 +233,7 @@ namespace System.Security.Cryptography.X509Certificates {
                                if (name1.canonEncoding.Length != name2.canonEncoding.Length)
                                        return false;
                                for (int i = 0; i < name1.canonEncoding.Length; i++) {
-                                       if (name1.canonEncoding[i] != name2.canonEncoding[2])
+                                       if (name1.canonEncoding[i] != name2.canonEncoding[i])
                                                return false;
                                }
                                return true;
index 29decab439faa252aeb371c167e754684e7f9ec9..ef10413f59722853150a79935cca076d7e1fbcae 100644 (file)
@@ -45,6 +45,7 @@ using MX = Mono.Security.X509;
 using System.IO;
 using System.Text;
 using System.Collections;
+using System.Runtime.Serialization;
 
 namespace System.Security.Cryptography.X509Certificates {
 
@@ -134,6 +135,10 @@ namespace System.Security.Cryptography.X509Certificates {
                {
                }
 
+               protected X509Certificate2 (SerializationInfo info, StreamingContext context) : base (info, context)
+               {
+               }
+
                internal X509Certificate2 (X509Certificate2Impl impl)
                        : base (impl)
                {
@@ -394,13 +399,10 @@ namespace System.Security.Cryptography.X509Certificates {
                // internal stuff because X509Certificate2 isn't complete enough
                // (maybe X509Certificate3 will be better?)
 
-               [Obsolete ("KILL")]
+               [MonoTODO ("See comment in X509Helper2.GetMonoCertificate().")]
                internal MX.X509Certificate MonoCertificate {
                        get {
-                               var monoImpl = Impl as X509Certificate2ImplMono;
-                               if (monoImpl == null)
-                                       throw new NotSupportedException ();
-                               return monoImpl.MonoCertificate;
+                               return X509Helper2.GetMonoCertificate (this);
                        }
                }
 
index 234d0907f2dbcaedf74a722b331e2083aaebf8af..38797d55fcee583b75ca47f09158b8dea078a3dd 100644 (file)
@@ -71,6 +71,10 @@ namespace System.Security.Cryptography.X509Certificates
                        get;
                }
 
+               internal abstract X509Certificate2Impl FallbackImpl {
+                       get;
+               }
+
                public abstract string GetNameInfo (X509NameType nameType, bool forIssuer);
 
                public abstract void Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags);
index cdc14c49eb13e2d2479c961ce8e9a4a4243ce484..ff2449906de7c2f8a45bb405397aed669f6e557e 100644 (file)
@@ -52,7 +52,6 @@ namespace System.Security.Cryptography.X509Certificates
        {
                bool _archived;
                X509ExtensionCollection _extensions;
-               string _serial;
                PublicKey _publicKey;
                X500DistinguishedName issuer_name;
                X500DistinguishedName subject_name;
@@ -483,6 +482,7 @@ namespace System.Security.Cryptography.X509Certificates
                [MonoTODO ("missing KeyStorageFlags support")]
                public override void Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
                {
+                       Reset ();
                        MX.X509Certificate cert = null;
                        if (password == null) {
                                try {
@@ -558,7 +558,6 @@ namespace System.Security.Cryptography.X509Certificates
                        _cert = null;
                        _archived = false;
                        _extensions = null;
-                       _serial = null;
                        _publicKey = null;
                        issuer_name = null;
                        subject_name = null;
@@ -718,6 +717,10 @@ namespace System.Security.Cryptography.X509Certificates
                internal MX.X509Certificate MonoCertificate {
                        get { return _cert; }
                }
+
+               internal override X509Certificate2Impl FallbackImpl {
+                       get { return this; }
+               }
        }
 }
 
index 0ea1c8e9b06ab45d4c27b716de5b7fcdea4c1e4b..a3323c8ef0c4b7d15a57dc0220289d54a6c58296 100644 (file)
@@ -47,8 +47,6 @@ namespace System.Security.Cryptography.X509Certificates {
 
                X509ChainImpl impl;
 
-               static X509ChainStatus[] Empty = new X509ChainStatus [0];
-
                internal X509ChainImpl Impl {
                        get {
                                X509Helper2.ThrowIfContextInvalid (impl);
index 1dc234575b86a3cb6806c7b471f8d0ba8ec9f694..2fcdd982f33366e8b1b163a1aa178947232fbd74 100644 (file)
@@ -91,6 +91,9 @@ namespace System.Security.Cryptography.X509Certificates {
                                }
                                return store2;
                        }
+                       internal set {
+                               store2 = value;
+                       }
                }
 
                public X509RevocationFlag RevocationFlag {
index 2a9163a346f89ae143e7477b9215c67659f5e875..9bbe99f86314cd4eb7e1eafbb667171e3133e079 100644 (file)
@@ -33,14 +33,57 @@ extern alias MonoSecurity;
 
 #if MONO_SECURITY_ALIAS
 using MonoSecurity::Mono.Security.Interface;
+using MX = MonoSecurity::Mono.Security.X509;
 #else
+#if !FEATURE_NO_BSD_SOCKETS
 using Mono.Security.Interface;
 #endif
+using MX = Mono.Security.X509;
+#endif
+
+#if !FEATURE_NO_BSD_SOCKETS
+using Mono.Btls;
+#endif
+#endif
+
+using System.IO;
+using System.Text;
 
 namespace System.Security.Cryptography.X509Certificates
 {
        internal static class X509Helper2
        {
+               internal static long GetSubjectNameHash (X509Certificate certificate)
+               {
+                       return GetSubjectNameHash (certificate.Impl);
+               }
+
+               internal static long GetSubjectNameHash (X509CertificateImpl impl)
+               {
+#if SECURITY_DEP
+                       using (var x509 = GetNativeInstance (impl))
+                               return GetSubjectNameHash (x509);
+#else
+                       throw new NotSupportedException ();
+#endif
+               }
+
+               internal static void ExportAsPEM (X509Certificate certificate, Stream stream, bool includeHumanReadableForm)
+               {
+                       ExportAsPEM (certificate.Impl, stream, includeHumanReadableForm);
+               }
+
+               internal static void ExportAsPEM (X509CertificateImpl impl, Stream stream, bool includeHumanReadableForm)
+               {
+#if SECURITY_DEP
+                       using (var x509 = GetNativeInstance (impl))
+                               ExportAsPEM (x509, stream, includeHumanReadableForm);
+#else
+                       throw new NotSupportedException ();
+#endif
+               }
+
+#if SECURITY_DEP
                internal static void Initialize ()
                {
                        X509Helper.InstallNativeHelper (new MyNativeHelper ());
@@ -51,32 +94,90 @@ namespace System.Security.Cryptography.X509Certificates
                        X509Helper.ThrowIfContextInvalid (impl);
                }
 
-               internal static X509Certificate2Impl Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
+#if FEATURE_NO_BSD_SOCKETS
+               static X509Certificate GetNativeInstance (X509CertificateImpl impl)
+               {
+                       throw new PlatformNotSupportedException ();
+               }
+#else
+               static MonoBtlsX509 GetNativeInstance (X509CertificateImpl impl)
                {
-                       var provider = MonoTlsProviderFactory.GetProvider ();
-                       if (provider.HasNativeCertificates) {
-                               var impl = provider.GetNativeCertificate (rawData, password, keyStorageFlags);
-                               return impl;
-                       } else {
-                               var impl = new X509Certificate2ImplMono ();
-                               impl.Import (rawData, password, keyStorageFlags);
-                               return impl;
+                       ThrowIfContextInvalid (impl);
+                       var btlsImpl = impl as X509CertificateImplBtls;
+                       if (btlsImpl != null)
+                               return btlsImpl.X509.Copy ();
+                       else
+                               return MonoBtlsX509.LoadFromData (impl.GetRawCertData (), MonoBtlsX509Format.DER);
+               }
+
+               internal static long GetSubjectNameHash (MonoBtlsX509 x509)
+               {
+                       using (var subject = x509.GetSubjectName ())
+                               return subject.GetHash ();
+               }
+
+               internal static void ExportAsPEM (MonoBtlsX509 x509, Stream stream, bool includeHumanReadableForm)
+               {
+                       using (var bio = MonoBtlsBio.CreateMonoStream (stream)) {
+                               x509.ExportAsPEM (bio, includeHumanReadableForm);
+                       }
+               }
+#endif // !FEATURE_NO_BSD_SOCKETS
+
+               internal static X509Certificate2Impl Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags, bool disableProvider = false)
+               {
+#if !FEATURE_NO_BSD_SOCKETS
+                       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 ();
+                       impl2.Import (rawData, password, keyStorageFlags);
+                       return impl2;
                }
 
-               internal static X509Certificate2Impl Import (X509Certificate cert)
+               internal static X509Certificate2Impl Import (X509Certificate cert, bool disableProvider = false)
                {
-                       var provider = MonoTlsProviderFactory.GetProvider ();
-                       if (provider.HasNativeCertificates) {
-                               var impl = provider.GetNativeCertificate (cert);
-                               return impl;
+#if !FEATURE_NO_BSD_SOCKETS
+                       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;
                        if (impl2 != null)
                                return (X509Certificate2Impl)impl2.Clone ();
                        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);
@@ -111,6 +212,6 @@ namespace System.Security.Cryptography.X509Certificates
                                return X509Helper2.Import (cert);
                        }
                }
+#endif
        }
 }
-#endif
index abb1faf58183a6b9e62820befc3bc07cf497b3aa..a2128834812f8a7f1b346c9508abb42722192359 100644 (file)
@@ -148,11 +148,9 @@ System.Diagnostics/PerformanceCounterPermissionEntryCollection.cs
 System.Diagnostics/PerformanceCounterPermissionEntry.cs
 System.Diagnostics/PerformanceCounterType.cs
 System.Diagnostics/Process.cs
-System.Diagnostics/ProcessModuleCollection.cs
 System.Diagnostics/ProcessModule.cs
 System.Diagnostics/ProcessPriorityClass.cs
 System.Diagnostics/ProcessStartInfo.cs
-System.Diagnostics/ProcessThreadCollection.cs
 System.Diagnostics/ProcessThread.cs
 System.Diagnostics/ProcessWindowStyle.cs
 System.Diagnostics/Stopwatch.cs
@@ -162,8 +160,8 @@ System.Diagnostics/ThreadWaitReason.cs
 System.Diagnostics/TraceImpl.cs
 System.Diagnostics/TraceSourceInfo.cs
 System.Diagnostics/Win32EventLog.cs
-System.Diagnostics.CodeAnalysis/ExcludeFromCodeCoverageAttribute.cs
 System/Platform.cs
+System/MonoToolsLocator.cs
 System.IO.Compression/CompressionLevel.cs
 System.IO.Compression/CompressionMode.cs
 System.IO.Compression/DeflateStream.cs
@@ -271,6 +269,7 @@ System.Net/HttpListener.cs
 System.Net/HttpListenerPrefixCollection.cs
 System.Net/HttpListenerRequest.cs
 System.Net/HttpListenerResponse.cs
+System.Net/HttpListenerResponseHelper.cs
 System.Net/HttpListenerTimeoutManager.cs
 System.Net/HttpRequestCreator.cs
 System.Net/HttpStreamAsyncResult.cs
@@ -376,35 +375,11 @@ System.Net/ServicePointManager.extra.cs
 System.Net/SimpleAsyncResult.cs
 System.Net/SocketPermissionAttribute.cs
 System.Net/SocketPermission.cs
-../referencesource/System/net/System/Net/Sockets/AddressFamily.cs
-../referencesource/System/net/System/Net/Sockets/IOControlCode.cs
-../referencesource/System/net/System/Net/Sockets/IPPacketInformation.cs
-../referencesource/System/net/System/Net/Sockets/LingerOption.cs
-../referencesource/System/net/System/Net/Sockets/MulticastOption.cs
-../referencesource/System/net/System/Net/Sockets/ProtocolFamily.cs
-../referencesource/System/net/System/Net/Sockets/ProtocolType.cs
 System.Net.Sockets/SafeSocketHandle.cs
-../referencesource/System/net/System/Net/Sockets/SelectMode.cs
-System.Net.Sockets/SendPacketsElement.cs
 System.Net.Sockets/Socket.cs
 System.Net.Sockets/SocketAsyncEventArgs.cs
-System.Net.Sockets/SocketAsyncOperation.cs
 System.Net.Sockets/SocketAsyncResult.cs
-../referencesource/System/net/System/Net/Sockets/SocketErrors.cs
-../referencesource/System/net/System/Net/SocketException.cs
-../referencesource/System/net/System/Net/Sockets/SocketFlags.cs
-../referencesource/System/net/System/Net/Sockets/SocketInformation.cs
-../referencesource/System/net/System/Net/Sockets/SocketInformationOptions.cs
 System.Net.Sockets/SocketOperation.cs
-../referencesource/System/net/System/Net/Sockets/SocketOptionLevel.cs
-../referencesource/System/net/System/Net/Sockets/SocketOptionName.cs
-../referencesource/System/net/System/Net/Sockets/SocketShutdown.cs
-../referencesource/System/net/System/Net/Sockets/SocketType.cs
-System.Net.Sockets/TcpClient.cs
-System.Net.Sockets/TcpListener.cs
-../referencesource/System/net/System/Net/Sockets/TransmitFileFlags.cs
-System.Net.Sockets/UdpClient.cs
-../referencesource/System/net/System/Net/Sockets/UdpReceiveResult.cs
 System.Net/WebAsyncResult.cs
 System.Net/WebConnection.cs
 System.Net/WebConnectionData.cs
@@ -437,7 +412,6 @@ System.Security.Authentication.ExtendedProtection/ExtendedProtectionPolicy.cs
 System.Security.Authentication.ExtendedProtection/ExtendedProtectionPolicyTypeConverter.cs
 System.Security.Authentication.ExtendedProtection/PolicyEnforcement.cs
 System.Security.Authentication.ExtendedProtection/ProtectionScenario.cs
-System.Security.Authentication.ExtendedProtection/ServiceNameCollection.cs
 System.Security.Authentication.ExtendedProtection.Configuration/ConfigUtil.cs
 System.Security.Authentication.ExtendedProtection.Configuration/ExtendedProtectionPolicyElement.cs
 System.Security.Authentication.ExtendedProtection.Configuration/ServiceNameElement.cs
@@ -539,6 +513,45 @@ System.Windows.Input/ICommand.cs
 
 System/IOSelector.cs
 
+Mono.Btls/MonoBtlsBio.cs
+Mono.Btls/MonoBtlsContext.cs
+Mono.Btls/MonoBtlsError.cs
+Mono.Btls/MonoBtlsException.cs
+Mono.Btls/MonoBtlsKey.cs
+Mono.Btls/MonoBtlsObject.cs
+Mono.Btls/MonoBtlsPkcs12.cs
+Mono.Btls/MonoBtlsProvider.cs
+Mono.Btls/MonoBtlsSsl.cs
+Mono.Btls/MonoBtlsSslCtx.cs
+Mono.Btls/MonoBtlsSslError.cs
+Mono.Btls/MonoBtlsStream.cs
+Mono.Btls/MonoBtlsUtils.cs
+Mono.Btls/MonoBtlsX509.cs
+Mono.Btls/MonoBtlsX509Chain.cs
+Mono.Btls/MonoBtlsX509Crl.cs
+Mono.Btls/MonoBtlsX509Error.cs
+Mono.Btls/MonoBtlsX509Exception.cs
+Mono.Btls/MonoBtlsX509FileType.cs
+Mono.Btls/MonoBtlsX509Format.cs
+Mono.Btls/MonoBtlsX509Lookup.cs
+Mono.Btls/MonoBtlsX509LookupMono.cs
+Mono.Btls/MonoBtlsX509LookupMonoCollection.cs
+Mono.Btls/MonoBtlsX509LookupType.cs
+Mono.Btls/MonoBtlsX509Name.cs
+Mono.Btls/MonoBtlsX509NameList.cs
+Mono.Btls/MonoBtlsX509NameEntryType.cs
+Mono.Btls/MonoBtlsX509Purpose.cs
+Mono.Btls/MonoBtlsX509Revoked.cs
+Mono.Btls/MonoBtlsX509Store.cs
+Mono.Btls/MonoBtlsX509StoreCtx.cs
+Mono.Btls/MonoBtlsX509StoreManager.cs
+Mono.Btls/MonoBtlsX509StoreType.cs
+Mono.Btls/MonoBtlsX509TrustKind.cs
+Mono.Btls/MonoBtlsX509VerifyFlags.cs
+Mono.Btls/MonoBtlsX509VerifyParam.cs
+Mono.Btls/X509CertificateImplBtls.cs
+Mono.Btls/X509ChainImplBtls.cs
+
 Mono.Net.Security/AsyncProtocolRequest.cs
 Mono.Net.Security/CallbackHelpers.cs
 Mono.Net.Security/ChainValidationHelper.cs
@@ -547,11 +560,10 @@ Mono.Net.Security/IMonoSslStream.cs
 Mono.Net.Security/LegacySslStream.cs
 Mono.Net.Security/MobileAuthenticatedStream.cs
 Mono.Net.Security/MobileTlsContext.cs
-Mono.Net.Security/MonoLegacyTlsProvider.cs
+Mono.Net.Security/LegacyTlsProvider.cs
 Mono.Net.Security/MonoSslStreamImpl.cs
 Mono.Net.Security/MonoSslStreamWrapper.cs
 Mono.Net.Security/MonoTlsProviderFactory.cs
-Mono.Net.Security/MonoTlsProviderImpl.cs
 Mono.Net.Security/MonoTlsProviderWrapper.cs
 Mono.Net.Security/MonoTlsStream.cs
 Mono.Net.Security/NoReflectionHelper.cs
@@ -563,7 +575,6 @@ ReferenceSources/BinaryCompatibility.cs
 ReferenceSources/ConfigurationManagerInternalFactory.cs
 ReferenceSources/CAPI.cs
 ReferenceSources/EnvironmentHelpers.cs
-ReferenceSources/Internal.cs
 ReferenceSources/HttpApi.cs
 ReferenceSources/HttpSysSettings.cs
 ReferenceSources/LocalAppContextSwitches.cs
@@ -577,14 +588,6 @@ ReferenceSources/SR2.cs
 ReferenceSources/SRCategoryAttribute.cs
 ReferenceSources/Win32Exception.cs
 
-ReferenceSources/SSPIConfiguration.cs
-ReferenceSources/SSPISafeHandles.cs
-ReferenceSources/SSPIWrapper.cs
-ReferenceSources/SslStream.cs
-ReferenceSources/_SecureChannel.cs
-ReferenceSources/_SslState.cs
-ReferenceSources/_SslStream.cs
-
 ../referencesource/System/misc/PrivilegedConfigurationManager.cs
 ../referencesource/System/regex/system/text/regularexpressions/Regex.cs
 ../referencesource/System/regex/system/text/regularexpressions/RegexBoyerMoore.cs
@@ -982,6 +985,7 @@ ReferenceSources/_SslStream.cs
 ../referencesource/System/net/System/Net/_ProxyChain.cs
 ../referencesource/System/net/System/Net/_ScatterGatherBuffers.cs
 ../referencesource/System/net/System/Net/_Semaphore.cs
+../referencesource/System/net/System/Net/_ServiceNameStore.cs
 ../referencesource/System/net/System/Net/_TimerThread.cs
 ../referencesource/System/net/System/Net/_WebProxyDataBuilder.cs
 ../referencesource/System/net/System/Net/AuthenticationScheme.cs
@@ -1024,6 +1028,7 @@ ReferenceSources/_SslStream.cs
 ../referencesource/System/net/System/Net/UnicodeEncodingConformance.cs
 ../referencesource/System/net/System/Net/ServicePointManager.cs
 ../referencesource/System/net/System/Net/SocketAddress.cs
+../referencesource/System/net/System/Net/SocketException.cs
 ../referencesource/System/net/System/Net/webclient.cs
 ../referencesource/System/net/System/Net/WebException.cs
 ../referencesource/System/net/System/Net/WebExceptionStatus.cs
@@ -1043,8 +1048,30 @@ ReferenceSources/_SslStream.cs
 
 ../referencesource/System/net/System/Net/Configuration/DefaultProxySection.cs
 
+../referencesource/System/net/System/Net/Sockets/AddressFamily.cs
+../referencesource/System/net/System/Net/Sockets/IOControlCode.cs
+../referencesource/System/net/System/Net/Sockets/IPPacketInformation.cs
 ../referencesource/System/net/System/Net/Sockets/IPProtectionLevel.cs
+../referencesource/System/net/System/Net/Sockets/LingerOption.cs
+../referencesource/System/net/System/Net/Sockets/MulticastOption.cs
 ../referencesource/System/net/System/Net/Sockets/NetworkStream.cs
+../referencesource/System/net/System/Net/Sockets/ProtocolFamily.cs
+../referencesource/System/net/System/Net/Sockets/ProtocolType.cs
+../referencesource/System/net/System/Net/Sockets/SelectMode.cs
+../referencesource/System/net/System/Net/Sockets/Socket.cs
+../referencesource/System/net/System/Net/Sockets/SocketErrors.cs
+../referencesource/System/net/System/Net/Sockets/SocketFlags.cs
+../referencesource/System/net/System/Net/Sockets/SocketInformation.cs
+../referencesource/System/net/System/Net/Sockets/SocketInformationOptions.cs
+../referencesource/System/net/System/Net/Sockets/SocketOptionLevel.cs
+../referencesource/System/net/System/Net/Sockets/SocketOptionName.cs
+../referencesource/System/net/System/Net/Sockets/SocketShutdown.cs
+../referencesource/System/net/System/Net/Sockets/SocketType.cs
+../referencesource/System/net/System/Net/Sockets/TCPClient.cs
+../referencesource/System/net/System/Net/Sockets/TCPListener.cs
+../referencesource/System/net/System/Net/Sockets/TransmitFileFlags.cs
+../referencesource/System/net/System/Net/Sockets/UdpReceiveResult.cs
+../referencesource/System/net/System/Net/Sockets/UDPClient.cs
 
 ../referencesource/System/net/System/Net/NetworkInformation/DuplicateAddressDetectionState.cs
 ../referencesource/System/net/System/Net/NetworkInformation/GatewayIPAddressInformation.cs
@@ -1078,7 +1105,6 @@ ReferenceSources/_SslStream.cs
 ../referencesource/System/net/System/Net/NetworkInformation/SystemGatewayIPAddressInformation.cs
 ../referencesource/System/net/System/Net/NetworkInformation/SystemIPAddressInformation.cs
 ../referencesource/System/net/System/Net/NetworkInformation/SystemMulticastIPAddressInformation.cs
-../referencesource/System/net/System/Net/NetworkInformation/SystemUnicastIPAddressInformation.cs
 ../referencesource/System/net/System/Net/NetworkInformation/SystemTcpConnection.cs
 ../referencesource/System/net/System/Net/NetworkInformation/TcpConnection.cs
 ../referencesource/System/net/System/Net/NetworkInformation/TcpState.cs
@@ -1092,6 +1118,8 @@ ReferenceSources/_SslStream.cs
 
 ../referencesource/System/sys/system/IO/ports/InternalResources.cs
 
+../referencesource/System/sys/system/Diagnostics/CodeAnalysis/ExcludeFromCodeCoverageAttribute.cs
+
 ../referencesource/System/sys/system/runtime/interopservices/DefaultParameterValueAttribute.cs
 ../referencesource/System/sys/system/runtime/interopservices/handlecollector.cs
 
@@ -1103,6 +1131,7 @@ ReferenceSources/_SslStream.cs
 ../referencesource/System/sys/system/windows/markup/ValueSerializerAttribute.cs
 
 ../referencesource/System/security/system/security/Authentication/ExtendedProtection/TokenBinding.cs
+../referencesource/System/security/system/security/Authentication/ExtendedProtection/ServiceNameCollection.cs
 
 ../referencesource/System/security/system/security/cryptography/oid.cs
 
@@ -1110,6 +1139,9 @@ ReferenceSources/_SslStream.cs
 
 ../referencesource/System/security/system/security/permissions/typedescriptorpermission.cs
 
+../referencesource/System/services/monitoring/system/diagnosticts/ProcessModuleCollection.cs
+../referencesource/System/services/monitoring/system/diagnosticts/ProcessThreadCollection.cs
+
 ../referencesource/System/services/timers/system/timers/ElapsedEventHandler.cs
 ../referencesource/System/services/timers/system/timers/Timer.cs
 ../referencesource/System/services/timers/system/timers/TimersDescriptionAttribute.cs
index 1f010668d722f454e024aecb54db05e68905f3a6..5d59fa64718a600b4d0cb4d16a0a3ae9a3893ad0 100644 (file)
@@ -33,6 +33,7 @@ using System.Net.Security;
 using System.Security.Cryptography.X509Certificates;
 #if SECURITY_DEP
 using MSX = Mono.Security.X509;
+using Mono.Btls;
 #endif
 
 namespace System {
@@ -43,6 +44,7 @@ namespace System {
                
 #if SECURITY_DEP
                static readonly Converter<List <byte[]>, bool> trustEvaluateSsl;
+               static readonly Func<long, bool, byte[]> certStoreLookup;
 #endif  // SECURITY_DEP
                static readonly Func<IWebProxy> getDefaultProxy;
                static readonly GetInterfaceAddressesDelegate getInterfaceAddresses;
@@ -58,6 +60,12 @@ namespace System {
                                                        "TrustEvaluateSsl",
                                                        ignoreCase:false,
                                                        throwOnBindFailure:true);
+                       certStoreLookup = (Func<long, bool, byte[]>)
+                               Delegate.CreateDelegate (typeof (Func<long, bool, byte[]>),
+                                                       t,
+                                                       "CertStoreLookup",
+                                                       ignoreCase:false,
+                                                       throwOnBindFailure:true);
 #endif  // SECURITY_DEP
                        getDefaultProxy = (Func<IWebProxy>)Delegate.CreateDelegate (
                                typeof (Func<IWebProxy>), t, "GetDefaultProxy",
@@ -83,6 +91,24 @@ namespace System {
                                certsRawData.Add (cert.GetRawCertData ());
                        return trustEvaluateSsl (certsRawData);
                }
+
+               internal static MonoBtlsX509 CertStoreLookup (MonoBtlsX509Name name)
+               {
+                       var hash = name.GetHash ();
+                       var hashOld = name.GetHashOld ();
+                       var result = certStoreLookup (hash, false);
+                       if (result == null)
+                               result = certStoreLookup (hashOld, false);
+                       if (result == null)
+                               result = certStoreLookup (hash, true);
+                       if (result == null)
+                               result = certStoreLookup (hashOld, true);
+
+                       if (result == null)
+                               return null;
+
+                       return MonoBtlsX509.LoadFromData (result, MonoBtlsX509Format.DER);
+               }
 #endif  // SECURITY_DEP
 
                internal static IWebProxy GetDefaultProxy ()
diff --git a/mcs/class/System/System/MonoToolsLocator.cs b/mcs/class/System/System/MonoToolsLocator.cs
new file mode 100755 (executable)
index 0000000..5443395
--- /dev/null
@@ -0,0 +1,96 @@
+#if !MOBILE
+
+using System.Diagnostics;
+using System.IO;
+using System.Reflection;
+using System.Runtime.InteropServices;
+using System.Text;
+
+namespace System {
+
+       static class MonoToolsLocator
+       {
+               public static readonly string Mono;
+               public static readonly string CSharpCompiler;
+               public static readonly string VBCompiler;
+               public static readonly string AssemblyLinker;
+
+               // TODO: Should be lazy
+               static MonoToolsLocator ()
+               {
+                       var gac = typeof (Environment).GetProperty ("GacPath", BindingFlags.Static | BindingFlags.NonPublic);
+                       var getGacMethod = gac.GetGetMethod (true);
+                       var GacPath = Path.GetDirectoryName ((string) getGacMethod.Invoke (null, null));
+
+                       if (Path.DirectorySeparatorChar == '\\') {
+                               StringBuilder moduleName = new StringBuilder (1024);
+                               GetModuleFileName (IntPtr.Zero, moduleName, moduleName.Capacity);
+                               string processExe = moduleName.ToString ();
+                               string fileName = Path.GetFileName (processExe);
+                               if (fileName.StartsWith ("mono") && fileName.EndsWith (".exe"))
+                                       Mono = processExe;
+
+                               if (!File.Exists (Mono))
+                                       Mono = Path.Combine (
+                                               Path.GetDirectoryName (
+                                                       Path.GetDirectoryName (GacPath)),
+                                               "bin\\mono.exe");
+
+                               if (!File.Exists (Mono))
+                                       Mono = Path.Combine (
+                                               Path.GetDirectoryName (
+                                                       Path.GetDirectoryName (
+                                                               Path.GetDirectoryName (GacPath))),
+                                               "mono\\mini\\mono.exe");
+
+                               //if (!File.Exists (Mono))
+                               //      throw new FileNotFoundException ("Windows mono path not found: " + Mono);
+
+                               CSharpCompiler = Path.Combine (GacPath, "4.5\\mcs.exe");
+                               if (!File.Exists (CSharpCompiler))
+                                       CSharpCompiler = Path.Combine (Path.GetDirectoryName (GacPath), "lib\\build\\mcs.exe");
+
+                               //if (!File.Exists (CSharpCompiler))
+                               //      throw new FileNotFoundException ("C# compiler not found at " + CSharpCompiler);
+
+                               VBCompiler = Path.Combine (GacPath,  "4.5\\vbnc.exe");
+                               AssemblyLinker = Path.Combine (GacPath, "4.5\\al.exe");
+
+                               if (!File.Exists (AssemblyLinker)) {
+                                       AssemblyLinker = Path.Combine (Path.GetDirectoryName (GacPath), "lib\\net_4_x\\al.exe");
+                               //      if (!File.Exists (AssemblyLinker))
+                               //              throw new FileNotFoundException ("Windows al path not found: " + AssemblyLinker);
+                               }
+                       } else {
+                               Mono = Path.Combine (GacPath, "bin", "mono");
+                               if (!File.Exists (Mono))
+                                       Mono = "mono";
+
+                               var mscorlibPath = new Uri (typeof (object).Assembly.CodeBase).LocalPath;
+                               CSharpCompiler = Path.GetFullPath (Path.Combine (mscorlibPath, "..", "..", "..", "..", "bin", "mcs"));
+                               if (!File.Exists (CSharpCompiler))
+                                       CSharpCompiler = "mcs";
+
+                               VBCompiler = Path.GetFullPath (Path.Combine (mscorlibPath, "..", "..", "..", "..", "bin", "vbnc"));
+                               if (!File.Exists (VBCompiler))
+                                       VBCompiler = "vbnc";
+
+                               AssemblyLinker = Path.GetFullPath (Path.Combine (mscorlibPath, "..", "..", "..", "..", "bin", "al"));
+                               if (!File.Exists (AssemblyLinker))
+                                       AssemblyLinker = "al";
+                       }
+               }
+
+               // Due to an issue with shadow copying  and app domains in mono, we cannot currently use 
+               // Process.GetCurrentProcess ().MainModule.FileName (which would give the same result)
+               // when running in an AppDomain (eg System.Web hosts).
+               //
+               // Using native Windows API to get current process filename. This will only
+               // be called when running on Windows. 
+               [DllImport ("kernel32.dll")]
+               static extern uint GetModuleFileName ([In] IntPtr hModule, [Out] StringBuilder lpFilename, [In] int nSize);
+
+       }
+}
+
+#endif
index 277604287550fde13168d44d19ec29833961db90..20a93a732b6f1d1c3dc00368a5e0e0bc846db7c9 100644 (file)
@@ -284,7 +284,9 @@ namespace MonoTests.System.Diagnostics
                                Assert.AreEqual (-2147467259, ex.ErrorCode, "#3");
                                Assert.IsNull (ex.InnerException, "#4");
                                Assert.IsNotNull (ex.Message, "#5");
-                               Assert.AreEqual (2, ex.NativeErrorCode, "#6");
+                               // TODO: On windows we get ACCESS_DENIED (5) instead of FILE_NOT_FOUND (2) and .NET
+                               // gives ERROR_INVALID_PARAMETER (87). See https://bugzilla.xamarin.com/show_bug.cgi?id=44514
+                               Assert.IsTrue (ex.NativeErrorCode == 2 || ex.NativeErrorCode == 5 || ex.NativeErrorCode == 87, "#6");
                        }
                }
 
@@ -440,7 +442,9 @@ namespace MonoTests.System.Diagnostics
                                Assert.AreEqual (-2147467259, ex.ErrorCode, "#3");
                                Assert.IsNull (ex.InnerException, "#4");
                                Assert.IsNotNull (ex.Message, "#5");
-                               Assert.AreEqual (2, ex.NativeErrorCode, "#6");
+                               // TODO: On windows we get ACCESS_DENIED (5) instead of FILE_NOT_FOUND (2) and .NET
+                               // gives ERROR_INVALID_PARAMETER (87). See https://bugzilla.xamarin.com/show_bug.cgi?id=44514
+                               Assert.IsTrue (ex.NativeErrorCode == 2 || ex.NativeErrorCode == 5 || ex.NativeErrorCode == 87, "#6");
                        }
                }
 
@@ -892,8 +896,11 @@ namespace MonoTests.System.Diagnostics
                                path = "/bin/cat";
 #endif
                                return new ProcessStartInfo (path);
-                       } else
-                               return new ProcessStartInfo ("type");
+                       } else {
+                               var psi = new ProcessStartInfo ("findstr");
+                               psi.Arguments = "\"^\"";
+                               return psi;
+                       }
                }
 #endif // MONO_FEATURE_PROCESS_START
 
@@ -1018,7 +1025,7 @@ namespace MonoTests.System.Diagnostics
 
                                StringBuilder sb = new StringBuilder ();
                                sb.AppendFormat ("Could not found: {0} {1}\n", name.Name, name.Version);
-                               sb.AppendLine ("Looked in assemblies:");
+                               sb.AppendLine ("Looked in modules:");
 
                                foreach (var o in modules) {
                                        var m = (ProcessModule) o;
index 909beb4988c8873dc7a6cd85d2b383443f1b290a..d3a39e413151fd52b8ed138b38e504c54e79c758 100644 (file)
@@ -16,16 +16,15 @@ using System.Threading;
 namespace MonoTests.System.Net.Mail
 {
        [TestFixture]
-       [Category ("RequiresBSDSockets")]
        public class SmtpClientTest
        {
-               SmtpClient smtp;
+               SmtpClient _smtp;
+               SmtpClient smtp { get { return _smtp ?? (_smtp = new SmtpClient ()); } }
                string tempFolder;
                
                [SetUp]
                public void GetReady ()
                {
-                       smtp = new SmtpClient ();
                        tempFolder = Path.Combine (Path.GetTempPath (), this.GetType ().FullName);
                        if (Directory.Exists (tempFolder))
                                Directory.Delete (tempFolder, true);
@@ -35,17 +34,24 @@ namespace MonoTests.System.Net.Mail
                [TearDown]
                public void TearDown ()
                {
+                       _smtp = null;
                        if (Directory.Exists (tempFolder))
                                Directory.Delete (tempFolder, true);
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Credentials_Default ()
                {
                        Assert.IsNull (smtp.Credentials);
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void DeliveryMethod ()
                {
                        Assert.AreEqual (SmtpDeliveryMethod.Network, smtp.DeliveryMethod, "#1");
@@ -61,6 +67,9 @@ namespace MonoTests.System.Net.Mail
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void EnableSsl ()
                {
                        Assert.IsFalse (smtp.EnableSsl, "#1");
@@ -71,6 +80,9 @@ namespace MonoTests.System.Net.Mail
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Host ()
                {
                        smtp.Host = "127.0.0.1";
@@ -87,6 +99,9 @@ namespace MonoTests.System.Net.Mail
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Host_Value_Null ()
                {
                        try {
@@ -101,6 +116,9 @@ namespace MonoTests.System.Net.Mail
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Host_Value_Empty ()
                {
                        try {
@@ -116,6 +134,9 @@ namespace MonoTests.System.Net.Mail
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void PickupDirectoryLocation ()
                {
                        Assert.IsNull (smtp.PickupDirectoryLocation, "#1");
@@ -132,6 +153,9 @@ namespace MonoTests.System.Net.Mail
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Port ()
                {
                        Assert.AreEqual (25, smtp.Port, "#1");
@@ -142,6 +166,9 @@ namespace MonoTests.System.Net.Mail
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Port_Value_Invalid ()
                {
                        // zero
@@ -168,6 +195,9 @@ namespace MonoTests.System.Net.Mail
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Send_Message_Null ()
                {
                        try {
@@ -182,6 +212,9 @@ namespace MonoTests.System.Net.Mail
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Send_Network_Host_Null ()
                {
                        try {
@@ -197,6 +230,9 @@ namespace MonoTests.System.Net.Mail
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Send_Network_Host_Whitespace ()
                {
                        smtp.Host = " \r\n ";
@@ -213,6 +249,9 @@ namespace MonoTests.System.Net.Mail
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Send_SpecifiedPickupDirectory ()
                {
                        smtp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
@@ -226,6 +265,9 @@ namespace MonoTests.System.Net.Mail
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Send_SpecifiedPickupDirectory_PickupDirectoryLocation_DirectoryNotFound ()
                {
                        Directory.Delete (tempFolder);
@@ -253,6 +295,9 @@ namespace MonoTests.System.Net.Mail
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Send_SpecifiedPickupDirectory_PickupDirectoryLocation_Empty ()
                {
                        smtp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
@@ -272,6 +317,9 @@ namespace MonoTests.System.Net.Mail
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Send_SpecifiedPickupDirectory_PickupDirectoryLocation_IllegalChars ()
                {
                        smtp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
@@ -297,6 +345,9 @@ namespace MonoTests.System.Net.Mail
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Send_SpecifiedPickupDirectory_PickupDirectoryLocation_NotAbsolute ()
                {
                        smtp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
@@ -316,6 +367,9 @@ namespace MonoTests.System.Net.Mail
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Send_SpecifiedPickupDirectory_PickupDirectoryLocation_Null ()
                {
                        smtp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
@@ -334,6 +388,9 @@ namespace MonoTests.System.Net.Mail
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Timeout ()
                {
                        Assert.AreEqual (100000, smtp.Timeout, "#1");
@@ -344,19 +401,29 @@ namespace MonoTests.System.Net.Mail
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (ArgumentOutOfRangeException))]
+#endif
                public void Timeout_Value_Negative ()
                {
                        smtp.Timeout = -1;
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void UseDefaultCredentials_Default ()
                {
                        Assert.IsFalse (smtp.UseDefaultCredentials);
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Deliver ()
                {
                        var server = new SmtpServer ();
@@ -373,6 +440,9 @@ namespace MonoTests.System.Net.Mail
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Deliver_Envelope ()
                {
                        var server = new SmtpServer ();
@@ -391,6 +461,9 @@ namespace MonoTests.System.Net.Mail
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Deliver_Async ()
                {
                        // SmtpClient uses BackgroundWorker and listens for the RunWorkerCompleted
index 7fe74638571ee72021ae1421ccbd981111299a5d..51752302b206e18dfc35f35ec0c21011494c8bb0 100644 (file)
@@ -113,6 +113,9 @@ namespace MonoTests.System.Net.NetworkInformation
                [Test]
                public void DnsEnabled ()
                {
+                       if (Environment.OSVersion.Platform == PlatformID.Win32NT)
+                               Assert.Ignore ("IsDnsEnabled is not nessasarily enabled for all interfaces on windows.");
+
                        NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces ();
                        foreach (NetworkInterface adapter in adapters)
                        {
index e5c70feab2c16b07d69d2a241697eea1f0d06220..e3542c34f37428c53bfd338e59b298a0909ff60a 100644 (file)
@@ -45,7 +45,6 @@ namespace MonoTests.System.Net.Security
 {
 
 [TestFixture]
-[Category ("RequiresBSDSockets")]
 public class SslStreamTest {
 
        byte[] m_serverCertRaw = { 48, 130, 5, 165, 2, 1, 3, 48, 130, 5, 95, 6, 9, 42, 134, 72, 134, 247, 13, 1, 7, 1, 160, 130, 5, 80, 4, 130, 5, 76, 48, 130, 5, 72, 48, 130, 2, 87, 6, 9, 42, 134, 72, 134, 247, 13, 1, 7, 6, 160, 130, 2, 72, 48, 130, 2, 68, 2, 1, 0, 48, 130, 2, 61, 6, 9, 42, 134, 72, 134, 247, 13, 1, 7, 1, 48, 28, 6, 10, 42, 134, 72, 134, 247, 13, 1, 12, 1, 3, 48, 14, 4, 8, 211, 176, 234, 3, 252, 26, 32, 15, 2, 2, 7, 208, 128, 130, 2, 16, 183, 149, 35, 180, 127, 95, 163, 122, 138, 244, 29, 177, 220, 173, 46, 73, 208, 217, 211, 190, 164, 183, 21, 110, 33, 122, 98, 163, 251, 16, 23, 106, 154, 14, 52, 177, 3, 12, 248, 226, 48, 123, 211, 6, 216, 6, 192, 175, 203, 142, 141, 143, 252, 178, 7, 162, 81, 232, 159, 42, 56, 177, 191, 53, 7, 146, 189, 236, 75, 140, 210, 143, 11, 103, 64, 58, 10, 73, 123, 39, 97, 119, 166, 114, 123, 65, 68, 214, 42, 17, 156, 122, 8, 58, 184, 134, 255, 48, 64, 20, 229, 247, 196, 12, 130, 56, 176, 69, 179, 254, 216, 45, 25, 244, 240, 116, 88, 137, 66, 13, 18, 202, 199, 59, 200, 245, 19, 175, 232, 217, 211, 12, 191, 222, 26, 162, 253, 73, 201, 48, 61, 3, 248, 117, 16, 71, 233, 183, 90, 110, 91, 116, 56, 133, 223, 148, 19, 78, 140, 123, 159, 203, 78, 15, 172, 39, 190, 39, 71, 180, 155, 48, 156, 116, 212, 52, 1, 231, 201, 196, 73, 87, 68, 104, 208, 40, 104, 32, 218, 235, 245, 84, 136, 168, 51, 9, 93, 126, 46, 80, 180, 240, 144, 79, 88, 87, 159, 24, 108, 186, 9, 20, 48, 100, 148, 250, 4, 163, 115, 131, 44, 13, 38, 222, 117, 196, 196, 128, 114, 149, 97, 93, 37, 191, 3, 192, 231, 88, 80, 218, 147, 8, 192, 165, 27, 206, 56, 42, 157, 230, 223, 130, 253, 169, 182, 245, 192, 181, 18, 212, 133, 168, 73, 92, 66, 197, 117, 245, 107, 127, 23, 146, 249, 41, 66, 219, 210, 207, 221, 205, 205, 15, 110, 92, 12, 207, 76, 239, 4, 13, 129, 127, 170, 205, 253, 148, 208, 24, 129, 24, 210, 220, 85, 45, 179, 137, 66, 134, 142, 22, 112, 48, 160, 236, 232, 38, 83, 101, 55, 51, 18, 110, 99, 69, 41, 173, 107, 233, 11, 199, 23, 61, 135, 222, 94, 74, 29, 219, 80, 128, 167, 186, 254, 235, 42, 96, 134, 5, 13, 90, 59, 231, 137, 195, 207, 28, 165, 12, 218, 5, 72, 102, 61, 135, 198, 73, 250, 97, 89, 214, 179, 244, 194, 23, 142, 157, 4, 243, 90, 69, 54, 10, 139, 76, 95, 40, 225, 219, 59, 15, 54, 182, 206, 142, 228, 248, 79, 156, 129, 246, 63, 6, 6, 236, 44, 67, 116, 213, 170, 47, 193, 186, 139, 25, 80, 166, 57, 99, 231, 156, 191, 117, 65, 76, 7, 243, 244, 127, 225, 210, 190, 164, 141, 46, 36, 99, 111, 203, 133, 127, 80, 28, 61, 160, 36, 132, 182, 16, 41, 39, 185, 232, 123, 32, 57, 189, 100, 152, 38, 205, 5, 189, 240, 65, 3, 191, 73, 85, 12, 209, 180, 1, 194, 70, 124, 57, 71, 48, 230, 235, 122, 175, 157, 35, 233, 83, 40, 20, 169, 224, 14, 11, 216, 48, 194, 105, 25, 187, 210, 182, 6, 184, 73, 95, 85, 210, 227, 113, 58, 10, 186, 175, 254, 25, 102, 39, 3, 2, 200, 194, 197, 200, 224, 77, 164, 8, 36, 114, 48, 130, 2, 233, 6, 9, 42, 134, 72, 134, 247, 13, 1, 7, 1, 160, 130, 2, 218, 4, 130, 2, 214, 48, 130, 2, 210, 48, 130, 2, 206, 6, 11, 42, 134, 72, 134, 247, 13, 1, 12, 10, 1, 2, 160, 130, 2, 166, 48, 130, 2, 162, 48, 28, 6, 10, 42, 134, 72, 134, 247, 13, 1, 12, 1, 3, 48, 14, 4, 8, 178, 13, 52, 135, 85, 49, 79, 105, 2, 2, 7, 208, 4, 130, 2, 128, 21, 84, 227, 109, 230, 144, 140, 170, 117, 250, 179, 207, 129, 100, 126, 126, 29, 231, 94, 140, 45, 26, 168, 45, 240, 4, 170, 73, 98, 115, 109, 96, 177, 206, 6, 80, 170, 22, 237, 144, 58, 95, 59, 26, 85, 135, 178, 69, 184, 44, 122, 81, 213, 135, 149, 198, 246, 83, 68, 129, 2, 186, 118, 33, 44, 214, 227, 240, 220, 51, 175, 220, 220, 180, 113, 216, 101, 138, 81, 54, 38, 0, 216, 30, 29, 187, 213, 230, 12, 181, 130, 21, 241, 98, 120, 41, 150, 176, 69, 37, 169, 249, 123, 212, 254, 135, 154, 214, 127, 39, 105, 149, 180, 218, 41, 207, 75, 70, 105, 169, 185, 169, 132, 173, 188, 82, 251, 71, 234, 136, 5, 254, 110, 223, 34, 4, 145, 7, 19, 51, 123, 140, 75, 226, 0, 21, 220, 228, 223, 218, 8, 169, 210, 194, 139, 93, 218, 55, 40, 174, 50, 238, 38, 166, 222, 103, 0, 209, 88, 131, 51, 222, 154, 217, 18, 172, 73, 17, 133, 54, 173, 208, 118, 104, 167, 113, 153, 223, 251, 154, 120, 176, 18, 127, 51, 206, 164, 77, 86, 9, 82, 212, 86, 162, 206, 230, 79, 217, 178, 42, 217, 162, 152, 188, 217, 59, 212, 117, 200, 135, 75, 74, 43, 1, 42, 79, 180, 164, 250, 122, 103, 103, 157, 11, 14, 33, 48, 8, 108, 155, 46, 124, 223, 204, 169, 124, 104, 11, 246, 213, 226, 16, 125, 17, 228, 15, 178, 141, 79, 78, 115, 76, 131, 122, 166, 124, 154, 1, 174, 178, 176, 213, 208, 188, 71, 118, 220, 168, 64, 218, 176, 134, 38, 229, 14, 109, 162, 125, 16, 57, 249, 201, 180, 17, 182, 143, 184, 12, 248, 113, 65, 70, 109, 79, 249, 34, 170, 35, 228, 219, 121, 202, 228, 121, 127, 255, 22, 173, 202, 171, 33, 232, 4, 240, 142, 216, 80, 56, 177, 83, 93, 123, 217, 213, 157, 99, 34, 194, 61, 228, 239, 194, 20, 27, 9, 53, 132, 79, 19, 97, 107, 31, 51, 39, 176, 223, 90, 88, 67, 138, 194, 169, 176, 144, 202, 119, 146, 74, 27, 118, 63, 129, 230, 101, 104, 75, 116, 49, 223, 254, 225, 70, 206, 183, 11, 134, 148, 10, 55, 57, 50, 178, 144, 164, 139, 233, 169, 109, 186, 211, 95, 123, 75, 111, 192, 187, 127, 240, 45, 226, 194, 240, 128, 10, 79, 178, 192, 66, 21, 197, 24, 171, 141, 255, 185, 230, 84, 206, 151, 9, 93, 115, 162, 12, 115, 129, 218, 103, 219, 183, 142, 123, 3, 110, 139, 208, 4, 146, 76, 99, 246, 240, 32, 169, 148, 16, 146, 172, 230, 36, 56, 145, 23, 94, 209, 92, 38, 244, 127, 70, 121, 253, 66, 55, 36, 140, 98, 105, 233, 112, 24, 23, 230, 112, 62, 244, 12, 48, 30, 51, 0, 18, 244, 139, 66, 245, 234, 203, 195, 52, 119, 255, 84, 82, 204, 100, 176, 167, 24, 224, 8, 127, 214, 148, 115, 242, 56, 190, 72, 221, 68, 252, 36, 74, 254, 57, 52, 96, 20, 173, 32, 236, 87, 15, 16, 76, 9, 48, 3, 61, 2, 137, 137, 9, 68, 213, 99, 163, 63, 201, 83, 241, 98, 7, 117, 108, 4, 123, 170, 18, 10, 19, 198, 31, 170, 15, 247, 216, 145, 172, 239, 137, 181, 80, 160, 24, 11, 35, 131, 58, 218, 22, 250, 215, 52, 160, 246, 197, 183, 92, 137, 0, 245, 63, 49, 183, 246, 195, 58, 63, 4, 75, 10, 92, 131, 181, 59, 78, 247, 44, 150, 49, 49, 107, 211, 62, 71, 62, 222, 159, 161, 118, 236, 55, 219, 49, 0, 3, 82, 236, 96, 20, 83, 39, 245, 208, 240, 245, 174, 218, 49, 21, 48, 19, 6, 9, 42, 134, 72, 134, 247, 13, 1, 9, 21, 49, 6, 4, 4, 1, 0, 0, 0, 48, 61, 48, 33, 48, 9, 6, 5, 43, 14, 3, 2, 26, 5, 0, 4, 20, 30, 154, 48, 126, 198, 239, 114, 62, 12, 58, 129, 172, 67, 156, 76, 214, 62, 205, 89, 28, 4, 20, 135, 177, 105, 83, 79, 93, 181, 149, 169, 49, 112, 201, 70, 212, 153, 79, 198, 163, 137, 90, 2, 2, 7, 208 };
@@ -60,6 +59,9 @@ public class SslStreamTest {
        }
 
        [Test] //bug https://bugzilla.novell.com/show_bug.cgi?id=457120
+#if FEATURE_NO_BSD_SOCKETS
+       [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
        public void AuthenticateClientAndServer_ClientSendsNoData ()
        {
                AuthenticateClientAndServer (true, true);
index e51f2d9b7d526e14185622f3337904180ebd89a9..0af239d238ccd494056a4fb8476cd8d1e356f1c4 100644 (file)
@@ -16,12 +16,16 @@ using NUnit.Framework;
 namespace MonoTests.System.Net.Sockets
 {
        [TestFixture]
-       [Category ("RequiresBSDSockets")]
        public class NetworkStreamTest
        {
                [Test]
                // See bug #371923
+
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException(typeof(IOException))]
+#endif
                public void NetworkStreamConnection ()
                {
                        IPEndPoint ipe = new IPEndPoint(Dns.GetHostEntry ("www.google.com").AddressList [0], 80);
@@ -31,6 +35,9 @@ namespace MonoTests.System.Net.Sockets
                }
                
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ReadTimeout ()
                {
                        Socket sock = new Socket (AddressFamily.InterNetwork,
index 28bc6bb81745f29059c186633126c3addaabfa9a..fff160c768c6e5dac98c6c2986e6c83140d74d95 100644 (file)
@@ -1,3 +1,4 @@
+using System;
 using System.Threading;
 using System.Net;
 using System.Net.Sockets;
@@ -6,10 +7,12 @@ using NUnit.Framework;
 namespace MonoTests.System.Net.Sockets
 {
        [TestFixture]
-       [Category ("RequiresBSDSockets")]
        public class SocketAcceptAsyncTest
        {
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void AcceptAsyncShouldUseAcceptSocketFromEventArgs()
                {
                        var readyEvent = new ManualResetEvent(false);
@@ -19,27 +22,40 @@ namespace MonoTests.System.Net.Sockets
                        var serverSocket = new Socket(
                                        AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        Socket acceptedSocket = null;
-
+                       Exception ex = null;
                        ThreadPool.QueueUserWorkItem(_ =>
                        {
-                               listenSocket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
-                               listenSocket.Listen(1);
-
-                               var asyncEventArgs = new SocketAsyncEventArgs {AcceptSocket = serverSocket};
-                               asyncEventArgs.Completed += (s, e) =>
-                               {
-                                       acceptedSocket = e.AcceptSocket;
-                                       mainEvent.Set();
-                               };
+                               SocketAsyncEventArgs asyncEventArgs;
+                               try {
+                                       listenSocket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
+                                       listenSocket.Listen(1);
 
-                               readyEvent.Set();
+                                       asyncEventArgs = new SocketAsyncEventArgs {AcceptSocket = serverSocket};
+                                       asyncEventArgs.Completed += (s, e) =>
+                                       {
+                                               acceptedSocket = e.AcceptSocket;
+                                               mainEvent.Set();
+                                       };
 
-                               if (listenSocket.AcceptAsync(asyncEventArgs))
+                               } catch (Exception e) {
+                                       ex = e;
                                        return;
-                               acceptedSocket = asyncEventArgs.AcceptSocket;
-                               mainEvent.Set();
+                               } finally {
+                                       readyEvent.Set();
+                               }
+
+                               try {
+                                       if (listenSocket.AcceptAsync(asyncEventArgs))
+                                               return;
+                                       acceptedSocket = asyncEventArgs.AcceptSocket;
+                                       mainEvent.Set();
+                               } catch (Exception e) {
+                                       ex = e;
+                               }
                        });
                        Assert.IsTrue(readyEvent.WaitOne(1500));
+                       if (ex != null)
+                               throw ex;
 
                        var clientSocket = new Socket(
                                AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
@@ -47,7 +63,7 @@ namespace MonoTests.System.Net.Sockets
                        clientSocket.NoDelay = true;
 
                        Assert.IsTrue(mainEvent.WaitOne(1500));
-                       Assert.AreEqual(serverSocket, acceptedSocket);
+                       Assert.AreEqual(serverSocket, acceptedSocket, "x");
                        mainEvent.Reset();
 
                        if (acceptedSocket != null)
index d286668707e437635c1bc4e3920b45b4d2fa7072..df31233d68fbd429825cac9d877e9029fb7c9e57 100644 (file)
@@ -8,7 +8,6 @@ using NUnit.Framework;
 namespace MonoTests.System.Net.Sockets
 {
        [TestFixture]
-       [Category ("RequiresBSDSockets")]
        public class SocketAsyncTest
        {
                Socket serverSocket;
@@ -17,8 +16,7 @@ namespace MonoTests.System.Net.Sockets
                ManualResetEvent mainEvent;
                Exception error;
 
-               [TestFixtureSetUp]
-               public void SetUp ()
+               void SetUp ()
                {
                        readyEvent = new ManualResetEvent (false);
                        mainEvent = new ManualResetEvent (false);
@@ -26,6 +24,9 @@ namespace MonoTests.System.Net.Sockets
                        ThreadPool.QueueUserWorkItem (_ => DoWork ());
                        readyEvent.WaitOne ();
 
+                       if (error != null)
+                               throw error;
+
                        clientSocket = new Socket (
                                AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        clientSocket.Connect (serverSocket.LocalEndPoint);
@@ -43,18 +44,22 @@ namespace MonoTests.System.Net.Sockets
 
                void DoWork ()
                {
-                       serverSocket = new Socket (
-                               AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
-                       serverSocket.Bind (new IPEndPoint (IPAddress.Loopback, 0));
-                       serverSocket.Listen (1);
-
-                       var async = new SocketAsyncEventArgs ();
-                       async.Completed += (s,e) => OnAccepted (e);
-
-                       readyEvent.Set ();
-
-                       if (!serverSocket.AcceptAsync (async))
-                               OnAccepted (async);
+                       try {
+                               serverSocket = new Socket (
+                                       AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+                               serverSocket.Bind (new IPEndPoint (IPAddress.Loopback, 0));
+                               serverSocket.Listen (1);
+
+                               var async = new SocketAsyncEventArgs ();
+                               async.Completed += (s,e) => OnAccepted (e);
+
+                               if (!serverSocket.AcceptAsync (async))
+                                       OnAccepted (async);
+                       } catch (Exception e) {
+                               error = e;
+                       } finally {
+                               readyEvent.Set ();
+                       }
                }
 
                void OnAccepted (SocketAsyncEventArgs e)
@@ -93,8 +98,12 @@ namespace MonoTests.System.Net.Sockets
 
                [Test]
                [Category("Test")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SendAsync ()
                {
+                       SetUp ();
                        var buffer = new byte [] { 0x12, 0x34, 0x56, 0x78 };
                        var m = new ManualResetEvent (false);
                        var e = new SocketAsyncEventArgs ();
index 4955d3f3c6096effcfa6a54a0c6dfb2a53b937e7..14ec2700869c289ee1159851c5402e07138b70a5 100755 (executable)
@@ -28,7 +28,6 @@ using MonoTests.Helpers;
 namespace MonoTests.System.Net.Sockets
 {
        [TestFixture]
-       [Category ("RequiresBSDSockets")]
        public class SocketTest
        {
                // note: also used in SocketCas tests
@@ -36,6 +35,9 @@ namespace MonoTests.System.Net.Sockets
                public const int BogusPort = 23483;
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ConnectIPAddressAny ()
                {
                        IPEndPoint ep = new IPEndPoint (IPAddress.Any, NetworkHelpers.FindFreePort ());
@@ -86,6 +88,9 @@ namespace MonoTests.System.Net.Sockets
 
                [Test]
                [Category ("InetAccess")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BogusEndConnect ()
                {
                        IPAddress ipOne = IPAddress.Parse (BogusAddress);
@@ -156,6 +161,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void AcceptBlockingStatus()
                {
                        bool block;
@@ -200,6 +208,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ConnectFailAsync ()
                {
                        Socket sock = new Socket (AddressFamily.InterNetwork,
@@ -222,6 +233,9 @@ namespace MonoTests.System.Net.Sockets
                }
                
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SetSocketOptionBoolean ()
                {
                        IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
@@ -233,6 +247,9 @@ namespace MonoTests.System.Net.Sockets
                        }
                }
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void TestSelect1 ()
                {
                        Socket srv = CreateServer (NetworkHelpers.FindFreePort ());
@@ -370,7 +387,11 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (ObjectDisposedException))]
+#endif
                public void Disposed19 ()
                {
                        Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
@@ -381,7 +402,11 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (ObjectDisposedException))]
+#endif
                public void Disposed20 ()
                {
                        Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
@@ -392,7 +417,11 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (ObjectDisposedException))]
+#endif
                public void Disposed21 ()
                {
                        Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
@@ -403,7 +432,11 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (ObjectDisposedException))]
+#endif
                public void Disposed22 ()
                {
                        Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
@@ -424,6 +457,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void GetHashCodeTest ()
                {
                        Socket server = new Socket (AddressFamily.InterNetwork,
@@ -459,6 +495,7 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+               [Category ("RequiresBSDSockets")] // This verifies particular error codes, which we don't care about when nothing's working anyway.
                public void SocketErrorTest ()
                {
                        Socket sock = new Socket (AddressFamily.InterNetwork,
@@ -700,6 +737,9 @@ namespace MonoTests.System.Net.Sockets
                }
                
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void IsBoundTcp ()
                {
                        Socket sock = new Socket (AddressFamily.InterNetwork,
@@ -732,6 +772,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void IsBoundUdp ()
                {
                        Socket sock = new Socket (AddressFamily.InterNetwork,
@@ -1304,7 +1347,11 @@ namespace MonoTests.System.Net.Sockets
                }
                
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof(InvalidOperationException))]
+#endif
                public void BeginAcceptNotListening ()
                {
                        Socket sock = new Socket (AddressFamily.InterNetwork,
@@ -1319,6 +1366,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BeginAccept ()
                {
                        Socket sock = new Socket (AddressFamily.InterNetwork,
@@ -1386,6 +1436,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BeginAcceptData ()
                {
                        Socket sock = new Socket (AddressFamily.InterNetwork,
@@ -1450,6 +1503,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BeginAcceptSocketUdp ()
                {
                        Socket sock = new Socket (AddressFamily.InterNetwork,
@@ -1477,6 +1533,9 @@ namespace MonoTests.System.Net.Sockets
                }
                
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BeginAcceptSocketBound ()
                {
                        Socket sock = new Socket (AddressFamily.InterNetwork,
@@ -1508,6 +1567,9 @@ namespace MonoTests.System.Net.Sockets
                }
                
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BeginAcceptSocket ()
                {
                        Socket sock = new Socket (AddressFamily.InterNetwork,
@@ -1589,6 +1651,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BeginAcceptSocketAccClosed ()
                {
                        Socket sock = new Socket (AddressFamily.InterNetwork,
@@ -1638,6 +1703,9 @@ namespace MonoTests.System.Net.Sockets
                }
                
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BeginConnectAddressPort ()
                {
                        Socket sock = new Socket (AddressFamily.InterNetwork,
@@ -1687,6 +1755,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BeginConnectAddressPortListen ()
                {
                        Socket sock = new Socket (AddressFamily.InterNetwork,
@@ -1781,6 +1852,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BeginConnectMultiple2 ()
                {
                        Socket sock = new Socket (AddressFamily.InterNetwork,
@@ -1853,6 +1927,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BeginConnectMultipleListen ()
                {
                        Socket sock = new Socket (AddressFamily.InterNetwork,
@@ -1917,6 +1994,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BeginConnectHostPortListen ()
                {
                        Socket sock = new Socket (AddressFamily.InterNetwork,
@@ -1984,6 +2064,9 @@ namespace MonoTests.System.Net.Sockets
                
                [Test]
                [Category ("NotDotNet")] // "Needs XP or later"
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BeginDisconnect ()
                {
                        Socket sock = new Socket (AddressFamily.InterNetwork,
@@ -2080,6 +2163,9 @@ namespace MonoTests.System.Net.Sockets
                }
                
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BindTwice ()
                {
                        Socket sock = new Socket (AddressFamily.InterNetwork,
@@ -2103,6 +2189,9 @@ namespace MonoTests.System.Net.Sockets
                }
                
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Close ()
                {
                        Socket sock = new Socket (AddressFamily.InterNetwork,
@@ -2131,6 +2220,9 @@ namespace MonoTests.System.Net.Sockets
                }
                
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ConnectAddressPort ()
                {
                        Socket sock = new Socket (AddressFamily.InterNetwork,
@@ -2171,6 +2263,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ConnectAddressPortListen ()
                {
                        Socket sock = new Socket (AddressFamily.InterNetwork,
@@ -2257,6 +2352,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ConnectMultiple2 ()
                {
                        Socket sock = new Socket (AddressFamily.InterNetwork,
@@ -2314,6 +2412,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ConnectMultipleListen ()
                {
                        Socket sock = new Socket (AddressFamily.InterNetwork,
@@ -2376,6 +2477,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ConnectHostPortListen ()
                {
                        Socket sock = new Socket (AddressFamily.InterNetwork,
@@ -2414,7 +2518,11 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof(ObjectDisposedException))]
+#endif
                public void ConnectHostPortClosed ()
                {
                        Socket sock = new Socket (AddressFamily.InterNetwork,
@@ -2428,6 +2536,9 @@ namespace MonoTests.System.Net.Sockets
                
                [Test]
                [Category ("NotDotNet")] // "Needs XP or later"
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Disconnect ()
                {
                        Socket sock = new Socket (AddressFamily.InterNetwork,
@@ -2485,6 +2596,9 @@ namespace MonoTests.System.Net.Sockets
                }
                
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ReceiveGeneric ()
                {
                        int i;
@@ -2542,6 +2656,9 @@ namespace MonoTests.System.Net.Sockets
                }
                
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SendGeneric ()
                {
                        int i;
@@ -2599,6 +2716,78 @@ namespace MonoTests.System.Net.Sockets
                        listensock.Close ();
                }
 
+               [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (AggregateException))] // Something catches the PlatformNotSupportedException and re-throws an AggregateException    
+#endif
+               public void ConcurrentExceedSocketLimit ()
+               {
+                       var tasks = new Task[4];
+                       for (int i = 0; i < 4; i++) {
+                               tasks[i] = Task.Factory.StartNew (() => SendGenericExceedBuffer ());
+                       }
+                       Task.WaitAll (tasks);
+               }
+
+               [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
+               public void SendGenericExceedBuffer ()
+               {
+                       // Create a buffer larger than the default max.
+                       const int BUFFER_SIZE = 65 * 1024;
+                       int i;
+
+                       IPEndPoint endpoint = new IPEndPoint(IPAddress.Loopback, NetworkHelpers.FindFreePort ());
+
+                       Socket listensock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+                       listensock.Bind (endpoint);
+                       listensock.Listen (1);
+
+                       Socket sendsock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+                       sendsock.Connect (endpoint);
+
+                       Socket clientsock = listensock.Accept ();
+
+                       byte[] sendbuf = new byte[BUFFER_SIZE];
+
+                       for (i = 0; i < BUFFER_SIZE; i++) {
+                               sendbuf[i] = (byte)i;
+                       }
+
+                       Task sendTask = Task.Factory.StartNew(() => {
+                               int sent = sendsock.Send (sendbuf);
+
+                               Assert.AreEqual (BUFFER_SIZE, sent, "#1");
+                       });
+
+                       byte[] recvbuf = new byte[BUFFER_SIZE];
+
+                       Task recvTask = Task.Factory.StartNew(() => {
+                               int totalReceived = 0;
+                               byte[] buffer = new byte[256];
+                               while (totalReceived < sendbuf.Length) {
+                                       int recvd = clientsock.Receive (buffer, 0, buffer.Length, SocketFlags.None);
+                                       Array.Copy (buffer, 0, recvbuf, totalReceived, recvd);
+                                       totalReceived += recvd;
+                               }
+
+                               Assert.AreEqual (BUFFER_SIZE, totalReceived, "#2");
+                       });
+
+                       Assert.IsTrue (Task.WaitAll (new []{sendTask, recvTask}, 20 * 1000), "#2a");
+
+                       for (i = 0; i < BUFFER_SIZE; i++) {
+                               Assert.AreEqual (recvbuf[i], sendbuf[i],
+                                                "#3/" + i.ToString());
+                       }
+
+                       sendsock.Close ();
+                       clientsock.Close ();
+                       listensock.Close ();
+               }
+
                [Test]
                public void ListenNotBound ()
                {
@@ -2634,6 +2823,9 @@ namespace MonoTests.System.Net.Sockets
                }
                
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void CloseWhileReceiving ()
                {
                        CWRSocket = new Socket (AddressFamily.InterNetwork,
@@ -3003,6 +3195,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test] // ReceiveFrom (Byte [], ref EndPoint)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ReceiveFrom1_Buffer_Null ()
                {
                        Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
@@ -3044,6 +3239,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test] // ReceiveFrom (Byte [], ref EndPoint)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ReceiveFrom1_Socket_Closed ()
                {
                        Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
@@ -3064,6 +3262,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test] // ReceiveFrom (Byte [], SocketFlags, ref EndPoint)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ReceiveFrom2_Buffer_Null ()
                {
                        Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
@@ -3105,6 +3306,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test] // ReceiveFrom (Byte [], SocketFlags, ref EndPoint)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ReceiveFrom2_Socket_Closed ()
                {
                        Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
@@ -3125,6 +3329,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test] // ReceiveFrom (Byte [], Int32, SocketFlags, ref EndPoint)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ReceiveFrom3_Buffer_Null ()
                {
                        Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
@@ -3167,6 +3374,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test] // ReceiveFrom (Byte [], Int32, SocketFlags, ref EndPoint)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ReceiveFrom3_Size_OutOfRange ()
                {
                        Socket s;
@@ -3208,6 +3418,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test] // ReceiveFrom (Byte [], Int32, SocketFlags, ref EndPoint)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ReceiveFrom3_Socket_Closed ()
                {
                        Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
@@ -3229,6 +3442,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test] // ReceiveFrom (Byte [], Int32, Int32, SocketFlags, EndPoint)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ReceiveFrom4_Buffer_Null ()
                {
                        Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
@@ -3248,6 +3464,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test] // ReceiveFrom (Byte [], Int32, Int32, SocketFlags, EndPoint)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ReceiveFrom4_Offset_OutOfRange ()
                {
                        Socket s;
@@ -3311,6 +3530,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test] // ReceiveFrom (Byte [], Int32, Int32, SocketFlags, EndPoint)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ReceiveFrom4_Size_OutOfRange ()
                {
                        Socket s;
@@ -3369,6 +3591,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test] // ReceiveFrom (Byte [], Int32, Int32, SocketFlags, ref EndPoint)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ReceiveFrom4_Socket_Closed ()
                {
                        Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
@@ -3391,6 +3616,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ReceiveRemoteClosed ()
                {
                        var port = NetworkHelpers.FindFreePort ();
@@ -3418,6 +3646,9 @@ namespace MonoTests.System.Net.Sockets
                //
                // Test case for bug #471580
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void UdpDoubleBind ()
                {
                        using (Socket s = new Socket (AddressFamily.InterNetwork,
@@ -3451,6 +3682,9 @@ namespace MonoTests.System.Net.Sockets
 
                // Test case for bug #31557
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void TcpDoubleBind ()
                {
                        using (Socket s = new Socket (AddressFamily.InterNetwork,
@@ -3689,6 +3923,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SetSocketOption3_AddMembershipIPv4_IPv6MulticastOption ()
                {
                        IPAddress mcast_addr = IPAddress.Parse ("239.255.255.250");
@@ -3711,6 +3948,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SetSocketOption3_AddMembershipIPv4_MulticastOption ()
                {
                        IPAddress mcast_addr = IPAddress.Parse ("239.255.255.250");
@@ -3747,6 +3987,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SetSocketOption3_AddMembershipIPv6_IPv6MulticastOption ()
                {
                        if (!Socket.OSSupportsIPv6)
@@ -3762,6 +4005,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SetSocketOption3_AddMembershipIPv6_MulticastOption ()
                {
                        if (!Socket.OSSupportsIPv6)
@@ -3916,6 +4162,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SetSocketOption3_DropMembershipIPv4_IPv6MulticastOption ()
                {
                        IPAddress mcast_addr = IPAddress.Parse ("239.255.255.250");
@@ -3940,6 +4189,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SetSocketOption3_DropMembershipIPv4_MulticastOption ()
                {
                        IPAddress mcast_addr = IPAddress.Parse ("239.255.255.250");
@@ -3980,6 +4232,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SetSocketOption3_DropMembershipIPv6_IPv6MulticastOption ()
                {
                        if (!Socket.OSSupportsIPv6)
@@ -3998,6 +4253,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SetSocketOption3_DropMembershipIPv6_MulticastOption ()
                {
                        if (!Socket.OSSupportsIPv6)
@@ -4084,6 +4342,7 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+               [Category ("RequiresBSDSockets")] // on watchOS device this happens: System.Net.Sockets.SocketException : The requested address is not valid in this context. This situation is too complex to detect and throw a PlatformNotSupportedException, so just ignore it.
                public void SetSocketOption_MulticastInterfaceIndex_Any ()
                {
                        IPAddress ip = IPAddress.Parse ("239.255.255.250");
@@ -4096,6 +4355,7 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+               [Category ("RequiresBSDSockets")] // on watchOS device this happens: System.Net.Sockets.SocketException : The requested address is not valid in this context. This situation is too complex to detect and throw a PlatformNotSupportedException, so just ignore it.
                public void SetSocketOption_MulticastInterfaceIndex_Loopback ()
                {
                        IPAddress ip = IPAddress.Parse ("239.255.255.250");
@@ -4132,6 +4392,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Shutdown_NoConnect ()
                {
                        Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
@@ -4228,6 +4491,9 @@ namespace MonoTests.System.Net.Sockets
                }
                
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SendAsyncFile ()
                {
                        Socket serverSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
@@ -4286,6 +4552,9 @@ namespace MonoTests.System.Net.Sockets
                }
                
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ConnectToIPV4EndPointUsingDualModelSocket () {
                        /*
                         * IPv6 DualMode sockets are defaults in Mono. Explicitly specify that
@@ -4326,6 +4595,9 @@ namespace MonoTests.System.Net.Sockets
                }
                
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BeginConnectToIPV4EndPointUsingDualModelSocket () {
                        /*
                         * IPv6 DualMode sockets are defaults in Mono. Explicitly specify that
@@ -4369,6 +4641,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void UdpMulticasTimeToLive ()
                {
                        /* see https://bugzilla.xamarin.com/show_bug.cgi?id=36941 */
index 4d3b8325048d9038ebfcaf8210960ebc71562f1a..a9e849fc1e77d0e9e4aec3513ee0f37c1e345b4a 100644 (file)
@@ -21,7 +21,6 @@ namespace MonoTests.System.Net.Sockets
        /// Tests System.Net.Sockets.TcpClient
        /// </summary>
        [TestFixture]
-       [Category ("RequiresBSDSockets")]
        public class TcpClientTest
        {
                
@@ -30,6 +29,9 @@ namespace MonoTests.System.Net.Sockets
                /// (from System.Net.Sockets)
                /// </summary>
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void TcpClient()
                {
                        // set up a listening Socket
@@ -77,6 +79,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test] // bug #81105
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void CloseTest ()
                {
                        var port = NetworkHelpers.FindFreePort ();
@@ -140,7 +145,11 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof(ArgumentNullException))]
+#endif
                public void ConnectMultiNull ()
                {
                        TcpClient client = new TcpClient ();
@@ -150,6 +159,9 @@ namespace MonoTests.System.Net.Sockets
                }
                
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ConnectMultiAny ()
                {
                        TcpClient client = new TcpClient ();
@@ -161,13 +173,16 @@ namespace MonoTests.System.Net.Sockets
                                client.Connect (ipAddresses, 1234);
                                Assert.Fail ("ConnectMultiAny #1");
                        } catch (SocketException ex) {
-                               Assert.AreEqual (10049, ex.ErrorCode, "ConnectMultiAny #2");
+                               Assert.AreEqual (10061, ex.ErrorCode, "ConnectMultiAny #2");
                        } catch {
                                Assert.Fail ("ConnectMultiAny #3");
                        }
                }
                
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ConnectMultiRefused ()
                {
                        TcpClient client = new TcpClient ();
index 1e211cf524920b999f0f090353814030a6dff829..25e8854ed6a87635c18cdec0a9f8778959ad2327 100644 (file)
@@ -20,10 +20,12 @@ using MonoTests.Helpers;
 namespace MonoTests.System.Net.Sockets
 {
        [TestFixture]
-       [Category ("RequiresBSDSockets")]
        public class TcpListenerTest
        {
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void TcpListener ()
                {
                        var port = NetworkHelpers.FindFreePort ();
@@ -75,6 +77,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void CtorInt1 ()
                {
                        int nex = 0;
@@ -87,21 +92,33 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (ArgumentNullException))]
+#endif
                public void CtorIPEndPoint ()
                {
                        new TcpListener (null);
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (ArgumentNullException))]
+#endif
                public void CtorIPAddressInt1 ()
                {
                        new TcpListener (null, 100000);
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (ArgumentOutOfRangeException))]
+#endif
                public void CtorIPAddressInt2 ()
                {
                        new TcpListener (IPAddress.Any, 100000);
@@ -125,6 +142,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void PreStartStatus ()
                {
                        MyListener listener = new MyListener ();
@@ -152,6 +172,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void PostStartStatus ()
                {
                        MyListener listener = new MyListener ();
@@ -173,6 +196,9 @@ namespace MonoTests.System.Net.Sockets
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void StartListenMoreThan5 ()
                {
                        var port = NetworkHelpers.FindFreePort ();
index 66b15308d1f84cb08efaae91d0bbe5b8e3acc62d..33dc4464c86d89bbb0cfedb032c25c3ebf2e7b85 100644 (file)
@@ -15,9 +15,11 @@ using NUnit.Framework;
 
 namespace MonoTests.System.Net.Sockets {
        [TestFixture]
-       [Category ("RequiresBSDSockets")]
        public class UdpClientTest {
                [Test] // .ctor ()
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Constructor1 ()
                {
                        MyUdpClient client;
@@ -43,6 +45,9 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // .ctor (AddressFamily)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Constructor2 ()
                {
                        MyUdpClient client;
@@ -88,6 +93,9 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // .ctor (AddressFamily)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Constructor2_Family_Invalid ()
                {
                        try {
@@ -114,6 +122,9 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // .ctor (Int32)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Constructor3 ()
                {
                        Socket s;
@@ -163,6 +174,9 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // .ctor (Int32)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Constructor3_Port_OutOfRange ()
                {
                        try {
@@ -189,6 +203,9 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // .ctor (IPEndPoint)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Constructor4 ()
                {
                        Socket s;
@@ -221,6 +238,9 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // .ctor (IPEndPoint)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Constructor4_LocalEP_Null ()
                {
                        try {
@@ -235,6 +255,9 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // .ctor (Int32, AddressFamily)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Constructor5 ()
                {
                        Socket s;
@@ -288,6 +311,9 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // .ctor (Int32, AddressFamily)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Constructor5_Family_Invalid ()
                {
                        try {
@@ -318,6 +344,9 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // .ctor (Int32, AddressFamily)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Constructor5_Port_OutOfRange ()
                {
                        try {
@@ -344,6 +373,9 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // .ctor (String, Int32)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Constructor6 ()
                {
                        Socket s;
@@ -394,6 +426,9 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // .ctor (String, Int32)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Constructor6_HostName_Null ()
                {
                        try {
@@ -408,6 +443,9 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // .ctor (String, Int32)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Constructor6_Port_OutOfRange ()
                {
                        try {
@@ -434,6 +472,9 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void UdpClientBroadcastTest () 
                {
                        UdpClient client = new UdpClient ();
@@ -447,6 +488,9 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // JoinMulticastGroup (IPAddress)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void JoinMulticastGroup1_IPv4 ()
                {
                        IPAddress mcast_addr = IPAddress.Parse ("224.0.0.23");
@@ -457,6 +501,9 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // JoinMulticastGroup (IPAddress)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void JoinMulticastGroup1_IPv6 ()
                {
                        if (!Socket.OSSupportsIPv6)
@@ -470,6 +517,9 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // JoinMulticastGroup (IPAddress)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void JoinMulticastGroup1_MulticastAddr_Null ()
                {
                        using (UdpClient client = new UdpClient (new IPEndPoint (IPAddress.Loopback, 1234))) {
@@ -486,6 +536,9 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // JoinMulticastGroup (IPAddress)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void JoinMulticastGroup1_Socket_Closed ()
                {
                        IPAddress mcast_addr = null;
@@ -505,29 +558,22 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // JoinMulticastGroup (IPAddress)
-               [Category ("NotWorking")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void JoinMulticastGroup1_Socket_NotBound ()
                {
                        IPAddress mcast_addr = IPAddress.Parse ("224.0.0.23");
 
-                       UdpClient client = new UdpClient (AddressFamily.InterNetwork);
-                       try {
+                       using (UdpClient client = new UdpClient (AddressFamily.InterNetwork)) {
                                client.JoinMulticastGroup (mcast_addr);
-                               Assert.Fail ("#1");
-                       } catch (SocketException ex) {
-                               // An invalid argument was supplied
-                               Assert.AreEqual (typeof (SocketException), ex.GetType (), "#2");
-                               Assert.AreEqual (10022, ex.ErrorCode, "#3");
-                               Assert.IsNull (ex.InnerException, "#4");
-                               Assert.IsNotNull (ex.Message, "#5");
-                               Assert.AreEqual (10022, ex.NativeErrorCode, "#6");
-                               Assert.AreEqual (SocketError.InvalidArgument, ex.SocketErrorCode, "#7");
-                       } finally {
-                               client.Close ();
                        }
                }
 
                [Test] // JoinMulticastGroup (In32, IPAddress)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void JoinMulticastGroup2_IPv4 ()
                {
                        IPAddress mcast_addr = IPAddress.Parse ("224.0.0.23");
@@ -550,6 +596,9 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // JoinMulticastGroup (In32, IPAddress)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void JoinMulticastGroup2_IPv6 ()
                {
                        if (!Socket.OSSupportsIPv6)
@@ -563,6 +612,9 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // JoinMulticastGroup (Int32, IPAddress)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void JoinMulticastGroup2_MulticastAddr_Null ()
                {
                        using (UdpClient client = new UdpClient (new IPEndPoint (IPAddress.Loopback, 1234))) {
@@ -579,6 +631,9 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // JoinMulticastGroup (Int32, IPAddress)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void JoinMulticastGroup2_Socket_Closed ()
                {
                        if (!Socket.OSSupportsIPv6)
@@ -601,29 +656,22 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // JoinMulticastGroup (Int32, IPAddress)
-               [Category ("NotWorking")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void JoinMulticastGroup2_Socket_NotBound ()
                {
                        IPAddress mcast_addr = IPAddress.Parse ("ff02::1");
 
-                       UdpClient client = new UdpClient (AddressFamily.InterNetworkV6);
-                       try {
+                       using (UdpClient client = new UdpClient (AddressFamily.InterNetworkV6)) {
                                client.JoinMulticastGroup (0, mcast_addr);
-                               Assert.Fail ("#1");
-                       } catch (SocketException ex) {
-                               // An invalid argument was supplied
-                               Assert.AreEqual (typeof (SocketException), ex.GetType (), "#2");
-                               Assert.AreEqual (10022, ex.ErrorCode, "#3");
-                               Assert.IsNull (ex.InnerException, "#4");
-                               Assert.IsNotNull (ex.Message, "#5");
-                               Assert.AreEqual (10022, ex.NativeErrorCode, "#6");
-                               Assert.AreEqual (SocketError.InvalidArgument, ex.SocketErrorCode, "#7");
-                       } finally {
-                               client.Close ();
                        }
                }
 
                [Test] // JoinMulticastGroup (IPAddress, Int32)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void JoinMulticastGroup3_IPv4 ()
                {
                        IPAddress mcast_addr = IPAddress.Parse ("224.0.0.23");
@@ -638,6 +686,9 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // JoinMulticastGroup (IPAddress, Int32)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void JoinMulticastGroup3_IPv6 ()
                {
                        if (!Socket.OSSupportsIPv6)
@@ -655,6 +706,9 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // JoinMulticastGroup (IPAddress, Int32)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void JoinMulticastGroup3_MulticastAddr_Null ()
                {
                        using (UdpClient client = new UdpClient (new IPEndPoint (IPAddress.Loopback, 1234))) {
@@ -671,6 +725,9 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // JoinMulticastGroup (IPAddress, Int32)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void JoinMulticastGroup3_Socket_Closed ()
                {
                        IPAddress mcast_addr = null;
@@ -690,29 +747,22 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // JoinMulticastGroup (IPAddress, Int32)
-               [Category ("NotWorking")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void JoinMulticastGroup3_Socket_NotBound ()
                {
                        IPAddress mcast_addr = IPAddress.Parse ("224.0.0.23");
 
-                       UdpClient client = new UdpClient (AddressFamily.InterNetwork);
-                       try {
+                       using (UdpClient client = new UdpClient (AddressFamily.InterNetwork)) {
                                client.JoinMulticastGroup (mcast_addr, 5);
-                               Assert.Fail ("#1");
-                       } catch (SocketException ex) {
-                               // An invalid argument was supplied
-                               Assert.AreEqual (typeof (SocketException), ex.GetType (), "#2");
-                               Assert.AreEqual (10022, ex.ErrorCode, "#3");
-                               Assert.IsNull (ex.InnerException, "#4");
-                               Assert.IsNotNull (ex.Message, "#5");
-                               Assert.AreEqual (10022, ex.NativeErrorCode, "#6");
-                               Assert.AreEqual (SocketError.InvalidArgument, ex.SocketErrorCode, "#7");
-                       } finally {
-                               client.Close ();
                        }
                }
 
                [Test] // JoinMulticastGroup (IPAddress, IPAddress)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void JoinMulticastGroup4_IPv4 ()
                {
                        IPAddress mcast_addr = IPAddress.Parse ("224.0.0.23");
@@ -724,6 +774,9 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // JoinMulticastGroup (IPAddress, IPAddress)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void JoinMulticastGroup4_IPv6 ()
                {
                        if (!Socket.OSSupportsIPv6)
@@ -750,6 +803,9 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // JoinMulticastGroup (IPAddress, IPAddress)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void JoinMulticastGroup4_LocalAddress_Null ()
                {
                        IPAddress mcast_addr = IPAddress.Parse ("224.0.0.23");
@@ -768,6 +824,9 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // JoinMulticastGroup (IPAddress, IPAddress)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void JoinMulticastGroup4_MulticastAddr_Null ()
                {
                        using (UdpClient client = new UdpClient (new IPEndPoint (IPAddress.Loopback, 1234))) {
@@ -784,6 +843,9 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // JoinMulticastGroup (IPAddress, IPAddress)
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void JoinMulticastGroup4_Socket_Closed ()
                {
                        IPAddress mcast_addr = null;
@@ -804,30 +866,23 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // JoinMulticastGroup (IPAddress, IPAddress)
-               [Category ("NotWorking")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void JoinMulticastGroup4_Socket_NotBound ()
                {
                        IPAddress mcast_addr = IPAddress.Parse ("224.0.0.23");
                        IPAddress local_addr = Dns.GetHostEntry (string.Empty).AddressList [0];
 
-                       UdpClient client = new UdpClient (AddressFamily.InterNetwork);
-                       try {
+                       using (UdpClient client = new UdpClient (AddressFamily.InterNetwork)) {
                                client.JoinMulticastGroup (mcast_addr, local_addr);
-                               Assert.Fail ("#1");
-                       } catch (SocketException ex) {
-                               // An invalid argument was supplied
-                               Assert.AreEqual (typeof (SocketException), ex.GetType (), "#2");
-                               Assert.AreEqual (10022, ex.ErrorCode, "#3");
-                               Assert.IsNull (ex.InnerException, "#4");
-                               Assert.IsNotNull (ex.Message, "#5");
-                               Assert.AreEqual (10022, ex.NativeErrorCode, "#6");
-                               Assert.AreEqual (SocketError.InvalidArgument, ex.SocketErrorCode, "#7");
-                       } finally {
-                               client.Close ();
                        }
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void CloseInReceive ()
                {
                        UdpClient client = null;
@@ -868,6 +923,9 @@ namespace MonoTests.System.Net.Sockets {
 
                // Test for bug 324033
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void JoinMulticastGroupWithLocal ()
                {
                        UdpClient client = new UdpClient (9001);
@@ -882,7 +940,11 @@ namespace MonoTests.System.Net.Sockets {
                }
                
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof(ArgumentNullException))]
+#endif
                public void BeginSendNull ()
                {
                        UdpClient client = new UdpClient ();
@@ -905,6 +967,9 @@ namespace MonoTests.System.Net.Sockets {
                }
                
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BeginSend ()
                {
                        UdpClient client = new UdpClient ();
@@ -959,6 +1024,9 @@ namespace MonoTests.System.Net.Sockets {
                }
                
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BeginReceive ()
                {
                        UdpClient client = new UdpClient (1237);
@@ -984,6 +1052,9 @@ namespace MonoTests.System.Net.Sockets {
                }
                
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Available ()
                {
                        using (UdpClient client = new UdpClient (1238)) {
@@ -1018,6 +1089,9 @@ namespace MonoTests.System.Net.Sockets {
                }
                
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void EnableBroadcastDefault ()
                {
                        UdpClient client = new UdpClient ();
@@ -1057,6 +1131,9 @@ namespace MonoTests.System.Net.Sockets {
                }
                
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void MulticastLoopbackDefault ()
                {
                        UdpClient client = new UdpClient ();
@@ -1067,6 +1144,9 @@ namespace MonoTests.System.Net.Sockets {
                }
 
                [Test] // #6057
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ReceiveIPv6 ()
                {
                        if (!Socket.OSSupportsIPv6)
index 4e7aa5668c35bc304532a5f6e14a716d069f1e72..e3dd58188c17358fe03c97bac68aaed04f105ef7 100644 (file)
@@ -18,31 +18,33 @@ namespace MonoTests.System.Net.WebSockets
        {
                const string EchoServerUrl = "ws://corefx-net.cloudapp.net/WebSocket/EchoWebSocket.ashx";
                int Port = NetworkHelpers.FindFreePort ();
-               HttpListener listener;
-               ClientWebSocket socket;
-               MethodInfo headerSetMethod;
-
-               [SetUp]
-               public void Setup ()
-               {
-                       listener = new HttpListener ();
-                       listener.Prefixes.Add ("http://localhost:" + Port + "/");
-                       listener.Start ();
-                       socket = new ClientWebSocket ();
+               HttpListener _listener;
+               HttpListener listener {
+                       get {
+                               if (_listener != null)
+                                       return _listener;
+                               var tmp = new HttpListener ();
+                               tmp.Prefixes.Add ("http://localhost:" + Port + "/");
+                               tmp.Start ();
+                               return _listener = tmp;
+                       }
                }
+               ClientWebSocket _socket;
+               ClientWebSocket socket { get { return _socket ?? (_socket = new ClientWebSocket ()); } }
+               MethodInfo headerSetMethod;
 
                [TearDown]
                public void Teardown ()
                {
-                       if (listener != null) {
-                               listener.Stop ();
-                               listener = null;
+                       if (_listener != null) {
+                               _listener.Stop ();
+                               _listener = null;
                        }
-                       if (socket != null) {
-                               if (socket.State == WebSocketState.Open)
-                                       socket.CloseAsync (WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).Wait (2000);
-                               socket.Dispose ();
-                               socket = null;
+                       if (_socket != null) {
+                               if (_socket.State == WebSocketState.Open)
+                                       _socket.CloseAsync (WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).Wait (2000);
+                               _socket.Dispose ();
+                               _socket = null;
                        }
                }
 
index 37c40d7445e070cd8d5021dc238253b6bdac5db5..f3c4eceea74abb0622b2945ecb3f6325a0bae2ce 100644 (file)
@@ -9,7 +9,6 @@ using NUnit.Framework;
 namespace MonoTests.System.Net
 {
        [TestFixture]
-       [Category ("RequiresBSDSockets")]
        public class CookieParserTest
        {
                public const string A = "Foo=Bar, expires=World; expires=Sat, 11-Oct-14 22:45:19 GMT, A=B";
@@ -72,6 +71,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void TestExpires ()
                {
                        var cookies = DoRequest (A);
@@ -82,6 +84,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void TestInvalidCookie ()
                {
                        var cookies = DoRequest (B);
@@ -92,6 +97,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void TestLocalCulture ()
                {
                        var old = Thread.CurrentThread.CurrentCulture;
@@ -109,6 +117,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void TestMultiple ()
                {
                        var cookies = DoRequest (D);
@@ -119,6 +130,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void TestMultiple2 ()
                {
                        var cookies = DoRequest (E);
@@ -128,6 +142,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void TestQuotation ()
                {
                        var cookies = DoRequest (F);
@@ -140,6 +157,7 @@ namespace MonoTests.System.Net
                {
                        Socket socket;
                        string[] headers;
+                       Exception ex;
 
                        public Listener (params string[] headers)
                        {
@@ -155,17 +173,28 @@ namespace MonoTests.System.Net
                                socket.Bind (new IPEndPoint (IPAddress.Loopback, 0));
                                socket.Listen (1);
                                socket.BeginAccept ((result) => {
-                                       var accepted = socket.EndAccept (result);
-                                       HandleRequest (accepted);
+                                       try {
+                                               var accepted = socket.EndAccept (result);
+                                               HandleRequest (accepted);
+                                       } catch (Exception e) {
+                                               ex = e;
+                                       }
                                }, null);
                        }
 
+                       void ThrowIfException ()
+                       {
+                               if (ex != null)
+                                       throw ex;
+                       }
+
                        public void Dispose ()
                        {
                                if (socket != null) {
                                        socket.Close ();
                                        socket = null;
                                }
+                               ThrowIfException ();
                        }
 
                        void HandleRequest (Socket accepted)
@@ -183,11 +212,17 @@ namespace MonoTests.System.Net
                        }
 
                        public EndPoint EndPoint {
-                               get { return socket.LocalEndPoint; }
+                               get {
+                                       ThrowIfException ();
+                                       return socket.LocalEndPoint;
+                               }
                        }
 
                        public string URI {
-                               get { return string.Format ("http://{0}/", EndPoint); }
+                               get {
+                                       ThrowIfException ();
+                                       return string.Format ("http://{0}/", EndPoint);
+                               }
                        }
                }
        }
index e06ca4bf5d6ae6e16ca43665f144953ba1d2b1c0..fef014541882d3011f1d7bbcd4ea466b8161c2f3 100644 (file)
@@ -19,7 +19,6 @@ using NUnit.Framework;
 namespace MonoTests.System.Net\r
 {\r
        [TestFixture]\r
-       [Category ("RequiresBSDSockets")]\r
        public class DnsTest\r
        {\r
                private String site1Name = "google-public-dns-a.google.com",\r
@@ -30,6 +29,9 @@ namespace MonoTests.System.Net
                private uint site1IP = 134744072, site2IP = 134743044; // Big-Endian\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void AsyncGetHostByName ()\r
                {\r
                        IAsyncResult async = Dns.BeginGetHostByName (site1Name, null, null);\r
@@ -39,6 +41,9 @@ namespace MonoTests.System.Net
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void AsyncGetHostByNameCallback ()\r
                {\r
                        var evt = new ManualResetEvent (false);\r
@@ -61,6 +66,9 @@ namespace MonoTests.System.Net
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void AsyncResolve ()\r
                {\r
                        IAsyncResult async = Dns.BeginResolve (site1Dot, null, null);\r
@@ -71,6 +79,9 @@ namespace MonoTests.System.Net
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void AsyncResolveCallback ()\r
                {\r
                        var evt = new ManualResetEvent (false);\r
@@ -205,6 +216,9 @@ namespace MonoTests.System.Net
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void GetHostByName ()\r
                {\r
                        SubTestGetHostByName (site1Name, site1Dot);\r
@@ -336,6 +350,9 @@ namespace MonoTests.System.Net
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void BeginResolve_HostName_Null ()\r
                {\r
                        try {\r
@@ -352,6 +369,9 @@ namespace MonoTests.System.Net
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void Resolve ()\r
                {\r
                        SubTestResolve (site1Name);\r
@@ -367,6 +387,9 @@ namespace MonoTests.System.Net
                }\r
 \r
                [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void Resolve_HostName_Null ()\r
                {\r
                        try {\r
@@ -381,6 +404,9 @@ namespace MonoTests.System.Net
                }\r
 \r
                [Test] // BeginGetHostEntry (IPAddress, AsyncCallback, Object)\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void BeginGetHostEntry1_Address_Null ()\r
                {\r
                        try {\r
@@ -398,6 +424,9 @@ namespace MonoTests.System.Net
                }\r
 \r
                [Test] // BeginGetHostEntry (String, AsyncCallback, Object)\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void BeginGetHostEntry2_HostNameOrAddress_Null ()\r
                {\r
                        try {\r
@@ -415,6 +444,9 @@ namespace MonoTests.System.Net
                }\r
 \r
                [Test] // BeginGetHostEntry (String, AsyncCallback, Object)\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void BeginGetHostEntry2_HostNameOrAddress_UnspecifiedAddress ()\r
                {\r
                        // IPv4\r
@@ -473,6 +505,9 @@ namespace MonoTests.System.Net
                }\r
 \r
                [Test] // GetHostEntry (String)\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
                public void GetHostEntry2 ()\r
                {\r
                        Dns.GetHostEntry (site1Name); // hostname\r
index 5f4166eecf855549bfd4ea8a51d9ffa556b14cb1..6793d2a48fdeffefa3c47d532c664f915bcc4330 100644 (file)
@@ -25,7 +25,6 @@ using NUnit.Framework;
 namespace MonoTests.System.Net
 {
        [TestFixture]
-       [Category ("RequiresBSDSockets")]
        public class FileWebRequestTest
        {
                private string _tempDirectory;
index 93697cd29294145f8c1466224e44eacb5b210667..771d5d1fb6ae4cf35c3e05db8b41a44cb6175435 100644 (file)
@@ -19,10 +19,12 @@ using System.Threading;
 namespace MonoTests.System.Net 
 {
        [TestFixture]
-       [Category ("RequiresBSDSockets")]
        public class FtpWebRequestTest
        {
-               FtpWebRequest defaultRequest;
+               FtpWebRequest _defaultRequest;
+               FtpWebRequest defaultRequest {
+                       get { return _defaultRequest ?? (_defaultRequest = (FtpWebRequest) WebRequest.Create ("ftp://www.contoso.com")); }
+               }
                
                private string _tempDirectory;
                private string _tempFile;
@@ -49,25 +51,31 @@ namespace MonoTests.System.Net
                                Directory.Delete (_tempDirectory, true);
                }
 
-               [TestFixtureSetUp]
-               public void Init ()
-               {
-                       defaultRequest = (FtpWebRequest) WebRequest.Create ("ftp://www.contoso.com");
-               }
-               
                [Test]
                public void ContentLength ()
                {
                        try {
                                long l = defaultRequest.ContentLength;
+#if FEATURE_NO_BSD_SOCKETS
+                               Assert.Fail ("#1a");
+                       } catch (PlatformNotSupportedException) {
+                               // OK.
+#else
                        } catch (NotSupportedException) {
                                Assert.Fail ("#1"); // Not overriden
+#endif
                        }
 
                        try {
                                defaultRequest.ContentLength = 2;
+#if FEATURE_NO_BSD_SOCKETS
+                               Assert.Fail ("#2a");
+                       } catch (PlatformNotSupportedException) {
+                               // OK.
+#else
                        } catch (NotSupportedException) {
                                Assert.Fail ("#2"); // Not overriden
+#endif
                        }
                }
 
@@ -88,6 +96,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ContentOffset ()
                {
                        try {
@@ -98,6 +109,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Credentials ()
                {
                        try {
@@ -109,6 +123,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Method ()
                {
                        try {
@@ -146,6 +163,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ReadWriteTimeout ()
                {
                        try {
@@ -156,6 +176,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Timeout ()
                {
                        try {
@@ -166,6 +189,9 @@ namespace MonoTests.System.Net
                }
                
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void DefaultValues ()
                {
                        FtpWebRequest request = (FtpWebRequest) WebRequest.Create ("ftp://www.contoso.com");
@@ -183,6 +209,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void RenameTo ()
                {
                        try {
@@ -199,11 +228,31 @@ namespace MonoTests.System.Net
                }
 
                [Test]
-               public void UploadFile1 ()
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
+               public void UploadFile1_v4 ()
+               {
+                       UploadFile1 (false);
+               }
+
+               [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
+               public void UploadFile1_v6 ()
+               {
+                       if (!Socket.OSSupportsIPv6)
+                               Assert.Ignore ("IPv6 not supported.");
+
+                       UploadFile1 (true);
+               }
+
+               void UploadFile1 (bool ipv6)
                {
-                       ServerPut sp = new ServerPut ();
+                       ServerPut sp = new ServerPut (ipv6);
                        sp.Start ();
-                       string uri = String.Format ("ftp://{0}:{1}/uploads/file.txt", sp.IPAddress, sp.Port);
+                       string uri = String.Format ("ftp://{0}:{1}/uploads/file.txt", EncloseIPv6 (sp.IPAddress), sp.Port);
                        try {
                                FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
                                ftp.KeepAlive = false;
@@ -229,15 +278,35 @@ namespace MonoTests.System.Net
                }
 
                [Test]
-               public void UploadFile_WebClient ()
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
+               public void UploadFile_WebClient_v4 ()
+               {
+                       UploadFile_WebClient (false);
+               }
+
+               [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
+               public void UploadFile_WebClient_v6 ()
+               {
+                       if (!Socket.OSSupportsIPv6)
+                               Assert.Ignore ("IPv6 not supported.");
+
+                       UploadFile_WebClient (true);
+               }
+
+               public void UploadFile_WebClient (bool ipv6)
                {
-                       ServerPut sp = new ServerPut ();
+                       ServerPut sp = new ServerPut (ipv6);
                        File.WriteAllText (_tempFile, "0123456789");
                        sp.Start ();
 
                        using (WebClient m_WebClient = new WebClient())
                        {
-                               string uri = String.Format ("ftp://{0}:{1}/uploads/file.txt", sp.IPAddress, sp.Port);
+                               string uri = String.Format ("ftp://{0}:{1}/uploads/file.txt", EncloseIPv6 (sp.IPAddress), sp.Port);
                                
                                m_WebClient.UploadFile(uri, _tempFile);
                        }
@@ -247,15 +316,30 @@ namespace MonoTests.System.Net
                }
 
                [Test]
-               public void DownloadFile1 ()
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
+               public void DownloadFile1_v4 ()
                {
-                       DownloadFile (new ServerDownload ());
+                       DownloadFile (new ServerDownload (false));
+               }
+
+               [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
+               public void DownloadFile1_v6 ()
+               {
+                       if (!Socket.OSSupportsIPv6)
+                               Assert.Ignore ("IPv6 not supported.");
+
+                       DownloadFile (new ServerDownload (true));
                }
 
                void DownloadFile (ServerDownload sp)
                {
                        sp.Start ();
-                       string uri = String.Format ("ftp://{0}:{1}/file.txt", sp.IPAddress, sp.Port);
+                       string uri = String.Format ("ftp://{0}:{1}/file.txt", EncloseIPv6 (sp.IPAddress), sp.Port);
                        try {
                                FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
                                ftp.KeepAlive = false;
@@ -279,19 +363,53 @@ namespace MonoTests.System.Net
                }
 
                [Test]
-               public void DownloadFile2 ()
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
+               public void DownloadFile2_v4 ()
+               {
+                       // Some embedded FTP servers in Industrial Automation Hardware report
+                       // the PWD using backslashes, but allow forward slashes for CWD.
+                       DownloadFile (new ServerDownload (@"\Users\someuser", "/Users/someuser/", false));
+               }
+
+               [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
+               public void DownloadFile2_v6 ()
                {
                        // Some embedded FTP servers in Industrial Automation Hardware report
                        // the PWD using backslashes, but allow forward slashes for CWD.
-                       DownloadFile (new ServerDownload (@"\Users\someuser", "/Users/someuser/"));
+                       DownloadFile (new ServerDownload (@"\Users\someuser", "/Users/someuser/", true));
                }
 
                [Test]
-               public void DeleteFile1 ()
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
+               public void DeleteFile1_v4 ()
+               {
+                       DeleteFile1 (false);
+               }
+
+               [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
+               public void DeleteFile1_v6 ()
+               {
+                       if (!Socket.OSSupportsIPv6)
+                               Assert.Ignore ("IPv6 not supported.");
+
+                       DeleteFile1 (true);
+               }
+
+               void DeleteFile1 (bool ipv6)
                {
-                       ServerDeleteFile sp = new ServerDeleteFile ();
+                       ServerDeleteFile sp = new ServerDeleteFile (ipv6);
                        sp.Start ();
-                       string uri = String.Format ("ftp://{0}:{1}/file.txt", sp.IPAddress, sp.Port);
+                       string uri = String.Format ("ftp://{0}:{1}/file.txt", EncloseIPv6 (sp.IPAddress), sp.Port);
                        try {
                                FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
                                Console.WriteLine (ftp.RequestUri);
@@ -313,11 +431,31 @@ namespace MonoTests.System.Net
                }
 
                [Test]
-               public void ListDirectory1 ()
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
+               public void ListDirectory1_v4 ()
+               {
+                       ListDirectory1 (false);
+               }
+
+               [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
+               public void ListDirectory1_v6 ()
+               {
+                       if (!Socket.OSSupportsIPv6)
+                               Assert.Ignore ("IPv6 not supported.");
+
+                       ListDirectory1 (true);
+               }
+
+               void ListDirectory1 (bool ipv6)
                {
-                       ServerListDirectory sp = new ServerListDirectory ();
+                       ServerListDirectory sp = new ServerListDirectory (ipv6);
                        sp.Start ();
-                       string uri = String.Format ("ftp://{0}:{1}/somedir/", sp.IPAddress, sp.Port);
+                       string uri = String.Format ("ftp://{0}:{1}/somedir/", EncloseIPv6 (sp.IPAddress), sp.Port);
                        try {
                                FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
                                Console.WriteLine (ftp.RequestUri);
@@ -340,7 +478,20 @@ namespace MonoTests.System.Net
                        }
                }
 
+               string EncloseIPv6 (IPAddress address)
+               {
+                       if (address.AddressFamily == AddressFamily.InterNetwork)
+                               return address.ToString ();
+                       
+                       return String.Format ("[{0}]", address.ToString ());
+               }
+
                class ServerListDirectory : FtpServer {
+                       public ServerListDirectory (bool ipv6)
+                               : base (ipv6)
+                       {
+                       }
+
                        protected override void Run ()
                        {
                                Socket client = control.Accept ();
@@ -358,24 +509,12 @@ namespace MonoTests.System.Net
                                }
 
                                string str = reader.ReadLine ();
-                               if (str != "PASV") {
-                                       Where = "PASV";
+                               string resp = FormatPassiveResponse (str);
+                               if (resp == null) {
                                        client.Close ();
                                        return;
                                }
-
-                               IPEndPoint end_data = (IPEndPoint) data.LocalEndPoint;
-                               byte [] addr_bytes = end_data.Address.GetAddressBytes ();
-                               byte [] port = new byte [2];
-                               port[0] = (byte) ((end_data.Port >> 8) & 255);
-                               port[1] = (byte) (end_data.Port & 255);
-                               StringBuilder sb = new StringBuilder ("227 Passive (");
-                               foreach (byte b in addr_bytes) {
-                                       sb.AppendFormat ("{0},", b);    
-                               }
-                               sb.AppendFormat ("{0},", port [0]);     
-                               sb.AppendFormat ("{0})", port [1]);     
-                               writer.WriteLine (sb.ToString ());
+                               writer.WriteLine (resp);
                                writer.Flush ();
 
                                str = reader.ReadLine ();
@@ -402,6 +541,11 @@ namespace MonoTests.System.Net
                }
 
                class ServerDeleteFile : FtpServer {
+                       public ServerDeleteFile (bool ipv6)
+                               : base (ipv6)
+                       {
+                       }
+
                        protected override void Run ()
                        {
                                Socket client = control.Accept ();
@@ -438,12 +582,13 @@ namespace MonoTests.System.Net
 
                        string Pwd, Cwd;
 
-                       public ServerDownload ()
-                               : this (null, null)
+                       public ServerDownload (bool ipv6)
+                               : this (null, null, ipv6)
                        {
                        }
 
-                       public ServerDownload (string pwd, string cwd)
+                       public ServerDownload (string pwd, string cwd, bool ipv6)
+                               : base (ipv6)
                        {
                                Pwd = pwd ?? "/home/someuser";
                                Cwd = cwd ?? "/home/someuser/";
@@ -466,24 +611,12 @@ namespace MonoTests.System.Net
                                }
 
                                string str = reader.ReadLine ();
-                               if (str != "PASV") {
-                                       Where = "PASV";
+                               string resp = FormatPassiveResponse (str);
+                               if (resp == null) {
                                        client.Close ();
                                        return;
                                }
-
-                               IPEndPoint end_data = (IPEndPoint) data.LocalEndPoint;
-                               byte [] addr_bytes = end_data.Address.GetAddressBytes ();
-                               byte [] port = new byte [2];
-                               port[0] = (byte) ((end_data.Port >> 8) & 255);
-                               port[1] = (byte) (end_data.Port & 255);
-                               StringBuilder sb = new StringBuilder ("227 Passive (");
-                               foreach (byte b in addr_bytes) {
-                                       sb.AppendFormat ("{0},", b);    
-                               }
-                               sb.AppendFormat ("{0},", port [0]);     
-                               sb.AppendFormat ("{0})", port [1]);     
-                               writer.WriteLine (sb.ToString ());
+                               writer.WriteLine (resp);
                                writer.Flush ();
 
                                str = reader.ReadLine ();
@@ -512,6 +645,11 @@ namespace MonoTests.System.Net
                class ServerPut : FtpServer {
                        public List<byte> result = new List<byte> ();
                        
+                       public ServerPut (bool ipv6)
+                               : base (ipv6)
+                       {
+                       }
+
                        protected override void Run ()
                        {
                                Socket client = control.Accept ();
@@ -529,24 +667,12 @@ namespace MonoTests.System.Net
                                }
 
                                string str = reader.ReadLine ();
-                               if (str != "PASV") {
-                                       Where = "PASV";
+                               string resp = FormatPassiveResponse (str);
+                               if (resp == null) {
                                        client.Close ();
                                        return;
                                }
-
-                               IPEndPoint end_data = (IPEndPoint) data.LocalEndPoint;
-                               byte [] addr_bytes = end_data.Address.GetAddressBytes ();
-                               byte [] port = new byte [2];
-                               port[0] = (byte) ((end_data.Port >> 8) & 255);
-                               port[1] = (byte) (end_data.Port & 255);
-                               StringBuilder sb = new StringBuilder ("227 Passive (");
-                               foreach (byte b in addr_bytes) {
-                                       sb.AppendFormat ("{0},", b);    
-                               }
-                               sb.AppendFormat ("{0},", port [0]);     
-                               sb.AppendFormat ("{0})", port [1]);     
-                               writer.WriteLine (sb.ToString ());
+                               writer.WriteLine (resp);
                                writer.Flush ();
 
                                str = reader.ReadLine ();
@@ -580,16 +706,18 @@ namespace MonoTests.System.Net
                        protected Socket control;
                        protected Socket data;
                        protected ManualResetEvent evt;
+                       protected bool ipv6;
                        public string Where = "";
 
-                       public FtpServer ()
+                       public FtpServer (bool ipv6)
                        {
-                               control = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
-                               control.Bind (new IPEndPoint (IPAddress.Loopback, 0));
+                               control = new Socket (ipv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+                               control.Bind (new IPEndPoint (ipv6 ? IPAddress.IPv6Loopback : IPAddress.Loopback, 0));
                                control.Listen (1);
-                               data = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
-                               data.Bind (new IPEndPoint (IPAddress.Loopback, 0));
+                               data = new Socket (ipv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+                               data.Bind (new IPEndPoint (ipv6 ? IPAddress.IPv6Loopback : IPAddress.Loopback, 0));
                                data.Listen (1);
+                               this.ipv6 = ipv6;
                        }
 
                        public void Start ()
@@ -673,7 +801,39 @@ namespace MonoTests.System.Net
                                writer.Flush ();
                                return true;
                        }
-                       
+
+                       protected string FormatPassiveResponse (string request)
+                       {
+                               if (ipv6) {
+                                       if (request != "EPSV") {
+                                               Where = "EPSV";
+                                               return null;
+                                       }
+
+                                       IPEndPoint end_data = (IPEndPoint) data.LocalEndPoint;
+                                       return String.Format ("229 Extended Passive (|||{0}|)", end_data.Port);
+                               }
+                               else {
+                                       if (request != "PASV") {
+                                               Where = "PASV";
+                                               return null;
+                                       }
+
+                                       IPEndPoint end_data = (IPEndPoint) data.LocalEndPoint;
+                                       byte [] addr_bytes = end_data.Address.GetAddressBytes ();
+                                       byte [] port = new byte [2];
+                                       port[0] = (byte) ((end_data.Port >> 8) & 255);
+                                       port[1] = (byte) (end_data.Port & 255);
+                                       StringBuilder sb = new StringBuilder ("227 Passive (");
+                                       foreach (byte b in addr_bytes) {
+                                               sb.AppendFormat ("{0},", b);    
+                                       }
+                                       sb.AppendFormat ("{0},", port [0]);     
+                                       sb.AppendFormat ("{0})", port [1]);     
+                                       return sb.ToString ();
+                               }
+                       }
+
                        public IPAddress IPAddress {
                                get { return ((IPEndPoint) control.LocalEndPoint).Address; }
                        }
index b0cedc555a4e8b34674790e2d6744c1a0e269b53..51e2990c0d18129f63dc2a748c8aa79707e1f4fa 100644 (file)
@@ -47,7 +47,6 @@ using MonoTests.Helpers;
 namespace MonoTests.System.Net {
        
        [TestFixture]
-       [Category ("RequiresBSDSockets")]
        public class HttpListener2Test {
                
                private HttpListener _listener = null;
@@ -147,6 +146,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Test1 ()
                {
                        var port = NetworkHelpers.FindFreePort ();
@@ -159,6 +161,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Test2 ()
                {
                        var port = NetworkHelpers.FindFreePort ();
@@ -171,6 +176,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Test3 ()
                {
                        StringBuilder bad = new StringBuilder ();
@@ -210,6 +218,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Test4 ()
                {
                        var port = NetworkHelpers.FindFreePort ();
@@ -222,6 +233,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Test5 ()
                {
                        var port = NetworkHelpers.FindFreePort ();
@@ -234,6 +248,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Test6 ()
                {
                        var port = NetworkHelpers.FindFreePort ();
@@ -247,6 +264,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Test7 ()
                {
                        var port = NetworkHelpers.FindFreePort ();
@@ -263,6 +283,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Test8 ()
                {
                        var port = NetworkHelpers.FindFreePort ();
@@ -280,6 +303,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Test9 ()
                {
                        var port = NetworkHelpers.FindFreePort ();
@@ -295,6 +321,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Test10 ()
                {
                        var port = NetworkHelpers.FindFreePort ();
@@ -311,6 +340,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Test11 ()
                {
                        var port = NetworkHelpers.FindFreePort ();
@@ -325,6 +357,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Test12 ()
                {
                        var port = NetworkHelpers.FindFreePort ();
@@ -339,6 +374,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Test13 ()
                {
                        var port = NetworkHelpers.FindFreePort ();
@@ -356,6 +394,9 @@ namespace MonoTests.System.Net {
                ManualResetEvent test_evt;
                bool test14_error;
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Test14 ()
                {
                        var port = NetworkHelpers.FindFreePort ();
@@ -392,6 +433,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Test15 ()
                {
                        var port = NetworkHelpers.FindFreePort ();
@@ -414,6 +458,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Test16 ()
                {
                        var port = NetworkHelpers.FindFreePort ();
@@ -438,6 +485,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Test17 ()
                {
                        var port = NetworkHelpers.FindFreePort ();
@@ -454,6 +504,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Test_MultipleClosesOnOuputStreamAllowed ()
                {
                        var port = NetworkHelpers.FindFreePort ();
@@ -484,6 +537,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ReceiveCookiesFromClient ()
                {
                        sendCookiePort = NetworkHelpers.FindFreePort ();                        
@@ -530,6 +586,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void SendCookiestoClient ()
                {
                        receiveCookiePort = NetworkHelpers.FindFreePort ();
@@ -581,6 +640,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void MultiResponses ()
                {
                        echoServerPort = NetworkHelpers.FindFreePort ();
@@ -646,9 +708,11 @@ namespace MonoTests.System.Net {
        }
 
        [TestFixture]
-       [Category ("RequiresBSDSockets")]
        public class HttpListenerBugs {
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void TestNonChunkedAsync ()
                {
                        var port = NetworkHelpers.FindFreePort ();
@@ -703,6 +767,9 @@ namespace MonoTests.System.Net {
                // a documented pattern to close the connection
                // 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Test_MultipleConnections ()
                {
                        var port = NetworkHelpers.FindFreePort ();                      
@@ -733,6 +800,9 @@ namespace MonoTests.System.Net {
                // Test case for bug 341443, an pretty old bug, filed on November of 2007.
                //
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Test_HostInUri ()
                {
                        var wait = new ManualResetEvent (false);
@@ -762,6 +832,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test] // bug #513849
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ClosePort ()
                {
                        var port = NetworkHelpers.FindFreePort ();
@@ -785,6 +858,9 @@ namespace MonoTests.System.Net {
                // does not also listen to another interface.
                //
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BindToSingleInterface ()
                {
                        IPAddress [] machineAddress = null;
@@ -811,6 +887,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BindToAllInterfaces ()
                {
                        var h = new HttpListener ();
@@ -823,6 +902,9 @@ namespace MonoTests.System.Net {
 
                // Test case for bug #31209
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Test_EmptyLineAtStart ()
                {
                        var port = NetworkHelpers.FindFreePort ();
index 21589dc6c30914ebe227c22b04a99143a720457e..b09a8180eafd6593fa30a07a9878138a93727de6 100644 (file)
@@ -36,6 +36,9 @@ namespace MonoTests.System.Net {
        public class HttpListenerPrefixCollectionTest {
                // NL -> Not listening -> tests when listener.IsListening == false
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void NL_DefaultProperties ()
                {
                        HttpListener listener = new HttpListener ();
@@ -46,6 +49,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void DefaultProperties ()
                {
                        HttpListener listener = new HttpListener ();
@@ -57,7 +63,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
-               [Category ("RequiresBSDSockets")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void AddOne ()
                {
                        HttpListener listener = new HttpListener ();
@@ -71,7 +79,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
-               [Category ("RequiresBSDSockets")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Duplicate ()
                {
                        HttpListener listener = new HttpListener ();
@@ -86,6 +96,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void EndsWithSlash ()
                {
                        HttpListener listener = new HttpListener ();
@@ -93,6 +106,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void DifferentPath ()
                {
                        HttpListener listener = new HttpListener ();
@@ -102,6 +118,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void NL_Clear ()
                {
                        HttpListener listener = new HttpListener ();
@@ -110,6 +129,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void NL_Remove ()
                {
                        HttpListener listener = new HttpListener ();
@@ -118,6 +140,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void NL_RemoveBadUri ()
                {
                        HttpListener listener = new HttpListener ();
@@ -126,7 +151,11 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (ArgumentException))]
+#endif
                public void NL_AddBadUri ()
                {
                        HttpListener listener = new HttpListener ();
@@ -135,7 +164,11 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (ArgumentException))]
+#endif
                public void NoHostInUrl ()
                {
                        HttpListener listener = new HttpListener ();
@@ -143,6 +176,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void MultipleSlashes ()
                {
                        // this one throws on Start(), not when adding it.
@@ -156,6 +192,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void PercentSign ()
                {
                        HttpListener listener = new HttpListener ();
@@ -169,6 +208,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Disposed1 ()
                {
                        HttpListener listener = new HttpListener ();
@@ -180,7 +222,11 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (ObjectDisposedException))]
+#endif
                public void Disposed2 ()
                {
                        HttpListener listener = new HttpListener ();
@@ -190,7 +236,11 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (ObjectDisposedException))]
+#endif
                public void Disposed3 ()
                {
                        HttpListener listener = new HttpListener ();
@@ -200,7 +250,11 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (ObjectDisposedException))]
+#endif
                public void Disposed4 ()
                {
                        HttpListener listener = new HttpListener ();
@@ -210,7 +264,11 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (ObjectDisposedException))]
+#endif
                public void Disposed5 ()
                {
                        HttpListener listener = new HttpListener ();
@@ -221,6 +279,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Disposed6 ()
                {
                        HttpListener listener = new HttpListener ();
@@ -234,6 +295,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Disposed7 ()
                {
                        HttpListener listener = new HttpListener ();
index c9227fd5b39dc09c6ce53f618c084c05d56b6b7f..d782103f33e33709321e1c7f2211d2b4fccf8a90 100644 (file)
@@ -42,7 +42,6 @@ using MonoTests.Helpers;
 namespace MonoTests.System.Net
 {
        [TestFixture]
-       [Category ("RequiresBSDSockets")]
        public class HttpListenerRequestTest
        {
                [Test]
@@ -151,6 +150,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void HttpMethod ()
                {
                        var port = NetworkHelpers.FindFreePort ();
@@ -165,6 +167,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void HttpBasicAuthScheme ()
                {
                        var port = NetworkHelpers.FindFreePort ();                      
@@ -180,6 +185,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void HttpRequestUriIsNotDecoded ()
                {
                        var port = NetworkHelpers.FindFreePort ();
@@ -194,6 +202,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void HttpRequestIsLocal ()
                {
                        var port = NetworkHelpers.FindFreePort ();
@@ -221,6 +232,9 @@ namespace MonoTests.System.Net
                }
 
                [Test] // #29927
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void HttpRequestUriUnescape ()
                {
                        var prefix = "http://localhost:" + NetworkHelpers.FindFreePort () + "/";
index 70dcede89717281e238f732afa91b55935082777..09d3cb0f3f291b649f7d12290719817cc4d51028 100644 (file)
@@ -37,17 +37,23 @@ using MonoTests.Helpers;
 
 namespace MonoTests.System.Net {
        [TestFixture]
-       [Category ("RequiresBSDSockets")]
        public class HttpListenerTest {
 
-               int port;
+               int? _port;
+               int port {
+                       get { return _port ?? (_port = NetworkHelpers.FindFreePort ()).Value; }
+               }
 
-               [SetUp]
-               public void SetUp () {
-                       port = NetworkHelpers.FindFreePort ();
+               [TearDown]
+               public void Teardown ()
+               {
+                       _port = null;
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void DefaultProperties ()
                {
                        HttpListener listener = new HttpListener ();
@@ -61,6 +67,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Start1 ()
                {
                        HttpListener listener = new HttpListener ();
@@ -68,6 +77,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Stop1 ()
                {
                        HttpListener listener = new HttpListener ();
@@ -75,7 +87,11 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (InvalidOperationException))]
+#endif
                public void GetContext1 ()
                {
                        HttpListener listener = new HttpListener ();
@@ -84,7 +100,11 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (InvalidOperationException))]
+#endif
                public void GetContext2 ()
                {
                        HttpListener listener = new HttpListener ();
@@ -94,7 +114,11 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (InvalidOperationException))]
+#endif
                public void BeginGetContext1 ()
                {
                        HttpListener listener = new HttpListener ();
@@ -103,6 +127,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BeginGetContext2 ()
                {
                        HttpListener listener = new HttpListener ();
@@ -135,6 +162,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void DefaultHttpPort ()
                {
                        if (!CanOpenPort (80))
@@ -148,6 +178,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void DefaultHttpsPort ()
                {
                        if (!CanOpenPort (443))
@@ -161,6 +194,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void TwoListeners_SameAddress ()
                {
                        if (!CanOpenPort (port))
@@ -174,7 +210,11 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (HttpListenerException))]
+#endif
                public void TwoListeners_SameURL ()
                {
                        if (!CanOpenPort (port))
@@ -188,7 +228,11 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (HttpListenerException))]
+#endif
                public void MultipleSlashes ()
                {
                        if (!CanOpenPort (port))
@@ -200,7 +244,11 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (HttpListenerException))]
+#endif
                public void PercentSign ()
                {
                        if (!CanOpenPort (port))
@@ -212,6 +260,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void CloseBeforeStart ()
                {
                        HttpListener listener = new HttpListener ();
@@ -219,6 +270,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void CloseTwice ()
                {
                        if (!CanOpenPort (port))
@@ -231,6 +285,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void StartStopStart ()
                {
                        if (!CanOpenPort (port))
@@ -244,6 +301,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void StartStopDispose ()
                {
                        if (!CanOpenPort (port))
@@ -256,6 +316,9 @@ namespace MonoTests.System.Net {
                }
                
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void AbortBeforeStart ()
                {
                        HttpListener listener = new HttpListener ();
@@ -263,6 +326,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void AbortTwice ()
                {
                        if (!CanOpenPort (port))
@@ -275,6 +341,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void PropertiesWhenClosed1 ()
                {
                        HttpListener listener = new HttpListener ();
@@ -288,7 +357,11 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (ObjectDisposedException))]
+#endif
                public void PropertiesWhenClosed2 ()
                {
                        HttpListener listener = new HttpListener ();
@@ -297,7 +370,11 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (ObjectDisposedException))]
+#endif
                public void PropertiesWhenClosedSet1 ()
                {
                        HttpListener listener = new HttpListener ();
@@ -306,7 +383,11 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (ObjectDisposedException))]
+#endif
                public void PropertiesWhenClosedSet2 ()
                {
                        HttpListener listener = new HttpListener ();
@@ -315,7 +396,11 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (ObjectDisposedException))]
+#endif
                public void PropertiesWhenClosedSet3 ()
                {
                        HttpListener listener = new HttpListener ();
@@ -324,7 +409,11 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (ObjectDisposedException))]
+#endif
                public void PropertiesWhenClosedSet4 ()
                {
                        HttpListener listener = new HttpListener ();
@@ -333,7 +422,11 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (ObjectDisposedException))]
+#endif
                public void PropertiesWhenClosedSet5 ()
                {
                        HttpListener listener = new HttpListener ();
@@ -342,6 +435,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void PropertiesWhenClosed3 ()
                {
                        HttpListener listener = new HttpListener ();
@@ -350,6 +446,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void CloseWhileBegin ()
                {
                        HttpListener listener = new HttpListener ();
@@ -366,6 +465,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void AbortWhileBegin ()
                {
                        HttpListener listener = new HttpListener ();
@@ -382,7 +484,11 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (HttpListenerException))]
+#endif
                public void CloseWhileGet ()
                {
                        // "System.Net.HttpListener Exception : The I/O operation has been aborted
@@ -399,7 +505,11 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (HttpListenerException))]
+#endif
                public void AbortWhileGet ()
                {
                        // "System.Net.HttpListener Exception : The I/O operation has been aborted
@@ -479,6 +589,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ConnectionReuse ()
                {
                        var uri = "http://localhost:" + NetworkHelpers.FindFreePort () + "/";
@@ -536,6 +649,9 @@ namespace MonoTests.System.Net {
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void UserHeaderWithDoubleMultiValue ()
                {
                        string uri = "http://localhost:" + NetworkHelpers.FindFreePort () + "/";
@@ -563,6 +679,9 @@ namespace MonoTests.System.Net {
                }
                
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void HttpClientIsDisconnectedCheckForWriteException()
                {
                        string uri = "http://localhost:" + NetworkHelpers.FindFreePort () + "/";
index 0d5763967b0d01256f3504a608fc899dfa65941e..a597b4cd0a240dd08b9f9f2e1722d4a28bcc6754 100644 (file)
@@ -36,7 +36,6 @@ using MonoTests.Helpers;
 namespace MonoTests.System.Net
 {
        [TestFixture]
-       [Category ("RequiresBSDSockets")]
        public class HttpWebRequestTest
        {
                private Random rand = new Random ();
@@ -45,11 +44,16 @@ namespace MonoTests.System.Net
                [TestFixtureSetUp]
                public void Setup ()
                {
+#if !FEATURE_NO_BSD_SOCKETS
                                ServicePointManager.Expect100Continue = false;
+#endif
                                rand.NextBytes (data64KB);
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Proxy_Null ()
                {
                        HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://www.google.com");
@@ -60,6 +64,9 @@ namespace MonoTests.System.Net
 
                [Test]
                [Category("InetAccess")]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Sync ()
                {
                        HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://www.google.com");
@@ -81,6 +88,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void AddRange ()
                {
                        HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://www.google.com");
@@ -96,6 +106,9 @@ namespace MonoTests.System.Net
                }
 
                [Test] // bug #471782
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void CloseRequestStreamAfterReadingResponse ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -182,6 +195,9 @@ namespace MonoTests.System.Net
                }
 #endif
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Missing_ContentEncoding ()
                {
                        ServicePointManager.CertificatePolicy = new AcceptAllPolicy ();
@@ -204,6 +220,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BadServer_ChunkedClose ()
                {
                        // The server will send a chunked response without a 'last-chunked' mark
@@ -269,6 +288,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BeginGetRequestStream_Body_NotAllowed ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -306,6 +328,9 @@ namespace MonoTests.System.Net
                }
 
                [Test] // bug #465613
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BeginGetRequestStream_NoBuffering ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -455,6 +480,9 @@ namespace MonoTests.System.Net
                }
 
                [Test] // bug #511851
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BeginGetRequestStream_Request_Aborted ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -480,6 +508,9 @@ namespace MonoTests.System.Net
                }
 
                [Test] // bug #511851
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BeginGetResponse_Request_Aborted ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -505,6 +536,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void EndGetRequestStream_AsyncResult_Null ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -583,6 +617,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void EndGetResponse_AsyncResult_Null ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -614,6 +651,9 @@ namespace MonoTests.System.Net
                }
 
                [Test] // bug #429200
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void GetRequestStream ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -636,6 +676,9 @@ namespace MonoTests.System.Net
                }
 
                [Test] // bug #511851
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void GetRequestStream_Request_Aborted ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -931,6 +974,9 @@ namespace MonoTests.System.Net
                }
 
                [Test] // bug #511851
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void GetResponse_Request_Aborted ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -987,6 +1033,9 @@ namespace MonoTests.System.Net
                }
 
                [Test] // bug #324300
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void AllowAutoRedirect ()
                {
                        IPEndPoint localEP = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -1033,6 +1082,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void PostAndRedirect_NoCL ()
                {
                        IPEndPoint localEP = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -1061,6 +1113,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void PostAndRedirect_CL ()
                {
                        IPEndPoint localEP = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -1089,6 +1144,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void PostAnd401 ()
                {
                        IPEndPoint localEP = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -1250,6 +1308,9 @@ namespace MonoTests.System.Net
                }
 
                [Test] // bug #513087
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void NonStandardVerb ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -1361,11 +1422,11 @@ namespace MonoTests.System.Net
 
                        internal void LaunchWebRequest ()
                        {
-                               var req = (HttpWebRequest) WebRequest.Create (url_to_test);
-                               req.Timeout = TimeOutInMilliSeconds;
-
-                               Start = DateTime.Now;
                                try {
+                                       var req = (HttpWebRequest) WebRequest.Create (url_to_test);
+                                       req.Timeout = TimeOutInMilliSeconds;
+
+                                       Start = DateTime.Now;
                                        using (var resp = (HttpWebResponse) req.GetResponse ())
                                        {
                                                var sr = new StreamReader (resp.GetResponseStream (), Encoding.UTF8);
@@ -1416,6 +1477,9 @@ namespace MonoTests.System.Net
                }
 
                [Test] // 1st possible case of https://bugzilla.novell.com/show_bug.cgi?id=MONO74177
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void TestTimeoutPropertyWithServerThatExistsAndRespondsButTooLate ()
                {
                        var ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -1428,6 +1492,7 @@ namespace MonoTests.System.Net
                }
 
                [Test] // 2nd possible case of https://bugzilla.novell.com/show_bug.cgi?id=MONO74177
+               [Category ("RequiresBSDSockets")] // Requires some test refactoring to assert that a PlatformNotSupportedException is thrown, so don't bother (there's plenty of other tests asserting the PlatformNotSupported exceptions).
                public void TestTimeoutWithEndpointThatDoesntExistThrowsConnectFailureBeforeTimeout ()
                {
                        string url = "http://127.0.0.1:8271/"; // some endpoint that is unlikely to exist
@@ -1682,6 +1747,9 @@ namespace MonoTests.System.Net
                        return Encoding.UTF8.GetBytes (sw.ToString ());
                }
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void NtlmAuthentication ()
                {
                        NtlmServer server = new NtlmServer ();
@@ -1824,6 +1892,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BeginGetRequestStream ()
                {
                        this.DoRequest (
@@ -1842,6 +1913,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BeginGetRequestStreamNoClose ()
                {
                        this.DoRequest (
@@ -1859,6 +1933,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BeginGetRequestStreamCancelIfNotAllBytesWritten ()
                {
                        this.DoRequest (
@@ -1883,6 +1960,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void GetRequestStream2 ()
                {
                        this.DoRequest (
@@ -1899,6 +1979,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void GetRequestStreamNotAllBytesWritten ()
                {
                        this.DoRequest (
@@ -1914,6 +1997,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void GetRequestStreamTimeout ()
                {
                        this.DoRequest (
@@ -1929,6 +2015,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BeginWrite ()
                {
                        byte[] received = new byte[data64KB.Length];
@@ -1961,6 +2050,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BeginWriteAfterAbort ()
                {
                        byte [] received = new byte [data64KB.Length];
@@ -1988,6 +2080,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void PrematureStreamCloseAborts ()
                {
                        byte [] received = new byte [data64KB.Length];
@@ -2015,6 +2110,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Write ()
                {
                        byte [] received = new byte [data64KB.Length];
@@ -2086,6 +2184,9 @@ namespace MonoTests.System.Net
                **/
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Read ()
                {
                        byte [] received = new byte [data64KB.Length];
@@ -2113,6 +2214,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ReadTimeout2 ()
                {
                        byte [] received = new byte [data64KB.Length];
@@ -2142,6 +2246,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ReadServerAborted ()
                {
                        byte [] received = new byte [data64KB.Length];
@@ -2166,6 +2273,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BeginGetResponse2 ()
                {
                        byte [] received = new byte [data64KB.Length];
@@ -2196,6 +2306,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BeginGetResponseAborts ()
                {
                        ManualResetEvent aborted = new ManualResetEvent(false);
@@ -2226,6 +2339,9 @@ namespace MonoTests.System.Net
                }
                
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void TestLargeDataReading ()
                {
                        int near2GBStartPosition = rand.Next (int.MaxValue - 500, int.MaxValue);
@@ -2323,7 +2439,11 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (ArgumentNullException))]
+#endif
                public void NullHost ()
                {
                        HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
@@ -2331,6 +2451,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void NoHost ()
                {
                        HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
@@ -2338,7 +2461,11 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (ArgumentException))]
+#endif
                public void EmptyHost ()
                {
                        HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
@@ -2346,6 +2473,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void HostAndPort ()
                {
                        HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com:80");
@@ -2355,6 +2485,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void PortRange ()
                {
                        for (int i = 0; i < 65536; i++) {
@@ -2367,7 +2500,11 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (ArgumentException))]
+#endif
                public void PortBelow ()
                {
                        HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
@@ -2375,7 +2512,11 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (ArgumentException))]
+#endif
                public void PortAbove ()
                {
                        HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
@@ -2383,7 +2524,11 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#else
                [ExpectedException (typeof (ArgumentException))]
+#endif
                public void HostTooLong ()
                {
                        HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
@@ -2403,6 +2548,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void NoDate ()
                {
                        HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
@@ -2410,6 +2558,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void UtcDate ()
                {
                        HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://go-mono.com");
@@ -2419,6 +2570,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void AddAndRemoveDate ()
                {
                        // Neil Armstrong set his foot on Moon
@@ -2452,6 +2606,9 @@ namespace MonoTests.System.Net
                }
                
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                // Bug #12393
                public void TestIPv6Host ()
                {
@@ -2483,6 +2640,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void AllowReadStreamBuffering ()
                {
                        var hr = WebRequest.CreateHttp ("http://www.google.com");
@@ -2680,6 +2840,9 @@ namespace MonoTests.System.Net
 #endif
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void CookieContainerTest ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -2761,10 +2924,12 @@ namespace MonoTests.System.Net
        }
 
        [TestFixture]
-       [Category ("RequiresBSDSockets")]
        public class HttpRequestStreamTest
        {
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BeginRead ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -2820,6 +2985,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void CanRead ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -2842,6 +3010,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void CanSeek ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -2864,6 +3035,9 @@ namespace MonoTests.System.Net
                }
 
                [Test] // bug #324182
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void CanTimeout ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -2886,6 +3060,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void CanWrite ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -2908,6 +3085,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Read ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -2935,6 +3115,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ReadByte ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -2961,6 +3144,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ReadTimeout ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -2983,6 +3169,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Seek ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -3009,6 +3198,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Write_Buffer_Null ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -3035,6 +3227,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Write_Count_Negative ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -3063,6 +3258,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Write_Count_Overflow ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -3091,6 +3289,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Write_Offset_Negative ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -3119,6 +3320,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Write_Offset_Overflow ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -3147,6 +3351,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Write_Request_Aborted ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -3202,6 +3409,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void WriteByte_Request_Aborted ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -3229,6 +3439,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void WriteTimeout ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -3251,6 +3464,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                // Bug6737
                // This test is supposed to fail prior to .NET 4.0
                public void Post_EmptyRequestStream ()
index 10d7d807444ce7527e56c73b601788be68f08664..b2c8e90488c059be03460d907142b53827d3a03f 100644 (file)
@@ -21,10 +21,12 @@ using NUnit.Framework;
 namespace MonoTests.System.Net
 {
        [TestFixture]
-       [Category ("RequiresBSDSockets")]
        public class HttpWebResponseTest
        {
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void CharacterSet_Disposed ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint();
@@ -53,6 +55,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Close_Disposed ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint();
@@ -72,6 +77,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ContentEncoding_Disposed ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint();
@@ -100,6 +108,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ContentLength_Disposed ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint();
@@ -120,6 +131,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ContentType_Disposed ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint();
@@ -148,6 +162,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Cookies_Disposed ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint();
@@ -186,6 +203,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void GetResponseHeader_Disposed ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint();
@@ -214,6 +234,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void GetResponseStream_Disposed ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint();
@@ -242,6 +265,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Headers_Disposed ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint();
@@ -269,6 +295,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void LastModified_Disposed ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint();
@@ -297,6 +326,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Method_Disposed ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint();
@@ -325,6 +357,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ProtocolVersion_Disposed ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint();
@@ -353,6 +388,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ResponseUri_Disposed ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint();
@@ -381,6 +419,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Server_Disposed ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint();
@@ -409,6 +450,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void StatusCode_Disposed ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint();
@@ -429,6 +473,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void StatusDescription_Disposed ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint();
@@ -477,10 +524,12 @@ namespace MonoTests.System.Net
        }
 
        [TestFixture]
-       [Category ("RequiresBSDSockets")]
        public class HttpResponseStreamTest
        {
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BeginRead_Buffer_Null ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint();
@@ -530,6 +579,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void BeginWrite ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint();
@@ -590,6 +642,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void CanSeek ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint();
@@ -617,6 +672,9 @@ namespace MonoTests.System.Net
                }
 
                [Test] // bug #324182
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void CanTimeout ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint();
@@ -644,6 +702,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void CanWrite ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint();
@@ -671,6 +732,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Read ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint();
@@ -708,6 +772,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Read_Buffer_Null ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint();
@@ -757,6 +824,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Read_Count_Negative ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint();
@@ -807,6 +877,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Read_Count_Overflow ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint();
@@ -857,6 +930,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Read_Offset_Negative ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint();
@@ -907,6 +983,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Read_Offset_Overflow ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint();
@@ -1021,6 +1100,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void ReadTimeout ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint();
@@ -1048,6 +1130,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void Write ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint();
@@ -1080,6 +1165,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void WriteTimeout ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint();
index 8922c14f00e65e1afe983af6cd8aa7b6d1a0685c..b6808979e4a2d77c8cfce2252e67568d7466a333 100644 (file)
@@ -29,8 +29,10 @@ public class ServicePointManagerTest
        [SetUp]\r
         public void GetReady () \r
        {\r
+#if !FEATURE_NO_BSD_SOCKETS\r
                maxIdle = ServicePointManager.MaxServicePointIdleTime;\r
                ServicePointManager.MaxServicePointIdleTime = 10;\r
+#endif\r
                googleUri = new Uri ("http://www.google.com");\r
                yahooUri = new Uri ("http://www.yahoo.com");\r
                apacheUri = new Uri ("http://www.apache.org");\r
@@ -39,7 +41,9 @@ public class ServicePointManagerTest
        [TearDown]\r
        public void Finish ()\r
        {\r
+#if !FEATURE_NO_BSD_SOCKETS\r
                ServicePointManager.MaxServicePointIdleTime = maxIdle;\r
+#endif\r
        }\r
 \r
         [Test, ExpectedException (typeof (InvalidOperationException))]\r
@@ -82,6 +86,9 @@ public class ServicePointManagerTest
        }\r
        \r
         [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+       [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
        public void FindServicePoint ()\r
        {\r
                ServicePointManager.MaxServicePoints = 0;\r
index 346f35bdeacd358202f49bad9a130cef91bd0066..6171a2fd25587d85a535b496111aa114628536e0 100644 (file)
@@ -13,7 +13,7 @@ using System;
 using System.Collections;\r
 using System.IO;\r
 using System.Net;\r
-using System.Reflection;
+using System.Reflection;\r
 using System.Threading;\r
 \r
 namespace MonoTests.System.Net\r
@@ -23,6 +23,8 @@ namespace MonoTests.System.Net
 public class ServicePointTest\r
 {\r
        static private int max;\r
+\r
+#if !FEATURE_NO_BSD_SOCKETS\r
        [SetUp]\r
        public void SaveMax () {\r
                max = ServicePointManager.MaxServicePoints;\r
@@ -33,6 +35,7 @@ public class ServicePointTest
        public void RestoreMax () {\r
                ServicePointManager.MaxServicePoints = max;\r
        }\r
+#endif\r
 \r
         [Test]\r
                [Category ("InetAccess")]\r
@@ -54,13 +57,13 @@ public class ServicePointTest
                HttpWebRequest req = (HttpWebRequest) WebRequest.Create ("http://www.google.com");\r
                HttpWebResponse res = (HttpWebResponse) req.GetResponse ();                     \r
                \r
-#if FOUND_SOME_OTHER_URL
-               // URL is no longer found, disabled the test until a more reliable URL is found :P
+#if FOUND_SOME_OTHER_URL\r
+               // URL is no longer found, disabled the test until a more reliable URL is found :P\r
                //WriteServicePoint ("google after getting a response", google);\r
                ServicePoint google2 = ServicePointManager.FindServicePoint (new Uri ("http://www.google.com/dilbert.html"));\r
                Assert.AreEqual (google, google2, "#equals");\r
                res.Close ();\r
-#endif
+#endif\r
                \r
                // in both instances property CurrentConnections is 0 according to ms.net.\r
                // let's see what it says when we do async operations...\r
@@ -87,8 +90,8 @@ public class ServicePointTest
                //Console.WriteLine ("ContentLength: " + res2.ContentLength);\r
                res2.Close ();\r
                \r
-               ServicePoint sp2;
-#if FOUND_SOME_OTHER_URL
+               ServicePoint sp2;\r
+#if FOUND_SOME_OTHER_URL\r
                // unless of course some buffering is taking place.. let's check\r
                Uri uri2 = new Uri ("http://freedesktop.org/Software/pkgconfig/releases/pkgconfig-0.15.0.tar.gz");\r
                sp2 = ServicePointManager.FindServicePoint (uri2);\r
@@ -102,7 +105,7 @@ public class ServicePointTest
                // and so it shows\r
                //Console.WriteLine ("ContentLength: " + res2.ContentLength);\r
                res2.Close ();\r
-#endif
+#endif\r
                \r
                \r
                // what's the limit of the cache?\r
@@ -154,7 +157,7 @@ public class ServicePointTest
 \r
        [Test]\r
        [Category ("InetAccess")]\r
-       [Category ("AndroidNotWorking")] // #A1 fails
+       [Category ("AndroidNotWorking")] // #A1 fails\r
        public void EndPointBind ()\r
        {\r
                Uri uri = new Uri ("http://www.go-mono.com/");\r
@@ -189,6 +192,10 @@ public class ServicePointTest
        }\r
 \r
        [Test] //Covers #19823\r
+#if FEATURE_NO_BSD_SOCKETS\r
+       // This test uses HttpWebRequest\r
+       [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
        public void CloseConnectionGroupConcurency ()\r
        {\r
                // Try with multiple service points\r
@@ -206,36 +213,37 @@ public class ServicePointTest
                }\r
        }\r
 \r
-
-       [Test]
-       public void DnsRefreshTimeout ()
-       {
-               const int dnsRefreshTimeout = 2000;
-
-               ServicePoint sp;
-               IPHostEntry host0, host1, host2;
-               Uri uri;
-               PropertyInfo hostEntryProperty;
-
-               ServicePointManager.DnsRefreshTimeout = dnsRefreshTimeout;
-
-               uri = new Uri ("http://localhost/");
-               sp = ServicePointManager.FindServicePoint (uri);
-
-               hostEntryProperty = typeof (ServicePoint).GetProperty ("HostEntry", BindingFlags.NonPublic | BindingFlags.Instance);
-
-               host0 = hostEntryProperty.GetValue (sp, null) as IPHostEntry;
-               host1 = hostEntryProperty.GetValue (sp, null) as IPHostEntry;
-
-               Assert.AreSame (host0, host1, "HostEntry should result in the same IPHostEntry object.");
-
-               Thread.Sleep (dnsRefreshTimeout * 2);
-               host2 = hostEntryProperty.GetValue (sp, null) as IPHostEntry;
-
-               Assert.AreNotSame(host0, host2, "HostEntry should result in a new IPHostEntry " +
-                               "object when DnsRefreshTimeout is reached.");
-       }
-
+\r
+       [Test]\r
+       [Category ("RequiresBSDSockets")] // Tests internals, so it doesn't make sense to assert that PlatformNotSupportedExceptions are thrown.\r
+       public void DnsRefreshTimeout ()\r
+       {\r
+               const int dnsRefreshTimeout = 2000;\r
+\r
+               ServicePoint sp;\r
+               IPHostEntry host0, host1, host2;\r
+               Uri uri;\r
+               PropertyInfo hostEntryProperty;\r
+\r
+               ServicePointManager.DnsRefreshTimeout = dnsRefreshTimeout;\r
+\r
+               uri = new Uri ("http://localhost/");\r
+               sp = ServicePointManager.FindServicePoint (uri);\r
+\r
+               hostEntryProperty = typeof (ServicePoint).GetProperty ("HostEntry", BindingFlags.NonPublic | BindingFlags.Instance);\r
+\r
+               host0 = hostEntryProperty.GetValue (sp, null) as IPHostEntry;\r
+               host1 = hostEntryProperty.GetValue (sp, null) as IPHostEntry;\r
+\r
+               Assert.AreSame (host0, host1, "HostEntry should result in the same IPHostEntry object.");\r
+\r
+               Thread.Sleep (dnsRefreshTimeout * 2);\r
+               host2 = hostEntryProperty.GetValue (sp, null) as IPHostEntry;\r
+\r
+               Assert.AreNotSame(host0, host2, "HostEntry should result in a new IPHostEntry " +\r
+                               "object when DnsRefreshTimeout is reached.");\r
+       }\r
+\r
 // Debug code not used now, but could be useful later\r
 /*\r
        private void WriteServicePoint (string label, ServicePoint sp)\r
index 1a6c45179aa8f65d7fb4e63909010ca984332d54..3b048781f29ad6a15109241cb99f362d55b2f521 100644 (file)
@@ -21,7 +21,6 @@ using MonoTests.Helpers;
 namespace MonoTests.System.Net
 {
        [TestFixture]
-       [Category ("RequiresBSDSockets")]
        public class WebClientTest
        {
                private string _tempFolder;
@@ -1419,6 +1418,9 @@ namespace MonoTests.System.Net
 
                [Test]
                [Category ("AndroidNotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void UploadValues1 ()
                {
                        IPEndPoint ep = NetworkHelpers.LocalEphemeralEndPoint ();
@@ -1669,6 +1671,10 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               // We throw a PlatformNotSupportedException deeper, which is caught and re-thrown as WebException
+               [ExpectedException (typeof (WebException))]
+#endif
                public void GetWebRequestOverriding ()
                {
                        GetWebRequestOverridingTestClass testObject = new GetWebRequestOverridingTestClass ();
@@ -1783,6 +1789,9 @@ namespace MonoTests.System.Net
                 
                [Test]
                [Category ("AndroidNotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void UploadStringAsyncCancelEvent ()
                {
                        UploadAsyncCancelEventTest (9301, (webClient, uri, cancelEvent) =>
@@ -1800,6 +1809,9 @@ namespace MonoTests.System.Net
 
                [Test]
                [Category ("AndroidNotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void UploadDataAsyncCancelEvent ()
                {
                        UploadAsyncCancelEventTest (9302, (webClient, uri, cancelEvent) =>
@@ -1816,6 +1828,9 @@ namespace MonoTests.System.Net
                
                [Test]
                [Category ("AndroidNotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void UploadValuesAsyncCancelEvent ()
                {
                        UploadAsyncCancelEventTest (9303, (webClient, uri, cancelEvent) =>
@@ -1832,6 +1847,9 @@ namespace MonoTests.System.Net
 
                [Test]
                [Category ("AndroidNotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void UploadFileAsyncCancelEvent ()
                {
                        UploadAsyncCancelEventTest (9304,(webClient, uri, cancelEvent) =>
@@ -1851,6 +1869,9 @@ namespace MonoTests.System.Net
 
                [Test]
                [Category ("AndroidNotWorking")] // Test suite hangs if the tests runs as part of the entire BCL suite. Works when only this fixture is ran
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void UploadFileAsyncContentType ()
                {
                        var port = NetworkHelpers.FindFreePort ();
index 1e21e43dc211db035e6e52457c7bb46e0e1e1a5a..c2bdeba6ab2575f999a524d17b242c27e93e2cfd 100644 (file)
@@ -124,6 +124,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void AddRestricted ()
                {
                        col = CreateRestrictedHeaders ();
@@ -236,6 +239,9 @@ namespace MonoTests.System.Net
                }
 
                [Test]
+#if FEATURE_NO_BSD_SOCKETS
+               [ExpectedException (typeof (PlatformNotSupportedException))]
+#endif
                public void RemoveRestricted ()
                {
                        col = CreateRestrictedHeaders ();
index 34ce1a370a1d4ed737bfe721ce2d4e03104c27b0..074c97d6982dcc787a0b3d64df4676c298bd9141 100644 (file)
 //\r
 \r
 using NUnit.Framework;\r
-using MonoTests.Helpers;
+using MonoTests.Helpers;\r
 using System;\r
 using System.Net;\r
-using System.Threading;
+using System.Threading;\r
 using System.Collections;\r
 using System.Runtime.Serialization;\r
 using Socks = System.Net.Sockets;\r
@@ -193,6 +193,9 @@ namespace MonoTests.System.Net {
                }\r
 \r
        [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+       [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
        public void All ()\r
        {\r
                WebRequest req = WebRequest.Create ("http://www.contoso.com");\r
@@ -264,6 +267,9 @@ namespace MonoTests.System.Net {
        }\r
 \r
        [Test]\r
+#if FEATURE_NO_BSD_SOCKETS\r
+       [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
        public void DefaultWebProxy ()\r
        {\r
                WebProxy proxy = new WebProxy ("proxy.intern.com", 83);\r
@@ -318,14 +324,18 @@ namespace MonoTests.System.Net {
        }\r
 \r
        [Test] //BNC#323452\r
-       // Throws exception with Status == Timeout. The same code behaves as the test expects when run from a regular app.
-       // Might be an issue with the test suite. To investigate.
-       [Category("AndroidNotWorking")] 
+       // Throws exception with Status == Timeout. The same code behaves as the test expects when run from a regular app.\r
+       // Might be an issue with the test suite. To investigate.\r
+       [Category("AndroidNotWorking")] \r
        public void TestFailedConnection ()\r
        {\r
                try {\r
                        WebRequest.Create ("http://127.0.0.1:0/non-existant.txt").GetResponse ();\r
                        Assert.Fail ("Should have raised an exception");\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               } catch (PlatformNotSupportedException) {\r
+                       // Expected\r
+#endif\r
                } catch (Exception e) {\r
                        Assert.IsTrue (e is WebException, "Got " + e.GetType ().Name + ": " + e.Message);\r
                        //#if NET_2_0 e.Message == "Unable to connect to the remote server"\r
@@ -342,7 +352,7 @@ namespace MonoTests.System.Net {
        }\r
 \r
        [Test] //BNC#323452\r
-       [Category ("AndroidNotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran
+       [Category ("AndroidNotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran\r
        public void TestFailedResolution ()\r
        {\r
                try {\r
@@ -359,6 +369,10 @@ namespace MonoTests.System.Net {
                                Assert.Ignore ("Misbehaving DNS server.");\r
 \r
                        Assert.Fail ("Should have raised an exception");\r
+#if FEATURE_NO_BSD_SOCKETS\r
+               } catch (PlatformNotSupportedException) {\r
+                       // Expected\r
+#endif\r
                } catch (Exception e) {\r
                        Assert.IsTrue (e is WebException);\r
                        //#if NET_2_0 e.Message == "The underlying connection was closed: The remote name could not be resolved."\r
@@ -412,53 +426,55 @@ namespace MonoTests.System.Net {
        {\r
                internal TestWebRequest3 () { }\r
        }\r
-
-       [Test] // Covers #41477
-       [Category ("RequiresBSDSockets")]
-       public void TestReceiveCancelation ()
-       {
-               var uri = "http://localhost:" + NetworkHelpers.FindFreePort () + "/";
-
-               HttpListener listener = new HttpListener ();
-               listener.Prefixes.Add (uri);
-               listener.Start ();
-
-               try {
-                       for (var i = 0; i < 10; i++) {
-                               var request = WebRequest.CreateHttp (uri);
-                               request.Method = "GET";
-
-                               var tokenSource = new CancellationTokenSource ();
-                               tokenSource.Token.Register(() => request.Abort ());
-
-                               var responseTask = request.GetResponseAsync ();
-
-                               var context = listener.GetContext ();
-                               byte[] outBuffer = new byte[8 * 1024];
-                               context.Response.OutputStream.WriteAsync (outBuffer, 0, outBuffer.Length);
-
-                               Assert.IsTrue (responseTask.Wait (1000), "Timeout #1");
-
-                               WebResponse response = responseTask.Result;
-                               var stream = response.GetResponseStream ();
-
-                               byte[] buffer = new byte[8 * 1024];
-                               var taskRead = stream.ReadAsync (buffer, 0, buffer.Length, tokenSource.Token);
-
-                               tokenSource.Cancel ();
-
-                               Assert.IsTrue (taskRead.Wait (1000), "Timeout #2");
-
-                               var byteRead = taskRead.Result;
-                       }
-               } catch (AggregateException ex) {
-                       var webEx = ex.InnerException as WebException;
-                       Assert.IsNotNull(webEx, "Inner exception is not a WebException");
-                       Assert.AreEqual (webEx.Status, WebExceptionStatus.RequestCanceled);
-               }
-
-               listener.Close ();
-       }
+\r
+       [Test] // Covers #41477\r
+#if FEATURE_NO_BSD_SOCKETS\r
+       [ExpectedException (typeof (PlatformNotSupportedException))]\r
+#endif\r
+       public void TestReceiveCancelation ()\r
+       {\r
+               var uri = "http://localhost:" + NetworkHelpers.FindFreePort () + "/";\r
+\r
+               HttpListener listener = new HttpListener ();\r
+               listener.Prefixes.Add (uri);\r
+               listener.Start ();\r
+\r
+               try {\r
+                       for (var i = 0; i < 10; i++) {\r
+                               var request = WebRequest.CreateHttp (uri);\r
+                               request.Method = "GET";\r
+\r
+                               var tokenSource = new CancellationTokenSource ();\r
+                               tokenSource.Token.Register(() => request.Abort ());\r
+\r
+                               var responseTask = request.GetResponseAsync ();\r
+\r
+                               var context = listener.GetContext ();\r
+                               byte[] outBuffer = new byte[8 * 1024];\r
+                               context.Response.OutputStream.WriteAsync (outBuffer, 0, outBuffer.Length);\r
+\r
+                               Assert.IsTrue (responseTask.Wait (1000), "Timeout #1");\r
+\r
+                               WebResponse response = responseTask.Result;\r
+                               var stream = response.GetResponseStream ();\r
+\r
+                               byte[] buffer = new byte[8 * 1024];\r
+                               var taskRead = stream.ReadAsync (buffer, 0, buffer.Length, tokenSource.Token);\r
+\r
+                               tokenSource.Cancel ();\r
+\r
+                               Assert.IsTrue (taskRead.Wait (1000), "Timeout #2");\r
+\r
+                               var byteRead = taskRead.Result;\r
+                       }\r
+               } catch (AggregateException ex) {\r
+                       var webEx = ex.InnerException as WebException;\r
+                       Assert.IsNotNull(webEx, "Inner exception is not a WebException");\r
+                       Assert.AreEqual (webEx.Status, WebExceptionStatus.RequestCanceled);\r
+               }\r
+\r
+               listener.Close ();\r
+       }\r
 }\r
 \r
 }\r
index 6ebd708ee02c0ea845f317e30f6d1f58230f7a20..52815f273a5d484798999909ad82cdd3e5e7e0dd 100644 (file)
@@ -1678,6 +1678,9 @@ namespace MonoTests.System
                [Category ("NotDotNet")]
                public void UnixAbsoluteFilePath_WithSpecialChars1 ()
                {
+                       if (isWin32)
+                               Assert.Ignore ();
+
                        Uri unixuri = new Uri ("/home/user/a@b");
                        Assert.AreEqual ("file", unixuri.Scheme, "UnixAbsoluteFilePath_WithSpecialChars #1");
                }
@@ -1686,6 +1689,9 @@ namespace MonoTests.System
                [Category ("NotDotNet")]
                public void UnixAbsoluteFilePath_WithSpecialChars2 ()
                {
+                       if (isWin32)
+                               Assert.Ignore ();
+
                        Uri unixuri = new Uri ("/home/user/a:b");
                        Assert.AreEqual ("file", unixuri.Scheme, "UnixAbsoluteFilePath_WithSpecialChars #2");
                }
@@ -1694,6 +1700,9 @@ namespace MonoTests.System
                [Category ("NotDotNet")]
                public void UnixAbsolutePath_ReplaceRelative ()
                {
+                       if (isWin32)
+                               Assert.Ignore ();
+
                        var u1 = new Uri ("/Users/demo/Projects/file.xml");
                        var u2 = new Uri (u1, "b.jpg");
 
@@ -1884,6 +1893,11 @@ namespace MonoTests.System
                [Test]
                public void DotNetRelativeOrAbsoluteTest ()
                {
+                       // On windows the path /foo is parsed as BadFormat and checking
+                       // if this is relative or absolute doesn't make sense.
+                       if (isWin32)
+                               Assert.Ignore();
+
                        FieldInfo useDotNetRelativeOrAbsoluteField = null;
                        bool useDotNetRelativeOrAbsoluteOld = false;
 
@@ -2043,6 +2057,9 @@ namespace MonoTests.System
                [Test]
                public void ImplicitUnixFileWithUnicode ()
                {
+                       if (isWin32)
+                               Assert.Ignore ();
+
                        string value = "/Library/Frameworks/System.Runtim…ee";
                        Uri uri;
                        Assert.IsTrue (Uri.TryCreate (value, UriKind.Absolute, out uri));
index 9b2e93b730cdb572d1d230c1da5f8566e66c9087..a39ac73d0afa0949dcd04172bdeae22851faef21 100644 (file)
@@ -312,6 +312,8 @@ namespace MonoTests.System
                        Assert.IsFalse (Uri.IsWellFormedUriString (null, UriKind.Absolute), "null");
                        Assert.IsFalse (Uri.IsWellFormedUriString ("data", UriKind.Absolute), "data");
                        Assert.IsTrue (Uri.IsWellFormedUriString ("http://www.go-mono.com/Main_Page#1", UriKind.Absolute), "http/hex");
+                       Assert.IsTrue (Uri.IsWellFormedUriString ("test", UriKind.RelativeOrAbsolute), "rel1");
+                       Assert.IsTrue (Uri.IsWellFormedUriString ("/test", UriKind.RelativeOrAbsolute), "rel2");
                }
 
                [Test]
index 1b4c33d5db27c04d48f883f9bcd5f22366b42b37..5224c4de657da210008dee056c6c4536a0e68aeb 100644 (file)
@@ -11,11 +11,9 @@ System.Diagnostics/FileVersionInfo.cs
 System.Diagnostics/MonitoringDescriptionAttribute.cs
 System.Diagnostics/Process.cs
 System.Diagnostics/ProcessModule.cs
-System.Diagnostics/ProcessModuleCollection.cs
 System.Diagnostics/ProcessPriorityClass.cs
 System.Diagnostics/ProcessStartInfo.cs
 System.Diagnostics/ProcessThread.cs
-System.Diagnostics/ProcessThreadCollection.cs
 System.Diagnostics/ProcessWindowStyle.cs
 System.Diagnostics/Stopwatch.cs
 System.Diagnostics/ThreadPriorityLevel.cs
@@ -28,6 +26,7 @@ System.IO.Compression/DeflateStream.cs
 System.IO.Compression/GZipStream.cs
 System.IO/InternalBufferOverflowException.cs
 System.IO/InvalidDataException.cs
+System.IO/IODescriptionAttribute.cs
 System.IO/ErrorEventArgs.cs
 System.IO/ErrorEventHandler.cs
 System.IO/FileSystemEventArgs.cs
@@ -119,35 +118,11 @@ System.Net.Security/SslPolicyErrors.cs
 System.Net.Security/SslStream.cs
 System.Net/SocketPermissionAttribute.cs
 System.Net/SocketPermission.cs
-../referencesource/System/net/System/Net/Sockets/AddressFamily.cs
-../referencesource/System/net/System/Net/Sockets/IOControlCode.cs
-../referencesource/System/net/System/Net/Sockets/IPPacketInformation.cs
-../referencesource/System/net/System/Net/Sockets/LingerOption.cs
-../referencesource/System/net/System/Net/Sockets/MulticastOption.cs
-../referencesource/System/net/System/Net/Sockets/ProtocolFamily.cs
-../referencesource/System/net/System/Net/Sockets/ProtocolType.cs
 System.Net.Sockets/SafeSocketHandle.cs
-../referencesource/System/net/System/Net/Sockets/SelectMode.cs
-System.Net.Sockets/SendPacketsElement.cs
 System.Net.Sockets/Socket.cs
 System.Net.Sockets/SocketAsyncEventArgs.cs
-System.Net.Sockets/SocketAsyncOperation.cs
 System.Net.Sockets/SocketAsyncResult.cs
-../referencesource/System/net/System/Net/Sockets/SocketErrors.cs
-../referencesource/System/net/System/Net/SocketException.cs
-../referencesource/System/net/System/Net/Sockets/SocketFlags.cs
-../referencesource/System/net/System/Net/Sockets/SocketInformation.cs
-../referencesource/System/net/System/Net/Sockets/SocketInformationOptions.cs
 System.Net.Sockets/SocketOperation.cs
-../referencesource/System/net/System/Net/Sockets/SocketOptionLevel.cs
-../referencesource/System/net/System/Net/Sockets/SocketOptionName.cs
-../referencesource/System/net/System/Net/Sockets/SocketShutdown.cs
-../referencesource/System/net/System/Net/Sockets/SocketType.cs
-System.Net.Sockets/TcpClient.cs
-System.Net.Sockets/TcpListener.cs
-../referencesource/System/net/System/Net/Sockets/TransmitFileFlags.cs
-System.Net.Sockets/UdpClient.cs
-../referencesource/System/net/System/Net/Sockets/UdpReceiveResult.cs
 System.Net/AuthenticationManager.cs
 System.Net/BasicClient.cs
 System.Net/BindIPEndPoint.cs
@@ -173,6 +148,7 @@ System.Net/HttpListenerContext.cs
 System.Net/HttpListenerPrefixCollection.cs
 System.Net/HttpListenerRequest.cs
 System.Net/HttpListenerResponse.cs
+System.Net/HttpListenerResponseHelper.cs
 System.Net/HttpListenerTimeoutManager.cs
 System.Net/HttpRequestCreator.cs
 System.Net/HttpStreamAsyncResult.cs
@@ -227,7 +203,6 @@ System.Security.Authentication.ExtendedProtection/ExtendedProtectionPolicy.cs
 System.Security.Authentication.ExtendedProtection/ExtendedProtectionPolicyTypeConverter.cs
 System.Security.Authentication.ExtendedProtection/PolicyEnforcement.cs
 System.Security.Authentication.ExtendedProtection/ProtectionScenario.cs
-System.Security.Authentication.ExtendedProtection/ServiceNameCollection.cs
 System.Security.Authentication.ExtendedProtection.Configuration/ConfigUtil.cs
 System.Security.Authentication.ExtendedProtection.Configuration/ExtendedProtectionPolicyElement.cs
 System.Security.Authentication.ExtendedProtection.Configuration/ServiceNameElement.cs
@@ -293,22 +268,59 @@ Mono.Net.Security/IMonoSslStream.cs
 Mono.Net.Security/LegacySslStream.cs
 Mono.Net.Security/MobileAuthenticatedStream.cs
 Mono.Net.Security/MobileTlsContext.cs
-Mono.Net.Security/MonoLegacyTlsProvider.cs
+Mono.Net.Security/LegacyTlsProvider.cs
 Mono.Net.Security/MonoSslStreamImpl.cs
 Mono.Net.Security/MonoSslStreamWrapper.cs
 Mono.Net.Security/MonoTlsProviderFactory.cs
-Mono.Net.Security/MonoTlsProviderImpl.cs
 Mono.Net.Security/MonoTlsProviderWrapper.cs
 Mono.Net.Security/MonoTlsStream.cs
 Mono.Net.Security/NoReflectionHelper.cs
 Mono.Net.Security/SystemCertificateValidator.cs
 
+Mono.Btls/MonoBtlsBio.cs
+Mono.Btls/MonoBtlsContext.cs
+Mono.Btls/MonoBtlsError.cs
+Mono.Btls/MonoBtlsException.cs
+Mono.Btls/MonoBtlsKey.cs
+Mono.Btls/MonoBtlsObject.cs
+Mono.Btls/MonoBtlsPkcs12.cs
+Mono.Btls/MonoBtlsProvider.cs
+Mono.Btls/MonoBtlsSsl.cs
+Mono.Btls/MonoBtlsSslCtx.cs
+Mono.Btls/MonoBtlsSslError.cs
+Mono.Btls/MonoBtlsStream.cs
+Mono.Btls/MonoBtlsUtils.cs
+Mono.Btls/MonoBtlsX509.cs
+Mono.Btls/MonoBtlsX509Chain.cs
+Mono.Btls/MonoBtlsX509Crl.cs
+Mono.Btls/MonoBtlsX509Error.cs
+Mono.Btls/MonoBtlsX509Exception.cs
+Mono.Btls/MonoBtlsX509FileType.cs
+Mono.Btls/MonoBtlsX509Format.cs
+Mono.Btls/MonoBtlsX509Lookup.cs
+Mono.Btls/MonoBtlsX509LookupMonoCollection.cs
+Mono.Btls/MonoBtlsX509LookupMono.cs
+Mono.Btls/MonoBtlsX509LookupType.cs
+Mono.Btls/MonoBtlsX509Name.cs
+Mono.Btls/MonoBtlsX509NameList.cs
+Mono.Btls/MonoBtlsX509NameEntryType.cs
+Mono.Btls/MonoBtlsX509Purpose.cs
+Mono.Btls/MonoBtlsX509Revoked.cs
+Mono.Btls/MonoBtlsX509Store.cs
+Mono.Btls/MonoBtlsX509StoreCtx.cs
+Mono.Btls/MonoBtlsX509StoreManager.cs
+Mono.Btls/MonoBtlsX509StoreType.cs
+Mono.Btls/MonoBtlsX509TrustKind.cs
+Mono.Btls/MonoBtlsX509VerifyFlags.cs
+Mono.Btls/MonoBtlsX509VerifyParam.cs
+Mono.Btls/X509CertificateImplBtls.cs
+Mono.Btls/X509ChainImplBtls.cs
+
 ReferenceSources/AutoWebProxyScriptEngine.cs
 ReferenceSources/AssertWrapper.cs
 ReferenceSources/CAPI.cs
 ReferenceSources/EnvironmentHelpers.cs
 ReferenceSources/HttpApi.cs
-ReferenceSources/Internal.cs
 ReferenceSources/LocalAppContextSwitches.cs
 ReferenceSources/HttpSysSettings.cs
 ReferenceSources/Logging.cs
@@ -706,6 +718,7 @@ ReferenceSources/Win32Exception.cs
 ../referencesource/System/net/System/Net/_ProxyChain.cs
 ../referencesource/System/net/System/Net/_ScatterGatherBuffers.cs
 ../referencesource/System/net/System/Net/_Semaphore.cs
+../referencesource/System/net/System/Net/_ServiceNameStore.cs
 ../referencesource/System/net/System/Net/_TimerThread.cs
 ../referencesource/System/net/System/Net/_WebProxyDataBuilder.cs
 ../referencesource/System/net/System/Net/AuthenticationScheme.cs
@@ -748,6 +761,7 @@ ReferenceSources/Win32Exception.cs
 ../referencesource/System/net/System/Net/UnicodeEncodingConformance.cs
 ../referencesource/System/net/System/Net/ServicePointManager.cs
 ../referencesource/System/net/System/Net/SocketAddress.cs
+../referencesource/System/net/System/Net/SocketException.cs
 ../referencesource/System/net/System/Net/webclient.cs
 ../referencesource/System/net/System/Net/WebException.cs
 ../referencesource/System/net/System/Net/WebExceptionStatus.cs
@@ -767,8 +781,30 @@ ReferenceSources/Win32Exception.cs
 
 ../referencesource/System/net/System/Net/Configuration/DefaultProxySection.cs
 
+../referencesource/System/net/System/Net/Sockets/AddressFamily.cs
+../referencesource/System/net/System/Net/Sockets/IOControlCode.cs
+../referencesource/System/net/System/Net/Sockets/IPPacketInformation.cs
 ../referencesource/System/net/System/Net/Sockets/IPProtectionLevel.cs
+../referencesource/System/net/System/Net/Sockets/LingerOption.cs
+../referencesource/System/net/System/Net/Sockets/MulticastOption.cs
 ../referencesource/System/net/System/Net/Sockets/NetworkStream.cs
+../referencesource/System/net/System/Net/Sockets/ProtocolFamily.cs
+../referencesource/System/net/System/Net/Sockets/ProtocolType.cs
+../referencesource/System/net/System/Net/Sockets/SelectMode.cs
+../referencesource/System/net/System/Net/Sockets/Socket.cs
+../referencesource/System/net/System/Net/Sockets/SocketErrors.cs
+../referencesource/System/net/System/Net/Sockets/SocketFlags.cs
+../referencesource/System/net/System/Net/Sockets/SocketInformation.cs
+../referencesource/System/net/System/Net/Sockets/SocketInformationOptions.cs
+../referencesource/System/net/System/Net/Sockets/SocketOptionLevel.cs
+../referencesource/System/net/System/Net/Sockets/SocketOptionName.cs
+../referencesource/System/net/System/Net/Sockets/SocketShutdown.cs
+../referencesource/System/net/System/Net/Sockets/SocketType.cs
+../referencesource/System/net/System/Net/Sockets/TCPClient.cs
+../referencesource/System/net/System/Net/Sockets/TCPListener.cs
+../referencesource/System/net/System/Net/Sockets/TransmitFileFlags.cs
+../referencesource/System/net/System/Net/Sockets/UdpReceiveResult.cs
+../referencesource/System/net/System/Net/Sockets/UDPClient.cs
 
 ../referencesource/System/net/System/Net/NetworkInformation/DuplicateAddressDetectionState.cs
 ../referencesource/System/net/System/Net/NetworkInformation/GatewayIPAddressInformation.cs
@@ -802,7 +838,6 @@ ReferenceSources/Win32Exception.cs
 ../referencesource/System/net/System/Net/NetworkInformation/SystemGatewayIPAddressInformation.cs
 ../referencesource/System/net/System/Net/NetworkInformation/SystemIPAddressInformation.cs
 ../referencesource/System/net/System/Net/NetworkInformation/SystemMulticastIPAddressInformation.cs
-../referencesource/System/net/System/Net/NetworkInformation/SystemUnicastIPAddressInformation.cs
 ../referencesource/System/net/System/Net/NetworkInformation/SystemTcpConnection.cs
 ../referencesource/System/net/System/Net/NetworkInformation/TcpConnection.cs
 ../referencesource/System/net/System/Net/NetworkInformation/TcpState.cs
@@ -814,6 +849,8 @@ ReferenceSources/Win32Exception.cs
 ../referencesource/System/net/System/Net/NetworkInformation/nodetype.cs
 ../referencesource/System/net/System/Net/NetworkInformation/pingexception.cs
 
+../referencesource/System/sys/system/Diagnostics/CodeAnalysis/ExcludeFromCodeCoverageAttribute.cs
+
 ../referencesource/System/sys/system/IO/ports/InternalResources.cs
 
 ../referencesource/System/sys/system/runtime/interopservices/DefaultParameterValueAttribute.cs
@@ -824,7 +861,10 @@ ReferenceSources/Win32Exception.cs
 ../referencesource/System/sys/system/threading/Barrier.cs
 ../referencesource/System/sys/system/threading/semaphore.cs
 
+../referencesource/System/sys/system/windows/markup/ValueSerializerAttribute.cs
+
 ../referencesource/System/security/system/security/Authentication/ExtendedProtection/TokenBinding.cs
+../referencesource/System/security/system/security/Authentication/ExtendedProtection/ServiceNameCollection.cs
 
 ../referencesource/System/security/system/security/cryptography/oid.cs
 
@@ -832,6 +872,9 @@ ReferenceSources/Win32Exception.cs
 
 ../referencesource/System/security/system/security/permissions/typedescriptorpermission.cs
 
+../referencesource/System/services/monitoring/system/diagnosticts/ProcessModuleCollection.cs
+../referencesource/System/services/monitoring/system/diagnosticts/ProcessThreadCollection.cs
+
 ../referencesource/System/services/timers/system/timers/ElapsedEventHandler.cs
 ../referencesource/System/services/timers/system/timers/Timer.cs
 ../referencesource/System/services/timers/system/timers/TimersDescriptionAttribute.cs
@@ -934,7 +977,6 @@ ReferenceSources/Win32Exception.cs
 ../Mono.Security/Mono.Security.Interface/HashAlgorithmType.cs
 ../Mono.Security/Mono.Security.Interface/IBufferOffsetSize.cs
 ../Mono.Security/Mono.Security.Interface/IMonoTlsEventSink.cs
-../Mono.Security/Mono.Security.Interface/IMonoTlsContext.cs
 ../Mono.Security/Mono.Security.Interface/IMonoSslStream.cs
 ../Mono.Security/Mono.Security.Interface/MonoTlsConnectionInfo.cs
 ../Mono.Security/Mono.Security.Interface/MonoTlsProvider.cs
index 686004bd3b16c16676290b8c5bec21daaa5b0827..c2950c536caf33f5d6f337df9463118118f248e8 100644 (file)
@@ -1,3 +1,4 @@
 #include mobile_System.dll.sources
 System/AndroidPlatform.cs
 Mono.Net.Security/MonoTlsProviderFactory.Droid.cs
+Mono.Btls/MonoBtlsX509LookupAndroid.cs
diff --git a/mcs/class/System/monotouch_watch_System.dll.exclude.sources b/mcs/class/System/monotouch_watch_System.dll.exclude.sources
new file mode 100644 (file)
index 0000000..1f1f612
--- /dev/null
@@ -0,0 +1,184 @@
+../Mono.Security/Mono.Security.Authenticode/PrivateKey.cs
+../Mono.Security/Mono.Security.Cryptography/MD5SHA1.cs
+../Mono.Security/Mono.Security.Cryptography/TlsHMAC.cs
+../Mono.Security/Mono.Security.Interface/Alert.cs
+../Mono.Security/Mono.Security.Interface/CertificateValidationHelper.cs
+../Mono.Security/Mono.Security.Interface/CipherAlgorithmType.cs
+../Mono.Security/Mono.Security.Interface/CipherSuiteCode.cs
+../Mono.Security/Mono.Security.Interface/ExchangeAlgorithmType.cs
+../Mono.Security/Mono.Security.Interface/HashAlgorithmType.cs
+../Mono.Security/Mono.Security.Interface/IBufferOffsetSize.cs
+../Mono.Security/Mono.Security.Interface/IMonoSslStream.cs
+../Mono.Security/Mono.Security.Interface/IMonoTlsContext.cs
+../Mono.Security/Mono.Security.Interface/IMonoTlsEventSink.cs
+../Mono.Security/Mono.Security.Interface/MonoTlsConnectionInfo.cs
+../Mono.Security/Mono.Security.Interface/MonoTlsProvider.cs
+../Mono.Security/Mono.Security.Interface/MonoTlsProviderFactory.Apple.cs
+../Mono.Security/Mono.Security.Interface/MonoTlsProviderFactory.cs
+../Mono.Security/Mono.Security.Interface/MonoTlsSettings.cs
+../Mono.Security/Mono.Security.Interface/TlsException.cs
+../Mono.Security/Mono.Security.Interface/TlsProtocolCode.cs
+../Mono.Security/Mono.Security.Interface/TlsProtocols.cs
+../Mono.Security/Mono.Security.Protocol.Ntlm/ChallengeResponse.cs
+../Mono.Security/Mono.Security.Protocol.Ntlm/ChallengeResponse2.cs
+../Mono.Security/Mono.Security.Protocol.Ntlm/MessageBase.cs
+../Mono.Security/Mono.Security.Protocol.Ntlm/NtlmAuthLevel.cs
+../Mono.Security/Mono.Security.Protocol.Ntlm/NtlmFlags.cs
+../Mono.Security/Mono.Security.Protocol.Ntlm/NtlmSettings.cs
+../Mono.Security/Mono.Security.Protocol.Ntlm/Type1Message.cs
+../Mono.Security/Mono.Security.Protocol.Ntlm/Type2Message.cs
+../Mono.Security/Mono.Security.Protocol.Ntlm/Type3Message.cs
+../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsClientCertificate.cs
+../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsClientCertificateVerify.cs
+../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsClientFinished.cs
+../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsClientHello.cs
+../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsClientKeyExchange.cs
+../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerCertificate.cs
+../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerCertificateRequest.cs
+../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerFinished.cs
+../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerHello.cs
+../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerHelloDone.cs
+../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerKeyExchange.cs
+../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientCertificate.cs
+../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientCertificateVerify.cs
+../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientFinished.cs
+../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientHello.cs
+../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientKeyExchange.cs
+../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerCertificate.cs
+../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerCertificateRequest.cs
+../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerFinished.cs
+../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerHello.cs
+../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerHelloDone.cs
+../Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerKeyExchange.cs
+../Mono.Security/Mono.Security.Protocol.Tls.Handshake/ClientCertificateType.cs
+../Mono.Security/Mono.Security.Protocol.Tls.Handshake/HandshakeMessage.cs
+../Mono.Security/Mono.Security.Protocol.Tls.Handshake/HandshakeType.cs
+../Mono.Security/Mono.Security.Protocol.Tls/Alert.cs
+../Mono.Security/Mono.Security.Protocol.Tls/CipherAlgorithmType.cs
+../Mono.Security/Mono.Security.Protocol.Tls/CipherSuite.cs
+../Mono.Security/Mono.Security.Protocol.Tls/CipherSuiteCollection.cs
+../Mono.Security/Mono.Security.Protocol.Tls/CipherSuiteFactory.cs
+../Mono.Security/Mono.Security.Protocol.Tls/ClientContext.cs
+../Mono.Security/Mono.Security.Protocol.Tls/ClientRecordProtocol.cs
+../Mono.Security/Mono.Security.Protocol.Tls/ClientSessionCache.cs
+../Mono.Security/Mono.Security.Protocol.Tls/ContentType.cs
+../Mono.Security/Mono.Security.Protocol.Tls/Context.cs
+../Mono.Security/Mono.Security.Protocol.Tls/DebugHelper.cs
+../Mono.Security/Mono.Security.Protocol.Tls/ExchangeAlgorithmType.cs
+../Mono.Security/Mono.Security.Protocol.Tls/HandshakeState.cs
+../Mono.Security/Mono.Security.Protocol.Tls/HashAlgorithmType.cs
+../Mono.Security/Mono.Security.Protocol.Tls/HttpsClientStream.cs
+../Mono.Security/Mono.Security.Protocol.Tls/RecordProtocol.cs
+../Mono.Security/Mono.Security.Protocol.Tls/RSASslSignatureDeformatter.cs
+../Mono.Security/Mono.Security.Protocol.Tls/RSASslSignatureFormatter.cs
+../Mono.Security/Mono.Security.Protocol.Tls/SecurityCompressionType.cs
+../Mono.Security/Mono.Security.Protocol.Tls/SecurityParameters.cs
+../Mono.Security/Mono.Security.Protocol.Tls/SecurityProtocolType.cs
+../Mono.Security/Mono.Security.Protocol.Tls/ServerContext.cs
+../Mono.Security/Mono.Security.Protocol.Tls/ServerRecordProtocol.cs
+../Mono.Security/Mono.Security.Protocol.Tls/SslCipherSuite.cs
+../Mono.Security/Mono.Security.Protocol.Tls/SslClientStream.cs
+../Mono.Security/Mono.Security.Protocol.Tls/SslHandshakeHash.cs
+../Mono.Security/Mono.Security.Protocol.Tls/SslServerStream.cs
+../Mono.Security/Mono.Security.Protocol.Tls/SslStreamBase.cs
+../Mono.Security/Mono.Security.Protocol.Tls/TlsCipherSuite.cs
+../Mono.Security/Mono.Security.Protocol.Tls/TlsClientSettings.cs
+../Mono.Security/Mono.Security.Protocol.Tls/TlsException.cs
+../Mono.Security/Mono.Security.Protocol.Tls/TlsServerSettings.cs
+../Mono.Security/Mono.Security.Protocol.Tls/TlsStream.cs
+Mono.Http/NtlmClient.cs
+Mono.Net.Security/AsyncProtocolRequest.cs
+Mono.Net.Security/CallbackHelpers.cs
+Mono.Net.Security/ChainValidationHelper.cs
+Mono.Net.Security/IMonoSslStream.cs
+Mono.Net.Security/IMonoTlsProvider.cs
+Mono.Net.Security/LegacySslStream.cs
+Mono.Net.Security/LegacySslStream.cs
+Mono.Net.Security/LegacyTlsProvider.cs
+Mono.Net.Security/LegacyTlsProvider.cs
+Mono.Net.Security/MobileAuthenticatedStream.cs
+Mono.Net.Security/MobileTlsContext.cs
+Mono.Net.Security/MonoSslStreamImpl.cs
+Mono.Net.Security/MonoSslStreamWrapper.cs
+Mono.Net.Security/MonoTlsProviderFactory.Apple.cs
+Mono.Net.Security/MonoTlsProviderFactory.cs
+Mono.Net.Security/MonoTlsProviderImpl.cs
+Mono.Net.Security/MonoTlsProviderWrapper.cs
+Mono.Net.Security/MonoTlsStream.cs
+Mono.Net.Security/NoReflectionHelper.cs
+Mono.Net.Security/SystemCertificateValidator.cs
+System.Net.Mail/SmtpClient.cs
+System.Net.Security/SslStream.cs
+System.Net.Sockets/TcpClient.cs
+System.Net.Sockets/TcpListener.cs
+System.Net.WebSockets/ClientWebSocket.cs
+System.Net/AuthenticationManager.cs
+System.Net/ChunkedInputStream.cs
+System.Net/EndPointListener.cs
+System.Net/EndPointManager.cs
+System.Net/FtpAsyncResult.cs
+System.Net/FtpDataStream.cs
+System.Net/FtpRequestCreator.cs
+System.Net/FtpRequestCreator.cs
+System.Net/FtpStatus.cs
+System.Net/FtpWebRequest.cs
+System.Net/FtpWebResponse.cs
+System.Net/HttpConnection.cs
+System.Net/HttpListener.cs
+System.Net/HttpListenerContext.cs
+System.Net/HttpListenerPrefixCollection.cs
+System.Net/HttpListenerRequest.cs
+System.Net/HttpListenerResponse.cs
+System.Net/HttpWebRequest.cs
+System.Net/HttpWebResponse.cs
+System.Net/IWebConnectionState.cs
+System.Net/ListenerAsyncResult.cs
+System.Net/NtlmClient.cs
+System.Net/ResponseStream.cs
+System.Net/ServicePoint.cs
+System.Net/ServicePointManager.cs
+System.Net/WebConnection.cs
+System.Net/WebConnectionData.cs
+System.Net/WebConnectionGroup.cs
+System.Net/WebConnectionStream.cs
+Mono.Btls/MonoBtlsBio.cs
+Mono.Btls/MonoBtlsContext.cs
+Mono.Btls/MonoBtlsError.cs
+Mono.Btls/MonoBtlsException.cs
+Mono.Btls/MonoBtlsKey.cs
+Mono.Btls/MonoBtlsObject.cs
+Mono.Btls/MonoBtlsPkcs12.cs
+Mono.Btls/MonoBtlsProvider.cs
+Mono.Btls/MonoBtlsSsl.cs
+Mono.Btls/MonoBtlsSslCtx.cs
+Mono.Btls/MonoBtlsSslError.cs
+Mono.Btls/MonoBtlsStream.cs
+Mono.Btls/MonoBtlsUtils.cs
+Mono.Btls/MonoBtlsX509.cs
+Mono.Btls/MonoBtlsX509Chain.cs
+Mono.Btls/MonoBtlsX509Crl.cs
+Mono.Btls/MonoBtlsX509Error.cs
+Mono.Btls/MonoBtlsX509Exception.cs
+Mono.Btls/MonoBtlsX509FileType.cs
+Mono.Btls/MonoBtlsX509Format.cs
+Mono.Btls/MonoBtlsX509Lookup.cs
+Mono.Btls/MonoBtlsX509LookupMonoCollection.cs
+Mono.Btls/MonoBtlsX509LookupMono.cs
+Mono.Btls/MonoBtlsX509LookupType.cs
+Mono.Btls/MonoBtlsX509Name.cs
+Mono.Btls/MonoBtlsX509NameList.cs
+Mono.Btls/MonoBtlsX509NameEntryType.cs
+Mono.Btls/MonoBtlsX509Purpose.cs
+Mono.Btls/MonoBtlsX509Revoked.cs
+Mono.Btls/MonoBtlsX509Store.cs
+Mono.Btls/MonoBtlsX509StoreCtx.cs
+Mono.Btls/MonoBtlsX509StoreManager.cs
+Mono.Btls/MonoBtlsX509StoreType.cs
+Mono.Btls/MonoBtlsX509TrustKind.cs
+Mono.Btls/MonoBtlsX509VerifyFlags.cs
+Mono.Btls/MonoBtlsX509VerifyParam.cs
+Mono.Btls/X509CertificateImplBtls.cs
+Mono.Btls/X509ChainImplBtls.cs
+../referencesource/System/net/System/Net/Sockets/TCPClient.cs
+../referencesource/System/net/System/Net/Sockets/TCPListener.cs
+../referencesource/System/net/System/Net/Sockets/UDPClient.cs
index 7c0bd5983a519e8499a57c6c30b9be525658c105..f7e73d81e36ecfd3775457593b9630c74bd0083d 100644 (file)
@@ -1 +1,20 @@
 #include monotouch_System.dll.sources
+System.Net.Mail/SmtpClient.platformnotsupported.cs
+System.Net.Security/SslStream.platformnotsupported.cs
+System.Net.Sockets/TcpClient.platformnotsupported.cs
+System.Net.Sockets/TcpListener.platformnotsupported.cs
+System.Net.Sockets/UdpClient.platformnotsupported.cs
+System.Net.WebSockets/ClientWebSocket.platformnotsupported.cs
+System.Net/AuthenticationManager.platformnotsupported.cs
+System.Net/FtpRequestCreator.platformnotsupported.cs
+System.Net/FtpWebRequest.platformnotsupported.cs
+System.Net/FtpWebResponse.platformnotsupported.cs
+System.Net/HttpListener.platformnotsupported.cs
+System.Net/HttpListenerContext.platformnotsupported.cs
+System.Net/HttpListenerPrefixCollection.platformnotsupported.cs
+System.Net/HttpListenerRequest.platformnotsupported.cs
+System.Net/HttpListenerResponse.platformnotsupported.cs
+System.Net/HttpWebRequest.platformnotsupported.cs
+System.Net/HttpWebResponse.platformnotsupported.cs
+System.Net/ServicePoint.platformnotsupported.cs
+System.Net/ServicePointManager.platformnotsupported.cs
diff --git a/mcs/class/System/monotouch_watch_runtime_System.dll.exclude.sources b/mcs/class/System/monotouch_watch_runtime_System.dll.exclude.sources
new file mode 100644 (file)
index 0000000..8869410
--- /dev/null
@@ -0,0 +1 @@
+#include monotouch_watch_System.dll.exclude.sources
index 7c0bd5983a519e8499a57c6c30b9be525658c105..c8c328c5ce6605a85a7e34f0db5e1f2c7335d9bb 100644 (file)
@@ -1 +1 @@
-#include monotouch_System.dll.sources
+#include monotouch_watch_System.dll.sources
old mode 100644 (file)
new mode 100755 (executable)
index e4b4ae1..002d592
@@ -404,7 +404,12 @@ namespace System.IO.Packaging {
                                throw new FileFormatException ("Stream length cannot be zero with FileMode.Open");
 
                        Stream s = File.Open (path, packageMode, packageAccess, packageShare);
-                       return Open (s, packageMode, packageAccess, true);
+                       try {
+                               return Open (s, packageMode, packageAccess, true);
+                       } catch {
+                               s.Close  ();
+                               throw;
+                       }
                }
 
                static Package OpenCore (Stream stream, FileMode packageMode, FileAccess packageAccess, bool ownsStream)
index e83008d4452c91ba8e6e4ffe00dc566eaba6f6e5..6fddadb2f9167de43dcc81e91ce1875d9548c3f6 100644 (file)
@@ -259,6 +259,7 @@ namespace MonoTests.System.Windows {
                }
 
                [Test]
+               [SetCulture ("en-us")]
                public void ToStringTest ()
                {
                        Rect r = new Rect (1.0, 2.5, 3, 4);
index f0a6e5c2ab68e58364251c20accbd8f2784cb8ca..c36c7ce5608ab796e4a659abf9e57fae4d39ae48 100644 (file)
@@ -181,6 +181,7 @@ System.Windows.Threading/DispatcherUnhandledExceptionEventArgs.cs
 System.Windows.Threading/DispatcherUnhandledExceptionEventHandler.cs
 System.Windows.Threading/DispatcherUnhandledExceptionFilterEventArgs.cs
 System.Windows.Threading/DispatcherUnhandledExceptionFilterEventHandler.cs
+ZipSharp/NativeVersion.cs
 ZipSharp/IOFunctions.cs
 ZipSharp/ZipArchive.cs
 ZipSharp/UnzipArchive.cs
index 04e6a3e9ca79e7919b62d2e245dc17959a5f1be2..d339f84425e9fdd4e006e4c9384664170a678629 100644 (file)
@@ -21,16 +21,28 @@ namespace zipsharp
        internal delegate IntPtr OpenFileFunc (IntPtr opaque, string filename, int mode);
 
        [UnmanagedFunctionPointerAttribute (CallingConvention.Cdecl)]
-       internal delegate /* ulong */ IntPtr ReadFileFunc (IntPtr opaque, IntPtr stream, IntPtr buffer, /* ulong */ IntPtr size);
+       internal delegate /* uLong */ uint ReadFileFunc32 (IntPtr opaque, IntPtr stream, IntPtr buffer, /* uLong */ uint size);
 
        [UnmanagedFunctionPointerAttribute (CallingConvention.Cdecl)]
-       internal delegate /* ulong */ IntPtr WriteFileFunc (IntPtr opaque, IntPtr stream, IntPtr buffer, /* ulong */ IntPtr size);
+       internal delegate /* uLong */ uint WriteFileFunc32 (IntPtr opaque, IntPtr stream, IntPtr buffer, /* uLong */ uint size);
 
        [UnmanagedFunctionPointerAttribute (CallingConvention.Cdecl)]
-       internal delegate /* long */ IntPtr TellFileFunc (IntPtr opaque, IntPtr stream);
+       internal delegate /* long */ int TellFileFunc32 (IntPtr opaque, IntPtr stream);
 
        [UnmanagedFunctionPointerAttribute (CallingConvention.Cdecl)]
-       internal delegate /* long */ IntPtr SeekFileFunc (IntPtr opaque, IntPtr stream, /* ulong */ IntPtr offset, int origin);
+       internal delegate /* long */ int SeekFileFunc32 (IntPtr opaque, IntPtr stream, /* uLong */ uint offset, int origin);
+
+       [UnmanagedFunctionPointerAttribute (CallingConvention.Cdecl)]
+       internal delegate /* uLong */ ulong ReadFileFunc64 (IntPtr opaque, IntPtr stream, IntPtr buffer, /* uLong */ ulong size);
+
+       [UnmanagedFunctionPointerAttribute (CallingConvention.Cdecl)]
+       internal delegate /* uLong */ ulong WriteFileFunc64 (IntPtr opaque, IntPtr stream, IntPtr buffer, /* uLong */ ulong size);
+
+       [UnmanagedFunctionPointerAttribute (CallingConvention.Cdecl)]
+       internal delegate /* long */ long TellFileFunc64 (IntPtr opaque, IntPtr stream);
+
+       [UnmanagedFunctionPointerAttribute (CallingConvention.Cdecl)]
+       internal delegate /* long */ long SeekFileFunc64 (IntPtr opaque, IntPtr stream, /* uLong */ ulong offset, int origin);
 
        [UnmanagedFunctionPointerAttribute (CallingConvention.Cdecl)]
        internal delegate int CloseFileFunc (IntPtr opaque, IntPtr stream);
@@ -39,13 +51,26 @@ namespace zipsharp
        internal delegate int TestErrorFileFunc (IntPtr opaque, IntPtr stream);
 
        [StructLayout (LayoutKind.Sequential)]
-       internal struct ZlibFileFuncDef
+       internal struct ZlibFileFuncDef32
+       {
+               [MarshalAs (UnmanagedType.FunctionPtr)] public OpenFileFunc      zopen_file;
+               [MarshalAs (UnmanagedType.FunctionPtr)] public ReadFileFunc32    zread_file;
+               [MarshalAs (UnmanagedType.FunctionPtr)] public WriteFileFunc32   zwrite_file;
+               [MarshalAs (UnmanagedType.FunctionPtr)] public TellFileFunc32    ztell_file;
+               [MarshalAs (UnmanagedType.FunctionPtr)] public SeekFileFunc32    zseek_file;
+               [MarshalAs (UnmanagedType.FunctionPtr)] public CloseFileFunc     zclose_file;
+               [MarshalAs (UnmanagedType.FunctionPtr)] public TestErrorFileFunc zerror_file;
+               public IntPtr            opaque;
+       }
+
+       [StructLayout (LayoutKind.Sequential)]
+       internal struct ZlibFileFuncDef64
        {
                [MarshalAs (UnmanagedType.FunctionPtr)] public OpenFileFunc      zopen_file;
-               [MarshalAs (UnmanagedType.FunctionPtr)] public ReadFileFunc      zread_file;
-               [MarshalAs (UnmanagedType.FunctionPtr)] public WriteFileFunc     zwrite_file;
-               [MarshalAs (UnmanagedType.FunctionPtr)] public TellFileFunc      ztell_file;
-               [MarshalAs (UnmanagedType.FunctionPtr)] public SeekFileFunc      zseek_file;
+               [MarshalAs (UnmanagedType.FunctionPtr)] public ReadFileFunc64    zread_file;
+               [MarshalAs (UnmanagedType.FunctionPtr)] public WriteFileFunc64   zwrite_file;
+               [MarshalAs (UnmanagedType.FunctionPtr)] public TellFileFunc64    ztell_file;
+               [MarshalAs (UnmanagedType.FunctionPtr)] public SeekFileFunc64    zseek_file;
                [MarshalAs (UnmanagedType.FunctionPtr)] public CloseFileFunc     zclose_file;
                [MarshalAs (UnmanagedType.FunctionPtr)] public TestErrorFileFunc zerror_file;
                public IntPtr            opaque;
index 3b3c3dc5d87dcf92a442a238a6dd325c1de151fe..673a2c921ebe3f240d4e0110c503983553c10d34 100644 (file)
@@ -65,43 +65,58 @@ namespace zipsharp
                        return unztell(handle).ToInt64 ();
                }
 
-               public static long CurrentFileLength (UnzipHandle handle)
+               public static long CurrentFileLength32 (UnzipHandle handle)
                {
-                       UnzipFileInfo info;
-                       int result = unzGetCurrentFileInfo (handle, out info, null, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, null,  IntPtr.Zero);
-                       
-                       if (result != 0)
-                               return -1;
-                       else
-                               return (long)info.UncompressedSize;
+                       UnzipFileInfo32 info;
+                       int result = unzGetCurrentFileInfo_32 (handle, out info, null, 0, IntPtr.Zero, 0, null,  0);
+                       return result != 0 ? -1 : (long) info.uncompressed_size;
                }
-               
-               static string GetCurrentFileName (UnzipHandle handle)
+
+               public static long CurrentFileLength64 (UnzipHandle handle)
                {
-                       UnzipFileInfo info;
-                       int result = unzGetCurrentFileInfo (handle, out info, null, IntPtr.Zero, IntPtr.Zero, new IntPtr (0), null,  IntPtr.Zero);
+                       UnzipFileInfo64 info;
+                       int result = unzGetCurrentFileInfo_64 (handle, out info, null, 0, IntPtr.Zero, 0, null,  0);
+                       return result != 0 ? -1 : (long) info.uncompressed_size;
+               }
 
-                       if (result != 0)
+               static string GetCurrentFileName32 (UnzipHandle handle)
+               {
+                       UnzipFileInfo32 info;
+                       if (unzGetCurrentFileInfo_32 (handle, out info, null, 0, IntPtr.Zero, 0, null, 0) != 0)
                                return null;
-                       
-                       StringBuilder sbName = new StringBuilder ((int)info.SizeFilename+1); // +1 to account for extra \0 at the end
-                       result = unzGetCurrentFileInfo (handle, out info, sbName, new IntPtr (sbName.Capacity), IntPtr.Zero, new IntPtr (0), null,  IntPtr.Zero);
-                       
-                       if (result != 0)
+                       var sbName = new StringBuilder ((int) info.size_filename + 1); // +1 to account for extra \0 at the end
+                       if (unzGetCurrentFileInfo_32 (handle, out info, sbName, (uint) sbName.Capacity, IntPtr.Zero, 0, null, 0) != 0)
                                return null;
-                       else
-                               return sbName.ToString ();
+                       return sbName.ToString ();
                }
 
-               public static string[] GetFiles (UnzipHandle handle)
+               static string GetCurrentFileName64 (UnzipHandle handle)
                {
-                       List<string> files = new List<string> ();
+                       UnzipFileInfo64 info;
+                       if (unzGetCurrentFileInfo_64 (handle, out info, null, 0, IntPtr.Zero, 0, null, 0) != 0)
+                               return null;
+                       var sbName = new StringBuilder ((int) info.size_filename + 1); // +1 to account for extra \0 at the end
+                       if (unzGetCurrentFileInfo_64 (handle, out info, sbName, (uint) sbName.Capacity, IntPtr.Zero, 0, null, 0) != 0)
+                               return null;
+                       return sbName.ToString ();
+               }
 
-                       GoToFirstFile (handle);
+               public static string[] GetFiles32 (UnzipHandle handle)
+               {
+                       return GetFiles (handle, GetCurrentFileName32);
+               }
+
+               public static string[] GetFiles64 (UnzipHandle handle)
+               {
+                       return GetFiles (handle, GetCurrentFileName64);
+               }
 
+               private static string[] GetFiles (UnzipHandle handle, Func<UnzipHandle, string> getCurrentFileName)
+               {
+                       GoToFirstFile (handle);
+                       var files = new List<string> ();
                        string name;
-                       while ((name = GetCurrentFileName(handle)) != null)
-                       {
+                       while ((name = getCurrentFileName (handle)) != null) {
                                files.Add (name);
                                if (!NativeUnzip.GoToNextFile (handle))
                                        break;
@@ -121,9 +136,17 @@ namespace zipsharp
                        return unzGoToNextFile(handle) == 0;
                }
                
-               public static UnzipHandle OpenArchive (ZlibFileFuncDef fileFuncs)
+               public static UnzipHandle OpenArchive32 (ZlibFileFuncDef32 fileFuncs)
+               {
+                       UnzipHandle handle = unzOpen2_32 ("", ref fileFuncs);
+                       if (handle.IsInvalid)
+                               throw new Exception ("Could not open unzip archive");
+                       return handle;
+               }
+
+               public static UnzipHandle OpenArchive64 (ZlibFileFuncDef64 fileFuncs)
                {
-                       UnzipHandle handle = unzOpen2 ("", ref fileFuncs);
+                       UnzipHandle handle = unzOpen2_64 ("", ref fileFuncs);
                        if (handle.IsInvalid)
                                throw new Exception ("Could not open unzip archive");
                        return handle;
@@ -160,9 +183,13 @@ namespace zipsharp
                [DllImport ("MonoPosixHelper", CallingConvention=CallingConvention.Cdecl)]
                static extern int unzGoToFirstFile (UnzipHandle handle);
 
-               [DllImport ("MonoPosixHelper", CallingConvention=CallingConvention.Cdecl)]
-               static extern UnzipHandle unzOpen2 (string path,
-                                                           ref ZlibFileFuncDef pzlib_filefunc_def);
+               [DllImport ("MonoPosixHelper", EntryPoint="unzOpen2", CallingConvention=CallingConvention.Cdecl)]
+               static extern UnzipHandle unzOpen2_32 (string path,
+                                                      ref ZlibFileFuncDef32 pzlib_filefunc_def);
+
+               [DllImport ("MonoPosixHelper", EntryPoint="unzOpen2", CallingConvention=CallingConvention.Cdecl)]
+               static extern UnzipHandle unzOpen2_64 (string path,
+                                                      ref ZlibFileFuncDef64 pzlib_filefunc_def);
 
                [DllImport ("MonoPosixHelper", CallingConvention=CallingConvention.Cdecl)]
                static extern int unzGoToNextFile (UnzipHandle handle);
@@ -178,15 +205,25 @@ namespace zipsharp
                                                       out int level,
                                                       int raw);
 
-               [DllImport ("MonoPosixHelper", CallingConvention=CallingConvention.Cdecl)]
-               static extern int unzGetCurrentFileInfo (UnzipHandle handle,
-                                                                out UnzipFileInfo pfile_info,
-                                                                StringBuilder szFileName,
-                                                                IntPtr fileNameBufferSize,   // uLong
-                                                                IntPtr extraField,           // void *
-                                                                IntPtr extraFieldBufferSize, // uLong
-                                                                StringBuilder szComment,
-                                                                IntPtr commentBufferSize);   // uLong
+               [DllImport ("MonoPosixHelper", EntryPoint="unzGetCurrentFileInfo", CallingConvention=CallingConvention.Cdecl)]
+               static extern int unzGetCurrentFileInfo_32 (UnzipHandle handle,
+                                                           out UnzipFileInfo32 pfile_info,
+                                                           StringBuilder szFileName,
+                                                           uint fileNameBufferSize,   // uLong
+                                                           IntPtr extraField,         // void *
+                                                           uint extraFieldBufferSize, // uLong
+                                                           StringBuilder szComment,
+                                                           uint commentBufferSize);   // uLong
+
+               [DllImport ("MonoPosixHelper", EntryPoint="unzGetCurrentFileInfo", CallingConvention=CallingConvention.Cdecl)]
+               static extern int unzGetCurrentFileInfo_64 (UnzipHandle handle,
+                                                           out UnzipFileInfo64 pfile_info,
+                                                           StringBuilder szFileName,
+                                                           ulong fileNameBufferSize,   // uLong
+                                                           IntPtr extraField,          // void *
+                                                           ulong extraFieldBufferSize, // uLong
+                                                           StringBuilder szComment,
+                                                           ulong commentBufferSize);   // uLong
 
                [DllImport ("MonoPosixHelper", CallingConvention=CallingConvention.Cdecl)]
                static unsafe extern int unzReadCurrentFile (UnzipHandle handle,
diff --git a/mcs/class/WindowsBase/ZipSharp/NativeVersion.cs b/mcs/class/WindowsBase/ZipSharp/NativeVersion.cs
new file mode 100755 (executable)
index 0000000..ce7112e
--- /dev/null
@@ -0,0 +1,20 @@
+using System;
+
+namespace zipsharp {
+       static class NativeVersion {
+
+               /// <summary>
+               /// ZipSharp code needs different code paths
+               /// depending on the size of the C long type on the underlying platform. On
+               /// gcc/clang the C long type follows the bitness of the targeted architecture,
+               /// it's 32-bit on 32-bit systems and 64-bit on 64-bit systems. With the VS
+               /// compiler however, the C long type is always 32-bit regardless of the
+               /// target architecture. zlib and minizip uses C long in a number of 
+               /// different function signatures and structs. 
+               /// 
+               /// This field is used to easily determine if the 32 bit version of 
+               /// functions and structs should be used when interacting with zlib.
+               /// </summary>
+               public static readonly bool Use32Bit = IntPtr.Size == 4 || Environment.OSVersion.Platform != PlatformID.Unix;
+       }
+}
index 225fc1acaba49b94a58b6999f54388d202c154e1..b556a9052e661d40251b895a24648346f7413466 100644 (file)
@@ -31,24 +31,44 @@ namespace zipsharp
                        zipCloseFileInZip (handle);
                }
 
-               public static ZipHandle OpenArchive (ZlibFileFuncDef funcDef, Append append)
+               public static ZipHandle OpenArchive32 (ZlibFileFuncDef32 funcDef, Append append)
                {
-                       ZipHandle h = zipOpen2 ("", (int) append, IntPtr.Zero, ref funcDef);
+                       ZipHandle h = zipOpen2_32 ("", (int) append, IntPtr.Zero, ref funcDef);
                        if (h.IsInvalid)
                                throw new Exception ("Could not open the zip archive");
                        return h;
                }
-               
-               public static int OpenFile (ZipHandle handle, string filename)
+
+               public static ZipHandle OpenArchive64 (ZlibFileFuncDef64 funcDef, Append append)
+               {
+                       ZipHandle h = zipOpen2_64 ("", (int) append, IntPtr.Zero, ref funcDef);
+                       if (h.IsInvalid)
+                               throw new Exception ("Could not open the zip archive");
+                       return h;
+               }
+
+               public static int OpenFile32 (ZipHandle handle, string filename)
+               {
+                       return OpenFile32 (handle, filename, DEFAULT_COMPRESSION);
+               }
+
+               public static int OpenFile32 (ZipHandle handle, string filename, int compressionLevel)
+               {
+                       ZipFileInfo32 fileInfo = new ZipFileInfo32 (DateTime.Now);
+                       int method = compressionLevel == 0 ? 0 : Z_DEFLATED;
+                       return zipOpenNewFileInZip_32 (handle, filename, ref fileInfo, IntPtr.Zero, 0, IntPtr.Zero, 0, "", method, compressionLevel);
+               }
+
+               public static int OpenFile64 (ZipHandle handle, string filename)
                {
-                       return OpenFile (handle, filename, DEFAULT_COMPRESSION);
+                       return OpenFile64 (handle, filename, DEFAULT_COMPRESSION);
                }
 
-               public static int OpenFile (ZipHandle handle, string filename, int compressionLevel)
+               public static int OpenFile64 (ZipHandle handle, string filename, int compressionLevel)
                {
-                       ZipFileInfo fileInfo = new ZipFileInfo (DateTime.Now);
+                       ZipFileInfo64 fileInfo = new ZipFileInfo64 (DateTime.Now);
                        int method = compressionLevel == 0 ? 0 : Z_DEFLATED;
-                       return zipOpenNewFileInZip (handle, filename, ref fileInfo, IntPtr.Zero, 0, IntPtr.Zero, 0, "", method, compressionLevel);
+                       return zipOpenNewFileInZip_64 (handle, filename, ref fileInfo, IntPtr.Zero, 0, IntPtr.Zero, 0, "", method, compressionLevel);
                }
 
                public static unsafe void Write (ZipHandle handle, byte[] buffer, int offset, uint count)
@@ -65,26 +85,43 @@ namespace zipsharp
                [DllImport ("MonoPosixHelper")]
                static extern int zipCloseFileInZip (ZipHandle handle);
 
-               [DllImport ("MonoPosixHelper")]
-               static extern ZipHandle zipOpen2 (string pathname,
-                                                 int append,
-                                                 IntPtr globalcomment, // zipcharpc*
-                                                 ref ZlibFileFuncDef pzlib_filefunc_def); // zlib_filefunc_def*
+               [DllImport ("MonoPosixHelper", EntryPoint = "zipOpen2")]
+               static extern ZipHandle zipOpen2_32 (string pathname,
+                                                    int append,
+                                                    IntPtr globalcomment, // zipcharpc*
+                                                    ref ZlibFileFuncDef32 pzlib_filefunc_def); // zlib_filefunc_def*
+
+               [DllImport ("MonoPosixHelper", EntryPoint = "zipOpen2")]
+               static extern ZipHandle zipOpen2_64 (string pathname,
+                                                    int append,
+                                                    IntPtr globalcomment, // zipcharpc*
+                                                    ref ZlibFileFuncDef64 pzlib_filefunc_def); // zlib_filefunc_def*
 
-               
                [DllImport ("MonoPosixHelper")]
                static extern int zipClose (ZipHandle handle, string globalComment);
 
-               [DllImport ("MonoPosixHelper")]
-               static extern int zipOpenNewFileInZip (ZipHandle handle,
-                                                      string filename,
-                                                      ref ZipFileInfo zipfi,
-                                                      IntPtr extrafield_local,
-                                                      uint size_extrafield_local,
-                                                      IntPtr extrafield_global,
-                                                      uint size_extrafield_global,
-                                                      string comment,
-                                                      int method,
-                                                      int level);
+               [DllImport ("MonoPosixHelper", EntryPoint = "zipOpenNewFileInZip")]
+               static extern int zipOpenNewFileInZip_32 (ZipHandle handle,
+                                                         string filename,
+                                                         ref ZipFileInfo32 zipfi,
+                                                         IntPtr extrafield_local,
+                                                         uint size_extrafield_local,
+                                                         IntPtr extrafield_global,
+                                                         uint size_extrafield_global,
+                                                         string comment,
+                                                         int method,
+                                                         int level);
+
+               [DllImport ("MonoPosixHelper", EntryPoint = "zipOpenNewFileInZip")]
+               static extern int zipOpenNewFileInZip_64 (ZipHandle handle,
+                                                         string filename,
+                                                         ref ZipFileInfo64 zipfi,
+                                                         IntPtr extrafield_local,
+                                                         uint size_extrafield_local,
+                                                         IntPtr extrafield_global,
+                                                         uint size_extrafield_global,
+                                                         string comment,
+                                                         int method,
+                                                         int level);
        }
 }
index d3be55886bf8cb9ed2b646c8911db857cfb740a3..59a5935c1128bb07ad734a9d339ce6348763ff25 100644 (file)
@@ -38,7 +38,7 @@ namespace zipsharp
                string[] Files {
                        get {
                                if (files == null)
-                                       files = NativeUnzip.GetFiles (Handle);
+                                       files = NativeVersion.Use32Bit ? NativeUnzip.GetFiles32 (Handle) : NativeUnzip.GetFiles64 (Handle);
                                return files;
                        }
                }
@@ -66,7 +66,7 @@ namespace zipsharp
                public UnzipArchive (Stream stream, bool ownsStream)
                {
                        Stream = new ZipStream (stream, ownsStream);
-                       Handle = NativeUnzip.OpenArchive (Stream.IOFunctions);
+                       Handle = NativeVersion.Use32Bit ? NativeUnzip.OpenArchive32 (Stream.IOFunctions32) : NativeUnzip.OpenArchive64 (Stream.IOFunctions64);
                }
 
                public void Dispose ()
index 9316c0a1773d617a8c26b266ddec0dd51d764723..d69241d7fa50ef1dab26f4597b4a10b614a3672e 100644 (file)
@@ -10,103 +10,46 @@ using System.Runtime.InteropServices;
 namespace zipsharp
 {
        [StructLayout (LayoutKind.Sequential)]
-       struct UnzipFileInfo
+       struct UnzipFileInfo32
        {
-           IntPtr version;              /* version made by                 2 bytes */
-           IntPtr version_needed;       /* version needed to extract       2 bytes */
-           IntPtr flag;                 /* general purpose bit flag        2 bytes */
-           IntPtr compression_method;   /* compression method              2 bytes */
-           IntPtr dosDate;              /* last mod file date in Dos fmt   4 bytes */
-           IntPtr crc;                  /* crc-32                          4 bytes */
-           IntPtr compressed_size;      /* compressed size                 4 bytes */
-           IntPtr uncompressed_size;    /* uncompressed size               4 bytes */
-           IntPtr size_filename;        /* filename length                 2 bytes */
-           IntPtr size_file_extra;      /* extra field length              2 bytes */
-           IntPtr size_file_comment;    /* file comment length             2 bytes */
+               public uint version;              /* version made by                 2 bytes */
+               public uint version_needed;       /* version needed to extract       2 bytes */
+               public uint flag;                 /* general purpose bit flag        2 bytes */
+               public uint compression_method;   /* compression method              2 bytes */
+               public uint dosDate;              /* last mod file date in Dos fmt   4 bytes */
+               public uint crc;                  /* crc-32                          4 bytes */
+               public uint compressed_size;      /* compressed size                 4 bytes */
+               public uint uncompressed_size;    /* uncompressed size               4 bytes */
+               public uint size_filename;        /* filename length                 2 bytes */
+               public uint size_file_extra;      /* extra field length              2 bytes */
+               public uint size_file_comment;    /* file comment length             2 bytes */
        
-           IntPtr disk_num_start;       /* disk number start               2 bytes */
-           IntPtr internal_fa;          /* internal file attributes        2 bytes */
-           IntPtr external_fa;          /* external file attributes        4 bytes */
+               public uint disk_num_start;       /* disk number start               2 bytes */
+               public uint internal_fa;          /* internal file attributes        2 bytes */
+               public uint external_fa;          /* external file attributes        4 bytes */
        
            ZipTime tmu_date;
-           
-           public ulong VersionNeeded {
-               get { return (ulong)version_needed.ToInt64 (); }
-               set { version_needed = new IntPtr ((int)value); }
-           }
-           
-           public ulong Version {
-               get { return (ulong)version.ToInt64 (); }
-               set { version = new IntPtr ((int)value); }
-           }
-           
-           public ulong UncompressedSize {
-               get { return (ulong)uncompressed_size.ToInt64 (); }
-                       set { uncompressed_size = new IntPtr ((int)value); }
-           }
-           
-           public ZipTime TmuDate {
-               get { return tmu_date; }
-               set { tmu_date = value; }
-           }
-           
-           public ulong SizeFilename {
-               get { return (ulong)size_filename.ToInt64 (); }
-               set { size_filename = new IntPtr ((int)value); }
-           }
-           
-           public ulong SizeFileExtra {
-               get { return (ulong)size_file_extra.ToInt64 (); }
-               set { size_file_extra = new IntPtr ((int)value); }
-           }
-           
-           public ulong SizeFileComment {
-               get {
-                       return (ulong)size_file_comment.ToInt64 ();
-               }
-               set {
-                       size_file_comment = new IntPtr ((int)value);
-               }
-           }
-           
-           public ulong InternalFa {
-               get { return (ulong)internal_fa.ToInt64 (); }
-               set { internal_fa = new IntPtr ((int)value); }
-           }
-           
-           public ulong Flag {
-               get { return (ulong)flag.ToInt64 (); }
-               set { flag = new IntPtr ((int)value); }
-           }
-           
-           public ulong ExternalFa {
-               get { return (ulong)external_fa.ToInt64 (); }
-               set { external_fa = new IntPtr ((int)value); }
-           }
-           
-           public ulong DosDate {
-               get { return (ulong)dosDate.ToInt64 (); }
-               set { dosDate = new IntPtr ((int)value); }
-           }
-           
-           public ulong DiskNumStart {
-               get { return (ulong)disk_num_start.ToInt64 (); }
-               set { disk_num_start = new IntPtr ((int)value); }
-           }
-           
-           public ulong Crc {
-               get { return (ulong)crc.ToInt64 (); }
-               set { crc = new IntPtr ((int)value); }
-           }
-           
-           public ulong CompressionMethod {
-               get { return (ulong)compression_method.ToInt64 (); }
-               set { compression_method = new IntPtr ((int)value); }
-           }
-           
-           public ulong CompressedSize {
-               get { return (ulong)compressed_size.ToInt64 (); }
-               set { compressed_size = new IntPtr ((int)value); }
-           }
+       }
+
+       [StructLayout (LayoutKind.Sequential)]
+       struct UnzipFileInfo64
+       {
+               public ulong version;              /* version made by                 2 bytes */
+               public ulong version_needed;       /* version needed to extract       2 bytes */
+               public ulong flag;                 /* general purpose bit flag        2 bytes */
+               public ulong compression_method;   /* compression method              2 bytes */
+               public ulong dosDate;              /* last mod file date in Dos fmt   4 bytes */
+               public ulong crc;                  /* crc-32                          4 bytes */
+               public ulong compressed_size;      /* compressed size                 4 bytes */
+               public ulong uncompressed_size;    /* uncompressed size               4 bytes */
+               public ulong size_filename;        /* filename length                 2 bytes */
+               public ulong size_file_extra;      /* extra field length              2 bytes */
+               public ulong size_file_comment;    /* file comment length             2 bytes */
+
+               public ulong disk_num_start;       /* disk number start               2 bytes */
+               public ulong internal_fa;          /* internal file attributes        2 bytes */
+               public ulong external_fa;          /* external file attributes        4 bytes */
+
+               ZipTime tmu_date;
        }
 }
index 39c793e8e0b2146ab808b62350689aa6453e9377..71cc129006d23f0581d3aae3a3e0c933d1d6e325 100644 (file)
@@ -70,7 +70,7 @@ namespace zipsharp
                        Archive = archive;
                        Archive.FileActive = true;
                        CompressionLevel = compressionLevel;
-                       length = NativeUnzip.CurrentFileLength (Archive.Handle);
+                       length = NativeVersion.Use32Bit ? NativeUnzip.CurrentFileLength32 (Archive.Handle) : NativeUnzip.CurrentFileLength64 (Archive.Handle);
                }
 
                public override void Close()
index 8f60aab4e9eedc97a8f48be7ffadc1e8e50e56b4..598d163991c8821d2540e28ee9b65d9f4c2565a6 100644 (file)
@@ -31,7 +31,7 @@ namespace zipsharp
                public ZipArchive (Stream stream, Append append, bool ownsStream)
                {
                        Stream = new ZipStream (stream, ownsStream);
-                       Handle = NativeZip.OpenArchive (Stream.IOFunctions, append);
+                       Handle = NativeVersion.Use32Bit ? NativeZip.OpenArchive32 (Stream.IOFunctions32, append) : NativeZip.OpenArchive64 (Stream.IOFunctions64, append);
                }
 
                
@@ -61,8 +61,11 @@ namespace zipsharp
                {
                        if (FileActive)
                                throw new InvalidOperationException ("A file is already open");
-                       
-                       NativeZip.OpenFile (Handle, filename, ConvertCompression (option));
+
+                       if (NativeVersion.Use32Bit)
+                               NativeZip.OpenFile32 (Handle, filename, ConvertCompression (option));
+                       else
+                               NativeZip.OpenFile64 (Handle, filename, ConvertCompression (option));
                        return new ZipWriteStream (this);
                }
 
index 2a81a73959bba6ddcf3595874bb9651989261160..0c3f0eeb7f98fefaa786a2c47db873fe1392acd9 100644 (file)
@@ -10,40 +10,36 @@ using System.Runtime.InteropServices;
 namespace zipsharp
 {
        [StructLayoutAttribute (LayoutKind.Sequential)]
-       struct ZipFileInfo
+       struct ZipFileInfo32
        {
                ZipTime date;
-               IntPtr dosDate;
-               IntPtr internalFileAttributes;
-               IntPtr externalFileAttributes;
+               uint dosDate;
+               uint internalFileAttributes;
+               uint externalFileAttributes;
 
-               public DateTime FileTime
+               public ZipFileInfo32 (DateTime fileTime)
                {
-                       get { return date.Date; }
+                       date = new ZipTime (fileTime);
+                       dosDate = 0;
+                       internalFileAttributes = 0;
+                       externalFileAttributes = 0;
                }
+       }
 
-               public long DosDate
-               {
-                       get { return dosDate.ToInt64 (); }
-               }
-               
-               internal long InternalFileAttributes
-               {
-                       get { return internalFileAttributes.ToInt64 (); }
-               }
+       [StructLayoutAttribute (LayoutKind.Sequential)]
+       struct ZipFileInfo64
+       {
+               ZipTime date;
+               ulong dosDate;
+               ulong internalFileAttributes;
+               ulong externalFileAttributes;
 
-               internal long ExternalFileAttributes
-               {
-                       get { return externalFileAttributes.ToInt64 (); }
-               }
-               
-               public ZipFileInfo (DateTime fileTime)
+               public ZipFileInfo64 (DateTime fileTime)
                {
                        date = new ZipTime (fileTime);
-                       dosDate = IntPtr.Zero;
-                       internalFileAttributes = IntPtr.Zero;
-                       externalFileAttributes = IntPtr.Zero;
+                       dosDate = 0;
+                       internalFileAttributes = 0;
+                       externalFileAttributes = 0;
                }
-
        }
 }
index 51d15c56c12dfa67691c08f2019edcedbd9c4851..f0007dfb8a244c059a0f511be0fb900b6fdda0cf 100644 (file)
@@ -40,7 +40,11 @@ namespace zipsharp
                        get; set;
                }
 
-               public ZlibFileFuncDef IOFunctions {
+               public ZlibFileFuncDef32 IOFunctions32 {
+                       get; set;
+               }
+
+               public ZlibFileFuncDef64 IOFunctions64 {
                        get; set;
                }
 
@@ -67,18 +71,27 @@ namespace zipsharp
                        DataStream = dataStream;
                        OwnsStream = ownsStream;
                        
-                       ZlibFileFuncDef f = new ZlibFileFuncDef();
-                       
-                       f.opaque = IntPtr.Zero;
-                       f.zclose_file = CloseFile_Native;
-                       f.zerror_file = TestError_Native;
-                       f.zopen_file = OpenFile_Native;
-                       f.zread_file = ReadFile_Native;
-                       f.zseek_file = SeekFile_Native;
-                       f.ztell_file = TellFile_Native;
-                       f.zwrite_file = WriteFile_Native;
-
-                       IOFunctions = f;
+                       ZlibFileFuncDef32 f32 = new ZlibFileFuncDef32 ();
+                       f32.opaque = IntPtr.Zero;
+                       f32.zclose_file = CloseFile_Native;
+                       f32.zerror_file = TestError_Native;
+                       f32.zopen_file = OpenFile_Native;
+                       f32.zread_file = ReadFile_Native32;
+                       f32.zseek_file = SeekFile_Native32;
+                       f32.ztell_file = TellFile_Native32;
+                       f32.zwrite_file = WriteFile_Native32;
+                       IOFunctions32 = f32;
+
+                       ZlibFileFuncDef64 f64 = new ZlibFileFuncDef64 ();
+                       f64.opaque = IntPtr.Zero;
+                       f64.zclose_file = CloseFile_Native;
+                       f64.zerror_file = TestError_Native;
+                       f64.zopen_file = OpenFile_Native;
+                       f64.zread_file = ReadFile_Native64;
+                       f64.zseek_file = SeekFile_Native64;
+                       f64.ztell_file = TellFile_Native64;
+                       f64.zwrite_file = WriteFile_Native64;
+                       IOFunctions64 = f64;
                }
 
                protected override void Dispose(bool disposing)
@@ -130,9 +143,14 @@ namespace zipsharp
                        return new IntPtr (1);
                }
 
-               unsafe IntPtr ReadFile_Native (IntPtr opaque, IntPtr stream, IntPtr buffer, IntPtr size)
+               unsafe uint ReadFile_Native32 (IntPtr opaque, IntPtr stream, IntPtr buffer, uint size)
                {
-                       int count = size.ToInt32 ();
+                       return (uint) ReadFile_Native64 (opaque, stream, buffer, size);
+               }
+
+               unsafe ulong ReadFile_Native64 (IntPtr opaque, IntPtr stream, IntPtr buffer, ulong size)
+               {
+                       int count = (int) size;
                        byte[] b = new byte[count];
                        int read;
                        
@@ -145,10 +163,15 @@ namespace zipsharp
                                read = -1;
                        }
 
-                       return new IntPtr (read);
+                       return (ulong) read;
                }
 
-               IntPtr SeekFile_Native (IntPtr opaque, IntPtr stream, IntPtr offset, int origin)
+               int SeekFile_Native32 (IntPtr opaque, IntPtr stream, uint offset, int origin)
+               {
+                       return (int) SeekFile_Native64 (opaque, stream, offset, origin);
+               }
+
+               long SeekFile_Native64 (IntPtr opaque, IntPtr stream, ulong offset, int origin)
                {
                        SeekOrigin seek;
                        if (origin == ZipStream.ZLIB_FILEFUNC_SEEK_CUR)
@@ -158,21 +181,21 @@ namespace zipsharp
                        else if (origin == ZLIB_FILEFUNC_SEEK_SET)
                                seek = SeekOrigin.Begin;
                        else
-                               return new IntPtr (-1);
+                               return -1;
 
-                       Seek (offset.ToInt64 (), seek);
+                       Seek ((long) offset, seek);
                        
-                       return new IntPtr (0);
+                       return 0;
                }
 
-               IntPtr TellFile_Native (IntPtr opaque, IntPtr stream)
+               int TellFile_Native32 (IntPtr opaque, IntPtr stream)
                {
-                       if (IntPtr.Size == 4)
-                               return new IntPtr ((int)Position);
-                       else if (IntPtr.Size == 8)
-                               return new IntPtr (Position);
-                       else
-                               return new IntPtr (-1);
+                       return (int) TellFile_Native64 (opaque, stream);
+               }
+
+               long TellFile_Native64 (IntPtr opaque, IntPtr stream)
+               {
+                       return Position;
                }
 
                int TestError_Native (IntPtr opaque, IntPtr stream)
@@ -181,9 +204,14 @@ namespace zipsharp
                        return 0;
                }
 
-               unsafe IntPtr WriteFile_Native (IntPtr opaque, IntPtr stream, IntPtr buffer, /* ulong */ IntPtr size)
+               unsafe uint WriteFile_Native32 (IntPtr opaque, IntPtr stream, IntPtr buffer, /* ulong */ uint size)
+               {
+                       return (uint) WriteFile_Native64 (opaque, stream, buffer, size);
+               }
+
+               unsafe ulong WriteFile_Native64 (IntPtr opaque, IntPtr stream, IntPtr buffer, /* ulong */ ulong size)
                {
-                       int count = size.ToInt32 ();
+                       int count = (int) size;
                        byte[] b = new byte[count];
 
                        byte* ptrBuffer = (byte*) buffer.ToPointer ();
@@ -196,7 +224,7 @@ namespace zipsharp
                                
                        }
 
-                       return new IntPtr (count);
+                       return (ulong) count;
                }
        }
 }
index 75828e154eb12f2fc6f7c21db9258888f7cd3c33..6dc94160d19aa713ed172469e82102f8c9396bbd 100644 (file)
@@ -83,6 +83,7 @@ using System.Runtime.InteropServices;
 [assembly: InternalsVisibleTo ("Xamarin.TVOS, PublicKey=0024000004800000940000000602000000240000525341310004000011000000438ac2a5acfbf16cbd2b2b47a62762f273df9cb2795ceccdf77d10bf508e69e7a362ea7a45455bbf3ac955e1f2e2814f144e5d817efc4c6502cc012df310783348304e3ae38573c6d658c234025821fda87a0be8a0d504df564e2c93b2b878925f42503e9d54dfef9f9586d9e6f38a305769587b1de01f6c0410328b2c9733db")]
 #elif MONOTOUCH_WATCH
 [assembly: InternalsVisibleTo ("Xamarin.WatchOS, PublicKey=0024000004800000940000000602000000240000525341310004000011000000438ac2a5acfbf16cbd2b2b47a62762f273df9cb2795ceccdf77d10bf508e69e7a362ea7a45455bbf3ac955e1f2e2814f144e5d817efc4c6502cc012df310783348304e3ae38573c6d658c234025821fda87a0be8a0d504df564e2c93b2b878925f42503e9d54dfef9f9586d9e6f38a305769587b1de01f6c0410328b2c9733db")]
+[assembly: InternalsVisibleTo ("System.Security, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")]
 #else
 [assembly: InternalsVisibleTo ("monotouch, PublicKey=0024000004800000940000000602000000240000525341310004000011000000438ac2a5acfbf16cbd2b2b47a62762f273df9cb2795ceccdf77d10bf508e69e7a362ea7a45455bbf3ac955e1f2e2814f144e5d817efc4c6502cc012df310783348304e3ae38573c6d658c234025821fda87a0be8a0d504df564e2c93b2b878925f42503e9d54dfef9f9586d9e6f38a305769587b1de01f6c0410328b2c9733db")]
 [assembly: InternalsVisibleTo ("Xamarin.iOS, PublicKey=0024000004800000940000000602000000240000525341310004000011000000438ac2a5acfbf16cbd2b2b47a62762f273df9cb2795ceccdf77d10bf508e69e7a362ea7a45455bbf3ac955e1f2e2814f144e5d817efc4c6502cc012df310783348304e3ae38573c6d658c234025821fda87a0be8a0d504df564e2c93b2b878925f42503e9d54dfef9f9586d9e6f38a305769587b1de01f6c0410328b2c9733db")]
@@ -94,5 +95,4 @@ using System.Runtime.InteropServices;
 [assembly: InternalsVisibleTo ("Xamarin.Mac, PublicKey=0024000004800000940000000602000000240000525341310004000011000000438ac2a5acfbf16cbd2b2b47a62762f273df9cb2795ceccdf77d10bf508e69e7a362ea7a45455bbf3ac955e1f2e2814f144e5d817efc4c6502cc012df310783348304e3ae38573c6d658c234025821fda87a0be8a0d504df564e2c93b2b878925f42503e9d54dfef9f9586d9e6f38a305769587b1de01f6c0410328b2c9733db")]
 #endif
 
-[assembly: InternalsVisibleTo ("Xamarin.BoringTls, PublicKey=002400000480000094000000060200000024000052534131000400001100000099dd12eda85767ae6f06023ee28e711c7e5a212462095c83868c29db75eddf6d8e296e03824c14fedd5f55553fed0b6173be3cc985a4b7f9fb7c83ccff8ba3938563b3d1f45a81122f12a1bcb73edcaad61a8456c7595a6da5184b4dd9d10f011b949ef1391fccfeab1ba62aa51c267ef8bd57ef1b6ba5a4c515d0badb81a78f")]
 [assembly: Guid ("BED7F4EA-1A96-11D2-8F08-00A0C9A6186D")]
index a112faf5570d99236ce2888b1c778a061d6dc4cf..a35fe1dc666eb5bcfb05e1e1fca35b2a7c611c7c 100644 (file)
@@ -39,6 +39,18 @@ namespace System.Security.Cryptography {
                {
                }
                
+               public RNGCryptoServiceProvider (byte[] rgb)
+               {
+               }
+
+               public RNGCryptoServiceProvider (CspParameters cspParams)
+               {
+               }
+
+               public RNGCryptoServiceProvider (string str) 
+               {
+               }
+
                ~RNGCryptoServiceProvider () 
                {
                }
diff --git a/mcs/class/corlib/Documentation/s b/mcs/class/corlib/Documentation/s
deleted file mode 100644 (file)
index aa4de65..0000000
+++ /dev/null
@@ -1,1374 +0,0 @@
-?      s
-?      en/System.Collections.Concurrent
-?      en/ns-System.Threading.Tasks.xml
-?      en/ns-System.Collections.Concurrent.xml
-?      en/ns-System.Diagnostics.Contracts.xml
-?      en/System.Threading.Tasks
-?      en/ns-.xml
-?      en/System.Diagnostics.Contracts.Internal
-?      en/ns-System.Diagnostics.Contracts.Internal.xml
-?      en/System.Diagnostics.Contracts
-M      en/System.Runtime.InteropServices.Expando/IExpando.xml
-?      en/System.Runtime.Versioning/TargetFrameworkAttribute.xml
-M      en/System.Runtime.Versioning/ResourceScope.xml
-M      en/System.Runtime.Versioning/VersioningHelper.xml
-M      en/System.Runtime.Versioning/ResourceExposureAttribute.xml
-M      en/System.Runtime.Versioning/ResourceConsumptionAttribute.xml
-?      en/System.Threading/CountdownEvent.xml
-?      en/System.Threading/CancellationTokenRegistration.xml
-?      en/System.Threading/SpinWait.xml
-?      en/System.Threading/ThreadLocal`1.xml
-?      en/System.Threading/SemaphoreSlim.xml
-?      en/System.Threading/SpinLock.xml
-?      en/System.Threading/LazyInitializer.xml
-?      en/System.Threading/SemaphoreFullException.xml
-?      en/System.Threading/LazyThreadSafetyMode.xml
-?      en/System.Threading/CancellationToken.xml
-?      en/System.Threading/LockRecursionException.xml
-?      en/System.Threading/ManualResetEventSlim.xml
-?      en/System.Threading/CancellationTokenSource.xml
-M      en/System.Threading/WaitHandle.xml
-M      en/System.Threading/WaitCallback.xml
-M      en/System.Threading/EventWaitHandle.xml
-M      en/System.Threading/LockCookie.xml
-M      en/System.Threading/SynchronizationLockException.xml
-M      en/System.Threading/EventResetMode.xml
-M      en/System.Threading/RegisteredWaitHandle.xml
-M      en/System.Threading/ThreadPool.xml
-M      en/System.Threading/Overlapped.xml
-M      en/System.Threading/HostExecutionContextManager.xml
-M      en/System.Threading/ParameterizedThreadStart.xml
-M      en/System.Threading/ThreadStartException.xml
-M      en/System.Threading/SynchronizationContext.xml
-M      en/System.Threading/AsyncFlowControl.xml
-M      en/System.Threading/HostExecutionContext.xml
-M      en/System.Threading/Thread.xml
-M      en/System.Threading/ExecutionContext.xml
-M      en/System.Threading/ThreadState.xml
-M      en/System.Threading/ThreadPriority.xml
-M      en/System.Threading/ThreadInterruptedException.xml
-M      en/System.Threading/IOCompletionCallback.xml
-M      en/System.Threading/Timer.xml
-M      en/System.Threading/ManualResetEvent.xml
-M      en/System.Threading/WaitOrTimerCallback.xml
-M      en/System.Threading/ThreadStart.xml
-M      en/System.Threading/Timeout.xml
-M      en/System.Threading/Monitor.xml
-M      en/System.Threading/ThreadStateException.xml
-M      en/System.Threading/CompressedStack.xml
-M      en/System.Threading/ApartmentState.xml
-M      en/System.Threading/TimerCallback.xml
-M      en/System.Threading/ContextCallback.xml
-M      en/System.Threading/Mutex.xml
-M      en/System.Threading/Interlocked.xml
-M      en/System.Threading/WaitHandleCannotBeOpenedException.xml
-M      en/System.Threading/ReaderWriterLock.xml
-M      en/System.Threading/NativeOverlapped.xml
-M      en/System.Threading/SendOrPostCallback.xml
-M      en/System.Threading/AbandonedMutexException.xml
-M      en/System.Threading/AutoResetEvent.xml
-M      en/System.Threading/ThreadAbortException.xml
-M      en/System.Runtime.Serialization.Formatters.Binary/BinaryFormatter.xml
-?      en/System.Security/SecurityContextSource.xml
-?      en/System.Security/SecurityRulesAttribute.xml
-?      en/System.Security/SecurityRuleSet.xml
-?      en/System.Security/SecurityState.xml
-M      en/System.Security/SecurityElement.xml
-M      en/System.Security/IEvidenceFactory.xml
-M      en/System.Security/SecurityException.xml
-M      en/System.Security/XmlSyntaxException.xml
-M      en/System.Security/PolicyLevelType.xml
-M      en/System.Security/UnverifiableCodeAttribute.xml
-M      en/System.Security/IStackWalk.xml
-M      en/System.Security/ISecurityPolicyEncodable.xml
-M      en/System.Security/HostSecurityManager.xml
-M      en/System.Security/IPermission.xml
-M      en/System.Security/VerificationException.xml
-M      en/System.Security/SecurityManager.xml
-M      en/System.Security/HostProtectionException.xml
-M      en/System.Security/SecurityZone.xml
-M      en/System.Security/PermissionSet.xml
-M      en/System.Security/CodeAccessPermission.xml
-M      en/System.Security/AllowPartiallyTrustedCallersAttribute.xml
-M      en/System.Security/SecuritySafeCriticalAttribute.xml
-M      en/System.Security/SecurityCriticalAttribute.xml
-M      en/System.Security/NamedPermissionSet.xml
-M      en/System.Security/SuppressUnmanagedCodeSecurityAttribute.xml
-M      en/System.Security/SecurityContext.xml
-M      en/System.Security/HostSecurityManagerOptions.xml
-M      en/System.Security/SecurityCriticalScope.xml
-M      en/System.Security/SecureString.xml
-M      en/System.Security/ISecurityEncodable.xml
-M      en/System.Security/SecurityTransparentAttribute.xml
-M      en/System.Security/SecurityTreatAsSafeAttribute.xml
-?      en/System.Security.AccessControl/ObjectSecurity`1.xml
-M      en/System.Security.AccessControl/ObjectAccessRule.xml
-M      en/System.Security.AccessControl/RegistryAccessRule.xml
-M      en/System.Security.AccessControl/MutexRights.xml
-M      en/System.Security.AccessControl/CustomAce.xml
-M      en/System.Security.AccessControl/DirectoryObjectSecurity.xml
-M      en/System.Security.AccessControl/GenericAce.xml
-M      en/System.Security.AccessControl/RegistryRights.xml
-M      en/System.Security.AccessControl/MutexSecurity.xml
-M      en/System.Security.AccessControl/AceQualifier.xml
-M      en/System.Security.AccessControl/AceEnumerator.xml
-M      en/System.Security.AccessControl/GenericAcl.xml
-M      en/System.Security.AccessControl/EventWaitHandleAccessRule.xml
-M      en/System.Security.AccessControl/ObjectSecurity.xml
-M      en/System.Security.AccessControl/FileSystemAccessRule.xml
-M      en/System.Security.AccessControl/RegistrySecurity.xml
-M      en/System.Security.AccessControl/EventWaitHandleRights.xml
-M      en/System.Security.AccessControl/SystemAcl.xml
-M      en/System.Security.AccessControl/AuthorizationRuleCollection.xml
-M      en/System.Security.AccessControl/AccessControlType.xml
-M      en/System.Security.AccessControl/FileSystemRights.xml
-M      en/System.Security.AccessControl/SecurityInfos.xml
-M      en/System.Security.AccessControl/CommonObjectSecurity.xml
-M      en/System.Security.AccessControl/RawAcl.xml
-M      en/System.Security.AccessControl/AccessControlSections.xml
-M      en/System.Security.AccessControl/EventWaitHandleSecurity.xml
-M      en/System.Security.AccessControl/FileSystemSecurity.xml
-M      en/System.Security.AccessControl/CommonSecurityDescriptor.xml
-M      en/System.Security.AccessControl/CryptoKeySecurity.xml
-M      en/System.Security.AccessControl/PrivilegeNotHeldException.xml
-M      en/System.Security.AccessControl/AccessControlActions.xml
-M      en/System.Security.AccessControl/RegistryAuditRule.xml
-M      en/System.Security.AccessControl/AuthorizationRule.xml
-M      en/System.Security.AccessControl/AccessControlModification.xml
-M      en/System.Security.AccessControl/ResourceType.xml
-M      en/System.Security.AccessControl/AccessRule.xml
-M      en/System.Security.AccessControl/DirectorySecurity.xml
-M      en/System.Security.AccessControl/CompoundAceType.xml
-M      en/System.Security.AccessControl/DiscretionaryAcl.xml
-M      en/System.Security.AccessControl/CommonAce.xml
-M      en/System.Security.AccessControl/FileSystemAuditRule.xml
-M      en/System.Security.AccessControl/AceFlags.xml
-M      en/System.Security.AccessControl/CommonAcl.xml
-M      en/System.Security.AccessControl/ObjectAce.xml
-M      en/System.Security.AccessControl/AuditFlags.xml
-M      en/System.Security.AccessControl/ObjectAceFlags.xml
-M      en/System.Security.AccessControl/CompoundAce.xml
-M      en/System.Security.AccessControl/CryptoKeyAccessRule.xml
-M      en/System.Security.AccessControl/KnownAce.xml
-M      en/System.Security.AccessControl/InheritanceFlags.xml
-M      en/System.Security.AccessControl/CryptoKeyAuditRule.xml
-M      en/System.Security.AccessControl/CryptoKeyRights.xml
-M      en/System.Security.AccessControl/QualifiedAce.xml
-M      en/System.Security.AccessControl/RawSecurityDescriptor.xml
-M      en/System.Security.AccessControl/MutexAuditRule.xml
-M      en/System.Security.AccessControl/ObjectAuditRule.xml
-M      en/System.Security.AccessControl/AceType.xml
-M      en/System.Security.AccessControl/ControlFlags.xml
-M      en/System.Security.AccessControl/AuditRule.xml
-M      en/System.Security.AccessControl/PropagationFlags.xml
-M      en/System.Security.AccessControl/EventWaitHandleAuditRule.xml
-M      en/System.Security.AccessControl/GenericSecurityDescriptor.xml
-M      en/System.Security.AccessControl/NativeObjectSecurity.xml
-M      en/System.Security.AccessControl/FileSecurity.xml
-M      en/System.Security.AccessControl/MutexAccessRule.xml
-M      en/System.Security.Permissions/PublisherIdentityPermission.xml
-M      en/System.Security.Permissions/SecurityPermission.xml
-M      en/System.Security.Permissions/KeyContainerPermissionFlags.xml
-M      en/System.Security.Permissions/RegistryPermission.xml
-M      en/System.Security.Permissions/StrongNameIdentityPermissionAttribute.xml
-M      en/System.Security.Permissions/IsolatedStoragePermissionAttribute.xml
-M      en/System.Security.Permissions/IsolatedStorageFilePermissionAttribute.xml
-M      en/System.Security.Permissions/PermissionState.xml
-M      en/System.Security.Permissions/IsolatedStorageContainment.xml
-M      en/System.Security.Permissions/PrincipalPermission.xml
-M      en/System.Security.Permissions/FileDialogPermissionAttribute.xml
-M      en/System.Security.Permissions/HostProtectionResource.xml
-M      en/System.Security.Permissions/ReflectionPermissionFlag.xml
-M      en/System.Security.Permissions/ZoneIdentityPermission.xml
-M      en/System.Security.Permissions/EnvironmentPermissionAccess.xml
-M      en/System.Security.Permissions/EnvironmentPermissionAttribute.xml
-M      en/System.Security.Permissions/GacIdentityPermissionAttribute.xml
-M      en/System.Security.Permissions/FileIOPermissionAccess.xml
-M      en/System.Security.Permissions/PublisherIdentityPermissionAttribute.xml
-M      en/System.Security.Permissions/KeyContainerPermission.xml
-M      en/System.Security.Permissions/SecurityPermissionAttribute.xml
-M      en/System.Security.Permissions/SecurityAction.xml
-M      en/System.Security.Permissions/CodeAccessSecurityAttribute.xml
-M      en/System.Security.Permissions/UrlIdentityPermissionAttribute.xml
-M      en/System.Security.Permissions/SecurityPermissionFlag.xml
-M      en/System.Security.Permissions/SiteIdentityPermissionAttribute.xml
-M      en/System.Security.Permissions/EnvironmentPermission.xml
-M      en/System.Security.Permissions/GacIdentityPermission.xml
-M      en/System.Security.Permissions/PrincipalPermissionAttribute.xml
-M      en/System.Security.Permissions/UIPermissionWindow.xml
-M      en/System.Security.Permissions/FileIOPermission.xml
-M      en/System.Security.Permissions/ZoneIdentityPermissionAttribute.xml
-M      en/System.Security.Permissions/KeyContainerPermissionAccessEntryCollection.xml
-M      en/System.Security.Permissions/StrongNamePublicKeyBlob.xml
-M      en/System.Security.Permissions/UrlIdentityPermission.xml
-M      en/System.Security.Permissions/UIPermission.xml
-M      en/System.Security.Permissions/ReflectionPermissionAttribute.xml
-M      en/System.Security.Permissions/SiteIdentityPermission.xml
-M      en/System.Security.Permissions/PermissionSetAttribute.xml
-M      en/System.Security.Permissions/KeyContainerPermissionAttribute.xml
-M      en/System.Security.Permissions/FileDialogPermissionAccess.xml
-M      en/System.Security.Permissions/SecurityAttribute.xml
-M      en/System.Security.Permissions/IUnrestrictedPermission.xml
-M      en/System.Security.Permissions/StrongNameIdentityPermission.xml
-M      en/System.Security.Permissions/IsolatedStoragePermission.xml
-M      en/System.Security.Permissions/IsolatedStorageFilePermission.xml
-M      en/System.Security.Permissions/ReflectionPermission.xml
-M      en/System.Security.Permissions/RegistryPermissionAccess.xml
-M      en/System.Security.Permissions/FileIOPermissionAttribute.xml
-M      en/System.Security.Permissions/RegistryPermissionAttribute.xml
-M      en/System.Security.Permissions/UIPermissionClipboard.xml
-M      en/System.Security.Permissions/KeyContainerPermissionAccessEntry.xml
-M      en/System.Security.Permissions/FileDialogPermission.xml
-M      en/System.Security.Permissions/HostProtectionAttribute.xml
-M      en/System.Security.Permissions/KeyContainerPermissionAccessEntryEnumerator.xml
-M      en/System.Security.Permissions/UIPermissionAttribute.xml
-M      en/System.Runtime.Remoting.Messaging/CallContext.xml
-M      en/System.Runtime.Remoting.Messaging/IRemotingFormatter.xml
-M      en/System.Runtime.Remoting.Messaging/RemotingSurrogateSelector.xml
-M      en/System.Runtime.Remoting.Messaging/InternalMessageWrapper.xml
-M      en/System.Runtime.Remoting.Messaging/IMessageSink.xml
-M      en/System.Runtime.Remoting.Messaging/IMessageCtrl.xml
-M      en/System.Runtime.Remoting.Messaging/MethodCallMessageWrapper.xml
-M      en/System.Runtime.Remoting.Messaging/ReturnMessage.xml
-M      en/System.Runtime.Remoting.Messaging/HeaderHandler.xml
-M      en/System.Runtime.Remoting.Messaging/ConstructionCall.xml
-M      en/System.Runtime.Remoting.Messaging/MessageSurrogateFilter.xml
-M      en/System.Runtime.Remoting.Messaging/MethodReturnMessageWrapper.xml
-M      en/System.Runtime.Remoting.Messaging/OneWayAttribute.xml
-M      en/System.Runtime.Remoting.Messaging/Header.xml
-M      en/System.Runtime.Remoting.Messaging/IMethodCallMessage.xml
-M      en/System.Runtime.Remoting.Messaging/IMessage.xml
-M      en/System.Runtime.Remoting.Messaging/IMethodReturnMessage.xml
-M      en/System.Runtime.Remoting.Messaging/IMethodMessage.xml
-M      en/System.Runtime.Remoting.Messaging/MethodResponse.xml
-M      en/System.Runtime.Remoting.Messaging/ILogicalThreadAffinative.xml
-M      en/System.Runtime.Remoting.Messaging/ConstructionResponse.xml
-M      en/System.Runtime.Remoting.Messaging/LogicalCallContext.xml
-M      en/System.Runtime.Remoting.Messaging/AsyncResult.xml
-M      en/System.Runtime.Remoting.Messaging/MethodCall.xml
-M      en/System.Security.Principal/TokenImpersonationLevel.xml
-M      en/System.Security.Principal/IdentityNotMappedException.xml
-M      en/System.Security.Principal/WellKnownSidType.xml
-M      en/System.Security.Principal/IdentityReferenceCollection.xml
-M      en/System.Security.Principal/GenericIdentity.xml
-M      en/System.Security.Principal/IPrincipal.xml
-M      en/System.Security.Principal/WindowsPrincipal.xml
-M      en/System.Security.Principal/NTAccount.xml
-M      en/System.Security.Principal/PrincipalPolicy.xml
-M      en/System.Security.Principal/IIdentity.xml
-M      en/System.Security.Principal/WindowsBuiltInRole.xml
-M      en/System.Security.Principal/WindowsIdentity.xml
-M      en/System.Security.Principal/WindowsImpersonationContext.xml
-M      en/System.Security.Principal/IdentityReference.xml
-M      en/System.Security.Principal/WindowsAccountType.xml
-M      en/System.Security.Principal/SecurityIdentifier.xml
-M      en/System.Security.Principal/TokenAccessLevels.xml
-M      en/System.Security.Principal/GenericPrincipal.xml
-M      en/System.Diagnostics.SymbolStore/ISymbolBinder1.xml
-M      en/System.Diagnostics.SymbolStore/ISymbolVariable.xml
-M      en/System.Diagnostics.SymbolStore/SymAddressKind.xml
-M      en/System.Diagnostics.SymbolStore/SymLanguageVendor.xml
-M      en/System.Diagnostics.SymbolStore/ISymbolNamespace.xml
-M      en/System.Diagnostics.SymbolStore/ISymbolReader.xml
-M      en/System.Diagnostics.SymbolStore/ISymbolBinder.xml
-M      en/System.Diagnostics.SymbolStore/SymbolToken.xml
-M      en/System.Diagnostics.SymbolStore/ISymbolScope.xml
-M      en/System.Diagnostics.SymbolStore/SymDocumentType.xml
-M      en/System.Diagnostics.SymbolStore/ISymbolDocumentWriter.xml
-M      en/System.Diagnostics.SymbolStore/ISymbolWriter.xml
-M      en/System.Diagnostics.SymbolStore/ISymbolDocument.xml
-M      en/System.Diagnostics.SymbolStore/SymLanguageType.xml
-M      en/System.Diagnostics.SymbolStore/ISymbolMethod.xml
-M      en/System.Runtime.Hosting/ApplicationActivator.xml
-M      en/System.Runtime.Hosting/ActivationArguments.xml
-M      en/System.Configuration.Assemblies/AssemblyHash.xml
-M      en/System.Configuration.Assemblies/AssemblyHashAlgorithm.xml
-M      en/System.Configuration.Assemblies/AssemblyVersionCompatibility.xml
-?      en/Microsoft.Win32.SafeHandles/SafeRegistryHandle.xml
-M      en/Microsoft.Win32.SafeHandles/CriticalHandleMinusOneIsInvalid.xml
-M      en/Microsoft.Win32.SafeHandles/CriticalHandleZeroOrMinusOneIsInvalid.xml
-M      en/Microsoft.Win32.SafeHandles/SafeFileHandle.xml
-M      en/Microsoft.Win32.SafeHandles/SafeHandleMinusOneIsInvalid.xml
-M      en/Microsoft.Win32.SafeHandles/SafeHandleZeroOrMinusOneIsInvalid.xml
-M      en/Microsoft.Win32.SafeHandles/SafeWaitHandle.xml
-?      en/System.Runtime.Serialization/SafeSerializationEventArgs.xml
-?      en/System.Runtime.Serialization/ISafeSerializationData.xml
-M      en/System.Runtime.Serialization/ISerializationSurrogate.xml
-M      en/System.Runtime.Serialization/StreamingContextStates.xml
-M      en/System.Runtime.Serialization/OnDeserializedAttribute.xml
-M      en/System.Runtime.Serialization/ISurrogateSelector.xml
-M      en/System.Runtime.Serialization/SerializationInfo.xml
-M      en/System.Runtime.Serialization/ObjectIDGenerator.xml
-M      en/System.Runtime.Serialization/FormatterConverter.xml
-M      en/System.Runtime.Serialization/SerializationInfoEnumerator.xml
-M      en/System.Runtime.Serialization/SerializationException.xml
-M      en/System.Runtime.Serialization/IObjectReference.xml
-M      en/System.Runtime.Serialization/StreamingContext.xml
-M      en/System.Runtime.Serialization/SerializationEntry.xml
-M      en/System.Runtime.Serialization/SerializationObjectManager.xml
-M      en/System.Runtime.Serialization/OnSerializingAttribute.xml
-M      en/System.Runtime.Serialization/ObjectManager.xml
-M      en/System.Runtime.Serialization/SerializationBinder.xml
-M      en/System.Runtime.Serialization/Formatter.xml
-M      en/System.Runtime.Serialization/IFormatterConverter.xml
-M      en/System.Runtime.Serialization/FormatterServices.xml
-M      en/System.Runtime.Serialization/OnDeserializingAttribute.xml
-M      en/System.Runtime.Serialization/OnSerializedAttribute.xml
-M      en/System.Runtime.Serialization/IFormatter.xml
-M      en/System.Runtime.Serialization/IDeserializationCallback.xml
-M      en/System.Runtime.Serialization/SurrogateSelector.xml
-M      en/System.Runtime.Serialization/OptionalFieldAttribute.xml
-M      en/System.Runtime.Serialization/ISerializable.xml
-?      en/System/Lazy`1.xml
-?      en/System/Action`3.xml
-?      en/System/Action`5.xml
-?      en/System/Action`7.xml
-?      en/System/Environment+SpecialFolderOption.xml
-?      en/System/TypeAccessException.xml
-?      en/System/Func`1.xml
-?      en/System/Func`3.xml
-?      en/System/Func`5.xml
-?      en/System/Func`7.xml
-?      en/System/Func`9.xml
-?      en/System/Tuple`1.xml
-?      en/System/TimeZoneInfo+TransitionTime.xml
-?      en/System/Tuple`3.xml
-?      en/System/IObservable`1.xml
-?      en/System/Tuple`5.xml
-?      en/System/InsufficientExecutionStackException.xml
-?      en/System/Tuple`7.xml
-?      en/System/TimeZoneInfo+AdjustmentRule.xml
-?      en/System/Action.xml
-?      en/System/Action`2.xml
-?      en/System/Action`4.xml
-?      en/System/Action`6.xml
-?      en/System/Action`8.xml
-?      en/System/IObserver`1.xml
-?      en/System/TimeZoneNotFoundException.xml
-?      en/System/Func`2.xml
-?      en/System/Func`4.xml
-?      en/System/Func`6.xml
-?      en/System/Func`8.xml
-?      en/System/Tuple.xml
-?      en/System/GCNotificationStatus.xml
-?      en/System/TimeZoneInfo.xml
-?      en/System/Tuple`2.xml
-?      en/System/Tuple`4.xml
-?      en/System/Tuple`6.xml
-?      en/System/InvalidTimeZoneException.xml
-?      en/System/Tuple`8.xml
-?      en/System/AggregateException.xml
-M      en/System/UnhandledExceptionEventHandler.xml
-M      en/System/ApplicationException.xml
-M      en/System/UInt32.xml
-M      en/System/InvalidOperationException.xml
-M      en/System/ConsoleKeyInfo.xml
-M      en/System/Activator.xml
-M      en/System/Action`1.xml
-M      en/System/Int32.xml
-M      en/System/TypeLoadException.xml
-M      en/System/LoaderOptimizationAttribute.xml
-M      en/System/ConsoleColor.xml
-M      en/System/Void.xml
-M      en/System/Environment.xml
-M      en/System/NullReferenceException.xml
-M      en/System/Double.xml
-M      en/System/AttributeUsageAttribute.xml
-M      en/System/TypeCode.xml
-M      en/System/Char.xml
-M      en/System/IComparable.xml
-M      en/System/MissingMemberException.xml
-M      en/System/IndexOutOfRangeException.xml
-M      en/System/Convert.xml
-M      en/System/Random.xml
-M      en/System/TimeSpan.xml
-M      en/System/BadImageFormatException.xml
-M      en/System/Predicate`1.xml
-M      en/System/ArrayTypeMismatchException.xml
-M      en/System/Version.xml
-M      en/System/MissingMethodException.xml
-M      en/System/TimeZone.xml
-M      en/System/Comparison`1.xml
-M      en/System/MTAThreadAttribute.xml
-M      en/System/AttributeTargets.xml
-M      en/System/InsufficientMemoryException.xml
-M      en/System/StringComparer.xml
-M      en/System/ContextBoundObject.xml
-M      en/System/DateTimeOffset.xml
-M      en/System/OutOfMemoryException.xml
-M      en/System/TimeoutException.xml
-M      en/System/ActivationContext.xml
-M      en/System/TypeInitializationException.xml
-M      en/System/MulticastNotSupportedException.xml
-M      en/System/ObjectDisposedException.xml
-M      en/System/OverflowException.xml
-M      en/System/ParamArrayAttribute.xml
-M      en/System/IServiceProvider.xml
-M      en/System/IAsyncResult.xml
-M      en/System/ResolveEventArgs.xml
-M      en/System/IAppDomainSetup.xml
-M      en/System/RuntimeFieldHandle.xml
-M      en/System/SystemException.xml
-M      en/System/ConsoleModifiers.xml
-M      en/System/_AppDomain.xml
-M      en/System/ExecutionEngineException.xml
-M      en/System/ArithmeticException.xml
-M      en/System/RankException.xml
-M      en/System/Environment+SpecialFolder.xml
-M      en/System/ConsoleSpecialKey.xml
-M      en/System/EventHandler.xml
-M      en/System/Boolean.xml
-M      en/System/InvalidCastException.xml
-M      en/System/Guid.xml
-M      en/System/PlatformNotSupportedException.xml
-M      en/System/MissingFieldException.xml
-M      en/System/OperatingSystem.xml
-M      en/System/AssemblyLoadEventArgs.xml
-M      en/System/ObsoleteAttribute.xml
-M      en/System/MulticastDelegate.xml
-M      en/System/EventHandler`1.xml
-M      en/System/RuntimeMethodHandle.xml
-M      en/System/PlatformID.xml
-M      en/System/AppDomainUnloadedException.xml
-M      en/System/Byte.xml
-M      en/System/Enum.xml
-M      en/System/UIntPtr.xml
-M      en/System/BitConverter.xml
-M      en/System/CrossAppDomainDelegate.xml
-M      en/System/FlagsAttribute.xml
-M      en/System/DBNull.xml
-M      en/System/ArraySegment`1.xml
-M      en/System/ArgIterator.xml
-M      en/System/FieldAccessException.xml
-M      en/System/Math.xml
-M      en/System/NonSerializedAttribute.xml
-M      en/System/SerializableAttribute.xml
-M      en/System/DateTime.xml
-M      en/System/Exception.xml
-M      en/System/OperationCanceledException.xml
-M      en/System/ThreadStaticAttribute.xml
-M      en/System/DllNotFoundException.xml
-M      en/System/AppDomain.xml
-M      en/System/StackOverflowException.xml
-M      en/System/GCCollectionMode.xml
-M      en/System/ActivationContext+ContextForm.xml
-M      en/System/Delegate.xml
-M      en/System/ApplicationId.xml
-M      en/System/EnvironmentVariableTarget.xml
-M      en/System/Single.xml
-M      en/System/UnauthorizedAccessException.xml
-M      en/System/NotSupportedException.xml
-M      en/System/InvalidProgramException.xml
-M      en/System/ICloneable.xml
-M      en/System/StringSplitOptions.xml
-M      en/System/ModuleHandle.xml
-M      en/System/RuntimeTypeHandle.xml
-M      en/System/StringComparison.xml
-M      en/System/Console.xml
-M      en/System/DateTimeKind.xml
-M      en/System/NotImplementedException.xml
-M      en/System/MarshalByRefObject.xml
-M      en/System/WeakReference.xml
-M      en/System/ConsoleCancelEventHandler.xml
-M      en/System/ContextMarshalException.xml
-M      en/System/CLSCompliantAttribute.xml
-M      en/System/TypeUnloadedException.xml
-M      en/System/Array.xml
-M      en/System/DayOfWeek.xml
-M      en/System/ValueType.xml
-M      en/System/Nullable`1.xml
-M      en/System/ResolveEventHandler.xml
-M      en/System/ContextStaticAttribute.xml
-M      en/System/MethodAccessException.xml
-M      en/System/Type.xml
-M      en/System/IConvertible.xml
-M      en/System/SByte.xml
-M      en/System/UInt16.xml
-M      en/System/NotFiniteNumberException.xml
-M      en/System/MidpointRounding.xml
-M      en/System/GC.xml
-M      en/System/AppDomainSetup.xml
-M      en/System/AsyncCallback.xml
-M      en/System/ArgumentOutOfRangeException.xml
-M      en/System/ArgumentNullException.xml
-M      en/System/IEquatable`1.xml
-M      en/System/IDisposable.xml
-M      en/System/UnhandledExceptionEventArgs.xml
-M      en/System/Int16.xml
-M      en/System/ArgumentException.xml
-M      en/System/LocalDataStoreSlot.xml
-M      en/System/Attribute.xml
-M      en/System/AppDomainManager.xml
-M      en/System/AccessViolationException.xml
-M      en/System/ICustomFormatter.xml
-M      en/System/IFormattable.xml
-M      en/System/Buffer.xml
-M      en/System/ConsoleKey.xml
-M      en/System/IFormatProvider.xml
-M      en/System/AppDomainInitializer.xml
-M      en/System/LoaderOptimization.xml
-M      en/System/ApplicationIdentity.xml
-M      en/System/AssemblyLoadEventHandler.xml
-M      en/System/CharEnumerator.xml
-M      en/System/IntPtr.xml
-M      en/System/DataMisalignedException.xml
-M      en/System/AppDomainManagerInitializationOptions.xml
-M      en/System/ConsoleCancelEventArgs.xml
-M      en/System/Converter`2.xml
-M      en/System/UInt64.xml
-M      en/System/Base64FormattingOptions.xml
-M      en/System/CannotUnloadAppDomainException.xml
-M      en/System/Nullable.xml
-M      en/System/EventArgs.xml
-M      en/System/Decimal.xml
-M      en/System/IComparable`1.xml
-M      en/System/RuntimeArgumentHandle.xml
-M      en/System/STAThreadAttribute.xml
-M      en/System/Int64.xml
-M      en/System/TypedReference.xml
-M      en/System/DuplicateWaitObjectException.xml
-M      en/System/Object.xml
-M      en/System/String.xml
-M      en/System/FormatException.xml
-M      en/System/EntryPointNotFoundException.xml
-M      en/System/MemberAccessException.xml
-M      en/System/DivideByZeroException.xml
-?      en/System.Runtime.InteropServices/SafeBuffer.xml
-?      en/System.Runtime.InteropServices/AllowReversePInvokeCallsAttribute.xml
-M      en/System.Runtime.InteropServices/ExporterEventKind.xml
-M      en/System.Runtime.InteropServices/SafeArrayTypeMismatchException.xml
-M      en/System.Runtime.InteropServices/TypeLibTypeFlags.xml
-M      en/System.Runtime.InteropServices/UCOMIEnumString.xml
-M      en/System.Runtime.InteropServices/InAttribute.xml
-M      en/System.Runtime.InteropServices/_EventInfo.xml
-M      en/System.Runtime.InteropServices/_PropertyInfo.xml
-M      en/System.Runtime.InteropServices/FUNCKIND.xml
-M      en/System.Runtime.InteropServices/BINDPTR.xml
-M      en/System.Runtime.InteropServices/UCOMIEnumConnections.xml
-M      en/System.Runtime.InteropServices/ComCompatibleVersionAttribute.xml
-M      en/System.Runtime.InteropServices/ITypeLibConverter.xml
-M      en/System.Runtime.InteropServices/_ILGenerator.xml
-M      en/System.Runtime.InteropServices/FieldOffsetAttribute.xml
-M      en/System.Runtime.InteropServices/TYPEDESC.xml
-M      en/System.Runtime.InteropServices/_Type.xml
-M      en/System.Runtime.InteropServices/ITypeLibImporterNotifySink.xml
-M      en/System.Runtime.InteropServices/DefaultCharSetAttribute.xml
-M      en/System.Runtime.InteropServices/ICustomMarshaler.xml
-M      en/System.Runtime.InteropServices/_MemberInfo.xml
-M      en/System.Runtime.InteropServices/ComDefaultInterfaceAttribute.xml
-M      en/System.Runtime.InteropServices/HandleRef.xml
-M      en/System.Runtime.InteropServices/ITypeLibExporterNotifySink.xml
-M      en/System.Runtime.InteropServices/UnmanagedFunctionPointerAttribute.xml
-M      en/System.Runtime.InteropServices/CurrencyWrapper.xml
-M      en/System.Runtime.InteropServices/TypeLibVarFlags.xml
-M      en/System.Runtime.InteropServices/TYPEFLAGS.xml
-M      en/System.Runtime.InteropServices/SafeArrayRankMismatchException.xml
-M      en/System.Runtime.InteropServices/UnknownWrapper.xml
-M      en/System.Runtime.InteropServices/_ConstructorInfo.xml
-M      en/System.Runtime.InteropServices/ComInterfaceType.xml
-M      en/System.Runtime.InteropServices/CALLCONV.xml
-M      en/System.Runtime.InteropServices/TypeLibVersionAttribute.xml
-M      en/System.Runtime.InteropServices/LCIDConversionAttribute.xml
-M      en/System.Runtime.InteropServices/AutomationProxyAttribute.xml
-M      en/System.Runtime.InteropServices/GCHandleType.xml
-M      en/System.Runtime.InteropServices/OptionalAttribute.xml
-M      en/System.Runtime.InteropServices/VarEnum.xml
-M      en/System.Runtime.InteropServices/UCOMIEnumConnectionPoints.xml
-M      en/System.Runtime.InteropServices/IMPLTYPEFLAGS.xml
-M      en/System.Runtime.InteropServices/PreserveSigAttribute.xml
-M      en/System.Runtime.InteropServices/LayoutKind.xml
-M      en/System.Runtime.InteropServices/CONNECTDATA.xml
-M      en/System.Runtime.InteropServices/ObjectCreationDelegate.xml
-M      en/System.Runtime.InteropServices/ITypeLibExporterNameProvider.xml
-M      en/System.Runtime.InteropServices/ComSourceInterfacesAttribute.xml
-M      en/System.Runtime.InteropServices/AssemblyRegistrationFlags.xml
-M      en/System.Runtime.InteropServices/UCOMIBindCtx.xml
-M      en/System.Runtime.InteropServices/SafeHandle.xml
-M      en/System.Runtime.InteropServices/PARAMFLAG.xml
-M      en/System.Runtime.InteropServices/UCOMITypeComp.xml
-M      en/System.Runtime.InteropServices/_Exception.xml
-M      en/System.Runtime.InteropServices/_FieldInfo.xml
-M      en/System.Runtime.InteropServices/TypeLibConverter.xml
-M      en/System.Runtime.InteropServices/ELEMDESC+DESCUNION.xml
-M      en/System.Runtime.InteropServices/_CustomAttributeBuilder.xml
-M      en/System.Runtime.InteropServices/ClassInterfaceAttribute.xml
-M      en/System.Runtime.InteropServices/ComRegisterFunctionAttribute.xml
-M      en/System.Runtime.InteropServices/RegistrationServices.xml
-M      en/System.Runtime.InteropServices/ArrayWithOffset.xml
-M      en/System.Runtime.InteropServices/ICustomAdapter.xml
-M      en/System.Runtime.InteropServices/InterfaceTypeAttribute.xml
-M      en/System.Runtime.InteropServices/DllImportAttribute.xml
-M      en/System.Runtime.InteropServices/OutAttribute.xml
-M      en/System.Runtime.InteropServices/InvalidComObjectException.xml
-M      en/System.Runtime.InteropServices/_ConstructorBuilder.xml
-M      en/System.Runtime.InteropServices/_ParameterInfo.xml
-M      en/System.Runtime.InteropServices/COMException.xml
-M      en/System.Runtime.InteropServices/DispIdAttribute.xml
-M      en/System.Runtime.InteropServices/DispatchWrapper.xml
-M      en/System.Runtime.InteropServices/ExternalException.xml
-M      en/System.Runtime.InteropServices/INVOKEKIND.xml
-M      en/System.Runtime.InteropServices/IDLFLAG.xml
-M      en/System.Runtime.InteropServices/MarshalDirectiveException.xml
-M      en/System.Runtime.InteropServices/StructLayoutAttribute.xml
-M      en/System.Runtime.InteropServices/_Thread.xml
-M      en/System.Runtime.InteropServices/RuntimeEnvironment.xml
-M      en/System.Runtime.InteropServices/ComConversionLossAttribute.xml
-M      en/System.Runtime.InteropServices/UCOMIRunningObjectTable.xml
-M      en/System.Runtime.InteropServices/CallingConvention.xml
-M      en/System.Runtime.InteropServices/_AssemblyName.xml
-M      en/System.Runtime.InteropServices/ComUnregisterFunctionAttribute.xml
-M      en/System.Runtime.InteropServices/EXCEPINFO.xml
-M      en/System.Runtime.InteropServices/SYSKIND.xml
-M      en/System.Runtime.InteropServices/_AssemblyBuilder.xml
-M      en/System.Runtime.InteropServices/UCOMIPersistFile.xml
-M      en/System.Runtime.InteropServices/_TypeBuilder.xml
-M      en/System.Runtime.InteropServices/UCOMIStream.xml
-M      en/System.Runtime.InteropServices/STATSTG.xml
-M      en/System.Runtime.InteropServices/FUNCDESC.xml
-M      en/System.Runtime.InteropServices/_MethodInfo.xml
-M      en/System.Runtime.InteropServices/FILETIME.xml
-M      en/System.Runtime.InteropServices/PARAMDESC.xml
-M      en/System.Runtime.InteropServices/MarshalAsAttribute.xml
-M      en/System.Runtime.InteropServices/_Attribute.xml
-M      en/System.Runtime.InteropServices/DISPPARAMS.xml
-M      en/System.Runtime.InteropServices/UCOMITypeLib.xml
-M      en/System.Runtime.InteropServices/TypeLibVarAttribute.xml
-M      en/System.Runtime.InteropServices/VARFLAGS.xml
-M      en/System.Runtime.InteropServices/VariantWrapper.xml
-M      en/System.Runtime.InteropServices/TypeLibFuncAttribute.xml
-M      en/System.Runtime.InteropServices/ComAliasNameAttribute.xml
-M      en/System.Runtime.InteropServices/TypeLibExporterFlags.xml
-M      en/System.Runtime.InteropServices/ComVisibleAttribute.xml
-M      en/System.Runtime.InteropServices/BIND_OPTS.xml
-M      en/System.Runtime.InteropServices/TYPEKIND.xml
-M      en/System.Runtime.InteropServices/SetWin32ContextInIDispatchAttribute.xml
-M      en/System.Runtime.InteropServices/IRegistrationServices.xml
-M      en/System.Runtime.InteropServices/VARDESC.xml
-M      en/System.Runtime.InteropServices/_ModuleBuilder.xml
-M      en/System.Runtime.InteropServices/ComImportAttribute.xml
-M      en/System.Runtime.InteropServices/TypeLibFuncFlags.xml
-M      en/System.Runtime.InteropServices/UnmanagedType.xml
-M      en/System.Runtime.InteropServices/TYPELIBATTR.xml
-M      en/System.Runtime.InteropServices/IDLDESC.xml
-M      en/System.Runtime.InteropServices/ProgIdAttribute.xml
-M      en/System.Runtime.InteropServices/PrimaryInteropAssemblyAttribute.xml
-M      en/System.Runtime.InteropServices/ComMemberType.xml
-M      en/System.Runtime.InteropServices/VARDESC+DESCUNION.xml
-M      en/System.Runtime.InteropServices/_MethodBase.xml
-M      en/System.Runtime.InteropServices/CoClassAttribute.xml
-M      en/System.Runtime.InteropServices/ICustomFactory.xml
-M      en/System.Runtime.InteropServices/IDispatchImplAttribute.xml
-M      en/System.Runtime.InteropServices/ExtensibleClassFactory.xml
-M      en/System.Runtime.InteropServices/ELEMDESC.xml
-M      en/System.Runtime.InteropServices/LIBFLAGS.xml
-M      en/System.Runtime.InteropServices/ImportedFromTypeLibAttribute.xml
-M      en/System.Runtime.InteropServices/_Module.xml
-M      en/System.Runtime.InteropServices/UCOMIEnumVARIANT.xml
-M      en/System.Runtime.InteropServices/_ParameterBuilder.xml
-M      en/System.Runtime.InteropServices/Marshal.xml
-M      en/System.Runtime.InteropServices/_EventBuilder.xml
-M      en/System.Runtime.InteropServices/_FieldBuilder.xml
-M      en/System.Runtime.InteropServices/ErrorWrapper.xml
-M      en/System.Runtime.InteropServices/_Activator.xml
-M      en/System.Runtime.InteropServices/RegistrationConnectionType.xml
-M      en/System.Runtime.InteropServices/IDispatchImplType.xml
-M      en/System.Runtime.InteropServices/SEHException.xml
-M      en/System.Runtime.InteropServices/_LocalBuilder.xml
-M      en/System.Runtime.InteropServices/RegistrationClassContext.xml
-M      en/System.Runtime.InteropServices/GCHandle.xml
-M      en/System.Runtime.InteropServices/UCOMIConnectionPoint.xml
-M      en/System.Runtime.InteropServices/CriticalHandle.xml
-M      en/System.Runtime.InteropServices/FUNCFLAGS.xml
-M      en/System.Runtime.InteropServices/ImporterEventKind.xml
-M      en/System.Runtime.InteropServices/_EnumBuilder.xml
-M      en/System.Runtime.InteropServices/TypeLibImportClassAttribute.xml
-M      en/System.Runtime.InteropServices/_Assembly.xml
-M      en/System.Runtime.InteropServices/DESCKIND.xml
-M      en/System.Runtime.InteropServices/ComEventInterfaceAttribute.xml
-M      en/System.Runtime.InteropServices/_MethodRental.xml
-M      en/System.Runtime.InteropServices/UCOMIEnumMoniker.xml
-M      en/System.Runtime.InteropServices/_MethodBuilder.xml
-M      en/System.Runtime.InteropServices/ClassInterfaceType.xml
-M      en/System.Runtime.InteropServices/CharSet.xml
-M      en/System.Runtime.InteropServices/UCOMITypeInfo.xml
-M      en/System.Runtime.InteropServices/_PropertyBuilder.xml
-M      en/System.Runtime.InteropServices/InvalidOleVariantTypeException.xml
-M      en/System.Runtime.InteropServices/TypeLibTypeAttribute.xml
-M      en/System.Runtime.InteropServices/BestFitMappingAttribute.xml
-M      en/System.Runtime.InteropServices/_SignatureHelper.xml
-M      en/System.Runtime.InteropServices/UCOMIMoniker.xml
-M      en/System.Runtime.InteropServices/TypeLibImporterFlags.xml
-M      en/System.Runtime.InteropServices/UCOMIConnectionPointContainer.xml
-M      en/System.Runtime.InteropServices/BStrWrapper.xml
-M      en/System.Runtime.InteropServices/TYPEATTR.xml
-M      en/System.Runtime.InteropServices/GuidAttribute.xml
-M      en/System.Runtime.Remoting.Activation/ActivatorLevel.xml
-M      en/System.Runtime.Remoting.Activation/IConstructionCallMessage.xml
-M      en/System.Runtime.Remoting.Activation/IActivator.xml
-M      en/System.Runtime.Remoting.Activation/UrlAttribute.xml
-M      en/System.Runtime.Remoting.Activation/IConstructionReturnMessage.xml
-M      en/System.Resources/ResourceManager.xml
-M      en/System.Resources/IResourceReader.xml
-M      en/System.Resources/ResourceSet.xml
-M      en/System.Resources/ResourceWriter.xml
-M      en/System.Resources/UltimateResourceFallbackLocation.xml
-M      en/System.Resources/MissingManifestResourceException.xml
-M      en/System.Resources/ResourceReader.xml
-M      en/System.Resources/IResourceWriter.xml
-M      en/System.Resources/NeutralResourcesLanguageAttribute.xml
-M      en/System.Resources/SatelliteContractVersionAttribute.xml
-M      en/System.Resources/MissingSatelliteAssemblyException.xml
-M      en/System.Runtime.Remoting.Contexts/IContributeClientContextSink.xml
-M      en/System.Runtime.Remoting.Contexts/IContextAttribute.xml
-M      en/System.Runtime.Remoting.Contexts/IContributeDynamicSink.xml
-M      en/System.Runtime.Remoting.Contexts/Context.xml
-M      en/System.Runtime.Remoting.Contexts/SynchronizationAttribute.xml
-M      en/System.Runtime.Remoting.Contexts/IDynamicMessageSink.xml
-M      en/System.Runtime.Remoting.Contexts/ContextProperty.xml
-M      en/System.Runtime.Remoting.Contexts/CrossContextDelegate.xml
-M      en/System.Runtime.Remoting.Contexts/IContributeEnvoySink.xml
-M      en/System.Runtime.Remoting.Contexts/IContextProperty.xml
-M      en/System.Runtime.Remoting.Contexts/IDynamicProperty.xml
-M      en/System.Runtime.Remoting.Contexts/IContributeObjectSink.xml
-M      en/System.Runtime.Remoting.Contexts/ContextAttribute.xml
-M      en/System.Runtime.Remoting.Contexts/IContributeServerContextSink.xml
-M      en/System.Runtime.Remoting.Contexts/IContextPropertyActivator.xml
-?      en/System.Collections/StructuralComparisons.xml
-?      en/System.Collections/IStructuralEquatable.xml
-?      en/System.Collections/IStructuralComparable.xml
-M      en/System.Collections/IDictionaryEnumerator.xml
-M      en/System.Collections/IComparer.xml
-M      en/System.Collections/IList.xml
-M      en/System.Collections/Queue.xml
-M      en/System.Collections/ReadOnlyCollectionBase.xml
-M      en/System.Collections/CaseInsensitiveComparer.xml
-M      en/System.Collections/CollectionBase.xml
-M      en/System.Collections/DictionaryEntry.xml
-M      en/System.Collections/IEnumerable.xml
-M      en/System.Collections/IEnumerator.xml
-M      en/System.Collections/Hashtable.xml
-M      en/System.Collections/SortedList.xml
-M      en/System.Collections/IEqualityComparer.xml
-M      en/System.Collections/DictionaryBase.xml
-M      en/System.Collections/IHashCodeProvider.xml
-M      en/System.Collections/ICollection.xml
-M      en/System.Collections/Stack.xml
-M      en/System.Collections/CaseInsensitiveHashCodeProvider.xml
-M      en/System.Collections/Comparer.xml
-M      en/System.Collections/ArrayList.xml
-M      en/System.Collections/BitArray.xml
-M      en/System.Collections/IDictionary.xml
-M      en/System.Runtime.ConstrainedExecution/Consistency.xml
-M      en/System.Runtime.ConstrainedExecution/CriticalFinalizerObject.xml
-M      en/System.Runtime.ConstrainedExecution/Cer.xml
-M      en/System.Runtime.ConstrainedExecution/PrePrepareMethodAttribute.xml
-M      en/System.Runtime.ConstrainedExecution/ReliabilityContractAttribute.xml
-M      en/System.Diagnostics.CodeAnalysis/SuppressMessageAttribute.xml
-M      en/System.Reflection.Emit/TypeToken.xml
-M      en/System.Reflection.Emit/MethodRental.xml
-M      en/System.Reflection.Emit/AssemblyBuilder.xml
-M      en/System.Reflection.Emit/TypeBuilder.xml
-M      en/System.Reflection.Emit/OperandType.xml
-M      en/System.Reflection.Emit/OpCodes.xml
-M      en/System.Reflection.Emit/ConstructorBuilder.xml
-M      en/System.Reflection.Emit/PackingSize.xml
-M      en/System.Reflection.Emit/StringToken.xml
-M      en/System.Reflection.Emit/OpCode.xml
-M      en/System.Reflection.Emit/StackBehaviour.xml
-M      en/System.Reflection.Emit/EnumBuilder.xml
-M      en/System.Reflection.Emit/ILGenerator.xml
-M      en/System.Reflection.Emit/ParameterToken.xml
-M      en/System.Reflection.Emit/MethodToken.xml
-M      en/System.Reflection.Emit/EventToken.xml
-M      en/System.Reflection.Emit/FieldToken.xml
-M      en/System.Reflection.Emit/PropertyToken.xml
-M      en/System.Reflection.Emit/DynamicILInfo.xml
-M      en/System.Reflection.Emit/DynamicMethod.xml
-M      en/System.Reflection.Emit/GenericTypeParameterBuilder.xml
-M      en/System.Reflection.Emit/ParameterBuilder.xml
-M      en/System.Reflection.Emit/MethodBuilder.xml
-M      en/System.Reflection.Emit/EventBuilder.xml
-M      en/System.Reflection.Emit/FieldBuilder.xml
-M      en/System.Reflection.Emit/PropertyBuilder.xml
-M      en/System.Reflection.Emit/ModuleBuilder.xml
-M      en/System.Reflection.Emit/PEFileKinds.xml
-M      en/System.Reflection.Emit/SignatureHelper.xml
-M      en/System.Reflection.Emit/LocalBuilder.xml
-M      en/System.Reflection.Emit/SignatureToken.xml
-M      en/System.Reflection.Emit/CustomAttributeBuilder.xml
-M      en/System.Reflection.Emit/UnmanagedMarshal.xml
-M      en/System.Reflection.Emit/AssemblyBuilderAccess.xml
-M      en/System.Reflection.Emit/FlowControl.xml
-M      en/System.Reflection.Emit/OpCodeType.xml
-M      en/System.Reflection.Emit/Label.xml
-M      en/System.Collections.Generic/IEqualityComparer`1.xml
-M      en/System.Collections.Generic/KeyValuePair`2.xml
-M      en/System.Collections.Generic/KeyNotFoundException.xml
-M      en/System.Collections.Generic/ICollection`1.xml
-M      en/System.Collections.Generic/Dictionary`2.xml
-M      en/System.Collections.Generic/Dictionary`2+KeyCollection.xml
-M      en/System.Collections.Generic/Dictionary`2+ValueCollection+Enumerator.xml
-M      en/System.Collections.Generic/Comparer`1.xml
-M      en/System.Collections.Generic/List`1.xml
-M      en/System.Collections.Generic/IDictionary`2.xml
-M      en/System.Collections.Generic/IComparer`1.xml
-M      en/System.Collections.Generic/Dictionary`2+KeyCollection+Enumerator.xml
-M      en/System.Collections.Generic/Dictionary`2+Enumerator.xml
-M      en/System.Collections.Generic/IList`1.xml
-M      en/System.Collections.Generic/EqualityComparer`1.xml
-M      en/System.Collections.Generic/IEnumerable`1.xml
-M      en/System.Collections.Generic/List`1+Enumerator.xml
-M      en/System.Collections.Generic/IEnumerator`1.xml
-M      en/System.Collections.Generic/Dictionary`2+ValueCollection.xml
-M      en/System.Deployment.Internal/InternalActivationContextHelper.xml
-M      en/System.Deployment.Internal/InternalApplicationIdentityHelper.xml
-?      en/System.Globalization/TimeSpanStyles.xml
-?      en/System.Globalization/CultureNotFoundException.xml
-M      en/System.Globalization/JapaneseCalendar.xml
-M      en/System.Globalization/DateTimeFormatInfo.xml
-M      en/System.Globalization/CalendarAlgorithmType.xml
-M      en/System.Globalization/DaylightTime.xml
-M      en/System.Globalization/UnicodeCategory.xml
-M      en/System.Globalization/IdnMapping.xml
-M      en/System.Globalization/HijriCalendar.xml
-M      en/System.Globalization/CultureInfo.xml
-M      en/System.Globalization/TextElementEnumerator.xml
-M      en/System.Globalization/KoreanLunisolarCalendar.xml
-M      en/System.Globalization/DigitShapes.xml
-M      en/System.Globalization/TaiwanLunisolarCalendar.xml
-M      en/System.Globalization/GregorianCalendar.xml
-M      en/System.Globalization/KoreanCalendar.xml
-M      en/System.Globalization/JapaneseLunisolarCalendar.xml
-M      en/System.Globalization/TaiwanCalendar.xml
-M      en/System.Globalization/CalendarWeekRule.xml
-M      en/System.Globalization/UmAlQuraCalendar.xml
-M      en/System.Globalization/StringInfo.xml
-M      en/System.Globalization/PersianCalendar.xml
-M      en/System.Globalization/EastAsianLunisolarCalendar.xml
-M      en/System.Globalization/NumberStyles.xml
-M      en/System.Globalization/GregorianCalendarTypes.xml
-M      en/System.Globalization/RegionInfo.xml
-M      en/System.Globalization/SortKey.xml
-M      en/System.Globalization/CharUnicodeInfo.xml
-M      en/System.Globalization/DateTimeStyles.xml
-M      en/System.Globalization/TextInfo.xml
-M      en/System.Globalization/ChineseLunisolarCalendar.xml
-M      en/System.Globalization/CompareInfo.xml
-M      en/System.Globalization/CompareOptions.xml
-M      en/System.Globalization/HebrewCalendar.xml
-M      en/System.Globalization/ThaiBuddhistCalendar.xml
-M      en/System.Globalization/CultureTypes.xml
-M      en/System.Globalization/Calendar.xml
-M      en/System.Globalization/JulianCalendar.xml
-M      en/System.Globalization/NumberFormatInfo.xml
-M      en/System.Runtime.Remoting.Channels/IClientChannelSinkProvider.xml
-M      en/System.Runtime.Remoting.Channels/IChannel.xml
-M      en/System.Runtime.Remoting.Channels/ClientChannelSinkStack.xml
-M      en/System.Runtime.Remoting.Channels/IChannelSender.xml
-M      en/System.Runtime.Remoting.Channels/IServerChannelSinkStack.xml
-M      en/System.Runtime.Remoting.Channels/IChannelReceiverHook.xml
-M      en/System.Runtime.Remoting.Channels/TransportHeaders.xml
-M      en/System.Runtime.Remoting.Channels/IChannelDataStore.xml
-M      en/System.Runtime.Remoting.Channels/IClientChannelSinkStack.xml
-M      en/System.Runtime.Remoting.Channels/IServerChannelSink.xml
-M      en/System.Runtime.Remoting.Channels/IClientFormatterSink.xml
-M      en/System.Runtime.Remoting.Channels/ITransportHeaders.xml
-M      en/System.Runtime.Remoting.Channels/BaseChannelSinkWithProperties.xml
-M      en/System.Runtime.Remoting.Channels/IChannelSinkBase.xml
-M      en/System.Runtime.Remoting.Channels/IServerResponseChannelSinkStack.xml
-M      en/System.Runtime.Remoting.Channels/BaseChannelObjectWithProperties.xml
-M      en/System.Runtime.Remoting.Channels/IServerFormatterSinkProvider.xml
-M      en/System.Runtime.Remoting.Channels/ServerProcessing.xml
-M      en/System.Runtime.Remoting.Channels/IClientChannelSink.xml
-M      en/System.Runtime.Remoting.Channels/IChannelReceiver.xml
-M      en/System.Runtime.Remoting.Channels/ISecurableChannel.xml
-M      en/System.Runtime.Remoting.Channels/IServerChannelSinkProvider.xml
-M      en/System.Runtime.Remoting.Channels/SinkProviderData.xml
-M      en/System.Runtime.Remoting.Channels/IClientResponseChannelSinkStack.xml
-M      en/System.Runtime.Remoting.Channels/ServerChannelSinkStack.xml
-M      en/System.Runtime.Remoting.Channels/IClientFormatterSinkProvider.xml
-M      en/System.Runtime.Remoting.Channels/ChannelServices.xml
-M      en/System.Runtime.Remoting.Channels/BaseChannelWithProperties.xml
-M      en/System.Runtime.Remoting.Channels/ChannelDataStore.xml
-M      en/System.Collections.ObjectModel/ReadOnlyCollection`1.xml
-M      en/System.Collections.ObjectModel/Collection`1.xml
-M      en/System.Collections.ObjectModel/KeyedCollection`2.xml
-M      en/System.Diagnostics/StackFrame.xml
-M      en/System.Diagnostics/DebuggableAttribute+DebuggingModes.xml
-M      en/System.Diagnostics/Debugger.xml
-M      en/System.Diagnostics/DebuggerHiddenAttribute.xml
-M      en/System.Diagnostics/StackTrace.xml
-M      en/System.Diagnostics/DebuggerBrowsableState.xml
-M      en/System.Diagnostics/DebuggerVisualizerAttribute.xml
-M      en/System.Diagnostics/ConditionalAttribute.xml
-M      en/System.Diagnostics/DebuggerDisplayAttribute.xml
-M      en/System.Diagnostics/DebuggableAttribute.xml
-M      en/System.Diagnostics/DebuggerStepThroughAttribute.xml
-M      en/System.Diagnostics/DebuggerBrowsableAttribute.xml
-M      en/System.Diagnostics/DebuggerTypeProxyAttribute.xml
-M      en/System.Diagnostics/DebuggerNonUserCodeAttribute.xml
-M      en/System.Diagnostics/DebuggerStepperBoundaryAttribute.xml
-M      en/System.Runtime.InteropServices.ComTypes/IMPLTYPEFLAGS.xml
-M      en/System.Runtime.InteropServices.ComTypes/EXCEPINFO.xml
-M      en/System.Runtime.InteropServices.ComTypes/ELEMDESC.xml
-M      en/System.Runtime.InteropServices.ComTypes/CONNECTDATA.xml
-M      en/System.Runtime.InteropServices.ComTypes/LIBFLAGS.xml
-M      en/System.Runtime.InteropServices.ComTypes/SYSKIND.xml
-M      en/System.Runtime.InteropServices.ComTypes/IConnectionPointContainer.xml
-M      en/System.Runtime.InteropServices.ComTypes/ITypeInfo2.xml
-M      en/System.Runtime.InteropServices.ComTypes/IRunningObjectTable.xml
-M      en/System.Runtime.InteropServices.ComTypes/STATSTG.xml
-M      en/System.Runtime.InteropServices.ComTypes/IEnumConnectionPoints.xml
-M      en/System.Runtime.InteropServices.ComTypes/FUNCDESC.xml
-M      en/System.Runtime.InteropServices.ComTypes/PARAMFLAG.xml
-M      en/System.Runtime.InteropServices.ComTypes/FILETIME.xml
-M      en/System.Runtime.InteropServices.ComTypes/PARAMDESC.xml
-M      en/System.Runtime.InteropServices.ComTypes/FUNCKIND.xml
-M      en/System.Runtime.InteropServices.ComTypes/IPersistFile.xml
-M      en/System.Runtime.InteropServices.ComTypes/IEnumVARIANT.xml
-M      en/System.Runtime.InteropServices.ComTypes/BINDPTR.xml
-M      en/System.Runtime.InteropServices.ComTypes/DISPPARAMS.xml
-M      en/System.Runtime.InteropServices.ComTypes/ITypeLib2.xml
-M      en/System.Runtime.InteropServices.ComTypes/IStream.xml
-M      en/System.Runtime.InteropServices.ComTypes/IEnumString.xml
-M      en/System.Runtime.InteropServices.ComTypes/ELEMDESC+DESCUNION.xml
-M      en/System.Runtime.InteropServices.ComTypes/IBindCtx.xml
-M      en/System.Runtime.InteropServices.ComTypes/VARFLAGS.xml
-M      en/System.Runtime.InteropServices.ComTypes/FUNCFLAGS.xml
-M      en/System.Runtime.InteropServices.ComTypes/ITypeComp.xml
-M      en/System.Runtime.InteropServices.ComTypes/IEnumConnections.xml
-M      en/System.Runtime.InteropServices.ComTypes/TYPEDESC.xml
-M      en/System.Runtime.InteropServices.ComTypes/BIND_OPTS.xml
-M      en/System.Runtime.InteropServices.ComTypes/ITypeLib.xml
-M      en/System.Runtime.InteropServices.ComTypes/IConnectionPoint.xml
-M      en/System.Runtime.InteropServices.ComTypes/DESCKIND.xml
-M      en/System.Runtime.InteropServices.ComTypes/TYPEKIND.xml
-M      en/System.Runtime.InteropServices.ComTypes/VARDESC.xml
-M      en/System.Runtime.InteropServices.ComTypes/TYPEFLAGS.xml
-M      en/System.Runtime.InteropServices.ComTypes/VARKIND.xml
-M      en/System.Runtime.InteropServices.ComTypes/INVOKEKIND.xml
-M      en/System.Runtime.InteropServices.ComTypes/CALLCONV.xml
-M      en/System.Runtime.InteropServices.ComTypes/IEnumMoniker.xml
-M      en/System.Runtime.InteropServices.ComTypes/IDLFLAG.xml
-M      en/System.Runtime.InteropServices.ComTypes/TYPELIBATTR.xml
-M      en/System.Runtime.InteropServices.ComTypes/ITypeInfo.xml
-M      en/System.Runtime.InteropServices.ComTypes/IDLDESC.xml
-M      en/System.Runtime.InteropServices.ComTypes/VARDESC+DESCUNION.xml
-M      en/System.Runtime.InteropServices.ComTypes/TYPEATTR.xml
-M      en/System.Runtime.InteropServices.ComTypes/IMoniker.xml
-M      en/index.xml
-M      en/System.Text/DecoderFallback.xml
-M      en/System.Text/Encoding.xml
-M      en/System.Text/EncoderFallbackBuffer.xml
-M      en/System.Text/UTF7Encoding.xml
-M      en/System.Text/UTF8Encoding.xml
-M      en/System.Text/UnicodeEncoding.xml
-M      en/System.Text/DecoderExceptionFallbackBuffer.xml
-M      en/System.Text/EncoderFallback.xml
-M      en/System.Text/DecoderReplacementFallbackBuffer.xml
-M      en/System.Text/ASCIIEncoding.xml
-M      en/System.Text/EncodingInfo.xml
-M      en/System.Text/DecoderFallbackException.xml
-M      en/System.Text/DecoderExceptionFallback.xml
-M      en/System.Text/DecoderReplacementFallback.xml
-M      en/System.Text/Decoder.xml
-M      en/System.Text/EncoderExceptionFallbackBuffer.xml
-M      en/System.Text/EncoderReplacementFallbackBuffer.xml
-M      en/System.Text/NormalizationForm.xml
-M      en/System.Text/UTF32Encoding.xml
-M      en/System.Text/StringBuilder.xml
-M      en/System.Text/EncoderFallbackException.xml
-M      en/System.Text/EncoderExceptionFallback.xml
-M      en/System.Text/EncoderReplacementFallback.xml
-M      en/System.Text/Encoder.xml
-M      en/System.Text/DecoderFallbackBuffer.xml
-M      en/System.Runtime.Remoting.Metadata/SoapAttribute.xml
-M      en/System.Runtime.Remoting.Metadata/SoapMethodAttribute.xml
-M      en/System.Runtime.Remoting.Metadata/SoapParameterAttribute.xml
-M      en/System.Runtime.Remoting.Metadata/SoapTypeAttribute.xml
-M      en/System.Runtime.Remoting.Metadata/XmlFieldOrderOption.xml
-M      en/System.Runtime.Remoting.Metadata/SoapFieldAttribute.xml
-M      en/System.Runtime.Remoting.Metadata/SoapOption.xml
-M      en/System.Security.Cryptography.X509Certificates/X509KeyStorageFlags.xml
-M      en/System.Security.Cryptography.X509Certificates/X509ContentType.xml
-M      en/System.Security.Cryptography.X509Certificates/X509Certificate.xml
-M      en/System.Runtime.Remoting.Proxies/ProxyAttribute.xml
-M      en/System.Runtime.Remoting.Proxies/RealProxy.xml
-?      en/System.IO.IsolatedStorage/IsolatedStorageSecurityState.xml
-?      en/System.IO.IsolatedStorage/IsolatedStorageSecurityOptions.xml
-M      en/System.IO.IsolatedStorage/IsolatedStorageScope.xml
-M      en/System.IO.IsolatedStorage/IsolatedStorageFileStream.xml
-M      en/System.IO.IsolatedStorage/IsolatedStorageException.xml
-M      en/System.IO.IsolatedStorage/IsolatedStorage.xml
-M      en/System.IO.IsolatedStorage/IsolatedStorageFile.xml
-M      en/System.IO.IsolatedStorage/INormalizeForIsolatedStorage.xml
-?      en/System.Runtime.CompilerServices/ConditionalWeakTable`2.xml
-?      en/System.Runtime.CompilerServices/ReferenceAssemblyAttribute.xml
-?      en/System.Runtime.CompilerServices/TypeForwardedFromAttribute.xml
-?      en/System.Runtime.CompilerServices/ConditionalWeakTable`2+CreateValueCallback.xml
-M      en/System.Runtime.CompilerServices/DiscardableAttribute.xml
-M      en/System.Runtime.CompilerServices/IsConst.xml
-M      en/System.Runtime.CompilerServices/IndexerNameAttribute.xml
-M      en/System.Runtime.CompilerServices/RuntimeWrappedException.xml
-M      en/System.Runtime.CompilerServices/MethodImplAttribute.xml
-M      en/System.Runtime.CompilerServices/CompilationRelaxations.xml
-M      en/System.Runtime.CompilerServices/DateTimeConstantAttribute.xml
-M      en/System.Runtime.CompilerServices/IsLong.xml
-M      en/System.Runtime.CompilerServices/LoadHint.xml
-M      en/System.Runtime.CompilerServices/IsByValue.xml
-M      en/System.Runtime.CompilerServices/NativeCppClassAttribute.xml
-M      en/System.Runtime.CompilerServices/InternalsVisibleToAttribute.xml
-M      en/System.Runtime.CompilerServices/IUnknownConstantAttribute.xml
-M      en/System.Runtime.CompilerServices/TypeForwardedToAttribute.xml
-M      en/System.Runtime.CompilerServices/IsImplicitlyDereferenced.xml
-M      en/System.Runtime.CompilerServices/DefaultDependencyAttribute.xml
-M      en/System.Runtime.CompilerServices/CallConvStdcall.xml
-M      en/System.Runtime.CompilerServices/CompilerGlobalScopeAttribute.xml
-M      en/System.Runtime.CompilerServices/ScopelessEnumAttribute.xml
-M      en/System.Runtime.CompilerServices/CallConvFastcall.xml
-M      en/System.Runtime.CompilerServices/RuntimeHelpers+TryCode.xml
-M      en/System.Runtime.CompilerServices/CompilationRelaxationsAttribute.xml
-M      en/System.Runtime.CompilerServices/IsExplicitlyDereferenced.xml
-M      en/System.Runtime.CompilerServices/MethodImplOptions.xml
-M      en/System.Runtime.CompilerServices/CompilerMarshalOverride.xml
-M      en/System.Runtime.CompilerServices/IsCopyConstructed.xml
-M      en/System.Runtime.CompilerServices/RuntimeHelpers+CleanupCode.xml
-M      en/System.Runtime.CompilerServices/StringFreezingAttribute.xml
-M      en/System.Runtime.CompilerServices/CallConvThiscall.xml
-M      en/System.Runtime.CompilerServices/FixedAddressValueTypeAttribute.xml
-M      en/System.Runtime.CompilerServices/IsUdtReturn.xml
-M      en/System.Runtime.CompilerServices/RequiredAttributeAttribute.xml
-M      en/System.Runtime.CompilerServices/CallConvCdecl.xml
-M      en/System.Runtime.CompilerServices/DecimalConstantAttribute.xml
-M      en/System.Runtime.CompilerServices/IsBoxed.xml
-M      en/System.Runtime.CompilerServices/IsSignUnspecifiedByte.xml
-M      en/System.Runtime.CompilerServices/HasCopySemanticsAttribute.xml
-M      en/System.Runtime.CompilerServices/RuntimeCompatibilityAttribute.xml
-M      en/System.Runtime.CompilerServices/DependencyAttribute.xml
-M      en/System.Runtime.CompilerServices/SuppressIldasmAttribute.xml
-M      en/System.Runtime.CompilerServices/AccessedThroughPropertyAttribute.xml
-M      en/System.Runtime.CompilerServices/UnsafeValueTypeAttribute.xml
-M      en/System.Runtime.CompilerServices/IsJitIntrinsic.xml
-M      en/System.Runtime.CompilerServices/SpecialNameAttribute.xml
-M      en/System.Runtime.CompilerServices/IDispatchConstantAttribute.xml
-M      en/System.Runtime.CompilerServices/RuntimeHelpers.xml
-M      en/System.Runtime.CompilerServices/CustomConstantAttribute.xml
-M      en/System.Runtime.CompilerServices/IsPinned.xml
-M      en/System.Runtime.CompilerServices/IsVolatile.xml
-M      en/System.Runtime.CompilerServices/FixedBufferAttribute.xml
-M      en/System.Runtime.CompilerServices/CompilerGeneratedAttribute.xml
-M      en/System.Runtime.CompilerServices/MethodCodeType.xml
-?      en/System.Security.Cryptography/Aes.xml
-M      en/System.Security.Cryptography/MD5CryptoServiceProvider.xml
-M      en/System.Security.Cryptography/RIPEMD160Managed.xml
-M      en/System.Security.Cryptography/RC2.xml
-M      en/System.Security.Cryptography/TripleDESCryptoServiceProvider.xml
-M      en/System.Security.Cryptography/RSAOAEPKeyExchangeFormatter.xml
-M      en/System.Security.Cryptography/CryptographicException.xml
-M      en/System.Security.Cryptography/HMACSHA384.xml
-M      en/System.Security.Cryptography/KeySizes.xml
-M      en/System.Security.Cryptography/DSA.xml
-M      en/System.Security.Cryptography/PasswordDeriveBytes.xml
-M      en/System.Security.Cryptography/MaskGenerationMethod.xml
-M      en/System.Security.Cryptography/KeyedHashAlgorithm.xml
-M      en/System.Security.Cryptography/RSA.xml
-M      en/System.Security.Cryptography/ICryptoTransform.xml
-M      en/System.Security.Cryptography/HMACSHA1.xml
-M      en/System.Security.Cryptography/AsymmetricKeyExchangeDeformatter.xml
-M      en/System.Security.Cryptography/Rijndael.xml
-M      en/System.Security.Cryptography/SHA1CryptoServiceProvider.xml
-M      en/System.Security.Cryptography/HashAlgorithm.xml
-M      en/System.Security.Cryptography/TripleDES.xml
-M      en/System.Security.Cryptography/HMACSHA512.xml
-M      en/System.Security.Cryptography/SHA1.xml
-M      en/System.Security.Cryptography/RandomNumberGenerator.xml
-M      en/System.Security.Cryptography/RSAPKCS1KeyExchangeDeformatter.xml
-M      en/System.Security.Cryptography/RSAOAEPKeyExchangeDeformatter.xml
-M      en/System.Security.Cryptography/CryptographicUnexpectedOperationException.xml
-M      en/System.Security.Cryptography/FromBase64Transform.xml
-M      en/System.Security.Cryptography/SignatureDescription.xml
-M      en/System.Security.Cryptography/CryptoAPITransform.xml
-M      en/System.Security.Cryptography/RIPEMD160.xml
-M      en/System.Security.Cryptography/DESCryptoServiceProvider.xml
-M      en/System.Security.Cryptography/SHA256.xml
-M      en/System.Security.Cryptography/PKCS1MaskGenerationMethod.xml
-M      en/System.Security.Cryptography/Rfc2898DeriveBytes.xml
-M      en/System.Security.Cryptography/CspKeyContainerInfo.xml
-M      en/System.Security.Cryptography/AsymmetricKeyExchangeFormatter.xml
-M      en/System.Security.Cryptography/HMACMD5.xml
-M      en/System.Security.Cryptography/SHA512Managed.xml
-M      en/System.Security.Cryptography/RSACryptoServiceProvider.xml
-M      en/System.Security.Cryptography/RNGCryptoServiceProvider.xml
-M      en/System.Security.Cryptography/RC2CryptoServiceProvider.xml
-M      en/System.Security.Cryptography/SymmetricAlgorithm.xml
-M      en/System.Security.Cryptography/RSAPKCS1KeyExchangeFormatter.xml
-M      en/System.Security.Cryptography/SHA384Managed.xml
-M      en/System.Security.Cryptography/DSAParameters.xml
-M      en/System.Security.Cryptography/CryptoStream.xml
-M      en/System.Security.Cryptography/AsymmetricSignatureDeformatter.xml
-M      en/System.Security.Cryptography/HMACRIPEMD160.xml
-M      en/System.Security.Cryptography/RijndaelManagedTransform.xml
-M      en/System.Security.Cryptography/KeyNumber.xml
-M      en/System.Security.Cryptography/RijndaelManaged.xml
-M      en/System.Security.Cryptography/RSAPKCS1SignatureDeformatter.xml
-M      en/System.Security.Cryptography/HMAC.xml
-M      en/System.Security.Cryptography/RSAParameters.xml
-M      en/System.Security.Cryptography/CspParameters.xml
-M      en/System.Security.Cryptography/FromBase64TransformMode.xml
-M      en/System.Security.Cryptography/SHA1Managed.xml
-M      en/System.Security.Cryptography/SHA384.xml
-M      en/System.Security.Cryptography/PaddingMode.xml
-M      en/System.Security.Cryptography/DES.xml
-M      en/System.Security.Cryptography/CipherMode.xml
-M      en/System.Security.Cryptography/AsymmetricSignatureFormatter.xml
-M      en/System.Security.Cryptography/ToBase64Transform.xml
-M      en/System.Security.Cryptography/AsymmetricAlgorithm.xml
-M      en/System.Security.Cryptography/MD5.xml
-M      en/System.Security.Cryptography/DeriveBytes.xml
-M      en/System.Security.Cryptography/SHA256Managed.xml
-M      en/System.Security.Cryptography/DSASignatureDeformatter.xml
-M      en/System.Security.Cryptography/RSAPKCS1SignatureFormatter.xml
-M      en/System.Security.Cryptography/CryptoStreamMode.xml
-M      en/System.Security.Cryptography/HMACSHA256.xml
-M      en/System.Security.Cryptography/ICspAsymmetricAlgorithm.xml
-M      en/System.Security.Cryptography/SHA512.xml
-M      en/System.Security.Cryptography/DSACryptoServiceProvider.xml
-M      en/System.Security.Cryptography/CryptoConfig.xml
-M      en/System.Security.Cryptography/MACTripleDES.xml
-M      en/System.Security.Cryptography/CspProviderFlags.xml
-M      en/System.Security.Cryptography/DSASignatureFormatter.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapYear.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapQName.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapNcName.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/ISoapXsd.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapAnyUri.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapNmtoken.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapEntity.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapDay.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapToken.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapNegativeInteger.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapName.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapMonthDay.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapLanguage.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapDuration.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapIdref.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapBase64Binary.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapNonNegativeInteger.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapNotation.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapDateTime.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapInteger.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapNmtokens.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapTime.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapYearMonth.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapIdrefs.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapDate.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapPositiveInteger.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapEntities.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapMonth.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapHexBinary.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapNonPositiveInteger.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapNormalizedString.xml
-M      en/System.Runtime.Remoting.Metadata.W3cXsd2001/SoapId.xml
-M      en/System.Runtime.Remoting.Lifetime/ClientSponsor.xml
-M      en/System.Runtime.Remoting.Lifetime/ILease.xml
-M      en/System.Runtime.Remoting.Lifetime/LifetimeServices.xml
-M      en/System.Runtime.Remoting.Lifetime/LeaseState.xml
-M      en/System.Runtime.Remoting.Lifetime/ISponsor.xml
-M      en/System.Security.Policy/PublisherMembershipCondition.xml
-M      en/System.Security.Policy/ApplicationTrustCollection.xml
-M      en/System.Security.Policy/Evidence.xml
-M      en/System.Security.Policy/Hash.xml
-M      en/System.Security.Policy/PolicyStatement.xml
-M      en/System.Security.Policy/UrlMembershipCondition.xml
-M      en/System.Security.Policy/ApplicationSecurityManager.xml
-M      en/System.Security.Policy/ApplicationVersionMatch.xml
-M      en/System.Security.Policy/SiteMembershipCondition.xml
-M      en/System.Security.Policy/CodeGroup.xml
-M      en/System.Security.Policy/FileCodeGroup.xml
-M      en/System.Security.Policy/ApplicationDirectory.xml
-M      en/System.Security.Policy/ZoneMembershipCondition.xml
-M      en/System.Security.Policy/UnionCodeGroup.xml
-M      en/System.Security.Policy/Url.xml
-M      en/System.Security.Policy/Site.xml
-M      en/System.Security.Policy/ApplicationTrust.xml
-M      en/System.Security.Policy/HashMembershipCondition.xml
-M      en/System.Security.Policy/CodeConnectAccess.xml
-M      en/System.Security.Policy/ApplicationSecurityInfo.xml
-M      en/System.Security.Policy/ApplicationTrustEnumerator.xml
-M      en/System.Security.Policy/PolicyStatementAttribute.xml
-M      en/System.Security.Policy/IApplicationTrustManager.xml
-M      en/System.Security.Policy/IMembershipCondition.xml
-M      en/System.Security.Policy/FirstMatchCodeGroup.xml
-M      en/System.Security.Policy/StrongName.xml
-M      en/System.Security.Policy/PolicyException.xml
-M      en/System.Security.Policy/TrustManagerUIContext.xml
-M      en/System.Security.Policy/TrustManagerContext.xml
-M      en/System.Security.Policy/PolicyLevel.xml
-M      en/System.Security.Policy/GacInstalled.xml
-M      en/System.Security.Policy/AllMembershipCondition.xml
-M      en/System.Security.Policy/Publisher.xml
-M      en/System.Security.Policy/NetCodeGroup.xml
-M      en/System.Security.Policy/StrongNameMembershipCondition.xml
-M      en/System.Security.Policy/IIdentityPermissionFactory.xml
-M      en/System.Security.Policy/PermissionRequestEvidence.xml
-M      en/System.Security.Policy/ApplicationDirectoryMembershipCondition.xml
-M      en/System.Security.Policy/Zone.xml
-M      en/System.Security.Policy/GacMembershipCondition.xml
-M      en/System.Runtime.Remoting/ObjectHandle.xml
-M      en/System.Runtime.Remoting/ServerException.xml
-M      en/System.Runtime.Remoting/InternalRemotingServices.xml
-M      en/System.Runtime.Remoting/IEnvoyInfo.xml
-M      en/System.Runtime.Remoting/WellKnownServiceTypeEntry.xml
-M      en/System.Runtime.Remoting/ActivatedClientTypeEntry.xml
-M      en/System.Runtime.Remoting/RemotingServices.xml
-M      en/System.Runtime.Remoting/IObjectHandle.xml
-M      en/System.Runtime.Remoting/IChannelInfo.xml
-M      en/System.Runtime.Remoting/CustomErrorsModes.xml
-M      en/System.Runtime.Remoting/RemotingException.xml
-M      en/System.Runtime.Remoting/TypeEntry.xml
-M      en/System.Runtime.Remoting/WellKnownClientTypeEntry.xml
-M      en/System.Runtime.Remoting/SoapServices.xml
-M      en/System.Runtime.Remoting/ObjRef.xml
-M      en/System.Runtime.Remoting/ActivatedServiceTypeEntry.xml
-M      en/System.Runtime.Remoting/RemotingTimeoutException.xml
-M      en/System.Runtime.Remoting/IRemotingTypeInfo.xml
-M      en/System.Runtime.Remoting/RemotingConfiguration.xml
-M      en/System.Runtime.Remoting/WellKnownObjectMode.xml
-?      en/System.IO/UnmanagedMemoryAccessor.xml
-M      en/System.IO/DirectoryInfo.xml
-M      en/System.IO/MemoryStream.xml
-M      en/System.IO/FileMode.xml
-M      en/System.IO/DriveInfo.xml
-M      en/System.IO/IOException.xml
-M      en/System.IO/FileAttributes.xml
-M      en/System.IO/StringReader.xml
-M      en/System.IO/Stream.xml
-M      en/System.IO/FileStream.xml
-M      en/System.IO/FileInfo.xml
-M      en/System.IO/SearchOption.xml
-M      en/System.IO/DirectoryNotFoundException.xml
-M      en/System.IO/FileAccess.xml
-M      en/System.IO/FileShare.xml
-M      en/System.IO/StringWriter.xml
-M      en/System.IO/Directory.xml
-M      en/System.IO/BinaryReader.xml
-M      en/System.IO/TextReader.xml
-M      en/System.IO/StreamReader.xml
-M      en/System.IO/File.xml
-M      en/System.IO/BinaryWriter.xml
-M      en/System.IO/TextWriter.xml
-M      en/System.IO/EndOfStreamException.xml
-M      en/System.IO/StreamWriter.xml
-M      en/System.IO/FileOptions.xml
-M      en/System.IO/Path.xml
-M      en/System.IO/BufferedStream.xml
-M      en/System.IO/FileLoadException.xml
-M      en/System.IO/SeekOrigin.xml
-M      en/System.IO/FileSystemInfo.xml
-M      en/System.IO/UnmanagedMemoryStream.xml
-M      en/System.IO/DriveNotFoundException.xml
-M      en/System.IO/FileNotFoundException.xml
-M      en/System.IO/DriveType.xml
-M      en/System.IO/PathTooLongException.xml
-?      en/System.Runtime/AssemblyTargetedPatchBandAttribute.xml
-?      en/System.Runtime/TargetedPatchingOptOutAttribute.xml
-M      en/System.Runtime/GCSettings.xml
-M      en/System.Runtime/GCLatencyMode.xml
-M      en/System.Runtime/MemoryFailPoint.xml
-?      en/Microsoft.Win32/RegistryView.xml
-?      en/Microsoft.Win32/RegistryOptions.xml
-M      en/Microsoft.Win32/RegistryKey.xml
-M      en/Microsoft.Win32/RegistryValueOptions.xml
-M      en/Microsoft.Win32/RegistryHive.xml
-M      en/Microsoft.Win32/Registry.xml
-M      en/Microsoft.Win32/RegistryKeyPermissionCheck.xml
-M      en/Microsoft.Win32/RegistryValueKind.xml
-M      en/System.Runtime.Serialization.Formatters/ISoapMessage.xml
-M      en/System.Runtime.Serialization.Formatters/ServerFault.xml
-M      en/System.Runtime.Serialization.Formatters/InternalST.xml
-M      en/System.Runtime.Serialization.Formatters/FormatterAssemblyStyle.xml
-M      en/System.Runtime.Serialization.Formatters/FormatterTypeStyle.xml
-M      en/System.Runtime.Serialization.Formatters/SoapMessage.xml
-M      en/System.Runtime.Serialization.Formatters/IFieldInfo.xml
-M      en/System.Runtime.Serialization.Formatters/InternalRM.xml
-M      en/System.Runtime.Serialization.Formatters/SoapFault.xml
-M      en/System.Runtime.Serialization.Formatters/TypeFilterLevel.xml
-M      en/System.Runtime.Remoting.Services/EnterpriseServicesHelper.xml
-M      en/System.Runtime.Remoting.Services/TrackingServices.xml
-M      en/System.Runtime.Remoting.Services/ITrackingHandler.xml
-M      en/System.Reflection/Pointer.xml
-M      en/System.Reflection/MemberInfo.xml
-M      en/System.Reflection/TypeFilter.xml
-M      en/System.Reflection/EventAttributes.xml
-M      en/System.Reflection/IReflect.xml
-M      en/System.Reflection/FieldInfo.xml
-M      en/System.Reflection/CallingConventions.xml
-M      en/System.Reflection/ObfuscationAttribute.xml
-M      en/System.Reflection/AssemblyTitleAttribute.xml
-M      en/System.Reflection/MethodImplAttributes.xml
-M      en/System.Reflection/MethodBase.xml
-M      en/System.Reflection/AssemblyKeyFileAttribute.xml
-M      en/System.Reflection/MemberFilter.xml
-M      en/System.Reflection/AssemblyName.xml
-M      en/System.Reflection/AssemblyFlagsAttribute.xml
-M      en/System.Reflection/GenericParameterAttributes.xml
-M      en/System.Reflection/Module.xml
-M      en/System.Reflection/ParameterAttributes.xml
-M      en/System.Reflection/AssemblyAlgorithmIdAttribute.xml
-M      en/System.Reflection/BindingFlags.xml
-M      en/System.Reflection/TypeAttributes.xml
-M      en/System.Reflection/PropertyAttributes.xml
-M      en/System.Reflection/ParameterInfo.xml
-M      en/System.Reflection/AssemblyCopyrightAttribute.xml
-M      en/System.Reflection/ResourceAttributes.xml
-M      en/System.Reflection/TargetInvocationException.xml
-M      en/System.Reflection/DefaultMemberAttribute.xml
-M      en/System.Reflection/PropertyInfo.xml
-M      en/System.Reflection/ConstructorInfo.xml
-M      en/System.Reflection/PortableExecutableKinds.xml
-M      en/System.Reflection/AssemblyDelaySignAttribute.xml
-M      en/System.Reflection/AssemblyCultureAttribute.xml
-M      en/System.Reflection/Missing.xml
-M      en/System.Reflection/ReflectionTypeLoadException.xml
-M      en/System.Reflection/LocalVariableInfo.xml
-M      en/System.Reflection/InterfaceMapping.xml
-M      en/System.Reflection/ResourceLocation.xml
-M      en/System.Reflection/AssemblyDefaultAliasAttribute.xml
-M      en/System.Reflection/ModuleResolveEventHandler.xml
-M      en/System.Reflection/CustomAttributeFormatException.xml
-M      en/System.Reflection/AmbiguousMatchException.xml
-M      en/System.Reflection/CustomAttributeData.xml
-M      en/System.Reflection/FieldAttributes.xml
-M      en/System.Reflection/AssemblyCompanyAttribute.xml
-M      en/System.Reflection/AssemblyInformationalVersionAttribute.xml
-M      en/System.Reflection/EventInfo.xml
-M      en/System.Reflection/AssemblyNameFlags.xml
-M      en/System.Reflection/MethodBody.xml
-M      en/System.Reflection/InvalidFilterCriteriaException.xml
-M      en/System.Reflection/AssemblyTrademarkAttribute.xml
-M      en/System.Reflection/ObfuscateAssemblyAttribute.xml
-M      en/System.Reflection/StrongNameKeyPair.xml
-M      en/System.Reflection/Binder.xml
-M      en/System.Reflection/AssemblyProductAttribute.xml
-M      en/System.Reflection/CustomAttributeTypedArgument.xml
-M      en/System.Reflection/TypeDelegator.xml
-M      en/System.Reflection/ExceptionHandlingClauseOptions.xml
-M      en/System.Reflection/AssemblyKeyNameAttribute.xml
-M      en/System.Reflection/TargetParameterCountException.xml
-M      en/System.Reflection/ProcessorArchitecture.xml
-M      en/System.Reflection/ICustomAttributeProvider.xml
-M      en/System.Reflection/AssemblyNameProxy.xml
-M      en/System.Reflection/MethodAttributes.xml
-M      en/System.Reflection/ManifestResourceInfo.xml
-M      en/System.Reflection/AssemblyConfigurationAttribute.xml
-M      en/System.Reflection/MethodInfo.xml
-M      en/System.Reflection/MemberTypes.xml
-M      en/System.Reflection/ParameterModifier.xml
-M      en/System.Reflection/ExceptionHandlingClause.xml
-M      en/System.Reflection/TargetException.xml
-M      en/System.Reflection/CustomAttributeNamedArgument.xml
-M      en/System.Reflection/ImageFileMachine.xml
-M      en/System.Reflection/AssemblyDescriptionAttribute.xml
-M      en/System.Reflection/AssemblyFileVersionAttribute.xml
-M      en/System.Reflection/AssemblyVersionAttribute.xml
-M      en/System.Reflection/Assembly.xml
index a0f17b0f19628aa6324538c6b019eb9e263223f7..c05eb88982187a2070f9c67e3eec257a9d60caf9 100644 (file)
@@ -35,7 +35,7 @@ RESOURCE_FILES = \
        resources/collation.cjkKO.bin \
        resources/collation.cjkKOlv2.bin
 
-REFERENCE_SOURCES_FLAGS = -d:FEATURE_PAL,GENERICS_WORK,FEATURE_LIST_PREDICATES,FEATURE_SERIALIZATION,FEATURE_ASCII,FEATURE_LATIN1,FEATURE_UTF7,FEATURE_UTF32,MONO_HYBRID_ENCODING_SUPPORT,FEATURE_ASYNC_IO,NEW_EXPERIMENTAL_ASYNC_IO,FEATURE_UTF32,FEATURE_EXCEPTIONDISPATCHINFO,FEATURE_CORRUPTING_EXCEPTIONS,FEATURE_EXCEPTION_NOTIFICATIONS,FEATURE_STRONGNAME_MIGRATION,FEATURE_USE_LCID,FEATURE_FUSION,FEATURE_CRYPTO,FEATURE_X509_SECURESTRINGS,FEATURE_SYNCHRONIZATIONCONTEXT,FEATURE_SYNCHRONIZATIONCONTEXT_WAIT
+REFERENCE_SOURCES_FLAGS = -d:FEATURE_PAL,GENERICS_WORK,FEATURE_LIST_PREDICATES,FEATURE_SERIALIZATION,FEATURE_ASCII,FEATURE_LATIN1,FEATURE_UTF7,FEATURE_UTF32,MONO_HYBRID_ENCODING_SUPPORT,FEATURE_ASYNC_IO,NEW_EXPERIMENTAL_ASYNC_IO,FEATURE_UTF32,FEATURE_EXCEPTIONDISPATCHINFO,FEATURE_CORRUPTING_EXCEPTIONS,FEATURE_EXCEPTION_NOTIFICATIONS,FEATURE_STRONGNAME_MIGRATION,FEATURE_USE_LCID,FEATURE_FUSION,FEATURE_CRYPTO,FEATURE_X509_SECURESTRINGS,FEATURE_SYNCHRONIZATIONCONTEXT,FEATURE_SYNCHRONIZATIONCONTEXT_WAIT,HAS_CORLIB_CONTRACTS
 
 ifndef MOBILE_PROFILE
 REFERENCE_SOURCES_FLAGS += -d:FEATURE_MACL
index 7a5f9887c6334fff01b0f7f9835659b44fac9be3..12148ed85d84c200f318fe12be0d087504dfff80 100644 (file)
@@ -31,7 +31,7 @@ using System.Runtime.CompilerServices;
 
 namespace Mono {
 
-#if MOBILE
+#if MOBILE || XAMMAC_4_5
        public
 #endif
        static class Runtime
@@ -40,16 +40,31 @@ namespace Mono {
                [MethodImplAttribute (MethodImplOptions.InternalCall)]
                private static extern void mono_runtime_install_handlers ();
 
-               static internal void InstallSignalHandlers ()
+#if MOBILE || XAMMAC_4_5
+               public
+#else
+               internal
+#endif
+               static void InstallSignalHandlers ()
                {
                        mono_runtime_install_handlers ();
                }
 
+#if MOBILE || XAMMAC_4_5
+               [MethodImplAttribute (MethodImplOptions.InternalCall)]
+               static extern void mono_runtime_cleanup_handlers ();
+
+               public static void RemoveSignalHandlers ()
+               {
+                       mono_runtime_cleanup_handlers ();
+               }
+#endif
+
                // Should not be removed intended for external use
                // Safe to be called using reflection
                // Format is undefined only for use as a string for reporting
                [MethodImplAttribute (MethodImplOptions.InternalCall)]
-#if MOBILE
+#if MOBILE || XAMMAC_4_5
                public
 #else
                internal
index 78cd58f81a89c863c60a9a9e4088d312b35c0828..40707aa77901e4ef83744e4a1f0a980daf7ee26f 100644 (file)
@@ -345,15 +345,13 @@ namespace System
 
                unsafe String ReplaceInternal (char oldChar, char newChar)
                {
-#if !BOOTSTRAP_BASIC                   
                        if (this.m_stringLength == 0 || oldChar == newChar)
                                return this;
-#endif
+
                        int start_pos = IndexOfUnchecked (oldChar, 0, this.m_stringLength);
-#if !BOOTSTRAP_BASIC
                        if (start_pos == -1)
                                return this;
-#endif
+
                        if (start_pos < 4)
                                start_pos = 0;
 
@@ -391,11 +389,8 @@ namespace System
                                throw new ArgumentException ("oldValue is the empty string.");
 
                        if (this.Length == 0)
-#if BOOTSTRAP_BASIC
-                               throw new NotImplementedException ("BOOTSTRAP_BASIC");
-#else
                                return this;
-#endif
+
                        if (newValue == null)
                                newValue = Empty;
 
@@ -405,11 +400,7 @@ namespace System
                private unsafe String ReplaceUnchecked (String oldValue, String newValue)
                {
                        if (oldValue.m_stringLength > m_stringLength)
-#if BOOTSTRAP_BASIC
-                               throw new NotImplementedException ("BOOTSTRAP_BASIC");
-#else
                                return this;
-#endif
 
                        if (oldValue.m_stringLength == 1 && newValue.m_stringLength == 1) {
                                return Replace (oldValue[0], newValue[0]);
@@ -434,11 +425,8 @@ namespace System
                                        i = found + oldValue.m_stringLength;
                                }
                                if (count == 0)
-#if BOOTSTRAP_BASIC
-                               throw new NotImplementedException ("BOOTSTRAP_BASIC");
-#else
-                               return this;
-#endif
+                                       return this;
+
                                int nlen = 0;
                                checked {
                                        try {
@@ -488,11 +476,8 @@ namespace System
                        if (totalWidth < 0)
                                throw new ArgumentOutOfRangeException ("totalWidth", "Non-negative number required");
                        if (totalWidth <= m_stringLength)
-#if BOOTSTRAP_BASIC
-                               throw new NotImplementedException ("BOOTSTRAP_BASIC");
-#else                  
                                return this;
-#endif
+
                        string result = FastAllocateString (totalWidth);
 
                        fixed (char *dest = result, src = &m_firstChar) {
@@ -518,11 +503,7 @@ namespace System
 
                internal bool StartsWithOrdinalUnchecked (String value)
                {
-#if BOOTSTRAP_BASIC
-                       throw new NotImplementedException ("BOOTSTRAP_BASIC");
-#else
                        return m_stringLength >= value.m_stringLength && CompareOrdinalUnchecked (this, 0, value.m_stringLength, value, 0, value.m_stringLength) == 0;
-#endif
                }
 
                internal unsafe bool IsAscii ()
index 370beffb237d13dfced0cf1337e278e0f83fee6c..a77d734c36617eaf2c41cc9d6b87cfe5f286118b 100644 (file)
@@ -102,6 +102,12 @@ namespace System
                        return UnderlyingSystemType;
                }
 
+               // Called from the runtime to return the corresponding finished Type object
+               internal virtual Type RuntimeResolve ()
+               {
+                       throw new NotImplementedException ();
+               }
+
                internal virtual bool IsUserType {
                        get {
                                return true;
diff --git a/mcs/class/corlib/ReferenceSources/TypeBuilderInstantiation.cs b/mcs/class/corlib/ReferenceSources/TypeBuilderInstantiation.cs
deleted file mode 100644 (file)
index 9e82664..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-namespace System.Reflection.Emit
-{
-       abstract class TypeBuilderInstantiation : TypeInfo
-       {
-               internal static Type MakeGenericType (Type type, Type[] typeArguments)
-               {
-#if FULL_AOT_RUNTIME
-                       throw new NotSupportedException ("User types are not supported under full aot");
-#else
-                       return new MonoGenericClass (type, typeArguments);
-#endif
-               }
-       }
-}
\ No newline at end of file
index 8397f4c2d2f4db3bcd383e583bf265b06d486137..bb1b719404a992efd5277abda3f6909cdecc3ede 100644 (file)
@@ -151,6 +151,7 @@ namespace System.Diagnostics.Tracing
                {
                }
 
+               [CLSCompliant (false)]
                public void Write<T> (string eventName, ref EventSourceOptions options, ref T data)
                {
                }
diff --git a/mcs/class/corlib/System.Diagnostics.Tracing/EventSourceException.cs b/mcs/class/corlib/System.Diagnostics.Tracing/EventSourceException.cs
deleted file mode 100644 (file)
index 3602e29..0000000
+++ /dev/null
@@ -1,50 +0,0 @@
-//
-// EventSourceException.cs
-//
-// Authors:
-//     Alexander Köplinger <alexander.koeplinger@xamarin.com>
-//
-// Copyright (C) 2016 Xamarin Inc (http://www.xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace System.Diagnostics.Tracing
-{
-       public class EventSourceException : Exception
-       {
-               [MonoTODO]
-               public EventSourceException ()
-               {
-               }
-
-               [MonoTODO]
-               public EventSourceException (string message)
-               {
-               }
-
-               [MonoTODO]
-               public EventSourceException (string message, Exception innerException)
-               {
-               }
-       }
-}
index e6741d4d3caf2c0cf6467e382e9821c4281646eb..63c0c015978b1c58d7cc38e2ad58f74ab5318958 100644 (file)
@@ -180,7 +180,6 @@ namespace System.Globalization
                        get { return territory; }
                }
 
-#if !MOBILE
                // FIXME: It is implemented, but would be hell slow.
                [ComVisible (false)]
                public CultureTypes CultureTypes {
@@ -266,7 +265,6 @@ namespace System.Globalization
                                }
                        }
                }
-#endif
 
                public virtual int LCID {
                        get {
index de55602cdbe4437a6def908340a01e5156e25b94..d3eebc441064065b3045fd0dfc83525f28864ae3 100644 (file)
@@ -38,10 +38,7 @@ using System.Diagnostics;
 using System.Security;
 using System.Text;
 using System.Runtime.InteropServices;
-
-#if !MOBILE
 using System.Security.AccessControl;
-#endif
 
 namespace System.IO
 {
@@ -147,7 +144,6 @@ namespace System.IO
                                FileShare.None, bufferSize, options);
                }
 
-#if !MOBILE
                [MonoLimitation ("FileOptions and FileSecurity are ignored")]
                public static FileStream Create (string path, int bufferSize,
                                                 FileOptions options,
@@ -156,7 +152,6 @@ namespace System.IO
                        return new FileStream (path, FileMode.Create, FileAccess.ReadWrite,
                                FileShare.None, bufferSize, options);
                }
-#endif
 
                public static StreamWriter CreateText (string path)
                {
@@ -201,7 +196,6 @@ namespace System.IO
                        return MonoIO.ExistsFile (path, out error);
                }
 
-#if !MOBILE
                public static FileSecurity GetAccessControl (string path)
                {
                        // AccessControlSections.Audit requires special permissions.
@@ -215,7 +209,6 @@ namespace System.IO
                {
                        return new FileSecurity (path, includeSections);
                }
-#endif
 
                public static FileAttributes GetAttributes (string path)
                {
@@ -434,7 +427,6 @@ namespace System.IO
                        }
                }
 
-#if !MOBILE
                public static void SetAccessControl (string path,
                                                     FileSecurity fileSecurity)
                {
@@ -443,7 +435,6 @@ namespace System.IO
 
                        fileSecurity.PersistModifications (path);
                }
-#endif
 
                public static void SetAttributes (string path,
                                                  FileAttributes fileAttributes)
index b2a15cd2b600fce61cdf1282ee7ce76695851966..db13468d36fcfaa9a4f0d82164ae8a33ccfeb2cf 100644 (file)
@@ -37,17 +37,11 @@ using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
 using System.Runtime.Remoting.Messaging;
 using System.Security;
+using System.Security.AccessControl;
 using System.Security.Permissions;
 using System.Threading;
-using Microsoft.Win32.SafeHandles;
-
-#if MOBILE
-using System.IO.IsolatedStorage;
-#else
-using System.Security.AccessControl;
-#endif
-
 using System.Threading.Tasks;
+using Microsoft.Win32.SafeHandles;
 
 namespace System.IO
 {
@@ -129,7 +123,6 @@ namespace System.IO
                        Init (handle, access, false, bufferSize, isAsync, false);
                }
 
-#if !MOBILE
                [MonoLimitation ("This ignores the rights parameter")]
                public FileStream (string path, FileMode mode,
                                   FileSystemRights rights, FileShare share,
@@ -146,7 +139,6 @@ namespace System.IO
                        : this (path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), share, bufferSize, false, options)
                {
                }
-#endif
 
                internal FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, string msgPath, bool bFromProxy, bool useLongPath = false, bool checkHost = false)
                        : this (path, mode, access, share, bufferSize, false, options)
@@ -942,7 +934,6 @@ namespace System.IO
                                throw exc;
                }
 
-#if !MOBILE
                public FileSecurity GetAccessControl ()
                {
                        if (safeHandle.IsClosed)
@@ -964,7 +955,6 @@ namespace System.IO
                                
                        fileSecurity.PersistModifications (SafeFileHandle);
                }
-#endif
 
                public override Task FlushAsync (CancellationToken cancellationToken)
                {
index 9c257cb9a80542fc882eb52ddfd9c05c58c0b2ee..ed524bb7c1878e5d63985411be8a9bf3a9dfbe9b 100644 (file)
@@ -1046,7 +1046,7 @@ namespace System.Reflection.Emit
                /*Warning, @typeArguments must be a mscorlib internal array. So make a copy before passing it in*/
                internal Type MakeGenericType (Type gtd, Type[] typeArguments)
                {
-                       return new MonoGenericClass (gtd, typeArguments);
+                       return new TypeBuilderInstantiation (gtd, typeArguments);
                }
 
                void _AssemblyBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
index 793e36fd2a01cc033d059b58e1d6d939c34cba2a..55a392d38442814419e937fdb4088f2f3bd8b526 100644 (file)
@@ -145,7 +145,11 @@ namespace System.Reflection.Emit {
                internal override Type GetParameterType (int pos) {
                        return parameters [pos];
                }
-               
+
+               internal MethodBase RuntimeResolve () {
+                       return type.RuntimeResolve ().GetConstructor (this);
+               }
+
                public override Object Invoke (Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
                {
                        throw not_supported ();
@@ -372,6 +376,11 @@ namespace System.Reflection.Emit {
                                        TypeBuilder.ResolveUserTypes (types);
                        }
                }
+
+               internal void FixupTokens (Dictionary<int, int> token_map, Dictionary<int, MemberInfo> member_map) {
+                       if (ilgen != null)
+                               ilgen.FixupTokens (token_map, member_map);
+               }
                
                internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
                {
index 149e5dbd6633d1a5d6940d761cfcc18be4a8e37f..643e7272a3a9be6666a2dd3366095b1dd968c8d5 100644 (file)
@@ -42,11 +42,11 @@ namespace System.Reflection.Emit
        internal class ConstructorOnTypeBuilderInst : ConstructorInfo
        {
                #region Keep in sync with object-internals.h
-               MonoGenericClass instantiation;
-               ConstructorInfo cb;
+               internal TypeBuilderInstantiation instantiation;
+               internal ConstructorInfo cb;
                #endregion
 
-               public ConstructorOnTypeBuilderInst (MonoGenericClass instantiation, ConstructorInfo cb)
+               public ConstructorOnTypeBuilderInst (TypeBuilderInstantiation instantiation, ConstructorInfo cb)
                {
                        this.instantiation = instantiation;
                        this.cb = cb;
@@ -134,6 +134,25 @@ namespace System.Reflection.Emit
                        return res;
                }
 
+               internal override Type[] GetParameterTypes () {
+                       if (cb is ConstructorBuilder) {
+                               return (cb as ConstructorBuilder).parameters;
+                       } else {
+                               ParameterInfo[] parms = cb.GetParameters ();
+                               var res = new Type [parms.Length];
+                               for (int i = 0; i < parms.Length; i++) {
+                                       res [i] = parms [i].ParameterType;
+                               }
+                               return res;
+                       }
+               }
+
+               // Called from the runtime to return the corresponding finished ConstructorInfo object
+               internal ConstructorInfo RuntimeResolve () {
+                       var type = instantiation.InternalResolve ();
+                       return type.GetConstructor (cb);
+               }
+
                public override int MetadataToken {
                        get {
                                return base.MetadataToken;
index b7ce6e0410a767355c9db8fcf9c9f0387ffd5f50..0e426991c6ec3392ece4fe91fb7342a7baa5fa61 100644 (file)
@@ -45,9 +45,6 @@ namespace System.Reflection.Emit
        {
                internal Type m_baseType;
 
-               [MethodImplAttribute(MethodImplOptions.InternalCall)]
-               static extern void create_unmanaged_type (Type type);
-
                internal SymbolType (Type elementType)
                {
                        this.m_baseType = elementType;
@@ -121,7 +118,6 @@ namespace System.Reflection.Emit
        
                public override Type UnderlyingSystemType {
                        get {
-                               create_unmanaged_type (this);
                                return this;
                        }
                }
@@ -131,6 +127,11 @@ namespace System.Reflection.Emit
                                return m_baseType.IsUserType;
                        }
                }
+
+               // Called from the runtime to return the corresponding finished Type object
+               internal override Type RuntimeResolve () {
+                       return InternalResolve ();
+               }
        }
 
        [StructLayout (LayoutKind.Sequential)]
@@ -150,9 +151,17 @@ namespace System.Reflection.Emit
 
                internal override Type InternalResolve ()
                {
-                       Type et = m_baseType.InternalResolve (); 
+                       Type et = m_baseType.InternalResolve ();
+                       if (rank == 0)
+                               return et.MakeArrayType ();
+                       return et.MakeArrayType (rank);
+               }
+
+               internal override Type RuntimeResolve ()
+               {
+                       Type et = m_baseType.RuntimeResolve ();
                        if (rank == 0)
-                               return et.MakeArrayType ();                     
+                               return et.MakeArrayType ();
                        return et.MakeArrayType (rank);
                }
 
index 2e4367ab96573525b9f8da270f134b7d83b8d06a..f54340ebf04df4013daf953c1ee1e3f5e31bc4ec 100644 (file)
@@ -42,17 +42,17 @@ namespace System.Reflection.Emit
        [StructLayout (LayoutKind.Sequential)]
        internal class EventOnTypeBuilderInst : EventInfo
        {
-               MonoGenericClass instantiation;
+               TypeBuilderInstantiation instantiation;
                EventBuilder event_builder;
                EventInfo event_info;
 
-               internal EventOnTypeBuilderInst (MonoGenericClass instantiation, EventBuilder evt)
+               internal EventOnTypeBuilderInst (TypeBuilderInstantiation instantiation, EventBuilder evt)
                {
                        this.instantiation = instantiation;
                        this.event_builder = evt;
                }
 
-               internal EventOnTypeBuilderInst (MonoGenericClass instantiation, EventInfo evt)
+               internal EventOnTypeBuilderInst (TypeBuilderInstantiation instantiation, EventInfo evt)
                {
                        this.instantiation = instantiation;
                        this.event_info = evt;
index f2fff7d7aa1ef9964d99e128965960aa869e2284..f8522ebe862a6dee35fac7668cf2d959260eb50d 100644 (file)
@@ -228,6 +228,10 @@ namespace System.Reflection.Emit {
                                marshal_info.marshaltyperef = TypeBuilder.ResolveUserType (marshal_info.marshaltyperef);
                }
 
+               internal FieldInfo RuntimeResolve () {
+                       return typeb.CreateType ().GetField (this);
+               }
+
                public override Module Module {
                        get {
                                return base.Module;
index ca3d43d85f94e49655d5a260e903cf04fd51b103..9de89b1e2b85d311ea49b1256755585b5f4f9895 100644 (file)
@@ -42,11 +42,11 @@ namespace System.Reflection.Emit
        internal class FieldOnTypeBuilderInst : FieldInfo
        {
                #region Keep in sync with object-internals.h
-               internal MonoGenericClass instantiation;
+               internal TypeBuilderInstantiation instantiation;
                internal FieldInfo fb;
                #endregion
 
-               public FieldOnTypeBuilderInst (MonoGenericClass instantiation, FieldInfo fb) {
+               public FieldOnTypeBuilderInst (TypeBuilderInstantiation instantiation, FieldInfo fb) {
                        this.instantiation = instantiation;
                        this.fb = fb;
                }
@@ -127,6 +127,12 @@ namespace System.Reflection.Emit
                public override void SetValue (object obj, object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) {
                        throw new NotSupportedException ();
                }
+
+               // Called from the runtime to return the corresponding finished FieldInfo object
+               internal FieldInfo RuntimeResolve () {
+                       var type = instantiation.RuntimeResolve ();
+                       return type.GetField (fb);
+               }
        }
 }
 #endif
index 037d36fdc3ee1fb6c06641a3a8a8ae38a895132d..30b6aac80e572f9402afd9b4403a9cf03e23c95b 100644 (file)
@@ -82,17 +82,21 @@ namespace System.Reflection.Emit
                        this.mbuilder = mbuilder;
                        this.name = name;
                        this.index = index;
-
-                       initialize ();
                }
 
                internal override Type InternalResolve ()
                {
-                       return tbuilder.InternalResolve ().GetGenericArguments () [index]; 
+                       if (mbuilder != null)
+                               return MethodBase.GetMethodFromHandle (mbuilder.MethodHandleInternal).GetGenericArguments () [index];
+                       return tbuilder.InternalResolve ().GetGenericArguments () [index];
                }
 
-               [MethodImplAttribute(MethodImplOptions.InternalCall)]
-               private extern void initialize ();
+               internal override Type RuntimeResolve ()
+               {
+                       if (mbuilder != null)
+                               return MethodBase.GetMethodFromHandle (mbuilder.MethodHandleInternal, mbuilder.TypeBuilder.RuntimeResolve ().TypeHandle).GetGenericArguments () [index];
+                       return tbuilder.RuntimeResolve ().GetGenericArguments () [index];
+               }
 
                [ComVisible (true)]
                public override bool IsSubclassOf (Type c)
index ac4fda04472f0572052c8433509685a8e063af93..bf879e8e942f79961b352b37de60b39592e47a5f 100644 (file)
@@ -521,7 +521,7 @@ namespace System.Reflection.Emit {
                        int token = token_gen.GetToken (con, true);
                        make_room (6);
                        ll_emit (opcode);
-                       if (con.DeclaringType.Module == module)
+                       if (con.DeclaringType.Module == module || (con is ConstructorOnTypeBuilderInst) || (con is ConstructorBuilder))
                                add_token_fixup (con);
                        emit_int (token);
                        
@@ -554,7 +554,7 @@ namespace System.Reflection.Emit {
                        int token = token_gen.GetToken (field, true);
                        make_room (6);
                        ll_emit (opcode);
-                       if (field.DeclaringType.Module == module)
+                       if (field.DeclaringType.Module == module || (field is FieldOnTypeBuilderInst) || (field is FieldBuilder))
                                add_token_fixup (field);
                        emit_int (token);
                }
@@ -737,7 +737,7 @@ namespace System.Reflection.Emit {
                        Type declaringType = meth.DeclaringType;
                        // Might be a DynamicMethod with no declaring type
                        if (declaringType != null) {
-                               if (declaringType.Module == module)
+                               if (declaringType.Module == module || meth is MethodOnTypeBuilderInst || meth is MethodBuilder)
                                        add_token_fixup (meth);
                        }
                        emit_int (token);
@@ -755,7 +755,7 @@ namespace System.Reflection.Emit {
                        // Might be a DynamicMethod with no declaring type
                        Type declaringType = method.DeclaringType;
                        if (declaringType != null) {
-                               if (declaringType.Module == module)
+                               if (declaringType.Module == module || method is MethodBuilder)
                                        add_token_fixup (method);
                        }
                        emit_int (token);
@@ -813,7 +813,10 @@ namespace System.Reflection.Emit {
 
                        make_room (6);
                        ll_emit (opcode);
-                       emit_int (token_gen.GetToken (cls, opcode != OpCodes.Ldtoken));
+                       int token = token_gen.GetToken (cls, opcode != OpCodes.Ldtoken);
+                       if (cls is TypeBuilderInstantiation || cls is SymbolType || cls is TypeBuilder || cls is GenericTypeParameterBuilder)
+                               add_token_fixup (cls);
+                       emit_int (token);
                }
 
                [MonoLimitation ("vararg methods are not supported")]
@@ -1007,6 +1010,21 @@ namespace System.Reflection.Emit {
                        }
                }
 
+               internal void FixupTokens (Dictionary<int, int> token_map, Dictionary<int, MemberInfo> member_map) {
+                       for (int i = 0; i < num_token_fixups; ++i) {
+                               int pos = token_fixups [i].code_pos;
+                               int old_token = code [pos] | (code [pos + 1] << 8) | (code [pos + 2] << 16) | (code [pos + 3] << 24);
+                               int new_token;
+                               if (token_map.TryGetValue (old_token, out new_token)) {
+                                       token_fixups [i].member = member_map [old_token];
+                                       int old_cl = code_len;
+                                       code_len = pos;
+                                       emit_int (new_token);
+                                       code_len = old_cl;
+                               }
+                       }
+               }
+
                // Used by MethodBuilder.SetMethodBody
                internal void SetExceptionHandlers (ILExceptionInfo[] exHandlers) {
                        this.ex_handlers = exHandlers;
index 5545adca27657930a58d9aed580ece83fe515ea8..8748f20aba2b1e998f751affb651e45a133172e3 100644 (file)
@@ -138,6 +138,12 @@ namespace System.Reflection.Emit
                        }
                }
 
+               internal RuntimeMethodHandle MethodHandleInternal {
+                       get {
+                               return mhandle;
+                       }
+               }
+
                public override Type ReturnType {
                        get { return rtype; }
                }
@@ -248,6 +254,10 @@ namespace System.Reflection.Emit
                        return parameters [pos];
                }
 
+               internal MethodBase RuntimeResolve () {
+                       return type.RuntimeResolve ().GetMethod (this);
+               }
+
                public Module GetModule ()
                {
                        return type.Module;
@@ -380,6 +390,11 @@ namespace System.Reflection.Emit
                        }
                }
 
+               internal void FixupTokens (Dictionary<int, int> token_map, Dictionary<int, MemberInfo> member_map) {
+                       if (ilgen != null)
+                               ilgen.FixupTokens (token_map, member_map);
+               }
+
                internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
                {
                        if (ilgen != null && ilgen.HasDebugInfo) {
index 9bc0b8a5994500a625b81919aa59c85cb18192a9..22c89ea9d0bf26717a90afce4b335e13fa97da78 100644 (file)
@@ -50,7 +50,7 @@ namespace System.Reflection.Emit
                #endregion
                MethodInfo generic_method_definition;
 
-               public MethodOnTypeBuilderInst (MonoGenericClass instantiation, MethodInfo base_method)
+               public MethodOnTypeBuilderInst (TypeBuilderInstantiation instantiation, MethodInfo base_method)
                {
                        this.instantiation = instantiation;
                        this.base_method = base_method;
@@ -100,6 +100,19 @@ namespace System.Reflection.Emit
                        return instantiation.GetGenericArguments ();
                }
 
+               // Called from the runtime to return the corresponding finished MethodInfo object
+               internal MethodInfo RuntimeResolve () {
+                       var type = instantiation.InternalResolve ();
+                       var m = type.GetMethod (base_method);
+                       if (method_arguments != null) {
+                               var args = new Type [method_arguments.Length];
+                               for (int i = 0; i < method_arguments.Length; ++i)
+                                       args [i] = method_arguments [i].InternalResolve ();
+                               m = m.MakeGenericMethod (args);
+                       }
+                       return m;
+               }
+
                //
                // MemberInfo members
                //
index d6c39114f16ef3da670dd957008a1c592b08af79..b055797bd86763c3e82bc201c6c4d380e9884875 100644 (file)
@@ -348,9 +348,6 @@ namespace System.Reflection.Emit {
                        return null;
                }
 
-               [MethodImplAttribute(MethodImplOptions.InternalCall)]
-               private static extern Type create_modified_type (TypeBuilder tb, string modifiers);
-
                private TypeBuilder GetMaybeNested (TypeBuilder t, IEnumerable<TypeName> nested) {
                        TypeBuilder result = t;
 
@@ -392,8 +389,27 @@ namespace System.Reflection.Emit {
                        if ((result == null) && throwOnError)
                                throw new TypeLoadException (className);
                        if (result != null && (ts.HasModifiers || ts.IsByRef)) {
-                               string modifiers = ts.ModifierString ();
-                               Type mt = create_modified_type (result, modifiers);
+                               Type mt = result;
+                               if (result is TypeBuilder) {
+                                       var tb = result as TypeBuilder;
+                                       if (tb.is_created)
+                                               mt = tb.CreateType ();
+                               }
+                               foreach (var mod in ts.Modifiers) {
+                                       if (mod is PointerSpec)
+                                               mt = mt.MakePointerType ();
+                                       else if (mod is ArraySpec) {
+                                               var spec = mod as ArraySpec;
+                                               if (spec.IsBound)
+                                                       return null;
+                                               if (spec.Rank == 1)
+                                                       mt = mt.MakeArrayType ();
+                                               else
+                                                       mt = mt.MakeArrayType (spec.Rank);
+                                       }
+                               }
+                               if (ts.IsByRef)
+                                       mt = mt.MakeByRefType ();
                                result = mt as TypeBuilder;
                                if (result == null)
                                        return mt;
@@ -665,15 +681,90 @@ namespace System.Reflection.Emit {
                        return result;
                }
 
+               static int typeref_tokengen =  0x01ffffff;
+               static int typedef_tokengen =  0x02ffffff;
+               static int typespec_tokengen =  0x1bffffff;
+               static int memberref_tokengen =  0x0affffff;
+               static int methoddef_tokengen =  0x06ffffff;
+               Dictionary<MemberInfo, int> inst_tokens = new Dictionary<MemberInfo, int> ();
+               Dictionary<MemberInfo, int> inst_tokens_open = new Dictionary<MemberInfo, int> ();
+
+               //
+               // Assign a pseudo token to the various TypeBuilderInst objects, so the runtime
+               // doesn't have to deal with them.
+               // For Save assemblies, the tokens will be fixed up later during Save ().
+               // For Run assemblies, the tokens will not be fixed up, so the runtime will
+               // still encounter these objects, it will resolve them by calling their
+               // RuntimeResolve () methods.
+               //
+               int GetPseudoToken (MemberInfo member, bool create_open_instance) {
+                       int token;
+
+                       if (create_open_instance) {
+                               if (inst_tokens_open.TryGetValue (member, out token))
+                                       return token;
+                       } else {
+                               if (inst_tokens.TryGetValue (member, out token))
+                                       return token;
+                       }
+                       // Count backwards to avoid collisions with the tokens
+                       // allocated by the runtime
+                       if (member is TypeBuilderInstantiation || member is SymbolType)
+                               token = typespec_tokengen --;
+                       else if (member is FieldOnTypeBuilderInst)
+                               token = memberref_tokengen --;
+                       else if (member is ConstructorOnTypeBuilderInst)
+                               token = memberref_tokengen --;
+                       else if (member is MethodOnTypeBuilderInst)
+                               token = memberref_tokengen --;
+                       else if (member is FieldBuilder)
+                               token = memberref_tokengen --;
+                       else if (member is TypeBuilder) {
+                               if (create_open_instance && (member as TypeBuilder).ContainsGenericParameters)
+                                       token = typespec_tokengen --;
+                               else if (member.Module == this)
+                                       token = typedef_tokengen --;
+                               else
+                                       token = typeref_tokengen --;
+                       } else if (member is ConstructorBuilder) {
+                               if (member.Module == this && !(member as ConstructorBuilder).TypeBuilder.ContainsGenericParameters)
+                                       token = methoddef_tokengen --;
+                               else
+                                       token = memberref_tokengen --;
+                       } else if (member is MethodBuilder) {
+                               var mb = member as MethodBuilder;
+                               if (member.Module == this && !mb.TypeBuilder.ContainsGenericParameters && !mb.IsGenericMethodDefinition)
+                                       token = methoddef_tokengen --;
+                               else
+                                       token = memberref_tokengen --;
+                       } else if (member is GenericTypeParameterBuilder) {
+                               token = typespec_tokengen --;
+                       } else
+                               throw new NotImplementedException ();
+                       if (create_open_instance)
+                               inst_tokens_open [member] = token;
+                       else
+                               inst_tokens [member] = token;
+                       RegisterToken (member, token);
+                       return token;
+               }
+
                internal int GetToken (MemberInfo member) {
+                       if (member is ConstructorBuilder || member is MethodBuilder)
+                               return GetPseudoToken (member, false);
                        return getToken (this, member, true);
                }
 
                internal int GetToken (MemberInfo member, bool create_open_instance) {
+                       if (member is TypeBuilderInstantiation || member is FieldOnTypeBuilderInst || member is ConstructorOnTypeBuilderInst || member is MethodOnTypeBuilderInst || member is SymbolType || member is FieldBuilder || member is TypeBuilder || member is ConstructorBuilder || member is MethodBuilder || member is GenericTypeParameterBuilder)
+                               return GetPseudoToken (member, create_open_instance);
                        return getToken (this, member, create_open_instance);
                }
 
                internal int GetToken (MethodBase method, IEnumerable<Type> opt_param_types) {
+                       if (method is ConstructorBuilder || method is MethodBuilder)
+                               return GetPseudoToken (method, false);
+
                        if (opt_param_types == null)
                                return getToken (this, method, true);
 
@@ -682,6 +773,8 @@ namespace System.Reflection.Emit {
                }
                
                internal int GetToken (MethodBase method, Type[] opt_param_types) {
+                       if (method is ConstructorBuilder || method is MethodBuilder)
+                               return GetPseudoToken (method, false);
                        return getMethodToken (this, method, opt_param_types);
                }
 
@@ -708,12 +801,88 @@ namespace System.Reflection.Emit {
                        return token_gen;
                }
 
+               // Called from the runtime to return the corresponding finished reflection object
+               internal static object RuntimeResolve (object obj) {
+                       if (obj is MethodBuilder)
+                               return (obj as MethodBuilder).RuntimeResolve ();
+                       if (obj is ConstructorBuilder)
+                               return (obj as ConstructorBuilder).RuntimeResolve ();
+                       if (obj is FieldBuilder)
+                               return (obj as FieldBuilder).RuntimeResolve ();
+                       if (obj is GenericTypeParameterBuilder)
+                               return (obj as GenericTypeParameterBuilder).RuntimeResolve ();
+                       if (obj is FieldOnTypeBuilderInst)
+                               return (obj as FieldOnTypeBuilderInst).RuntimeResolve ();
+                       if (obj is MethodOnTypeBuilderInst)
+                               return (obj as MethodOnTypeBuilderInst).RuntimeResolve ();
+                       if (obj is ConstructorOnTypeBuilderInst)
+                               return (obj as ConstructorOnTypeBuilderInst).RuntimeResolve ();
+                       if (obj is Type)
+                               return (obj as Type).RuntimeResolve ();
+                       throw new NotImplementedException (obj.GetType ().FullName);
+               }
+
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
                private static extern void build_metadata (ModuleBuilder mb);
 
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
                private extern void WriteToFile (IntPtr handle);
 
+               void FixupTokens (Dictionary<int, int> token_map, Dictionary<int, MemberInfo> member_map, Dictionary<MemberInfo, int> inst_tokens,
+                                                 bool open) {
+                       foreach (var v in inst_tokens) {
+                               var member = v.Key;
+                               var old_token = v.Value;
+                               MemberInfo finished = null;
+
+                               // Construct the concrete reflection object corresponding to the
+                               // TypeBuilderInst object, and request a token for it instead.
+                               if (member is TypeBuilderInstantiation || member is SymbolType) {
+                                       finished = (member as Type).RuntimeResolve ();
+                               } else if (member is FieldOnTypeBuilderInst) {
+                                       finished = (member as FieldOnTypeBuilderInst).RuntimeResolve ();
+                               } else if (member is ConstructorOnTypeBuilderInst) {
+                                       finished = (member as ConstructorOnTypeBuilderInst).RuntimeResolve ();
+                               } else if (member is MethodOnTypeBuilderInst) {
+                                       finished = (member as MethodOnTypeBuilderInst).RuntimeResolve ();
+                               } else if (member is FieldBuilder) {
+                                       finished = (member as FieldBuilder).RuntimeResolve ();
+                               } else if (member is TypeBuilder) {
+                                       finished = (member as TypeBuilder).RuntimeResolve ();
+                               } else if (member is ConstructorBuilder) {
+                                       finished = (member as ConstructorBuilder).RuntimeResolve ();
+                               } else if (member is MethodBuilder) {
+                                       finished = (member as MethodBuilder).RuntimeResolve ();
+                               } else if (member is GenericTypeParameterBuilder) {
+                                       finished = (member as GenericTypeParameterBuilder).RuntimeResolve ();
+                               } else {
+                                       throw new NotImplementedException ();
+                               }
+
+                               int new_token = GetToken (finished, open);
+                               token_map [old_token] = new_token;
+                               member_map [old_token] = finished;
+                               // Replace the token mapping in the runtime so it points to the new object
+                               RegisterToken (finished, old_token);
+                       }
+               }
+
+               //
+               // Fixup the pseudo tokens assigned to the various SRE objects
+               //
+               void FixupTokens () {
+                       var token_map = new Dictionary<int, int> ();
+                       var member_map = new Dictionary<int, MemberInfo> ();
+                       FixupTokens (token_map, member_map, inst_tokens, false);
+                       FixupTokens (token_map, member_map, inst_tokens_open, true);
+
+                       // Replace the tokens in the IL stream
+                       if (types != null) {
+                               for (int i = 0; i < num_types; ++i)
+                                       types [i].FixupTokens (token_map, member_map);
+                       }
+               }
+
                internal void Save ()
                {
                        if (transient && !is_main)
@@ -725,6 +894,8 @@ namespace System.Reflection.Emit {
                                                throw new NotSupportedException ("Type '" + types [i].FullName + "' was not completed.");
                        }
 
+                       FixupTokens ();
+
                        if ((global_type != null) && (global_type_created == null))
                                global_type_created = global_type.CreateType ();
 
index 1035f494c86223a3bcc547243d9ea635be84dd9c..8b21446c4ef5416f3bd1421a6e59160c001a4cea 100644 (file)
@@ -41,10 +41,10 @@ namespace System.Reflection.Emit
        [StructLayout (LayoutKind.Sequential)]
        internal class PropertyOnTypeBuilderInst : PropertyInfo
        {
-               MonoGenericClass instantiation;
+               TypeBuilderInstantiation instantiation;
                PropertyInfo prop;
 
-               internal PropertyOnTypeBuilderInst (MonoGenericClass instantiation, PropertyInfo prop)
+               internal PropertyOnTypeBuilderInst (TypeBuilderInstantiation instantiation, PropertyInfo prop)
                {
                        this.instantiation = instantiation;
                        this.prop = prop;
index 3972192308d8082a7c6be66c929a8989b4a85dce..30ae09cdf16be9181dcdc2efc3335c966cb0739d 100644 (file)
@@ -40,6 +40,7 @@ using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
 using System.Globalization;
 using System.Collections;
+using System.Collections.Generic;
 using System.Security;
 using System.Security.Permissions;
 using System.Diagnostics.SymbolStore;
@@ -91,15 +92,6 @@ namespace System.Reflection.Emit
                {
                        return attrs;
                }
-               
-               [MethodImplAttribute(MethodImplOptions.InternalCall)]
-               private extern void setup_internal_class ();
-               
-               [MethodImplAttribute(MethodImplOptions.InternalCall)]
-               private extern void create_generic_class ();
-
-               [MethodImplAttribute(MethodImplOptions.InternalCall)]
-               private extern EventInfo get_event_info (EventBuilder eb);
 
                internal TypeBuilder (ModuleBuilder mb, TypeAttributes attr, int table_idx)
                {
@@ -111,7 +103,6 @@ namespace System.Reflection.Emit
                        this.nspace = String.Empty;
                        this.fullname = TypeIdentifiers.WithoutEscape(this.tname);
                        pmodule = mb;
-                       setup_internal_class ();
                }
 
                internal TypeBuilder (ModuleBuilder mb, string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packing_size, int type_size, Type nesting_type)
@@ -147,7 +138,6 @@ namespace System.Reflection.Emit
 
                        // skip .<Module> ?
                        table_idx = mb.get_next_table_index (this, 0x02, true);
-                       setup_internal_class ();
                        fullname = GetFullName ();
                }
 
@@ -764,8 +754,6 @@ namespace System.Reflection.Emit
                                SetParent (pmodule.assemblyb.corlib_object_type);
                        }
 
-                       create_generic_class ();
-
                        // Fire TypeResolve events for fields whose type is an unfinished
                        // value type.
                        if (fields != null) {
@@ -873,6 +861,21 @@ namespace System.Reflection.Emit
                        }
                }
 
+               internal void FixupTokens (Dictionary<int, int> token_map, Dictionary<int, MemberInfo> member_map) {
+                       if (methods != null) {
+                               for (int i = 0; i < num_methods; ++i)
+                                       methods[i].FixupTokens (token_map, member_map);
+                       }
+                       if (ctors != null) {
+                               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)
                {
                        symbolWriter.OpenNamespace (this.Namespace);
@@ -968,53 +971,6 @@ namespace System.Reflection.Emit
                        throw new NotSupportedException ();
                }
 
-               // This is only used from MonoGenericInst.initialize().
-               internal EventInfo[] GetEvents_internal (BindingFlags bindingAttr)
-               {
-                       if (events == null)
-                               return new EventInfo [0];
-                       ArrayList l = new ArrayList ();
-                       bool match;
-                       MethodAttributes mattrs;
-                       MethodInfo accessor;
-
-                       foreach (EventBuilder eb in events) {
-                               if (eb == null)
-                                       continue;
-                               EventInfo c = get_event_info (eb);
-                               match = false;
-                               accessor = c.GetAddMethod (true);
-                               if (accessor == null)
-                                       accessor = c.GetRemoveMethod (true);
-                               if (accessor == null)
-                                       continue;
-                               mattrs = accessor.Attributes;
-                               if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
-                                       if ((bindingAttr & BindingFlags.Public) != 0)
-                                               match = true;
-                               } else {
-                                       if ((bindingAttr & BindingFlags.NonPublic) != 0)
-                                               match = true;
-                               }
-                               if (!match)
-                                       continue;
-                               match = false;
-                               if ((mattrs & MethodAttributes.Static) != 0) {
-                                       if ((bindingAttr & BindingFlags.Static) != 0)
-                                               match = true;
-                               } else {
-                                       if ((bindingAttr & BindingFlags.Instance) != 0)
-                                               match = true;
-                               }
-                               if (!match)
-                                       continue;
-                               l.Add (c);
-                       }
-                       EventInfo[] result = new EventInfo [l.Count];
-                       l.CopyTo (result);
-                       return result;
-               }
-
                public override FieldInfo GetField (string name, BindingFlags bindingAttr)
                {
                        if (created != null)
@@ -1642,9 +1598,6 @@ namespace System.Reflection.Emit
                                this.parent = parent;
                        }
                        this.parent = ResolveUserType (this.parent);
-
-                       // will just set the parent-related bits if called a second time
-                       setup_internal_class ();
                }
 
                internal int get_next_table_index (object obj, int table, bool inc) {
@@ -1666,6 +1619,12 @@ namespace System.Reflection.Emit
                        return created;
                }
 
+               internal override Type RuntimeResolve ()
+               {
+                       check_created ();
+                       return created;
+               }
+
                internal bool is_created {
                        get {
                                return createTypeCalled;
@@ -1764,9 +1723,10 @@ namespace System.Reflection.Emit
                        }
                }
 
-               public extern override bool IsGenericParameter {
-                       [MethodImplAttribute(MethodImplOptions.InternalCall)]
-                       get;
+               public override bool IsGenericParameter {
+                       get {
+                               return false;
+                       }
                }
 
                public override GenericParameterAttributes GenericParameterAttributes {
@@ -1843,7 +1803,7 @@ namespace System.Reflection.Emit
 
                static bool IsValidGetMethodType (Type type)
                {
-                       if (type is TypeBuilder || type is MonoGenericClass)
+                       if (type is TypeBuilder || type is TypeBuilderInstantiation)
                                return true;
                        /*GetMethod() must work with TypeBuilders after CreateType() was called.*/
                        if (type.Module is ModuleBuilder)
diff --git a/mcs/class/corlib/System.Reflection.Emit/TypeBuilderInstantiation.cs b/mcs/class/corlib/System.Reflection.Emit/TypeBuilderInstantiation.cs
new file mode 100644 (file)
index 0000000..c6870f9
--- /dev/null
@@ -0,0 +1,506 @@
+//
+// System.Reflection.Emit.TypeBuilderInstantiation
+//
+// Sean MacIsaac (macisaac@ximian.com)
+// Paolo Molaro (lupus@ximian.com)
+// Patrik Torstensson (patrik.torstensson@labs2.com)
+//
+// (C) 2001 Ximian, Inc.
+//
+
+//
+// Copyright (C) 2004 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.
+//
+
+#if !FULL_AOT_RUNTIME
+using System.Reflection;
+using System.Reflection.Emit;
+using System.Collections;
+using System.Runtime.CompilerServices;
+using System.Globalization;
+using System.Runtime.Serialization;
+using System.Text;
+using System.Runtime.InteropServices;
+
+namespace System.Reflection.Emit
+{
+       /*
+        * TypeBuilderInstantiation represents an instantiation of a generic TypeBuilder.
+        */
+       [StructLayout (LayoutKind.Sequential)]
+       sealed class TypeBuilderInstantiation :
+               TypeInfo
+       {
+               #region Keep in sync with object-internals.h
+#pragma warning disable 649
+               internal Type generic_type;
+               Type[] type_arguments;
+#pragma warning restore 649
+               #endregion
+
+               Hashtable fields, ctors, methods;
+
+               internal TypeBuilderInstantiation ()
+               {
+                       // this should not be used
+                       throw new InvalidOperationException ();
+               }
+
+               internal TypeBuilderInstantiation (Type tb, Type[] args)
+               {
+                       this.generic_type = tb;
+                       this.type_arguments = args;
+               }
+
+               internal override Type InternalResolve ()
+               {
+                       Type gtd = generic_type.InternalResolve ();
+                       Type[] args = new Type [type_arguments.Length];
+                       for (int i = 0; i < type_arguments.Length; ++i)
+                               args [i] = type_arguments [i].InternalResolve ();
+                       return gtd.MakeGenericType (args);
+               }
+
+               // Called from the runtime to return the corresponding finished Type object
+               internal override Type RuntimeResolve ()
+               {
+                       if (generic_type is TypeBuilder && !(generic_type as TypeBuilder).IsCreated ())
+                               AppDomain.CurrentDomain.DoTypeResolve (generic_type);
+                       for (int i = 0; i < type_arguments.Length; ++i) {
+                               var t = type_arguments [i];
+                               if (t is TypeBuilder && !(t as TypeBuilder).IsCreated ())
+                                       AppDomain.CurrentDomain.DoTypeResolve (t);
+                       }
+                       return InternalResolve ();
+               }
+
+               internal bool IsCreated {
+                       get {
+                               TypeBuilder tb = generic_type as TypeBuilder;
+                               return tb != null ? tb.is_created : true;
+                       }
+               }
+
+               private const BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
+               BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
+
+               Type GetParentType ()
+               {
+                       return InflateType (generic_type.BaseType);             
+               }
+
+               internal Type InflateType (Type type)
+               {
+                       return InflateType (type, type_arguments, null);
+               }
+
+               internal Type InflateType (Type type, Type[] method_args)
+               {
+                       return InflateType (type, type_arguments, method_args);
+               }
+
+               internal static Type InflateType (Type type, Type[] type_args, Type[] method_args)
+               {
+                       if (type == null)
+                               return null;
+                       if (!type.IsGenericParameter && !type.ContainsGenericParameters)
+                               return type;
+                       if (type.IsGenericParameter) {
+                               if (type.DeclaringMethod == null)
+                                       return type_args == null ? type : type_args [type.GenericParameterPosition];
+                               return method_args == null ? type : method_args [type.GenericParameterPosition];
+                       }
+                       if (type.IsPointer)
+                               return InflateType (type.GetElementType (), type_args, method_args).MakePointerType ();
+                       if (type.IsByRef)
+                               return InflateType (type.GetElementType (), type_args, method_args).MakeByRefType ();
+                       if (type.IsArray) {
+                               if (type.GetArrayRank () > 1)
+                                       return InflateType (type.GetElementType (), type_args, method_args).MakeArrayType (type.GetArrayRank ());
+                               
+                               if (type.ToString ().EndsWith ("[*]", StringComparison.Ordinal)) /*FIXME, the reflection API doesn't offer a way around this*/
+                                       return InflateType (type.GetElementType (), type_args, method_args).MakeArrayType (1);
+                               return InflateType (type.GetElementType (), type_args, method_args).MakeArrayType ();
+                       }
+
+                       Type[] args = type.GetGenericArguments ();
+                       for (int i = 0; i < args.Length; ++i)
+                               args [i] = InflateType (args [i], type_args, method_args);
+
+                       Type gtd = type.IsGenericTypeDefinition ? type : type.GetGenericTypeDefinition ();
+                       return gtd.MakeGenericType (args);
+               }
+               
+               public override Type BaseType {
+                       get { return generic_type.BaseType; }
+               }
+
+               public override Type[] GetInterfaces ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               protected override bool IsValueTypeImpl ()
+               {
+                       return generic_type.IsValueType;
+               }
+
+               internal override MethodInfo GetMethod (MethodInfo fromNoninstanciated)
+               {
+                       if (methods == null)
+                               methods = new Hashtable ();
+                       if (!methods.ContainsKey (fromNoninstanciated))
+                               methods [fromNoninstanciated] = new MethodOnTypeBuilderInst (this, fromNoninstanciated);
+                       return (MethodInfo)methods [fromNoninstanciated];
+               }
+
+               internal override ConstructorInfo GetConstructor (ConstructorInfo fromNoninstanciated)
+               {
+                       if (ctors == null)
+                               ctors = new Hashtable ();
+                       if (!ctors.ContainsKey (fromNoninstanciated))
+                               ctors [fromNoninstanciated] = new ConstructorOnTypeBuilderInst (this, fromNoninstanciated);
+                       return (ConstructorInfo)ctors [fromNoninstanciated];
+               }
+
+               internal override FieldInfo GetField (FieldInfo fromNoninstanciated)
+               {
+                       if (fields == null)
+                               fields = new Hashtable ();
+                       if (!fields.ContainsKey (fromNoninstanciated))
+                               fields [fromNoninstanciated] = new FieldOnTypeBuilderInst (this, fromNoninstanciated);
+                       return (FieldInfo)fields [fromNoninstanciated];
+               }
+               
+               public override MethodInfo[] GetMethods (BindingFlags bf)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override ConstructorInfo[] GetConstructors (BindingFlags bf)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override FieldInfo[] GetFields (BindingFlags bf)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override PropertyInfo[] GetProperties (BindingFlags bf)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override EventInfo[] GetEvents (BindingFlags bf)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override Type[] GetNestedTypes (BindingFlags bf)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override bool IsAssignableFrom (Type c)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override Type UnderlyingSystemType {
+                       get { return this; }
+               }
+
+               public override Assembly Assembly {
+                       get { return generic_type.Assembly; }
+               }
+
+               public override Module Module {
+                       get { return generic_type.Module; }
+               }
+
+               public override string Name {
+                       get { return generic_type.Name; }
+               }
+
+               public override string Namespace {
+                       get { return generic_type.Namespace; }
+               }
+
+               public override string FullName {
+                       get { return format_name (true, false); }
+               }
+
+               public override string AssemblyQualifiedName {
+                       get { return format_name (true, true); }
+               }
+
+               public override Guid GUID {
+                       get { throw new NotSupportedException (); }
+               }
+
+               string format_name (bool full_name, bool assembly_qualified)
+               {
+                       StringBuilder sb = new StringBuilder (generic_type.FullName);
+
+                       sb.Append ("[");
+                       for (int i = 0; i < type_arguments.Length; ++i) {
+                               if (i > 0)
+                                       sb.Append (",");
+                               
+                               string name;
+                               if (full_name) {
+                                       string assemblyName = type_arguments [i].Assembly.FullName;
+                                       name = type_arguments [i].FullName;
+                                       if (name != null && assemblyName != null)
+                                               name = name + ", " + assemblyName;
+                               } else {
+                                       name = type_arguments [i].ToString ();
+                               }
+                               if (name == null) {
+                                       return null;
+                               }
+                               if (full_name)
+                                       sb.Append ("[");
+                               sb.Append (name);
+                               if (full_name)
+                                       sb.Append ("]");
+                       }
+                       sb.Append ("]");
+                       if (assembly_qualified) {
+                               sb.Append (", ");
+                               sb.Append (generic_type.Assembly.FullName);
+                       }
+                       return sb.ToString ();
+               }
+
+               public override string ToString ()
+               {
+                       return format_name (false, false);
+               }
+
+               public override Type GetGenericTypeDefinition ()
+               {
+                       return generic_type;
+               }
+
+               public override Type[] GetGenericArguments ()
+               {
+                       Type[] ret = new Type [type_arguments.Length];
+                       type_arguments.CopyTo (ret, 0);
+                       return ret;
+               }
+
+               public override bool ContainsGenericParameters {
+                       get {
+                               foreach (Type t in type_arguments) {
+                                       if (t.ContainsGenericParameters)
+                                               return true;
+                               }
+                               return false;
+                       }
+               }
+
+               public override bool IsGenericTypeDefinition {
+                       get { return false; }
+               }
+
+               public override bool IsGenericType {
+                       get { return true; }
+               }
+
+               public override Type DeclaringType {
+                       get { return generic_type.DeclaringType; }
+               }
+
+               public override RuntimeTypeHandle TypeHandle {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override Type MakeArrayType ()
+               {
+                       return new ArrayType (this, 0);
+               }
+
+               public override Type MakeArrayType (int rank)
+               {
+                       if (rank < 1)
+                               throw new IndexOutOfRangeException ();
+                       return new ArrayType (this, rank);
+               }
+
+               public override Type MakeByRefType ()
+               {
+                       return new ByRefType (this);
+               }
+
+               public override Type MakePointerType ()
+               {
+                       return new PointerType (this);
+               }
+
+               public override Type GetElementType ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               protected override bool HasElementTypeImpl ()
+               {
+                       return false;
+               }
+
+               protected override bool IsCOMObjectImpl ()
+               {
+                       return false;
+               }
+
+               protected override bool IsPrimitiveImpl ()
+               {
+                       return false;
+               }
+
+               protected override bool IsArrayImpl ()
+               {
+                       return false;
+               }
+
+               protected override bool IsByRefImpl ()
+               {
+                       return false;
+               }
+
+               protected override bool IsPointerImpl ()
+               {
+                       return false;
+               }
+
+               protected override TypeAttributes GetAttributeFlagsImpl ()
+               {
+                       return generic_type.Attributes; 
+               }
+
+               //stuff that throws
+               public override Type GetInterface (string name, bool ignoreCase)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override EventInfo GetEvent (string name, BindingFlags bindingAttr)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override FieldInfo GetField( string name, BindingFlags bindingAttr)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override MemberInfo[] GetMembers (BindingFlags bindingAttr)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override Type GetNestedType (string name, BindingFlags bindingAttr)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override object InvokeMember (string name, BindingFlags invokeAttr,
+                                                    Binder binder, object target, object[] args,
+                                                    ParameterModifier[] modifiers,
+                                                    CultureInfo culture, string[] namedParameters)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr, Binder binder,
+                                                            CallingConventions callConvention, Type[] types,
+                                                            ParameterModifier[] modifiers)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               protected override PropertyInfo GetPropertyImpl (string name, BindingFlags bindingAttr, Binder binder,
+                                                                Type returnType, Type[] types, ParameterModifier[] modifiers)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               protected override ConstructorInfo GetConstructorImpl (BindingFlags bindingAttr,
+                                                                      Binder binder,
+                                                                      CallingConventions callConvention,
+                                                                      Type[] types,
+                                                                      ParameterModifier[] modifiers)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               //MemberInfo
+               public override bool IsDefined (Type attributeType, bool inherit)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override object [] GetCustomAttributes (bool inherit)
+               {
+                       if (IsCreated)
+                               return generic_type.GetCustomAttributes (inherit);
+                       throw new NotSupportedException ();
+               }
+
+               public override object [] GetCustomAttributes (Type attributeType, bool inherit)
+               {
+                       if (IsCreated)
+                               return generic_type.GetCustomAttributes (attributeType, inherit);
+                       throw new NotSupportedException ();
+               }
+
+               internal override bool IsUserType {
+                       get {
+                               foreach (var t in type_arguments) {
+                                       if (t.IsUserType)
+                                               return true;
+                               }
+                               return false;
+                       }
+               }
+
+               internal static Type MakeGenericType (Type type, Type[] typeArguments)
+               {
+                       return new TypeBuilderInstantiation (type, typeArguments);
+               }
+       }
+}
+#else
+namespace System.Reflection.Emit
+{
+       abstract class TypeBuilderInstantiation : TypeInfo
+       {
+               internal static Type MakeGenericType (Type type, Type[] typeArguments)
+               {
+                       throw new NotSupportedException ("User types are not supported under full aot");
+               }
+       }
+}
+#endif
index c5cecb3858e7d17ef3db6c34fb55db48b3ea6ba2..4f8948cc265081e49b9f9717e04267ab0aabe4db 100644 (file)
@@ -53,12 +53,15 @@ namespace System.Reflection {
        [ClassInterface(ClassInterfaceType.None)]
        [StructLayout (LayoutKind.Sequential)]
 #if MOBILE
-       public partial class Assembly : ICustomAttributeProvider {
+       public partial class Assembly : ICustomAttributeProvider, ISerializable
 #else
-       public abstract class Assembly : ICustomAttributeProvider, _Assembly, IEvidenceFactory, ISerializable {
+       public abstract class Assembly : ICustomAttributeProvider, _Assembly, IEvidenceFactory, ISerializable
 #endif
-               internal class ResolveEventHolder {
+       {
+               internal class ResolveEventHolder {     
+#pragma warning disable 67
                        public event ModuleResolveEventHandler ModuleResolve;
+#pragma warning restore
                }
 
                internal class UnmanagedMemoryStreamForModule : UnmanagedMemoryStream
@@ -117,7 +120,7 @@ namespace System.Reflection {
                // We can't store the event directly in this class, since the
                // compiler would silently insert the fields before _mono_assembly
                //
-               public event ModuleResolveEventHandler ModuleResolve {
+               public virtual event ModuleResolveEventHandler ModuleResolve {
                        [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
                        add {
                                resolve_event_holder.ModuleResolve += value;
@@ -894,13 +897,12 @@ namespace System.Reflection {
                public virtual PermissionSet PermissionSet {
                        get { return this.GrantedPermissionSet; }
                }
-               
+#endif
+
                public virtual SecurityRuleSet SecurityRuleSet {
                        get { throw CreateNIE (); }
                }
 
-#endif
-
                static Exception CreateNIE ()
                {
                        return new NotImplementedException ("Derived classes must implement it");
diff --git a/mcs/class/corlib/System.Reflection/MonoGenericClass.cs b/mcs/class/corlib/System.Reflection/MonoGenericClass.cs
deleted file mode 100644 (file)
index 51a1a50..0000000
+++ /dev/null
@@ -1,519 +0,0 @@
-//
-// System.Reflection.MonoGenericClass
-//
-// Sean MacIsaac (macisaac@ximian.com)
-// Paolo Molaro (lupus@ximian.com)
-// Patrik Torstensson (patrik.torstensson@labs2.com)
-//
-// (C) 2001 Ximian, Inc.
-//
-
-//
-// Copyright (C) 2004 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.
-//
-
-#if !FULL_AOT_RUNTIME
-using System.Reflection;
-using System.Reflection.Emit;
-using System.Collections;
-using System.Runtime.CompilerServices;
-using System.Globalization;
-using System.Runtime.Serialization;
-using System.Text;
-using System.Runtime.InteropServices;
-
-namespace System.Reflection
-{
-       /*
-        * MonoGenericClass represents an instantiation of a generic TypeBuilder. MS
-        * calls this class TypeBuilderInstantiation (a much better name). MS returns 
-        * NotImplementedException for many of the methods but we can't do that as gmcs
-        * depends on them.
-        */
-       [StructLayout (LayoutKind.Sequential)]
-       sealed class MonoGenericClass :
-               TypeInfo
-       {
-               #region Keep in sync with object-internals.h
-#pragma warning disable 649
-               internal Type generic_type;
-               Type[] type_arguments;
-               bool initialized;
-#pragma warning restore 649
-               #endregion
-
-               Hashtable fields, ctors, methods;
-
-               internal MonoGenericClass ()
-               {
-                       // this should not be used
-                       throw new InvalidOperationException ();
-               }
-
-               internal MonoGenericClass (Type tb, Type[] args)
-               {
-                       this.generic_type = tb;
-                       this.type_arguments = args;
-                       /*
-                       This is a temporary hack until we can fix the rest of the runtime
-                       to properly handle this class to be a complete UT.
-
-                       We must not regisrer this with the runtime after the type is created
-                       otherwise created_type.MakeGenericType will return an instance of MonoGenericClass,
-                       which is very very broken.
-                       */
-                       if (tb is TypeBuilder && !(tb as TypeBuilder).is_created)
-                               register_with_runtime (this);
-                       
-               }
-
-               internal override Type InternalResolve ()
-               {
-                       Type gtd = generic_type.InternalResolve ();
-                       Type[] args = new Type [type_arguments.Length];
-                       for (int i = 0; i < type_arguments.Length; ++i)
-                               args [i] = type_arguments [i].InternalResolve ();
-                       return gtd.MakeGenericType (args);
-               }
-
-               [MethodImplAttribute(MethodImplOptions.InternalCall)]
-               extern void initialize (FieldInfo[] fields);
-
-               [MethodImplAttribute(MethodImplOptions.InternalCall)]
-               internal static extern void register_with_runtime (Type type);
-
-               internal bool IsCreated {
-                       get {
-                               TypeBuilder tb = generic_type as TypeBuilder;
-                               return tb != null ? tb.is_created : true;
-                       }
-               }
-
-               private const BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
-               BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
-
-               void initialize ()
-               {
-                       if (initialized)
-                               return;
-
-                       MonoGenericClass parent = GetParentType () as MonoGenericClass;
-                       if (parent != null)
-                               parent.initialize ();
-                               
-                       initialize (generic_type.GetFields (flags));
-
-                       initialized = true;
-               }
-
-               Type GetParentType ()
-               {
-                       return InflateType (generic_type.BaseType);             
-               }
-
-               internal Type InflateType (Type type)
-               {
-                       return InflateType (type, type_arguments, null);
-               }
-
-               internal Type InflateType (Type type, Type[] method_args)
-               {
-                       return InflateType (type, type_arguments, method_args);
-               }
-
-               internal static Type InflateType (Type type, Type[] type_args, Type[] method_args)
-               {
-                       if (type == null)
-                               return null;
-                       if (!type.IsGenericParameter && !type.ContainsGenericParameters)
-                               return type;
-                       if (type.IsGenericParameter) {
-                               if (type.DeclaringMethod == null)
-                                       return type_args == null ? type : type_args [type.GenericParameterPosition];
-                               return method_args == null ? type : method_args [type.GenericParameterPosition];
-                       }
-                       if (type.IsPointer)
-                               return InflateType (type.GetElementType (), type_args, method_args).MakePointerType ();
-                       if (type.IsByRef)
-                               return InflateType (type.GetElementType (), type_args, method_args).MakeByRefType ();
-                       if (type.IsArray) {
-                               if (type.GetArrayRank () > 1)
-                                       return InflateType (type.GetElementType (), type_args, method_args).MakeArrayType (type.GetArrayRank ());
-                               
-                               if (type.ToString ().EndsWith ("[*]", StringComparison.Ordinal)) /*FIXME, the reflection API doesn't offer a way around this*/
-                                       return InflateType (type.GetElementType (), type_args, method_args).MakeArrayType (1);
-                               return InflateType (type.GetElementType (), type_args, method_args).MakeArrayType ();
-                       }
-
-                       Type[] args = type.GetGenericArguments ();
-                       for (int i = 0; i < args.Length; ++i)
-                               args [i] = InflateType (args [i], type_args, method_args);
-
-                       Type gtd = type.IsGenericTypeDefinition ? type : type.GetGenericTypeDefinition ();
-                       return gtd.MakeGenericType (args);
-               }
-               
-               public override Type BaseType {
-                       get { return generic_type.BaseType; }
-               }
-
-               public override Type[] GetInterfaces ()
-               {
-                       throw new NotSupportedException ();
-               }
-
-               protected override bool IsValueTypeImpl ()
-               {
-                       return generic_type.IsValueType;
-               }
-
-               internal override MethodInfo GetMethod (MethodInfo fromNoninstanciated)
-               {
-                       initialize ();
-
-                       if (methods == null)
-                               methods = new Hashtable ();
-                       if (!methods.ContainsKey (fromNoninstanciated))
-                               methods [fromNoninstanciated] = new MethodOnTypeBuilderInst (this, fromNoninstanciated);
-                       return (MethodInfo)methods [fromNoninstanciated];
-               }
-
-               internal override ConstructorInfo GetConstructor (ConstructorInfo fromNoninstanciated)
-               {
-                       initialize ();
-
-                       if (ctors == null)
-                               ctors = new Hashtable ();
-                       if (!ctors.ContainsKey (fromNoninstanciated))
-                               ctors [fromNoninstanciated] = new ConstructorOnTypeBuilderInst (this, fromNoninstanciated);
-                       return (ConstructorInfo)ctors [fromNoninstanciated];
-               }
-
-               internal override FieldInfo GetField (FieldInfo fromNoninstanciated)
-               {
-                       initialize ();
-                       if (fields == null)
-                               fields = new Hashtable ();
-                       if (!fields.ContainsKey (fromNoninstanciated))
-                               fields [fromNoninstanciated] = new FieldOnTypeBuilderInst (this, fromNoninstanciated);
-                       return (FieldInfo)fields [fromNoninstanciated];
-               }
-               
-               public override MethodInfo[] GetMethods (BindingFlags bf)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override ConstructorInfo[] GetConstructors (BindingFlags bf)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override FieldInfo[] GetFields (BindingFlags bf)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override PropertyInfo[] GetProperties (BindingFlags bf)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override EventInfo[] GetEvents (BindingFlags bf)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override Type[] GetNestedTypes (BindingFlags bf)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override bool IsAssignableFrom (Type c)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override Type UnderlyingSystemType {
-                       get { return this; }
-               }
-
-               public override Assembly Assembly {
-                       get { return generic_type.Assembly; }
-               }
-
-               public override Module Module {
-                       get { return generic_type.Module; }
-               }
-
-               public override string Name {
-                       get { return generic_type.Name; }
-               }
-
-               public override string Namespace {
-                       get { return generic_type.Namespace; }
-               }
-
-               public override string FullName {
-                       get { return format_name (true, false); }
-               }
-
-               public override string AssemblyQualifiedName {
-                       get { return format_name (true, true); }
-               }
-
-               public override Guid GUID {
-                       get { throw new NotSupportedException (); }
-               }
-
-               string format_name (bool full_name, bool assembly_qualified)
-               {
-                       StringBuilder sb = new StringBuilder (generic_type.FullName);
-
-                       sb.Append ("[");
-                       for (int i = 0; i < type_arguments.Length; ++i) {
-                               if (i > 0)
-                                       sb.Append (",");
-                               
-                               string name;
-                               if (full_name) {
-                                       string assemblyName = type_arguments [i].Assembly.FullName;
-                                       name = type_arguments [i].FullName;
-                                       if (name != null && assemblyName != null)
-                                               name = name + ", " + assemblyName;
-                               } else {
-                                       name = type_arguments [i].ToString ();
-                               }
-                               if (name == null) {
-                                       return null;
-                               }
-                               if (full_name)
-                                       sb.Append ("[");
-                               sb.Append (name);
-                               if (full_name)
-                                       sb.Append ("]");
-                       }
-                       sb.Append ("]");
-                       if (assembly_qualified) {
-                               sb.Append (", ");
-                               sb.Append (generic_type.Assembly.FullName);
-                       }
-                       return sb.ToString ();
-               }
-
-               public override string ToString ()
-               {
-                       return format_name (false, false);
-               }
-
-               public override Type GetGenericTypeDefinition ()
-               {
-                       return generic_type;
-               }
-
-               public override Type[] GetGenericArguments ()
-               {
-                       Type[] ret = new Type [type_arguments.Length];
-                       type_arguments.CopyTo (ret, 0);
-                       return ret;
-               }
-
-               public override bool ContainsGenericParameters {
-                       get {
-                               foreach (Type t in type_arguments) {
-                                       if (t.ContainsGenericParameters)
-                                               return true;
-                               }
-                               return false;
-                       }
-               }
-
-               public override bool IsGenericTypeDefinition {
-                       get { return false; }
-               }
-
-               public override bool IsGenericType {
-                       get { return true; }
-               }
-
-               public override Type DeclaringType {
-                       get { return generic_type.DeclaringType; }
-               }
-
-               public override RuntimeTypeHandle TypeHandle {
-                       get {
-                               throw new NotSupportedException ();
-                       }
-               }
-
-               public override Type MakeArrayType ()
-               {
-                       return new ArrayType (this, 0);
-               }
-
-               public override Type MakeArrayType (int rank)
-               {
-                       if (rank < 1)
-                               throw new IndexOutOfRangeException ();
-                       return new ArrayType (this, rank);
-               }
-
-               public override Type MakeByRefType ()
-               {
-                       return new ByRefType (this);
-               }
-
-               public override Type MakePointerType ()
-               {
-                       return new PointerType (this);
-               }
-
-               public override Type GetElementType ()
-               {
-                       throw new NotSupportedException ();
-               }
-
-               protected override bool HasElementTypeImpl ()
-               {
-                       return false;
-               }
-
-               protected override bool IsCOMObjectImpl ()
-               {
-                       return false;
-               }
-
-               protected override bool IsPrimitiveImpl ()
-               {
-                       return false;
-               }
-
-               protected override bool IsArrayImpl ()
-               {
-                       return false;
-               }
-
-               protected override bool IsByRefImpl ()
-               {
-                       return false;
-               }
-
-               protected override bool IsPointerImpl ()
-               {
-                       return false;
-               }
-
-               protected override TypeAttributes GetAttributeFlagsImpl ()
-               {
-                       return generic_type.Attributes; 
-               }
-
-               //stuff that throws
-               public override Type GetInterface (string name, bool ignoreCase)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override EventInfo GetEvent (string name, BindingFlags bindingAttr)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override FieldInfo GetField( string name, BindingFlags bindingAttr)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override MemberInfo[] GetMembers (BindingFlags bindingAttr)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override Type GetNestedType (string name, BindingFlags bindingAttr)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override object InvokeMember (string name, BindingFlags invokeAttr,
-                                                    Binder binder, object target, object[] args,
-                                                    ParameterModifier[] modifiers,
-                                                    CultureInfo culture, string[] namedParameters)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr, Binder binder,
-                                                            CallingConventions callConvention, Type[] types,
-                                                            ParameterModifier[] modifiers)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               protected override PropertyInfo GetPropertyImpl (string name, BindingFlags bindingAttr, Binder binder,
-                                                                Type returnType, Type[] types, ParameterModifier[] modifiers)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               protected override ConstructorInfo GetConstructorImpl (BindingFlags bindingAttr,
-                                                                      Binder binder,
-                                                                      CallingConventions callConvention,
-                                                                      Type[] types,
-                                                                      ParameterModifier[] modifiers)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               //MemberInfo
-               public override bool IsDefined (Type attributeType, bool inherit)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override object [] GetCustomAttributes (bool inherit)
-               {
-                       if (IsCreated)
-                               return generic_type.GetCustomAttributes (inherit);
-                       throw new NotSupportedException ();
-               }
-
-               public override object [] GetCustomAttributes (Type attributeType, bool inherit)
-               {
-                       if (IsCreated)
-                               return generic_type.GetCustomAttributes (attributeType, inherit);
-                       throw new NotSupportedException ();
-               }
-
-               internal override bool IsUserType {
-                       get {
-                               foreach (var t in type_arguments) {
-                                       if (t.IsUserType)
-                                               return true;
-                               }
-                               return false;
-                       }
-               }
-
-       }
-}
-
-#endif
diff --git a/mcs/class/corlib/System.Reflection/MonoGenericMethod.cs b/mcs/class/corlib/System.Reflection/MonoGenericMethod.cs
deleted file mode 100644 (file)
index 48ef423..0000000
+++ /dev/null
@@ -1,60 +0,0 @@
-//
-// System.Reflection.MonoGenericMethod
-//
-// Martin Baulig (martin@ximian.com)
-//
-// (C) 2004 Novell, Inc.
-//
-
-//
-// Copyright (C) 2004 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.Reflection;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-
-namespace System.Reflection
-{
-       [Serializable]
-       [StructLayout (LayoutKind.Sequential)]
-       internal class MonoGenericMethod : MonoMethod
-       {
-               internal MonoGenericMethod ()
-               {
-                       // this should not be used
-                       throw new InvalidOperationException ();
-               }
-
-       }
-
-       [Serializable]
-       [StructLayout (LayoutKind.Sequential)]
-       internal class MonoGenericCMethod : MonoCMethod
-       {
-               internal MonoGenericCMethod ()
-               {
-                       // this should not be used
-                       throw new InvalidOperationException ();
-               }
-       }
-}
diff --git a/mcs/class/corlib/System.Reflection/TargetException.cs b/mcs/class/corlib/System.Reflection/TargetException.cs
deleted file mode 100644 (file)
index 5c5c69e..0000000
+++ /dev/null
@@ -1,65 +0,0 @@
-//
-// System.Reflection.TargetException.cs
-//
-// Author: Duncan Mak (duncan@ximian.com)
-//
-// (C) Ximian, Inc. http://www.ximian.com
-//
-
-//
-// Copyright (C) 2004 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.Globalization;
-using System.Runtime.Serialization;
-using System.Runtime.InteropServices;
-
-namespace System.Reflection
-{
-       [ComVisible (true)]
-       [Serializable]
-#if MOBILE
-       public class TargetException : Exception {
-#else
-       public class TargetException : ApplicationException {
-#endif
-               public TargetException ()
-                       : base (Locale.GetText ("Unable to invoke an invalid target."))
-               {
-               }
-
-               public TargetException (string message)
-                       : base (message)
-               {
-               }
-
-               public TargetException (string message, Exception inner)
-                       : base (message, inner)
-               {
-               }
-
-               protected TargetException (SerializationInfo info, StreamingContext context)
-                       : base (info, context)
-               {
-               }
-       }
-}
diff --git a/mcs/class/corlib/System.Reflection/TargetInvocationException.cs b/mcs/class/corlib/System.Reflection/TargetInvocationException.cs
deleted file mode 100644 (file)
index 5f56432..0000000
+++ /dev/null
@@ -1,59 +0,0 @@
-//
-// System.Reflection.TargetInvocationException
-//
-// Sean MacIsaac (macisaac@ximian.com)
-// Duncan Mak  (duncan@ximian.com)
-//
-// (C) 2001 Ximian, Inc.
-
-//
-// Copyright (C) 2004 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.Runtime.Serialization;
-using System.Runtime.InteropServices;
-
-namespace System.Reflection
-{
-       [ComVisible (true)]
-       [Serializable]
-#if MOBILE
-       public sealed class TargetInvocationException : Exception {
-#else
-       public sealed class TargetInvocationException : ApplicationException {
-#endif
-               public TargetInvocationException (Exception inner)
-                       : base ("Exception has been thrown by the target of an invocation.", inner)
-               {                       
-               }
-
-               public TargetInvocationException (string message, Exception inner)
-                       : base (message, inner)
-               {
-               }               
-
-               internal TargetInvocationException (SerializationInfo info, StreamingContext sc)
-                       : base (info, sc)
-               {
-               }
-       }       
-}
diff --git a/mcs/class/corlib/System.Reflection/TargetParameterCountException.cs b/mcs/class/corlib/System.Reflection/TargetParameterCountException.cs
deleted file mode 100644 (file)
index 8b6c2b2..0000000
+++ /dev/null
@@ -1,66 +0,0 @@
-//
-// System.Reflection.TargetParameterCountException.cs
-//
-// Author: Duncan Mak (duncan@ximian.com)
-//
-// (C) Ximian, Inc. http://www.ximian.com
-//
-
-//
-// Copyright (C) 2004 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.Runtime.Serialization;
-using System.Globalization;
-using System.Runtime.InteropServices;
-
-namespace System.Reflection
-{
-       [ComVisible (true)]
-       [Serializable]
-#if MOBILE
-       public sealed class TargetParameterCountException : Exception {
-#else
-       public sealed class TargetParameterCountException : ApplicationException {
-#endif
-               public TargetParameterCountException ()
-                       : base (Locale.GetText ("Number of parameter does not match expected count."))
-               {
-               }
-
-               public TargetParameterCountException (string message)
-                       : base (message)
-               {
-               }
-
-               public TargetParameterCountException (string message, Exception inner)
-                       : base (message, inner)
-               {
-               }
-
-               internal TargetParameterCountException (SerializationInfo info,
-                                                      StreamingContext context)
-                       : base (info, context)
-               {
-               }
-       }
-}
index d7128abc33553234622f969754c0ffe932741ded..2def9ddba50828744ab6ae26d6e37d1870df033b 100644 (file)
@@ -1426,10 +1426,10 @@ namespace System.Runtime.InteropServices
                        const int COR_E_TARGET = unchecked ((int)0x80131603L);
                        const int COR_E_TARGETINVOCATION = unchecked ((int)0x80131604L);
                        const int COR_E_TARGETPARAMCOUNT = unchecked ((int)0x8002000EL);
-                       const int COR_E_THREADABORTED = unchecked ((int)0x80131530L);
+                       //const int COR_E_THREADABORTED = unchecked ((int)0x80131530L);
                        const int COR_E_THREADINTERRUPTED = unchecked ((int)0x80131519L);
                        const int COR_E_THREADSTATE = unchecked ((int)0x80131520L);
-                       const int COR_E_THREADSTOP = unchecked ((int)0x80131521L);
+                       //const int COR_E_THREADSTOP = unchecked ((int)0x80131521L);
                        const int COR_E_TYPEINITIALIZATION = unchecked ((int)0x80131534L);
                        const int COR_E_VERIFICATION = unchecked ((int)0x8013150DL);
                        //const int COR_E_WEAKREFERENCE = unchecked ((int)?);
index 33fef7a0a8d2c26525bdb5146ef1093305ae47d7..eb45ced8220104fedb88ee88eb5f57c6af55be7f 100644 (file)
@@ -106,7 +106,12 @@ namespace System.Runtime.Remoting
                {
                        lock (channelTemplates) {
                                if (!defaultConfigRead) {
-                                       ReadConfigFile (Environment.GetMachineConfigPath ());
+                                       var bundled = Environment.GetBundledMachineConfig ();
+                                       if (bundled != null)
+                                               ReadConfigString (bundled);
+
+                                       if (File.Exists (Environment.GetMachineConfigPath ()))
+                                               ReadConfigFile (Environment.GetMachineConfigPath ());
                                        defaultConfigRead = true;
                                }
 
@@ -121,6 +126,22 @@ namespace System.Runtime.Remoting
                        Configure (filename, false);
                }
 
+               private static void ReadConfigString (string filename)
+               {
+                       try
+                       {
+                               SmallXmlParser parser = new SmallXmlParser ();
+                               using (TextReader rreader = new StringReader (filename)) {
+                                       ConfigHandler handler = new ConfigHandler (false);
+                                       parser.Parse (rreader, handler);
+                               }
+                       }
+                       catch (Exception ex)
+                       {
+                               throw new RemotingException ("Configuration string could not be loaded: " + ex.Message, ex);
+                       }
+               }
+
                private static void ReadConfigFile (string filename)
                {
                        try
index 2bb0fd9f6c344df832f76bb55180ca188e775921..7c9f393da25234ef2bc178b23a75810937a30436 100644 (file)
@@ -35,6 +35,7 @@ namespace System.Runtime
                Batch = 0,
                Interactive = 1,
                LowLatency = 2,
-               SustainedLowLatency = 3
+               SustainedLowLatency = 3,
+               NoGCRegion = 4
        }
 }
index 8cfd398094e6fea6a08e2edd79805da54b96a29b..ac20b894ef3ea3928492ef0c4923b6ea1898c7b2 100644 (file)
@@ -127,6 +127,11 @@ namespace System.Security.AccessControl
                {
                        SetAuditRule((AuditRule)rule);
                }
+
+               internal void Persist (SafeHandle handle)
+               {
+                       PersistModifications (handle);
+               }
        }
 }
 
index d97859f49db9d0164c155ad5d2e3e012338831ab..db43c8b549001e029973a5926fd63929792a1cd4 100644 (file)
@@ -135,12 +135,7 @@ namespace System.Security.AccessControl
                {
                        Persist (name, includeSections, null);
                }
-
-               internal void Persist (SafeHandle handle)
-               {
-                       PersistModifications (handle);
-               }
-               
+       
                internal void PersistModifications (SafeHandle handle)
                {
                        WriteLock();
@@ -422,12 +417,14 @@ namespace System.Security.AccessControl
                [return: MarshalAs (UnmanagedType.Bool)]
                static extern bool IsValidSecurityDescriptor (IntPtr descriptor);
                
+               /*
                struct SecurityDescriptor
                {
                        public byte Revision, Size;
                        public ushort ControlFlags;
                        public IntPtr Owner, Group, Sacl, Dacl;
                }
+               */
                #endregion
 #endif
        }
index 93c4c2d451a93713bdd13c0579d95aaa8fc6a277..4bed60fc3b93acbda77c62ddc51f284fc284254c 100644 (file)
@@ -166,7 +166,7 @@ namespace System.Security.AccessControl
                        SetAuditRule((AuditRule)rule);
                }
                
-               protected new void Persist (SafeHandle handle)
+               protected void Persist (SafeHandle handle)
                {
                        WriteLock ();
                        try {
index 29322f74ea8b8c8c30e82044455472439bcd7eb1..9ae2a61b75ad539b714e6c40a1042d8c1f02c56b 100755 (executable)
@@ -44,6 +44,16 @@ namespace System.Security.Cryptography {
        [ComVisible (true)]
        public partial class CryptoConfig {
 
+               public static void AddAlgorithm (Type algorithm, params string[] names)
+               {
+                       throw new PlatformNotSupportedException ();
+               }
+
+               public static void AddOID (string oid, params string[] names)
+               {
+                       throw new PlatformNotSupportedException ();
+               }
+
                // try to avoid hitting the CreateFromName overloads to help the linker
 
                public static object CreateFromName (string name)
index 8a98c9d5ad849b43707eedfd77ec93b5de597c53..7abdbecd11a782671b3976c02e15089365142756 100644 (file)
@@ -58,7 +58,7 @@ namespace System.Security.Cryptography {
                        _handle = RngInitialize (null);
                        Check ();
                }
-#if !MOBILE
+
                public RNGCryptoServiceProvider (byte[] rgb)
                {
                        _handle = RngInitialize (rgb);
@@ -81,7 +81,7 @@ namespace System.Security.Cryptography {
                                _handle = RngInitialize (Encoding.UTF8.GetBytes (str));
                        Check ();
                }
-#endif
+
                private void Check () 
                {
                        if (_handle == IntPtr.Zero) {
index 94d6aac785a15beba965aae8f8dff67574385331..2e19104a39d81b5d9b92fdc6b2eda620468c3fad 100644 (file)
@@ -91,6 +91,7 @@ namespace System.Threading {
                private IntPtr thread_pinning_ref;
                private IntPtr abort_protected_block_count;
                private int priority = (int) ThreadPriority.Normal;
+               private IntPtr owned_mutex;
                /* 
                 * These fields are used to avoid having to increment corlib versions
                 * when a new field is added to the unmanaged MonoThread structure.
@@ -459,6 +460,12 @@ namespace System.Threading {
                {
                        throw new PlatformNotSupportedException ("Thread.ResetAbort is not supported on the current platform.");
                }
+
+               internal object AbortReason {
+                       get {
+                               throw new PlatformNotSupportedException ("Thread.ResetAbort is not supported on the current platform.");
+                       }
+               }
 #endif // MONO_FEATURE_THREAD_ABORT
 
                [MethodImplAttribute (MethodImplOptions.InternalCall)]
@@ -703,5 +710,10 @@ namespace System.Threading {
                        throw new PlatformNotSupportedException ("Thread.Resume is not supported on the current platform.");
                }
 #endif
+
+               public void DisableComObjectEagerCleanup ()
+               {
+                       throw new PlatformNotSupportedException ();
+               }
        }
 }
index 76a637ea631fbd4b64cfaf30bdb37607954f8380..ea12a7f34681a93c7def93d8e8678882349c7ccc 100644 (file)
@@ -1217,14 +1217,16 @@ namespace System {
                        SetData (name, data);
                }
 
-#if !MOBILE
                [Obsolete ("Use AppDomainSetup.DynamicBase")]
                [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
                public void SetDynamicBase (string path)
                {
+#if MOBILE
+                       throw new PlatformNotSupportedException ();
+#else
                        SetupInformationNoCopy.DynamicBase = path;
+#endif // MOBILE
                }
-#endif // !MOBILE
 
                [Obsolete ("AppDomain.GetCurrentThreadId has been deprecated"
                        + " because it does not provide a stable Id when managed"
@@ -1286,14 +1288,11 @@ namespace System {
                private Assembly DoAssemblyResolve (string name, Assembly requestingAssembly, bool refonly)
                {
                        ResolveEventHandler del;
-#if !MOBILE
                        if (refonly)
                                del = ReflectionOnlyAssemblyResolve;
                        else
                                del = AssemblyResolve;
-#else
-                       del = AssemblyResolve;
-#endif
+
                        if (del == null)
                                return null;
                        
@@ -1490,9 +1489,7 @@ namespace System {
                }
 #endif // MONO_FEATURE_MULTIPLE_APPDOMAINS
 
-#if !MOBILE
                public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
-#endif
 
         #pragma warning disable 649
 #if MOBILE
index d6b0ec038e4e7ad4878b4fd0e29645994c3e7b26..19d17929c54a552b07f4b16c4f587d6aba2ef421 100644 (file)
@@ -57,7 +57,7 @@ namespace System {
                 * of icalls, do not require an increment.
                 */
 #pragma warning disable 169
-               private const int mono_corlib_version = 155;
+               private const int mono_corlib_version = 160;
 #pragma warning restore 169
 
                [ComVisible (true)]
@@ -322,7 +322,7 @@ namespace System {
                                return trace.ToString ();
                        }
                }
-#if !MOBILE
+
                /// <summary>
                /// Get a fully qualified path to the system directory
                /// </summary>
@@ -331,7 +331,7 @@ namespace System {
                                return GetFolderPath (SpecialFolder.System);
                        }
                }
-#endif
+
                /// <summary>
                /// Get the number of milliseconds that have elapsed since the system was booted
                /// </summary>
@@ -996,6 +996,14 @@ namespace System {
                [MethodImplAttribute (MethodImplOptions.InternalCall)]
                internal extern static int GetPageSize ();
 
+               [MethodImplAttribute(MethodImplOptions.InternalCall)]
+               extern private static string get_bundled_machine_config ();
+
+               internal static string GetBundledMachineConfig ()
+               {
+                       return get_bundled_machine_config ();
+               }
+
                static internal bool IsUnix {
                        get {
                                int platform = (int) Environment.Platform;
diff --git a/mcs/class/corlib/System/GC.cs b/mcs/class/corlib/System/GC.cs
deleted file mode 100644 (file)
index a673419..0000000
+++ /dev/null
@@ -1,159 +0,0 @@
-//
-// System.GC.cs
-//
-// Author:
-//   Paolo Molaro (lupus@ximian.com)
-//
-// (C) 2001 Ximian, Inc.  http://www.ximian.com
-//
-
-//
-// Copyright (C) 2004 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.Runtime.CompilerServices;
-using System.Runtime.ConstrainedExecution;
-using System.Security.Permissions;
-
-namespace System
-{
-       public static class GC
-       {
-
-               public extern static int MaxGeneration {
-                       [MethodImplAttribute(MethodImplOptions.InternalCall)]
-                       get;
-               }
-
-               [MethodImplAttribute (MethodImplOptions.InternalCall)]
-               extern static void InternalCollect (int generation);
-               
-               public static void Collect () {
-                       InternalCollect (MaxGeneration);
-               }
-
-               public static void Collect (int generation) {
-                       if (generation < 0)
-                               throw new ArgumentOutOfRangeException ("generation");
-                       InternalCollect (generation);
-               }
-
-               [MonoDocumentationNote ("mode parameter ignored")]
-               public static void Collect (int generation, GCCollectionMode mode) {
-                       Collect (generation);
-               }
-
-               [MonoDocumentationNote ("mode and blocking parameters ignored")]
-               public static void Collect (int generation, GCCollectionMode mode, bool blocking) {
-                       Collect (generation);
-               }
-
-               [MethodImplAttribute (MethodImplOptions.InternalCall)]
-               public extern static int GetGeneration (object obj);
-
-               public static int GetGeneration (WeakReference wo) {
-                       object obj = wo.Target;
-                       if (obj == null)
-                               throw new ArgumentException ();
-                       return GetGeneration (obj);
-               }
-
-               [MethodImplAttribute (MethodImplOptions.InternalCall)]
-               public extern static long GetTotalMemory (bool forceFullCollection);
-
-               /* this icall has weird semantics check the docs... */
-               [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
-               [MethodImplAttribute (MethodImplOptions.InternalCall)]
-               public extern static void KeepAlive (object obj);
-               
-               [MethodImplAttribute (MethodImplOptions.InternalCall)]
-               public extern static void ReRegisterForFinalize (object obj);
-
-               [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
-               [MethodImplAttribute (MethodImplOptions.InternalCall)]
-               public extern static void SuppressFinalize (object obj);
-
-               [MethodImplAttribute (MethodImplOptions.InternalCall)]
-               public extern static void WaitForPendingFinalizers ();
-
-               [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
-               [MethodImplAttribute (MethodImplOptions.InternalCall)]
-               public extern static int CollectionCount (int generation);
-
-               [MethodImplAttribute (MethodImplOptions.InternalCall)]
-               private extern static void RecordPressure (long bytesAllocated);
-
-               public static void AddMemoryPressure (long bytesAllocated) {
-                       RecordPressure (bytesAllocated);
-               }
-
-               public static void RemoveMemoryPressure (long bytesAllocated) {
-                       RecordPressure (-bytesAllocated);
-               }
-
-               [PermissionSetAttribute (SecurityAction.LinkDemand, Name = "FullTrust")]
-               [MonoTODO]
-               public static GCNotificationStatus WaitForFullGCApproach () {
-                       throw new NotImplementedException ();
-               }
-
-               [PermissionSetAttribute (SecurityAction.LinkDemand, Name = "FullTrust")]
-               [MonoTODO]
-               public static GCNotificationStatus WaitForFullGCApproach (int millisecondsTimeout) {
-                       throw new NotImplementedException ();
-               }
-
-               [PermissionSetAttribute (SecurityAction.LinkDemand, Name = "FullTrust")]
-               [MonoTODO]
-               public static GCNotificationStatus WaitForFullGCComplete () {
-                       throw new NotImplementedException ();
-               }
-
-               [PermissionSetAttribute (SecurityAction.LinkDemand, Name = "FullTrust")]
-               [MonoTODO]
-               public static GCNotificationStatus WaitForFullGCComplete (int millisecondsTimeout) {
-                       throw new NotImplementedException ();
-               }
-
-               [PermissionSetAttribute (SecurityAction.LinkDemand, Name = "FullTrust")]
-               public static void RegisterForFullGCNotification (int maxGenerationThreshold, int largeObjectHeapThreshold) {
-                       if (maxGenerationThreshold < 1 || maxGenerationThreshold > 99)
-                               throw new ArgumentOutOfRangeException ("maxGenerationThreshold", maxGenerationThreshold, "maxGenerationThreshold must be between 1 and 99 inclusive");
-                       if (largeObjectHeapThreshold < 1 || largeObjectHeapThreshold > 99)
-                               throw new ArgumentOutOfRangeException ("largeObjectHeapThreshold", largeObjectHeapThreshold, "largeObjectHeapThreshold must be between 1 and 99 inclusive");
-                       throw new NotImplementedException ();
-               }
-
-               [PermissionSetAttribute (SecurityAction.LinkDemand, Name = "FullTrust")]
-               public static void CancelFullGCNotification () {
-                       throw new NotImplementedException ();
-               }
-
-               [MethodImplAttribute (MethodImplOptions.InternalCall)]
-               internal extern static void register_ephemeron_array (Ephemeron[] array);
-
-               [MethodImplAttribute (MethodImplOptions.InternalCall)]
-               extern static object get_ephemeron_tombstone ();
-
-               internal static readonly object EPHEMERON_TOMBSTONE = get_ephemeron_tombstone ();
-       }
-}
diff --git a/mcs/class/corlib/System/GCCollectionMode.cs b/mcs/class/corlib/System/GCCollectionMode.cs
deleted file mode 100644 (file)
index 0134db6..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-//
-// System.GCCollectionMode.cs
-//
-
-//
-// Copyright (C) 2007 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.
-//
-
-// Net 3.5 type
-
-namespace System
-{
-       [Serializable]
-       public enum GCCollectionMode {
-               Default = 0,
-               Forced = 1,
-               Optimized = 2
-       }
-}
diff --git a/mcs/class/corlib/System/GCNotificationStatus.cs b/mcs/class/corlib/System/GCNotificationStatus.cs
deleted file mode 100644 (file)
index d48dab5..0000000
+++ /dev/null
@@ -1,40 +0,0 @@
-//
-// System.GCNotificationStatus.cs
-//
-// Authors:
-//   Gonzalo Paniagua (gonzalo@ximian.com)
-//
-// Copyright (C) 2009 Novell, Inc (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System.Collections.Generic;
-using System.Runtime.ConstrainedExecution;
-
-namespace System {
-       public enum GCNotificationStatus {
-               Succeeded,
-               Failed,
-               Canceled,
-               Timeout,
-               NotApplicable
-       }
-}
index ff6cc88a8096815dc51967017dd6bd835d5a894e..d849b03f8d66dbb4a2106a95baaa950e044ef286 100644 (file)
@@ -1556,22 +1556,52 @@ namespace System {
                                case 'O':                                         // logical
                                        int second = stack.Pop().Int32; // it's a stack... the second value was pushed last
                                        int first = stack.Pop().Int32;
-                                       char c = format[pos];
-                                       stack.Push(
-                                               c == '+' ? (first + second) :
-                                               c == '-' ? (first - second) :
-                                               c == '*' ? (first * second) :
-                                               c == '/' ? (first / second) :
-                                               c == 'm' ? (first % second) :
-                                               c == '^' ? (first ^ second) :
-                                               c == '&' ? (first & second) :
-                                               c == '|' ? (first | second) :
-                                               c == '=' ? AsInt(first == second) :
-                                               c == '>' ? AsInt(first > second) :
-                                               c == '<' ? AsInt(first < second) :
-                                               c == 'A' ? AsInt(AsBool(first) && AsBool(second)) :
-                                               c == 'O' ? AsInt(AsBool(first) || AsBool(second)) :
-                                               0); // not possible; we just validated above
+                                       int res;
+                                       switch (format[pos]) {
+                                       case '+':
+                                               res = first + second;
+                                               break;
+                                       case '-':
+                                               res = first - second;
+                                               break;
+                                       case '*':
+                                               res = first * second;
+                                               break;
+                                       case '/':
+                                               res = first / second;
+                                               break;
+                                       case 'm':
+                                               res = first % second;
+                                               break;
+                                       case '^':
+                                               res = first ^ second;
+                                               break;
+                                       case '&':
+                                               res = first & second;
+                                               break;
+                                       case '|':
+                                               res = first | second;
+                                               break;
+                                       case '=':
+                                               res = AsInt(first == second);
+                                               break;
+                                       case '>':
+                                               res = AsInt(first > second);
+                                               break;
+                                       case '<':
+                                               res = AsInt(first < second);
+                                               break;
+                                       case 'A':
+                                               res = AsInt(AsBool(first) && AsBool(second));
+                                               break;
+                                       case 'O':
+                                               res = AsInt(AsBool(first) || AsBool(second));
+                                               break;
+                                       default:
+                                               res = 0;
+                                               break;
+                                       }
+                                       stack.Push(res);
                                        break;
 
                                        // Unary operations
index 3cf08ae352089a434b6c8ac006bf6ab5e9c6e1a3..f233bec088e123de8984765477eac5827e41380f 100644 (file)
@@ -70,6 +70,18 @@ namespace System {
                {
                        return Append (new Text.StringBuilder ()).ToString ();
                }
+
+               public int Rank {
+                       get {
+                               return dimensions;
+                       }
+               }
+
+               public bool IsBound {
+                       get {
+                               return bound;
+                       }
+               }
        }
 
        internal class PointerSpec : ModifierSpec
index 73bfa734fa842390426dbbd1a8cc660c7bce12a7..b2a720650f5f748208d1780beb7f1f1280fb6667 100644 (file)
@@ -752,13 +752,18 @@ namespace MonoTests.System.Globalization
                [Test]
                public void FlowCultureInfoFromParentThreadSinceNet46 ()
                {
+                       if (SynchronizationContext.Current != null) {
+                               Assert.Ignore ();
+                               return;
+                       }
+
                        Func<Task> f = async () => {
                                Thread.CurrentThread.CurrentUICulture = new CultureInfo ("pt-BR");
                                await Task.Yield ();
                                Assert.AreEqual ("pt-BR", Thread.CurrentThread.CurrentUICulture.Name);
                        };
 
-                       f ().Wait ();
+                       Assert.IsTrue (f ().Wait (5 * 1000), "#1");
                }
        }
 }
index 7f381d63c86c36a38acf4145d9ea0d0956d1f2fd..7f5e1ee5000932c728fd8a48396d04bb37744518 100644 (file)
@@ -506,6 +506,8 @@ namespace MonoTests.System.Reflection.Emit
                }
 
                [Test]
+               // The token is not guaranteed to be 0x0a000001
+               [Category ("NotWorking")]
                public void ResolveFieldMemberRefWithGenericArguments ()
                {
                        var assembly = genAssembly ();
@@ -533,6 +535,8 @@ namespace MonoTests.System.Reflection.Emit
                }
 
                [Test]
+               // The token is not guaranteed to be 0x0a000002
+               [Category ("NotWorking")]
                public void ResolveMethodMemberRefWithGenericArguments ()
                {
                        var assembly = genAssembly ();
@@ -566,6 +570,8 @@ namespace MonoTests.System.Reflection.Emit
                }
 
                [Test]
+               // The token is not guaranteed to be 0x2b000001
+               [Category("NotWorking")]
                public void ResolveMethodSpecWithGenericArguments ()
                {
                        var assembly = genAssembly ();
@@ -794,5 +800,18 @@ namespace MonoTests.System.Reflection.Emit
                        // ArgumentNullException should not occur.
                        module.GetConstructorToken (method, null);
                }
+
+               [Test]
+               public void GetType ()
+               {
+                       AssemblyBuilder ab = genAssembly ();
+                       ModuleBuilder module = ab.DefineDynamicModule ("foo.dll", "foo.dll", true);
+                       TypeBuilder tb = module.DefineType ("t1", TypeAttributes.Public);
+
+                       Assert.AreEqual ("t1[]", module.GetType ("t1[]").FullName);
+                       Assert.AreEqual ("t1*", module.GetType ("t1*").FullName);
+                       Assert.AreEqual ("t1&", module.GetType ("t1&").FullName);
+                       Assert.AreEqual ("t1[]&", module.GetType ("t1[]&").FullName);
+               }
        }
 }
index d3115c76913f1792f567eb5069b74d9e4fa77897..ac3b1f149fa3d8e587cb8cf5a691fcc62eef46a5 100644 (file)
@@ -112,7 +112,7 @@ namespace MonoTests.System.Reflection.Emit
                                Thread.GetDomain ().DefineDynamicAssembly (
                                        assemblyName, AssemblyBuilderAccess.RunAndSave, Path.GetTempPath ());
 
-                       module = assembly.DefineDynamicModule ("module1");
+                       module = assembly.DefineDynamicModule (ASSEMBLY_NAME, ASSEMBLY_NAME + ".dll");
                }
 
                static int typeIndexer = 0;
@@ -1827,6 +1827,23 @@ namespace MonoTests.System.Reflection.Emit
                        // TODO:
                }
 
+               [Test]
+               public void NestedTypeSave () {
+                       var tb = module.DefineType (genTypeName ());
+
+                       var tbuilder = tb.DefineNestedType ("Test.CodeGen", TypeAttributes.Public | TypeAttributes.Class);
+                       var entryp = tbuilder.DefineMethod("Main", MethodAttributes.Public | MethodAttributes.Static, typeof (void), null);
+                       var ilg = entryp.GetILGenerator (128);
+                       ilg.Emit (OpCodes.Ldtoken, tb);
+                       ilg.Emit (OpCodes.Pop);
+                       ilg.Emit (OpCodes.Ret);
+
+                       tbuilder.CreateType ();
+                       tb.CreateType ();
+
+                       assembly.Save (ASSEMBLY_NAME + ".dll");
+               }
+
                [Test]
                public void DefinePInvokeMethod_Name_NullChar ()
                {
@@ -9094,6 +9111,8 @@ namespace MonoTests.System.Reflection.Emit
 
 
                [Test]
+               // Casts don't work with unfinished types
+               [Category ("NotWorking")]
                [Category ("NotDotNet")]
                public void IsAssignableFrom_NotCreated_Array ()
                {
@@ -9746,6 +9765,33 @@ namespace MonoTests.System.Reflection.Emit
                        //Console.WriteLine (res[0]);
                }
 
+               [Test]
+               public void FieldWithInitializedDataWorksWithCompilerRuntimeHelpers2 ()
+               {
+                       TypeBuilder tb = module.DefineType ("Type1", TypeAttributes.Public);
+                       var garg = tb.DefineGenericParameters ("T") [0];
+                       FieldBuilder fb = tb.DefineInitializedData ("Foo", new byte [] {1,2,3,4}, FieldAttributes.Static|FieldAttributes.Public);
+                       tb.CreateType ();
+
+                       assembly = Thread.GetDomain ().DefineDynamicAssembly (new AssemblyName (ASSEMBLY_NAME+"2"), AssemblyBuilderAccess.RunAndSave, Path.GetTempPath ());
+                       module = assembly.DefineDynamicModule ("Instance.exe");
+
+                       TypeBuilder tb2 = module.DefineType ("Type2", TypeAttributes.Public);
+                       MethodBuilder mb = tb2.DefineMethod ("Test", MethodAttributes.Public | MethodAttributes.Static, typeof (object), new Type [0]);
+                       ILGenerator il = mb.GetILGenerator ();
+
+                       il.Emit (OpCodes.Ldc_I4_1);
+                       il.Emit (OpCodes.Newarr, typeof (int));
+                       il.Emit (OpCodes.Dup);
+                       il.Emit (OpCodes.Ldtoken, fb);
+                       il.Emit (OpCodes.Call, typeof (RuntimeHelpers).GetMethod ("InitializeArray"));
+                       il.Emit (OpCodes.Ret);
+
+                       Type t = tb2.CreateType ();
+                       int[] res = (int[])t.GetMethod ("Test").Invoke (null, new object[0]);
+                       //Console.WriteLine (res[0]);
+               }
+
                public interface IDelegateFactory
                {
                        Delegate Create (Delegate del);
index 9234e9fc300cdbbb00d6ce0d774e4e8abcf08ab5..108680d10ad19f025c0b803d5cccceca134fac2c 100644 (file)
@@ -7,6 +7,7 @@
 
 using System;
 using System.Runtime.CompilerServices;
+using System.Threading;
 
 using NUnit.Framework;
 
@@ -45,6 +46,7 @@ namespace MonoTests.System.Runtime.CompilerServices {
                        }
                }
 
+               [Test]
                public void TestOffsetToStringData () 
                {
                        Assert.AreEqual (
@@ -52,6 +54,7 @@ namespace MonoTests.System.Runtime.CompilerServices {
                                                  RuntimeHelpers.OffsetToStringData, "OffsetToStringData is not constant");
                }
 
+               [Test]
                public void TestGetObjectValue ()
                {
                        FooStruct s1;
@@ -75,6 +78,7 @@ namespace MonoTests.System.Runtime.CompilerServices {
                        Assert.AreEqual (s2.j, "FOO");
                }
 
+               [Test]
                public void TestRunClassConstructor ()
                {
                        RuntimeHelpers.RunClassConstructor (typeof(FooClass).TypeHandle);
@@ -169,6 +173,7 @@ namespace MonoTests.System.Runtime.CompilerServices {
                        RuntimeHelpers.InitializeArray (new Fielder ().array, rfh);
                }
 
+               [Test]
                public void TestGetHashCode ()
                {
                        Assert.AreEqual (0, RuntimeHelpers.GetHashCode (null));
@@ -177,6 +182,7 @@ namespace MonoTests.System.Runtime.CompilerServices {
                        Assert.IsTrue (5 != RuntimeHelpers.GetHashCode (new FooClass ()));
                }                       
 
+               [Test]
                public void TestEquals ()
                {
                        Assert.IsTrue (RuntimeHelpers.Equals (null, null));
@@ -197,5 +203,21 @@ namespace MonoTests.System.Runtime.CompilerServices {
                        Assert.IsTrue (RuntimeHelpers.Equals (o1, o3));
                        Assert.IsTrue (!RuntimeHelpers.Equals (o1, o4));
                }
+
+               [Test]
+               public void TestEnsureSufficientExecutionStack ()
+               {
+                       var t = new Thread (() => {
+                               unsafe {
+                                       var s = stackalloc byte [1024];
+                               }
+
+                               RuntimeHelpers.EnsureSufficientExecutionStack ();
+                       });
+
+
+                       t.Start ();
+                       t.Join ();
+               }
        }
 }
index d609c188831a013943cb6c55945524a421bc1a12..dd66b8c7a2c2868e3b8b9441626c7e7c397f0f85 100644 (file)
@@ -903,7 +903,13 @@ namespace MonoTests.System
                        Assert.AreEqual (1, res.Length, "#1");
                }
 
-               abstract class Abs
+               abstract class Root
+               {
+                       [MyAttribute]
+                       public abstract void Foo ();
+               }
+
+               abstract class Abs : Root
                {
                        public abstract string Name { get; set; }
                }
@@ -915,6 +921,8 @@ namespace MonoTests.System
                                get { return ""; }
                                set {}
                        }
+
+                       public override void Foo () { }
                }
                
                class Sub: Base
@@ -1032,6 +1040,27 @@ namespace MonoTests.System
                        a.GetHashCode ();
                }
 
+
+               [Test]
+               public void DerivedClassOverrideHasInhertedAttributeFromAbstractRoot ()
+               {
+                       // regression test for #44010
+                       // we have
+                       // abstract class Root {
+                       //   [MyAttribute]
+                       //   public abstract void Foo ();
+                       // }
+                       // abstract class Abs : Root { }
+                       // class Base : Abs {
+                       //   public override void  Foo () { }
+                       // }
+                       // note that Abs does not itself override Foo.
+                       var bt = typeof(Base);
+                       var m = bt.GetMethod ("Foo");
+                       var attribute = Attribute.GetCustomAttribute (m, typeof (MyAttribute), true);
+                       Assert.IsNotNull (attribute);
+               }
+
                class ArrayAttribute : Attribute
                {
 #pragma warning disable 414
diff --git a/mcs/class/corlib/Test/System/GCTest.cs b/mcs/class/corlib/Test/System/GCTest.cs
new file mode 100644 (file)
index 0000000..6ce65b4
--- /dev/null
@@ -0,0 +1,72 @@
+//
+// GCTest.cs - NUnit Test Cases for GC
+//
+// Authors:
+//     Marek Safar  <marek.safar@gmail.com>
+//
+// Copyright (C) 2016 Xamarin Inc (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Threading.Tasks;
+
+using NUnit.Framework;
+
+namespace MonoTests.System {
+
+       [TestFixture]
+       public class GCTest {
+
+               class MyFinalizeObject
+               {
+                       public volatile static int finalized;
+
+                       ~MyFinalizeObject ()
+                       {
+                               if (finalized++ == 0) {
+                                       GC.ReRegisterForFinalize (this);
+                               }
+                       }
+               }
+
+               static void Run_ReRegisterForFinalizeTest ()
+               {
+                       var m = new WeakReference<MyFinalizeObject> (new MyFinalizeObject ());
+                       m.SetTarget (null);
+               }
+
+               [Test]
+               public void ReRegisterForFinalizeTest ()
+               {
+                       Run_ReRegisterForFinalizeTest ();
+                       var t = Task.Factory.StartNew (() => {
+                               do {
+                                       GC.Collect ();
+                                       GC.WaitForPendingFinalizers ();
+                                       Task.Yield ();
+                               } while (MyFinalizeObject.finalized != 2);
+                       });
+
+                       Assert.IsTrue (t.Wait (5000));
+               }
+       }
+}
\ No newline at end of file
index 1f408618bee270e7bb5c65ea1ace8861b925449e..d70e5fdde709fd20dcbcf54bf9fa7e338d5483bb 100644 (file)
@@ -3058,9 +3058,15 @@ namespace MonoTests.System
                public void MakeArrayTypeTest ()
                {
                        // This should not crash:
-                       typeof (void).MakeArrayType ();
+                       Type t = typeof (void).MakeArrayType ();
                }
                
+               [Test]
+               [ExpectedException (typeof (InvalidProgramException))]
+               public void MakeArrayTypedReferenceInstanceTest ()
+               {
+                       object o = Array.CreateInstance (typeof (global::System.TypedReference), 1);
+               }
 
                [ComVisible (true)]
                public class ComFoo<T> {
diff --git a/mcs/class/corlib/corefx/SR.cs b/mcs/class/corlib/corefx/SR.cs
new file mode 100644 (file)
index 0000000..7330ff6
--- /dev/null
@@ -0,0 +1,7 @@
+// TODO: Should be auto-generated from resources.resx
+
+static class SR
+{
+       public const string ArgumentException_ValueTupleIncorrectType = "The parameter should be a ValueTuple type of appropriate arity.";
+       public const string ArgumentException_ValueTupleLastArgumentNotAValueTuple = "The TRest type argument of ValueTuple`8 must be a ValueTuple.";
+}
\ No newline at end of file
index 95f0db7329cb36a446b037c41d2f4f6a1347bf06..80bce2dd720b884d1511d97509a096df15a917d6 100644 (file)
     <Compile Include="System.Reflection\MonoEvent.cs" />\r
     <Compile Include="System.Reflection\MonoField.cs" />\r
     <Compile Include="System.Reflection\MonoGenericClass.cs" />\r
-    <Compile Include="System.Reflection\MonoGenericMethod.cs" />\r
     <Compile Include="System.Reflection\MonoMethod.cs" />\r
     <Compile Include="System.Reflection\MonoModule.cs" />\r
     <Compile Include="System.Reflection\MonoParameterInfo.cs" />\r
index 9dbb35f5773c119b527b16c2cd6532f8cc1e866c..e2dfdbb5b8f46859d56b68790614970ea4a9149e 100644 (file)
@@ -105,9 +105,6 @@ System/DomainManagerInitializationFlags.cs
 System/EmptyArray.cs
 System/Environment.cs
 System/EnvironmentVariableTarget.cs
-System/GC.cs
-System/GCCollectionMode.cs
-System/GCNotificationStatus.cs
 System/Guid.cs
 System/IConsoleDriver.cs
 System/IntPtr.cs
@@ -180,7 +177,6 @@ System.Diagnostics.Tracing/EventFieldFormat.cs
 System.Diagnostics.Tracing/EventFieldTags.cs
 System.Diagnostics.Tracing/EventIgnoreAttribute.cs
 System.Diagnostics.Tracing/EventManifestOptions.cs
-System.Diagnostics.Tracing/EventSourceException.cs
 System.Diagnostics.SymbolStore/ISymbolBinder.cs
 System.Diagnostics.SymbolStore/ISymbolBinder1.cs
 System.Diagnostics.SymbolStore/ISymbolDocument.cs
@@ -249,8 +245,6 @@ System.Reflection/MethodBody.cs
 System.Reflection/Module.cs
 System.Reflection/ModuleResolveEventHandler.cs
 System.Reflection/MonoAssembly.cs
-System.Reflection/MonoGenericClass.cs
-System.Reflection/MonoGenericMethod.cs
 System.Reflection/MonoEvent.cs
 System.Reflection/MonoField.cs
 System.Reflection/MonoMethod.cs
@@ -262,15 +256,11 @@ System.Reflection/PortableExecutableKinds.cs
 System.Reflection/PropertyInfo.cs
 System.Reflection/ReflectionTypeLoadException.cs
 System.Reflection/StrongNameKeyPair.cs
-System.Reflection/TargetException.cs
-System.Reflection/TargetInvocationException.cs
-System.Reflection/TargetParameterCountException.cs
 System.Reflection.Emit/AssemblyBuilder.cs
 System.Reflection.Emit/AssemblyBuilderAccess.cs
 System.Reflection.Emit/ConstructorBuilder.cs
 System.Reflection.Emit/ConstructorOnTypeBuilderInst.cs
 System.Reflection.Emit/CustomAttributeBuilder.cs
-System.Reflection.Emit/CustomAttributeBuilder.pns.cs
 System.Reflection.Emit/DerivedTypes.cs
 System.Reflection.Emit/DynamicILInfo.cs
 System.Reflection.Emit/DynamicMethod.cs
@@ -284,7 +274,6 @@ System.Reflection.Emit/FieldToken.cs
 System.Reflection.Emit/FlowControl.cs
 System.Reflection.Emit/GenericTypeParameterBuilder.cs
 System.Reflection.Emit/ILGenerator.cs
-System.Reflection.Emit/ILGenerator.pns.cs
 System.Reflection.Emit/Label.cs
 System.Reflection.Emit/LocalBuilder.cs
 System.Reflection.Emit/MethodBuilder.cs
@@ -300,18 +289,17 @@ System.Reflection.Emit/OpCodeType.cs
 System.Reflection.Emit/OperandType.cs
 System.Reflection.Emit/PackingSize.cs
 System.Reflection.Emit/ParameterBuilder.cs
-System.Reflection.Emit/ParameterBuilder.pns.cs
 System.Reflection.Emit/ParameterToken.cs
 System.Reflection.Emit/PEFileKinds.cs
 System.Reflection.Emit/PropertyBuilder.cs
 System.Reflection.Emit/PropertyOnTypeBuilderInst.cs
 System.Reflection.Emit/PropertyToken.cs
 System.Reflection.Emit/SignatureHelper.cs
-System.Reflection.Emit/SignatureHelper.pns.cs
 System.Reflection.Emit/SignatureToken.cs
 System.Reflection.Emit/StackBehaviour.cs
 System.Reflection.Emit/StringToken.cs
 System.Reflection.Emit/TypeBuilder.cs
+System.Reflection.Emit/TypeBuilderInstantiation.cs
 System.Reflection.Emit/TypeToken.cs
 System.Reflection.Emit/UnmanagedMarshal.cs
 System.Reflection.Emit/AssemblyBuilder.pns.cs
@@ -911,7 +899,6 @@ ReferenceSources/MethodBase.cs
 ReferenceSources/NativeMethods.cs
 ReferenceSources/RuntimeHandles.cs
 ReferenceSources/CompareInfo.cs
-ReferenceSources/TypeBuilderInstantiation.cs
 ReferenceSources/Buffer.cs
 ReferenceSources/TextInfo.cs
 ReferenceSources/win32native.cs
@@ -919,6 +906,8 @@ ReferenceSources/SharedStatics.cs
 ReferenceSources/SecurityContext.cs
 ReferenceSources/PathInternal.cs
 ReferenceSources/BinaryCompatibility.cs
+ReferenceSources/String.cs
+ReferenceSources/Type.cs
 
 ../referencesource/mscorlib/system/__filters.cs
 ../referencesource/mscorlib/system/__hresults.cs
@@ -984,6 +973,7 @@ ReferenceSources/BinaryCompatibility.cs
 ../referencesource/mscorlib/system/flagsattribute.cs
 ../referencesource/mscorlib/system/formatexception.cs
 ../referencesource/mscorlib/system/FormattableString.cs
+../referencesource/mscorlib/system/gc.cs
 ../referencesource/mscorlib/system/guid.cs
 ../referencesource/mscorlib/system/iappdomain.cs
 ../referencesource/mscorlib/system/iappdomainsetup.cs
@@ -1144,6 +1134,7 @@ ReferenceSources/BinaryCompatibility.cs
 ../referencesource/mscorlib/system/diagnostics/contracts/contractsbcl.cs
 
 ../referencesource/mscorlib/system/diagnostics/eventing/eventactivityoptions.cs
+../referencesource/mscorlib/system/diagnostics/eventing/eventsourceexception.cs
 ../referencesource/mscorlib/system/diagnostics/eventing/winmeta.cs
 
 ../referencesource/mscorlib/system/diagnostics/eventing/TraceLogging/EventSourceOptions.cs
@@ -1261,6 +1252,9 @@ ReferenceSources/BinaryCompatibility.cs
 ../referencesource/mscorlib/system/reflection/reflectioncontext.cs
 ../referencesource/mscorlib/system/reflection/resourceattributes.cs
 ../referencesource/mscorlib/system/reflection/RuntimeReflectionExtensions.cs
+../referencesource/mscorlib/system/reflection/targetexception.cs
+../referencesource/mscorlib/system/reflection/targetinvocationexception.cs
+../referencesource/mscorlib/system/reflection/targetparametercountexception.cs
 ../referencesource/mscorlib/system/reflection/typeattributes.cs
 ../referencesource/mscorlib/system/reflection/typedelegator.cs
 ../referencesource/mscorlib/system/reflection/typefilter.cs
@@ -1381,6 +1375,7 @@ ReferenceSources/BinaryCompatibility.cs
 ../referencesource/mscorlib/system/runtime/compilerservices/FormattableStringFactory.cs
 ../referencesource/mscorlib/system/runtime/compilerservices/hascopysemanticsattribute.cs
 ../referencesource/mscorlib/system/runtime/compilerservices/IAsyncStateMachine.cs
+../referencesource/mscorlib/system/runtime/compilerservices/idispatchconstantattribute.cs
 ../referencesource/mscorlib/system/runtime/compilerservices/indexernameattribute.cs
 ../referencesource/mscorlib/system/runtime/compilerservices/INotifyCompletion.cs
 ../referencesource/mscorlib/system/runtime/compilerservices/internalsvisibletoattribute.cs
@@ -1647,5 +1642,10 @@ ReferenceSources/BinaryCompatibility.cs
 ../referencesource/mscorlib/microsoft/win32/safehandles/safewaithandle.cs
 ../referencesource/mscorlib/microsoft/win32/safehandles/win32safehandles.cs
 
-ReferenceSources/String.cs
-ReferenceSources/Type.cs
+corefx/SR.cs
+
+../../../external/corefx/src/Common/src/System/Numerics/Hashing/HashHelpers.cs
+
+../../../external/corefx/src/System.ValueTuple/src/System/ValueTuple/ValueTuple.cs
+../../../external/corefx/src/System.ValueTuple/src/System/ValueTuple/TupleExtensions.cs
+../../../external/corefx/src/System.ValueTuple/src/System/Runtime/CompilerServices/TupleElementNamesAttribute.cs
index bfa344cf598ae671dca5b6e25920aebe05be733e..bc43d92b9202a4dd44bdfb2a61ad24b4f04e4e2a 100644 (file)
@@ -22,6 +22,7 @@ System/CharCategoryTest.cs
 System/CharEnumeratorTest.cs
 System/CharTest.cs
 System/DelegateTest.cs
+System/GCTest.cs
 System/ModuleHandleTest.cs
 System/NullableTest.cs
 System/ObsoleteAttributeTest.cs
diff --git a/mcs/class/corlib/net_4_x_corlib.dll.sources b/mcs/class/corlib/net_4_x_corlib.dll.sources
deleted file mode 100644 (file)
index 2ea5c40..0000000
+++ /dev/null
@@ -1,2 +0,0 @@
-#include corlib.dll.sources
-../referencesource/mscorlib/system/runtime/compilerservices/idispatchconstantattribute.cs
index 329928fd80ca3f0ddcb6cb1fc9d799903b80b468..b87eecde4e0d3524529469383fca3cdb6e696a69 100644 (file)
@@ -48,6 +48,10 @@ namespace System.Runtime.CompilerServices {
         public static DebugInfoGenerator CreatePdbGenerator() {
             return new SymbolDocumentGenerator();
         }
+#else
+        public static DebugInfoGenerator CreatePdbGenerator() {
+            throw new PlatformNotSupportedException();
+        }
 #endif
         /// <summary>
         /// Marks a sequence point.
index a2e5ca0a4c157c1d6e97c17d340b90375fbbaef3..3489ee15514ca283e2c358fbbfa84cdeaf144b88 100644 (file)
@@ -29,7 +29,9 @@ namespace System.Linq.Expressions.Compiler {
         private const MethodAttributes CtorAttributes = MethodAttributes.RTSpecialName | MethodAttributes.HideBySig | MethodAttributes.Public;
         private const MethodImplAttributes ImplAttributes = MethodImplAttributes.Runtime | MethodImplAttributes.Managed;
         private const MethodAttributes InvokeAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual;
+#if FEATURE_REFEMIT
         private static readonly Type[] _DelegateCtorSignature = new Type[] { typeof(object), typeof(IntPtr) };
+#endif
 
         private static Type MakeNewCustomDelegate(Type[] types) {
 #if FEATURE_REFEMIT
index c2d07020d5896115448953dc25dcf7c133519f18..8dec8d4d72c2ee37bd13c0bf764bacb4f8de8118 100644 (file)
@@ -189,7 +189,9 @@ namespace System.Linq.Parallel
 
             private QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TLeftKey> m_leftSource; // Left data source.
             private QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TRightKey> m_rightSource; // Right data source.
+#if !MONO
             private readonly int m_partitionIndex; // The current partition.
+#endif
             private Set<TInputOutput> m_hashLookup; // The hash lookup, used to produce the union.
             private CancellationToken m_cancellationToken;
             private Shared<int> m_outputLoopCount;
@@ -210,7 +212,9 @@ namespace System.Linq.Parallel
 
                 m_leftSource = leftSource;
                 m_rightSource = rightSource;
+#if !MONO
                 m_partitionIndex = partitionIndex;
+#endif
                 m_comparer = comparer;
                 m_cancellationToken = cancellationToken;
             }
index 33baf3f8056e37c2b090c14ede08fa5fb4759382..08ae2840d333c766b2f91da8b331feeb1323f8f7 100644 (file)
@@ -23,8 +23,10 @@ namespace System.Linq.Parallel
     /// <typeparam name="TSource"></typeparam>
     internal sealed class OrderingQueryOperator<TSource> : QueryOperator<TSource>
     {
+#if !MONO
         // Turns on order (AsOrdered) or turns off order (AsUnordered)
         private bool m_orderOn;
+#endif
         private QueryOperator<TSource> m_child;
         private OrdinalIndexState m_ordinalIndexState;
 
@@ -33,7 +35,9 @@ namespace System.Linq.Parallel
         {
             m_child = child;
             m_ordinalIndexState = m_child.OrdinalIndexState;
+#if !MONO
             m_orderOn = orderOn;
+#endif
         }
 
         internal override QueryResults<TSource> Open(QuerySettings settings, bool preferStriping)
index d55436affb55dc0108c0df5b39eb618478784ce4..6f8c4a521f50cbfef3b9221022c8b7808fc710cd 100644 (file)
@@ -233,7 +233,9 @@ namespace System.Linq.Parallel
 
         class ConcatQueryOperatorResults : BinaryQueryOperatorResults
         {
+#if !MONO
             ConcatQueryOperator<TSource> m_concatOp; // Operator that generated the results
+#endif
             int m_leftChildCount; // The number of elements in the left child result set
             int m_rightChildCount; // The number of elements in the right child result set
 
@@ -260,7 +262,9 @@ namespace System.Linq.Parallel
                 bool preferStriping)
                 : base(leftChildQueryResults, rightChildQueryResults, concatOp, settings, preferStriping)
             {
+#if !MONO
                 m_concatOp = concatOp;
+#endif
                 Contract.Assert(leftChildQueryResults.IsIndexible && rightChildQueryResults.IsIndexible);
 
                 m_leftChildCount = leftChildQueryResults.ElementsCount;
index b73b8bd0829bd908ac8dfd0b5f6d3d59345d1804..02d220bce7815a333d8856b8580432f6272762cd 100644 (file)
@@ -150,7 +150,9 @@ namespace System.Linq.Parallel
         protected QueryResults<TInputOutput> m_childQueryResults; // Results of the child query
         private SortQueryOperator<TInputOutput, TSortKey> m_op; // Operator that generated these results
         private QuerySettings m_settings; // Settings collected from the query
+#if !MONO
         private bool m_preferStriping; // If the results are indexible, should we use striping when partitioning them
+#endif
 
         internal SortQueryOperatorResults(
             QueryResults<TInputOutput> childQueryResults, SortQueryOperator<TInputOutput, TSortKey> op,
@@ -159,7 +161,9 @@ namespace System.Linq.Parallel
             m_childQueryResults = childQueryResults;
             m_op = op;
             m_settings = settings;
+#if !MONO
             m_preferStriping = preferStriping;
+#endif
         }
 
         internal override bool IsIndexible
index f1e99baedb4ce522c751ad8098306333091d47c1..598d1e13aa3edbf10c8865de6a9a52dc678f1c76 100644 (file)
@@ -25,7 +25,9 @@ namespace System.Linq.Parallel
     class OrderPreservingPipeliningSpoolingTask<TOutput, TKey> : SpoolingTaskBase
     {
         private readonly QueryTaskGroupState m_taskGroupState; // State shared among tasks.
+#if !MONO
         private readonly TaskScheduler m_taskScheduler; // The task manager to execute the query.
+#endif
         private readonly QueryOperatorEnumerator<TOutput, TKey> m_partition; // The source partition.
         private readonly bool[] m_consumerWaiting; // Whether a consumer is waiting on a particular producer
         private readonly bool[] m_producerWaiting; // Whether a particular producer is waiting on the consumer
@@ -83,7 +85,9 @@ namespace System.Linq.Parallel
             m_partitionIndex = partitionIndex;
             m_buffers = buffers;
             m_bufferLock = bufferLock;
+#if !MONO
             m_taskScheduler = taskScheduler;
+#endif
             m_autoBuffered = autoBuffered;
         }
 
index fb355997295e4dd81c1b737c9e92cfe08bf2e2a2..5007e479c7408a2113cb2c72b317c21657e92d15 100644 (file)
@@ -70,11 +70,15 @@ namespace System.Linq.Parallel
             Contract.Assert(sharedkeys != null);
             Contract.Assert(sharedValues != null);
             Contract.Assert(sharedBarriers != null);
+#if !MONO
             Contract.Assert(groupState.CancellationState.MergedCancellationToken != null);
+#endif
             Contract.Assert(sharedIndices.Length <= sharedkeys.Length);
             Contract.Assert(sharedIndices.Length == sharedValues.Length);
             Contract.Assert(sharedIndices.Length == sharedBarriers.GetLength(1));
+#if !MONO            
             Contract.Assert(groupState.CancellationState.MergedCancellationToken != null);
+#endif
 
             m_source = source;
             m_partitionCount = partitionCount;
index c26925aae8d8822feed0d0973f7da72d685d745d..365a490d06d1eec87ccc94e0e0145bd367b23ca1 100644 (file)
@@ -101,7 +101,9 @@ namespace System.Linq {
         object IQueryProvider.Execute(Expression expression){
             if (expression == null)
                 throw Error.ArgumentNull("expression");
+#if !MONO
             Type execType = typeof(EnumerableExecutor<>).MakeGenericType(expression.Type);
+#endif
             return EnumerableExecutor.Create(expression).ExecuteBoxed();
         }
 
@@ -194,7 +196,9 @@ namespace System.Linq {
 
             // check for args changed
             if (obj != m.Object || args != m.Arguments) {
+#if !MONO
                 Expression[] argArray = args.ToArray();
+#endif
                 Type[] typeArgs = (m.Method.IsGenericMethod) ? m.Method.GetGenericArguments() : null;
 
                 if ((m.Method.IsStatic || m.Method.DeclaringType.IsAssignableFrom(obj.Type)) 
index d603b38fdcb1197ccaefe0df9449a6646e0e5779..a86c03ff01e8cfc78fb5c08150c498456faf873f 100644 (file)
@@ -40,6 +40,7 @@ namespace System.Data.Sql {
 
         override public DataTable GetDataSources() {
 #if MONO
+            timeoutTime = 0;
             throw new NotImplementedException ();
 #else
             (new NamedPermissionSet("FullTrust")).Demand(); // SQLBUDT 244304
index c36cb152e95807dc20cc19a6a001a1b7c2cc8802..bf5a3cb3e525bf43470435effd249ac53d7dc5e7 100644 (file)
@@ -67,7 +67,6 @@ namespace System.Runtime.Serialization
                         nodes[i].WriteTo(xmlWriter);
         }
 
-#if !MOBILE
         internal static string AddDefaultSchemaMethodName = "AddDefaultSchema";
         public static void AddDefaultSchema(XmlSchemaSet schemas, XmlQualifiedName typeQName)
         {
@@ -77,6 +76,5 @@ namespace System.Runtime.Serialization
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("typeQName");
             SchemaExporter.AddDefaultXmlType(schemas, typeQName.Name, typeQName.Namespace);
         }
-#endif
     }
 }
index 9feea179f30dba470524c8f8a4c5e69ea385fac5..d1b0ab5f9ebfd615bf7497c17a6fe2dc50c09f72 100644 (file)
@@ -31,7 +31,9 @@ namespace System.CodeDom {
         private CodeNamespaceImportCollection imports = new CodeNamespaceImportCollection();
         private CodeCommentStatementCollection comments = new CodeCommentStatementCollection();
         private CodeTypeDeclarationCollection classes = new CodeTypeDeclarationCollection();
+#if CODEDOM_NESTED_NAMESPACES
         private CodeNamespaceCollection namespaces = new CodeNamespaceCollection();
+#endif
         
         private int  populated = 0x0;
         private const int ImportsCollection = 0x1;
index 28d511744cc529a7ce58dcd005affdd709863c8f..38ccf72ec0efd622c8ddb04f9d6f9bf6d7dae25a 100644 (file)
@@ -27,7 +27,9 @@ namespace System.CodeDom {
     public class CodePropertyReferenceExpression : CodeExpression {
         private CodeExpression targetObject;
         private string propertyName;
+#if !MONO
         private CodeExpressionCollection parameters = new CodeExpressionCollection();
+#endif
 
         /// <devdoc>
         ///    <para>
index 96ec1aa520a7c723dec25a3cfec0622a4fe1ca0d..82bfe6c56ae9d6e0857deca6701a76f49326824f 100644 (file)
@@ -98,11 +98,15 @@ namespace System.ComponentModel {
         }
 
         private class LicFileLicense : License {
+#if !MONO
             private LicFileLicenseProvider owner;
+#endif
             private string key;
 
             public LicFileLicense(LicFileLicenseProvider owner, string key) {
+#if !MONO
                 this.owner = owner;
+#endif
                 this.key = key;
             }
             public override string LicenseKey { 
index cfdaabbfc31b6a1cebc722cc91676164afa19480..ce8d0cd7dfdb4d866312365a2dad2c2f79c20bc8 100644 (file)
@@ -67,9 +67,10 @@ namespace System.ComponentModel {
     /// </devdoc>
     [HostProtection(SharedState = true)]
     internal sealed class ReflectEventDescriptor : EventDescriptor {
-
+#if !MONO
         private static readonly Type[] argsNone = new Type[0];
         private static readonly object  noDefault = new object();
+#endif
 
         private Type type;           // the delegate type for the event
         private readonly Type componentClass; // the class of the component this info is for
index 401c21e4d6697f3c41556dd58df794435d5c3d73..94424b88b02e177303499237b0c0f28e7a7894e7 100644 (file)
@@ -64,7 +64,9 @@ namespace System.ComponentModel {
         
         private static TraceSwitch PropDescCreateSwitch = new TraceSwitch("PropDescCreate", "ReflectPropertyDescriptor: Dump errors when creating property info");
         private static TraceSwitch PropDescUsageSwitch  = new TraceSwitch("PropDescUsage", "ReflectPropertyDescriptor: Debug propertydescriptor usage");
+#if !MONO
         private static TraceSwitch PropDescSwitch       = new TraceSwitch("PropDesc", "ReflectPropertyDescriptor: Debug property descriptor");
+#endif
         
         private static readonly int BitDefaultValueQueried      = BitVector32.CreateMask();
         private static readonly int BitGetQueried               = BitVector32.CreateMask(BitDefaultValueQueried);
index 246b3aee430291b32e13ec4c5882d268e17ce5b4..3bcd73437916cca6106e50c327e3fb4d4b83005a 100644 (file)
@@ -28,8 +28,10 @@ namespace System.ComponentModel {
 
         private const string s_UseCompatibleTypeConverterBehavior = "UseCompatibleTypeConverterBehavior";
         private static volatile bool useCompatibleTypeConversion = false;
+#if !MONO
         private static volatile bool firstLoadAppSetting = true;
         private static object loadAppSettingLock = new Object();
+#endif
 
         private static bool UseCompatibleTypeConversion {
             get {
index 1d92faa541f6a2d6c5a5700a11dc0113895d3e89..26248db1547dde54dbe4420740baf3ef93cbee90 100644 (file)
@@ -4,6 +4,10 @@
 // </copyright>
 //------------------------------------------------------------------------------
 
+#if MONO
+#undef FEATURE_PAL
+#endif
+
 namespace System.Net.Sockets {
     using System.Collections;
     using System.Collections.Generic;
@@ -24,9 +28,9 @@ namespace System.Net.Sockets {
     ///    interface.</para>
     /// </devdoc>
 
-
-    public class Socket : IDisposable
+    public partial class Socket : IDisposable
     {
+#if !MONO
         internal const int DefaultCloseTimeout = -1; // don't change for default, otherwise breaking change
 
         // AcceptQueue - queued list of accept requests for BeginAccept or async Result for Begin Connect
@@ -81,12 +85,12 @@ namespace System.Net.Sockets {
         //
         // Overlapped constants.
         //
-#if !FEATURE_PAL || CORIOLIS
+#if !(FEATURE_PAL && !MONO) || CORIOLIS
         internal static volatile bool UseOverlappedIO;
 #else
         // Disable the I/O completion port for Rotor
         internal static volatile bool UseOverlappedIO = true;
-#endif // !FEATURE_PAL || CORIOLIS
+#endif // !(FEATURE_PAL && !MONO) || CORIOLIS
         private bool useOverlappedIO;
 
         // Bool marked true if the native socket m_Handle was bound to the ThreadPool
@@ -104,12 +108,15 @@ namespace System.Net.Sockets {
         private SocketAddress   m_PermittedRemoteAddress;
 
         private DynamicWinsockMethods m_DynamicWinsockMethods;
+#endif // !MONO
 
         private static object s_InternalSyncObject;
+#if !MONO
         private int m_CloseTimeout = Socket.DefaultCloseTimeout;
         private int m_IntCleanedUp;                 // 0 if not completed >0 otherwise.
         private const int microcnv = 1000000;
         private readonly static int protocolInformationSize = Marshal.SizeOf(typeof(UnsafeNclNativeMethods.OSSOCK.WSAPROTOCOL_INFO));
+#endif // !MONO
 
         internal static volatile bool s_SupportsIPv4;
         internal static volatile bool s_SupportsIPv6;
@@ -140,10 +147,16 @@ namespace System.Net.Sockets {
             s_LoggingEnabled = Logging.On;
             if(s_LoggingEnabled)Logging.Enter(Logging.Sockets, this, "Socket", addressFamily);
             InitializeSockets();
+
+#if MONO
+            int error;
+            m_Handle = new SafeSocketHandle (Socket_internal (addressFamily, socketType, protocolType, out error), true);
+#else
             m_Handle = SafeCloseSocket.CreateWSASocket(
                     addressFamily,
                     socketType,
                     protocolType);
+#endif
 
             if (m_Handle.IsInvalid) {
                 //
@@ -161,10 +174,14 @@ namespace System.Net.Sockets {
                 SetIPProtectionLevel(defaultProtectionLevel);
             }
 
+#if MONO
+            SocketDefaults ();
+#endif
+
             if(s_LoggingEnabled)Logging.Exit(Logging.Sockets, this, "Socket", null);
         }
 
-
+#if !MONO
         public Socket(SocketInformation socketInformation) {
             s_LoggingEnabled = Logging.On;
             if(s_LoggingEnabled)Logging.Enter(Logging.Sockets, this, "Socket", addressFamily);
@@ -282,7 +299,7 @@ namespace System.Net.Sockets {
             protocolType = Sockets.ProtocolType.Unknown;
             if(s_LoggingEnabled)Logging.Exit(Logging.Sockets, this, "Socket", null);
         }
-
+#endif
 
 
 //************* properties *************************
@@ -333,7 +350,7 @@ namespace System.Net.Sockets {
             }
         }
 
-
+#if !MONO
         /// <devdoc>
         ///    <para>
         ///       Gets the amount of data pending in the network's input buffer that can be
@@ -475,6 +492,7 @@ namespace System.Net.Sockets {
                 return m_RemoteEndPoint;
             }
         }
+#endif // !MONO
 
         /// <devdoc>
         ///    <para>
@@ -484,10 +502,13 @@ namespace System.Net.Sockets {
         /// </devdoc>
         public IntPtr Handle {
             get {
+#if !MONO
                 ExceptionHelper.UnmanagedPermission.Demand();
+#endif
                 return m_Handle.DangerousGetHandle();
             }
         }
+#if !MONO
         internal SafeCloseSocket SafeHandle {
             get {
                 return m_Handle;
@@ -534,6 +555,7 @@ namespace System.Net.Sockets {
                 willBlock = current;
             }
         }
+#endif // !MONO
 
         public bool UseOnlyOverlappedIO{
             get {
@@ -544,16 +566,17 @@ namespace System.Net.Sockets {
 
             }
             set {
-
+#if !MONO
                 if (m_BoundToThreadPool) {
                     throw new InvalidOperationException(SR.GetString(SR.net_io_completionportwasbound));
                 }
+#endif
 
                 useOverlappedIO = value;
             }
         }
 
-
+#if !MONO
         /// <devdoc>
         ///    <para>
         ///       Gets the connection state of the Socket. This property will return the latest
@@ -577,6 +600,7 @@ namespace System.Net.Sockets {
                 return m_IsConnected;
             }
         }
+#endif // !MONO
 
         /// <devdoc>
         ///    <para>
@@ -611,13 +635,13 @@ namespace System.Net.Sockets {
             }
         }
 
-
+#if !MONO
         public bool IsBound{
             get{
                 return (m_RightEndPoint != null);
             }
         }
-
+#endif // !MONO
 
         public bool ExclusiveAddressUse{
             get {
@@ -707,6 +731,7 @@ namespace System.Net.Sockets {
             }
         }
 
+#if !MONO
         public bool NoDelay {
             get {
                 return (int)GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay) != 0 ? true : false;
@@ -715,6 +740,7 @@ namespace System.Net.Sockets {
                 SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, value ? 1 : 0);
             }
         }
+#endif // !MONO
 
         public short Ttl{
             get {
@@ -769,6 +795,7 @@ namespace System.Net.Sockets {
             }
         }
 
+#if !MONO
         public bool MulticastLoopback{
             get {
                 if (addressFamily == AddressFamily.InterNetwork) {
@@ -796,7 +823,6 @@ namespace System.Net.Sockets {
             }
         }
 
-
         public bool EnableBroadcast{
             get {
                 return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast) != 0 ? true : false;
@@ -805,7 +831,8 @@ namespace System.Net.Sockets {
                 SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, value ? 1 : 0);
             }
         }
-                
+#endif // !MONO
+
         public bool DualMode {
             get {
                 if (AddressFamily != AddressFamily.InterNetworkV6) {
@@ -837,7 +864,7 @@ namespace System.Net.Sockets {
 
 
 
-
+#if !MONO
         /// <devdoc>
         ///    <para>Associates a socket with an end point.</para>
         /// </devdoc>
@@ -1258,7 +1285,7 @@ namespace System.Net.Sockets {
             }
             return socket;
         }
-
+#endif // !MONO
 
         /// <devdoc>
         ///    <para>Sends a data buffer to a connected socket.</para>
@@ -1300,7 +1327,7 @@ namespace System.Net.Sockets {
             return bytesTransferred;
         }
 
-
+#if !MONO
         public int Send(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode) {
             if(s_LoggingEnabled)Logging.Enter(Logging.Sockets, this, "Send", "");
             if (CleanedUp) {
@@ -1392,8 +1419,7 @@ namespace System.Net.Sockets {
             if(s_LoggingEnabled)Logging.Exit(Logging.Sockets, this, "Send", bytesTransferred);
             return bytesTransferred;
         }
-
-
+#endif // !MONO
 
         /// <devdoc>
         ///    <para>Sends a file to
@@ -1406,8 +1432,7 @@ namespace System.Net.Sockets {
             SendFile(fileName,null,null,TransmitFileOptions.UseDefaultWorkerThread);
         }
 
-
-
+#if !MONO
         /// <devdoc>
         ///    <para>Sends a file to
         ///       a connected socket.</para>
@@ -1492,6 +1517,7 @@ namespace System.Net.Sockets {
             if(s_LoggingEnabled)Logging.Exit(Logging.Sockets, this, "SendFile", errorCode);
             return;
         }
+#endif // !MONO
 #endif // !FEATURE_PAL
 
 
@@ -1511,8 +1537,7 @@ namespace System.Net.Sockets {
             return bytesTransferred;
         }
 
-
-
+#if !MONO
         public int Send(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode) {
             if(s_LoggingEnabled)Logging.Enter(Logging.Sockets, this, "Send", "");
 
@@ -1688,6 +1713,7 @@ namespace System.Net.Sockets {
             if(s_LoggingEnabled)Logging.Exit(Logging.Sockets, this, "SendTo", bytesTransferred);
             return bytesTransferred;
         }
+#endif // !MONO
 
         /// <devdoc>
         ///    <para>Sends data to a specific end point, starting at the indicated location in the data.</para>
@@ -1695,12 +1721,14 @@ namespace System.Net.Sockets {
         public int SendTo(byte[] buffer, int size, SocketFlags socketFlags, EndPoint remoteEP) {
             return SendTo(buffer, 0, size, socketFlags, remoteEP);
         }
+
         /// <devdoc>
         ///    <para>[To be supplied.]</para>
         /// </devdoc>
         public int SendTo(byte[] buffer, SocketFlags socketFlags, EndPoint remoteEP) {
             return SendTo(buffer, 0, buffer!=null ? buffer.Length : 0, socketFlags, remoteEP);
         }
+
         /// <devdoc>
         ///    <para>[To be supplied.]</para>
         /// </devdoc>
@@ -1742,7 +1770,7 @@ namespace System.Net.Sockets {
             return bytesTransferred;
         }
 
-
+#if !MONO
         public int Receive(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode) {
             if(s_LoggingEnabled)Logging.Enter(Logging.Sockets, this, "Receive", "");
             if (CleanedUp) {
@@ -1820,7 +1848,7 @@ namespace System.Net.Sockets {
 
             return bytesTransferred;
         }
-
+#endif // !MONO
 
         public int Receive(IList<ArraySegment<byte>> buffers) {
             return Receive(buffers,SocketFlags.None);
@@ -1836,6 +1864,7 @@ namespace System.Net.Sockets {
             return bytesTransferred;
         }
 
+#if !MONO
         public int Receive(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode) {
             if(s_LoggingEnabled)Logging.Enter(Logging.Sockets, this, "Receive", "");
             if (CleanedUp) {
@@ -2153,8 +2182,7 @@ namespace System.Net.Sockets {
             if(s_LoggingEnabled)Logging.Exit(Logging.Sockets, this, "ReceiveFrom", bytesTransferred);
             return bytesTransferred;
         }
-
-
+#endif // !MONO
 
         /// <devdoc>
         ///    <para>Receives a datagram and stores the source end point.</para>
@@ -2175,6 +2203,7 @@ namespace System.Net.Sockets {
             return ReceiveFrom(buffer, 0, buffer!=null ? buffer.Length : 0, SocketFlags.None, ref remoteEP);
         }
 
+#if !MONO
         // UE
         /// <devdoc>
         ///    <para>[To be supplied.]</para>
@@ -2220,6 +2249,7 @@ namespace System.Net.Sockets {
 
             return realOptionLength;
         }
+#endif // !MONO
 
         // UE
         /// <devdoc>
@@ -2229,6 +2259,7 @@ namespace System.Net.Sockets {
             return IOControl(unchecked((int)ioControlCode),optionInValue,optionOutValue);
         }
 
+#if !MONO
         internal int IOControl(        IOControlCode ioControlCode, 
                                                                        IntPtr optionInValue, 
                                                                        int inValueSize,
@@ -2273,6 +2304,7 @@ namespace System.Net.Sockets {
 
             return realOptionLength;
         }
+#endif // !MONO
 
         public void SetIPProtectionLevel(IPProtectionLevel level) {
             if (level == IPProtectionLevel.Unspecified) {
@@ -2290,6 +2322,7 @@ namespace System.Net.Sockets {
             }
         }
 
+#if !MONO
         /// <devdoc>
         ///    <para>
         ///       Sets the specified option to the specified value.
@@ -2660,6 +2693,7 @@ namespace System.Net.Sockets {
             SelectFileDescriptor(checkWrite, writefileDescriptorSet);
             SelectFileDescriptor(checkError, errfileDescriptorSet);
         }
+#endif // !MONO
 
 #if !FEATURE_PAL
         /// <devdoc>
@@ -2678,7 +2712,7 @@ namespace System.Net.Sockets {
         }
 #endif
 
-
+#if !MONO
         //
         // Async Winsock Support, the following functions use either
         //   the Async Winsock support to do overlapped I/O WSASend/WSARecv
@@ -3100,6 +3134,7 @@ namespace System.Net.Sockets {
             if(s_LoggingEnabled)Logging.Exit(Logging.Sockets, this, "BeginConnect", result);
             return result;
         }
+#endif // !MONO
 
         [HostProtection(ExternalThreading=true)]
         public IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback requestCallback, object state){
@@ -3124,6 +3159,7 @@ namespace System.Net.Sockets {
             return result;
         }
 
+#if !MONO
         [HostProtection(ExternalThreading=true)]
         public IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback requestCallback, object state)
         {
@@ -3193,7 +3229,7 @@ namespace System.Net.Sockets {
 
             GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::DoBeginDisconnect() ");
 
-#if FEATURE_PAL
+#if FEATURE_PAL && !MONO
             throw new PlatformNotSupportedException(SR.GetString(SR.WinXPRequired));
 #endif
 
@@ -3242,9 +3278,9 @@ namespace System.Net.Sockets {
                  throw new ObjectDisposedException(this.GetType().FullName);
              }
 
-#if FEATURE_PAL
+#if FEATURE_PAL && !MONO
             throw new PlatformNotSupportedException(SR.GetString(SR.WinXPRequired));
-#endif // FEATURE_PAL
+#endif // FEATURE_PAL && !MONO
 
 
              GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::Disconnect() ");
@@ -3370,9 +3406,9 @@ namespace System.Net.Sockets {
                throw new ObjectDisposedException(this.GetType().FullName);
              }
 
-#if FEATURE_PAL
+#if FEATURE_PAL && !MONO
             throw new PlatformNotSupportedException(SR.GetString(SR.WinNTRequired));
-#endif // FEATURE_PAL
+#endif // FEATURE_PAL && !MONO
 
              if (asyncResult==null) {
                throw new ArgumentNullException("asyncResult");
@@ -3412,7 +3448,7 @@ namespace System.Net.Sockets {
              if(s_LoggingEnabled)Logging.Exit(Logging.Sockets, this, "EndDisconnect", null);
              return;
         }
-
+#endif // !MONO
 
         /*++
 
@@ -3451,6 +3487,7 @@ namespace System.Net.Sockets {
             return result;
         }
 
+#if !MONO
         [HostProtection(ExternalThreading=true)]
         public IAsyncResult BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
         {
@@ -3620,9 +3657,9 @@ namespace System.Net.Sockets {
                 throw new ObjectDisposedException(this.GetType().FullName);
             }
 
-#if FEATURE_PAL
+#if FEATURE_PAL && !MONO
             throw new PlatformNotSupportedException(SR.GetString(SR.WinNTRequired));
-#endif // FEATURE_PAL
+#endif // FEATURE_PAL && !MONO
 
 
             if (!Connected) {
@@ -3698,7 +3735,7 @@ namespace System.Net.Sockets {
         }
 
 #endif // !FEATURE_PAL
-
+#endif // !MONO
 
         /// <devdoc>
         ///    <para>[To be supplied.]</para>
@@ -3714,7 +3751,7 @@ namespace System.Net.Sockets {
             return result;
         }
 
-
+#if !MONO
         [HostProtection(ExternalThreading=true)]
         public IAsyncResult BeginSend(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
         {
@@ -3804,7 +3841,7 @@ namespace System.Net.Sockets {
             }
             return errorCode;
         }
-
+#endif // !MONO
 
         /*++
 
@@ -3836,7 +3873,7 @@ namespace System.Net.Sockets {
             return bytesTransferred;
         }
 
-
+#if !MONO
         public int EndSend(IAsyncResult asyncResult, out SocketError errorCode) {
             if(s_LoggingEnabled)Logging.Enter(Logging.Sockets, this, "EndSend", asyncResult);
             if (CleanedUp) {
@@ -3904,9 +3941,9 @@ namespace System.Net.Sockets {
                 throw new ObjectDisposedException(this.GetType().FullName);
             }
 
-#if FEATURE_PAL
+#if FEATURE_PAL && !MONO
             throw new PlatformNotSupportedException(SR.GetString(SR.WinNTRequired));
-#endif // FEATURE_PAL
+#endif // FEATURE_PAL && !MONO
             //
             // parameter validation
             //
@@ -4160,7 +4197,7 @@ namespace System.Net.Sockets {
             if(s_LoggingEnabled)Logging.Exit(Logging.Sockets, this, "EndSendTo", bytesTransferred);
             return bytesTransferred;
         }
-
+#endif // !MONO
 
         /*++
 
@@ -4206,6 +4243,7 @@ namespace System.Net.Sockets {
         }
 
 
+#if !MONO
         [HostProtection(ExternalThreading=true)]
         public IAsyncResult BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
         {
@@ -4329,7 +4367,7 @@ namespace System.Net.Sockets {
 
             return errorCode;
         }
-
+#endif // !MONO
 
         [HostProtection(ExternalThreading=true)]
         public IAsyncResult BeginReceive(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, AsyncCallback callback, object state)
@@ -4342,7 +4380,7 @@ namespace System.Net.Sockets {
             return result;
         }
 
-
+#if !MONO
         [HostProtection(ExternalThreading=true)]
         public IAsyncResult BeginReceive(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
         {
@@ -4451,6 +4489,8 @@ namespace System.Net.Sockets {
         private int m_LastReceiveTick;
 #endif
 
+#endif // !MONO
+
         /*++
 
         Routine Description:
@@ -4481,7 +4521,7 @@ namespace System.Net.Sockets {
             return bytesTransferred;
         }
 
-
+#if !MONO
         public int EndReceive(IAsyncResult asyncResult, out SocketError errorCode) {
             if(s_LoggingEnabled)Logging.Enter(Logging.Sockets, this, "EndReceive", asyncResult);
             if (CleanedUp) {
@@ -5342,8 +5382,10 @@ namespace System.Net.Sockets {
                 }
             }
         }
+#endif // !MONO
 
 #if !FEATURE_PAL
+#if !MONO
         private bool CanUseAcceptEx
         {
             get
@@ -5352,6 +5394,7 @@ namespace System.Net.Sockets {
                     (Thread.CurrentThread.IsThreadPoolThread || SettingsSectionInternal.Section.AlwaysUseCompletionPortsForAccept || m_IsDisconnected);
             }
         }
+#endif // !MONO
 
         /// <devdoc>
         ///    <para>[To be supplied.]</para>
@@ -5363,6 +5406,7 @@ namespace System.Net.Sockets {
 
         ///  This is the true async version that uses AcceptEx
 
+#if !MONO
         /// <devdoc>
         ///    <para>[To be supplied.]</para>
         /// </devdoc>
@@ -5461,10 +5505,9 @@ namespace System.Net.Sockets {
                 throw socketException;
             }
         }
-
+#endif // !MONO
 #endif // !FEATURE_PAL
 
-
         /*++
 
         Routine Description:
@@ -5483,6 +5526,7 @@ namespace System.Net.Sockets {
 
         --*/
 
+#if !MONO
         /// <devdoc>
         ///    <para>[To be supplied.]</para>
         /// </devdoc>
@@ -5552,9 +5596,9 @@ namespace System.Net.Sockets {
             }
             return acceptedSocket;
         }
+#endif // !MONO
 
 #if !FEATURE_PAL
-
         /// <devdoc>
         ///    <para>[To be supplied.]</para>
         /// </devdoc>
@@ -5569,6 +5613,7 @@ namespace System.Net.Sockets {
             return socket;
         }
 
+#if !MONO
         /// <devdoc>
         ///    <para>[To be supplied.]</para>
         /// </devdoc>
@@ -5635,13 +5680,13 @@ namespace System.Net.Sockets {
             }
             return socket;
         }
-
+#endif // !MONO
 #endif // !FEATURE_PAL
 
 
 
 
-
+#if !MONO
         /// <devdoc>
         ///    <para>
         ///       Disables sends and receives on a socket.
@@ -5682,7 +5727,7 @@ namespace System.Net.Sockets {
             InternalSetBlocking(willBlockInternal);
             if(s_LoggingEnabled)Logging.Exit(Logging.Sockets, this, "Shutdown", "");
         }
-
+#endif
 
 
 //************* internal and private properties *************************
@@ -5697,6 +5742,7 @@ namespace System.Net.Sockets {
             }
         }
 
+#if !MONO
         private CacheSet Caches
         {
             get
@@ -5821,6 +5867,7 @@ namespace System.Net.Sockets {
                 Interlocked.CompareExchange(ref m_AcceptQueueOrConnectResult, new Queue(16), null);
             return (Queue)m_AcceptQueueOrConnectResult;
         }
+#endif // !MONO
 
         internal bool CleanedUp {
             get {
@@ -5828,6 +5875,7 @@ namespace System.Net.Sockets {
             }
         }
 
+#if !MONO
         internal TransportType Transport {
             get {
                 return
@@ -5968,13 +6016,14 @@ namespace System.Net.Sockets {
 
             return socketAddress;
         }
-
+#endif
 
         internal static void InitializeSockets() {
             if (!s_Initialized) {
                 lock(InternalSyncObject){
                     if (!s_Initialized) {
 
+#if !MONO
                         WSAData wsaData = new WSAData();
 
                         SocketError errorCode =
@@ -5989,6 +6038,7 @@ namespace System.Net.Sockets {
                             // WSAStartup does not set LastWin32Error
                             throw new SocketException(errorCode);
                         }
+#endif
 
 #if !FEATURE_PAL
                         //
@@ -6009,6 +6059,10 @@ namespace System.Net.Sockets {
                         bool   ipv4      = true; 
                         bool   ipv6      = true; 
 
+#if MONO
+                        ipv4 = IsProtocolSupported (System.Net.NetworkInformation.NetworkInterfaceComponent.IPv4);
+                        ipv6 = IsProtocolSupported (System.Net.NetworkInformation.NetworkInterfaceComponent.IPv6);
+#else
                         SafeCloseSocket.InnerSafeCloseSocket socketV4 = 
                                                              UnsafeNclNativeMethods.OSSOCK.WSASocket(
                                                                     AddressFamily.InterNetwork, 
@@ -6042,7 +6096,7 @@ namespace System.Net.Sockets {
                         socketV6.Close();
 
                         // <
-
+#endif // MONO
 
 
 #if COMNET_DISABLEIPV6
@@ -6076,16 +6130,19 @@ namespace System.Net.Sockets {
 
                         // Cache some settings locally.
 
+#if !MONO
 #if !FEATURE_PAL // perfcounter
                         s_PerfCountersEnabled = NetworkingPerfCounters.Instance.Enabled;
 #endif
+#endif
+
                         s_Initialized = true;
                     }
                 }
             }
         }
 
-
+#if !MONO
         internal void InternalConnect(EndPoint remoteEP)
         {
             EndPoint endPointSnapshot = remoteEP;
@@ -6330,6 +6387,7 @@ namespace System.Net.Sockets {
                 m_AsyncEvent.Close();
             }
         }
+#endif // !MONO
 
         public void Dispose() {
             Dispose(true);
@@ -6340,6 +6398,7 @@ namespace System.Net.Sockets {
             Dispose(false);
         }
 
+#if !MONO
         // this version does not throw.
         internal void InternalShutdown(SocketShutdown how) {
             GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::InternalShutdown() how:" + how.ToString());
@@ -8350,10 +8409,10 @@ namespace System.Net.Sockets {
 
             return retval;
         }
-
+#endif // !MONO
     }  // end of class Socket
 
-
+#if !MONO
     internal class ConnectAsyncResult:ContextAwareResult{
         private EndPoint m_EndPoint;
         internal ConnectAsyncResult(object myObject, EndPoint endPoint, object myState, AsyncCallback myCallBack):base(myObject, myState, myCallBack) {
@@ -8368,7 +8427,7 @@ namespace System.Net.Sockets {
         internal AcceptAsyncResult(object myObject, object myState, AsyncCallback myCallBack):base(myObject, myState, myCallBack) {
         }
     }
-
+#endif
 
     public enum SocketAsyncOperation {
         None = 0,
@@ -8389,7 +8448,11 @@ namespace System.Net.Sockets {
         internal byte [] m_Buffer;
         internal int m_Offset;
         internal int m_Count;
+#if MONO
+        bool m_endOfPacket;
+#else
         internal UnsafeNclNativeMethods.OSSOCK.TransmitPacketsElementFlags m_Flags;
+#endif
 
         // hide default constructor
         private SendPacketsElement() {}
@@ -8415,8 +8478,13 @@ namespace System.Net.Sockets {
             }
             Contract.EndContractBlock();
 
+#if MONO
+            Initialize(filepath, null, offset, count, /*UnsafeNclNativeMethods.OSSOCK.TransmitPacketsElementFlags.File,*/
+                endOfPacket);
+#else
             Initialize(filepath, null, offset, count, UnsafeNclNativeMethods.OSSOCK.TransmitPacketsElementFlags.File,
                 endOfPacket);
+#endif
         }
 
         // constructors for buffer elements
@@ -8438,21 +8506,30 @@ namespace System.Net.Sockets {
             }
             Contract.EndContractBlock();
 
+#if MONO
+            Initialize(null, buffer, offset, count, /*UnsafeNclNativeMethods.OSSOCK.TransmitPacketsElementFlags.Memory,*/
+                endOfPacket);
+#else
             Initialize(null, buffer, offset, count, UnsafeNclNativeMethods.OSSOCK.TransmitPacketsElementFlags.Memory, 
                 endOfPacket);
+#endif
         }
 
         private void Initialize(string filePath, byte[] buffer, int offset, int count, 
-            UnsafeNclNativeMethods.OSSOCK.TransmitPacketsElementFlags flags, bool endOfPacket) {
+            /*UnsafeNclNativeMethods.OSSOCK.TransmitPacketsElementFlags flags,*/ bool endOfPacket) {
 
             m_FilePath = filePath;
             m_Buffer = buffer;
             m_Offset = offset;
             m_Count = count;
+#if MONO
+            m_endOfPacket = endOfPacket;
+#else
             m_Flags = flags;
             if (endOfPacket) {
                 m_Flags |= UnsafeNclNativeMethods.OSSOCK.TransmitPacketsElementFlags.EndOfPacket;
             }
+#endif
         }
 
         // Filename property
@@ -8477,7 +8554,13 @@ namespace System.Net.Sockets {
 
         // EndOfPacket property
         public bool EndOfPacket {
-            get { return (m_Flags & UnsafeNclNativeMethods.OSSOCK.TransmitPacketsElementFlags.EndOfPacket) != 0; }
+            get {
+#if MONO
+                return m_endOfPacket;
+#else
+                return (m_Flags & UnsafeNclNativeMethods.OSSOCK.TransmitPacketsElementFlags.EndOfPacket) != 0;
+#endif
+             }
         }
     }
 
@@ -8492,6 +8575,7 @@ namespace System.Net.Sockets {
     }
     #endregion        
 
+#if !MONO
     public class SocketAsyncEventArgs : EventArgs, IDisposable {
 
         // Struct sizes needed for some custom marshalling.
@@ -10234,5 +10318,6 @@ namespace System.Net.Sockets {
         }
     }
 #endif // SOCKETTHREADPOOL
+#endif // !MONO
 
 }
index a9be75be0a64be172631a8208a3654087be8cb87..9f1444146c15c608265776922dd3d83da803f650 100644 (file)
@@ -1209,7 +1209,6 @@ namespace System.Net {
             }
         }
 
-#if !MONO
         //
         internal void SetupCacheProtocol(Uri uri)
         {
@@ -1224,6 +1223,7 @@ namespace System.Net {
             }
         }
 
+#if !MONO
         delegate void DelEtwFireBeginWRGet(object id, string uri, bool success, bool synchronous);
         delegate void DelEtwFireEndWRGet(object id, bool success, bool synchronous);
         delegate void DelEtwFireEndWRespGet(object id, bool success, bool synchronous, int statusCode);
index 2a315eaf42426b0beae95ed064b64a4e4168d184..501fc3493562b8bdc73c722de30153dc2038161e 100644 (file)
@@ -146,7 +146,9 @@ namespace System.Net {
             }
             public object OwningObject;
             public GeneralAsyncDelegate AsyncCallback;
+#if !MONO
             public bool Completed;
+#endif
             public ConnectionPool Pool;
             public int CreationTimeout;
         }
@@ -811,7 +813,9 @@ namespace System.Net {
     /// </devdoc>
     sealed internal class InterlockedStack {
         private readonly Stack _stack = new Stack();
+#if !MONO
         private int _count;
+#endif
 
 #if DEBUG
         private readonly Hashtable doublepush = new Hashtable();
@@ -832,7 +836,9 @@ namespace System.Net {
 #if DEBUG
                 GlobalLog.Assert(_count+1 == _stack.Count, "push count mishandle");
 #endif
+#if !MONO
                 _count = _stack.Count;
+#endif
             }
         }
 
@@ -845,7 +851,9 @@ namespace System.Net {
                     GlobalLog.Assert(_count-1 == _stack.Count, "pop count mishandle");
                     doublepush.Remove(pooledStream);
 #endif
+#if !MONO
                     _count = _stack.Count;
+#endif
                 }
                 return pooledStream;
             }
index 0db05f3620e2fc500dfb3c0db05801c66b6bf99c..8e2c50447f2275d3045433a231570f072dd588c1 100644 (file)
@@ -18,8 +18,10 @@ namespace System.Net {
 
         private static WaitCallback s_GetRequestStreamCallback = new WaitCallback(GetRequestStreamCallback);
         private static WaitCallback s_GetResponseCallback = new WaitCallback(GetResponseCallback);
+#if !MONO
         private static ContextCallback s_WrappedGetRequestStreamCallback = new ContextCallback(GetRequestStreamCallback);
         private static ContextCallback s_WrappedResponseCallback = new ContextCallback(GetResponseCallback);
+#endif
 
     // fields
 
index 80acb75ad34e7d3d5b2b24817a568c07b451b34f..510d7922bc73d878c8ae327beff78ae60ae00458 100644 (file)
@@ -1092,7 +1092,11 @@ namespace System.Net {
 
             internal long ContentLength;
             internal long Length;
+#if MONO
+            const int Offset = 0;
+#else
             internal int  Offset;
+#endif
 
 
             internal ProgressData Progress;
@@ -1365,8 +1369,10 @@ namespace System.Net {
                 WebClient = webClient;
             }
 
+#if !MONO
             internal long Length;
             internal int  Offset;
+#endif
 
             internal ProgressData Progress;
 
index 9f55631246f21d5a8d9579df9422dc10efdc4183..1a587adf4e833b9fe51d569212471200a7005722 100644 (file)
@@ -443,6 +443,11 @@ namespace System {
         {
             Uri result;
 
+#if MONO
+            if (uriKind == UriKind.RelativeOrAbsolute)
+                uriKind = DotNetRelativeOrAbsolute;
+#endif
+
             if (!Uri.TryCreate(uriString, uriKind, out result))
                 return false;
 
index 7b9b1e1911554202ca41795357d004fc2f7dfe04..4675771138671184da9cab61a354f3441eebb24c 100644 (file)
@@ -473,6 +473,7 @@ namespace System.Text.RegularExpressions {
         }
 
 #if NETSTANDARD
+        [CLSCompliant (false)]
         protected IDictionary Caps
         {
             get
@@ -500,6 +501,7 @@ namespace System.Text.RegularExpressions {
             }
         }
 
+        [CLSCompliant (false)]
         protected IDictionary CapNames
         {
             get
@@ -1398,7 +1400,7 @@ namespace System.Text.RegularExpressions {
             return newcached;
         }
 
-#if !(SILVERLIGHT||FULL_AOT_RUNTIME)
+#if !SILVERLIGHT
         /*
          * True if the O option was set
          */
@@ -1408,7 +1410,11 @@ namespace System.Text.RegularExpressions {
         protected bool UseOptionC() {
                /* Mono: Set to false until we investigate  https://bugzilla.xamarin.com/show_bug.cgi?id=25671 */
            return false;
+#if FULL_AOT_RUNTIME
+            return false;
+#else
             return(roptions & RegexOptions.Compiled) != 0;
+#endif
         }
 #endif
 
index 6f191129671672f5a0d3c58901385525b798814c..6d603688023c9cc7d06bcf48021419eb519cb3c3 100644 (file)
@@ -3033,7 +3033,9 @@ namespace System.Text.RegularExpressions {
 
     internal class RegexTypeCompiler : RegexCompiler {
         private static int _typeCount = 0;
+#if !MONO
         private static LocalDataStoreSlot _moduleSlot = Thread.AllocateDataSlot();
+#endif
 
         private  AssemblyBuilder _assembly;
         private  ModuleBuilder  _module;
index f5fabc69b61c62caeab800216bb48ca02982fb76..7be029f7e81e27c00a6f6cb479eab8e084d77c7f 100644 (file)
@@ -41,8 +41,10 @@ namespace System.Diagnostics {
         // a user's char[] directly, instead of our internal char[].
         private int _maxCharsPerBuffer;
 
+#pragma warning disable 414
         // Store a backpointer to the process class, to check for user callbacks
         private Process process;
+#pragma warning restore
 
         // Delegate to call user function.
         private UserCallBack userCallBack;
@@ -57,6 +59,11 @@ namespace System.Diagnostics {
         // Cache the last position scanned in sb when searching for lines.
         private int currentLinePos;
                
+#if MONO
+               //users to coordinate between Dispose and BeginReadLine
+               private object syncObject = new Object ();
+#endif
+
         internal AsyncStreamReader(Process process, Stream stream, UserCallBack callback, Encoding encoding) 
             : this(process, stream, callback, encoding, DefaultBufferSize) {
         }
@@ -104,6 +111,9 @@ namespace System.Diagnostics {
 
         protected virtual void Dispose(bool disposing)
         {
+#if MONO
+            lock (syncObject) {
+#endif
             if (disposing) {
                 if (stream != null)
                     stream.Close();
@@ -120,6 +130,9 @@ namespace System.Diagnostics {
                 eofEvent.Close();
                 eofEvent = null;
             }
+#if MONO
+            }
+#endif
         }
         
         public virtual Encoding CurrentEncoding {
@@ -155,6 +168,12 @@ namespace System.Diagnostics {
             int byteLen;
             
             try {
+#if MONO
+                var stream = this.stream;
+                if (stream == null)
+                byteLen = 0;
+                else
+#endif
                 byteLen = stream.EndRead(ar);
             }
             catch (IOException ) {
@@ -171,6 +190,9 @@ namespace System.Diagnostics {
                 byteLen = 0; // Treat this as EOF
             }
                 
+#if MONO
+retry_dispose:
+#endif
             if (byteLen == 0) { 
                 // We're at EOF, we won't call this function again from here on.
                 lock(messageQueue) {
@@ -186,13 +208,45 @@ namespace System.Diagnostics {
                     FlushMessageQueue();
                 }
                 finally {
+#if MONO
+                    lock (syncObject) {
+                        if (eofEvent != null) {
+                            try {
+                                eofEvent.Set ();
+                            } catch (System.ObjectDisposedException) {
+                                // This races with Dispose, it's safe to ignore the error as it comes from a SafeHandle doing its job
+                            }
+                        }
+                    }
+#else
                     eofEvent.Set();
+#endif
                 }
             } else {
+#if MONO
+                lock (syncObject) {
+                    if (decoder == null) { //we got disposed after the EndRead, retry as Diposed
+                        byteLen = 0;
+                        goto retry_dispose;
+                    }
+#endif
                 int charLen = decoder.GetChars(byteBuffer, 0, byteLen, charBuffer, 0);
                 sb.Append(charBuffer, 0, charLen);
+#if MONO
+                }
+#endif
                 GetLinesFromStringBuilder();
+#if MONO
+                lock (syncObject) {
+                    if (stream == null) { //we got disposed after the EndRead, retry as Diposed
+                        byteLen = 0;
+                        goto retry_dispose;
+                    }
+#endif
                 stream.BeginRead(byteBuffer, 0 , byteBuffer.Length,  new AsyncCallback(ReadBuffer), null);
+#if MONO
+                }
+#endif
             }
         }
         
index cbd2456ab966dcad784e6055e16ea4b2a7964721..13016654b5ce11c726809607480a982610e976c0 100644 (file)
@@ -91,12 +91,14 @@ namespace System.Diagnostics {
                
         DateTime exitTime;
         bool haveExitTime;
-        
+
+#if !MONO
         bool responding;
         bool haveResponding;
         
         bool priorityBoostEnabled;
         bool havePriorityBoostEnabled;
+#endif
         
         bool raisedOnExited;
         RegisteredWaitHandle registeredWaitHandle;
@@ -108,7 +110,9 @@ namespace System.Diagnostics {
         OperatingSystem operatingSystem;
         bool disposed;
         
+#if !MONO
         static object s_CreateProcessLock = new object();
+#endif
         
         // This enum defines the operation mode for redirected process stream.
         // We don't support switching between synchronous mode and asynchronous mode.
@@ -122,6 +126,9 @@ namespace System.Diagnostics {
         StreamReadMode outputStreamReadMode;
         StreamReadMode errorStreamReadMode;
         
+#if MONO
+        StreamReadMode inputStreamReadMode;
+#endif
        
         // Support for asynchrously reading streams
         [Browsable(true), MonitoringDescription(SR.ProcessAssociated)]
@@ -136,8 +143,9 @@ namespace System.Diagnostics {
         internal bool pendingOutputRead;
         internal bool pendingErrorRead;
 
-
+#if !MONO
         private static SafeFileHandle InvalidPipeHandle = new SafeFileHandle(IntPtr.Zero, false);
+#endif
 #if DEBUG
         internal static TraceSwitch processTracing = new TraceSwitch("processTracing", "Controls debug output from Process component");
 #else
@@ -1183,6 +1191,9 @@ namespace System.Diagnostics {
                     throw new InvalidOperationException(SR.GetString(SR.CantGetStandardIn));
                 }
 
+#if MONO
+                inputStreamReadMode = StreamReadMode.syncMode;
+#endif
                 return standardInput;
             }
         }
@@ -1346,6 +1357,40 @@ namespace System.Diagnostics {
                 machineName = ".";
                 raisedOnExited = false;
 
+#if MONO
+                //Call close on streams if the user never saw them.
+                //A stream in the undefined mode was never fetched by the user.
+                //A stream in the async mode is wrapped on a AsyncStreamReader and we should dispose that instead.
+                //  no way for users to get a hand on a AsyncStreamReader.
+                var tmpIn = standardInput;
+                standardInput = null;
+                if (inputStreamReadMode == StreamReadMode.undefined && tmpIn != null)
+                    tmpIn.Close ();
+
+                var tmpOut = standardOutput;
+                standardOutput = null;
+                if (outputStreamReadMode == StreamReadMode.undefined && tmpOut != null)
+                    tmpOut.Close ();
+
+                tmpOut = standardError;
+                standardError = null;
+                if (errorStreamReadMode == StreamReadMode.undefined && tmpOut != null)
+                    tmpOut.Close ();
+
+                var tmpAsync = output;
+                output = null;
+                if (outputStreamReadMode == StreamReadMode.asyncMode && tmpAsync != null) {
+                    tmpAsync.CancelOperation ();
+                    tmpAsync.Close ();
+                }
+
+                tmpAsync = error;
+                error = null;
+                if (errorStreamReadMode == StreamReadMode.asyncMode && tmpAsync != null) {
+                    tmpAsync.CancelOperation ();
+                    tmpAsync.Close ();
+                }
+#else
                 //Don't call close on the Readers and writers
                 //since they might be referenced by somebody else while the 
                 //process is still alive but this method called.
@@ -1356,6 +1401,7 @@ namespace System.Diagnostics {
                 output = null;
                 error = null;
        
+#endif
 
                 Refresh();
             }
@@ -1832,8 +1878,10 @@ namespace System.Diagnostics {
             haveProcessorAffinity = false;
             havePriorityClass = false;
             haveExitTime = false;
+#if !MONO
             haveResponding = false;
             havePriorityBoostEnabled = false;
+#endif
         }
 
         /// <devdoc>
index ef960754ba860b5776c94f68ad708ae04079cfed..85d996b827a588a47f18ea4782bcb9f4981d4419 100644 (file)
@@ -53,6 +53,270 @@ namespace System.Diagnostics {
         public void CopyTo(ProcessModule[] array, int index) {
             InnerList.CopyTo(array, index);
         }
+
+#if MOBILE
+        [Obsolete ("This API is no longer available", true)]
+        public int Capacity {
+            get {
+                throw new NotSupportedException ();
+            }
+            set {
+                throw new NotSupportedException ();
+            }
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void Add (ProcessModule item)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void AddRange (System.Collections.Generic.IEnumerable<ProcessModule> collection)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public System.Collections.ObjectModel.ReadOnlyCollection<ProcessModule> AsReadOnly()
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public int BinarySearch(int index, int count, ProcessModule item, System.Collections.Generic.IComparer<ProcessModule> comparer)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public int BinarySearch(ProcessModule item)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public int BinarySearch(ProcessModule item, System.Collections.Generic.IComparer<ProcessModule> comparer)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void Clear()
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public System.Collections.Generic.List<TOutput> ConvertAll<TOutput>(Converter<ProcessModule,TOutput> converter)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void CopyTo(ProcessModule[] array)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void CopyTo(int index, ProcessModule[] array, int arrayIndex, int count)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public bool Exists(Predicate<ProcessModule> match)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public ProcessModule Find(Predicate<ProcessModule> match)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public System.Collections.Generic.List<ProcessModule> FindAll(Predicate<ProcessModule> match)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public int FindIndex(Predicate<ProcessModule> match)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public int FindIndex(int startIndex, Predicate<ProcessModule> match)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public int FindIndex(int startIndex, int count, Predicate<ProcessModule> match)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public ProcessModule FindLast(Predicate<ProcessModule> match)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public int FindLastIndex(Predicate<ProcessModule> match)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public int FindLastIndex(int startIndex, Predicate<ProcessModule> match)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public int FindLastIndex(int startIndex, int count, Predicate<ProcessModule> match)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void ForEach(Action<ProcessModule> action)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public System.Collections.Generic.List<ProcessModule> GetRange(int index, int count)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public int IndexOf(ProcessModule item, int index)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public int IndexOf(ProcessModule item, int index, int count)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void Insert(int index, ProcessModule item)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void InsertRange(int index, System.Collections.Generic.IEnumerable<ProcessModule> collection)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public int LastIndexOf(ProcessModule item)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public int LastIndexOf(ProcessModule item, int index)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public int LastIndexOf(ProcessModule item, int index, int count)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public bool Remove(ProcessModule item)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public int RemoveAll(Predicate<ProcessModule> match)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void RemoveAt(int index)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void RemoveRange(int index, int count)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void Reverse()
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void Reverse(int index, int count)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void Sort()
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void Sort(System.Collections.Generic.IComparer<ProcessModule> comparer)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void Sort(int index, int count, System.Collections.Generic.IComparer<ProcessModule> comparer)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void Sort(Comparison<ProcessModule> comparison)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public ProcessModule[] ToArray()
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void TrimExcess()
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public bool TrueForAll(Predicate<ProcessModule> match)
+        {
+            throw new NotSupportedException ();
+        }
+#endif
     }
 }
 
index 127c1d4319a7ea32bd83a47eb3d1d3ac0f3e45ea..94fa2f43bbd193043baafbb83bffb528e9ca27ba 100644 (file)
@@ -77,6 +77,252 @@ namespace System.Diagnostics {
         public void CopyTo(ProcessThread[] array, int index) {
             InnerList.CopyTo(array, index);
         }
+
+#if MOBILE
+        [Obsolete ("This API is no longer available", true)]
+        public int Capacity {
+            get {
+                throw new NotSupportedException ();
+            }
+            set {
+                throw new NotSupportedException ();
+            }
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void AddRange (System.Collections.Generic.IEnumerable<ProcessThread> collection)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public System.Collections.ObjectModel.ReadOnlyCollection<ProcessThread> AsReadOnly()
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public int BinarySearch(int index, int count, ProcessThread item, System.Collections.Generic.IComparer<ProcessThread> comparer)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public int BinarySearch(ProcessThread item)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public int BinarySearch(ProcessThread item, System.Collections.Generic.IComparer<ProcessThread> comparer)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void Clear()
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public System.Collections.Generic.List<TOutput> ConvertAll<TOutput>(Converter<ProcessThread,TOutput> converter)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void CopyTo(ProcessThread[] array)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void CopyTo(int index, ProcessThread[] array, int arrayIndex, int count)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public bool Exists(Predicate<ProcessThread> match)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public ProcessThread Find(Predicate<ProcessThread> match)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public System.Collections.Generic.List<ProcessThread> FindAll(Predicate<ProcessThread> match)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public int FindIndex(Predicate<ProcessThread> match)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public int FindIndex(int startIndex, Predicate<ProcessThread> match)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public int FindIndex(int startIndex, int count, Predicate<ProcessThread> match)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public ProcessThread FindLast(Predicate<ProcessThread> match)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public int FindLastIndex(Predicate<ProcessThread> match)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public int FindLastIndex(int startIndex, Predicate<ProcessThread> match)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public int FindLastIndex(int startIndex, int count, Predicate<ProcessThread> match)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void ForEach(Action<ProcessThread> action)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public System.Collections.Generic.List<ProcessThread> GetRange(int index, int count)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public int IndexOf(ProcessThread item, int index)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public int IndexOf(ProcessThread item, int index, int count)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void InsertRange(int index, System.Collections.Generic.IEnumerable<ProcessThread> collection)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public int LastIndexOf(ProcessThread item)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public int LastIndexOf(ProcessThread item, int index)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public int LastIndexOf(ProcessThread item, int index, int count)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public int RemoveAll(Predicate<ProcessThread> match)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void RemoveAt(int index)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void RemoveRange(int index, int count)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void Reverse()
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void Reverse(int index, int count)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void Sort()
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void Sort(System.Collections.Generic.IComparer<ProcessThread> comparer)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void Sort(int index, int count, System.Collections.Generic.IComparer<ProcessThread> comparer)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void Sort(Comparison<ProcessThread> comparison)
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public ProcessThread[] ToArray()
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public void TrimExcess()
+        {
+            throw new NotSupportedException ();
+        }
+
+        [Obsolete ("This API is no longer available", true)]
+        public bool TrueForAll(Predicate<ProcessThread> match)
+        {
+            throw new NotSupportedException ();
+        }
+#endif
         
     }
 }
index 2a0102e8c57e11c654e1996120fd29cb04c76fdb..37f19b3aa8e1d599f442232477d4cc73f86437be 100644 (file)
@@ -26,7 +26,9 @@ namespace System.Windows.Markup
     /// attached property.
     /// </summary>
     [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Property | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
+#if !MOBILE
     [TypeForwardedFrom("WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")]
+#endif
     public sealed class ValueSerializerAttribute : Attribute
     {
         /// <summary>
index b0290241aa4f877917c8b3bb88c20e8ec9aaba3f..f7298b8d117d32e6ffc08d38a4682c28d71efcd4 100644 (file)
@@ -20,7 +20,7 @@ namespace System {
     using System.Security.Permissions;
     [Serializable]
     [System.Runtime.InteropServices.ComVisible(true)]
-#if FEATURE_REMOTING
+#if FEATURE_REMOTING || MONO
     public abstract class ContextBoundObject : MarshalByRefObject {
 #else // FEATURE_REMOTING
     public abstract class ContextBoundObject {
index a4d5858e9ecddca1d47d729104352d351ceff953..dcc15f55ededabd0d03d75d548d3c77511076a8f 100644 (file)
@@ -65,6 +65,28 @@ namespace System {
 
     public static class GC 
     {
+#if MONO
+        [MethodImplAttribute (MethodImplOptions.InternalCall)]
+        extern static int GetCollectionCount (int generation);
+
+        [MethodImplAttribute (MethodImplOptions.InternalCall)]
+        extern static int GetMaxGeneration ();
+
+        [MethodImplAttribute (MethodImplOptions.InternalCall)]
+        extern static void InternalCollect (int generation);
+
+        [MethodImplAttribute (MethodImplOptions.InternalCall)]
+        extern static void RecordPressure (long bytesAllocated);
+
+        // TODO: Move following to ConditionalWeakTable
+        [MethodImplAttribute (MethodImplOptions.InternalCall)]
+        internal extern static void register_ephemeron_array (Ephemeron[] array);
+
+        [MethodImplAttribute (MethodImplOptions.InternalCall)]
+        extern static object get_ephemeron_tombstone ();
+
+        internal static readonly object EPHEMERON_TOMBSTONE = get_ephemeron_tombstone ();
+#else
         [System.Security.SecurityCritical]  // auto-generated
         [ResourceExposure(ResourceScope.None)]
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -139,6 +161,7 @@ namespace System {
         [ResourceExposure(ResourceScope.None)]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
         private static extern void _RemoveMemoryPressure(UInt64 bytesAllocated);
+#endif
         
         [System.Security.SecurityCritical]  // auto-generated_required
         public static void AddMemoryPressure (long bytesAllocated) {
@@ -153,7 +176,11 @@ namespace System {
             }
             Contract.EndContractBlock();
 
+#if MONO
+            RecordPressure (bytesAllocated);
+#else
             _AddMemoryPressure((ulong)bytesAllocated);
+#endif
         }
 
         [System.Security.SecurityCritical]  // auto-generated_required
@@ -169,7 +196,11 @@ namespace System {
             }
             Contract.EndContractBlock();
 
+#if MONO
+            RecordPressure (-bytesAllocated);
+#else
             _RemoveMemoryPressure((ulong) bytesAllocated);
+#endif
         }
 
 
@@ -198,8 +229,12 @@ namespace System {
         //
         [System.Security.SecuritySafeCritical]  // auto-generated
         public static void Collect() {
+#if MONO
+            InternalCollect (MaxGeneration);
+#else
             //-1 says to GC all generations.
             _Collect(-1, (int)InternalGCCollectionMode.Blocking);
+#endif
         }
 
         [System.Security.SecuritySafeCritical]  // auto-generated
@@ -248,7 +283,11 @@ namespace System {
                 iInternalModes |= (int)InternalGCCollectionMode.NonBlocking;
             }
 
+#if MONO
+            InternalCollect (generation);
+#else
             _Collect(generation, iInternalModes);
+#endif
         }
 
         [System.Security.SecuritySafeCritical]  // auto-generated
@@ -260,9 +299,15 @@ namespace System {
                 throw new ArgumentOutOfRangeException("generation", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
             }
             Contract.EndContractBlock();
+
+#if MONO
+            return GetCollectionCount(generation);
+#else
             return _CollectionCount(generation, 0);
+#endif
         }
 
+#if !MONO
         // pass in true to get the BGC or FGC count.
         [System.Security.SecuritySafeCritical]  // auto-generated
         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
@@ -275,6 +320,7 @@ namespace System {
             Contract.EndContractBlock();
             return _CollectionCount(generation, (getSpecialGCCount ? 1 : 0));
         }
+#endif
         
         // This method DOES NOT DO ANYTHING in and of itself.  It's used to 
         // prevent a finalizable object from losing any outstanding references 
@@ -318,9 +364,16 @@ namespace System {
         //
         [System.Security.SecuritySafeCritical]  // auto-generated
         public static int GetGeneration(WeakReference wo) {
+#if MONO
+            object obj = wo.Target;
+            if (obj == null)
+                throw new ArgumentException ();
+            return GetGeneration (obj);
+#else
             int result = GetGenerationWR(wo.m_handle);
             KeepAlive(wo);
             return result;
+#endif
         }
     
         // Returns the maximum GC generation.  Currently assumes only 1 heap.
@@ -330,17 +383,23 @@ namespace System {
             get { return GetMaxGeneration(); }
         }
 
+#if MONO
+        [MethodImplAttribute (MethodImplOptions.InternalCall)]
+        public extern static void WaitForPendingFinalizers ();
+#else
         [System.Security.SecurityCritical]  // auto-generated
         [ResourceExposure(ResourceScope.None)]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern void _WaitForPendingFinalizers();
 
+
         [System.Security.SecuritySafeCritical]  // auto-generated
         public static void WaitForPendingFinalizers() {
             // QCalls can not be exposed from mscorlib directly, need to wrap it.
             _WaitForPendingFinalizers();
         }
+#endif
     
         // Indicates that the system should not call the Finalize() method on
         // an object that would normally require this call.
@@ -380,6 +439,31 @@ namespace System {
         // the GC heap.  This does not return the total size of the GC heap, but
         // only the live objects in the GC heap.
         //
+#if MONO
+        [MethodImplAttribute (MethodImplOptions.InternalCall)]
+        public extern static long GetTotalMemory (bool forceFullCollection);
+
+        static bool _RegisterForFullGCNotification(int maxGenerationPercentage, int largeObjectHeapPercentage)
+        {
+            throw new NotImplementedException ();
+        }
+
+        static bool _CancelFullGCNotification ()
+        {
+            throw new NotImplementedException ();
+        }
+
+        static int _WaitForFullGCApproach (int millisecondsTimeout)
+        {
+            throw new NotImplementedException ();
+        }
+
+        static int _WaitForFullGCComplete (int millisecondsTimeout)
+        {
+            throw new NotImplementedException ();
+        }
+
+#else 
         [System.Security.SecuritySafeCritical]  // auto-generated
         public static long GetTotalMemory(bool forceFullCollection) {
             long size = GetTotalMemory();
@@ -416,6 +500,7 @@ namespace System {
 
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern int _WaitForFullGCComplete(int millisecondsTimeout);
+#endif
 
         [SecurityCritical]
         public static void RegisterForFullGCNotification(int maxGenerationThreshold, int largeObjectHeapThreshold)
@@ -503,6 +588,9 @@ namespace System {
         [SecurityCritical]
         static bool StartNoGCRegionWorker(long totalSize, bool hasLohSize, long lohSize, bool disallowFullBlockingGC)
         {
+#if MONO
+            throw new NotImplementedException ();
+#else
             StartNoGCRegionStatus status = (StartNoGCRegionStatus)_StartNoGCRegion(totalSize, hasLohSize, lohSize, disallowFullBlockingGC);
             if (status == StartNoGCRegionStatus.AmountTooLarge)
                 throw new ArgumentOutOfRangeException("totalSize", 
@@ -512,6 +600,7 @@ namespace System {
             else if (status == StartNoGCRegionStatus.NotEnoughMemory)
                 return false;
             return true;
+#endif
         }
 
         [SecurityCritical]
@@ -541,6 +630,9 @@ namespace System {
         [SecurityCritical]
         static EndNoGCRegionStatus EndNoGCRegionWorker()
         {
+#if MONO
+            throw new NotImplementedException ();
+#else
             EndNoGCRegionStatus status = (EndNoGCRegionStatus)_EndNoGCRegion();
             if (status == EndNoGCRegionStatus.NotInProgress)
                 throw new InvalidOperationException("NoGCRegion mode must be set");
@@ -550,6 +642,7 @@ namespace System {
                 throw new InvalidOperationException("Allocated memory exceeds specified memory for NoGCRegion mode");
 
             return EndNoGCRegionStatus.Succeeded;
+#endif
         }
 
         [SecurityCritical]
index 147ef7382e1b349d631e9834a24caebff0d7bdb9..4bfcfea188124d36797966b59cecc4d6dfd0a893 100644 (file)
@@ -1357,8 +1357,9 @@ namespace System.Globalization {
         {
             return NativeInternalInitSortHandle(localeName, out handleOrigin);
         }
+#endif
 
-#if !FEATURE_CORECLR
+#if !FEATURE_CORECLR || MONO
         private const int SORT_VERSION_WHIDBEY = 0x00001000;
         private const int SORT_VERSION_V4 = 0x00060101;
 
@@ -1375,7 +1376,11 @@ namespace System.Globalization {
             [System.Security.SecuritySafeCritical]
             get
             {
+#if MONO
+                return SORT_VERSION_V4;
+#else
                 return InternalGetSortVersion();
+#endif
             }
         }
 
@@ -1389,16 +1394,21 @@ namespace System.Globalization {
             {
                 if(m_SortVersion == null) 
                 {
+#if MONO
+                    m_SortVersion = new SortVersion(SORT_VERSION_V4, new Guid("00000001-57ee-1e5c-00b4-d0000bb1e11e")); // Guid returned by corefx and .NET 4.6
+#else
                     Win32Native.NlsVersionInfoEx v = new Win32Native.NlsVersionInfoEx();
                     v.dwNLSVersionInfoSize = Marshal.SizeOf(typeof(Win32Native.NlsVersionInfoEx));
                     InternalGetNlsVersionEx(m_dataHandle, m_handleOrigin, m_sortName, ref v);
                     m_SortVersion = new SortVersion(v.dwNLSVersion, (v.dwEffectiveId != 0) ? v.dwEffectiveId : LCID, v.guidCustomVersion);
+#endif
                 }
 
                 return m_SortVersion;
             }
         }
-        
+
+#if !MONO
         [System.Security.SecurityCritical]
         [ResourceExposure(ResourceScope.None)]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
@@ -1412,7 +1422,6 @@ namespace System.Globalization {
         [SuppressUnmanagedCodeSecurity]
         private static extern uint InternalGetSortVersion();
 
-#endif
         [System.Security.SecurityCritical]
         [ResourceExposure(ResourceScope.None)]
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
@@ -1456,6 +1465,8 @@ namespace System.Globalization {
         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
         [SuppressUnmanagedCodeSecurity]
         private static extern int InternalGetSortKey(IntPtr handle, IntPtr handleOrigin, String localeName, int flags, String source, int sourceCount, byte[] target, int targetCount);
+#endif
+
 #endif
     }
 }
index 2402d9d2bdec1d287f5612c413bc2c3f101c9b46..cb2f144af24ceedf715ef302761a5fc7db00ae61 100644 (file)
@@ -17,7 +17,7 @@
 ===========================================================*/
 
 using System;
-#if FEATURE_MACL
+#if FEATURE_MACL || MONO
 using System.Security.AccessControl;
 #endif
 using System.Security.Permissions;
@@ -226,7 +226,7 @@ namespace System.IO {
             }
         }
 
-#if FEATURE_MACL
+#if FEATURE_MACL || MONO
         [ResourceExposure(ResourceScope.None)]
         [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
         public FileSecurity GetAccessControl()
index aab4fe9497568f6ad79cd7d0ceb1a50f9d4f01e1..2db4c807d8797f45a97f136996d363d3b6b47ef1 100644 (file)
@@ -34,7 +34,7 @@ namespace System.IO {
     [FileIOPermissionAttribute(SecurityAction.InheritanceDemand,Unrestricted=true)]
 #endif
     [ComVisible(true)]
-#if FEATURE_REMOTING        
+#if FEATURE_REMOTING || MONO
     public abstract class FileSystemInfo : MarshalByRefObject, ISerializable {
 #else // FEATURE_REMOTING
     public abstract class FileSystemInfo : ISerializable {   
index 007745c7ab57d6979632e580b69c75f901908af5..fa022e96e5d8fc29a94d34b28c2212e6eadd28f1 100644 (file)
@@ -39,7 +39,7 @@ namespace System.IO {
 #if CONTRACTS_FULL
     [ContractClass(typeof(StreamContract))]
 #endif
-#if FEATURE_REMOTING
+#if FEATURE_REMOTING || MONO
     public abstract class Stream : MarshalByRefObject, IDisposable {
 #else // FEATURE_REMOTING
     public abstract class Stream : IDisposable {
index 5f8e7b98a7d8240203fc1deb2db8526bd4299c58..9023902cbfc3403426645684534b05089e24115c 100644 (file)
@@ -39,7 +39,7 @@ namespace System.IO {
     // There are methods on the Stream class for reading bytes. 
     [Serializable]
     [ComVisible(true)]
-#if FEATURE_REMOTING
+#if FEATURE_REMOTING || MONO
     public abstract class TextReader : MarshalByRefObject, IDisposable {
 #else // FEATURE_REMOTING
     public abstract class TextReader : IDisposable {
index 2afe3a6cbfae4d9751a6ceb27ad2343f4fb54259..3f484ffaddb1d5ebea09a176058b4b04274ff4f4 100644 (file)
@@ -39,7 +39,7 @@ namespace System.IO {
     // There are methods on the Stream class for writing bytes. 
     [Serializable]
     [ComVisible(true)]
-#if FEATURE_REMOTING
+#if FEATURE_REMOTING || MONO
     public abstract class TextWriter : MarshalByRefObject, IDisposable {
 #else // FEATURE_REMOTING
     public abstract class TextWriter : IDisposable {
index b74e4d606b57f0e28c77d31cb059015706e0da26..dd983a383ef6c34e6c4701fd694e9f9ea6dffe6a 100644 (file)
@@ -151,7 +151,13 @@ namespace System.Runtime.InteropServices {
             }
         }
 
-#if FEATURE_COMINTEROP && !MONO
+#if FEATURE_COMINTEROP || MONO
+#if MONO
+        private static IntPtr GetRuntimeInterfaceImpl(Guid clsid, Guid riid)
+        {
+            throw new NotSupportedException();
+        }
+#else
         [System.Security.SecurityCritical]
         [ResourceExposure(ResourceScope.Process)]
         [ResourceConsumption(ResourceScope.Process)]
@@ -160,6 +166,7 @@ namespace System.Runtime.InteropServices {
         private static extern IntPtr GetRuntimeInterfaceImpl(
             [In, MarshalAs(UnmanagedType.LPStruct)] Guid clsid,
             [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid);
+#endif
 
         //
         // This function does the equivalent of calling GetInterface(clsid, riid) on the
index 0e7bfafaf9e7bec12929f3349b607f1211c53ddc..b82294c787ba14115fb78a1ba897b19c3dd738a2 100644 (file)
@@ -34,7 +34,7 @@ namespace System.Runtime.Serialization.Formatters.Binary {
     
     [System.Runtime.InteropServices.ComVisible(true)]
     sealed public class BinaryFormatter :
-#if !FEATURE_REMOTING
+#if !FEATURE_REMOTING && !MONO
         IFormatter
 #else
         IRemotingFormatter 
index cd8b165baaf1c6e2c0781e66122bb49a56f82f80..090998e0a51b276b05e83722d12818ab5f4f451a 100644 (file)
@@ -86,12 +86,12 @@ namespace System.Security
     {
 #pragma warning disable 618    // We still use SecurityCriticalScope for v2 compat
 
-#if !FEATURE_CORECLR && !MOBILE
+#if !FEATURE_CORECLR
          private SecurityCriticalScope  _val;
 #endif // FEATURE_CORECLR
         public SecurityCriticalAttribute () {}
 
-#if !FEATURE_CORECLR && !MOBILE
+#if !FEATURE_CORECLR
         public SecurityCriticalAttribute(SecurityCriticalScope scope)
         {
             _val = scope;
index c97acf8e60bef4fd1ebc624a257471ef823acc8d..89877e0add7f11bfb3a72d4148a5df8f9e96a7f6 100644 (file)
@@ -70,6 +70,9 @@ namespace System.Security.Cryptography {
         [System.Security.SecuritySafeCritical]  // auto-generated
         public override ICryptoTransform CreateEncryptor (byte[] rgbKey, byte[] rgbIV) {
 #if MONO
+            if (m_use40bitSalt)
+                throw new NotImplementedException ("UseSalt=true is not implemented on Mono yet");
+
             return new RC2Transform (this, true, rgbKey, rgbIV);
 #else
             return _NewEncryptor(rgbKey, ModeValue, rgbIV, EffectiveKeySizeValue, 
@@ -80,6 +83,9 @@ namespace System.Security.Cryptography {
         [System.Security.SecuritySafeCritical]  // auto-generated
         public override ICryptoTransform CreateDecryptor (byte[] rgbKey, byte[] rgbIV) {
 #if MONO
+            if (m_use40bitSalt)
+                throw new NotImplementedException ("UseSalt=true is not implemented on Mono yet");
+
             return new RC2Transform (this, false, rgbKey, rgbIV);
 #else
             return _NewEncryptor(rgbKey, ModeValue, rgbIV, EffectiveKeySizeValue,
index 804eeda9bdac32d93a1173972e7989b8989a6352..63bbb53d3b13d3a79dcc27a74c3f003d6b71b568 100644 (file)
@@ -209,13 +209,15 @@ namespace System.Security.Cryptography {
             m_block++;
             return ret;
         }
-#if !MONO
         [System.Security.SecuritySafeCritical]  // auto-generated
         public byte[] CryptDeriveKey(string algname, string alghashname, int keySize, byte[] rgbIV)
         {
             if (keySize < 0)
                 throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeySize"));
 
+#if MONO
+            throw new NotSupportedException ("CspParameters are not supported by Mono");
+#else
             int algidhash = X509Utils.NameOrOidToAlgId(alghashname, OidGroup.HashAlgorithm);
             if (algidhash == 0)
                 throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_InvalidAlgorithm"));
@@ -233,8 +235,10 @@ namespace System.Security.Cryptography {
                       m_password, m_password.Length, keySize << 16, rgbIV, rgbIV.Length,
                       JitHelpers.GetObjectHandleOnStack(ref key));
             return key;
+#endif
         }
 
+#if !MONO
         [System.Security.SecurityCritical] // auto-generated
         private SafeProvHandle _safeProvHandle = null;
         private SafeProvHandle ProvHandle
index 60046c7dba2ff68d34dbc612b28405e125b430b3..3063b06aed614150203337276bab3c04169751b2 100644 (file)
@@ -39,12 +39,11 @@ namespace System.Threading
             : base(info, context) 
         {
         }
-#if !MOBILE
+
         public Object ExceptionState 
         {
             [System.Security.SecuritySafeCritical]  // auto-generated
             get {return Thread.CurrentThread.AbortReason;}
         }
-#endif
     }
 }
index 118d89410e2efbb38ce56371da9b5012593e7e5a..74e77b0edf0f66df063ca925485701b4a139b671 100644 (file)
@@ -91,8 +91,11 @@ namespace MonoTests.Helpers
                                        listenSocket = tcpListener.AcceptSocket ();
                                        listenSocket.Send (requestHandler (listenSocket));
                                        try {
-                                               listenSocket.Shutdown (SocketShutdown.Receive);
+                                               // On Windows a Receive() is needed here before Shutdown() to consume the data some tests send.
+                                               listenSocket.ReceiveTimeout = 10 * 1000;
+                                               listenSocket.Receive (new byte [0]);
                                                listenSocket.Shutdown (SocketShutdown.Send);
+                                               listenSocket.Shutdown (SocketShutdown.Receive);
                                        } catch {
                                        }
                                } catch (SocketException ex) {
diff --git a/mcs/errors/cs0177-15.cs b/mcs/errors/cs0177-15.cs
new file mode 100644 (file)
index 0000000..310f405
--- /dev/null
@@ -0,0 +1,21 @@
+// CS0177: The out parameter `x' must be assigned to before control leaves the current method
+// Line: 6
+
+public class GotoWithOut
+{
+       public static void Test (bool cond, out int x)
+       {
+               if (cond)
+               {
+                       goto Label2;
+               }
+               else
+               {
+                       goto Label;
+               }
+               Label:
+               x = 0;
+               Label2:
+               return;
+       }
+}
\ No newline at end of file
diff --git a/mcs/errors/cs0219-7.cs b/mcs/errors/cs0219-7.cs
new file mode 100644 (file)
index 0000000..ca40a59
--- /dev/null
@@ -0,0 +1,11 @@
+// CS0219: The constant `C' is never used
+// Line: 9
+// Compiler options: -warn:3 -warnaserror
+
+class C
+{
+       public static void Main ()
+       {
+               const int C = 1;
+       }
+}
\ No newline at end of file
index 63ddee82bfa286db0e183495ef80d6a93e4d5b90..fea30ff25c6d0e4846b95d8fedb86605285138c2 100644 (file)
@@ -3276,13 +3276,13 @@ exptype_head            : D_CLASS K_EXTERN expt_attr comp_name
 expt_attr              : { $$ = 0; } /* EMPTY */\r
                        | expt_attr K_PRIVATE                   { $$ = (TypeAttr)$1 | TypeAttr.Private; }\r
                        | expt_attr K_PUBLIC                    { $$ = (TypeAttr)$1 | TypeAttr.Public; }\r
+                       | expt_attr K_FORWARDER                 { $$ = (TypeAttr)$1 | TypeAttr.Forwarder; }\r
                        | expt_attr K_NESTED K_PUBLIC           { $$ = (TypeAttr)$1 | TypeAttr.NestedPublic; }\r
                        | expt_attr K_NESTED K_PRIVATE          { $$ = (TypeAttr)$1 | TypeAttr.NestedPrivate; }\r
                        | expt_attr K_NESTED K_FAMILY           { $$ = (TypeAttr)$1 | TypeAttr.NestedFamily; }\r
                        | expt_attr K_NESTED K_ASSEMBLY         { $$ = (TypeAttr)$1 | TypeAttr.NestedAssembly;}\r
                        | expt_attr K_NESTED K_FAMANDASSEM      { $$ = (TypeAttr)$1 | TypeAttr.NestedFamAndAssem; }\r
                        | expt_attr K_NESTED K_FAMORASSEM       { $$ = (TypeAttr)$1 | TypeAttr.NestedFamOrAssem; }\r
-                       | K_FORWARDER                           { $$ = TypeAttr.Forwarder; }\r
                        ;\r
 \r
 exptype_decls          : /* EMPTY */\r
index b2399c8bd89d45c71aee3882c56bb09c8fddd2e1..33b05ff809b320ddcb69813f7fbc448007e81153 100644 (file)
@@ -526,6 +526,19 @@ namespace Mono.CSharp
                        return da;
                }
 
+               public Dictionary<Statement, List<DefiniteAssignmentBitSet>> CopyLabelStack ()
+               {
+                       if (LabelStack == null)
+                               return null;
+
+                       var dest = new Dictionary<Statement, List<DefiniteAssignmentBitSet>> ();
+                       foreach (var entry in LabelStack) {
+                               dest.Add (entry.Key, new List<DefiniteAssignmentBitSet> (entry.Value));
+                       }
+
+                       return dest;
+               }
+
                public bool IsDefinitelyAssigned (VariableInfo variable)
                {
                        return variable.IsAssigned (DefiniteAssignment);
@@ -536,6 +549,11 @@ namespace Mono.CSharp
                        return variable.IsStructFieldAssigned (DefiniteAssignment, name);
                }
 
+               public void SetLabelStack (Dictionary<Statement, List<DefiniteAssignmentBitSet>> labelStack)
+               {
+                       LabelStack = labelStack;
+               }
+
                public void SetVariableAssigned (VariableInfo variable, bool generatedAssignment = false)
                {
                        variable.SetAssigned (DefiniteAssignment, generatedAssignment);
index 1915a07240b379fdf4443385f6bd5a0af1e07783..e6a95fe8163a3590acb9f23602cc10d4cdec63dd 100644 (file)
@@ -2465,6 +2465,12 @@ namespace Mono.CSharp
                                case '\"':
                                        ++str_quote;
                                        break;
+                               case '\\':
+                                       // Skip escaped " character
+                                       c = reader.Read ();
+                                       if (c == -1)
+                                               res = false;
+                                       break;
                                case -1:
                                        res = false;
                                        break;
index edc860eca83b595e90b61975654147dbd691c4e9..2077f26bf2cf99d835fed105bbf4503bfeeae1d5 100644 (file)
@@ -4784,7 +4784,7 @@ namespace Mono.CSharp {
                                // is no better expression conversion
                                //
                                if (candidate_pd.Count < best_pd.Count) {
-                                       if (!candidate_params && !candidate_pd.FixedParameters [j - j].HasDefaultValue) {
+                                       if (!candidate_params && !candidate_pd.FixedParameters [j - 1].HasDefaultValue) {
                                                return true;
                                        }
                                } else if (candidate_pd.Count == best_pd.Count) {
index 48d2dc01b96c28e35cd2981830306cdbef1d0302..fdf5b81f92c38a4ef8dba73e5c202a990383eec3 100644 (file)
@@ -3159,7 +3159,7 @@ namespace Mono.CSharp {
                                        var ga_u = u.TypeArguments;
                                        var ga_v = v.TypeArguments;
 
-                                       if (u.TypeArguments.Length != u.TypeArguments.Length)
+                                       if (u.TypeArguments.Length != v.TypeArguments.Length)
                                                return 0;
 
                                        int score = 0;
index 17dc6f8817627126ab4fcd9d4f39b3f1dcd9fd88..14824d136b63f814975bdcedd6be3580593ce98e 100644 (file)
@@ -356,26 +356,23 @@ namespace Mono.CSharp
                        }
 
                        if (version_mismatch != null) {
-                               if (version_mismatch is AssemblyBuilder)
+                               if (is_fx_assembly || version_mismatch is AssemblyBuilder)
                                        return version_mismatch;
 
                                var ref_an = new AssemblyName (refname);
                                var v1 = ref_an.Version;
                                var v2 = version_mismatch.GetName ().Version;
+                               AssemblyReferenceMessageInfo messageInfo;
 
                                if (v1 > v2) {
-                                       var messageInfo = new AssemblyReferenceMessageInfo (ref_an, report => {
+                                       messageInfo = new AssemblyReferenceMessageInfo (ref_an, report => {
                                                report.SymbolRelatedToPreviousError (args.RequestingAssembly.Location);
                                                report.Error (1705, string.Format ("Assembly `{0}' depends on `{1}' which has a higher version number than referenced assembly `{2}'",
                                                                                                                   args.RequestingAssembly.FullName, refname, version_mismatch.GetName ().FullName));
                                        });
 
-                                       AddReferenceVersionMismatch (args.RequestingAssembly.GetName (), messageInfo);
-                                       return version_mismatch;
-                               }
-
-                               if (!is_fx_assembly) {
-                                       var messageInfo = new AssemblyReferenceMessageInfo (ref_an, report => {
+                               } else {
+                                       messageInfo = new AssemblyReferenceMessageInfo (ref_an, report => {
                                                if (v1.Major != v2.Major || v1.Minor != v2.Minor) {
                                                        report.Warning (1701, 2,
                                                                "Assuming assembly reference `{0}' matches assembly `{1}'. You may need to supply runtime policy",
@@ -386,10 +383,10 @@ namespace Mono.CSharp
                                                                refname, version_mismatch.GetName ().FullName);
                                                }
                                        });
-
-                                       AddReferenceVersionMismatch (args.RequestingAssembly.GetName (), messageInfo);
                                }
 
+                               AddReferenceVersionMismatch (args.RequestingAssembly.GetName (), messageInfo);
+
                                return version_mismatch;
                        }
 
index 60073b9f4c1338929c6098c9a28f861d36534132..9518427e1a17c1fe1499516410ea4c9fde28a893 100644 (file)
@@ -142,6 +142,7 @@ namespace Mono.CSharp
                        compiled_types = new Dictionary<MetaType, TypeSpec> (40, ReferenceEquality<MetaType>.Default);
                        assembly_2_definition = new Dictionary<Assembly, IAssemblyDefinition> (ReferenceEquality<Assembly>.Default);
                        IgnorePrivateMembers = true;
+                       IgnoreCompilerGeneratedField = true;
                }
 
                #region Properties
@@ -154,6 +155,8 @@ namespace Mono.CSharp
 
                public bool IgnorePrivateMembers { get; set; }
 
+               public bool IgnoreCompilerGeneratedField { get; set; }
+
                #endregion
 
                public abstract void AddCompiledType (TypeBuilder builder, TypeSpec spec);
@@ -179,8 +182,10 @@ namespace Mono.CSharp
                                        break;
                                default:
                                        // Ignore private fields (even for error reporting) to not require extra dependencies
-                                       if ((IgnorePrivateMembers && !declaringType.IsStruct) ||
-                                               HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "CompilerGeneratedAttribute", CompilerServicesNamespace))
+                                       if (IgnorePrivateMembers && !declaringType.IsStruct)
+                                               return null;
+
+                                       if (IgnoreCompilerGeneratedField && HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "CompilerGeneratedAttribute", CompilerServicesNamespace))
                                                return null;
 
                                        mod = Modifiers.PRIVATE;
index 8036f2c1126a56319198464e021386325110ca10..6b1990e1f0983d87bd8b91d0f60dee7efe51129c 100644 (file)
@@ -1210,12 +1210,11 @@ namespace Mono.CSharp
 
                        backing_field = new Field (Parent,
                                new TypeExpression (MemberType, Location),
-                               Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
+                               Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.DEBUGGER_HIDDEN | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
                                MemberName, null);
 
                        Parent.PartialContainer.Members.Add (backing_field);
                        backing_field.Initializer = Initializer;
-                       backing_field.ModFlags &= ~Modifiers.COMPILER_GENERATED;
 
                        // Call define because we passed fields definition
                        backing_field.Define ();
index 6b658945ff30c30261efeadb5015965883c92a6a..eab87d16a17871ef5789fd98503ec70a99708f86 100644 (file)
@@ -270,10 +270,14 @@ namespace Mono.CSharp {
                        var da_false = new DefiniteAssignmentBitSet (fc.DefiniteAssignmentOnFalse);
 
                        fc.DefiniteAssignment = fc.DefiniteAssignmentOnTrue;
+                       var labels = fc.CopyLabelStack ();
 
                        var res = TrueStatement.FlowAnalysis (fc);
 
+                       fc.SetLabelStack (labels);
+
                        if (FalseStatement == null) {
+
                                var c = expr as Constant;
                                if (c != null && !c.IsDefaultValue)
                                        return true_returns;
@@ -288,14 +292,20 @@ namespace Mono.CSharp {
 
                        if (true_returns) {
                                fc.DefiniteAssignment = da_false;
-                               return FalseStatement.FlowAnalysis (fc);
+
+                               res = FalseStatement.FlowAnalysis (fc);
+                               fc.SetLabelStack (labels);
+                               return res;
                        }
 
                        var da_true = fc.DefiniteAssignment;
 
                        fc.DefiniteAssignment = da_false;
+
                        res &= FalseStatement.FlowAnalysis (fc);
 
+                       fc.SetLabelStack (labels);
+
                        if (!TrueStatement.IsUnreachable) {
                                if (false_returns || FalseStatement.IsUnreachable)
                                        fc.DefiniteAssignment = da_true;
@@ -2280,6 +2290,9 @@ namespace Mono.CSharp {
 
                public override void Emit (EmitContext ec)
                {
+                       if (!Variable.IsUsed)
+                               ec.Report.Warning (219, 3, loc, "The constant `{0}' is never used", Variable.Name);
+                       
                        // Nothing to emit, not even sequence point
                }
 
@@ -2438,6 +2451,12 @@ namespace Mono.CSharp {
                        }
                }
 
+               public bool IsUsed {
+                       get {
+                               return (flags & Flags.Used) != 0;
+                       }
+               }
+
                public bool IsFixed {
                        get {
                                return (flags & Flags.FixedVariable) != 0;
@@ -2527,8 +2546,10 @@ namespace Mono.CSharp {
 
                public Expression CreateReferenceExpression (ResolveContext rc, Location loc)
                {
-                       if (IsConstant && const_value != null)
+                       if (IsConstant && const_value != null) {
+                               SetIsUsed ();
                                return Constant.CreateConstantFromValue (Type, const_value.GetValue (), loc);
+                       }
 
                        return new LocalVariableReference (this, loc);
                }
diff --git a/mcs/tests/test-16628-lib.il b/mcs/tests/test-16628-lib.il
new file mode 100644 (file)
index 0000000..ca46405
--- /dev/null
@@ -0,0 +1,33 @@
+.assembly bz16628.typeforwarder2 {}
+.assembly extern mscorlib {}
+.assembly extern bz16628.typeforwardee2 {}
+
+.class extern public forwarder NSwForwardee2.Foo_SPECIAL{
+       .assembly extern bz16628.typeforwardee2
+}
+
+.class public auto ansi beforefieldinit NSwForwardee2.Bar_SPECIAL
+       extends [mscorlib]System.Object
+{
+  .field public static int32 A
+  .method public hidebysig specialname rtspecialname 
+          instance void  .ctor() cil managed
+  {
+    // Code size       7 (0x7)
+    .maxstack  8
+    IL_0000:  ldarg.0
+    IL_0001:  call       instance void [mscorlib]System.Object::.ctor()
+    IL_0006:  ret
+  } // end of method Foo::.ctor
+
+  .method private hidebysig specialname rtspecialname static 
+          void  .cctor() cil managed
+  {
+    // Code size       8 (0x8)
+    .maxstack  8
+    IL_0000:  ldc.i4.s   320
+    IL_0002:  stsfld     int32 NSwForwardee2.Bar_SPECIAL::A
+    IL_0007:  ret
+  } // end of method Foo::.cctor
+} 
+
index 1971d2f4e4812fa82feb8fbed1c666537ce0a723..36453ea86b397061250c48d9d7b086bc1dca1d8d 100644 (file)
@@ -1,5 +1,6 @@
 using System;
 using System.Reflection;
+using System.Runtime.CompilerServices;
 
 [assembly: Test]
 
@@ -130,7 +131,8 @@ public class ClassMain
                Assert (ei.GetRemoveMethod ().GetCustomAttributes (true), false, 44);
                Assert (ei.GetRemoveMethod ().ReturnTypeCustomAttributes.GetCustomAttributes (true), false, 45);
                FieldInfo fi = typeof(Test_3).GetField ("e_1", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
-               Assert (fi.GetCustomAttributes (true), true, 46);
+               Assert (fi.GetCustomAttributes (typeof (CompilerGeneratedAttribute), true), true, 46);
+               Assert (fi.GetCustomAttributes (typeof (TestAttribute), true), true, 47);
 
                ei = typeof(Test_3).GetEvent ("e_2");
                Assert (ei.GetCustomAttributes (true), false, 51);
@@ -139,7 +141,8 @@ public class ClassMain
                Assert (ei.GetRemoveMethod ().GetCustomAttributes (true), true, 54);
                Assert (ei.GetRemoveMethod ().ReturnTypeCustomAttributes.GetCustomAttributes (true), false, 55);
                fi = typeof(Test_3).GetField ("e_2", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
-               Assert (fi.GetCustomAttributes (true), false, 56);
+               Assert (fi.GetCustomAttributes (typeof (CompilerGeneratedAttribute), true), true, 56);
+               Assert (fi.GetCustomAttributes (typeof (TestAttribute), true), false, 57);
 
                ei = typeof(Test_4).GetEvent ("e_2");
                Assert (ei.GetCustomAttributes (true), false, 71);
@@ -148,7 +151,8 @@ public class ClassMain
                Assert (ei.GetRemoveMethod ().GetCustomAttributes (true), false, 74);
                Assert (ei.GetRemoveMethod ().ReturnTypeCustomAttributes.GetCustomAttributes (true), true, 75);
                fi = typeof(Test_3).GetField ("e_2", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
-               Assert (fi.GetCustomAttributes (true), false, 76);
+               Assert (fi.GetCustomAttributes (typeof (CompilerGeneratedAttribute), true), true, 76);
+               Assert (fi.GetCustomAttributes (typeof (TestAttribute), true), false, 77);
 
                ei = typeof(Test_4).GetEvent ("e_3");
                Assert (ei.GetCustomAttributes (true), false, 81);
@@ -159,7 +163,8 @@ public class ClassMain
                Assert (ei.GetRemoveMethod ().ReturnTypeCustomAttributes.GetCustomAttributes (true), false, 86);
                Assert (ei.GetRemoveMethod ().GetParameters ()[0].GetCustomAttributes (true), true, 87);
                fi = typeof(Test_3).GetField ("e_2", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
-               Assert (fi.GetCustomAttributes (true), false, 88);
+               Assert (fi.GetCustomAttributes (typeof (CompilerGeneratedAttribute), true), true, 86);
+               Assert (fi.GetCustomAttributes (typeof (TestAttribute), true), false, 87);
 
                return failed ? 1 : 0;
        }
diff --git a/mcs/tests/test-941.cs b/mcs/tests/test-941.cs
new file mode 100644 (file)
index 0000000..f5d90c0
--- /dev/null
@@ -0,0 +1,30 @@
+public class GotoCodeFlowBug
+{
+       public static void Test (bool cond, out int x)
+       {
+               if (cond)
+               {
+                       goto Label;
+               }
+               Label:
+               x = 0;
+       }
+
+       public static void Test2 (bool cond, out int x)
+       {
+               if (cond)
+               {
+                       goto Label;
+               }
+               else
+               {
+                       goto Label;
+               }
+               Label:
+               x = 0;
+       }
+
+       public static void Main ()
+       {
+       }
+}
\ No newline at end of file
index 3dd99f5f2797f7c0db8b3b033fa08dedab20f9ca..4cf2e64196bd6b4a50cd1036eb0f2225dd3a5036 100644 (file)
@@ -13,6 +13,13 @@ public class ParserTest
                Console.WriteLine($"This should work but the compiler explodes if the string is too long!");            
        }
 
+       void Test3 ()
+       {
+               string field = "";
+               var l1 = $"\"{field.Replace("\"", "gg")}\"";
+               var l2 = $@"""{field.Replace("\"", "gg")}""";
+       }
+
        public static void Main()
        {
        }
index 0cbfab7639446a263dbd2ddf710b6179d65babaa..56e35f7709f857723d5c158e14535337098d1e93 100644 (file)
         <size>80</size>
       </method>
       <method name="Int32 Main()" attrs="150">
-        <size>1169</size>
+        <size>1309</size>
       </method>
       <method name="Void .ctor()" attrs="6278">
         <size>7</size>
       </method>
     </type>
   </test>
+  <test name="test-941.cs">
+    <type name="GotoCodeFlowBug">
+      <method name="Void Test(Boolean, Int32 ByRef)" attrs="150">
+        <size>17</size>
+      </method>
+      <method name="Void Test2(Boolean, Int32 ByRef)" attrs="150">
+        <size>23</size>
+      </method>
+      <method name="Void Main()" attrs="150">
+        <size>2</size>
+      </method>
+      <method name="Void .ctor()" attrs="6278">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
   <test name="test-95.cs">
     <type name="X">
       <method name="Int32 Main()" attrs="150">
       <method name="Void Test2()" attrs="129">
         <size>12</size>
       </method>
+      <method name="Void Test3()" attrs="129">
+        <size>62</size>
+      </method>
     </type>
   </test>
   <test name="test-interpolation-06.cs">
index 693318cbea7e07fdb27df8413379a15d159e7ac0..af120d403ed56646c67d8ad8299c5779f5a6cb12 100644 (file)
@@ -47,7 +47,8 @@ net_4_5_dirs := \
        mdbrebase       \
        ikdasm          \
        mono-symbolicate        \
-       linker-analyzer
+       linker-analyzer \
+       btls
 
 build_SUBDIRS = gacutil security culevel cil-stringreplacer commoncryptogenerator
 net_4_5_SUBDIRS = gacutil
diff --git a/mcs/tools/btls/AssemblyInfo.cs b/mcs/tools/btls/AssemblyInfo.cs
new file mode 100644 (file)
index 0000000..06f8d61
--- /dev/null
@@ -0,0 +1,26 @@
+using System;
+using System.Diagnostics;
+using System.Reflection;
+using System.Resources;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+[assembly: AssemblyTitle ("btls-cert-sync")]
+[assembly: AssemblyDescription ("btls-cert-sync")]
+[assembly: AssemblyDefaultAlias ("btls-cert-sync")]
+
+[assembly: AssemblyCompany (Consts.MonoCompany)]
+[assembly: AssemblyProduct (Consts.MonoProduct)]
+[assembly: AssemblyCopyright (Consts.MonoCopyright)]
+[assembly: AssemblyVersion (Consts.FxVersion)]
+[assembly: AssemblyFileVersion (Consts.FxFileVersion)]
+[assembly: SatelliteContractVersion (Consts.FxVersion)]
+[assembly: AssemblyInformationalVersion (Consts.FxFileVersion)]
+
+[assembly: CLSCompliant (true)]
+[assembly: NeutralResourcesLanguage ("en-US")]
+
+[assembly: ComVisible (false)]
+
+[assembly: AssemblyDelaySign (true)]
+[assembly: AssemblyKeyFile ("../../class/mono.pub")]
diff --git a/mcs/tools/btls/Makefile b/mcs/tools/btls/Makefile
new file mode 100644 (file)
index 0000000..b871a0f
--- /dev/null
@@ -0,0 +1,9 @@
+thisdir = tools/btls
+SUBDIRS = 
+include ../../build/rules.make
+
+LOCAL_MCS_FLAGS =
+LIB_REFS = System Mono.Security Mono.Btls.Interface
+PROGRAM = btls-cert-sync.exe
+
+include ../../build/executable.make
diff --git a/mcs/tools/btls/btls-cert-sync.cs b/mcs/tools/btls/btls-cert-sync.cs
new file mode 100644 (file)
index 0000000..fcdc708
--- /dev/null
@@ -0,0 +1,61 @@
+using System;
+using System.IO;
+using System.Text;
+using System.Security.Cryptography.X509Certificates;
+using MNS = Mono.Net.Security;
+
+namespace Mono.Btls
+{
+       static class BtlsCertSync
+       {
+               static void Main (string[] args)
+               {
+                       if (!MNS.MonoTlsProviderFactory.IsBtlsSupported ()) {
+                               Console.Error.WriteLine ("BTLS is not supported in this runtime!");
+                               Environment.Exit (255);
+                       }
+
+                       var configPath = Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData);
+                       configPath = Path.Combine (configPath, ".mono");
+
+                       var oldStorePath = Path.Combine (configPath, "certs", "Trust");
+                       var newStorePath = MonoBtlsX509StoreManager.GetStorePath (MonoBtlsX509StoreType.UserTrustedRoots);
+
+                       if (!Directory.Exists (oldStorePath)) {
+                               Console.WriteLine ("Old trust store {0} does not exist.");
+                               Environment.Exit (255);
+                       }
+
+                       if (Directory.Exists (newStorePath))
+                               Directory.Delete (newStorePath, true);
+                       Directory.CreateDirectory (newStorePath);
+
+                       var oldfiles = Directory.GetFiles (oldStorePath, "*.cer");
+                       Console.WriteLine ("Found {0} files in the old store.", oldfiles.Length);
+
+                       foreach (var file in oldfiles) {
+                               Console.WriteLine ("Converting {0}.", file);
+                               var data = File.ReadAllBytes (file);
+                               using (var x509 = MonoBtlsX509.LoadFromData (data, MonoBtlsX509Format.DER)) {
+                                       ConvertToNewFormat (newStorePath, x509);
+                               }
+                       }
+               }
+
+               static void ConvertToNewFormat (string root, MonoBtlsX509 x509)
+               {
+                       long hash = x509.GetSubjectNameHash ();
+
+                       string newName;
+                       int index = 0;
+                       do {
+                               newName = Path.Combine (root, string.Format ("{0:x8}.{1}", hash, index++));
+                       } while (File.Exists (newName));
+                       Console.WriteLine ("  new name: {0}", newName);
+
+                       using (var stream = new FileStream (newName, FileMode.Create))
+                       using (var bio = MonoBtlsBio.CreateMonoStream (stream))
+                                x509.ExportAsPEM (bio, true);
+               }
+       }
+}
diff --git a/mcs/tools/btls/btls-cert-sync.exe.sources b/mcs/tools/btls/btls-cert-sync.exe.sources
new file mode 100644 (file)
index 0000000..706d78f
--- /dev/null
@@ -0,0 +1,4 @@
+../../build/common/SR.cs
+../../build/common/Consts.cs
+AssemblyInfo.cs
+btls-cert-sync.cs
index f177c17ef3a5215b60d576381f6959ff3602b474..b9262adae0c7c88c205d58cfc235ed3d615723f7 100644 (file)
@@ -14,7 +14,7 @@ namespace Xamarin {
 
        public static class CommonCryptor {
                
-               static public void Generate (string namespaceName, string typeName, string baseTypeName, string ccAlgorithmName, string feedbackSize = "8", string ctorInitializers = null)
+               static public void Generate (string namespaceName, string typeName, string baseTypeName, string ccAlgorithmName, string feedbackSize = "8", string ctorInitializers = null, string decryptorInitializers = null, string encryptorInitializers = null, string properties = null)
                {
                        string template = @"// Generated file to bind CommonCrypto cipher algorithms - DO NOT EDIT
 //
@@ -38,7 +38,9 @@ namespace %NAMESPACE% {
                        FeedbackSizeValue = %FEEDBACKSIZE%;
                        %CTOR_INIT%
                }
-               
+
+               %PROPERTIES%
+
                public override void GenerateIV ()
                {
                        IVValue = KeyBuilder.IV (BlockSizeValue >> 3);
@@ -51,6 +53,8 @@ namespace %NAMESPACE% {
                
                public override ICryptoTransform CreateDecryptor (byte[] rgbKey, byte[] rgbIV) 
                {
+                       %CREATEDECRYPTOR_INIT%
+
                        IntPtr decryptor = IntPtr.Zero;
                        switch (Mode) {
                        case CipherMode.CBC:
@@ -74,6 +78,8 @@ namespace %NAMESPACE% {
                
                public override ICryptoTransform CreateEncryptor (byte[] rgbKey, byte[] rgbIV) 
                {
+                       %CREATEENCRYPTOR_INIT%
+                       
                        IntPtr encryptor = IntPtr.Zero;
                        switch (Mode) {
                        case CipherMode.CBC:
@@ -98,6 +104,9 @@ namespace %NAMESPACE% {
                        
                        File.WriteAllText (typeName + ".g.cs", template.Replace ("%NAMESPACE%", namespaceName).
                                Replace ("%TYPE%", typeName).Replace ("%BASE%", baseTypeName).Replace("%FEEDBACKSIZE%", feedbackSize).Replace ("%CTOR_INIT%", ctorInitializers).
+                               Replace ("%CREATEDECRYPTOR_INIT%", decryptorInitializers).
+                               Replace ("%CREATEENCRYPTOR_INIT%", encryptorInitializers).
+                               Replace ("%PROPERTIES%", properties).
                                Replace ("%CCALGORITHM%", ccAlgorithmName.ToString ()));
                }
        }
index a7d13c8cb80c9738d0cd90f07c07eb333f031e62..4fb846fe8f74fa1a879236ddd0c660d9dd84f117 100644 (file)
@@ -42,7 +42,13 @@ namespace Xamarin {
                        // mscorlib replacements
                        CommonCryptor.Generate ("System.Security.Cryptography", "DESCryptoServiceProvider", "DES", "DES");
                        CommonCryptor.Generate ("System.Security.Cryptography", "TripleDESCryptoServiceProvider", "TripleDES", "TripleDES");
-                       CommonCryptor.Generate ("System.Security.Cryptography", "RC2CryptoServiceProvider", "RC2", "RC2", ctorInitializers: "LegalKeySizesValue = new[] { new KeySizes(40, 128, 8) };");
+
+                       const string checkUseSalt = "if (UseSalt) throw new NotImplementedException (\"UseSalt=true is not implemented on Mono yet\");";
+                       CommonCryptor.Generate ("System.Security.Cryptography", "RC2CryptoServiceProvider", "RC2", "RC2",
+                               ctorInitializers: "LegalKeySizesValue = new[] { new KeySizes(40, 128, 8) };",
+                               decryptorInitializers: checkUseSalt,
+                               encryptorInitializers: checkUseSalt,
+                               properties: "public bool UseSalt { get; set; }");
                        // Rijndael supports block sizes that are not available in AES - as such it does not use the same generated code
                        // but has it's own version, using AES (128 bits block size) and falling back to managed (192/256 bits block size)
 
index 7636c2b204f4e6ed8cfc300f30bbe2ccca2e6268..cf6b17771074300da5e30245ccf685e92d93488a 100644 (file)
@@ -1155,11 +1155,14 @@ namespace CorCompare
                                string direction = first && HasExtensionParameter ? "this" : "in";
                                first = false;
 
-                               if (parameter.ParameterType is ByReferenceType)
+                               var pt = parameter.ParameterType;
+                               var brt = pt as ByReferenceType;
+                               if (brt != null) {
                                        direction = parameter.IsOut ? "out" : "ref";
+                                       pt = brt.ElementType;
+                               }
 
-                               TypeReference t = parameter.ParameterType;
-                               AddAttribute ("type", Utils.CleanupTypeName (t));
+                               AddAttribute ("type", Utils.CleanupTypeName (pt));
 
                                if (parameter.IsOptional) {
                                        AddAttribute ("optional", "true");
@@ -1538,13 +1541,15 @@ namespace CorCompare
 
                                ParameterDefinition info = infos [i];
 
+                               string modifier = string.Empty;
                                if (info.ParameterType.IsByReference) {
-                                       string modifier;
-                                       if ((info.Attributes & (ParameterAttributes.Out | ParameterAttributes.In)) == ParameterAttributes.Out)
+                                       if ((info.Attributes & ParameterAttributes.In) != 0)
+                                               modifier = "in";
+                                       else if ((info.Attributes & ParameterAttributes.Out) != 0)
                                                modifier = "out";
-                                       else
-                                               modifier = "ref";
+                               }
 
+                               if (modifier.Length > 0) {
                                        signature.Append (modifier);
                                        signature.Append (" ");
                                }
index f98314ecec7afb9db0957bb70edde80431c647b9..ff66d61364ca057147d7539772b5b7286c5628ea 100644 (file)
@@ -2,8 +2,8 @@ thisdir = tools/gacutil
 SUBDIRS = 
 include ../../build/rules.make
 
-LIB_REFS = Mono.Security
-LOCAL_MCS_FLAGS = -unsafe
+LIB_REFS = System Mono.Security System.Security
+LOCAL_MCS_FLAGS = -unsafe -define:NO_SYMBOL_WRITER
 
 PROGRAM = gacutil.exe
 
index 13f686e22c64ec5dadc09c136838db3ed7c74a43..47c4ac8df96bd44da12af6c98d5309da235cbc89 100644 (file)
@@ -14,7 +14,6 @@ using System;
 using System.IO;
 using System.Diagnostics;
 using System.Text;
-using System.Reflection;
 using System.Collections;
 using System.Globalization;
 using System.Runtime.InteropServices;
@@ -23,6 +22,8 @@ using System.Security.Cryptography;
 using Mono.Security;
 using Mono.Security.Cryptography;
 
+using IKVM.Reflection;
+
 namespace Mono.Tools {
 
        public class Driver {
@@ -48,6 +49,7 @@ namespace Mono.Tools {
 
                private static bool silent;
                static bool in_bootstrap;
+               private static Universe _universe;
 
                public static int Main (string [] args)
                {
@@ -244,7 +246,7 @@ namespace Mono.Tools {
                        AssemblyName an = null;
 
                        try {
-                               assembly = Assembly.LoadFrom (name);
+                               assembly = ReflectionOnlyLoadFrom (name);
                        } catch {
                                WriteLine (string.Format (failure_msg, name) + "The file specified is not a valid assembly.");
                                return false;
@@ -744,12 +746,27 @@ namespace Mono.Tools {
                        }
                }
 
+               private static Universe GetUniverse () {
+                       if (_universe == null) {
+                               _universe = new Universe (UniverseOptions.MetadataOnly);
+                       }
+                       return _universe;
+               }
+
+               private static Assembly ReflectionOnlyLoadFrom (string fileName)
+               {
+                       return GetUniverse ().LoadFile (fileName);
+               }
+               private static AssemblyName GetCorlibName ()
+               {
+                       return GetUniverse ().Mscorlib.GetName ();
+               }
+
                private static bool CheckReferencedAssemblies (AssemblyName an)
                {
-                       AppDomain d = null;
                        try {
-                               Assembly a = Assembly.LoadFrom (an.CodeBase);
-                               AssemblyName corlib = typeof (object).Assembly.GetName ();
+                               Assembly a = ReflectionOnlyLoadFrom (an.CodeBase);
+                               AssemblyName corlib = GetCorlibName ();
 
                                foreach (AssemblyName ref_an in a.GetReferencedAssemblies ()) {
                                        if (ref_an.Name == corlib.Name) // Just do a string compare so we can install on diff versions
@@ -763,12 +780,6 @@ namespace Mono.Tools {
                        } catch (Exception e) {
                                WriteLine (e.ToString ()); // This should be removed pre beta3
                                return false;
-                       } finally {
-                               if (d != null) {
-                                       try {
-                                               AppDomain.Unload (d);
-                                       } catch { }
-                               }
                        }
 
                        return true;
@@ -800,8 +811,8 @@ namespace Mono.Tools {
 
                static bool LoadConfig (bool quiet)
                {
-                       MethodInfo config = typeof (System.Environment).GetMethod ("GetMachineConfigPath",
-                               BindingFlags.Static | BindingFlags.NonPublic);
+                       System.Reflection.MethodInfo config = typeof (System.Environment).GetMethod ("GetMachineConfigPath",
+                               System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
 
                        if (config != null) {
                                string path = (string) config.Invoke (null, null);
@@ -832,7 +843,7 @@ namespace Mono.Tools {
 
                        // Note: MustVerify is based on the original token (by design). Public key
                        // remapping won't affect if the assembly is verified or not.
-                       if (StrongNameManager.MustVerify (an)) {
+                       if (StrongNameManager.MustVerify (new System.Reflection.AssemblyName (an.FullName))) {
                                RSA rsa = CryptoConvert.FromCapiPublicKeyBlob (publicKey, 12);
                                StrongName sn = new StrongName (rsa);
                                if (sn.Verify (assemblyFile)) {
@@ -899,20 +910,20 @@ namespace Mono.Tools {
                public static extern int symlink (string oldpath, string newpath);
 
                private static string GetGacDir () {
-                       PropertyInfo gac = typeof (System.Environment).GetProperty ("GacPath",
-                                       BindingFlags.Static|BindingFlags.NonPublic);
+                       System.Reflection.PropertyInfo gac = typeof (System.Environment).GetProperty ("GacPath",
+                                       System.Reflection.BindingFlags.Static|System.Reflection.BindingFlags.NonPublic);
                        if (gac == null) {
                                WriteLine ("ERROR: Mono runtime not detected, please use " +
                                                "the mono runtime for gacutil.exe");
                                Environment.Exit (1);
                        }
-                       MethodInfo get_gac = gac.GetGetMethod (true);
+                       System.Reflection.MethodInfo get_gac = gac.GetGetMethod (true);
                        return (string) get_gac.Invoke (null, null);
                }
 
                private static string GetLibDir () {
-                       MethodInfo libdir = typeof (System.Environment).GetMethod ("internalGetGacPath",
-                                       BindingFlags.Static|BindingFlags.NonPublic);
+                       System.Reflection.MethodInfo libdir = typeof (System.Environment).GetMethod ("internalGetGacPath",
+                                       System.Reflection.BindingFlags.Static|System.Reflection.BindingFlags.NonPublic);
                        if (libdir == null) {
                                WriteLine ("ERROR: Mono runtime not detected, please use " +
                                                "the mono runtime for gacutil.exe");
index 911afaf9d8219cd369a76a6269e559c1429cd238..4772378b43cb3ad9898901b636de031cacd48cbc 100644 (file)
@@ -1,2 +1,9 @@
 driver.cs
 ../security/StrongNameManager.cs
+../../../external/ikvm/reflect/*.cs
+../../../external/ikvm/reflect/Metadata/*.cs
+../../../external/ikvm/reflect/Emit/*.cs
+../../../external/ikvm/reflect/Reader/*.cs
+../../../external/ikvm/reflect/Writer/*.cs
+../../../external/ikvm/reflect/Impl/ITypeOwner.cs
+../../../external/ikvm/reflect/Impl/SymbolSupport.cs
index 396acc5a69eb9d4b15cbab8a7e160fe041adcd2a..31764d0efac7e6113a3689c233918c2aed052786 100644 (file)
                <type fullname="System.Reflection.MonoEventInfo" preserve="fields" />
                <type fullname="System.Reflection.MonoField" preserve="fields" />
                <type fullname="System.Reflection.MonoGenericClass" preserve="fields" />
-               <type fullname="System.Reflection.MonoGenericMethod" preserve="fields" />
-               <type fullname="System.Reflection.MonoGenericCMethod" preserve="fields" />
                <type fullname="System.Reflection.MonoMethod" preserve="fields" />
                <type fullname="System.Reflection.MonoMethodInfo" preserve="fields" />
                <type fullname="System.Reflection.MonoPropertyInfo" preserve="fields" />
                <type fullname="System.Reflection.Emit.MethodBuilder" preserve="fields" />
                <type fullname="System.Reflection.Emit.ModuleBuilder" preserve="fields">
                        <method name="Mono_GetGuid" />
+                       <method name="RuntimeResolve" />
                </type>
                <type fullname="System.Reflection.Emit.MonoResource" preserve="fields" />
                <type fullname="System.Reflection.Emit.MonoWin32Resource" preserve="fields" />
index 0c39910ff5ea06b2d5a538e7ebbda7b09f27f63b..9bf293d7f13fe527b221ceab7461a6c35e2a7d84 100644 (file)
@@ -69,29 +69,27 @@ namespace Mono.Linker.Steps {
                protected virtual void InitializeAssembly (AssemblyDefinition assembly)
                {
                        MarkAssembly (assembly);
-                       foreach (TypeDefinition type in assembly.MainModule.Types) {
-                               if (!Annotations.IsMarked (type))
-                                       continue;
 
+                       foreach (TypeDefinition type in assembly.MainModule.Types)
                                InitializeType (type);
-                       }
                }
 
                void InitializeType (TypeDefinition type)
                {
+                       if (type.HasNestedTypes) {
+                               foreach (var nested in type.NestedTypes)
+                                       InitializeType (nested);
+                       }
+
+                       if (!Annotations.IsMarked (type))
+                               return;
+
                        MarkType (type);
 
                        if (type.HasFields)
                                InitializeFields (type);
                        if (type.HasMethods)
                                InitializeMethods (type.Methods);
-
-                       if (type.HasNestedTypes) {
-                               foreach (var nested in type.NestedTypes) {
-                                       if (Annotations.IsMarked (nested))
-                                               InitializeType (nested);
-                               }
-                       }
                }
 
                void InitializeFields (TypeDefinition type)
index f7074361022d4314aa934b4e5954245d5adacf89..17ed9971f2f90fb1e8cc11851737175932c2d788 100644 (file)
@@ -70,6 +70,13 @@ MONO = \
        MONO_PATH="$(topdir)/class/lib/$(PROFILE)$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" \
        $(RUNTIME) $(RUNTIME_FLAGS)
 
+DIFF = diff -rup
+DIFF_QUIET = diff --brief
+ifeq ($(PLATFORM), win32)
+DIFF = diff -rupZ
+DIFF_QUIET = diff --brief -Z
+endif
+
 dist-local: dist-default dist-tests
 
 dist-tests:
@@ -160,7 +167,7 @@ check-monodocer-addNonGeneric: $(PROGRAM)
        $(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual Test/DocTest-addNonGeneric-v2.dll
        $(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual Test/DocTest-addNonGeneric-v2.dll
        $(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual Test/DocTest-addNonGeneric-v2.dll
-       diff -rup Test/en.expected-addNonGeneric Test/en.actual
+       $(DIFF) Test/en.expected-addNonGeneric Test/en.actual
 
 check-monodocer-dropns-classic: $(PROGRAM)
        # tests the simplest --dropns case, a single class where the root namespace was dropped.
@@ -168,7 +175,7 @@ check-monodocer-dropns-classic: $(PROGRAM)
        $(MAKE) Test/DocTest-DropNS-classic.dll
        $(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual Test/DocTest-DropNS-classic.dll --api-style=classic
        $(MAKE) update-monodocer-dropns-unified
-       diff -rup Test/en.expected-dropns-classic-v1 Test/en.actual
+       $(DIFF) Test/en.expected-dropns-classic-v1 Test/en.actual
 
 check-monodocer-dropns-multi: $(PROGRAM)
        -rm -Rf Test/en.actual
@@ -185,7 +192,7 @@ check-monodocer-dropns-multi: $(PROGRAM)
        $(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual $(MULTI-CLASSIC) --api-style=classic 
        $(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual $(MULTI-UNIFIED) --api-style=unified --dropns Test/DocTest-DropNS-unified.dll=MyFramework --dropns Test/DocTest-DropNS-unified-multitest.dll=MyFramework 
        
-       diff -rup Test/en.expected-dropns-multi Test/en.actual
+       $(DIFF) Test/en.expected-dropns-multi Test/en.actual
 
 
 check-monodocer-dropns-multi-withexisting: $(PROGRAM)
@@ -203,7 +210,7 @@ check-monodocer-dropns-multi-withexisting: $(PROGRAM)
        $(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual $(MULTI-CLASSIC) --api-style=classic 
        $(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual $(MULTI-UNIFIED) --api-style=unified --dropns Test/DocTest-DropNS-unified.dll=MyFramework --dropns Test/DocTest-DropNS-unified-multitest.dll=MyFramework 
        
-       diff -rup Test/en.expected-dropns-multi-withexisting Test/en.actual
+       $(DIFF) Test/en.expected-dropns-multi-withexisting Test/en.actual
 
 check-monodocer-dropns-delete: $(PROGRAM)
        -rm -Rf Test/en.actual
@@ -217,7 +224,7 @@ check-monodocer-dropns-delete: $(PROGRAM)
        $(MONO) $(PROGRAM) update --delete --exceptions=all -o Test/en.actual Test/DocTest-DropNS-classic-deletetest.dll --api-style=classic
        $(MAKE) Test/DocTest-DropNS-unified-deletetest-V2.dll
        $(MONO) $(PROGRAM) update --delete --exceptions=all -o Test/en.actual Test/DocTest-DropNS-unified-deletetest.dll --api-style=unified --dropns Test/DocTest-DropNS-unified-deletetest.dll=MyFramework
-       diff -rup Test/en.expected-dropns-delete Test/en.actual
+       $(DIFF) Test/en.expected-dropns-delete Test/en.actual
 
 check-monodocer-dropns-classic-withsecondary: $(PROGRAM)
        # tests case where a secondary assembly is included with a --dropns parameter
@@ -226,7 +233,7 @@ check-monodocer-dropns-classic-withsecondary: $(PROGRAM)
        $(MAKE) Test/DocTest-DropNS-classic-secondary.dll
        $(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual Test/DocTest-DropNS-classic.dll Test/DocTest-DropNS-classic-secondary.dll --api-style=classic
        $(MAKE) update-monodocer-dropns-unified-withsecondary
-       diff -rup Test/en.expected-dropns-classic-withsecondary Test/en.actual
+       $(DIFF) Test/en.expected-dropns-classic-withsecondary Test/en.actual
 
 update-monodocer-dropns-unified: $(PROGRAM)
        $(MAKE) Test/DocTest-DropNS-unified.dll
@@ -245,13 +252,13 @@ check-monodocer-internal-interface: $(PROGRAM)
        -rm -Rf Test/en.actual
        $(MAKE) Test/DocTest-InternalInterface.dll
        $(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual Test/DocTest-InternalInterface.dll
-       diff -rup Test/en.expected-internal-interface Test/en.actual
+       $(DIFF) Test/en.expected-internal-interface Test/en.actual
 
 check-monodocer-enumerations: $(PROGRAM)
        -rm -Rf Test/en.actual
        $(MAKE) Test/DocTest-enumerations.dll
        $(MONO) $(PROGRAM) update --exceptions=all -o Test/en.actual Test/DocTest-enumerations.dll
-       diff -rup Test/en.expected-enumerations Test/en.actual
+       $(DIFF) Test/en.expected-enumerations Test/en.actual
 
 check-monodocer-update: $(PROGRAM)
        find Test/en.expected -name \*.xml -exec rm "{}" \;
@@ -262,9 +269,9 @@ check-monodocer: $(PROGRAM)
        -rm -Rf Test/en.actual
        $(MAKE) Test/DocTest.dll-v1
        $(MONO) $(PROGRAM) update --debug --exceptions=all -o Test/en.actual Test/DocTest.dll
-       diff -rup Test/en.expected Test/en.actual
+       $(DIFF) Test/en.expected Test/en.actual
        $(MONO) $(PROGRAM) update --debug --exceptions=all -o Test/en.actual Test/DocTest.dll 
-       diff -rup Test/en.expected Test/en.actual
+       $(DIFF) Test/en.expected Test/en.actual
 
 check-monodocer-since-update: $(PROGRAM)
        find Test/en.expected.since -name \*.xml -exec rm "{}" \;
@@ -281,7 +288,7 @@ check-monodocer-since: $(PROGRAM)
        $(MAKE) Test/DocTest.dll-v2
        $(MONO) $(PROGRAM) --debug update --exceptions=all --since="Version 2.0" \
                -o Test/en.actual Test/DocTest.dll 
-       diff -rup Test/en.expected.since Test/en.actual
+       $(DIFF) Test/en.expected.since Test/en.actual
 
 check-monodocer-delete-update: $(PROGRAM)
        find Test/en.expected.delete -type f -exec rm "{}" \;
@@ -301,7 +308,7 @@ check-monodocer-delete: $(PROGRAM)
        $(MONO) $(PROGRAM) --debug update --exceptions=all -o Test/en.actual Test/DocTest.dll
        $(MAKE) Test/DocTest.dll-v1
        $(MONO) $(PROGRAM) --debug update -fno-assembly-versions --delete --exceptions=all -o Test/en.actual Test/DocTest.dll
-       diff -rup Test/en.expected.delete Test/en.actual
+       $(DIFF) Test/en.expected.delete Test/en.actual
 
 check-monodocer-importslashdoc-update: $(PROGRAM)
        find Test/en.expected.importslashdoc -name \*.xml -exec rm "{}" \;
@@ -314,7 +321,7 @@ check-monodocer-importslashdoc: $(PROGRAM)
        $(MAKE) Test/DocTest.dll-v1 TEST_CSCFLAGS=-doc:Test/DocTest.xml
        $(MONO) $(PROGRAM) --debug update --exceptions=all -i Test/DocTest.xml \
                -o Test/en.actual Test/DocTest.dll 
-       diff -rup Test/en.expected.importslashdoc Test/en.actual
+       $(DIFF) Test/en.expected.importslashdoc Test/en.actual
 
 check-monodocer-importecmadoc-update: $(PROGRAM)
        find Test/en.expected.importecmadoc -name \*.xml -exec rm "{}" \;
@@ -331,7 +338,7 @@ check-monodocer-importecmadoc: $(PROGRAM)
                '--type=System.Action`1' --type=System.AsyncCallback \
                --type=System.Environment --type=System.Array \
                -o Test/en.actual Test/DocTest.dll 
-       diff -rup Test/en.expected.importecmadoc Test/en.actual
+       $(DIFF) Test/en.expected.importecmadoc Test/en.actual
 
 check-mdoc-export-html-update: $(PROGRAM)
        find Test/html.expected -name \*.html -exec rm "{}" \;
@@ -342,7 +349,7 @@ check-mdoc-export-html: check-monodocer $(PROGRAM)
        rm -Rf Test/html.actual
        $(MONO) $(PROGRAM) export-html -o Test/html.actual \
                Test/en.expected.importslashdoc
-       diff -rup Test/html.expected Test/html.actual
+       $(DIFF) Test/html.expected Test/html.actual
 
 check-mdoc-export-html-with-version: $(PROGRAM)
        rm -Rf Test/html.actual.v0 Test/html.actual.since-with-v0 .v0.txt .v2.txt
@@ -352,12 +359,12 @@ check-mdoc-export-html-with-version: $(PROGRAM)
                Test/en.expected.since -with-version 0.0.0.0
        (cd Test/html.actual.v0            && find . -type f) | sort > .v0.txt
        (cd Test/html.actual.since-with-v0 && find . -type f) | sort > .v2.txt
-       diff -rup .v0.txt .v2.txt   # assert no types added
+       $(DIFF) .v0.txt .v2.txt   # assert no types added
 
 check-md-html-dir: $(PROGRAM)
        rm -Rf Test/html.actual
        $(MONO) $(PROGRAM) export-html -dest:Test/html.actual $(DIR) 
-       diff -rup Test/html.expected Test/html.actual
+       $(DIFF) Test/html.expected Test/html.actual
 
 check-mdoc-export-msxdoc-update:
        $(MONO) $(PROGRAM) export-msxdoc -o - Test/en.expected.importslashdoc \
@@ -365,7 +372,7 @@ check-mdoc-export-msxdoc-update:
 
 check-mdoc-export-msxdoc:
        $(MONO) $(PROGRAM) export-msxdoc -o - Test/en.expected.importslashdoc \
-               | diff --brief - Test/msxdoc-expected.importslashdoc.xml
+               | $(DIFF_QUIET) - Test/msxdoc-expected.importslashdoc.xml
 
 my_abs_top_srcdir = $(shell cd . && pwd)
 
@@ -383,13 +390,13 @@ check-mdoc-validate-update: $(PROGRAM)
 check-mdoc-validate: $(PROGRAM)
        $(MONO) $(PROGRAM) validate -f ecma Test/en.expected 2>&1 | \
                sed 's#file://$(my_abs_top_srcdir)/##g' | \
-               diff - Test/validate.check.monodocer
+               $(DIFF_QUIET) - Test/validate.check.monodocer
        $(MONO) $(PROGRAM) validate -f ecma Test/en.expected.importslashdoc 2>&1 | \
                sed 's#file://$(my_abs_top_srcdir)/##g' | \
-               diff --brief - Test/validate.check.monodocer.importslashdoc
+               $(DIFF_QUIET) - Test/validate.check.monodocer.importslashdoc
        $(MONO) $(PROGRAM) validate -f ecma Test/en.expected.since 2>&1 | \
                sed 's#file://$(my_abs_top_srcdir)/##g' | \
-               diff --brief - Test/validate.check.monodocer.since
+               $(DIFF_QUIET) - Test/validate.check.monodocer.since
 
 run-test-local: check-doc-tools
 
index ef681913e28e9d6fb4edd83d9f970e2b5748803a..447540860f50024ec14df5685b4cf49d5fc3218d 100755 (executable)
@@ -23,7 +23,6 @@ using System.Runtime.InteropServices;
 using System.Text;
 using IKVM.Reflection;
 using System.Linq;
-using System.Diagnostics;
 using System.Net;
 using System.Threading.Tasks;
 
@@ -31,6 +30,7 @@ class MakeBundle {
        static string output = "a.out";
        static string object_out = null;
        static List<string> link_paths = new List<string> ();
+       static Dictionary<string,string> libraries = new Dictionary<string,string> ();
        static bool autodeps = false;
        static bool keeptemp = false;
        static bool compile_only = false;
@@ -126,6 +126,33 @@ class MakeBundle {
                                cross_target = args [++i];
                                break;
 
+                       case "--library":
+                               if (i+1 == top){
+                                       Help (); 
+                                       return 1;
+                               }
+                               if (custom_mode){
+                                       Console.Error.WriteLine ("--library can only be used with --simple/--runtime/--cross mode");
+                                       Help ();
+                                       return 1;
+                               }
+                               var lspec = args [++i];
+                               var p = lspec.IndexOf (",");
+                               string alias, path;
+                               if (p == -1){
+                                       alias = Path.GetFileName (lspec);
+                                       path = lspec;
+                               } else {
+                                       alias = lspec.Substring (0, p);
+                                       path = lspec.Substring (p+1);
+                               }
+                               if (!File.Exists (path)){
+                                       Console.Error.WriteLine ($"The specified library file {path} does not exist");
+                                       return 1;
+                               }
+                               libraries [alias] = path;
+                               break;
+
                        case "--fetch-target":
                                if (i+1 == top){
                                        Help (); 
@@ -289,7 +316,7 @@ class MakeBundle {
                                        return 1;
                                }
                                var env = args [++i];
-                               var p = env.IndexOf ('=');
+                               p = env.IndexOf ('=');
                                if (p == -1)
                                        environment.Add (env, "");
                                else
@@ -359,11 +386,11 @@ class MakeBundle {
                                        }
                                }
                                
-                               Console.WriteLine ("Using runtime {0} for {1}", runtime, output);
                        }
                        GeneratePackage (files);
                }
-               
+               Console.WriteLine ("Generated {0}", output);
+
                return 0;
        }
 
@@ -581,6 +608,7 @@ class MakeBundle {
                }
                
                var maker = new PackageMaker (output);
+               Console.WriteLine ("Using runtime: " + runtime);
                maker.AddFile (runtime);
                
                foreach (var url in files){
@@ -588,9 +616,13 @@ class MakeBundle {
                        string aname = MakeBundle.GetAssemblyName (fname);
 
                        maker.Add ("assembly:" + aname, fname);
-                       if (File.Exists (fname + ".config"))
+                       Console.WriteLine ("     Assembly: " + fname);
+                       if (File.Exists (fname + ".config")){
                                maker.Add ("config:" + aname, fname + ".config");
+                               Console.WriteLine ("       Config: " + runtime);
+                       }
                }
+               
                if (!MaybeAddFile (maker, "systemconfig:", config_file) || !MaybeAddFile (maker, "machineconfig:", machine_config_file))
                        return false;
 
@@ -602,6 +634,12 @@ class MakeBundle {
                        foreach (var key in environment.Keys)
                                maker.AddStringPair ("env:" + key, key, environment [key]);
                }
+               if (libraries.Count > 0){
+                       foreach (var alias_and_path in libraries){
+                               Console.WriteLine ("     Library:  " + alias_and_path.Value);
+                               maker.Add ("library:" + alias_and_path.Key, alias_and_path.Value);
+                       }
+               }
                maker.Dump ();
                maker.Close ();
                return true;
@@ -854,7 +892,7 @@ void          mono_register_config_for_assembly (const char* assembly_name, cons
                                string monoPath = GetEnv("MONOPREFIX", @"C:\Program Files (x86)\Mono");
 
                                string[] includes = new string[] {winsdkPath + @"\Include\um", winsdkPath + @"\Include\shared", vsPath + @"\include", monoPath + @"\include\mono-2.0", "." };
-                               string[] libs = new string[] { winsdkPath + @"\Lib\winv6.3\um\x86" , vsPath + @"\lib" };
+                               // string[] libs = new string[] { winsdkPath + @"\Lib\winv6.3\um\x86" , vsPath + @"\lib" };
                                var linkLibraries = new string[] {  "kernel32.lib",
                                                                                                "version.lib",
                                                                                                "Ws2_32.lib",
@@ -1120,40 +1158,42 @@ void          mono_register_config_for_assembly (const char* assembly_name, cons
        {
                Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
                                   "Options:\n" +
-                                  "    --config F          Bundle system config file `F'\n" +
-                                  "    --config-dir D      Set MONO_CFG_DIR to `D'\n" +
-                                  "    --deps              Turns on automatic dependency embedding (default on simple)\n" +
-                                  "    -L path             Adds `path' to the search path for assemblies\n" +
-                                  "    --machine-config F  Use the given file as the machine.config for the application.\n" +
-                                  "    -o out              Specifies output filename\n" +
-                                  "    --nodeps            Turns off automatic dependency embedding (default on custom)\n" +
-                                  "    --skip-scan         Skip scanning assemblies that could not be loaded (but still embed them).\n" +
-                                  "    --i18n ENCODING     none, all or comma separated list of CJK, MidWest, Other, Rare, West.\n" +
-                                  "    -v                  Verbose output\n" + 
+                                  "    --config F           Bundle system config file `F'\n" +
+                                  "    --config-dir D       Set MONO_CFG_DIR to `D'\n" +
+                                  "    --deps               Turns on automatic dependency embedding (default on simple)\n" +
+                                  "    -L path              Adds `path' to the search path for assemblies\n" +
+                                  "    --machine-config F   Use the given file as the machine.config for the application.\n" +
+                                  "    -o out               Specifies output filename\n" +
+                                  "    --nodeps             Turns off automatic dependency embedding (default on custom)\n" +
+                                  "    --skip-scan          Skip scanning assemblies that could not be loaded (but still embed them).\n" +
+                                  "    --i18n ENCODING      none, all or comma separated list of CJK, MidWest, Other, Rare, West.\n" +
+                                  "    -v                   Verbose output\n" + 
                                   "\n" + 
                                   "--simple   Simple mode does not require a C toolchain and can cross compile\n" + 
-                                  "    --cross TARGET      Generates a binary for the given TARGET\n"+
-                                  "    --local-targets     Lists locally available targets\n" +
-                                  "    --list-targets      Lists available targets on the remote server\n" +
-                                  "    --options OPTIONS   Embed the specified Mono command line options on target\n" +
-                                  "    --runtime RUNTIME   Manually specifies the Mono runtime to use\n" +
-                                  "    --target-server URL Specified a server to download targets from, default is " + target_server + "\n" +
-                                  "    --env KEY=VALUE     Hardcodes an environment variable for the target\n" +
+                                  "    --cross TARGET       Generates a binary for the given TARGET\n"+
+                                  "    --env KEY=VALUE      Hardcodes an environment variable for the target\n" +
+                                  "    --library [LIB,]PATH Bundles the specified dynamic library to be used at runtime\n" +
+                                  "                         LIB is optional shortname for file located at PATH\n" + 
+                                  "    --list-targets       Lists available targets on the remote server\n" +
+                                  "    --local-targets      Lists locally available targets\n" +
+                                  "    --options OPTIONS    Embed the specified Mono command line options on target\n" +
+                                  "    --runtime RUNTIME    Manually specifies the Mono runtime to use\n" +
+                                  "    --target-server URL  Specified a server to download targets from, default is " + target_server + "\n" +
                                   "\n" +
                                   "--custom   Builds a custom launcher, options for --custom\n" +
-                                  "    -c                  Produce stub only, do not compile\n" +
-                                  "    -oo obj             Specifies output filename for helper object file\n" +
+                                  "    -c                   Produce stub only, do not compile\n" +
+                                  "    -oo obj              Specifies output filename for helper object file\n" +
                                   "    --dos2unix[=true|false]\n" +
-                                  "                        When no value provided, or when `true` specified\n" +
-                                  "                        `dos2unix` will be invoked to convert paths on Windows.\n" +
-                                  "                        When `--dos2unix=false` used, dos2unix is NEVER used.\n" +
-                                  "    --keeptemp          Keeps the temporary files\n" +
-                                  "    --static            Statically link to mono libs\n" +
-                                  "    --nomain            Don't include a main() function, for libraries\n" +
-                                  "    --custom-main C     Link the specified compilation unit (.c or .obj) with entry point/init code\n" +
-                                  "    -z                  Compress the assemblies before embedding.\n" +
-                                  "    --static-ctor ctor  Add a constructor call to the supplied function.\n" +
-                                  "                        You need zlib development headers and libraries.\n");
+                                  "                         When no value provided, or when `true` specified\n" +
+                                  "                         `dos2unix` will be invoked to convert paths on Windows.\n" +
+                                  "                         When `--dos2unix=false` used, dos2unix is NEVER used.\n" +
+                                  "    --keeptemp           Keeps the temporary files\n" +
+                                  "    --static             Statically link to mono libs\n" +
+                                  "    --nomain             Don't include a main() function, for libraries\n" +
+                                  "    --custom-main C      Link the specified compilation unit (.c or .obj) with entry point/init code\n" +
+                                  "    -z                   Compress the assemblies before embedding.\n" +
+                                  "    --static-ctor ctor   Add a constructor call to the supplied function.\n" +
+                                  "                         You need zlib development headers and libraries.\n");
        }
 
        [DllImport ("libc")]
index 884bea5a114ff7b5c0f82e9ff1f912cd0d0bce52..df2fb2702a3873ac3686354a19d5f0200f233e14 100644 (file)
@@ -5,9 +5,9 @@ include ../../build/rules.make
 PROGRAM = mono-symbolicate.exe
 
 LOCAL_MCS_FLAGS = \
-       /D:NO_AUTHENTICODE
+       /D:NO_AUTHENTICODE /D:CECIL
 
-LIB_REFS = Mono.Cecil Mono.Cecil.Mdb System.Xml System.Core System
+LIB_REFS = System.Xml System.Core System
 
 include ../../build/executable.make
 
@@ -26,7 +26,7 @@ SYMBOLICATE_EXPECTED_FILE = Test/symbolicate.expected
 CHECK_DIFF = @\
        $(MONO) $(TEST_EXE) > $(STACKTRACE_FILE); \
        $(MONO) $(LIB_PATH)/$(PROGRAM) $(MSYM_DIR) $(STACKTRACE_FILE) > $(SYMBOLICATE_RAW_FILE); \
-       sed "s/) .* in .*\/mcs\//) in mcs\//" $(SYMBOLICATE_RAW_FILE) | sed '/\[MVID\]/d' | sed '/\[AOTID\]/d' > $(SYMBOLICATE_RESULT_FILE); \
+       cat $(SYMBOLICATE_RAW_FILE) | tr '\\' '/' | sed "s/) .* in .*\/mcs\//) in mcs\//" | sed '/\[MVID\]/d' | sed '/\[AOTID\]/d' > $(SYMBOLICATE_RESULT_FILE); \
        DIFF=$$(diff -up $(SYMBOLICATE_EXPECTED_FILE) $(SYMBOLICATE_RESULT_FILE)); \
        if [ ! -z "$$DIFF" ]; then \
                echo "Symbolicate tests failed."; \
index 6cb8042e9c528e3bbcb3dd6b6710452a9dce37df..da336168f902e41e14155acdcacc879b9043d180 100644 (file)
@@ -5,3 +5,106 @@ StackFrameData.cs
 SymbolManager.cs
 Logger.cs
 ../../class/Mono.Options/Mono.Options/Options.cs
+
+../../../external/cecil/Mono/*.cs
+../../../external/cecil/Mono.Cecil/ArrayType.cs
+../../../external/cecil/Mono.Cecil/AssemblyDefinition.cs
+../../../external/cecil/Mono.Cecil/AssemblyFlags.cs
+../../../external/cecil/Mono.Cecil/AssemblyHashAlgorithm.cs
+../../../external/cecil/Mono.Cecil/AssemblyLinkedResource.cs
+../../../external/cecil/Mono.Cecil/AssemblyNameDefinition.cs
+../../../external/cecil/Mono.Cecil/AssemblyNameReference.cs
+../../../external/cecil/Mono.Cecil/AssemblyReader.cs
+../../../external/cecil/Mono.Cecil/AssemblyWriter.cs
+../../../external/cecil/Mono.Cecil/BaseAssemblyResolver.cs
+../../../external/cecil/Mono.Cecil/CallSite.cs
+../../../external/cecil/Mono.Cecil/CustomAttribute.cs
+../../../external/cecil/Mono.Cecil/DefaultAssemblyResolver.cs
+../../../external/cecil/Mono.Cecil/EmbeddedResource.cs
+../../../external/cecil/Mono.Cecil/EventAttributes.cs
+../../../external/cecil/Mono.Cecil/EventDefinition.cs
+../../../external/cecil/Mono.Cecil/EventReference.cs
+../../../external/cecil/Mono.Cecil/ExportedType.cs
+../../../external/cecil/Mono.Cecil/FieldAttributes.cs
+../../../external/cecil/Mono.Cecil/FieldDefinition.cs
+../../../external/cecil/Mono.Cecil/FieldReference.cs
+../../../external/cecil/Mono.Cecil/FileAttributes.cs
+../../../external/cecil/Mono.Cecil/FunctionPointerType.cs
+../../../external/cecil/Mono.Cecil/GenericInstanceMethod.cs
+../../../external/cecil/Mono.Cecil/GenericInstanceType.cs
+../../../external/cecil/Mono.Cecil/GenericParameter.cs
+../../../external/cecil/Mono.Cecil/GenericParameterAttributes.cs
+../../../external/cecil/Mono.Cecil/IConstantProvider.cs
+../../../external/cecil/Mono.Cecil/ICustomAttributeProvider.cs
+../../../external/cecil/Mono.Cecil/IGenericInstance.cs
+../../../external/cecil/Mono.Cecil/IGenericParameterProvider.cs
+../../../external/cecil/Mono.Cecil/IMarshalInfoProvider.cs
+../../../external/cecil/Mono.Cecil/IMemberDefinition.cs
+../../../external/cecil/Mono.Cecil/IMetadataScope.cs
+../../../external/cecil/Mono.Cecil/IMetadataTokenProvider.cs
+../../../external/cecil/Mono.Cecil/IMethodSignature.cs
+../../../external/cecil/Mono.Cecil/Import.cs
+../../../external/cecil/Mono.Cecil/LinkedResource.cs
+../../../external/cecil/Mono.Cecil/ManifestResourceAttributes.cs
+../../../external/cecil/Mono.Cecil/MarshalInfo.cs
+../../../external/cecil/Mono.Cecil/MemberDefinitionCollection.cs
+../../../external/cecil/Mono.Cecil/MemberReference.cs
+../../../external/cecil/Mono.Cecil/MetadataResolver.cs
+../../../external/cecil/Mono.Cecil/MetadataSystem.cs
+../../../external/cecil/Mono.Cecil/MethodAttributes.cs
+../../../external/cecil/Mono.Cecil/MethodCallingConvention.cs
+../../../external/cecil/Mono.Cecil/MethodDefinition.cs
+../../../external/cecil/Mono.Cecil/MethodImplAttributes.cs
+../../../external/cecil/Mono.Cecil/MethodReference.cs
+../../../external/cecil/Mono.Cecil/MethodReturnType.cs
+../../../external/cecil/Mono.Cecil/MethodSemanticsAttributes.cs
+../../../external/cecil/Mono.Cecil/MethodSpecification.cs
+../../../external/cecil/Mono.Cecil/Modifiers.cs
+../../../external/cecil/Mono.Cecil/ModuleDefinition.cs
+../../../external/cecil/Mono.Cecil/ModuleKind.cs
+../../../external/cecil/Mono.Cecil/ModuleReference.cs
+../../../external/cecil/Mono.Cecil/NativeType.cs
+../../../external/cecil/Mono.Cecil/ParameterAttributes.cs
+../../../external/cecil/Mono.Cecil/ParameterDefinition.cs
+../../../external/cecil/Mono.Cecil/ParameterDefinitionCollection.cs
+../../../external/cecil/Mono.Cecil/ParameterReference.cs
+../../../external/cecil/Mono.Cecil/PinnedType.cs
+../../../external/cecil/Mono.Cecil/PInvokeAttributes.cs
+../../../external/cecil/Mono.Cecil/PInvokeInfo.cs
+../../../external/cecil/Mono.Cecil/PointerType.cs
+../../../external/cecil/Mono.Cecil/PropertyAttributes.cs
+../../../external/cecil/Mono.Cecil/PropertyDefinition.cs
+../../../external/cecil/Mono.Cecil/PropertyReference.cs
+../../../external/cecil/Mono.Cecil/ReferenceType.cs
+../../../external/cecil/Mono.Cecil/Resource.cs
+../../../external/cecil/Mono.Cecil/SecurityDeclaration.cs
+../../../external/cecil/Mono.Cecil/SentinelType.cs
+../../../external/cecil/Mono.Cecil/TargetRuntime.cs
+../../../external/cecil/Mono.Cecil/Treatments.cs
+../../../external/cecil/Mono.Cecil/TypeAttributes.cs
+../../../external/cecil/Mono.Cecil/TypeDefinition.cs
+../../../external/cecil/Mono.Cecil/TypeDefinitionCollection.cs
+../../../external/cecil/Mono.Cecil/TypeParser.cs
+../../../external/cecil/Mono.Cecil/TypeReference.cs
+../../../external/cecil/Mono.Cecil/TypeSpecification.cs
+../../../external/cecil/Mono.Cecil/TypeSystem.cs
+../../../external/cecil/Mono.Cecil/VariantType.cs
+../../../external/cecil/Mono.Cecil/WindowsRuntimeProjections.cs
+../../../external/cecil/Mono.Cecil.Cil/*.cs
+../../../external/cecil/Mono.Cecil.Metadata/*.cs
+../../../external/cecil/Mono.Cecil.PE/*.cs
+../../../external/cecil/Mono.Collections.Generic/*.cs
+../../../external/cecil/Mono.Security.Cryptography/*.cs
+../../../external/cecil/System.Security.Cryptography/*.cs
+../../../external/cecil/symbols/mdb/Mono.Cecil.Mdb/MdbReader.cs
+../../../external/cecil/symbols/mdb/Mono.Cecil.Mdb/MdbWriter.cs
+../../../external/cecil/symbols/mdb/Mono.CompilerServices.SymbolWriter/*.cs
+../../../external/cecil/symbols/pdb/Microsoft.Cci.Pdb/*.cs
+../../../external/cecil/symbols/pdb/Mono.Cecil.Pdb/ISymUnmanagedDocumentWriter.cs
+../../../external/cecil/symbols/pdb/Mono.Cecil.Pdb/ISymUnmanagedWriter2.cs
+../../../external/cecil/symbols/pdb/Mono.Cecil.Pdb/ModuleMetadata.cs
+../../../external/cecil/symbols/pdb/Mono.Cecil.Pdb/PdbHelper.cs
+../../../external/cecil/symbols/pdb/Mono.Cecil.Pdb/PdbReader.cs
+../../../external/cecil/symbols/pdb/Mono.Cecil.Pdb/PdbWriter.cs
+../../../external/cecil/symbols/pdb/Mono.Cecil.Pdb/SymDocumentWriter.cs
+../../../external/cecil/symbols/pdb/Mono.Cecil.Pdb/SymWriter.cs
index ac2c2ef82c72d87c20a4c9a4a86869f290bd53b1..56797562e50592fbcf07f610d2bc5b2eed162755 100644 (file)
@@ -50,6 +50,7 @@ namespace Mono.Tools
                static string inputFile;
                static bool quiet;
                static bool userStore;
+               static bool btlsStore = false;
 
                static X509Certificate DecodeCertificate (string s)
                {
@@ -116,14 +117,19 @@ namespace Mono.Tools
                                return 0;
                        }
                                
-                       X509Stores stores = userStore ? X509StoreManager.CurrentUser : X509StoreManager.LocalMachine;
-                       X509CertificateCollection trusted = stores.TrustedRoot.Certificates;
+                       X509Stores stores;
+                       if (userStore)
+                               stores = btlsStore ? X509StoreManager.NewCurrentUser : X509StoreManager.CurrentUser;
+                       else
+                               stores = btlsStore ? X509StoreManager.NewLocalMachine : X509StoreManager.LocalMachine;
+                       X509Store store = stores.TrustedRoot;
+                       X509CertificateCollection trusted = store.Certificates;
                        int additions = 0;
                        WriteLine ("I already trust {0}, your new list has {1}", trusted.Count, roots.Count);
                        foreach (X509Certificate root in roots) {
                                if (!trusted.Contains (root)) {
                                        try {
-                                               stores.TrustedRoot.Import (root);
+                                               store.Import (root);
                                                WriteLine ("Certificate added: {0}", root.SubjectName);
                                                additions++;
                                        } catch (Exception e) {
@@ -145,7 +151,7 @@ namespace Mono.Tools
                                WriteLine ("{0} previously trusted certificates were removed.", removed.Count);
 
                                foreach (X509Certificate old in removed) {
-                                       stores.TrustedRoot.Remove (old);
+                                       store.Remove (old);
                                        WriteLine ("Certificate removed: {0}", old.SubjectName);
                                }
                        }
@@ -173,6 +179,9 @@ namespace Mono.Tools
                                case "--user":
                                        userStore = true;
                                        break;
+                               case "--btls":
+                                       btlsStore = true;
+                                       break;
                                default:
                                        WriteLine ("Unknown option '{0}'.", args[i]);
                                        return false;
@@ -228,4 +237,4 @@ namespace Mono.Tools
                        }
                }
        }
-}
\ No newline at end of file
+}
diff --git a/mcs/tools/xbuild/tests/Vbc/1.vbproj b/mcs/tools/xbuild/tests/Vbc/1.vbproj
new file mode 100644 (file)
index 0000000..c056fd1
--- /dev/null
@@ -0,0 +1,22 @@
+<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" >
+       
+       <ItemGroup>
+               <Input Include="test.vb" />
+               <Output Include="test.exe" />
+       </ItemGroup>
+       
+       <Target Name="Compile1" >
+               <Vbc
+                       Sources="@(Input)"
+                        OutputAssembly="@(Output)"
+               />
+       </Target>
+       
+       <Target Name="Clean" >
+               <Delete Files="@(Output)" />
+       </Target>
+       
+       <Target Name="Execute" >
+               <Exec Command="@(Output)" />
+       </Target>
+</Project>
diff --git a/mcs/tools/xbuild/tests/Vbc/2.vbproj b/mcs/tools/xbuild/tests/Vbc/2.vbproj
new file mode 100644 (file)
index 0000000..517036a
--- /dev/null
@@ -0,0 +1,13 @@
+<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTarget="Build">
+       
+       <ItemGroup>
+               <Input Include="test.vb" />
+               <Output Include="test.exe" />
+       </ItemGroup>
+       
+       <Target Name="Build" >
+               <Vbc
+                       Sources="@(Input)"
+               />
+       </Target>
+</Project>
diff --git a/mcs/tools/xbuild/tests/Vbc/test.vb b/mcs/tools/xbuild/tests/Vbc/test.vb
new file mode 100644 (file)
index 0000000..4f76bf6
--- /dev/null
@@ -0,0 +1,7 @@
+Imports System
+
+Public Module mainmod
+  Sub Main()
+    Console.WriteLine("Hello, world!")
+  End sub
+End Module
index 7bf7b5c3dedfa0122abb5dba36dd6120370cb231..651271c25f895fe4a332287feba54f1eed76833f 100644 (file)
@@ -2,11 +2,15 @@ if SUPPORT_SGEN
 sgen_dirs = sgen
 endif
 
+if BTLS
+btls_dirs = btls
+endif
+
 if CROSS_COMPILING
-SUBDIRS = arch utils io-layer cil metadata $(sgen_dirs) mini dis profiler
+SUBDIRS = $(btls_dirs) arch utils io-layer cil metadata $(sgen_dirs) mini dis profiler
 else
 if INSTALL_MONOTOUCH
-SUBDIRS = arch utils io-layer metadata $(sgen_dirs) mini profiler
+SUBDIRS = $(btls_dirs) arch utils io-layer metadata $(sgen_dirs) mini profiler
 
 monotouch-do-build:
        @list='$(SUBDIRS)'; for subdir in $$list; do \
@@ -30,7 +34,7 @@ monotouch-do-clean:
          (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$target); \
     done;
 else
-SUBDIRS = arch utils io-layer cil metadata $(sgen_dirs) mini dis tests unit-tests benchmark profiler
+SUBDIRS = $(btls_dirs) arch utils io-layer cil metadata $(sgen_dirs) mini dis tests unit-tests benchmark profiler
 endif
 endif
-DIST_SUBDIRS = arch utils io-layer cil metadata $(sgen_dirs) mini dis tests unit-tests benchmark profiler
+DIST_SUBDIRS = btls arch utils io-layer cil metadata $(sgen_dirs) mini dis tests unit-tests benchmark profiler
diff --git a/mono/btls/.gitignore b/mono/btls/.gitignore
new file mode 100644 (file)
index 0000000..545f630
--- /dev/null
@@ -0,0 +1,6 @@
+Makefile
+Makefile.in
+build/
+martin-test
+build-shared/
+build-static/
diff --git a/mono/btls/CMakeLists.txt b/mono/btls/CMakeLists.txt
new file mode 100644 (file)
index 0000000..aba7440
--- /dev/null
@@ -0,0 +1,93 @@
+cmake_minimum_required (VERSION 2.8.10)
+
+project (mono-btls)
+
+if(POLICY CMP0026)
+cmake_policy(SET CMP0026 NEW)
+endif()
+if(POLICY CMP0042)
+cmake_policy(SET CMP0042 NEW)
+endif()
+
+enable_language(C)
+enable_language(CXX)
+
+# FIXME: cmake's asm detection is broken when using xcrun.
+set (CMAKE_ASM_COMPILER "${CMAKE_C_COMPILER}")
+set (CMAKE_ASM_COMPILER_ARG1 "${CMAKE_C_COMPILER_ARG1}")
+set (CMAKE_ASM_COMPILER_ID "${CMAKE_C_COMPILER_ID}")
+enable_language(ASM)
+
+if (NOT "${BTLS_ARCH}" STREQUAL "")
+       message (WARNING "SET ARCH: ${BTLS_ARCH}")
+       set (CMAKE_SYSTEM_PROCESSOR "${BTLS_ARCH}")
+endif ()
+set (C_CXX_FLAGS "-Wall -Wsign-compare -Wmissing-field-initializers -ggdb -fvisibility=hidden")
+set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${C_CXX_FLAGS} ${BTLS_CFLAGS}")
+set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${C_CXX_FLAGS} ${BTLS_CFLAGS}")
+set (CMAKE_ASM_FLAGS "${CMAKE_ASM_FLAGS} ${BTLS_CFLAGS}")
+set (CMAKE_MACOSX_RPATH 1)
+set (MONO_BTLS 1)
+
+add_subdirectory (${BTLS_ROOT} boringssl)
+
+include_directories (
+       ${SRC_DIR}
+       ${BTLS_ROOT}/include
+)
+
+set (
+       MONO_BTLS_SOURCES
+
+       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-ctx.c
+       btls-ssl-ctx.h
+       btls-ssl.c
+       btls-ssl.h
+       btls-util.c
+       btls-util.h
+       btls-x509-chain.c
+       btls-x509-chain.h
+       btls-x509-crl.c
+       btls-x509-crl.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-ctx.c
+       btls-x509-store-ctx.h
+       btls-x509-store.c
+       btls-x509-store.h
+       btls-x509-verify-param.c
+       btls-x509-verify-param.h
+       btls-x509.c
+       btls-x509.h
+
+       btls-android-utils.c
+
+       ${BORINGSSL_OBJECTS}
+)
+
+if (BUILD_SHARED_LIBS)
+       add_library (mono-btls-shared SHARED ${MONO_BTLS_SOURCES})
+       set_target_properties (mono-btls-shared PROPERTIES RULE_LAUNCH_LINK
+               "${PROJECT_SOURCE_DIR}/create-object-library.sh ${CMAKE_BINARY_DIR} mono-btls-shared.txt mono-btls-shared-lo.txt libmono-btls-shared.a shared ${CMAKE_AR} ${CMAKE_RANLIB} <OBJECTS> --"
+       )
+else ()
+       add_library (mono-btls-static STATIC ${MONO_BTLS_SOURCES})
+       set_target_properties (mono-btls-static PROPERTIES RULE_LAUNCH_LINK
+               "${PROJECT_SOURCE_DIR}/create-object-library.sh ${CMAKE_BINARY_DIR} mono-btls-static.txt mono-btls-static-lo.txt libmono-btls-static.a static ${CMAKE_AR} ${CMAKE_RANLIB} <OBJECTS> --"
+       )
+endif ()
+
diff --git a/mono/btls/Makefile.am b/mono/btls/Makefile.am
new file mode 100644 (file)
index 0000000..0bb00bf
--- /dev/null
@@ -0,0 +1,66 @@
+BTLS_STATIC_LIST = build-static/mono-btls-static-lo.txt
+BTLS_SHARED_LIST = build-shared/mono-btls-shared-lo.txt
+
+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,)
+
+CMAKE_ARGS = -D CMAKE_INSTALL_PREFIX:PATH=$(prefix) -D BTLS_ROOT:PATH=$(BTLS_ROOT) \
+       -D SRC_DIR:PATH=$(abs_top_srcdir)/mono/btls -D BTLS_CFLAGS:STRING="$(BTLS_CFLAGS)"
+
+all-local: $(BTLS_STATIC_LIST) $(BTLS_SHARED_LIST)
+
+build-shared/Makefile:
+       -mkdir -p build-shared
+       (cd build-shared && $(CMAKE) $(CMAKE_ARGS) $(BTLS_CMAKE_ARGS) -DBUILD_SHARED_LIBS=1 $(abs_top_srcdir)/mono/btls)
+
+build-static/Makefile:
+       -mkdir -p build-static
+       (cd build-static && $(CMAKE) $(CMAKE_ARGS) $(BTLS_CMAKE_ARGS) $(abs_top_srcdir)/mono/btls)
+
+$(BTLS_STATIC_LIST): build-static/Makefile
+       $(MAKE) -C build-static $(CMAKE_VERBOSE)
+
+$(BTLS_SHARED_LIST): build-shared/Makefile
+       $(MAKE) -C build-shared $(CMAKE_VERBOSE)
+
+clean-local:
+       -rm -rf build-static
+       -rm -rf build-shared
+
diff --git a/mono/btls/btls-android-utils.c b/mono/btls/btls-android-utils.c
new file mode 100644 (file)
index 0000000..df30f85
--- /dev/null
@@ -0,0 +1,33 @@
+// Copied from Chromium: https://src.chromium.org/svn/trunk/src/base/os_compat_android.cc
+
+// Copyright (c) 2012 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#if defined(__ANDROID__)
+
+#include <asm/unistd.h>
+#include <errno.h>
+#include <math.h>
+#include <sys/stat.h>
+#include <sys/syscall.h>
+
+#if !defined(__LP64__)
+#include <time64.h>
+#endif
+
+#if !defined(__LP64__)
+// 32-bit Android has only timegm64() and not timegm().
+// We replicate the behaviour of timegm() when the result overflows time_t.
+time_t timegm(struct tm* const t) {
+  // time_t is signed on Android.
+  static const time_t kTimeMax = ~(1L << (sizeof(time_t) * CHAR_BIT - 1));
+  static const time_t kTimeMin = (1L << (sizeof(time_t) * CHAR_BIT - 1));
+  time64_t result = timegm64(t);
+  if (result < kTimeMin || result > kTimeMax)
+    return -1;
+  return result;
+}
+#endif
+
+#endif
diff --git a/mono/btls/btls-bio.c b/mono/btls/btls-bio.c
new file mode 100644 (file)
index 0000000..5af2d86
--- /dev/null
@@ -0,0 +1,206 @@
+//
+//  btls-bio.c
+//  MonoBtls
+//
+//  Created by Martin Baulig on 14/11/15.
+//  Copyright (c) 2015 Xamarin. All rights reserved.
+//
+
+#include <btls-ssl.h>
+#include <btls-bio.h>
+#include <errno.h>
+
+struct MonoBtlsBio {
+       const void *instance;
+       MonoBtlsReadFunc read_func;
+       MonoBtlsWriteFunc write_func;
+       MonoBtlsControlFunc control_func;
+};
+
+#if 0
+static void
+mono_debug (const char *message)
+{
+       BIO *bio_err;
+       bio_err = BIO_new_fp (stderr, BIO_NOCLOSE);
+       fprintf (stderr, "DEBUG: %s\n", message);
+       ERR_print_errors (bio_err);
+}
+#endif
+
+static int
+mono_read (BIO *bio, char *out, int outl)
+{
+       MonoBtlsBio *mono = (MonoBtlsBio *)bio->ptr;
+       int ret, wantMore;
+
+       if (!mono)
+               return -1;
+
+       ret = mono->read_func (mono->instance, out, outl, &wantMore);
+
+       if (ret < 0)
+               return -1;
+       if (ret > 0)
+               return ret;
+
+       if (wantMore) {
+               errno = EAGAIN;
+               BIO_set_retry_read (bio);
+               return -1;
+       }
+
+       return 0;
+}
+
+static int
+mono_write (BIO *bio, const char *in, int inl)
+{
+       MonoBtlsBio *mono = (MonoBtlsBio *)bio->ptr;
+
+       if (!mono)
+               return -1;
+
+       return mono->write_func (mono->instance, in, inl);
+}
+
+static long
+mono_ctrl (BIO *bio, int cmd, long num, void *ptr)
+{
+       MonoBtlsBio *mono = (MonoBtlsBio *)bio->ptr;
+
+       if (!mono)
+               return -1;
+
+       // fprintf (stderr, "mono_ctrl: %x - %lx - %p\n", cmd, num, ptr);
+       switch (cmd) {
+               case BIO_CTRL_FLUSH:
+                       return mono->control_func (mono->instance, MONO_BTLS_CONTROL_COMMAND_FLUSH, 0);
+               default:
+                       return -1;
+       }
+       return -1;
+}
+
+static int
+mono_new (BIO *bio)
+{
+       // mono_debug("mono_new!\n");
+       bio->init = 0;
+       bio->num = -1;
+       bio->flags = 0;
+       return 1;
+}
+
+static int
+mono_free (BIO *bio)
+{
+       // mono_debug ("mono_free!\n");
+       if (bio->ptr) {
+               MonoBtlsBio *mono = (MonoBtlsBio *)bio->ptr;
+
+               bio->ptr = NULL;
+               mono->instance = NULL;
+               mono->read_func = NULL;
+               mono->write_func = NULL;
+               mono->control_func = NULL;
+               free (mono);
+       }
+       return 1;
+}
+
+static const BIO_METHOD mono_method = {
+       BIO_TYPE_NONE, "mono", mono_write, mono_read,
+       NULL, NULL, mono_ctrl, mono_new, mono_free, NULL
+};
+
+BIO *
+mono_btls_bio_mono_new (void)
+{
+       BIO *bio;
+       MonoBtlsBio *monoBio;
+
+       bio = BIO_new (&mono_method);
+       if (!bio)
+               return NULL;
+
+       monoBio = calloc (1, sizeof (MonoBtlsBio));
+       if (!monoBio) {
+               BIO_free (bio);
+               return NULL;
+       }
+
+       bio->ptr = monoBio;
+       bio->init = 0;
+
+       return bio;
+}
+
+void
+mono_btls_bio_mono_initialize (BIO *bio, const void *instance,
+                             MonoBtlsReadFunc read_func, MonoBtlsWriteFunc write_func,
+                             MonoBtlsControlFunc control_func)
+{
+       MonoBtlsBio *monoBio = bio->ptr;
+
+       monoBio->instance = instance;
+       monoBio->read_func = read_func;
+       monoBio->write_func = write_func;
+       monoBio->control_func = control_func;
+
+       bio->init = 1;
+}
+
+int
+mono_btls_bio_read (BIO *bio, void *data, int len)
+{
+       return BIO_read (bio, data, len);
+}
+
+int
+mono_btls_bio_write (BIO *bio, const void *data, int len)
+{
+       return BIO_write (bio, data, len);
+}
+
+int
+mono_btls_bio_flush (BIO *bio)
+{
+       return BIO_flush (bio);
+}
+
+int
+mono_btls_bio_indent (BIO *bio, unsigned indent, unsigned max_indent)
+{
+       return BIO_indent (bio, indent, max_indent);
+}
+
+int
+mono_btls_bio_hexdump (BIO *bio, const uint8_t *data, int len, unsigned indent)
+{
+       return BIO_hexdump (bio, data, len, indent);
+}
+
+void
+mono_btls_bio_print_errors (BIO *bio)
+{
+       BIO_print_errors (bio);
+}
+
+void
+mono_btls_bio_free (BIO *bio)
+{
+       BIO_free (bio);
+}
+
+BIO *
+mono_btls_bio_mem_new (void)
+{
+       return BIO_new (BIO_s_mem ());
+}
+
+int
+mono_btls_bio_mem_get_data (BIO *bio, void **data)
+{
+       return (int)BIO_get_mem_data (bio, (char**)data);
+}
diff --git a/mono/btls/btls-bio.h b/mono/btls/btls-bio.h
new file mode 100644 (file)
index 0000000..d4429f6
--- /dev/null
@@ -0,0 +1,58 @@
+//
+//  btls-bio.h
+//  MonoBtls
+//
+//  Created by Martin Baulig on 14/11/15.
+//  Copyright (c) 2015 Xamarin. All rights reserved.
+//
+
+#ifndef __btls__btls_bio__
+#define __btls__btls_bio__
+
+#include <stdio.h>
+#include <btls-ssl.h>
+
+typedef enum {
+       MONO_BTLS_CONTROL_COMMAND_FLUSH = 1
+} MonoBtlsControlCommand;
+
+typedef int (* MonoBtlsReadFunc) (const void *instance, const void *buf, int size, int *wantMore);
+typedef int (* MonoBtlsWriteFunc) (const void *instance, const void *buf, int size);
+typedef long (* MonoBtlsControlFunc) (const void *instance, MonoBtlsControlCommand command, long arg);
+
+BIO *
+mono_btls_bio_mono_new (void);
+
+void
+mono_btls_bio_mono_initialize (BIO *bio, const void *instance,
+                             MonoBtlsReadFunc read_func, MonoBtlsWriteFunc write_func,
+                             MonoBtlsControlFunc control_func);
+
+int
+mono_btls_bio_read (BIO *bio, void *data, int len);
+
+int
+mono_btls_bio_write (BIO *bio, const void *data, int len);
+
+int
+mono_btls_bio_flush (BIO *bio);
+
+int
+mono_btls_bio_indent (BIO *bio, unsigned indent, unsigned max_indent);
+
+int
+mono_btls_bio_hexdump (BIO *bio, const uint8_t *data, int len, unsigned indent);
+
+void
+mono_btls_bio_print_errors (BIO *bio);
+
+void
+mono_btls_bio_free (BIO *bio);
+
+BIO *
+mono_btls_bio_mem_new (void);
+
+int
+mono_btls_bio_mem_get_data (BIO *bio, void **data);
+
+#endif /* defined(__btls__btls_bio__) */
diff --git a/mono/btls/btls-error.c b/mono/btls/btls-error.c
new file mode 100644 (file)
index 0000000..8ed950c
--- /dev/null
@@ -0,0 +1,35 @@
+//
+//  btls-error.c
+//  MonoBtls
+//
+//  Created by Martin Baulig on 6/19/16.
+//  Copyright Â© 2016 Xamarin. All rights reserved.
+//
+
+#include <btls-error.h>
+#include <assert.h>
+
+int
+mono_btls_error_peek_error (void)
+{
+       return ERR_peek_error ();
+}
+
+int
+mono_btls_error_get_error (void)
+{
+       return ERR_get_error ();
+}
+
+void
+mono_btls_error_clear_error (void)
+{
+       ERR_clear_error ();
+}
+
+void
+mono_btls_error_get_error_string_n (int error, char *buf, int len)
+{
+       ERR_error_string_n (error, buf, len);
+}
+
diff --git a/mono/btls/btls-error.h b/mono/btls/btls-error.h
new file mode 100644 (file)
index 0000000..6f791c3
--- /dev/null
@@ -0,0 +1,29 @@
+//
+//  btls-util.h
+//  MonoBtls
+//
+//  Created by Martin Baulig on 3/23/16.
+//  Copyright Â© 2016 Xamarin. All rights reserved.
+//
+
+#ifndef __btls__btls_error__
+#define __btls__btls_error__
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <openssl/ssl.h>
+
+int
+mono_btls_error_peek_error (void);
+
+int
+mono_btls_error_get_error (void);
+
+void
+mono_btls_error_clear_error (void);
+
+void
+mono_btls_error_get_error_string_n (int error, char *buf, int len);
+
+#endif /* __btls__btls_error__ */
diff --git a/mono/btls/btls-key.c b/mono/btls/btls-key.c
new file mode 100644 (file)
index 0000000..756f9c7
--- /dev/null
@@ -0,0 +1,62 @@
+//
+//  btls-key.c
+//  MonoBtls
+//
+//  Created by Martin Baulig on 3/7/16.
+//  Copyright Â© 2016 Xamarin. All rights reserved.
+//
+
+#include <btls-key.h>
+
+void
+mono_btls_key_free (EVP_PKEY *pkey)
+{
+       EVP_PKEY_free (pkey);
+}
+
+EVP_PKEY *
+mono_btls_key_up_ref (EVP_PKEY *pkey)
+{
+       return EVP_PKEY_up_ref (pkey);
+}
+
+int
+mono_btls_key_get_bits (EVP_PKEY *pkey)
+{
+       return EVP_PKEY_bits (pkey);
+}
+
+int
+mono_btls_key_is_rsa (EVP_PKEY *pkey)
+{
+       return pkey->type == EVP_PKEY_RSA;
+}
+
+int
+mono_btls_key_get_bytes (EVP_PKEY *pkey, uint8_t **buffer, int *size, int include_private_bits)
+{
+       size_t len;
+       RSA *rsa;
+       int ret;
+
+       *size = 0;
+       *buffer = NULL;
+
+       if (pkey->type != EVP_PKEY_RSA)
+               return 0;
+
+       rsa = EVP_PKEY_get1_RSA (pkey);
+       if (!rsa)
+               return 0;
+
+       if (include_private_bits)
+               ret = RSA_private_key_to_bytes (buffer, &len, rsa);
+       else
+               ret = RSA_public_key_to_bytes (buffer, &len, rsa);
+
+       if (ret != 1)
+               return 0;
+
+       *size = (int)len;
+       return 1;
+}
diff --git a/mono/btls/btls-key.h b/mono/btls/btls-key.h
new file mode 100644 (file)
index 0000000..85ee5b2
--- /dev/null
@@ -0,0 +1,32 @@
+//
+//  btls-key.h
+//  MonoBtls
+//
+//  Created by Martin Baulig on 3/7/16.
+//  Copyright Â© 2016 Xamarin. All rights reserved.
+//
+
+#ifndef __btls__btls_key__
+#define __btls__btls_key__
+
+#include <stdio.h>
+#include <btls-ssl.h>
+#include <btls-x509.h>
+
+void
+mono_btls_key_free (EVP_PKEY *pkey);
+
+EVP_PKEY *
+mono_btls_key_up_ref (EVP_PKEY *pkey);
+
+int
+mono_btls_key_get_bits (EVP_PKEY *pkey);
+
+int
+mono_btls_key_is_rsa (EVP_PKEY *pkey);
+
+int
+mono_btls_key_get_bytes (EVP_PKEY *pkey, uint8_t **buffer, int *size, int include_private_bits);
+
+#endif /* __btls__btls_key__ */
+
diff --git a/mono/btls/btls-pkcs12.c b/mono/btls/btls-pkcs12.c
new file mode 100644 (file)
index 0000000..d037ddb
--- /dev/null
@@ -0,0 +1,101 @@
+//
+//  btls-pkcs12.c
+//  MonoBtls
+//
+//  Created by Martin Baulig on 3/8/16.
+//  Copyright Â© 2016 Xamarin. All rights reserved.
+//
+
+#include <btls-pkcs12.h>
+#include <openssl/pkcs12.h>
+
+struct MonoBtlsPkcs12 {
+       STACK_OF(X509) *certs;
+       EVP_PKEY *private_key;
+       CRYPTO_refcount_t references;
+};
+
+MonoBtlsPkcs12 *
+mono_btls_pkcs12_new (void)
+{
+       MonoBtlsPkcs12 *pkcs12 = (MonoBtlsPkcs12 *)OPENSSL_malloc (sizeof (MonoBtlsPkcs12));
+       if (pkcs12 == NULL)
+               return NULL;
+
+       memset (pkcs12, 0, sizeof(MonoBtlsPkcs12));
+       pkcs12->certs = sk_X509_new_null ();
+       pkcs12->references = 1;
+       return pkcs12;
+}
+
+int
+mono_btls_pkcs12_get_count (MonoBtlsPkcs12 *pkcs12)
+{
+       return (int)sk_X509_num (pkcs12->certs);
+}
+
+X509 *
+mono_btls_pkcs12_get_cert (MonoBtlsPkcs12 *pkcs12, int index)
+{
+       X509 *cert;
+
+       if ((size_t)index >= sk_X509_num (pkcs12->certs))
+               return NULL;
+       cert = sk_X509_value (pkcs12->certs, index);
+       if (cert)
+               X509_up_ref (cert);
+       return cert;
+}
+
+STACK_OF(X509) *
+mono_btls_pkcs12_get_certs (MonoBtlsPkcs12 *pkcs12)
+{
+       return pkcs12->certs;
+}
+
+int
+mono_btls_pkcs12_free (MonoBtlsPkcs12 *pkcs12)
+{
+       if (!CRYPTO_refcount_dec_and_test_zero (&pkcs12->references))
+               return 0;
+
+       sk_X509_pop_free (pkcs12->certs, X509_free);
+       OPENSSL_free (pkcs12);
+       return 1;
+}
+
+MonoBtlsPkcs12 *
+mono_btls_pkcs12_up_ref (MonoBtlsPkcs12 *pkcs12)
+{
+       CRYPTO_refcount_inc (&pkcs12->references);
+       return pkcs12;
+}
+
+void
+mono_btls_pkcs12_add_cert (MonoBtlsPkcs12 *pkcs12, X509 *x509)
+{
+       X509_up_ref (x509);
+       sk_X509_push (pkcs12->certs, x509);
+}
+
+int
+mono_btls_pkcs12_import (MonoBtlsPkcs12 *pkcs12, const void *data, int len, const void *password)
+{
+       CBS cbs;
+       CBS_init (&cbs, data, len);
+       return PKCS12_get_key_and_certs (&pkcs12->private_key, pkcs12->certs, &cbs, password);
+}
+
+int
+mono_btls_pkcs12_has_private_key (MonoBtlsPkcs12 *pkcs12)
+{
+       return pkcs12->private_key != NULL;
+}
+
+EVP_PKEY *
+mono_btls_pkcs12_get_private_key (MonoBtlsPkcs12 *pkcs12)
+{
+       if (!pkcs12->private_key)
+               return NULL;
+       return EVP_PKEY_up_ref (pkcs12->private_key);
+}
diff --git a/mono/btls/btls-pkcs12.h b/mono/btls/btls-pkcs12.h
new file mode 100644 (file)
index 0000000..20c4fd9
--- /dev/null
@@ -0,0 +1,46 @@
+//
+//  btls-pkcs12.h
+//  MonoBtls
+//
+//  Created by Martin Baulig on 3/8/16.
+//  Copyright Â© 2016 Xamarin. All rights reserved.
+//
+
+#ifndef __btls__btls_pkcs12__
+#define __btls__btls_pkcs12__
+
+#include <stdio.h>
+#include <btls-ssl.h>
+#include <btls-x509.h>
+
+MonoBtlsPkcs12 *
+mono_btls_pkcs12_new (void);
+
+int
+mono_btls_pkcs12_get_count (MonoBtlsPkcs12 *pkcs12);
+
+X509 *
+mono_btls_pkcs12_get_cert (MonoBtlsPkcs12 *pkcs12, int index);
+
+STACK_OF(X509) *
+mono_btls_pkcs12_get_certs (MonoBtlsPkcs12 *pkcs12);
+
+int
+mono_btls_pkcs12_free (MonoBtlsPkcs12 *pkcs12);
+
+MonoBtlsPkcs12 *
+mono_btls_pkcs12_up_ref (MonoBtlsPkcs12 *pkcs12);
+
+void
+mono_btls_pkcs12_add_cert (MonoBtlsPkcs12 *pkcs12, X509 *x509);
+
+int
+mono_btls_pkcs12_import (MonoBtlsPkcs12 *pkcs12, const void *data, int len, const void *password);
+
+int
+mono_btls_pkcs12_has_private_key (MonoBtlsPkcs12 *pkcs12);
+
+EVP_PKEY *
+mono_btls_pkcs12_get_private_key (MonoBtlsPkcs12 *pkcs12);
+
+#endif /* __btls__btls_pkcs12__ */
diff --git a/mono/btls/btls-ssl-ctx.c b/mono/btls/btls-ssl-ctx.c
new file mode 100644 (file)
index 0000000..ddbb02f
--- /dev/null
@@ -0,0 +1,255 @@
+//
+//  btls-ssl-ctx.c
+//  MonoBtls
+//
+//  Created by Martin Baulig on 4/11/16.
+//  Copyright Â© 2016 Xamarin. All rights reserved.
+//
+
+#include <btls-ssl-ctx.h>
+#include <btls-x509-verify-param.h>
+
+struct MonoBtlsSslCtx {
+       CRYPTO_refcount_t references;
+       SSL_CTX *ctx;
+       BIO *bio;
+       BIO *debug_bio;
+       void *instance;
+       MonoBtlsVerifyFunc verify_func;
+       MonoBtlsSelectFunc select_func;
+};
+
+#define debug_print(ptr,message) \
+do { if (mono_btls_ssl_ctx_is_debug_enabled(ptr)) \
+mono_btls_ssl_ctx_debug_printf (ptr, "%s:%d:%s(): " message, __FILE__, __LINE__, \
+       __func__); } while (0)
+
+#define debug_printf(ptr,fmt, ...) \
+do { if (mono_btls_ssl_ctx_is_debug_enabled(ptr)) \
+mono_btls_ssl_ctx_debug_printf (ptr, "%s:%d:%s(): " fmt, __FILE__, __LINE__, \
+       __func__, __VA_ARGS__); } while (0)
+
+void ssl_cipher_preference_list_free (struct ssl_cipher_preference_list_st *cipher_list);
+
+int
+mono_btls_ssl_ctx_is_debug_enabled (MonoBtlsSslCtx *ctx)
+{
+       return ctx->debug_bio != NULL;
+}
+
+int
+mono_btls_ssl_ctx_debug_printf (MonoBtlsSslCtx *ctx, const char *format, ...)
+{
+       va_list args;
+       int ret;
+
+       if (!ctx->debug_bio)
+               return 0;
+
+       va_start (args, format);
+       ret = mono_btls_debug_printf (ctx->debug_bio, format, args);
+       va_end (args);
+       return ret;
+}
+
+MonoBtlsSslCtx *
+mono_btls_ssl_ctx_new (void)
+{
+       MonoBtlsSslCtx *ctx;
+
+       ctx = OPENSSL_malloc (sizeof (MonoBtlsSslCtx));
+       if (!ctx)
+               return NULL;
+
+       memset (ctx, 0, sizeof (MonoBtlsSslCtx));
+       ctx->references = 1;
+       ctx->ctx = SSL_CTX_new (TLS_method ());
+       return ctx;
+}
+
+MonoBtlsSslCtx *
+mono_btls_ssl_ctx_up_ref (MonoBtlsSslCtx *ctx)
+{
+       CRYPTO_refcount_inc (&ctx->references);
+       return ctx;
+}
+
+int
+mono_btls_ssl_ctx_free (MonoBtlsSslCtx *ctx)
+{
+       if (!CRYPTO_refcount_dec_and_test_zero (&ctx->references))
+               return 0;
+       SSL_CTX_free (ctx->ctx);
+       ctx->instance = NULL;
+       OPENSSL_free (ctx);
+       return 1;
+}
+
+SSL_CTX *
+mono_btls_ssl_ctx_get_ctx (MonoBtlsSslCtx *ctx)
+{
+       return ctx->ctx;
+}
+
+void
+mono_btls_ssl_ctx_set_debug_bio (MonoBtlsSslCtx *ctx, BIO *debug_bio)
+{
+       if (debug_bio)
+               ctx->debug_bio = BIO_up_ref(debug_bio);
+       else
+               ctx->debug_bio = NULL;
+}
+
+void
+mono_btls_ssl_ctx_initialize (MonoBtlsSslCtx *ctx, void *instance)
+{
+       ctx->instance = instance;
+}
+
+static int
+cert_verify_callback (X509_STORE_CTX *storeCtx, void *arg)
+{
+       MonoBtlsSslCtx *ptr = (MonoBtlsSslCtx*)arg;
+       int ret;
+
+       debug_printf (ptr, "cert_verify_callback(): %p\n", ptr->verify_func);
+       ret = X509_verify_cert (storeCtx);
+       debug_printf (ptr, "cert_verify_callback() #1: %d\n", ret);
+
+       if (ptr->verify_func)
+               ret = ptr->verify_func (ptr->instance, ret, storeCtx);
+
+       return ret;
+}
+
+void
+mono_btls_ssl_ctx_set_cert_verify_callback (MonoBtlsSslCtx *ptr, MonoBtlsVerifyFunc func, int cert_required)
+{
+       int mode;
+
+       ptr->verify_func = func;
+       SSL_CTX_set_cert_verify_callback (ptr->ctx, cert_verify_callback, ptr);
+
+       mode = SSL_VERIFY_PEER;
+       if (cert_required)
+               mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
+
+       SSL_CTX_set_verify (ptr->ctx, mode, NULL);
+}
+
+static int
+cert_select_callback (SSL *ssl, void *arg)
+{
+       MonoBtlsSslCtx *ptr = (MonoBtlsSslCtx*)arg;
+       int ret = 1;
+
+       debug_printf (ptr, "cert_select_callback(): %p\n", ptr->select_func);
+       if (ptr->select_func)
+               ret = ptr->select_func (ptr->instance);
+       debug_printf (ptr, "cert_select_callback() #1: %d\n", ret);
+
+       return ret;
+}
+
+void
+mono_btls_ssl_ctx_set_cert_select_callback (MonoBtlsSslCtx *ptr, MonoBtlsSelectFunc func)
+{
+       ptr->select_func = func;
+       SSL_CTX_set_cert_cb (ptr->ctx, cert_select_callback, ptr);
+}
+
+X509_STORE *
+mono_btls_ssl_ctx_peek_store (MonoBtlsSslCtx *ctx)
+{
+       return SSL_CTX_get_cert_store (ctx->ctx);
+}
+
+void
+mono_btls_ssl_ctx_set_min_version (MonoBtlsSslCtx *ctx, int version)
+{
+       SSL_CTX_set_min_version (ctx->ctx, version);
+}
+
+void
+mono_btls_ssl_ctx_set_max_version (MonoBtlsSslCtx *ctx, int version)
+{
+       SSL_CTX_set_max_version (ctx->ctx, version);
+}
+
+int
+mono_btls_ssl_ctx_is_cipher_supported (MonoBtlsSslCtx *ctx, uint16_t value)
+{
+       const SSL_CIPHER *cipher;
+
+       cipher = SSL_get_cipher_by_value (value);
+       return cipher != NULL;
+}
+
+int
+mono_btls_ssl_ctx_set_ciphers (MonoBtlsSslCtx *ctx, int count, const uint16_t *data,
+                                  int allow_unsupported)
+{
+       STACK_OF(SSL_CIPHER) *ciphers = NULL;
+       struct ssl_cipher_preference_list_st *pref_list = NULL;
+       uint8_t *in_group_flags = NULL;
+       int i;
+
+       ciphers = sk_SSL_CIPHER_new_null ();
+       if (!ciphers)
+               goto err;
+
+       for (i = 0; i < count; i++) {
+               const SSL_CIPHER *cipher = SSL_get_cipher_by_value (data [i]);
+               if (!cipher) {
+                       debug_printf (ctx, "mono_btls_ssl_ctx_set_ciphers(): unknown cipher %02x", data [i]);
+                       if (!allow_unsupported)
+                               goto err;
+                       continue;
+               }
+               if (!sk_SSL_CIPHER_push (ciphers, cipher))
+                        goto err;
+       }
+
+       pref_list = OPENSSL_malloc (sizeof (struct ssl_cipher_preference_list_st));
+       if (!pref_list)
+               goto err;
+
+       memset (pref_list, 0, sizeof (struct ssl_cipher_preference_list_st));
+       pref_list->ciphers = sk_SSL_CIPHER_dup (ciphers);
+       if (!pref_list->ciphers)
+               goto err;
+       pref_list->in_group_flags = OPENSSL_malloc (sk_SSL_CIPHER_num (ciphers));
+       if (!pref_list->in_group_flags)
+               goto err;
+
+       if (ctx->ctx->cipher_list)
+               ssl_cipher_preference_list_free (ctx->ctx->cipher_list);
+       if (ctx->ctx->cipher_list_by_id)
+               sk_SSL_CIPHER_free (ctx->ctx->cipher_list_by_id);
+       if (ctx->ctx->cipher_list_tls10) {
+               ssl_cipher_preference_list_free (ctx->ctx->cipher_list_tls10);
+               ctx->ctx->cipher_list_tls10 = NULL;
+       }
+       if (ctx->ctx->cipher_list_tls11) {
+               ssl_cipher_preference_list_free (ctx->ctx->cipher_list_tls11);
+               ctx->ctx->cipher_list_tls11 = NULL;
+       }
+
+       ctx->ctx->cipher_list = pref_list;
+       ctx->ctx->cipher_list_by_id = ciphers;
+
+       return (int)sk_SSL_CIPHER_num (ciphers);
+
+err:
+       sk_SSL_CIPHER_free (ciphers);
+       OPENSSL_free (pref_list);
+       OPENSSL_free (in_group_flags);
+       return 0;
+}
+
+int
+mono_btls_ssl_ctx_set_verify_param (MonoBtlsSslCtx *ctx, const MonoBtlsX509VerifyParam *param)
+{
+       return SSL_CTX_set1_param (ctx->ctx, mono_btls_x509_verify_param_peek_param (param));
+}
+
diff --git a/mono/btls/btls-ssl-ctx.h b/mono/btls/btls-ssl-ctx.h
new file mode 100644 (file)
index 0000000..0954192
--- /dev/null
@@ -0,0 +1,84 @@
+//
+//  btls-ssl-ctx.h
+//  MonoBtls
+//
+//  Created by Martin Baulig on 4/11/16.
+//  Copyright Â© 2016 Xamarin. All rights reserved.
+//
+
+#ifndef __btls_ssl_ctx__btls_ssl_ctx__
+#define __btls_ssl_ctx__btls_ssl_ctx__
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <openssl/ssl.h>
+#include <btls-util.h>
+
+typedef struct MonoBtlsBio MonoBtlsBio;
+typedef struct MonoBtlsX509Chain MonoBtlsX509Chain;
+typedef struct MonoBtlsX509Crl MonoBtlsX509Crl;
+typedef struct MonoBtlsX509Lookup MonoBtlsX509Lookup;
+typedef struct MonoBtlsX509LookupMono MonoBtlsX509LookupMono;
+typedef struct MonoBtlsX509Name MonoBtlsX509Name;
+typedef struct MonoBtlsX509Store MonoBtlsX509Store;
+typedef struct MonoBtlsX509StoreCtx MonoBtlsX509StoreCtx;
+typedef struct MonoBtlsX509Revoked MonoBtlsX509Revoked;
+typedef struct MonoBtlsX509VerifyParam MonoBtlsX509VerifyParam;
+typedef struct MonoBtlsPkcs12 MonoBtlsPkcs12;
+typedef struct MonoBtlsSsl MonoBtlsSsl;
+typedef struct MonoBtlsSslCtx MonoBtlsSslCtx;
+
+typedef int (* MonoBtlsVerifyFunc) (void *instance, int preverify_ok, X509_STORE_CTX *ctx);
+typedef int (* MonoBtlsSelectFunc) (void *instance);
+
+MonoBtlsSslCtx *
+mono_btls_ssl_ctx_new (void);
+
+MonoBtlsSslCtx *
+mono_btls_ssl_ctx_up_ref (MonoBtlsSslCtx *ctx);
+
+int
+mono_btls_ssl_ctx_free (MonoBtlsSslCtx *ctx);
+
+void
+mono_btls_ssl_ctx_initialize (MonoBtlsSslCtx *ctx, void *instance);
+
+SSL_CTX *
+mono_btls_ssl_ctx_get_ctx (MonoBtlsSslCtx *ctx);
+
+int
+mono_btls_ssl_ctx_debug_printf (MonoBtlsSslCtx *ctx, const char *format, ...);
+
+int
+mono_btls_ssl_ctx_is_debug_enabled (MonoBtlsSslCtx *ctx);
+
+void
+mono_btls_ssl_ctx_set_cert_verify_callback (MonoBtlsSslCtx *ptr, MonoBtlsVerifyFunc func, int cert_required);
+
+void
+mono_btls_ssl_ctx_set_cert_select_callback (MonoBtlsSslCtx *ptr, MonoBtlsSelectFunc func);
+
+void
+mono_btls_ssl_ctx_set_debug_bio (MonoBtlsSslCtx *ctx, BIO *debug_bio);
+
+X509_STORE *
+mono_btls_ssl_ctx_peek_store (MonoBtlsSslCtx *ctx);
+
+void
+mono_btls_ssl_ctx_set_min_version (MonoBtlsSslCtx *ctx, int version);
+
+void
+mono_btls_ssl_ctx_set_max_version (MonoBtlsSslCtx *ctx, int version);
+
+int
+mono_btls_ssl_ctx_is_cipher_supported (MonoBtlsSslCtx *ctx, uint16_t value);
+
+int
+mono_btls_ssl_ctx_set_ciphers (MonoBtlsSslCtx *ctx, int count, const uint16_t *data,
+                                  int allow_unsupported);
+
+int
+mono_btls_ssl_ctx_set_verify_param (MonoBtlsSslCtx *ctx, const MonoBtlsX509VerifyParam *param);
+
+#endif /* __btls_ssl_ctx__btls_ssl_ctx__ */
diff --git a/mono/btls/btls-ssl.c b/mono/btls/btls-ssl.c
new file mode 100644 (file)
index 0000000..fa3e53d
--- /dev/null
@@ -0,0 +1,209 @@
+//
+//  btls-ssl.c
+//  MonoBtls
+//
+//  Created by Martin Baulig on 14/11/15.
+//  Copyright (c) 2015 Xamarin. All rights reserved.
+//
+
+#include <btls-ssl.h>
+#include <btls-x509-verify-param.h>
+
+struct MonoBtlsSsl {
+       MonoBtlsSslCtx *ctx;
+       SSL *ssl;
+};
+
+#define debug_print(ptr,message) \
+do { if (mono_btls_ssl_ctx_is_debug_enabled(ptr->ctx)) \
+mono_btls_ssl_ctx_debug_printf (ptr->ctx, "%s:%d:%s(): " message, __FILE__, __LINE__, \
+__func__); } while (0)
+
+#define debug_printf(ptr,fmt, ...) \
+do { if (mono_btls_ssl_ctx_is_debug_enabled(ptr->ctx)) \
+mono_btls_ssl_ctx_debug_printf (ptr->ctx, "%s:%d:%s(): " fmt, __FILE__, __LINE__, \
+__func__, __VA_ARGS__); } while (0)
+
+STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list (SSL *s, const CBS *cbs);
+
+MonoBtlsSsl *
+mono_btls_ssl_new (MonoBtlsSslCtx *ctx)
+{
+       MonoBtlsSsl *ptr;
+
+       ptr = calloc (1, sizeof (MonoBtlsSsl));
+
+       ptr->ctx = mono_btls_ssl_ctx_up_ref (ctx);
+       ptr->ssl = SSL_new (mono_btls_ssl_ctx_get_ctx (ptr->ctx));
+
+       SSL_set_options (ptr->ssl, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
+
+       return ptr;
+}
+
+void
+mono_btls_ssl_destroy (MonoBtlsSsl *ptr)
+{
+       mono_btls_ssl_close (ptr);
+       if (ptr->ssl) {
+               SSL_free (ptr->ssl);
+               ptr->ssl = NULL;
+       }
+       if (ptr->ctx) {
+               mono_btls_ssl_ctx_free (ptr->ctx);
+               ptr->ctx = NULL;
+       }
+       free (ptr);
+}
+
+void
+mono_btls_ssl_close (MonoBtlsSsl *ptr)
+{
+       ;
+}
+
+void
+mono_btls_ssl_set_bio (MonoBtlsSsl *ptr, BIO *bio)
+{
+       BIO_up_ref (bio);
+       SSL_set_bio (ptr->ssl, bio, bio);
+}
+
+void
+mono_btls_ssl_print_errors_cb (ERR_print_errors_callback_t callback, void *ctx)
+{
+       ERR_print_errors_cb (callback, ctx);
+}
+
+int
+mono_btls_ssl_use_certificate (MonoBtlsSsl *ptr, X509 *x509)
+{
+       return SSL_use_certificate (ptr->ssl, x509);
+}
+
+int
+mono_btls_ssl_use_private_key (MonoBtlsSsl *ptr, EVP_PKEY *key)
+{
+       return SSL_use_PrivateKey (ptr->ssl, key);
+}
+
+int
+mono_btls_ssl_add_chain_certificate (MonoBtlsSsl *ptr, X509 *x509)
+{
+       return SSL_add1_chain_cert (ptr->ssl, x509);
+}
+
+int
+mono_btls_ssl_accept (MonoBtlsSsl *ptr)
+{
+       return SSL_accept (ptr->ssl);
+}
+
+int
+mono_btls_ssl_connect (MonoBtlsSsl *ptr)
+{
+       return SSL_connect (ptr->ssl);
+}
+
+int
+mono_btls_ssl_handshake (MonoBtlsSsl *ptr)
+{
+       return SSL_do_handshake (ptr->ssl);
+}
+
+int
+mono_btls_ssl_read (MonoBtlsSsl *ptr, void *buf, int count)
+{
+       return SSL_read (ptr->ssl, buf, count);
+}
+
+int
+mono_btls_ssl_write (MonoBtlsSsl *ptr, void *buf, int count)
+{
+       return SSL_write (ptr->ssl, buf, count);
+}
+
+int
+mono_btls_ssl_get_version (MonoBtlsSsl *ptr)
+{
+       return SSL_version (ptr->ssl);
+}
+
+void
+mono_btls_ssl_set_min_version (MonoBtlsSsl *ptr, int version)
+{
+       SSL_set_min_version (ptr->ssl, version);
+}
+
+void
+mono_btls_ssl_set_max_version (MonoBtlsSsl *ptr, int version)
+{
+       SSL_set_max_version (ptr->ssl, version);
+}
+
+int
+mono_btls_ssl_get_cipher (MonoBtlsSsl *ptr)
+{
+       const SSL_CIPHER *cipher;
+
+       cipher = SSL_get_current_cipher (ptr->ssl);
+       if (!cipher)
+               return 0;
+       return (uint16_t)SSL_CIPHER_get_id (cipher);
+}
+
+int
+mono_btls_ssl_set_cipher_list (MonoBtlsSsl *ptr, const char *str)
+{
+       return SSL_set_cipher_list(ptr->ssl, str);
+}
+
+int
+mono_btls_ssl_get_ciphers (MonoBtlsSsl *ptr, uint16_t **data)
+{
+       STACK_OF(SSL_CIPHER) *ciphers;
+       int count, i;
+
+       *data = NULL;
+
+       ciphers = SSL_get_ciphers (ptr->ssl);
+       if (!ciphers)
+               return 0;
+
+       count = (int)sk_SSL_CIPHER_num (ciphers);
+
+       *data = OPENSSL_malloc (2 * count);
+       if (!*data)
+               return 0;
+
+       for (i = 0; i < count; i++) {
+               const SSL_CIPHER *cipher = sk_SSL_CIPHER_value (ciphers, i);
+               (*data) [i] = (uint16_t) SSL_CIPHER_get_id (cipher);
+       }
+
+       return count;
+}
+
+X509 *
+mono_btls_ssl_get_peer_certificate (MonoBtlsSsl *ptr)
+{
+       return SSL_get_peer_certificate (ptr->ssl);
+}
+
+int
+mono_btls_ssl_get_error (MonoBtlsSsl *ptr, int ret_code)
+{
+       return SSL_get_error (ptr->ssl, ret_code);
+}
+
+int
+mono_btls_ssl_set_verify_param (MonoBtlsSsl *ptr, const MonoBtlsX509VerifyParam *param)
+{
+       return SSL_set1_param (ptr->ssl, mono_btls_x509_verify_param_peek_param (param));
+}
+
+int
+mono_btls_ssl_set_server_name (MonoBtlsSsl *ptr, const char *name)
+{
+       return SSL_set_tlsext_host_name (ptr->ssl, name);
+}
diff --git a/mono/btls/btls-ssl.h b/mono/btls/btls-ssl.h
new file mode 100644 (file)
index 0000000..10da436
--- /dev/null
@@ -0,0 +1,83 @@
+//
+//  btls-ssl.h
+//  MonoBtls
+//
+//  Created by Martin Baulig on 14/11/15.
+//  Copyright (c) 2015 Xamarin. All rights reserved.
+//
+
+#ifndef __btls__btls_ssl__
+#define __btls__btls_ssl__
+
+#include <btls-ssl-ctx.h>
+
+MonoBtlsSsl *
+mono_btls_ssl_new (MonoBtlsSslCtx *ctx);
+
+int
+mono_btls_ssl_use_certificate (MonoBtlsSsl *ptr, X509 *x509);
+
+int
+mono_btls_ssl_use_private_key (MonoBtlsSsl *ptr, EVP_PKEY *key);
+
+int
+mono_btls_ssl_add_chain_certificate (MonoBtlsSsl *ptr, X509 *x509);
+
+int
+mono_btls_ssl_accept (MonoBtlsSsl *ptr);
+
+int
+mono_btls_ssl_connect (MonoBtlsSsl *ptr);
+
+int
+mono_btls_ssl_handshake (MonoBtlsSsl *ptr);
+
+void
+mono_btls_ssl_print_errors_cb (ERR_print_errors_callback_t callback, void *ctx);
+
+void
+mono_btls_ssl_set_bio (MonoBtlsSsl *ptr, BIO *bio);
+
+int
+mono_btls_ssl_read (MonoBtlsSsl *ptr, void *buf, int count);
+
+int
+mono_btls_ssl_write (MonoBtlsSsl *ptr, void *buf, int count);
+
+int
+mono_btls_ssl_get_version (MonoBtlsSsl *ptr);
+
+void
+mono_btls_ssl_set_min_version (MonoBtlsSsl *ptr, int version);
+
+void
+mono_btls_ssl_set_max_version (MonoBtlsSsl *ptr, int version);
+
+int
+mono_btls_ssl_get_cipher (MonoBtlsSsl *ptr);
+
+int
+mono_btls_ssl_set_cipher_list (MonoBtlsSsl *ptr, const char *str);
+
+int
+mono_btls_ssl_get_ciphers (MonoBtlsSsl *ptr, uint16_t **data);
+
+X509 *
+mono_btls_ssl_get_peer_certificate (MonoBtlsSsl *ptr);
+
+void
+mono_btls_ssl_close (MonoBtlsSsl *ptr);
+
+int
+mono_btls_ssl_get_error (MonoBtlsSsl *ptr, int ret_code);
+
+int
+mono_btls_ssl_set_verify_param (MonoBtlsSsl *ptr, const MonoBtlsX509VerifyParam *param);
+
+int
+mono_btls_ssl_set_server_name (MonoBtlsSsl *ptr, const char *name);
+
+void
+mono_btls_ssl_destroy (MonoBtlsSsl *ptr);
+
+#endif /* defined(__btls__btls_ssl__) */
diff --git a/mono/btls/btls-util.c b/mono/btls/btls-util.c
new file mode 100644 (file)
index 0000000..d28763a
--- /dev/null
@@ -0,0 +1,76 @@
+//
+//  btls-util.c
+//  MonoBtls
+//
+//  Created by Martin Baulig on 3/23/16.
+//  Copyright Â© 2016 Xamarin. All rights reserved.
+//
+
+#include <btls-util.h>
+#include <assert.h>
+#include <time.h>
+
+#if defined(__ANDROID__) && !defined(__LP64__)
+#include <time64.h>
+extern time_t timegm (struct tm* const t);
+#endif
+
+extern int asn1_generalizedtime_to_tm (struct tm *tm, const ASN1_GENERALIZEDTIME *d);
+
+void
+mono_btls_free (void *data)
+{
+       OPENSSL_free (data);
+}
+
+long
+mono_btls_util_asn1_time_to_ticks (ASN1_TIME *time)
+{
+       ASN1_GENERALIZEDTIME *gtime;
+       struct tm tm;
+       time_t epoch;
+
+       gtime = ASN1_TIME_to_generalizedtime (time, NULL);
+       asn1_generalizedtime_to_tm (&tm, gtime);
+       ASN1_GENERALIZEDTIME_free (gtime);
+       epoch = timegm(&tm);
+
+       return epoch;
+}
+
+// Copied from crypto/bio/printf.c, takes va_list
+int
+mono_btls_debug_printf (BIO *bio, const char *format, va_list args)
+{
+       char buf[256], *out, out_malloced = 0;
+       int out_len, ret;
+
+       out_len = vsnprintf (buf, sizeof(buf), format, args);
+       if (out_len < 0) {
+               return -1;
+       }
+
+       if ((size_t) out_len >= sizeof(buf)) {
+               const int requested_len = out_len;
+               /* The output was truncated. Note that vsnprintf's return value
+                * does not include a trailing NUL, but the buffer must be sized
+                * for it. */
+               out = OPENSSL_malloc (requested_len + 1);
+               out_malloced = 1;
+               if (out == NULL) {
+                       OPENSSL_PUT_ERROR(BIO, ERR_R_MALLOC_FAILURE);
+                       return -1;
+               }
+               out_len = vsnprintf (out, requested_len + 1, format, args);
+               assert(out_len == requested_len);
+       } else {
+               out = buf;
+       }
+
+       ret = BIO_write(bio, out, out_len);
+       if (out_malloced) {
+               OPENSSL_free(out);
+       }
+
+       return ret;
+}
diff --git a/mono/btls/btls-util.h b/mono/btls/btls-util.h
new file mode 100644 (file)
index 0000000..a77bfcd
--- /dev/null
@@ -0,0 +1,29 @@
+//
+//  btls-util.h
+//  MonoBtls
+//
+//  Created by Martin Baulig on 3/23/16.
+//  Copyright Â© 2016 Xamarin. All rights reserved.
+//
+
+#ifndef __btls__btls_util__
+#define __btls__btls_util__
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <openssl/ssl.h>
+
+void
+mono_btls_free (void *data);
+
+long
+mono_btls_util_asn1_time_to_ticks (ASN1_TIME *time);
+
+int
+mono_btls_debug_printf (BIO *bio, const char *format, va_list args);
+
+OPENSSL_EXPORT void CRYPTO_refcount_inc(CRYPTO_refcount_t *count);
+OPENSSL_EXPORT int CRYPTO_refcount_dec_and_test_zero(CRYPTO_refcount_t *count);
+
+#endif /* __btls__btls_util__ */
diff --git a/mono/btls/btls-x509-chain.c b/mono/btls/btls-x509-chain.c
new file mode 100644 (file)
index 0000000..0584791
--- /dev/null
@@ -0,0 +1,96 @@
+//
+//  btls-x509-chain.c
+//  MonoBtls
+//
+//  Created by Martin Baulig on 3/3/16.
+//  Copyright Â© 2016 Xamarin. All rights reserved.
+//
+
+#include <btls-x509-chain.h>
+
+struct MonoBtlsX509Chain {
+       STACK_OF(X509) *certs;
+       CRYPTO_refcount_t references;
+};
+
+MonoBtlsX509Chain *
+mono_btls_x509_chain_new (void)
+{
+       MonoBtlsX509Chain *chain = (MonoBtlsX509Chain *)OPENSSL_malloc (sizeof (MonoBtlsX509Chain));
+       if (chain == NULL)
+               return NULL;
+
+       memset(chain, 0, sizeof(MonoBtlsX509Chain));
+       chain->certs = sk_X509_new_null ();
+       chain->references = 1;
+       return chain;
+}
+
+MonoBtlsX509Chain *
+mono_btls_x509_chain_from_certs (STACK_OF(X509) *certs)
+{
+       MonoBtlsX509Chain *chain = (MonoBtlsX509Chain *)OPENSSL_malloc (sizeof (MonoBtlsX509Chain));
+       if (chain == NULL)
+               return NULL;
+
+       memset(chain, 0, sizeof(MonoBtlsX509Chain));
+       chain->certs = X509_chain_up_ref(certs);
+       chain->references = 1;
+       return chain;
+}
+
+STACK_OF(X509) *
+mono_btls_x509_chain_peek_certs (MonoBtlsX509Chain *chain)
+{
+       return chain->certs;
+}
+
+int
+mono_btls_x509_chain_get_count (MonoBtlsX509Chain *chain)
+{
+       return (int)sk_X509_num(chain->certs);
+}
+
+X509 *
+mono_btls_x509_chain_get_cert (MonoBtlsX509Chain *chain, int index)
+{
+       X509 *cert;
+
+       if ((size_t)index >= sk_X509_num(chain->certs))
+               return NULL;
+       cert = sk_X509_value(chain->certs, index);
+       if (cert)
+               X509_up_ref(cert);
+       return cert;
+}
+
+STACK_OF(X509) *
+mono_btls_x509_chain_get_certs (MonoBtlsX509Chain *chain)
+{
+       return chain->certs;
+}
+
+int
+mono_btls_x509_chain_free (MonoBtlsX509Chain *chain)
+{
+       if (!CRYPTO_refcount_dec_and_test_zero(&chain->references))
+               return 0;
+
+       sk_X509_pop_free(chain->certs, X509_free);
+       OPENSSL_free (chain);
+       return 1;
+}
+
+MonoBtlsX509Chain *
+mono_btls_x509_chain_up_ref (MonoBtlsX509Chain *chain)
+{
+       CRYPTO_refcount_inc(&chain->references);
+       return chain;
+}
+
+void
+mono_btls_x509_chain_add_cert (MonoBtlsX509Chain *chain, X509 *x509)
+{
+       X509_up_ref(x509);
+       sk_X509_push(chain->certs, x509);
+}
diff --git a/mono/btls/btls-x509-chain.h b/mono/btls/btls-x509-chain.h
new file mode 100644 (file)
index 0000000..68ef577
--- /dev/null
@@ -0,0 +1,41 @@
+//
+//  btls-x509-chain.h
+//  MonoBtls
+//
+//  Created by Martin Baulig on 3/3/16.
+//  Copyright Â© 2016 Xamarin. All rights reserved.
+//
+
+#ifndef __btls__btls_x509_chain__
+#define __btls__btls_x509_chain__
+
+#include <stdio.h>
+#include <btls-ssl.h>
+#include <btls-x509.h>
+
+MonoBtlsX509Chain *
+mono_btls_x509_chain_new (void);
+
+MonoBtlsX509Chain *
+mono_btls_x509_chain_from_certs (STACK_OF(X509) *certs);
+
+STACK_OF(X509) *
+mono_btls_x509_chain_peek_certs (MonoBtlsX509Chain *chain);
+
+int
+mono_btls_x509_chain_get_count (MonoBtlsX509Chain *chain);
+
+X509 *
+mono_btls_x509_chain_get_cert (MonoBtlsX509Chain *chain, int index);
+
+MonoBtlsX509Chain *
+mono_btls_x509_chain_up_ref (MonoBtlsX509Chain *chain);
+
+int
+mono_btls_x509_chain_free (MonoBtlsX509Chain *chain);
+
+void
+mono_btls_x509_chain_add_cert (MonoBtlsX509Chain *chain, X509 *x509);
+
+#endif /* defined(__btls__btls_x509_chain__) */
+
diff --git a/mono/btls/btls-x509-crl.c b/mono/btls/btls-x509-crl.c
new file mode 100644 (file)
index 0000000..ccd3e28
--- /dev/null
@@ -0,0 +1,150 @@
+//
+//  btls-x509-crl.c
+//  MonoBtls
+//
+//  Created by Martin Baulig on 3/23/16.
+//  Copyright Â© 2016 Xamarin. All rights reserved.
+//
+
+#include <btls-x509-crl.h>
+#include <btls-x509-revoked.h>
+
+struct MonoBtlsX509Crl {
+       X509_CRL *crl;
+       CRYPTO_refcount_t references;
+};
+
+MonoBtlsX509Crl *
+mono_btls_x509_crl_from_data (const void *buf, int len, MonoBtlsX509Format format)
+{
+       MonoBtlsX509Crl *crl;
+       BIO *bio;
+
+       crl = OPENSSL_malloc (sizeof (MonoBtlsX509Crl));
+       memset (crl, 0, sizeof(MonoBtlsX509Crl));
+       crl->references = 1;
+
+       bio = BIO_new_mem_buf ((void *)buf, len);
+       switch (format) {
+               case MONO_BTLS_X509_FORMAT_DER:
+                       crl->crl = d2i_X509_CRL_bio (bio, NULL);
+                       break;
+               case MONO_BTLS_X509_FORMAT_PEM:
+                       crl->crl = PEM_read_bio_X509_CRL (bio, NULL, NULL, NULL);
+                       break;
+       }
+       BIO_free (bio);
+
+       if (!crl->crl) {
+               OPENSSL_free (crl);
+               return NULL;
+       }
+
+       return crl;
+}
+
+MonoBtlsX509Crl *
+mono_btls_x509_crl_ref (MonoBtlsX509Crl *crl)
+{
+       CRYPTO_refcount_inc (&crl->references);
+       return crl;
+}
+
+int
+mono_btls_x509_crl_free (MonoBtlsX509Crl *crl)
+{
+       if (!CRYPTO_refcount_dec_and_test_zero (&crl->references))
+               return 0;
+
+       X509_CRL_free (crl->crl);
+       OPENSSL_free (crl);
+       return 1;
+}
+
+MonoBtlsX509Revoked *
+mono_btls_x509_crl_get_by_cert (MonoBtlsX509Crl *crl, X509 *x509)
+{
+       X509_REVOKED *revoked;
+       int ret;
+
+       revoked = NULL;
+       ret = X509_CRL_get0_by_cert (crl->crl, &revoked, x509);
+       fprintf (stderr, "mono_btls_x509_crl_get_by_cert: %d - %p\n", ret, revoked);
+
+       if (!ret || !revoked)
+               return NULL;
+
+       return mono_btls_x509_revoked_new (crl, revoked);
+}
+
+MonoBtlsX509Revoked *
+mono_btls_x509_crl_get_by_serial (MonoBtlsX509Crl *crl, void *serial, int len)
+{
+       ASN1_INTEGER si;
+       X509_REVOKED *revoked;
+       int ret;
+
+       si.type = V_ASN1_INTEGER;
+       si.length = len;
+       si.data = serial;
+
+       revoked = NULL;
+       ret = X509_CRL_get0_by_serial (crl->crl, &revoked, &si);
+       fprintf (stderr, "mono_btls_x509_crl_get_by_serial: %d - %p\n", ret, revoked);
+
+       if (!ret || !revoked)
+               return NULL;
+
+       return mono_btls_x509_revoked_new (crl, revoked);
+}
+
+int
+mono_btls_x509_crl_get_revoked_count (MonoBtlsX509Crl *crl)
+{
+       STACK_OF(X509_REVOKED) *stack;
+
+       stack = X509_CRL_get_REVOKED (crl->crl);
+       return (int)sk_X509_REVOKED_num (stack);
+}
+
+MonoBtlsX509Revoked *
+mono_btls_x509_crl_get_revoked (MonoBtlsX509Crl *crl, int index)
+{
+       STACK_OF(X509_REVOKED) *stack;
+       X509_REVOKED *revoked;
+
+       stack = X509_CRL_get_REVOKED (crl->crl);
+       if ((size_t)index >= sk_X509_REVOKED_num (stack))
+               return NULL;
+
+       revoked = sk_X509_REVOKED_value (stack, index);
+       if (!revoked)
+               return NULL;
+
+       return mono_btls_x509_revoked_new (crl, revoked);
+}
+
+long
+mono_btls_x509_crl_get_last_update (MonoBtlsX509Crl *crl)
+{
+       return mono_btls_util_asn1_time_to_ticks (X509_CRL_get_lastUpdate (crl->crl));
+}
+
+long
+mono_btls_x509_crl_get_next_update (MonoBtlsX509Crl *crl)
+{
+       return mono_btls_util_asn1_time_to_ticks (X509_CRL_get_nextUpdate (crl->crl));
+}
+
+long
+mono_btls_x509_crl_get_version (MonoBtlsX509Crl *crl)
+{
+       return X509_CRL_get_version (crl->crl);
+}
+
+MonoBtlsX509Name *
+mono_btls_x509_crl_get_issuer (MonoBtlsX509Crl *crl)
+{
+       return mono_btls_x509_name_copy (X509_CRL_get_issuer (crl->crl));
+}
+
diff --git a/mono/btls/btls-x509-crl.h b/mono/btls/btls-x509-crl.h
new file mode 100644 (file)
index 0000000..0813fe5
--- /dev/null
@@ -0,0 +1,49 @@
+//
+//  btls-x509-crl.h
+//  MonoBtls
+//
+//  Created by Martin Baulig on 3/23/16.
+//  Copyright Â© 2016 Xamarin. All rights reserved.
+//
+
+#ifndef __btls__btls_x509_crl__
+#define __btls__btls_x509_crl__
+
+#include <stdio.h>
+#include <btls-ssl.h>
+#include <btls-x509.h>
+
+MonoBtlsX509Crl *
+mono_btls_x509_crl_from_data (const void *buf, int len, MonoBtlsX509Format format);
+
+MonoBtlsX509Crl *
+mono_btls_x509_crl_ref (MonoBtlsX509Crl *crl);
+
+int
+mono_btls_x509_crl_free (MonoBtlsX509Crl *crl);
+
+MonoBtlsX509Revoked *
+mono_btls_x509_crl_get_by_cert (MonoBtlsX509Crl *crl, X509 *x509);
+
+MonoBtlsX509Revoked *
+mono_btls_x509_crl_get_by_serial (MonoBtlsX509Crl *crl, void *serial, int len);
+
+int
+mono_btls_x509_crl_get_revoked_count (MonoBtlsX509Crl *crl);
+
+MonoBtlsX509Revoked *
+mono_btls_x509_crl_get_revoked (MonoBtlsX509Crl *crl, int index);
+
+long
+mono_btls_x509_crl_get_last_update (MonoBtlsX509Crl *crl);
+
+long
+mono_btls_x509_crl_get_next_update (MonoBtlsX509Crl *crl);
+
+long
+mono_btls_x509_crl_get_version (MonoBtlsX509Crl *crl);
+
+MonoBtlsX509Name *
+mono_btls_x509_crl_get_issuer (MonoBtlsX509Crl *crl);
+
+#endif /* __btls__btls_x509_crl__ */
diff --git a/mono/btls/btls-x509-lookup-mono.c b/mono/btls/btls-x509-lookup-mono.c
new file mode 100644 (file)
index 0000000..cce7368
--- /dev/null
@@ -0,0 +1,228 @@
+//
+//  btls-x509-lookup-mono.c
+//  MonoBtls
+//
+//  Created by Martin Baulig on 3/6/16.
+//  Copyright Â© 2016 Xamarin. All rights reserved.
+//
+
+#include <btls-x509-lookup.h>
+#include <btls-x509-lookup-mono.h>
+#include <openssl/stack.h>
+
+// random high number
+#define MONO_BTLS_X509_L_MONO_ADD      36292
+
+typedef struct MonoLookupNode MonoLookupNode;
+struct MonoLookupNode {
+       MonoBtlsX509LookupMono *mono;
+       MonoLookupNode *next;
+};
+
+typedef struct {
+       MonoLookupNode *nodes;
+} MonoLookup;
+
+struct MonoBtlsX509LookupMono {
+       const void *instance;
+       MonoBtlsX509LookupMono_BySubject by_subject_func;
+       MonoLookup *lookup;
+};
+
+MonoBtlsX509LookupMono *
+mono_btls_x509_lookup_mono_new (void)
+{
+       MonoBtlsX509LookupMono *mono;
+
+       mono = OPENSSL_malloc (sizeof (MonoBtlsX509LookupMono));
+       if (!mono)
+               return NULL;
+
+       memset (mono, 0, sizeof (MonoBtlsX509LookupMono));
+       return mono;
+}
+
+void
+mono_btls_x509_lookup_mono_init (MonoBtlsX509LookupMono *mono, const void *instance,
+                                MonoBtlsX509LookupMono_BySubject by_subject_func)
+{
+       mono->instance = instance;
+       mono->by_subject_func = by_subject_func;
+}
+
+static int
+mono_lookup_install (MonoLookup *lookup, MonoBtlsX509LookupMono *mono)
+{
+       MonoLookupNode *node;
+
+       node = OPENSSL_malloc (sizeof (MonoLookupNode));
+       if (!node)
+               return 0;
+
+       memset (node, 0, sizeof (MonoLookupNode));
+       mono->lookup = lookup;
+       node->mono = mono;
+       node->next = lookup->nodes;
+       lookup->nodes = node;
+       return 1;
+}
+
+static int
+mono_lookup_uninstall (MonoBtlsX509LookupMono *mono)
+{
+       MonoLookupNode **ptr;
+
+       if (!mono->lookup)
+               return 0;
+
+       for (ptr = &mono->lookup->nodes; *ptr; ptr = &(*ptr)->next) {
+               if ((*ptr)->mono == mono) {
+                       *ptr = (*ptr)->next;
+                       return 1;
+               }
+       }
+
+       return 0;
+}
+
+int
+mono_btls_x509_lookup_mono_free (MonoBtlsX509LookupMono *mono)
+{
+       mono->instance = NULL;
+       mono->by_subject_func = NULL;
+
+       if (mono->lookup) {
+               if (!mono_lookup_uninstall (mono))
+                       return 0;
+       }
+
+       mono->lookup = NULL;
+
+       OPENSSL_free (mono);
+       return 1;
+}
+
+static int
+mono_lookup_ctrl (X509_LOOKUP *ctx, int cmd, const char *argp, long argl, char **ret)
+{
+       MonoLookup *lookup = (MonoLookup*)ctx->method_data;
+       MonoBtlsX509LookupMono *mono = (MonoBtlsX509LookupMono*)argp;
+
+       if (!lookup || cmd != MONO_BTLS_X509_L_MONO_ADD)
+               return 0;
+       if (!mono || mono->lookup)
+               return 0;
+
+       return mono_lookup_install (lookup, mono);
+}
+
+static int
+mono_lookup_new (X509_LOOKUP *ctx)
+{
+       MonoLookup *data;
+
+       data = OPENSSL_malloc (sizeof (MonoLookup));
+       if (!data)
+               return 0;
+
+       memset (data, 0, sizeof (MonoLookup));
+       ctx->method_data = (void *)data;
+       return 1;
+}
+
+static void
+mono_lookup_free (X509_LOOKUP *ctx)
+{
+       MonoLookup *lookup;
+       MonoLookupNode *ptr;
+
+       lookup = (MonoLookup *)ctx->method_data;
+       ctx->method_data = NULL;
+       if (!lookup)
+               return;
+
+       ptr = lookup->nodes;
+       lookup->nodes = NULL;
+
+       while (ptr) {
+               MonoLookupNode *node = ptr;
+               ptr = ptr->next;
+
+               if (node->mono)
+                       node->mono->lookup = NULL;
+               node->mono = NULL;
+               node->next = NULL;
+               OPENSSL_free (node);
+       }
+
+       OPENSSL_free (lookup);
+}
+
+static int
+mono_lookup_get_by_subject (X509_LOOKUP *ctx, int type, X509_NAME *name, X509_OBJECT *obj_ret)
+{
+       MonoLookup *lookup;
+       MonoBtlsX509Name *name_obj;
+       MonoLookupNode *node;
+       X509 *x509 = NULL;
+       int ret = 0;
+
+       lookup = (MonoLookup *)ctx->method_data;
+
+       if (!lookup || !lookup->nodes)
+               return 0;
+       if (type != X509_LU_X509)
+               return 0;
+
+       name_obj = mono_btls_x509_name_from_name (name);
+       x509 = NULL;
+
+       for (node = lookup->nodes; node; node = node->next) {
+               if (!node->mono || !node->mono->by_subject_func)
+                       continue;
+               ret = (* node->mono->by_subject_func) (node->mono->instance, name_obj, &x509);
+               if (ret)
+                       break;
+       }
+
+       mono_btls_x509_name_free (name_obj);
+
+       if (!ret) {
+               if (x509)
+                       X509_free(x509);
+               return 0;
+       }
+
+       obj_ret->type = X509_LU_X509;
+       obj_ret->data.x509 = x509;
+       return 1;
+}
+
+static X509_LOOKUP_METHOD mono_lookup_method = {
+       "Mono lookup method",
+       mono_lookup_new,                /* new */
+       mono_lookup_free,               /* free */
+       NULL,                           /* init */
+       NULL,                           /* shutdown */
+       mono_lookup_ctrl,               /* ctrl */
+       mono_lookup_get_by_subject,     /* get_by_subject */
+       NULL,                           /* get_by_issuer_serial */
+       NULL,                           /* get_by_fingerprint */
+       NULL,                           /* get_by_alias */
+};
+
+X509_LOOKUP_METHOD *
+mono_btls_x509_lookup_mono_method (void)
+{
+       return &mono_lookup_method;
+}
+
+int
+mono_btls_x509_lookup_add_mono (MonoBtlsX509Lookup *lookup, MonoBtlsX509LookupMono *mono)
+{
+       if (mono_btls_x509_lookup_get_type (lookup) != MONO_BTLS_X509_LOOKUP_TYPE_MONO)
+               return 0;
+       return X509_LOOKUP_ctrl (mono_btls_x509_lookup_peek_lookup (lookup),
+                                MONO_BTLS_X509_L_MONO_ADD,
+                                (void*)mono, 0, NULL);
+}
diff --git a/mono/btls/btls-x509-lookup-mono.h b/mono/btls/btls-x509-lookup-mono.h
new file mode 100644 (file)
index 0000000..06df552
--- /dev/null
@@ -0,0 +1,36 @@
+//
+//  btls-x509-lookup-mono.h
+//  MonoBtls
+//
+//  Created by Martin Baulig on 3/3/16.
+//  Copyright Â© 2016 Xamarin. All rights reserved.
+//
+
+#ifndef __btls__btls_x509_lookup_mono__
+#define __btls__btls_x509_lookup_mono__
+
+#include <stdio.h>
+#include <btls-ssl.h>
+#include <btls-x509.h>
+#include <btls-x509-store.h>
+
+typedef int (* MonoBtlsX509LookupMono_BySubject) (const void *instance, MonoBtlsX509Name *name, X509 **ret);
+
+MonoBtlsX509LookupMono *
+mono_btls_x509_lookup_mono_new (void);
+
+int
+mono_btls_x509_lookup_mono_free (MonoBtlsX509LookupMono *mono);
+
+void
+mono_btls_x509_lookup_mono_init (MonoBtlsX509LookupMono *mono, const void *instance,
+                                MonoBtlsX509LookupMono_BySubject by_subject_func);
+
+int
+mono_btls_x509_lookup_add_mono (MonoBtlsX509Lookup *lookup, MonoBtlsX509LookupMono *mono);
+
+X509_LOOKUP_METHOD *
+mono_btls_x509_lookup_mono_method (void);
+
+#endif /* defined(__btls__btls_x509_lookup_mono__) */
+
diff --git a/mono/btls/btls-x509-lookup.c b/mono/btls/btls-x509-lookup.c
new file mode 100644 (file)
index 0000000..1cfc174
--- /dev/null
@@ -0,0 +1,160 @@
+//
+//  btls-x509-lookup.c
+//  MonoBtls
+//
+//  Created by Martin Baulig on 3/6/16.
+//  Copyright Â© 2016 Xamarin. All rights reserved.
+//
+
+#include <btls-x509-lookup.h>
+#include <btls-x509-lookup-mono.h>
+
+struct MonoBtlsX509Lookup {
+       MonoBtlsX509LookupType type;
+       X509_LOOKUP *lookup;
+       int owns_lookup;
+       MonoBtlsX509Store *store;
+       CRYPTO_refcount_t references;
+};
+
+static X509_LOOKUP_METHOD *
+get_lookup_method (MonoBtlsX509LookupType type)
+{
+       switch (type) {
+       case MONO_BTLS_X509_LOOKUP_TYPE_FILE:
+               return X509_LOOKUP_file ();
+       case MONO_BTLS_X509_LOOKUP_TYPE_HASH_DIR:
+               return X509_LOOKUP_hash_dir ();
+       case MONO_BTLS_X509_LOOKUP_TYPE_MONO:
+               return mono_btls_x509_lookup_mono_method ();
+       default:
+               return NULL;
+       }
+}
+
+MonoBtlsX509Lookup *
+mono_btls_x509_lookup_new (MonoBtlsX509Store *store, MonoBtlsX509LookupType type)
+{
+       MonoBtlsX509Lookup *lookup;
+       X509_LOOKUP *store_lookup;
+       X509_LOOKUP_METHOD *method;
+
+       method = get_lookup_method (type);
+       if (!method)
+               return NULL;
+
+       lookup = OPENSSL_malloc (sizeof(MonoBtlsX509Lookup));
+       if (!lookup)
+               return NULL;
+
+       store_lookup = X509_STORE_add_lookup (mono_btls_x509_store_peek_store (store), method);
+       if (!store_lookup)
+               return NULL;
+
+       memset (lookup, 0, sizeof(MonoBtlsX509Lookup));
+       // The X509_STORE owns the X509_LOOKUP.
+       lookup->store = mono_btls_x509_store_up_ref (store);
+       lookup->lookup = store_lookup;
+       lookup->owns_lookup = 0;
+       lookup->references = 1;
+       lookup->type = type;
+       return lookup;
+}
+
+int
+mono_btls_x509_lookup_load_file (MonoBtlsX509Lookup *lookup, const char *file, MonoBtlsX509FileType type)
+{
+       return X509_LOOKUP_load_file (lookup->lookup, file, type);
+}
+
+int
+mono_btls_x509_lookup_add_dir (MonoBtlsX509Lookup *lookup, const char *dir, MonoBtlsX509FileType type)
+{
+       return X509_LOOKUP_add_dir (lookup->lookup, dir, type);
+}
+
+MonoBtlsX509Lookup *
+mono_btls_x509_lookup_up_ref (MonoBtlsX509Lookup *lookup)
+{
+       CRYPTO_refcount_inc (&lookup->references);
+       return lookup;
+}
+
+int
+mono_btls_x509_lookup_free (MonoBtlsX509Lookup *lookup)
+{
+       if (!CRYPTO_refcount_dec_and_test_zero (&lookup->references))
+               return 0;
+
+       if (lookup->store) {
+               mono_btls_x509_store_free (lookup->store);
+               lookup->store = NULL;
+       }
+
+       if (lookup->lookup) {
+               if (lookup->owns_lookup)
+                       X509_LOOKUP_free (lookup->lookup);
+               lookup->lookup = NULL;
+       }
+
+       OPENSSL_free (lookup);
+       return 1;
+}
+
+int
+mono_btls_x509_lookup_init (MonoBtlsX509Lookup *lookup)
+{
+       return X509_LOOKUP_init (lookup->lookup);
+}
+
+int
+mono_btls_x509_lookup_shutdown (MonoBtlsX509Lookup *lookup)
+{
+       return X509_LOOKUP_shutdown (lookup->lookup);
+}
+
+MonoBtlsX509LookupType
+mono_btls_x509_lookup_get_type (MonoBtlsX509Lookup *lookup)
+{
+       return lookup->type;
+}
+
+X509_LOOKUP *
+mono_btls_x509_lookup_peek_lookup (MonoBtlsX509Lookup *lookup)
+{
+       return lookup->lookup;
+}
+
+X509 *
+mono_btls_x509_lookup_by_subject (MonoBtlsX509Lookup *lookup, MonoBtlsX509Name *name)
+{
+       X509_OBJECT obj;
+       X509 *x509;
+       int ret;
+
+       ret = X509_LOOKUP_by_subject (lookup->lookup, X509_LU_X509, mono_btls_x509_name_peek_name (name), &obj);
+       if (ret != X509_LU_X509) {
+               X509_OBJECT_free_contents (&obj);
+               return NULL;
+       }
+
+       x509 = X509_up_ref (obj.data.x509);
+       return x509;
+}
+
+X509 *
+mono_btls_x509_lookup_by_fingerprint (MonoBtlsX509Lookup *lookup, unsigned char *bytes, int len)
+{
+       X509_OBJECT obj;
+       X509 *x509;
+       int ret;
+
+       ret = X509_LOOKUP_by_fingerprint (lookup->lookup, X509_LU_X509, bytes, len, &obj);
+       if (ret != X509_LU_X509) {
+               X509_OBJECT_free_contents (&obj);
+               return NULL;
+       }
+
+       x509 = X509_up_ref (obj.data.x509);
+       return x509;
+}
diff --git a/mono/btls/btls-x509-lookup.h b/mono/btls/btls-x509-lookup.h
new file mode 100644 (file)
index 0000000..df3d37f
--- /dev/null
@@ -0,0 +1,58 @@
+//
+//  btls-x509-lookup.h
+//  MonoBtls
+//
+//  Created by Martin Baulig on 3/3/16.
+//  Copyright Â© 2016 Xamarin. All rights reserved.
+//
+
+#ifndef __btls__btls_x509_lookup__
+#define __btls__btls_x509_lookup__
+
+#include <stdio.h>
+#include <btls-ssl.h>
+#include <btls-x509.h>
+#include <btls-x509-store.h>
+
+typedef enum {
+       MONO_BTLS_X509_LOOKUP_TYPE_UNKNOWN = 0,
+       MONO_BTLS_X509_LOOKUP_TYPE_FILE,
+       MONO_BTLS_X509_LOOKUP_TYPE_HASH_DIR,
+       MONO_BTLS_X509_LOOKUP_TYPE_MONO
+} MonoBtlsX509LookupType;
+
+MonoBtlsX509Lookup *
+mono_btls_x509_lookup_new (MonoBtlsX509Store *store, MonoBtlsX509LookupType type);
+
+int
+mono_btls_x509_lookup_load_file (MonoBtlsX509Lookup *lookup, const char *file, MonoBtlsX509FileType type);
+
+int
+mono_btls_x509_lookup_add_dir (MonoBtlsX509Lookup *lookup, const char *dir, MonoBtlsX509FileType type);
+
+MonoBtlsX509Lookup *
+mono_btls_x509_lookup_up_ref (MonoBtlsX509Lookup *lookup);
+
+int
+mono_btls_x509_lookup_free (MonoBtlsX509Lookup *lookup);
+
+int
+mono_btls_x509_lookup_init (MonoBtlsX509Lookup *lookup);
+
+MonoBtlsX509LookupType
+mono_btls_x509_lookup_get_type (MonoBtlsX509Lookup *lookup);
+
+X509_LOOKUP *
+mono_btls_x509_lookup_peek_lookup (MonoBtlsX509Lookup *lookup);
+
+int
+mono_btls_x509_lookup_shutdown (MonoBtlsX509Lookup *lookup);
+
+X509 *
+mono_btls_x509_lookup_by_subject (MonoBtlsX509Lookup *lookup, MonoBtlsX509Name *name);
+
+X509 *
+mono_btls_x509_lookup_by_fingerprint (MonoBtlsX509Lookup *lookup, unsigned char *bytes, int len);
+
+#endif /* defined(__btls__btls_x509_lookup__) */
+
diff --git a/mono/btls/btls-x509-name.c b/mono/btls/btls-x509-name.c
new file mode 100644 (file)
index 0000000..7a40f75
--- /dev/null
@@ -0,0 +1,296 @@
+//
+//  btls-x509-name.c
+//  MonoBtls
+//
+//  Created by Martin Baulig on 3/5/16.
+//  Copyright Â© 2016 Xamarin. All rights reserved.
+//
+
+#include <btls-x509-name.h>
+
+struct MonoBtlsX509Name {
+       int owns;
+       X509_NAME *name;
+};
+
+MonoBtlsX509Name *
+mono_btls_x509_name_from_name (X509_NAME *xn)
+{
+       MonoBtlsX509Name *name;
+
+       name = OPENSSL_malloc (sizeof (MonoBtlsX509Name));
+       if (!name)
+               return NULL;
+
+       memset(name, 0, sizeof(MonoBtlsX509Name));
+       name->name = xn;
+       return name;
+}
+
+MonoBtlsX509Name *
+mono_btls_x509_name_copy (X509_NAME *xn)
+{
+       MonoBtlsX509Name *name;
+
+       name = OPENSSL_malloc (sizeof (MonoBtlsX509Name));
+       if (!name)
+               return NULL;
+
+       memset(name, 0, sizeof(MonoBtlsX509Name));
+       name->name = X509_NAME_dup(xn);
+       name->owns = 1;
+       return name;
+}
+
+void
+mono_btls_x509_name_free (MonoBtlsX509Name *name)
+{
+       if (name->owns) {
+               if (name->name) {
+                       X509_NAME_free(name->name);
+                       name->name = NULL;
+               }
+       }
+       OPENSSL_free(name);
+}
+
+X509_NAME *
+mono_btls_x509_name_peek_name (MonoBtlsX509Name *name)
+{
+       return name->name;
+}
+
+int
+mono_btls_x509_name_print_bio (MonoBtlsX509Name *name, BIO *bio)
+{
+       return X509_NAME_print_ex (bio, name->name, 0, ASN1_STRFLGS_RFC2253 | XN_FLAG_FN_SN | XN_FLAG_SEP_CPLUS_SPC | XN_FLAG_DN_REV);
+}
+
+int
+mono_btls_x509_name_get_raw_data (MonoBtlsX509Name *name, void **buffer, int use_canon_enc)
+{
+       int len;
+       void *ptr;
+
+       if (use_canon_enc) {
+               // make sure canon_enc is initialized.
+               i2d_X509_NAME (name->name, NULL);
+
+               len = name->name->canon_enclen;
+               ptr = name->name->canon_enc;
+       } else {
+               len = (int)name->name->bytes->length;
+               ptr = name->name->bytes->data;
+       }
+
+       *buffer = OPENSSL_malloc (len);
+       if (!*buffer)
+               return 0;
+
+       memcpy (*buffer, ptr, len);
+       return len;
+}
+
+MonoBtlsX509Name *
+mono_btls_x509_name_from_data (const void *data, int len, int use_canon_enc)
+{
+       MonoBtlsX509Name *name;
+       uint8_t *buf;
+       const unsigned char *ptr;
+       X509_NAME *ret;
+
+       name = OPENSSL_malloc (sizeof (MonoBtlsX509Name));
+       if (!name)
+               return NULL;
+
+       memset (name, 0, sizeof(MonoBtlsX509Name));
+       name->owns = 1;
+
+       name->name = X509_NAME_new ();
+       if (!name->name) {
+               OPENSSL_free (name);
+               return NULL;
+       }
+
+       if (use_canon_enc) {
+               CBB cbb, contents;
+               size_t buf_len;
+
+               // re-add ASN1 SEQUENCE header.
+               CBB_init(&cbb, 0);
+               if (!CBB_add_asn1(&cbb, &contents, 0x30) ||
+                   !CBB_add_bytes(&contents, data, len) ||
+                   !CBB_finish(&cbb, &buf, &buf_len)) {
+                       CBB_cleanup (&cbb);
+                       mono_btls_x509_name_free (name);
+                       return NULL;
+               }
+
+               ptr = buf;
+               len = (int)buf_len;
+       } else {
+               ptr = data;
+               buf = NULL;
+       }
+
+       ret = d2i_X509_NAME (&name->name, &ptr, len);
+
+       if (buf)
+               OPENSSL_free (buf);
+
+       if (ret != name->name) {
+               mono_btls_x509_name_free (name);
+               return NULL;
+       }
+
+       return name;
+}
+
+int
+mono_btls_x509_name_print_string (MonoBtlsX509Name *name, char *buffer, int size)
+{
+       *buffer = 0;
+       return X509_NAME_oneline (name->name, buffer, size) != NULL;
+}
+
+long
+mono_btls_x509_name_hash (MonoBtlsX509Name *name)
+{
+       return X509_NAME_hash (name->name);
+}
+
+long
+mono_btls_x509_name_hash_old (MonoBtlsX509Name *name)
+{
+       return X509_NAME_hash_old (name->name);
+}
+
+int
+mono_btls_x509_name_get_entry_count (MonoBtlsX509Name *name)
+{
+       return X509_NAME_entry_count (name->name);
+}
+
+static MonoBtlsX509NameEntryType
+nid2mono (int nid)
+{
+       switch (nid) {
+       case NID_countryName:
+               return MONO_BTLS_X509_NAME_ENTRY_TYPE_COUNTRY_NAME;
+       case NID_organizationName:
+               return MONO_BTLS_X509_NAME_ENTRY_TYPE_ORGANIZATION_NAME;
+       case NID_organizationalUnitName:
+               return MONO_BTLS_X509_NAME_ENTRY_TYPE_ORGANIZATIONAL_UNIT_NAME;
+       case NID_commonName:
+               return MONO_BTLS_X509_NAME_ENTRY_TYPE_COMMON_NAME;
+       case NID_localityName:
+               return MONO_BTLS_X509_NAME_ENTRY_TYPE_LOCALITY_NAME;
+       case NID_stateOrProvinceName:
+               return MONO_BTLS_X509_NAME_ENTRY_TYPE_STATE_OR_PROVINCE_NAME;
+       case NID_streetAddress:
+               return MONO_BTLS_X509_NAME_ENTRY_TYPE_STREET_ADDRESS;
+       case NID_serialNumber:
+               return MONO_BTLS_X509_NAME_ENTRY_TYPE_SERIAL_NUMBER;
+       case NID_domainComponent:
+               return MONO_BTLS_X509_NAME_ENTRY_TYPE_DOMAIN_COMPONENT;
+       case NID_userId:
+               return MONO_BTLS_X509_NAME_ENTRY_TYPE_USER_ID;
+       case NID_dnQualifier:
+               return MONO_BTLS_X509_NAME_ENTRY_TYPE_DN_QUALIFIER;
+       case NID_title:
+               return MONO_BTLS_X509_NAME_ENTRY_TYPE_TITLE;
+       case NID_surname:
+               return MONO_BTLS_X509_NAME_ENTRY_TYPE_SURNAME;
+       case NID_givenName:
+               return MONO_BTLS_X509_NAME_ENTRY_TYPE_GIVEN_NAME;
+       case NID_initials:
+               return MONO_BTLS_X509_NAME_ENTRY_TYPE_INITIAL;
+       default:
+               return MONO_BTLS_X509_NAME_ENTRY_TYPE_UNKNOWN;
+       }
+}
+
+MonoBtlsX509NameEntryType
+mono_btls_x509_name_get_entry_type (MonoBtlsX509Name *name, int index)
+{
+       X509_NAME_ENTRY *entry;
+       ASN1_OBJECT *obj;
+
+       if (index >= X509_NAME_entry_count (name->name))
+               return -1;
+
+       entry = X509_NAME_get_entry (name->name, index);
+       if (!entry)
+               return -1;
+
+       obj = X509_NAME_ENTRY_get_object (entry);
+       if (!obj)
+               return -1;
+
+       return nid2mono (OBJ_obj2nid (obj));
+}
+
+int
+mono_btls_x509_name_get_entry_oid (MonoBtlsX509Name *name, int index, char *buffer, int size)
+{
+       X509_NAME_ENTRY *entry;
+       ASN1_OBJECT *obj;
+
+       if (index >= X509_NAME_entry_count (name->name))
+               return 0;
+
+       entry = X509_NAME_get_entry (name->name, index);
+       if (!entry)
+               return 0;
+
+       obj = X509_NAME_ENTRY_get_object (entry);
+       if (!obj)
+               return 0;
+
+       return OBJ_obj2txt (buffer, size, obj, 1);
+}
+
+int
+mono_btls_x509_name_get_entry_oid_data (MonoBtlsX509Name *name, int index, const void **data)
+{
+       X509_NAME_ENTRY *entry;
+       ASN1_OBJECT *obj;
+
+       if (index >= X509_NAME_entry_count (name->name))
+               return -1;
+
+       entry = X509_NAME_get_entry (name->name, index);
+       if (!entry)
+               return -1;
+
+       obj = X509_NAME_ENTRY_get_object (entry);
+       if (!obj)
+               return -1;
+
+       *data = obj->data;
+       return obj->length;
+}
+
+int
+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;
+
+       entry = X509_NAME_get_entry (name->name, index);
+       if (!entry)
+               return 0;
+
+       data = X509_NAME_ENTRY_get_data (entry);
+       if (!data)
+               return 0;
+
+       *tag = data->type;
+       return ASN1_STRING_to_UTF8 (str, data);
+}
diff --git a/mono/btls/btls-x509-name.h b/mono/btls/btls-x509-name.h
new file mode 100644 (file)
index 0000000..604de2b
--- /dev/null
@@ -0,0 +1,80 @@
+//
+//  btls-x509-name.h
+//  MonoBtls
+//
+//  Created by Martin Baulig on 3/5/16.
+//  Copyright Â© 2016 Xamarin. All rights reserved.
+//
+
+#ifndef __btls__btls_x509_name__
+#define __btls__btls_x509_name__
+
+#include <stdio.h>
+#include <btls-ssl.h>
+
+typedef enum {
+       MONO_BTLS_X509_NAME_ENTRY_TYPE_UNKNOWN = 0,
+       MONO_BTLS_X509_NAME_ENTRY_TYPE_COUNTRY_NAME,
+       MONO_BTLS_X509_NAME_ENTRY_TYPE_ORGANIZATION_NAME,
+       MONO_BTLS_X509_NAME_ENTRY_TYPE_ORGANIZATIONAL_UNIT_NAME,
+       MONO_BTLS_X509_NAME_ENTRY_TYPE_COMMON_NAME,
+       MONO_BTLS_X509_NAME_ENTRY_TYPE_LOCALITY_NAME,
+       MONO_BTLS_X509_NAME_ENTRY_TYPE_STATE_OR_PROVINCE_NAME,
+       MONO_BTLS_X509_NAME_ENTRY_TYPE_STREET_ADDRESS,
+       MONO_BTLS_X509_NAME_ENTRY_TYPE_SERIAL_NUMBER,
+       MONO_BTLS_X509_NAME_ENTRY_TYPE_DOMAIN_COMPONENT,
+       MONO_BTLS_X509_NAME_ENTRY_TYPE_USER_ID,
+       MONO_BTLS_X509_NAME_ENTRY_TYPE_EMAIL,
+       MONO_BTLS_X509_NAME_ENTRY_TYPE_DN_QUALIFIER,
+       MONO_BTLS_X509_NAME_ENTRY_TYPE_TITLE,
+       MONO_BTLS_X509_NAME_ENTRY_TYPE_SURNAME,
+       MONO_BTLS_X509_NAME_ENTRY_TYPE_GIVEN_NAME,
+       MONO_BTLS_X509_NAME_ENTRY_TYPE_INITIAL
+} MonoBtlsX509NameEntryType;
+
+MonoBtlsX509Name *
+mono_btls_x509_name_from_name (X509_NAME *name);
+
+MonoBtlsX509Name *
+mono_btls_x509_name_copy (X509_NAME *xn);
+
+void
+mono_btls_x509_name_free (MonoBtlsX509Name *name);
+
+X509_NAME *
+mono_btls_x509_name_peek_name (MonoBtlsX509Name *name);
+
+MonoBtlsX509Name *
+mono_btls_x509_name_from_data (const void *data, int len, int use_canon_enc);
+
+int
+mono_btls_x509_name_print_bio (MonoBtlsX509Name *name, BIO *bio);
+
+int
+mono_btls_x509_name_print_string (MonoBtlsX509Name *name, char *buffer, int size);
+
+int
+mono_btls_x509_name_get_raw_data (MonoBtlsX509Name *name, void **buffer, int use_canon_enc);
+
+long
+mono_btls_x509_name_hash (MonoBtlsX509Name *name);
+
+long
+mono_btls_x509_name_hash_old (MonoBtlsX509Name *name);
+
+int
+mono_btls_x509_name_get_entry_count (MonoBtlsX509Name *name);
+
+MonoBtlsX509NameEntryType
+mono_btls_x509_name_get_entry_type (MonoBtlsX509Name *name, int index);
+
+int
+mono_btls_x509_name_get_entry_oid (MonoBtlsX509Name *name, int index, char *buffer, int size);
+
+int
+mono_btls_x509_name_get_entry_oid_data (MonoBtlsX509Name *name, int index, const void **data);
+
+int
+mono_btls_x509_name_get_entry_value (MonoBtlsX509Name *name, int index, int *tag, unsigned char **str);
+
+#endif /* __btls__btls_x509_name__ */
diff --git a/mono/btls/btls-x509-revoked.c b/mono/btls/btls-x509-revoked.c
new file mode 100644 (file)
index 0000000..e6fb4b0
--- /dev/null
@@ -0,0 +1,72 @@
+//
+//  btls-x509-revoked.c
+//  MonoBtls
+//
+//  Created by Martin Baulig on 3/23/16.
+//  Copyright Â© 2016 Xamarin. All rights reserved.
+//
+
+#include <btls-x509-revoked.h>
+
+struct MonoBtlsX509Revoked {
+       MonoBtlsX509Crl *owner;
+       X509_REVOKED *revoked;
+};
+
+MonoBtlsX509Revoked *
+mono_btls_x509_revoked_new (MonoBtlsX509Crl *owner, X509_REVOKED *revoked)
+{
+       MonoBtlsX509Revoked *instance;
+
+       instance = OPENSSL_malloc (sizeof (MonoBtlsX509Revoked));
+       memset (instance, 0, sizeof (MonoBtlsX509Revoked));
+
+       instance->owner = mono_btls_x509_crl_ref (owner);
+       instance->revoked = revoked;
+       return instance;
+}
+
+void
+mono_btls_x509_revoked_free (MonoBtlsX509Revoked *revoked)
+{
+       mono_btls_x509_crl_free (revoked->owner);
+       OPENSSL_free (revoked);
+}
+
+int
+mono_btls_x509_revoked_get_serial_number (MonoBtlsX509Revoked *revoked, char *buffer, int size)
+{
+       ASN1_INTEGER *serial;
+
+       serial = revoked->revoked->serialNumber;
+       if (serial->length == 0 || serial->length+1 > size)
+               return 0;
+
+       memcpy (buffer, serial->data, serial->length);
+       return serial->length;
+}
+
+long
+mono_btls_x509_revoked_get_revocation_date (MonoBtlsX509Revoked *revoked)
+{
+       ASN1_TIME *date;
+
+       date = revoked->revoked->revocationDate;
+       if (!date)
+               return 0;
+
+       return mono_btls_util_asn1_time_to_ticks (date);
+}
+
+int
+mono_btls_x509_revoked_get_reason (MonoBtlsX509Revoked *revoked)
+{
+       return revoked->revoked->reason;
+}
+
+int
+mono_btls_x509_revoked_get_sequence (MonoBtlsX509Revoked *revoked)
+{
+       return revoked->revoked->sequence;
+}
+
diff --git a/mono/btls/btls-x509-revoked.h b/mono/btls/btls-x509-revoked.h
new file mode 100644 (file)
index 0000000..e1229c6
--- /dev/null
@@ -0,0 +1,34 @@
+//
+//  btls-x509-revoked.h
+//  MonoBtls
+//
+//  Created by Martin Baulig on 3/23/16.
+//  Copyright Â© 2016 Xamarin. All rights reserved.
+//
+
+#ifndef __btls__btls_x509_revoked__
+#define __btls__btls_x509_revoked__
+
+#include <stdio.h>
+#include <btls-ssl.h>
+#include <btls-x509-crl.h>
+
+MonoBtlsX509Revoked *
+mono_btls_x509_revoked_new (MonoBtlsX509Crl *owner, X509_REVOKED *revoked);
+
+void
+mono_btls_x509_revoked_free (MonoBtlsX509Revoked *revoked);
+
+int
+mono_btls_x509_revoked_get_serial_number (MonoBtlsX509Revoked *revoked, char *buffer, int size);
+
+long
+mono_btls_x509_revoked_get_revocation_date (MonoBtlsX509Revoked *revoked);
+
+int
+mono_btls_x509_revoked_get_reason (MonoBtlsX509Revoked *revoked);
+
+int
+mono_btls_x509_revoked_get_sequence (MonoBtlsX509Revoked *revoked);
+
+#endif /* __btls__btls_x509_revoked__ */
diff --git a/mono/btls/btls-x509-store-ctx.c b/mono/btls/btls-x509-store-ctx.c
new file mode 100644 (file)
index 0000000..f023e31
--- /dev/null
@@ -0,0 +1,217 @@
+//
+//  btls-x509-store-ctx.c
+//  MonoBtls
+//
+//  Created by Martin Baulig on 3/5/16.
+//  Copyright Â© 2016 Xamarin. All rights reserved.
+//
+
+#include <btls-x509-store-ctx.h>
+
+struct MonoBtlsX509StoreCtx {
+       int owns;
+       X509_STORE_CTX *ctx;
+       CRYPTO_refcount_t references;
+       MonoBtlsX509Store *store;
+       MonoBtlsX509Chain *chain;
+};
+
+MonoBtlsX509StoreCtx *
+mono_btls_x509_store_ctx_from_ptr (X509_STORE_CTX *ptr)
+{
+       MonoBtlsX509StoreCtx *ctx;
+
+       ctx = OPENSSL_malloc (sizeof(MonoBtlsX509StoreCtx));
+       if (!ctx)
+               return NULL;
+
+       memset (ctx, 0, sizeof (MonoBtlsX509StoreCtx));
+       ctx->ctx = ptr;
+       ctx->references = 1;
+       return ctx;
+}
+
+MonoBtlsX509StoreCtx *
+mono_btls_x509_store_ctx_new (void)
+{
+       MonoBtlsX509StoreCtx *ctx;
+
+       ctx = OPENSSL_malloc (sizeof(MonoBtlsX509StoreCtx));
+       if (!ctx)
+               return NULL;
+
+       memset (ctx, 0, sizeof (MonoBtlsX509StoreCtx));
+       ctx->ctx = X509_STORE_CTX_new ();
+       ctx->references = 1;
+       ctx->owns = 1;
+       return ctx;
+}
+
+MonoBtlsX509StoreCtx *
+mono_btls_x509_store_ctx_up_ref (MonoBtlsX509StoreCtx *ctx)
+{
+       CRYPTO_refcount_inc (&ctx->references);
+       return ctx;
+}
+
+int
+mono_btls_x509_store_ctx_free (MonoBtlsX509StoreCtx *ctx)
+{
+       if (!CRYPTO_refcount_dec_and_test_zero (&ctx->references))
+               return 0;
+
+       if (ctx->owns) {
+               X509_STORE_CTX_cleanup (ctx->ctx);
+               X509_STORE_CTX_free (ctx->ctx);
+               ctx->owns = 0;
+       }
+       if (ctx->store) {
+               mono_btls_x509_store_free (ctx->store);
+               ctx->store = NULL;
+       }
+       if (ctx->chain) {
+               mono_btls_x509_chain_free (ctx->chain);
+               ctx->chain = NULL;
+       }
+       OPENSSL_free (ctx);
+       return 1;
+}
+
+int
+mono_btls_x509_store_ctx_get_error (MonoBtlsX509StoreCtx *ctx, const char **error_string)
+{
+       int error;
+
+       error = X509_STORE_CTX_get_error (ctx->ctx);
+       if (error_string)
+               *error_string = X509_verify_cert_error_string (error);
+       return error;
+}
+
+int
+mono_btls_x509_store_ctx_get_error_depth (MonoBtlsX509StoreCtx *ctx)
+{
+       return X509_STORE_CTX_get_error_depth (ctx->ctx);
+}
+
+MonoBtlsX509Chain *
+mono_btls_x509_store_ctx_get_chain (MonoBtlsX509StoreCtx *ctx)
+{
+       STACK_OF(X509) *certs;
+
+       certs = X509_STORE_CTX_get_chain (ctx->ctx);
+       if (!certs)
+               return NULL;
+
+       return mono_btls_x509_chain_from_certs (certs);
+}
+
+MonoBtlsX509Chain *
+mono_btls_x509_store_ctx_get_untrusted (MonoBtlsX509StoreCtx *ctx)
+{
+       STACK_OF(X509) *untrusted;
+
+       /*
+        * Unfortunately, there is no accessor function for this.
+        *
+        * This is the set of certificate that's passed in by
+        * X509_STORE_CTX_init() and X509_STORE_CTX_set_chain().
+        */
+       untrusted = ctx->ctx->untrusted;
+       if (!untrusted)
+               return NULL;
+
+       return mono_btls_x509_chain_from_certs (untrusted);
+}
+
+int
+mono_btls_x509_store_ctx_init (MonoBtlsX509StoreCtx *ctx,
+                                  MonoBtlsX509Store *store, MonoBtlsX509Chain *chain)
+{
+       STACK_OF(X509) *certs;
+       X509 *leaf;
+       int ret;
+
+       if (ctx->store)
+               return 0;
+
+       certs = mono_btls_x509_chain_peek_certs (chain);
+       if (!certs || !sk_X509_num (certs))
+               return 0;
+
+       ctx->store = mono_btls_x509_store_up_ref(store);
+       ctx->chain = mono_btls_x509_chain_up_ref(chain);
+
+       leaf = sk_X509_value (certs, 0);
+       ret = X509_STORE_CTX_init (ctx->ctx, mono_btls_x509_store_peek_store (store), leaf, certs);
+       if (ret != 1)
+               return ret;
+
+       X509_STORE_CTX_set_app_data (ctx->ctx, ctx);
+       return 1;
+}
+
+int
+mono_btls_x509_store_ctx_set_param (MonoBtlsX509StoreCtx *ctx, MonoBtlsX509VerifyParam *param)
+{
+       return X509_VERIFY_PARAM_set1 (X509_STORE_CTX_get0_param (ctx->ctx), mono_btls_x509_verify_param_peek_param (param));
+}
+
+int
+mono_btls_x509_store_ctx_verify_cert (MonoBtlsX509StoreCtx *ctx)
+{
+       return X509_verify_cert (ctx->ctx);
+}
+
+X509 *
+mono_btls_x509_store_ctx_get_by_subject (MonoBtlsX509StoreCtx *ctx, MonoBtlsX509Name *name)
+{
+       X509_OBJECT obj;
+       X509 *x509;
+       int ret;
+
+       ret = X509_STORE_get_by_subject (ctx->ctx, X509_LU_X509, mono_btls_x509_name_peek_name (name), &obj);
+       if (ret != X509_LU_X509) {
+               X509_OBJECT_free_contents (&obj);
+               return NULL;
+       }
+
+       x509 = X509_up_ref (obj.data.x509);
+       return x509;
+}
+
+X509 *
+mono_btls_x509_store_ctx_get_current_cert (MonoBtlsX509StoreCtx *ctx)
+{
+       X509 *x509 = X509_STORE_CTX_get_current_cert (ctx->ctx);
+       if (!x509)
+               return NULL;
+       return X509_up_ref (x509);
+}
+
+X509 *
+mono_btls_x509_store_ctx_get_current_issuer (MonoBtlsX509StoreCtx *ctx)
+{
+       X509 *x509 = X509_STORE_CTX_get0_current_issuer (ctx->ctx);
+       if (!x509)
+               return NULL;
+       return X509_up_ref (x509);
+}
+
+MonoBtlsX509VerifyParam *
+mono_btls_x509_store_ctx_get_verify_param (MonoBtlsX509StoreCtx *ctx)
+{
+       X509_VERIFY_PARAM *param;
+
+       param = X509_STORE_CTX_get0_param (ctx->ctx);
+       if (!param)
+               return NULL;
+
+       return mono_btls_x509_verify_param_from_store_ctx (ctx, param);
+}
+
+int
+mono_btls_x509_store_ctx_get_foo (MonoBtlsX509StoreCtx *ctx)
+{
+       return 0;
+}
\ No newline at end of file
diff --git a/mono/btls/btls-x509-store-ctx.h b/mono/btls/btls-x509-store-ctx.h
new file mode 100644 (file)
index 0000000..188092e
--- /dev/null
@@ -0,0 +1,66 @@
+//
+//  btls-x509-store-ctx.h
+//  MonoBtls
+//
+//  Created by Martin Baulig on 3/3/16.
+//  Copyright Â© 2016 Xamarin. All rights reserved.
+//
+
+#ifndef __btls__btls_x509_store_ctx__
+#define __btls__btls_x509_store_ctx__
+
+#include <stdio.h>
+#include <btls-ssl.h>
+#include <btls-x509-chain.h>
+#include <btls-x509-name.h>
+#include <btls-x509-store.h>
+#include <btls-x509-verify-param.h>
+
+MonoBtlsX509StoreCtx *
+mono_btls_x509_store_ctx_from_ptr (X509_STORE_CTX *ptr);
+
+MonoBtlsX509StoreCtx *
+mono_btls_x509_store_ctx_new (void);
+
+MonoBtlsX509StoreCtx *
+mono_btls_x509_store_ctx_up_ref (MonoBtlsX509StoreCtx *ctx);
+
+int
+mono_btls_x509_store_ctx_free (MonoBtlsX509StoreCtx *ctx);
+
+int
+mono_btls_x509_store_ctx_get_error (MonoBtlsX509StoreCtx *ctx, const char **error_string);
+
+int
+mono_btls_x509_store_ctx_get_error_depth (MonoBtlsX509StoreCtx *ctx);
+
+MonoBtlsX509Chain *
+mono_btls_x509_store_ctx_get_chain (MonoBtlsX509StoreCtx *ctx);
+
+X509 *
+mono_btls_x509_store_ctx_get_current_cert (MonoBtlsX509StoreCtx *ctx);
+
+X509 *
+mono_btls_x509_store_ctx_get_current_issuer (MonoBtlsX509StoreCtx *ctx);
+
+int
+mono_btls_x509_store_ctx_init (MonoBtlsX509StoreCtx *ctx,
+                                  MonoBtlsX509Store *store, MonoBtlsX509Chain *chain);
+
+int
+mono_btls_x509_store_ctx_set_param (MonoBtlsX509StoreCtx *ctx, MonoBtlsX509VerifyParam *param);
+
+X509 *
+mono_btls_x509_store_ctx_get_by_subject (MonoBtlsX509StoreCtx *ctx, MonoBtlsX509Name *name);
+
+int
+mono_btls_x509_store_ctx_verify_cert (MonoBtlsX509StoreCtx *ctx);
+
+MonoBtlsX509VerifyParam *
+mono_btls_x509_store_ctx_get_verify_param (MonoBtlsX509StoreCtx *ctx);
+
+MonoBtlsX509Chain *
+mono_btls_x509_store_ctx_get_untrusted (MonoBtlsX509StoreCtx *ctx);
+
+#endif /* defined(__btls__btls_x509_store_ctx__) */
+
diff --git a/mono/btls/btls-x509-store.c b/mono/btls/btls-x509-store.c
new file mode 100644 (file)
index 0000000..f2c826e
--- /dev/null
@@ -0,0 +1,110 @@
+//
+//  btls-x509-store.c
+//  MonoBtls
+//
+//  Created by Martin Baulig on 3/3/16.
+//  Copyright Â© 2016 Xamarin. All rights reserved.
+//
+
+#include <btls-x509-store.h>
+
+struct MonoBtlsX509Store {
+       X509_STORE *store;
+       CRYPTO_refcount_t references;
+};
+
+MonoBtlsX509Store *
+mono_btls_x509_store_from_store (X509_STORE *ctx)
+{
+       MonoBtlsX509Store *store;
+
+       store = OPENSSL_malloc (sizeof(MonoBtlsX509Store));
+       if (!store)
+               return NULL;
+
+       memset (store, 0, sizeof(MonoBtlsX509Store));
+       store->store = ctx;
+       CRYPTO_refcount_inc (&store->store->references);
+       store->references = 1;
+       return store;
+}
+
+MonoBtlsX509Store *
+mono_btls_x509_store_from_ctx (X509_STORE_CTX *ctx)
+{
+       return mono_btls_x509_store_from_store (ctx->ctx);
+}
+
+MonoBtlsX509Store *
+mono_btls_x509_store_new (void)
+{
+       MonoBtlsX509Store *store;
+
+       store = OPENSSL_malloc (sizeof(MonoBtlsX509Store));
+       if (!store)
+               return NULL;
+
+       memset (store, 0, sizeof(MonoBtlsX509Store));
+       store->store = X509_STORE_new ();
+       store->references = 1;
+       return store;
+}
+
+X509_STORE *
+mono_btls_x509_store_peek_store (MonoBtlsX509Store *store)
+{
+       return store->store;
+}
+
+MonoBtlsX509Store *
+mono_btls_x509_store_from_ssl_ctx (MonoBtlsSslCtx *ctx)
+{
+       X509_STORE *store = mono_btls_ssl_ctx_peek_store (ctx);
+       return mono_btls_x509_store_from_store (store);
+}
+
+int
+mono_btls_x509_store_free (MonoBtlsX509Store *store)
+{
+       if (!CRYPTO_refcount_dec_and_test_zero(&store->references))
+               return 0;
+
+       if (store->store) {
+               X509_STORE_free (store->store);
+               store->store = NULL;
+       }
+       OPENSSL_free (store);
+       return 1;
+}
+
+MonoBtlsX509Store *
+mono_btls_x509_store_up_ref (MonoBtlsX509Store *store)
+{
+       CRYPTO_refcount_inc (&store->references);
+       return store;
+}
+
+int
+mono_btls_x509_store_add_cert (MonoBtlsX509Store *store, X509 *cert)
+{
+       return X509_STORE_add_cert (store->store, cert);
+}
+
+int
+mono_btls_x509_store_load_locations (MonoBtlsX509Store *store, const char *file, const char *path)
+{
+       return X509_STORE_load_locations (store->store, file, path);
+}
+
+int
+mono_btls_x509_store_set_default_paths (MonoBtlsX509Store *store)
+{
+       return X509_STORE_set_default_paths (store->store);
+}
+
+int
+mono_btls_x509_store_get_count (MonoBtlsX509Store *store)
+{
+       return (int)sk_X509_OBJECT_num (store->store->objs);
+}
+
diff --git a/mono/btls/btls-x509-store.h b/mono/btls/btls-x509-store.h
new file mode 100644 (file)
index 0000000..67ffe00
--- /dev/null
@@ -0,0 +1,46 @@
+//
+//  btls-x509-store.h
+//  MonoBtls
+//
+//  Created by Martin Baulig on 3/3/16.
+//  Copyright Â© 2016 Xamarin. All rights reserved.
+//
+
+#ifndef __btls__btls_x509_store__
+#define __btls__btls_x509_store__
+
+#include <stdio.h>
+#include <btls-ssl.h>
+
+MonoBtlsX509Store *
+mono_btls_x509_store_new (void);
+
+MonoBtlsX509Store *
+mono_btls_x509_store_from_ctx (X509_STORE_CTX *ctx);
+
+MonoBtlsX509Store *
+mono_btls_x509_store_from_ssl_ctx (MonoBtlsSslCtx *ctx);
+
+MonoBtlsX509Store *
+mono_btls_x509_store_up_ref (MonoBtlsX509Store *store);
+
+int
+mono_btls_x509_store_free (MonoBtlsX509Store *store);
+
+X509_STORE *
+mono_btls_x509_store_peek_store (MonoBtlsX509Store *store);
+
+int
+mono_btls_x509_store_add_cert (MonoBtlsX509Store *store, X509 *cert);
+
+int
+mono_btls_x509_store_load_locations (MonoBtlsX509Store *store, const char *file, const char *path);
+
+int
+mono_btls_x509_store_set_default_paths (MonoBtlsX509Store *store);
+
+int
+mono_btls_x509_store_get_count (MonoBtlsX509Store *store);
+
+#endif /* defined(__btls__btls_x509_store__) */
+
diff --git a/mono/btls/btls-x509-verify-param.c b/mono/btls/btls-x509-verify-param.c
new file mode 100644 (file)
index 0000000..643fdcd
--- /dev/null
@@ -0,0 +1,221 @@
+//
+//  btls-x509-verify-param.c
+//  MonoBtls
+//
+//  Created by Martin Baulig on 3/5/16.
+//  Copyright Â© 2016 Xamarin. All rights reserved.
+//
+
+#include <btls-x509-verify-param.h>
+#include <btls-x509-store-ctx.h>
+
+struct MonoBtlsX509VerifyParam {
+       int owns;
+       MonoBtlsX509StoreCtx *owner;
+       X509_VERIFY_PARAM *param;
+};
+
+MonoBtlsX509VerifyParam *
+mono_btls_x509_verify_param_new (void)
+{
+       MonoBtlsX509VerifyParam *param;
+
+       param = OPENSSL_malloc (sizeof(MonoBtlsX509VerifyParam));
+       if (!param)
+               return NULL;
+       memset (param, 0, sizeof (MonoBtlsX509VerifyParam));
+       param->param = X509_VERIFY_PARAM_new();
+       param->owns = 1;
+       return param;
+}
+
+MonoBtlsX509VerifyParam *
+mono_btls_x509_verify_param_from_store_ctx (MonoBtlsX509StoreCtx *ctx, X509_VERIFY_PARAM *param)
+{
+       MonoBtlsX509VerifyParam *instance;
+
+       instance = OPENSSL_malloc (sizeof(MonoBtlsX509VerifyParam));
+       if (!instance)
+               return NULL;
+       memset (instance, 0, sizeof (MonoBtlsX509VerifyParam));
+       instance->param = param;
+       instance->owner = mono_btls_x509_store_ctx_up_ref (ctx);
+       return instance;
+}
+
+MonoBtlsX509VerifyParam *
+mono_btls_x509_verify_param_copy (const MonoBtlsX509VerifyParam *from)
+{
+       MonoBtlsX509VerifyParam *param;
+
+       param = mono_btls_x509_verify_param_new ();
+       if (!param)
+               return NULL;
+
+       X509_VERIFY_PARAM_set1 (param->param, from->param);
+       return param;
+}
+
+const X509_VERIFY_PARAM *
+mono_btls_x509_verify_param_peek_param (const MonoBtlsX509VerifyParam *param)
+{
+       return param->param;
+}
+
+int
+mono_btls_x509_verify_param_can_modify (MonoBtlsX509VerifyParam *param)
+{
+       return param->owns;
+}
+
+MonoBtlsX509VerifyParam *
+mono_btls_x509_verify_param_lookup (const char *name)
+{
+       MonoBtlsX509VerifyParam *param;
+       const X509_VERIFY_PARAM *p;
+
+       p = X509_VERIFY_PARAM_lookup(name);
+       if (!p)
+               return NULL;
+
+       param = OPENSSL_malloc (sizeof(MonoBtlsX509VerifyParam));
+       if (!param)
+               return NULL;
+       memset (param, 0, sizeof (MonoBtlsX509VerifyParam));
+       param->param = (X509_VERIFY_PARAM *)p;
+       return param;
+}
+
+void
+mono_btls_x509_verify_param_free (MonoBtlsX509VerifyParam *param)
+{
+       if (param->owns) {
+               if (param->param) {
+                       X509_VERIFY_PARAM_free (param->param);
+                       param->param = NULL;
+               }
+       }
+       if (param->owner) {
+               mono_btls_x509_store_ctx_free (param->owner);
+               param->owner = NULL;
+       }
+       OPENSSL_free (param);
+}
+
+int
+mono_btls_x509_verify_param_set_name (MonoBtlsX509VerifyParam *param, const char *name)
+{
+       if (!param->owns)
+               return -1;
+       return X509_VERIFY_PARAM_set1_name (param->param, name);
+}
+
+int
+mono_btls_x509_verify_param_set_host (MonoBtlsX509VerifyParam *param, const char *host, int namelen)
+{
+       if (!param->owns)
+               return -1;
+       return X509_VERIFY_PARAM_set1_host (param->param, host, namelen);
+}
+
+int
+mono_btls_x509_verify_param_add_host (MonoBtlsX509VerifyParam *param, const char *host, int namelen)
+{
+       if (!param->owns)
+               return -1;
+       return X509_VERIFY_PARAM_set1_host (param->param, host, namelen);
+}
+
+unsigned long
+mono_btls_x509_verify_param_get_flags (MonoBtlsX509VerifyParam *param)
+{
+       return X509_VERIFY_PARAM_get_flags (param->param);
+}
+
+int
+mono_btls_x509_verify_param_set_flags (MonoBtlsX509VerifyParam *param, unsigned long flags)
+{
+       if (!param->owns)
+               return -1;
+       return X509_VERIFY_PARAM_set_flags (param->param, flags);
+}
+
+MonoBtlsX509VerifyFlags
+mono_btls_x509_verify_param_get_mono_flags (MonoBtlsX509VerifyParam *param)
+{
+       MonoBtlsX509VerifyFlags current;
+       unsigned long flags;
+
+       if (!param->owns)
+               return -1;
+
+       current = 0;
+       flags = X509_VERIFY_PARAM_get_flags (param->param);
+
+       if (flags & X509_V_FLAG_CRL_CHECK)
+               current |= MONO_BTLS_X509_VERIFY_FLAGS_CRL_CHECK;
+       if (flags & X509_V_FLAG_CRL_CHECK_ALL)
+               current |= MONO_BTLS_X509_VERIFY_FLAGS_CRL_CHECK_ALL;
+       if (flags & X509_V_FLAG_X509_STRICT)
+               current |= MONO_BTLS_X509_VERIFY_FLAGS_X509_STRICT;
+
+       return current;
+}
+
+int
+mono_btls_x509_verify_param_set_mono_flags (MonoBtlsX509VerifyParam *param, MonoBtlsX509VerifyFlags flags)
+{
+       unsigned long current;
+
+       if (!param->owns)
+               return -1;
+
+       current = X509_VERIFY_PARAM_get_flags (param->param);
+       if (flags & MONO_BTLS_X509_VERIFY_FLAGS_CRL_CHECK)
+               current |= X509_V_FLAG_CRL_CHECK;
+       if (flags & MONO_BTLS_X509_VERIFY_FLAGS_CRL_CHECK_ALL)
+               current |= X509_V_FLAG_CRL_CHECK_ALL;
+       if (flags & MONO_BTLS_X509_VERIFY_FLAGS_X509_STRICT)
+               current |= X509_V_FLAG_X509_STRICT;
+
+       return X509_VERIFY_PARAM_set_flags (param->param, current);
+}
+
+int
+mono_btls_x509_verify_param_set_purpose (MonoBtlsX509VerifyParam *param, MonoBtlsX509Purpose purpose)
+{
+       if (!param->owns)
+               return -1;
+       return X509_VERIFY_PARAM_set_purpose (param->param, purpose);
+}
+
+int
+mono_btls_x509_verify_param_get_depth (MonoBtlsX509VerifyParam *param)
+{
+       return X509_VERIFY_PARAM_get_depth (param->param);
+}
+
+int
+mono_btls_x509_verify_param_set_depth (MonoBtlsX509VerifyParam *param, int depth)
+{
+       if (!param->owns)
+               return -1;
+       X509_VERIFY_PARAM_set_depth (param->param, depth);
+       return 1;
+}
+
+int
+mono_btls_x509_verify_param_set_time (MonoBtlsX509VerifyParam *param, long time)
+{
+       if (!param->owns)
+               return -1;
+       X509_VERIFY_PARAM_set_time (param->param, time);
+       return 1;
+}
+
+char *
+mono_btls_x509_verify_param_get_peername (MonoBtlsX509VerifyParam *param)
+{
+       char *peer = X509_VERIFY_PARAM_get0_peername (param->param);
+       return peer;
+}
diff --git a/mono/btls/btls-x509-verify-param.h b/mono/btls/btls-x509-verify-param.h
new file mode 100644 (file)
index 0000000..6f4f1b5
--- /dev/null
@@ -0,0 +1,81 @@
+//
+//  btls-x509-verify-param.h
+//  MonoBtls
+//
+//  Created by Martin Baulig on 3/3/16.
+//  Copyright Â© 2016 Xamarin. All rights reserved.
+//
+
+#ifndef __btls__btls_x509_verify_param__
+#define __btls__btls_x509_verify_param__
+
+#include <stdio.h>
+#include <btls-ssl.h>
+#include <btls-x509.h>
+
+typedef enum {
+       MONO_BTLS_X509_VERIFY_FLAGS_DEFAULT             = 0,
+       MONO_BTLS_X509_VERIFY_FLAGS_CRL_CHECK   = 1,
+       MONO_BTLS_X509_VERIFY_FLAGS_CRL_CHECK_ALL       = 2,
+       MONO_BTLS_X509_VERIFY_FLAGS_X509_STRICT = 4
+} MonoBtlsX509VerifyFlags;
+
+MonoBtlsX509VerifyParam *
+mono_btls_x509_verify_param_new (void);
+
+MonoBtlsX509VerifyParam *
+mono_btls_x509_verify_param_from_store_ctx (MonoBtlsX509StoreCtx *ctx, X509_VERIFY_PARAM *param);
+
+MonoBtlsX509VerifyParam *
+mono_btls_x509_verify_param_copy (const MonoBtlsX509VerifyParam *from);
+
+void
+mono_btls_x509_verify_param_free (MonoBtlsX509VerifyParam *param);
+
+const X509_VERIFY_PARAM *
+mono_btls_x509_verify_param_peek_param (const MonoBtlsX509VerifyParam *param);
+
+int
+mono_btls_x509_verify_param_can_modify (MonoBtlsX509VerifyParam *param);
+
+MonoBtlsX509VerifyParam *
+mono_btls_x509_verify_param_lookup (const char *name);
+
+int
+mono_btls_x509_verify_param_set_name (MonoBtlsX509VerifyParam *param, const char *name);
+
+int
+mono_btls_x509_verify_param_set_host (MonoBtlsX509VerifyParam *param, const char *host, int namelen);
+
+int
+mono_btls_x509_verify_param_add_host (MonoBtlsX509VerifyParam *param, const char *host, int namelen);
+
+unsigned long
+mono_btls_x509_verify_param_get_flags (MonoBtlsX509VerifyParam *param);
+
+int
+mono_btls_x509_verify_param_set_flags (MonoBtlsX509VerifyParam *param, unsigned long flags);
+
+MonoBtlsX509VerifyFlags
+mono_btls_x509_verify_param_get_mono_flags (MonoBtlsX509VerifyParam *param);
+
+int
+mono_btls_x509_verify_param_set_mono_flags (MonoBtlsX509VerifyParam *param, MonoBtlsX509VerifyFlags flags);
+
+int
+mono_btls_x509_verify_param_set_purpose (MonoBtlsX509VerifyParam *param, MonoBtlsX509Purpose purpose);
+
+int
+mono_btls_x509_verify_param_get_depth (MonoBtlsX509VerifyParam *param);
+
+int
+mono_btls_x509_verify_param_set_depth (MonoBtlsX509VerifyParam *param, int depth);
+
+int
+mono_btls_x509_verify_param_set_time (MonoBtlsX509VerifyParam *param, long time);
+
+char *
+mono_btls_x509_verify_param_get_peername (MonoBtlsX509VerifyParam *param);
+
+#endif /* defined(__btls__btls_x509_verify_param__) */
+
diff --git a/mono/btls/btls-x509.c b/mono/btls/btls-x509.c
new file mode 100644 (file)
index 0000000..bd31008
--- /dev/null
@@ -0,0 +1,441 @@
+//
+//  btls-x509.c
+//  MonoBtls
+//
+//  Created by Martin Baulig on 14/11/15.
+//  Copyright (c) 2015 Xamarin. All rights reserved.
+//
+
+#include <btls-x509.h>
+#include <openssl/x509v3.h>
+#include <openssl/pkcs12.h>
+
+X509 *
+mono_btls_x509_from_data (const void *buf, int len, MonoBtlsX509Format format)
+{
+       BIO *bio;
+       X509 *cert = NULL;
+
+       bio = BIO_new_mem_buf ((void *)buf, len);
+       switch (format) {
+               case MONO_BTLS_X509_FORMAT_DER:
+                       cert = d2i_X509_bio (bio, NULL);
+                       break;
+               case MONO_BTLS_X509_FORMAT_PEM:
+                       cert = PEM_read_bio_X509 (bio, NULL, NULL, NULL);
+                       break;
+       }
+       BIO_free (bio);
+       return cert;
+}
+
+X509 *
+mono_btls_x509_up_ref (X509 *x509)
+{
+       X509_up_ref (x509);
+       return x509;
+}
+
+void
+mono_btls_x509_free (X509 *x509)
+{
+       X509_free (x509);
+}
+
+X509 *
+mono_btls_x509_dup (X509 *x509)
+{
+       return X509_dup (x509);
+}
+
+MonoBtlsX509Name *
+mono_btls_x509_get_subject_name (X509 *x509)
+{
+       return mono_btls_x509_name_copy (X509_get_subject_name (x509));
+}
+
+MonoBtlsX509Name *
+mono_btls_x509_get_issuer_name (X509 *x509)
+{
+       return mono_btls_x509_name_copy (X509_get_issuer_name (x509));
+}
+
+int
+mono_btls_x509_get_subject_name_string (X509 *name, char *buffer, int size)
+{
+       *buffer = 0;
+       return X509_NAME_oneline (X509_get_subject_name (name), buffer, size) != NULL;
+}
+
+int
+mono_btls_x509_get_issuer_name_string (X509 *name, char *buffer, int size)
+{
+       *buffer = 0;
+       return X509_NAME_oneline (X509_get_issuer_name (name), buffer, size) != NULL;
+}
+
+int
+mono_btls_x509_get_raw_data (X509 *x509, BIO *bio, MonoBtlsX509Format format)
+{
+       switch (format) {
+               case MONO_BTLS_X509_FORMAT_DER:
+                       return i2d_X509_bio (bio, x509);
+               case MONO_BTLS_X509_FORMAT_PEM:
+                       return PEM_write_bio_X509 (bio, x509);
+               default:
+                       return 0;
+       }
+}
+
+int
+mono_btls_x509_cmp (const X509 *a, const X509 *b)
+{
+       return X509_cmp (a, b);
+}
+
+int
+mono_btls_x509_get_hash (X509 *x509, const void **data)
+{
+       X509_check_purpose (x509, -1, 0);
+       *data = x509->sha1_hash;
+       return SHA_DIGEST_LENGTH;
+}
+
+long
+mono_btls_x509_get_not_before (X509 *x509)
+{
+       return mono_btls_util_asn1_time_to_ticks (X509_get_notBefore (x509));
+}
+
+long
+mono_btls_x509_get_not_after (X509 *x509)
+{
+       return mono_btls_util_asn1_time_to_ticks (X509_get_notAfter (x509));
+}
+
+int
+mono_btls_x509_get_public_key (X509 *x509, BIO *bio)
+{
+       EVP_PKEY *pkey;
+       uint8_t *data = NULL;
+       int ret;
+
+       pkey = X509_get_pubkey (x509);
+       if (!pkey)
+               return -1;
+
+       ret = i2d_PublicKey (pkey, &data);
+
+       if (ret > 0 && data) {
+               ret = BIO_write (bio, data, ret);
+               OPENSSL_free (data);
+       }
+
+       EVP_PKEY_free (pkey);
+       return ret;
+}
+
+int
+mono_btls_x509_get_serial_number (X509 *x509, char *buffer, int size, int mono_style)
+{
+       ASN1_INTEGER *serial;
+       unsigned char *temp, *p;
+       int len, idx;
+
+       serial = X509_get_serialNumber (x509);
+       if (serial->length == 0 || serial->length+1 > size)
+               return 0;
+
+       if (!mono_style) {
+               memcpy (buffer, serial->data, serial->length);
+               return serial->length;
+       }
+
+       temp = OPENSSL_malloc (serial->length + 1);
+       if (!temp)
+               return 0;
+
+       p = temp;
+       len = i2c_ASN1_INTEGER (serial, &p);
+
+       if (!len) {
+               OPENSSL_free (temp);
+               return 0;
+       }
+
+       for (idx = 0; idx < len; idx++) {
+               buffer [idx] = *(--p);
+       }
+       buffer [len] = 0;
+
+       OPENSSL_free (temp);
+       return len;
+}
+
+int
+mono_btls_x509_get_public_key_algorithm (X509 *x509, char *buffer, int size)
+{
+       X509_PUBKEY *pkey;
+       ASN1_OBJECT *ppkalg;
+       int ret;
+
+       *buffer = 0;
+       pkey = X509_get_X509_PUBKEY (x509);
+       if (!pkey)
+               return 0;
+
+       ret = X509_PUBKEY_get0_param (&ppkalg, NULL, NULL, NULL, pkey);
+       if (!ret || !ppkalg)
+               return ret;
+
+       return OBJ_obj2txt (buffer, size, ppkalg, 1);
+}
+
+int
+mono_btls_x509_get_version (X509 *x509)
+{
+       return (int)X509_get_version (x509) + 1;
+}
+
+int
+mono_btls_x509_get_signature_algorithm (X509 *x509, char *buffer, int size)
+{
+       const ASN1_OBJECT *obj;
+       int nid;
+
+       *buffer = 0;
+
+       nid = X509_get_signature_nid (x509);
+
+       obj = OBJ_nid2obj (nid);
+       if (!obj)
+               return 0;
+
+       return OBJ_obj2txt (buffer, size, obj, 1);
+}
+
+int
+mono_btls_x509_get_public_key_asn1 (X509 *x509, char *out_oid, int oid_len, uint8_t **buffer, int *size)
+{
+       X509_PUBKEY *pkey;
+       ASN1_OBJECT *ppkalg;
+       const unsigned char *pk;
+       int pk_len;
+       int ret;
+
+       if (out_oid)
+               *out_oid = 0;
+
+       pkey = X509_get_X509_PUBKEY (x509);
+       if (!pkey || !pkey->public_key)
+               return 0;
+
+       ret = X509_PUBKEY_get0_param (&ppkalg, &pk, &pk_len, NULL, pkey);
+       if (ret != 1 || !ppkalg || !pk)
+               return 0;
+
+       if (out_oid) {
+               OBJ_obj2txt (out_oid, oid_len, ppkalg, 1);
+       }
+
+       if (buffer) {
+               *size = pk_len;
+               *buffer = OPENSSL_malloc (pk_len);
+               if (!*buffer)
+                       return 0;
+
+               memcpy (*buffer, pk, pk_len);
+       }
+
+       return 1;
+
+}
+
+int
+mono_btls_x509_get_public_key_parameters (X509 *x509, char *out_oid, int oid_len, uint8_t **buffer, int *size)
+{
+       X509_PUBKEY *pkey;
+       X509_ALGOR *algor;
+       ASN1_OBJECT *paobj;
+       int ptype;
+       void *pval;
+       int ret;
+
+       if (out_oid)
+               *out_oid = 0;
+
+       pkey = X509_get_X509_PUBKEY (x509);
+
+       ret = X509_PUBKEY_get0_param (NULL, NULL, NULL, &algor, pkey);
+       if (ret != 1 || !algor)
+               return 0;
+
+       X509_ALGOR_get0 (&paobj, &ptype, &pval, algor);
+
+       if (ptype != V_ASN1_NULL && ptype != V_ASN1_SEQUENCE)
+               return 0;
+
+       if (ptype == V_ASN1_NULL) {
+               uint8_t *ptr;
+
+               *size = 2;
+               *buffer = OPENSSL_malloc (2);
+               if (!*buffer)
+                       return 0;
+
+               ptr = *buffer;
+               *ptr++ = 0x05;
+               *ptr++ = 0x00;
+
+               if (out_oid)
+                       OBJ_obj2txt (out_oid, oid_len, paobj, 1);
+
+               return 1;
+       } else if (ptype == V_ASN1_SEQUENCE) {
+               ASN1_STRING *pstr = pval;
+
+               *size = pstr->length;
+               *buffer = OPENSSL_malloc (pstr->length);
+               if (!*buffer)
+                       return 0;
+
+               memcpy (*buffer, pstr->data, pstr->length);
+
+               if (out_oid)
+                       OBJ_obj2txt (out_oid, oid_len, paobj, 1);
+
+               return 1;
+       } else {
+               return 0;
+       }
+}
+
+EVP_PKEY *
+mono_btls_x509_get_pubkey (X509 *x509)
+{
+       return X509_get_pubkey (x509);
+}
+
+int
+mono_btls_x509_get_subject_key_identifier (X509 *x509, uint8_t **buffer, int *size)
+{
+       ASN1_OCTET_STRING *skid;
+
+       *size = 0;
+       *buffer = NULL;
+
+       if (X509_get_version (x509) != 2)
+               return 0;
+
+       skid = X509_get_ext_d2i (x509, NID_subject_key_identifier, NULL, NULL);
+       if (!skid)
+               return 0;
+
+       *size = skid->length;
+       *buffer = OPENSSL_malloc (*size);
+       if (!*buffer)
+               return 0;
+
+       memcpy (*buffer, skid->data, *size);
+       return 1;
+}
+
+int
+mono_btls_x509_print (X509 *x509, BIO *bio)
+{
+       return X509_print_ex (bio, x509, XN_FLAG_COMPAT, X509_FLAG_COMPAT);
+}
+
+static int
+get_trust_nid (MonoBtlsX509Purpose purpose)
+{
+       switch (purpose) {
+               case MONO_BTLS_X509_PURPOSE_SSL_CLIENT:
+                       return NID_client_auth;
+               case MONO_BTLS_X509_PURPOSE_SSL_SERVER:
+                       return NID_server_auth;
+               default:
+                       return 0;
+       }
+}
+
+int
+mono_btls_x509_add_trust_object (X509 *x509, MonoBtlsX509Purpose purpose)
+{
+       ASN1_OBJECT *trust;
+       int nid;
+
+       nid = get_trust_nid (purpose);
+       if (!nid)
+               return 0;
+
+       trust = ASN1_OBJECT_new ();
+       if (!trust)
+               return 0;
+
+       trust->nid = nid;
+       return X509_add1_trust_object (x509, trust);
+}
+
+int
+mono_btls_x509_add_reject_object (X509 *x509, MonoBtlsX509Purpose purpose)
+{
+       ASN1_OBJECT *reject;
+       int nid;
+
+       nid = get_trust_nid (purpose);
+       if (!nid)
+               return 0;
+
+       reject = ASN1_OBJECT_new ();
+       if (!reject)
+               return 0;
+
+       reject->nid = nid;
+       return X509_add1_reject_object (x509, reject);
+}
+
+int
+mono_btls_x509_add_explicit_trust (X509 *x509, MonoBtlsX509TrustKind kind)
+{
+       int ret = 0;
+
+       if ((kind & MONO_BTLS_X509_TRUST_KIND_REJECT_ALL) != 0)
+               kind |= MONO_BTLS_X509_TRUST_KIND_REJECT_CLIENT | MONO_BTLS_X509_TRUST_KIND_REJECT_SERVER;
+
+       if ((kind & MONO_BTLS_X509_TRUST_KIND_TRUST_ALL) != 0)
+               kind |= MONO_BTLS_X509_TRUST_KIND_TRUST_CLIENT | MONO_BTLS_X509_TRUST_KIND_TRUST_SERVER;
+
+
+       if ((kind & MONO_BTLS_X509_TRUST_KIND_REJECT_CLIENT) != 0) {
+               ret = mono_btls_x509_add_reject_object (x509, MONO_BTLS_X509_PURPOSE_SSL_CLIENT);
+               if (!ret)
+                       return ret;
+       }
+
+       if ((kind & MONO_BTLS_X509_TRUST_KIND_REJECT_SERVER) != 0) {
+               ret = mono_btls_x509_add_reject_object (x509, MONO_BTLS_X509_PURPOSE_SSL_SERVER);
+               if (!ret)
+                       return ret;
+       }
+
+       if (ret) {
+               // Ignore any MONO_BTLS_X509_TRUST_KIND_TRUST_* settings if we added
+               // any kind of MONO_BTLS_X509_TRUST_KIND_REJECT_* before.
+               return ret;
+       }
+
+       if ((kind & MONO_BTLS_X509_TRUST_KIND_TRUST_CLIENT) != 0) {
+               ret = mono_btls_x509_add_trust_object (x509, MONO_BTLS_X509_PURPOSE_SSL_CLIENT);
+               if (!ret)
+                       return ret;
+       }
+
+       if ((kind & MONO_BTLS_X509_TRUST_KIND_TRUST_SERVER) != 0) {
+               ret = mono_btls_x509_add_trust_object (x509, MONO_BTLS_X509_PURPOSE_SSL_SERVER);
+               if (!ret)
+                       return ret;
+       }
+
+       return ret;
+}
diff --git a/mono/btls/btls-x509.h b/mono/btls/btls-x509.h
new file mode 100644 (file)
index 0000000..a9a9200
--- /dev/null
@@ -0,0 +1,127 @@
+//
+//  btls-x509.h
+//  MonoBtls
+//
+//  Created by Martin Baulig on 14/11/15.
+//  Copyright (c) 2015 Xamarin. All rights reserved.
+//
+
+#ifndef __btls__btls_x509__
+#define __btls__btls_x509__
+
+#include <stdio.h>
+#include <btls-ssl.h>
+#include <btls-x509-name.h>
+
+typedef enum {
+       MONO_BTLS_X509_FORMAT_DER = 1,
+       MONO_BTLS_X509_FORMAT_PEM = 2
+} MonoBtlsX509Format;
+
+typedef enum {
+       MONO_BTLS_x509_FILE_TYPE_PEM = 1,               // X509_FILETYPE_PEM
+       MONO_BTLS_x509_FILE_TYPE_ASN1 = 2,              // X509_FILETYPE_ASN1
+       MONO_BTLS_x509_FILE_TYPE_DEFAULT = 3,   // X509_FILETYPE_DEFAULT
+} MonoBtlsX509FileType;
+
+typedef enum {
+       MONO_BTLS_X509_PURPOSE_SSL_CLIENT               = 1,
+       MONO_BTLS_X509_PURPOSE_SSL_SERVER               = 2,
+       MONO_BTLS_X509_PURPOSE_NS_SSL_SERVER    = 3,
+       MONO_BTLS_X509_PURPOSE_SMIME_SIGN               = 4,
+       MONO_BTLS_X509_PURPOSE_SMIME_ENCRYPT    = 5,
+       MONO_BTLS_X509_PURPOSE_CRL_SIGN         = 6,
+       MONO_BTLS_X509_PURPOSE_ANY                      = 7,
+       MONO_BTLS_X509_PURPOSE_OCSP_HELPER              = 8,
+       MONO_BTLS_X509_PURPOSE_TIMESTAMP_SIGN   = 9,
+} MonoBtlsX509Purpose;
+
+typedef enum {
+       MONO_BTLS_X509_TRUST_KIND_DEFAULT               = 0,
+       MONO_BTLS_X509_TRUST_KIND_TRUST_CLIENT  = 1,
+       MONO_BTLS_X509_TRUST_KIND_TRUST_SERVER  = 2,
+       MONO_BTLS_X509_TRUST_KIND_TRUST_ALL             = 4,
+       MONO_BTLS_X509_TRUST_KIND_REJECT_CLIENT = 32,
+       MONO_BTLS_X509_TRUST_KIND_REJECT_SERVER = 64,
+       MONO_BTLS_X509_TRUST_KIND_REJECT_ALL    = 128
+} MonoBtlsX509TrustKind;
+
+X509 *
+mono_btls_x509_from_data (const void *buf, int len, MonoBtlsX509Format format);
+
+X509 *
+mono_btls_x509_up_ref (X509 *x509);
+
+void
+mono_btls_x509_free (X509 *x509);
+
+X509 *
+mono_btls_x509_dup (X509 *x509);
+
+MonoBtlsX509Name *
+mono_btls_x509_get_subject_name (X509 *x509);
+
+MonoBtlsX509Name *
+mono_btls_x509_get_issuer_name (X509 *x509);
+
+int
+mono_btls_x509_get_subject_name_string (X509 *name, char *buffer, int size);
+
+int
+mono_btls_x509_get_issuer_name_string (X509 *name, char *buffer, int size);
+
+int
+mono_btls_x509_get_raw_data (X509 *x509, BIO *bio, MonoBtlsX509Format format);
+
+int
+mono_btls_x509_cmp (const X509 *a, const X509 *b);
+
+int
+mono_btls_x509_get_hash (X509 *x509, const void **data);
+
+long
+mono_btls_x509_get_not_before (X509 *x509);
+
+long
+mono_btls_x509_get_not_after (X509 *x509);
+
+int
+mono_btls_x509_get_public_key (X509 *x509, BIO *bio);
+
+int
+mono_btls_x509_get_public_key_parameters (X509 *x509, char *out_oid, int oid_len, uint8_t **buffer, int *size);
+
+int
+mono_btls_x509_get_serial_number (X509 *x509, char *buffer, int size, int mono_style);
+
+int
+mono_btls_x509_get_public_key_algorithm (X509 *x509, char *buffer, int size);
+
+int
+mono_btls_x509_get_version (X509 *x509);
+
+int
+mono_btls_x509_get_signature_algorithm (X509 *x509, char *buffer, int size);
+
+int
+mono_btls_x509_get_public_key_asn1 (X509 *x509, char *out_oid, int oid_len, uint8_t **buffer, int *size);
+
+EVP_PKEY *
+mono_btls_x509_get_pubkey (X509 *x509);
+
+int
+mono_btls_x509_get_subject_key_identifier (X509 *x509, uint8_t **buffer, int *size);
+
+int
+mono_btls_x509_print (X509 *x509, BIO *bio);
+
+int
+mono_btls_x509_add_trust_object (X509 *x509, MonoBtlsX509Purpose purpose);
+
+int
+mono_btls_x509_add_reject_object (X509 *x509, MonoBtlsX509Purpose purpose);
+
+int
+mono_btls_x509_add_explicit_trust (X509 *x509, MonoBtlsX509TrustKind kind);
+
+#endif /* defined(__btls__btls_x509__) */
diff --git a/mono/btls/create-object-library.sh b/mono/btls/create-object-library.sh
new file mode 100755 (executable)
index 0000000..8ceda08
--- /dev/null
@@ -0,0 +1,33 @@
+#!/bin/sh
+
+DIR=$1; shift
+FILELIST=$1; shift
+LOFILELIST=$1 ; shift
+TARGET=$1; shift
+STATIC=$1; shift
+AR=$1; shift
+RANLIB=$1; shift
+
+HEADER="# Generated by Martin's tool $0, not libtool"
+
+test -f $TARGET && exit 0
+
+rm -f $FILELIST
+rm -f $LOFILELIST
+
+while [ "$1" != "--" ]; do
+       file=$1; shift
+       filename=`basename $file`
+       LOFILE=$file.lo
+       echo "$HEADER" > $LOFILE
+       if [ "$STATIC" = "static" ]; then
+               echo "non_pic_object='$filename'" >> $LOFILE
+       else
+               echo "pic_object='$filename'" >> $LOFILE
+       fi
+       echo "$DIR/$file " >> $FILELIST
+       echo "$DIR/$LOFILE " >> $LOFILELIST
+done
+
+(cd $DIR && $AR cr $TARGET `cat $FILELIST` && $RANLIB $TARGET)
+
index 1af061c383ad8b58abc1d42a636c8b4de55d26b1..53de00ae71577c4a902472c6a2448a648608bf62 100644 (file)
@@ -32,6 +32,7 @@
 #include <mono/metadata/assembly.h>
 #include <mono/metadata/appdomain.h>
 #include <mono/utils/bsearch.h>
+#include <mono/utils/mono-counters.h>
 
 static void     setup_filter          (MonoImage *image);
 static gboolean should_include_type   (int idx);
@@ -1963,9 +1964,16 @@ usage (void)
        exit (1);
 }
 
+static void
+thread_state_init (MonoThreadUnwindState *ctx)
+{
+}
+
 int
 main (int argc, char *argv [])
 {
+       MonoThreadInfoRuntimeCallbacks ticallbacks;
+
        GList *input_files = NULL, *l;
        int i, j;
 
@@ -2016,6 +2024,15 @@ main (int argc, char *argv [])
        if (input_files == NULL)
                usage ();
 
+       CHECKED_MONO_INIT ();
+       mono_counters_init ();
+       memset (&ticallbacks, 0, sizeof (ticallbacks));
+       ticallbacks.thread_state_init = thread_state_init;
+#ifndef HOST_WIN32
+       mono_w32handle_init ();
+#endif
+       mono_threads_runtime_init (&ticallbacks);
+
        mono_install_assembly_load_hook (monodis_assembly_load_hook, NULL);
        mono_install_assembly_search_hook (monodis_assembly_search_hook, NULL);
 
index a3cbe2abfee3419be56e504891aa2e749f9ed3cf..e9096e25580ee216938e36854d2668b6325b4a45 100755 (executable)
@@ -11,6 +11,9 @@
 #ifndef _MONO_IOLAYER_IOLAYER_H_
 #define _MONO_IOLAYER_IOLAYER_H_
 
+#include <config.h>
+#include <glib.h>
+
 #if defined(__WIN32__) || defined(_WIN32)
 /* Native win32 */
 #define __USE_W32_SOCKETS
@@ -25,8 +28,8 @@
 #include <ws2tcpip.h>
 #endif
 #include <psapi.h>
-#include <shlobj.h>
-/*
+
+ /*
  * Workaround for missing WSAPOLLFD typedef in mingw's winsock2.h that is required for mswsock.h below.
  * Remove once http://sourceforge.net/p/mingw/bugs/1980/ is fixed.
  */
@@ -37,7 +40,11 @@ typedef struct pollfd {
   short  revents;
 } WSAPOLLFD, *PWSAPOLLFD, *LPWSAPOLLFD;
 #endif
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 #include <mswsock.h>
+#endif
+
 #else  /* EVERYONE ELSE */
 #include "mono/io-layer/wapi.h"
 #include "mono/io-layer/uglify.h"
index 35cd67eb5c0d60435aad18ee1a774c2ee52f94b9..fd55cd74314bcad2d4029a28d27bcec1c3fc8b9e 100644 (file)
@@ -412,10 +412,10 @@ is_managed_binary (const char *filename)
        off_t new_offset;
        unsigned char buffer[8];
        off_t file_size, optional_header_offset;
-       off_t pe_header_offset;
+       off_t pe_header_offset, clr_header_offset;
        gboolean managed = FALSE;
        int num_read;
-       guint32 first_word, second_word;
+       guint32 first_word, second_word, magic_number;
        
        /* If we are unable to open the file, then we definitely
         * can't say that it is managed. The child mono process
@@ -480,13 +480,34 @@ is_managed_binary (const char *filename)
        if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
                goto leave;
 
+       optional_header_offset = pe_header_offset + 24;
+
+       /* Read the PE magic number */
+       new_offset = lseek (file, optional_header_offset, SEEK_SET);
+       
+       if (new_offset != optional_header_offset)
+               goto leave;
+
+       num_read = read (file, buffer, 2);
+
+       if (num_read != 2)
+               goto leave;
+
+       magic_number = (buffer[0] | (buffer[1] << 8));
+       
+       if (magic_number == 0x10B)  // PE32
+               clr_header_offset = 208;
+       else if (magic_number == 0x20B)  // PE32+
+               clr_header_offset = 224;
+       else
+               goto leave;
+
        /* Read the CLR header address and size fields. These will be
         * zero if the binary is not managed.
         */
-       optional_header_offset = pe_header_offset + 24;
-       new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
+       new_offset = lseek (file, optional_header_offset + clr_header_offset, SEEK_SET);
 
-       if (new_offset != optional_header_offset + 208)
+       if (new_offset != optional_header_offset + clr_header_offset)
                goto leave;
 
        num_read = read (file, buffer, 8);
@@ -2685,8 +2706,6 @@ MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler, (int _dummy, sigi
        int pid;
        struct MonoProcess *p;
 
-       MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "SIG CHILD handler for pid: %i\n", info->si_pid);
-
        do {
                do {
                        pid = waitpid (-1, &status, WNOHANG);
@@ -2695,8 +2714,6 @@ MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler, (int _dummy, sigi
                if (pid <= 0)
                        break;
 
-               MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "child ended: %i", pid);
-
                /*
                 * This can run concurrently with the code in the rest of this module.
                 */
@@ -2714,8 +2731,6 @@ MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler, (int _dummy, sigi
                        p->freeable = TRUE;
                }
        } while (1);
-
-       MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "SIG CHILD handler: done looping.");
 }
 
 #endif
@@ -2806,7 +2821,7 @@ process_wait (gpointer handle, guint32 timeout, gboolean *alerted)
        while (1) {
                if (timeout != INFINITE) {
                        MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): waiting on semaphore for %li ms...", 
-                                  __func__, handle, timeout, (timeout - (now - start)));
+                                   __func__, handle, timeout, (long)(timeout - (now - start)));
                        ret = mono_os_sem_timedwait (&mp->exit_sem, (timeout - (now - start)), alerted ? MONO_SEM_FLAGS_ALERTABLE : MONO_SEM_FLAGS_NONE);
                } else {
                        MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s (%p, %u): waiting on semaphore forever...", 
index 0c0c4c27be7982eb62ef855bcd955b9262ed793e..3f754d04f3f26b85edc3d982fa69080c81d79737 100644 (file)
@@ -1,9 +1,21 @@
 if HOST_WIN32
 win32_sources = \
        console-win32.c \
+       console-win32-internals.h \
+       file-io-windows.c \
+       file-io-windows-internals.h \
+       icall-windows.c \
+       icall-windows-internals.h \
+       marshal-windows.c \
+       marshal-windows-internals.h \
+       mono-security-windows.c \
+       mono-security-windows-internals.h \
+       process-windows.c \
+       process-windows-internals.h \
        w32mutex-win32.c \
        w32semaphore-win32.c \
-       w32event-win32.c
+       w32event-win32.c \
+       socket-io-windows.c
 
 platform_sources = $(win32_sources)
 
@@ -38,6 +50,14 @@ if PLATFORM_ANDROID
 platform_sources += ../../support/libm/complex.c
 endif
 
+if BTLS
+btls_file_list := $(shell cat ../btls/build-shared/mono-btls-shared-lo.txt)
+btls_static_file_list := $(shell cat ../btls/build-static/mono-btls-static-lo.txt)
+btls_libs = $(btls_file_list)
+btls_static_libs = $(btls_static_file_list)
+btls_cflags = -I$(top_srcdir)/external/boringssl/include -I$(top_srcdir)/mono/btls
+endif
+
 #
 # libtool is not capable of creating static/shared versions of the same
 # convenience lib, so we have to do it ourselves
@@ -70,7 +90,7 @@ else
 noinst_LTLIBRARIES = libmonoruntime-config.la $(boehm_libraries) $(sgen_libraries)
 endif
 
-AM_CPPFLAGS = -I$(top_srcdir) -I$(top_srcdir)/mono $(LIBGC_CPPFLAGS) $(GLIB_CFLAGS) $(SHARED_CFLAGS)
+AM_CPPFLAGS = -I$(top_srcdir) -I$(top_srcdir)/mono $(LIBGC_CPPFLAGS) $(GLIB_CFLAGS) $(SHARED_CFLAGS) $(btls_cflags)
 
 #
 # Make sure any prefix changes are updated in the binaries too.
@@ -101,6 +121,7 @@ null_gc_sources = \
 common_sources = \
        $(platform_sources)     \
        assembly.c              \
+       assembly-internals.h    \
        attach.h                \
        attach.c                \
        cil-coff.h              \
@@ -111,6 +132,7 @@ common_sources = \
        console-io.h            \
        coree.c                 \
        coree.h                 \
+       coree-internals.h \
        culture-info.h          \
        culture-info-tables.h   \
        debug-helpers.c         \
@@ -128,10 +150,12 @@ common_sources = \
        exception-internals.h   \
        file-io.c               \
        file-io.h               \
+       file-io-internals.h \
        filewatcher.c           \
        filewatcher.h           \
        gc-internals.h          \
        icall.c                 \
+       icall-internals.h \
        icall-def.h             \
        image.c                 \
        image-internals.h       \
@@ -143,6 +167,7 @@ common_sources = \
        lock-tracer.h           \
        marshal.c               \
        marshal.h               \
+       marshal-internals.h \
        mempool.c               \
        mempool.h               \
        mempool-internals.h     \
@@ -180,6 +205,7 @@ common_sources = \
        socket-io.h             \
        process.c               \
        process.h               \
+       process-internals.h \
        profiler.c              \
        profiler-private.h      \
        rand.h                  \
@@ -225,7 +251,6 @@ common_sources = \
        handle.c        \
        handle.h        \
        w32mutex.h      \
-       w32mutex-utils.h        \
        w32semaphore.h  \
        w32event.h      \
        w32handle-namespace.h   \
@@ -270,21 +295,21 @@ sgen_sources = \
 
 libmonoruntime_la_SOURCES = $(common_sources) $(gc_dependent_sources) $(null_gc_sources) $(boehm_sources)
 libmonoruntime_la_CFLAGS = $(BOEHM_DEFINES)
-libmonoruntime_la_LIBADD = libmonoruntime-config.la
+libmonoruntime_la_LIBADD = libmonoruntime-config.la $(btls_libs)
 
 libmonoruntimesgen_la_SOURCES = $(common_sources) $(gc_dependent_sources) $(sgen_sources)
 libmonoruntimesgen_la_CFLAGS = $(SGEN_DEFINES)
-libmonoruntimesgen_la_LIBADD = libmonoruntime-config.la
+libmonoruntimesgen_la_LIBADD = libmonoruntime-config.la $(btls_libs)
 
 libmonoruntime_static_la_SOURCES = $(libmonoruntime_la_SOURCES)
 libmonoruntime_static_la_LDFLAGS = -static
 libmonoruntime_static_la_CFLAGS = $(BOEHM_DEFINES)
-libmonoruntime_static_la_LIBADD = $(bundle_obj) $(libmonoruntime_la_LIBADD)
+libmonoruntime_static_la_LIBADD = $(bundle_obj) libmonoruntime-config.la $(btls_static_libs)
 
 libmonoruntimesgen_static_la_SOURCES = $(libmonoruntimesgen_la_SOURCES)
 libmonoruntimesgen_static_la_LDFLAGS = -static
 libmonoruntimesgen_static_la_CFLAGS = $(SGEN_DEFINES)
-libmonoruntimesgen_static_la_LIBADD = $(libmonoruntimesgen_la_LIBADD)
+libmonoruntimesgen_static_la_LIBADD = libmonoruntime-config.la $(btls_static_libs)
 
 libmonoruntimeincludedir = $(includedir)/mono-$(API_VER)/mono/metadata
 
index 789eb27977ddd0eb1456a3d00a6a1bdacf7fa5d0..b4c20c8e22bd57c6fad22d3e588661b55df19a35 100644 (file)
@@ -84,7 +84,7 @@
  * Changes which are already detected at runtime, like the addition
  * of icalls, do not require an increment.
  */
-#define MONO_CORLIB_VERSION 155
+#define MONO_CORLIB_VERSION 160
 
 typedef struct
 {
@@ -1415,7 +1415,12 @@ shadow_copy_sibling (gchar *src, gint srclen, const char *extension, gchar *targ
        dest = g_utf8_to_utf16 (target, strlen (target), NULL, NULL, NULL);
        
        DeleteFile (dest);
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
        copy_result = CopyFile (orig, dest, FALSE);
+#else
+       copy_result = SUCCEEDED (CopyFile2 (orig, dest, NULL));
+#endif
 
        /* Fix for bug #556884 - make sure the files have the correct mode so that they can be
         * overwritten when updated in their original locations. */
@@ -1743,7 +1748,11 @@ mono_make_shadow_copy (const char *filename, MonoError *oerror)
                return (char *)filename;
        }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
        copy_result = CopyFile (orig, dest, FALSE);
+#else
+       copy_result = SUCCEEDED (CopyFile2 (orig, dest, NULL));
+#endif
 
        /* Fix for bug #556884 - make sure the files have the correct mode so that they can be
         * overwritten when updated in their original locations. */
@@ -2568,7 +2577,7 @@ mono_domain_try_unload (MonoDomain *domain, MonoObject **exc)
         * First we create a separate thread for unloading, since
         * we might have to abort some threads, including the current one.
         */
-       thread_handle = mono_threads_create_thread (unload_thread_main, thread_data, 0, &tid);
+       thread_handle = mono_threads_create_thread (unload_thread_main, thread_data, NULL, &tid);
        if (thread_handle == NULL)
                return;
 
diff --git a/mono/metadata/assembly-internals.h b/mono/metadata/assembly-internals.h
new file mode 100644 (file)
index 0000000..5af7bd6
--- /dev/null
@@ -0,0 +1,12 @@
+/*
+ * Copyright 2015 Xamarin Inc
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#ifndef __MONO_METADATA_ASSEMBLY_INTERNALS_H__
+#define __MONO_METADATA_ASSEMBLY_INTERNALS_H__
+
+#include <mono/metadata/assembly.h>
+
+MONO_API MonoImage*    mono_assembly_load_module_checked (MonoAssembly *assembly, uint32_t idx, MonoError *error);
+
+#endif /* __MONO_METADATA_ASSEMBLY_INTERNALS_H__ */
index 06fe1da5d3a271b1fcd2c8cd3a7dd4a6cb09b326..643c4930b1a29360e4c80fc4cae1df1cf51da0bf 100644 (file)
@@ -16,7 +16,9 @@
 #include <string.h>
 #include <stdlib.h>
 #include "assembly.h"
+#include "assembly-internals.h"
 #include "image.h"
+#include "image-internals.h"
 #include "object-internals.h"
 #include <mono/metadata/loader.h>
 #include <mono/metadata/tabledefs.h>
@@ -3448,9 +3450,19 @@ mono_assembly_close (MonoAssembly *assembly)
 MonoImage*
 mono_assembly_load_module (MonoAssembly *assembly, guint32 idx)
 {
-       return mono_image_load_file_for_image (assembly->image, idx);
+       MonoError error;
+       MonoImage *result = mono_assembly_load_module_checked (assembly, idx, &error);
+       mono_error_assert_ok (&error);
+       return result;
 }
 
+MONO_API MonoImage*
+mono_assembly_load_module_checked (MonoAssembly *assembly, uint32_t idx, MonoError *error)
+{
+       return mono_image_load_file_for_image_checked (assembly->image, idx, error);
+}
+
+
 /**
  * mono_assembly_foreach:
  * @func: function to invoke for each assembly loaded
index 2a3857cd9cb32497d08563366ac45930ab0d77c3..6126feda0e1c9053ddc792e2a466a1aa60dd2953 100644 (file)
@@ -1,6 +1,7 @@
 #ifndef _MONONET_METADATA_ASSEMBLY_H_ 
 #define _MONONET_METADATA_ASSEMBLY_H_
 
+#include <mono/utils/mono-error.h>
 #include <mono/metadata/image.h>
 
 MONO_BEGIN_DECLS
@@ -32,7 +33,7 @@ MONO_API MonoAssembly* mono_assembly_loaded_full (MonoAssemblyName *aname, mono_
 MONO_API void          mono_assembly_get_assemblyref (MonoImage *image, int index, MonoAssemblyName *aname);
 MONO_API void          mono_assembly_load_reference (MonoImage *image, int index);
 MONO_API void          mono_assembly_load_references (MonoImage *image, MonoImageOpenStatus *status);
-MONO_API MonoImage*    mono_assembly_load_module (MonoAssembly *assembly, uint32_t idx);
+MONO_RT_EXTERNAL_ONLY MONO_API MonoImage*    mono_assembly_load_module (MonoAssembly *assembly, uint32_t idx);
 MONO_API void          mono_assembly_close      (MonoAssembly *assembly);
 MONO_API void          mono_assembly_setrootdir (const char *root_dir);
 MONO_API MONO_CONST_RETURN char *mono_assembly_getrootdir (void);
index ea7fa289a3899b91b7917f21311f394b2726788f..01d208c2ea275de80efa69f0f93dce1fe036edbf 100644 (file)
@@ -480,7 +480,7 @@ transport_start_receive (void)
        if (!listen_fd)
                return;
 
-       receiver_thread_handle = mono_threads_create_thread (receiver_thread, NULL, 0, NULL);
+       receiver_thread_handle = mono_threads_create_thread (receiver_thread, NULL, NULL, NULL);
        g_assert (receiver_thread_handle);
 }
 
index d3153d29967deb995f5d80da007197e6f7575475..d3debe1cd03665f7ffe5df29c3a55de1bd885660 100644 (file)
@@ -58,6 +58,8 @@ boehm_thread_register (MonoThreadInfo* info, void *baseptr);
 static void
 boehm_thread_unregister (MonoThreadInfo *p);
 static void
+boehm_thread_detach (MonoThreadInfo *p);
+static void
 register_test_toggleref_callback (void);
 
 #define BOEHM_GC_BIT_FINALIZER_AWARE 1
@@ -97,6 +99,9 @@ mono_gc_warning (char *msg, GC_word arg)
        mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_GC, msg, (unsigned long)arg);
 }
 
+static void on_gc_notification (GC_EventType event);
+static void on_gc_heap_resize (size_t new_size);
+
 void
 mono_gc_base_init (void)
 {
@@ -109,6 +114,10 @@ mono_gc_base_init (void)
 
        mono_counters_init ();
 
+#ifndef HOST_WIN32
+       mono_w32handle_init ();
+#endif
+
        /*
         * Handle the case when we are called from a thread different from the main thread,
         * confusing libgc.
@@ -236,6 +245,7 @@ mono_gc_base_init (void)
        memset (&cb, 0, sizeof (cb));
        cb.thread_register = boehm_thread_register;
        cb.thread_unregister = boehm_thread_unregister;
+       cb.thread_detach = boehm_thread_detach;
        cb.mono_method_is_critical = (gboolean (*)(void *))mono_runtime_is_critical_method;
 
        mono_threads_init (&cb, sizeof (MonoThreadInfo));
@@ -244,7 +254,8 @@ mono_gc_base_init (void)
 
        mono_thread_info_attach (&dummy);
 
-       mono_gc_enable_events ();
+       GC_set_on_collection_event (on_gc_notification);
+       GC_on_heap_resize = on_gc_heap_resize;
 
        MONO_GC_REGISTER_ROOT_FIXED (gc_handles [HANDLE_NORMAL].entries, MONO_ROOT_SOURCE_GC_HANDLE, "gc handles table");
        MONO_GC_REGISTER_ROOT_FIXED (gc_handles [HANDLE_PINNED].entries, MONO_ROOT_SOURCE_GC_HANDLE, "gc handles table");
@@ -406,6 +417,13 @@ boehm_thread_unregister (MonoThreadInfo *p)
                mono_threads_add_joinable_thread ((gpointer)tid);
 }
 
+static void
+boehm_thread_detach (MonoThreadInfo *p)
+{
+       if (mono_thread_internal_current_is_attached ())
+               mono_thread_detach_internal (mono_thread_internal_current ());
+}
+
 gboolean
 mono_object_is_alive (MonoObject* o)
 {
@@ -509,21 +527,6 @@ on_gc_heap_resize (size_t new_size)
        mono_profiler_gc_heap_resize (new_size);
 }
 
-void
-mono_gc_enable_events (void)
-{
-       GC_set_on_collection_event (on_gc_notification);
-       GC_on_heap_resize = on_gc_heap_resize;
-}
-
-static gboolean alloc_events = FALSE;
-
-void
-mono_gc_enable_alloc_events (void)
-{
-       alloc_events = TRUE;
-}
-
 int
 mono_gc_register_root (char *start, size_t size, void *descr, MonoGCRootSource source, const char *msg)
 {
@@ -665,7 +668,7 @@ mono_gc_alloc_obj (MonoVTable *vtable, size_t size)
                obj->vtable = vtable;
        }
 
-       if (G_UNLIKELY (alloc_events))
+       if (G_UNLIKELY (mono_profiler_events & MONO_PROFILE_ALLOCATIONS))
                mono_profiler_allocation (obj);
 
        return obj;
@@ -699,7 +702,7 @@ mono_gc_alloc_vector (MonoVTable *vtable, size_t size, uintptr_t max_length)
 
        obj->max_length = max_length;
 
-       if (G_UNLIKELY (alloc_events))
+       if (G_UNLIKELY (mono_profiler_events & MONO_PROFILE_ALLOCATIONS))
                mono_profiler_allocation (&obj->obj);
 
        return obj;
@@ -736,7 +739,7 @@ mono_gc_alloc_array (MonoVTable *vtable, size_t size, uintptr_t max_length, uint
        if (bounds_size)
                obj->bounds = (MonoArrayBounds *) ((char *) obj + size - bounds_size);
 
-       if (G_UNLIKELY (alloc_events))
+       if (G_UNLIKELY (mono_profiler_events & MONO_PROFILE_ALLOCATIONS))
                mono_profiler_allocation (&obj->obj);
 
        return obj;
@@ -754,7 +757,7 @@ mono_gc_alloc_string (MonoVTable *vtable, size_t size, gint32 len)
        obj->length = len;
        obj->chars [len] = 0;
 
-       if (G_UNLIKELY (alloc_events))
+       if (G_UNLIKELY (mono_profiler_events & MONO_PROFILE_ALLOCATIONS))
                mono_profiler_allocation (&obj->object);
 
        return obj;
@@ -1366,6 +1369,16 @@ mono_gc_get_logfile (void)
        return NULL;
 }
 
+void
+mono_gc_params_set (const char* options)
+{
+}
+
+void
+mono_gc_debug_set (const char* options)
+{
+}
+
 void
 mono_gc_conservatively_scan_area (void *start, void *end)
 {
@@ -1929,8 +1942,9 @@ mono_gchandle_free_domain (MonoDomain *domain)
 
 }
 #else
-       #ifdef _MSC_VER
-               // Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
-               void __mono_win32_boehm_gc_quiet_lnk4221(void) {}
-       #endif
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_boehm_gc_quiet_lnk4221(void) {}
+#endif
 #endif /* no Boehm GC */
index b62d6155f91e3bd40e6c204c16bfd1b4eb94143b..6305d51c2682a171b9bdbc73969e8e36e00161a8 100644 (file)
@@ -324,12 +324,7 @@ struct _MonoClass {
        guint has_finalize_inited    : 1; /* has_finalize is initialized */
        guint fields_inited : 1; /* fields is initialized */
        guint setup_fields_called : 1; /* to prevent infinite loops in setup_fields */
-
-       guint8     exception_type;      /* MONO_EXCEPTION_* */
-
-       /* Additional information about the exception */
-       /* Stored as property MONO_CLASS_PROP_EXCEPTION_DATA */
-       //void       *exception_data;
+       guint has_failure : 1; /* See MONO_CLASS_PROP_EXCEPTION_DATA for a MonoErrorBoxed with the details */
 
        MonoClass  *parent;
        MonoClass  *nested_in;
@@ -1258,10 +1253,7 @@ const char*
 mono_lookup_jit_icall_symbol (const char *name);
 
 gboolean
-mono_class_set_failure (MonoClass *klass, guint32 ex_type, void *ex_data);
-
-gpointer
-mono_class_get_exception_data (MonoClass *klass);
+mono_class_set_type_load_failure (MonoClass *klass, const char * fmt, ...) MONO_ATTR_FORMAT_PRINTF(2,3);
 
 MonoException*
 mono_class_get_exception_for_failure (MonoClass *klass);
@@ -1350,6 +1342,12 @@ mono_class_get_generic_container (MonoClass *klass);
 MonoGenericClass*
 mono_class_get_generic_class (MonoClass *klass);
 
+gpointer
+mono_class_alloc (MonoClass *klass, int size);
+
+gpointer
+mono_class_alloc0 (MonoClass *klass, int size);
+
 void
 mono_class_alloc_ext (MonoClass *klass);
 
@@ -1431,20 +1429,9 @@ MonoClass*
 mono_class_try_load_from_name (MonoImage *image, const char* name_space, const char *name);
 
 void
-mono_error_set_for_class_failure (MonoError *orerror, MonoClass *klass);
+mono_error_set_for_class_failure (MonoError *orerror, const MonoClass *klass);
 
-static inline guint8
-mono_class_get_failure (MonoClass *klass)
-{
-       g_assert (klass != NULL);
-       return klass->exception_type;
-}
-
-static inline gboolean
-mono_class_has_failure (MonoClass *klass)
-{
-       g_assert (klass != NULL);
-       return mono_class_get_failure (klass) != MONO_EXCEPTION_NONE;
-}
+gboolean
+mono_class_has_failure (const MonoClass *klass);
 
 #endif /* __MONO_METADATA_CLASS_INTERNALS_H__ */
index a419af381492313e250c7887c0217c26ea071269..ba8197161313c653362b932564aca2ce7caae37d 100644 (file)
@@ -18,7 +18,9 @@
 #include <string.h>
 #include <stdlib.h>
 #include <mono/metadata/image.h>
+#include <mono/metadata/image-internals.h>
 #include <mono/metadata/assembly.h>
+#include <mono/metadata/assembly-internals.h>
 #include <mono/metadata/metadata.h>
 #include <mono/metadata/metadata-internals.h>
 #include <mono/metadata/profiler-private.h>
@@ -75,6 +77,10 @@ static guint32 mono_field_resolve_flags (MonoClassField *field);
 static void mono_class_setup_vtable_full (MonoClass *klass, GList *in_setup);
 static void mono_generic_class_setup_parent (MonoClass *klass, MonoClass *gklass);
 
+static gboolean mono_class_set_failure (MonoClass *klass, MonoErrorBoxed *boxed_error);
+static gpointer mono_class_get_exception_data (const MonoClass *klass);
+
+
 /*
 We use gclass recording to allow recursive system f types to be referenced by a parent.
 
@@ -216,7 +222,7 @@ mono_class_from_typeref_checked (MonoImage *image, guint32 type_token, MonoError
                goto done;
 
        case MONO_RESOLUTION_SCOPE_MODULEREF:
-               module = mono_image_load_module (image, idx);
+               module = mono_image_load_module_checked (image, idx, error);
                if (module)
                        res = mono_class_from_name_checked (module, nspace, name, error);
                goto done;
@@ -1130,6 +1136,15 @@ mono_class_inflate_generic_method_full_checked (MonoMethod *method, MonoClass *k
        result->sre_method = FALSE;
        result->signature = NULL;
 
+       if (method->wrapper_type) {
+               MonoMethodWrapper *mw = (MonoMethodWrapper*)method;
+               MonoMethodWrapper *resw = (MonoMethodWrapper*)result;
+               int len = GPOINTER_TO_INT (((void**)mw->method_data) [0]);
+
+               resw->method_data = (void **)g_malloc (sizeof (gpointer) * (len + 1));
+               memcpy (resw->method_data, mw->method_data, sizeof (gpointer) * (len + 1));
+       }
+
        if (iresult->context.method_inst) {
                /* Set the generic_container of the result to the generic_container of method */
                MonoGenericContainer *generic_container = mono_method_get_generic_container (method);
@@ -1350,7 +1365,7 @@ fail:
 }
 
 /*
- * Checks for MonoClass::exception_type without resolving all MonoType's into MonoClass'es
+ * Checks for MonoClass::has_failure without resolving all MonoType's into MonoClass'es
  */
 static gboolean
 mono_type_has_exceptions (MonoType *type)
@@ -1370,49 +1385,11 @@ mono_type_has_exceptions (MonoType *type)
 }
 
 void
-mono_error_set_for_class_failure (MonoError *oerror, MonoClass *klass)
+mono_error_set_for_class_failure (MonoError *oerror, const MonoClass *klass)
 {
-       gpointer exception_data = mono_class_get_exception_data (klass);
-
-       switch (mono_class_get_failure(klass)) {
-       case MONO_EXCEPTION_TYPE_LOAD: {
-               mono_error_set_type_load_class (oerror, klass, "Error Loading class");
-               return;
-       }
-       case MONO_EXCEPTION_MISSING_METHOD: {
-               char *class_name = (char *)exception_data;
-               char *member_name = class_name + strlen (class_name) + 1;
-
-               mono_error_set_method_load (oerror, klass, member_name, "Error Loading Method");
-               return;
-       }
-       case MONO_EXCEPTION_MISSING_FIELD: {
-               char *class_name = (char *)exception_data;
-               char *member_name = class_name + strlen (class_name) + 1;
-
-               mono_error_set_field_load (oerror, klass, member_name, "Error Loading Field");
-               return;
-       }
-       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);
-
-               mono_error_set_assembly_load (oerror, assembly_name, msg);
-               return;
-       }
-       case MONO_EXCEPTION_BAD_IMAGE: {
-               mono_error_set_bad_image (oerror, NULL, (const char *)exception_data);
-               return;
-       }
-       case MONO_EXCEPTION_INVALID_PROGRAM: {
-               mono_error_set_invalid_program (oerror, (const char *)exception_data);
-               return;
-       }
-       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);
 }
 
 
@@ -1422,7 +1399,7 @@ mono_error_set_for_class_failure (MonoError *oerror, MonoClass *klass)
  *   Allocate memory for some data belonging to CLASS, either from its image's mempool,
  * or from the heap.
  */
-static gpointer
+gpointer
 mono_class_alloc (MonoClass *klass, int size)
 {
        if (klass->generic_class)
@@ -1431,7 +1408,7 @@ mono_class_alloc (MonoClass *klass, int size)
                return mono_image_alloc (klass->image, size);
 }
 
-static gpointer
+gpointer
 mono_class_alloc0 (MonoClass *klass, int size)
 {
        gpointer res;
@@ -1505,6 +1482,33 @@ mono_class_setup_basic_field_info (MonoClass *klass)
        }
 }
 
+/**
+ * mono_class_set_failure_causedby_class:
+ * @klass: the class that is failing
+ * @caused_by: the class that caused the failure
+ * @msg: Why @klass is failing.
+ * 
+ * If @caused_by has a failure, sets a TypeLoadException failure on
+ * @klass with message "@msg, due to: {@caused_by message}".
+ *
+ * Returns: TRUE if a failiure was set, or FALSE if @caused_by doesn't have a failure.
+ */
+static gboolean
+mono_class_set_type_load_failure_causedby_class (MonoClass *klass, const MonoClass *caused_by, const gchar* msg)
+{
+       if (mono_class_has_failure (caused_by)) {
+               MonoError cause_error;
+               mono_error_init (&cause_error);
+               mono_error_set_for_class_failure (&cause_error, caused_by);
+               mono_class_set_type_load_failure (klass, "%s, due to: %s", msg, mono_error_get_message (&cause_error));
+               mono_error_cleanup (&cause_error);
+               return TRUE;
+       } else {
+               return FALSE;
+       }
+}
+
+
 /** 
  * mono_class_setup_fields:
  * @class: The class to initialize
@@ -1592,10 +1596,8 @@ mono_class_setup_fields (MonoClass *klass)
 
        if (gtd) {
                mono_class_setup_fields (gtd);
-               if (mono_class_has_failure (gtd)) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+               if (mono_class_set_type_load_failure_causedby_class (klass, gtd, "Generic type definition failed"))
                        return;
-               }
        }
 
        instance_size = 0;
@@ -1607,10 +1609,8 @@ mono_class_setup_fields (MonoClass *klass)
                mono_class_init (klass->parent);
                if (!klass->parent->size_inited) {
                        mono_class_setup_fields (klass->parent);
-                       if (mono_class_has_failure (klass->parent)) {
-                               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+                       if (mono_class_set_type_load_failure_causedby_class (klass, klass->parent, "Could not set up parent class"))
                                return;
-                       }
                }
                instance_size += klass->parent->instance_size;
                klass->min_align = klass->parent->min_align;
@@ -1635,8 +1635,7 @@ mono_class_setup_fields (MonoClass *klass)
 
        if (explicit_size) {
                if ((packing_size & 0xffffff00) != 0) {
-                       char *err_msg = g_strdup_printf ("Could not load struct '%s' with packing size %d >= 256", klass->name, packing_size);
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, err_msg);
+                       mono_class_set_type_load_failure (klass, "Could not load struct '%s' with packing size %d >= 256", klass->name, packing_size);
                        return;
                }
                klass->packing_size = packing_size;
@@ -1703,15 +1702,15 @@ mono_class_setup_fields (MonoClass *klass)
                                field->offset = offset;
 
                                if (field->offset == (guint32)-1 && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
-                                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("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, g_strdup_printf ("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, g_strdup_printf ("Generic class cannot have explicit layout."));
+                                       mono_class_set_type_load_failure (klass, "Generic class cannot have explicit layout.");
                                        break;
                                }
                        }
@@ -1726,7 +1725,11 @@ mono_class_setup_fields (MonoClass *klass)
                                if (field_class) {
                                        mono_class_setup_fields (field_class);
                                        if (mono_class_has_failure (field_class)) {
-                                               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+                                               MonoError field_error;
+                                               mono_error_init (&field_error);
+                                               mono_error_set_for_class_failure (&field_error, field_class);
+                                               mono_class_set_type_load_failure (klass, "Could not set up field '%s' due to: %s", field->name, mono_error_get_message (&field_error));
+                                               mono_error_cleanup (&field_error);
                                                break;
                                        }
                                }
@@ -1744,7 +1747,7 @@ mono_class_setup_fields (MonoClass *klass)
                        char *class_name = mono_type_get_full_name (klass);
                        char *type_name = mono_type_full_name (field->type);
 
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+                       mono_class_set_type_load_failure (klass, "");
                        g_warning ("Invalid type %s for instance field %s:%s", type_name, class_name, field->name);
                        g_free (class_name);
                        g_free (type_name);
@@ -1759,7 +1762,7 @@ mono_class_setup_fields (MonoClass *klass)
        klass->blittable = blittable;
 
        if (klass->enumtype && !mono_class_enum_basetype (klass)) {
-               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+               mono_class_set_type_load_failure (klass, "The enumeration's base type is invalid.");
                return;
        }
        if (explicit_size && real_size) {
@@ -1772,7 +1775,7 @@ mono_class_setup_fields (MonoClass *klass)
 
        /*valuetypes can't be neither bigger than 1Mb or empty. */
        if (klass->valuetype && (klass->instance_size <= 0 || klass->instance_size > (0x100000 + sizeof (MonoObject))))
-               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+               mono_class_set_type_load_failure (klass, "Value type instance size (%d) cannot be zero, negative, or bigger than 1Mb", klass->instance_size);
 
        mono_memory_barrier ();
        klass->fields_inited = 1;
@@ -1957,10 +1960,8 @@ mono_class_layout_fields (MonoClass *klass, int instance_size)
 
                if (klass->parent) {
                        mono_class_setup_fields (klass->parent);
-                       if (mono_class_has_failure (klass->parent)) {
-                               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+                       if (mono_class_set_type_load_failure_causedby_class (klass, klass->parent, "Cannot initialize parent class"))
                                return;
-                       }
                        real_size = klass->parent->instance_size;
                } else {
                        real_size = sizeof (MonoObject);
@@ -2061,7 +2062,7 @@ mono_class_layout_fields (MonoClass *klass, int instance_size)
                        ftype = mono_type_get_basic_type_from_generic (ftype);
                        if (type_has_references (klass, ftype)) {
                                if (field->offset % sizeof (gpointer)) {
-                                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+                                       mono_class_set_type_load_failure (klass, "Reference typed field '%s' has explicit offset that is not pointer-size aligned.", field->name);
                                }
                        }
 
@@ -2099,8 +2100,7 @@ mono_class_layout_fields (MonoClass *klass, int instance_size)
                                // FIXME: Too much code does this
 #if 0
                                if (!MONO_TYPE_IS_REFERENCE (field->type) && ref_bitmap [field->offset / sizeof (gpointer)]) {
-                                       char *err_msg = g_strdup_printf ("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
                        }
@@ -2155,7 +2155,7 @@ mono_class_layout_fields (MonoClass *klass, int instance_size)
                        continue;
 
                if (mono_type_has_exceptions (field->type)) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+                       mono_class_set_type_load_failure (klass, "Field '%s' has an invalid type.", field->name);
                        break;
                }
 
@@ -2205,7 +2205,7 @@ create_array_method (MonoClass *klass, const char *name, MonoMethodSignature *si
  * Methods belonging to an interface are assigned a sequential slot starting
  * from 0.
  *
- * On failure this function sets klass->exception_type
+ * On failure this function sets klass->has_failure and stores a MonoErrorBoxed with details
  */
 void
 mono_class_setup_methods (MonoClass *klass)
@@ -2223,11 +2223,8 @@ mono_class_setup_methods (MonoClass *klass)
                mono_class_init (gklass);
                if (!mono_class_has_failure (gklass))
                        mono_class_setup_methods (gklass);
-               if (mono_class_has_failure (gklass)) {
-                       /* FIXME make exception_data less opaque so it's possible to dup it here */
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("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;
@@ -2238,7 +2235,7 @@ mono_class_setup_methods (MonoClass *klass)
                                gklass->methods [i], klass, mono_class_get_context (klass), &error);
                        if (!mono_error_ok (&error)) {
                                char *method = mono_method_full_name (gklass->methods [i], TRUE);
-                               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("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);
@@ -2344,7 +2341,7 @@ mono_class_setup_methods (MonoClass *klass)
                        int idx = mono_metadata_translate_token_index (klass->image, MONO_TABLE_METHOD, klass->method.first + i + 1);
                        methods [i] = mono_get_method_checked (klass->image, MONO_TOKEN_METHOD_DEF | idx, klass, NULL, &error);
                        if (!methods [i]) {
-                               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("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);
                        }
                }
@@ -2521,10 +2518,8 @@ mono_class_setup_properties (MonoClass *klass)
 
                mono_class_init (gklass);
                mono_class_setup_properties (gklass);
-               if (mono_class_has_failure (gklass)) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("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);
 
@@ -2654,10 +2649,8 @@ mono_class_setup_events (MonoClass *klass)
                MonoGenericContext *context = NULL;
 
                mono_class_setup_events (gklass);
-               if (mono_class_has_failure (gklass)) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("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;
@@ -2695,7 +2688,6 @@ mono_class_setup_events (MonoClass *klass)
                if (count) {
                        mono_class_setup_methods (klass);
                        if (mono_class_has_failure (klass)) {
-                               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Generic type definition failed to load"));
                                return;
                        }
                }
@@ -3513,7 +3505,7 @@ mono_class_interface_match (const uint8_t *bitmap, int id)
 
 /*
  * LOCKING: this is supposed to be called with the loader lock held.
- * Return -1 on failure and set exception_type
+ * Return -1 on failure and set klass->has_failure and store a MonoErrorBoxed with the details.
  */
 static int
 setup_interface_offsets (MonoClass *klass, int cur_slot, gboolean overwrite)
@@ -3557,7 +3549,7 @@ setup_interface_offsets (MonoClass *klass, int cur_slot, gboolean overwrite)
                ifaces = mono_class_get_implemented_interfaces (k, &error);
                if (!mono_error_ok (&error)) {
                        char *name = mono_type_get_full_name (k);
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("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;
@@ -3624,7 +3616,7 @@ setup_interface_offsets (MonoClass *klass, int cur_slot, gboolean overwrite)
                        count = count_virtual_methods (ic);
                        if (count == -1) {
                                char *name = mono_type_get_full_name (ic);
-                               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("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;
@@ -3800,10 +3792,8 @@ mono_class_check_vtable_constraints (MonoClass *klass, GList *in_setup)
        }
 
        mono_class_setup_vtable_full (mono_class_get_generic_type_definition (klass), in_setup);
-       if (mono_class_has_failure (klass->generic_class->container_class)) {
-               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("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) {
@@ -3815,7 +3805,7 @@ mono_class_check_vtable_constraints (MonoClass *klass, GList *in_setup)
                if (mono_class_has_gtd_parent (klass, arg) || mono_class_has_gtd_parent (arg, klass))
                        continue;
                if (!mono_class_check_vtable_constraints (arg, in_setup)) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Failed to load generic parameter %d", i));
+                       mono_class_set_type_load_failure (klass, "Failed to load generic parameter %d", i);
                        return FALSE;
                }
        }
@@ -3830,7 +3820,8 @@ mono_class_check_vtable_constraints (MonoClass *klass, GList *in_setup)
  * - vtable
  * - vtable_size
  * Plus all the fields initialized by setup_interface_offsets ().
- * If there is an error during vtable construction, klass->exception_type is set.
+ * If there is an error during vtable construction, klass->has_failure
+ * is set and details are stored in a MonoErrorBoxed.
  *
  * LOCKING: Acquires the loader lock.
  */
@@ -3898,7 +3889,7 @@ mono_class_setup_vtable_full (MonoClass *klass, GList *in_setup)
                if (!is_ok (&error)) {
                        mono_loader_unlock ();
                        g_list_remove (in_setup, klass);
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf("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;
                }
@@ -3911,7 +3902,7 @@ mono_class_setup_vtable_full (MonoClass *klass, GList *in_setup)
        if (ok)
                mono_class_setup_vtable_general (klass, overrides, onum, in_setup);
        else
-               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Could not load list of method overrides"));
+               mono_class_set_type_load_failure (klass, "Could not load list of method overrides");
                
        g_free (overrides);
 
@@ -4027,7 +4018,7 @@ check_interface_method_override (MonoClass *klass, MonoMethod *im, MonoMethod *c
                cmsig = mono_method_signature (cm);
                imsig = mono_method_signature (im);
                if (!cmsig || !imsig) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("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;
                }
 
@@ -4045,7 +4036,7 @@ check_interface_method_override (MonoClass *klass, MonoMethod *im, MonoMethod *c
                if (is_wcf_hack_disabled () && !mono_method_can_access_method_full (cm, im, NULL)) {
                        char *body_name = mono_method_full_name (cm, TRUE);
                        char *decl_name = mono_method_full_name (im, TRUE);
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("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;
@@ -4069,7 +4060,7 @@ check_interface_method_override (MonoClass *klass, MonoMethod *im, MonoMethod *c
                cmsig = mono_method_signature (cm);
                imsig = mono_method_signature (im);
                if (!cmsig || !imsig) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("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;
                }
 
@@ -4126,7 +4117,7 @@ check_interface_method_override (MonoClass *klass, MonoMethod *im, MonoMethod *c
                if (is_wcf_hack_disabled () && !mono_method_can_access_method_full (cm, im, NULL)) {
                        char *body_name = mono_method_full_name (cm, TRUE);
                        char *decl_name = mono_method_full_name (im, TRUE);
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("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;
@@ -4293,28 +4284,28 @@ verify_class_overrides (MonoClass *klass, MonoMethod **overrides, int onum)
                MonoMethod *body = overrides [i * 2 + 1];
 
                if (mono_class_get_generic_type_definition (body->klass) != mono_class_get_generic_type_definition (klass)) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("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, g_strdup ("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, g_strdup ("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, g_strdup ("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, g_strdup ("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, g_strdup ("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;
                }
 
@@ -4324,7 +4315,7 @@ verify_class_overrides (MonoClass *klass, MonoMethod **overrides, int onum)
                if (is_wcf_hack_disabled () && !mono_method_can_access_method_full (body, decl, NULL)) {
                        char *body_name = mono_method_full_name (body, TRUE);
                        char *decl_name = mono_method_full_name (decl, TRUE);
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("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;
@@ -4367,7 +4358,7 @@ mono_class_setup_vtable_general (MonoClass *klass, MonoMethod **overrides, int o
        ifaces = mono_class_get_implemented_interfaces (klass, &error);
        if (!mono_error_ok (&error)) {
                char *name = mono_type_get_full_name (klass);
-               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("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;
@@ -4384,12 +4375,8 @@ mono_class_setup_vtable_general (MonoClass *klass, MonoMethod **overrides, int o
                mono_class_init (klass->parent);
                mono_class_setup_vtable_full (klass->parent, in_setup);
 
-               if (mono_class_has_failure (klass->parent)) {
-                       char *name = mono_type_get_full_name (klass->parent);
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("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;
@@ -4423,10 +4410,8 @@ mono_class_setup_vtable_general (MonoClass *klass, MonoMethod **overrides, int o
                MonoMethod **tmp;
 
                mono_class_setup_vtable_full (gklass, in_setup);
-               if (mono_class_has_failure (gklass)) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+               if (mono_class_set_type_load_failure_causedby_class (klass, gklass, "Could not load generic definition"))
                        return;
-               }
 
                tmp = (MonoMethod **)mono_class_alloc0 (klass, sizeof (gpointer) * gklass->vtable_size);
                klass->vtable_size = gklass->vtable_size;
@@ -4434,9 +4419,7 @@ mono_class_setup_vtable_general (MonoClass *klass, MonoMethod **overrides, int o
                        if (gklass->vtable [i]) {
                                MonoMethod *inflated = mono_class_inflate_generic_method_full_checked (gklass->vtable [i], klass, mono_class_get_context (klass), &error);
                                if (!mono_error_ok (&error)) {
-                                       char *err_msg = g_strdup_printf ("Could not inflate method due to %s", mono_error_get_message (&error));
-                                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, err_msg);
-                                       g_free (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;
                                }
@@ -4509,7 +4492,7 @@ mono_class_setup_vtable_general (MonoClass *klass, MonoMethod **overrides, int o
                        int dslot;
                        dslot = mono_method_get_vtable_slot (decl);
                        if (dslot == -1) {
-                               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+                               mono_class_set_type_load_failure (klass, "");
                                return;
                        }
 
@@ -4686,7 +4669,8 @@ mono_class_setup_vtable_general (MonoClass *klass, MonoMethod **overrides, int o
                                        m1sig = mono_method_signature (m1);
 
                                        if (!cmsig || !m1sig) {
-                                               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+                                               /* FIXME proper error message */
+                                               mono_class_set_type_load_failure (klass, "");
                                                return;
                                        }
 
@@ -4703,7 +4687,7 @@ mono_class_setup_vtable_general (MonoClass *klass, MonoMethod **overrides, int o
                                                if (is_wcf_hack_disabled () && !mono_method_can_access_method_full (cm, m1, NULL)) {
                                                        char *body_name = mono_method_full_name (cm, TRUE);
                                                        char *decl_name = mono_method_full_name (m1, TRUE);
-                                                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("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;
@@ -4788,7 +4772,7 @@ mono_class_setup_vtable_general (MonoClass *klass, MonoMethod **overrides, int o
                        if (vtable [i] == NULL || (vtable [i]->flags & (METHOD_ATTRIBUTE_ABSTRACT | METHOD_ATTRIBUTE_STATIC))) {
                                char *type_name = mono_type_get_full_name (klass);
                                char *method_name = vtable [i] ? mono_method_full_name (vtable [i], TRUE) : g_strdup ("none");
-                               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("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;
@@ -4872,7 +4856,7 @@ mono_class_setup_vtable_general (MonoClass *klass, MonoMethod **overrides, int o
 fail:
        {
        char *name = mono_type_get_full_name (klass);
-       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("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);
@@ -5112,14 +5096,14 @@ mono_class_init (MonoClass *klass)
        }
 
        if (klass->init_pending) {
-               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("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;
        }
 
@@ -5128,10 +5112,8 @@ mono_class_init (MonoClass *klass)
                MonoClass *element_class = klass->element_class;
                if (!element_class->inited) 
                        mono_class_init (element_class);
-               if (mono_class_has_failure (element_class)) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+               if (mono_class_set_type_load_failure_causedby_class (klass, element_class, "Could not load array element class"))
                        goto leave;
-               }
        }
 
        mono_stats.initialized_class_count++;
@@ -5148,10 +5130,8 @@ mono_class_init (MonoClass *klass)
                // FIXME: Why is this needed ?
                if (!mono_class_has_failure (gklass))
                        mono_class_setup_methods (gklass);
-               if (mono_class_has_failure (gklass)) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("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);
@@ -5235,10 +5215,8 @@ mono_class_init (MonoClass *klass)
                klass->has_cctor = gklass->has_cctor;
 
                mono_class_setup_vtable (gklass);
-               if (mono_class_has_failure (gklass)) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+               if (mono_class_set_type_load_failure_causedby_class (klass, gklass, "Generic type definition failed to init"))
                        goto leave;
-               }
 
                klass->vtable_size = gklass->vtable_size;
        } else {
@@ -5283,18 +5261,18 @@ mono_class_init (MonoClass *klass)
        }
 
        if (klass->parent) {
+               MonoError parent_error;
+               mono_error_init (&parent_error);
                int first_iface_slot;
                /* This will compute klass->parent->vtable_size for some classes */
                mono_class_init (klass->parent);
-               if (mono_class_has_failure (klass->parent)) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+               if (mono_class_set_type_load_failure_causedby_class (klass, klass->parent, "Parent class failed to initialize")) {
                        goto leave;
                }
                if (!klass->parent->vtable_size) {
                        /* FIXME: Get rid of this somehow */
                        mono_class_setup_vtable (klass->parent);
-                       if (mono_class_has_failure (klass->parent)) {
-                               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+                       if (mono_class_set_type_load_failure_causedby_class (klass, klass->parent, "Parent class vtable failed to initialize")) {
                                goto leave;
                        }
                }
@@ -5310,7 +5288,7 @@ mono_class_init (MonoClass *klass)
                mono_security_core_clr_check_inheritance (klass);
 
        if (klass->generic_class && !mono_verifier_class_is_valid_generic_instantiation (klass))
-               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Invalid generic instantiation"));
+               mono_class_set_type_load_failure (klass, "Invalid generic instantiation");
 
        goto leave;
 
@@ -5546,7 +5524,7 @@ init_com_from_comimport (MonoClass *klass)
                        /* but it can not be made available for application (i.e. user code) since all COM calls
                         * are considered native calls. In this case we fail with a TypeLoadException (just like
                         * Silverlight 2 does */
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+                       mono_class_set_type_load_failure (klass, "");
                        return;
                }
        }
@@ -5590,7 +5568,7 @@ mono_class_setup_parent (MonoClass *klass, MonoClass *parent)
                if (!parent) {
                        /* set the parent to something useful and safe, but mark the type as broken */
                        parent = mono_defaults.object_class;
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+                       mono_class_set_type_load_failure (klass, "");
                }
 
                klass->parent = parent;
@@ -5708,8 +5686,8 @@ fix_gclass_incomplete_instantiation (MonoClass *gclass, void *user_data)
 static void
 mono_class_set_failure_and_error (MonoClass *klass, MonoError *error, const char *msg)
 {
-       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup (msg));
-       mono_error_set_type_load_class (error, klass, msg);
+       mono_class_set_type_load_failure (klass, "%s", msg);
+       mono_error_set_type_load_class (error, klass, "%s", msg);
 }
 
 /**
@@ -5803,7 +5781,7 @@ mono_class_create_from_typedef (MonoImage *image, guint32 type_token, MonoError
                        parent = mono_class_inflate_generic_class_checked (parent, context, error);
 
                if (parent == NULL) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup (mono_error_get_message (error)));
+                       mono_class_set_type_load_failure (klass, "%s", mono_error_get_message (error));
                        goto parent_failure;
                }
 
@@ -5835,7 +5813,7 @@ mono_class_create_from_typedef (MonoImage *image, guint32 type_token, MonoError
                klass->nested_in = mono_class_create_from_typedef (image, nesting_tokeen, error);
                if (!mono_error_ok (error)) {
                        /*FIXME implement a mono_class_set_failure_from_mono_error */
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup (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;
@@ -5856,7 +5834,7 @@ mono_class_create_from_typedef (MonoImage *image, guint32 type_token, MonoError
                if (!mono_metadata_interfaces_from_typedef_full (
                            image, type_token, &interfaces, &icount, FALSE, context, error)){
 
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup (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;
@@ -5906,7 +5884,7 @@ mono_class_create_from_typedef (MonoImage *image, guint32 type_token, MonoError
                if (!enum_basetype) {
                        /*set it to a default value as the whole runtime can't handle this to be null*/
                        klass->cast_class = klass->element_class = mono_defaults.int32_class;
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup (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;
@@ -5920,7 +5898,7 @@ mono_class_create_from_typedef (MonoImage *image, guint32 type_token, MonoError
         * work.
         */
        if (klass->generic_container && !mono_metadata_load_generic_param_constraints_checked (image, type_token, klass->generic_container, error)) {
-               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("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;
@@ -5972,7 +5950,7 @@ mono_generic_class_setup_parent (MonoClass *klass, MonoClass *gtd)
                if (!mono_error_ok (&error)) {
                        /*Set parent to something safe as the runtime doesn't handle well this kind of failure.*/
                        klass->parent = mono_defaults.object_class;
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+                       mono_class_set_type_load_failure (klass, "Parent is a generic type instantiation that failed due to: %s", mono_error_get_message (&error));
                        mono_error_cleanup (&error);
                }
        }
@@ -6217,7 +6195,7 @@ make_generic_param_class (MonoGenericParam *param, MonoGenericParamInfo *pinfo)
        if (count - pos > 0) {
                mono_class_setup_vtable (klass->parent);
                if (mono_class_has_failure (klass->parent))
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("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);
        }
@@ -6432,8 +6410,7 @@ mono_ptr_class_get (MonoType *type)
        result->image = el_class->image;
        result->inited = TRUE;
        result->flags = TYPE_ATTRIBUTE_CLASS | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK);
-       /* Can pointers get boxed? */
-       result->instance_size = sizeof (gpointer);
+       result->instance_size = sizeof (MonoObject) + sizeof (gpointer);
        result->cast_class = result->element_class = el_class;
        result->blittable = TRUE;
 
@@ -6491,8 +6468,7 @@ mono_fnptr_class_get (MonoMethodSignature *sig)
        result->image = mono_defaults.corlib; /* need to fix... */
        result->inited = TRUE;
        result->flags = TYPE_ATTRIBUTE_CLASS; /* | (el_class->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK); */
-       /* Can pointers get boxed? */
-       result->instance_size = sizeof (gpointer);
+       result->instance_size = sizeof (MonoObject) + sizeof (gpointer);
        result->cast_class = result->element_class = result;
        result->blittable = TRUE;
 
@@ -6734,7 +6710,11 @@ mono_bounded_array_class_get (MonoClass *eclass, guint32 rank, gboolean bounded)
 
        if (eclass->byval_arg.type == MONO_TYPE_TYPEDBYREF || eclass->byval_arg.type == MONO_TYPE_VOID) {
                /*Arrays of those two types are invalid.*/
-               mono_class_set_failure (klass, MONO_EXCEPTION_INVALID_PROGRAM, NULL);
+               MonoError prepared_error;
+               mono_error_init (&prepared_error);
+               mono_error_set_invalid_program (&prepared_error, "Arrays of void or System.TypedReference types are invalid.");
+               mono_class_set_failure (klass, mono_error_box (&prepared_error, klass->image));
+               mono_error_cleanup (&prepared_error);
        } else if (eclass->enumtype && !mono_class_enum_basetype (eclass)) {
                if (!eclass->ref_info_handle || eclass->wastypebuilder) {
                        g_warning ("Only incomplete TypeBuilder objects are allowed to be an enum without base_type");
@@ -6751,8 +6731,8 @@ mono_bounded_array_class_get (MonoClass *eclass, guint32 rank, gboolean bounded)
                mono_class_init (eclass);
        if (!eclass->size_inited)
                mono_class_setup_fields (eclass);
-       if (mono_class_has_failure (eclass)) /*FIXME we fail the array type, but we have to let other fields be set.*/
-               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+       mono_class_set_type_load_failure_causedby_class (klass, eclass, "Could not load array element type");
+       /*FIXME we fail the array type, but we have to let other fields be set.*/
 
        klass->has_references = MONO_TYPE_IS_REFERENCE (&eclass->byval_arg) || eclass->has_references? TRUE: FALSE;
 
@@ -7813,7 +7793,7 @@ search_modules (MonoImage *image, const char *name_space, const char *name, Mono
                if (cols [MONO_FILE_FLAGS] == FILE_CONTAINS_NO_METADATA)
                        continue;
 
-               file_image = mono_image_load_file_for_image (image, i + 1);
+               file_image = mono_image_load_file_for_image_checked (image, i + 1, error);
                if (file_image) {
                        klass = mono_class_from_name_checked (file_image, name_space, name, error);
                        if (klass || !is_ok (error))
@@ -7909,7 +7889,7 @@ mono_class_from_name_checked_aux (MonoImage *image, const char* name_space, cons
 
                impl = cols [MONO_EXP_TYPE_IMPLEMENTATION];
                if ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE) {
-                       loaded_image = mono_assembly_load_module (image->assembly, impl >> MONO_IMPLEMENTATION_BITS);
+                       loaded_image = mono_assembly_load_module_checked (image->assembly, impl >> MONO_IMPLEMENTATION_BITS, error);
                        if (!loaded_image)
                                return NULL;
                        klass = mono_class_from_name_checked_aux (loaded_image, name_space, name, visited_images, error);
@@ -9925,21 +9905,63 @@ mono_class_get_method_from_name_flags (MonoClass *klass, const char *name, int p
  *
  * LOCKING: Acquires the loader lock.
  */
-gboolean
-mono_class_set_failure (MonoClass *klass, guint32 ex_type, void *ex_data)
+static gboolean
+mono_class_set_failure (MonoClass *klass, MonoErrorBoxed *boxed_error)
 {
+       g_assert (boxed_error != NULL);
+
        if (mono_class_has_failure (klass))
                return FALSE;
 
        mono_loader_lock ();
-       klass->exception_type = ex_type;
-       if (ex_data)
-               mono_image_property_insert (klass->image, klass, MONO_CLASS_PROP_EXCEPTION_DATA, ex_data);
+       klass->has_failure = 1;
+       mono_image_property_insert (klass->image, klass, MONO_CLASS_PROP_EXCEPTION_DATA, boxed_error);
        mono_loader_unlock ();
 
        return TRUE;
 }
 
+gboolean
+mono_class_has_failure (const MonoClass *klass)
+{
+       g_assert (klass != NULL);
+       return klass->has_failure != 0;
+}
+
+
+/**
+ * mono_class_set_type_load_failure:
+ * @klass: class in which the failure was detected
+ * @fmt: Printf-style error message string.
+ *
+ * Collect detected failure informaion in the class for later processing.
+ * The error is stored as a MonoErrorBoxed as with mono_error_set_type_load_class ()
+ * Note that only the first failure is kept.
+ *
+ * Returns FALSE if a failure was already set on the class, or TRUE otherwise.
+ *
+ * LOCKING: Acquires the loader lock.
+ */
+gboolean
+mono_class_set_type_load_failure (MonoClass *klass, const char * fmt, ...)
+{
+       MonoError prepare_error;
+       va_list args;
+
+       if (mono_class_has_failure (klass))
+               return FALSE;
+       
+       mono_error_init (&prepare_error);
+       
+       va_start (args, fmt);
+       mono_error_vset_type_load_class (&prepare_error, klass, fmt, args);
+       va_end (args);
+
+       MonoErrorBoxed *box = mono_error_box (&prepare_error, klass->image);
+       mono_error_cleanup (&prepare_error);
+       return mono_class_set_failure (klass, box);
+}
+
 /*
  * mono_class_get_exception_data:
  *
@@ -9947,10 +9969,10 @@ mono_class_set_failure (MonoClass *klass, guint32 ex_type, void *ex_data)
  *
  * LOCKING: Acquires the loader lock.
  */
-gpointer
-mono_class_get_exception_data (MonoClass *klass)
+static gpointer
+mono_class_get_exception_data (const MonoClass *klass)
 {
-       return mono_image_property_lookup (klass->image, klass, MONO_CLASS_PROP_EXCEPTION_DATA);
+       return mono_image_property_lookup (klass->image, (MonoClass*)klass, MONO_CLASS_PROP_EXCEPTION_DATA);
 }
 
 /**
@@ -10000,55 +10022,12 @@ mono_classes_cleanup (void)
 MonoException*
 mono_class_get_exception_for_failure (MonoClass *klass)
 {
-       gpointer exception_data = mono_class_get_exception_data (klass);
-
-       switch (mono_class_get_failure(klass)) {
-       case MONO_EXCEPTION_TYPE_LOAD: {
-               MonoString *name;
-               MonoException *ex;
-               char *str = mono_type_get_full_name (klass);
-               char *astr = klass->image->assembly? mono_stringify_assembly_name (&klass->image->assembly->aname): NULL;
-               name = mono_string_new (mono_domain_get (), str);
-               g_free (str);
-               ex = mono_get_exception_type_load (name, astr);
-               g_free (astr);
-               return ex;
-       }
-       case MONO_EXCEPTION_MISSING_METHOD: {
-               char *class_name = (char *)exception_data;
-               char *assembly_name = class_name + strlen (class_name) + 1;
-
-               return mono_get_exception_missing_method (class_name, assembly_name);
-       }
-       case MONO_EXCEPTION_MISSING_FIELD: {
-               char *class_name = (char *)exception_data;
-               char *member_name = class_name + strlen (class_name) + 1;
-
-               return mono_get_exception_missing_field (class_name, member_name);
-       }
-       case MONO_EXCEPTION_FILE_NOT_FOUND: {
-               char *msg_format = (char *)exception_data;
-               char *assembly_name = msg_format + strlen (msg_format) + 1;
-               char *msg = g_strdup_printf (msg_format, assembly_name);
-               MonoException *ex;
-
-               ex = mono_get_exception_file_not_found2 (msg, mono_string_new (mono_domain_get (), assembly_name));
-
-               g_free (msg);
-
-               return ex;
-       }
-       case MONO_EXCEPTION_BAD_IMAGE: {
-               return mono_get_exception_bad_image_format ((const char *)exception_data);
-       }
-       case MONO_EXCEPTION_INVALID_PROGRAM: {
-               return mono_exception_from_name_msg (mono_defaults.corlib, "System", "InvalidProgramException", "");
-       }
-       default: {
-               /* TODO - handle other class related failures */
-               return mono_get_exception_execution_engine ("Unknown class failure");
-       }
-       }
+       if (!mono_class_has_failure (klass))
+               return NULL;
+       MonoError unboxed_error;
+       mono_error_init (&unboxed_error);
+       mono_error_set_for_class_failure (&unboxed_error, klass);
+       return mono_error_convert_to_exception (&unboxed_error);
 }
 
 static gboolean
@@ -10634,7 +10613,7 @@ mono_class_setup_interfaces (MonoClass *klass, MonoError *error)
 
                mono_class_setup_interfaces (gklass, error);
                if (!mono_error_ok (error)) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Could not setup the interfaces"));
+                       mono_class_set_type_load_failure (klass, "Could not setup the interfaces");
                        return;
                }
 
@@ -10643,7 +10622,7 @@ mono_class_setup_interfaces (MonoClass *klass, MonoError *error)
                for (i = 0; i < interface_count; i++) {
                        interfaces [i] = mono_class_inflate_generic_class_checked (gklass->interfaces [i], mono_generic_class_get_context (klass->generic_class), error);
                        if (!mono_error_ok (error)) {
-                               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup ("Could not setup the interfaces"));
+                               mono_class_set_type_load_failure (klass, "Could not setup the interfaces");
                                return;
                        }
                }
@@ -10680,14 +10659,12 @@ mono_field_resolve_type (MonoClassField *field, MonoError *error)
                MonoClassField *gfield = &gtd->fields [field_idx];
                MonoType *gtype = mono_field_get_type_checked (gfield, error);
                if (!mono_error_ok (error)) {
-                       char *err_msg = g_strdup_printf ("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 = g_strdup_printf ("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;
@@ -10710,7 +10687,7 @@ mono_field_resolve_type (MonoClassField *field, MonoError *error)
 
                if (!mono_verifier_verify_field_signature (image, cols [MONO_FIELD_SIGNATURE], NULL)) {
                        mono_error_set_type_load_class (error, klass, "Could not verify field %s signature", field->name);;
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, g_strdup (mono_error_get_message (error)));
+                       mono_class_set_type_load_failure (klass, "%s", mono_error_get_message (error));
                        return;
                }
 
@@ -10722,8 +10699,7 @@ mono_field_resolve_type (MonoClassField *field, MonoError *error)
 
                field->type = mono_metadata_parse_type_checked (image, container, cols [MONO_FIELD_FLAGS], FALSE, sig + 1, &sig, error);
                if (!field->type) {
-                       char *err_msg = g_strdup_printf ("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));
                }
        }
 }
index bedd740079bfdc160e07c76ae65b67134f7af777..5f7d15560aa1c3c83d20b8664b7ae7cfe4517e34 100644 (file)
 #include <string.h>
 #include <errno.h>
 
+#if defined(HOST_WIN32)
+#include <oleauto.h>
+#endif
+
 /*
 Code shared between the DISABLE_COM and !DISABLE_COM
 */
diff --git a/mono/metadata/console-win32-internals.h b/mono/metadata/console-win32-internals.h
new file mode 100644 (file)
index 0000000..e0cd222
--- /dev/null
@@ -0,0 +1,18 @@
+/*
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#ifndef __MONO_CONSOLE_WIN32_INTERNALS_H__
+#define __MONO_CONSOLE_WIN32_INTERNALS_H__
+
+#include <config.h>
+#include <glib.h>
+
+#include "mono/metadata/object.h"
+#include "mono/metadata/object-internals.h"
+#include "mono/utils/mono-error.h"
+#include "mono/utils/mono-error-internals.h"
+#include <mono/metadata/console-io.h>
+
+#endif /* __MONO_CONSOLE_WIN32_INTERNALS_H__ */
+
diff --git a/mono/metadata/console-win32-uwp.c b/mono/metadata/console-win32-uwp.c
new file mode 100644 (file)
index 0000000..56d4336
--- /dev/null
@@ -0,0 +1,100 @@
+/*
+ * console-win32-uwp.c: UWP console support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+
+#if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
+#include <Windows.h>
+#include "mono/metadata/console-win32-internals.h"
+
+MonoBoolean
+ves_icall_System_ConsoleDriver_Isatty (HANDLE handle)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("Console");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "Console");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+MonoBoolean
+ves_icall_System_ConsoleDriver_SetEcho (MonoBoolean want_echo)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("Console");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "Console");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+MonoBoolean
+ves_icall_System_ConsoleDriver_SetBreak (MonoBoolean want_break)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("Console");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "Console");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+gint32
+ves_icall_System_ConsoleDriver_InternalKeyAvailable (gint32 timeout)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("Console");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "Console");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+MonoBoolean
+ves_icall_System_ConsoleDriver_TtySetup (MonoString *keypad, MonoString *teardown, MonoArray **control_chars, int **size)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("Console");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "Console");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+#else /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_console_windows_uwp_quiet_lnk4221(void) {}
+#endif
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
index c7c8c49017b6182ee292e7d2d9fc373621384b22..06a0244477e1afd5e3a0ba40d4fddcd4c8e56ed1 100644 (file)
@@ -41,11 +41,11 @@ mono_console_handle_async_ops (void)
 {
 }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 MonoBoolean
 ves_icall_System_ConsoleDriver_Isatty (HANDLE handle)
 {
        DWORD mode;
-
        return GetConsoleMode (handle, &mode) != 0;
 }
 
@@ -72,3 +72,4 @@ ves_icall_System_ConsoleDriver_TtySetup (MonoString *keypad, MonoString *teardow
 {
        return FALSE;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
diff --git a/mono/metadata/coree-internals.h b/mono/metadata/coree-internals.h
new file mode 100644 (file)
index 0000000..3df754f
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#ifndef __MONO_COREE_INTERNALS_H__
+#define __MONO_COREE_INTERNALS_H__
+
+#include <config.h>
+#include <glib.h>
+
+#ifdef HOST_WIN32
+#include <Windows.h>
+
+BOOL STDMETHODCALLTYPE
+_CorDllMain (HINSTANCE hInst, DWORD dwReason, LPVOID lpReserved);
+
+__int32 STDMETHODCALLTYPE
+_CorExeMain (void);
+
+void STDMETHODCALLTYPE
+CorExitProcess (int exitCode);
+
+STDAPI
+_CorValidateImage (PVOID *ImageBase, LPCWSTR FileName);
+
+STDAPI_(VOID)
+_CorImageUnloading (PVOID ImageBase);
+
+STDAPI
+CorBindToRuntimeEx (LPCWSTR pwszVersion, LPCWSTR pwszBuildFlavor,
+                   DWORD startupFlags, REFCLSID rclsid, REFIID riid, LPVOID FAR *ppv);
+
+STDAPI
+CorBindToRuntime (LPCWSTR pwszVersion, LPCWSTR pwszBuildFlavor,
+                 REFCLSID rclsid, REFIID riid, LPVOID FAR *ppv);
+
+HMODULE WINAPI
+MonoLoadImage (LPCWSTR FileName);
+
+void mono_coree_set_act_ctx (const char *file_name);
+#endif /* HOST_WIN32 */
+
+#endif /* __MONO_COREE_INTERNALS_H__ */
+
diff --git a/mono/metadata/coree-windows-uwp.c b/mono/metadata/coree-windows-uwp.c
new file mode 100644 (file)
index 0000000..7aacb5e
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * coree-windows-uwp.c: UWP coree support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+
+#if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
+#include <Windows.h>
+#include "mono/metadata/coree-internals.h"
+
+BOOL STDMETHODCALLTYPE
+_CorDllMain(HINSTANCE hInst, DWORD dwReason, LPVOID lpReserved)
+{
+       g_unsupported_api ("_CorDllMain");
+       return FALSE;
+}
+
+__int32 STDMETHODCALLTYPE
+_CorExeMain(void)
+{
+       g_unsupported_api ("_CorExeMain");
+       ExitProcess (EXIT_FAILURE);
+}
+
+STDAPI
+_CorValidateImage(PVOID *ImageBase, LPCWSTR FileName)
+{
+       g_unsupported_api ("_CorValidateImage");
+       return E_UNEXPECTED;
+}
+
+HMODULE WINAPI
+MonoLoadImage(LPCWSTR FileName)
+{
+       g_unsupported_api ("MonoLoadImage");
+       return NULL;
+}
+
+void
+mono_coree_set_act_ctx (const char *file_name)
+{
+       g_unsupported_api ("CreateActCtx, ActivateActCtx");
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return;
+}
+
+#else /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_coree_windows_uwp_quiet_lnk4221(void) {}
+#endif
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
index 4436229376e10101b1d16f827601c72f466d2328..428fb9b989f80b6fea16ac5b54aad5cdf52cceb3 100644 (file)
@@ -12,8 +12,8 @@
 
 #ifdef HOST_WIN32
 
-#include <string.h>
 #include <glib.h>
+#include <string.h>
 #include <mono/io-layer/io-layer.h>
 #include <mono/utils/mono-path.h>
 #include "cil-coff.h"
 #include "threads.h"
 #include "environment.h"
 #include "coree.h"
+#include "coree-internals.h"
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 #include <shellapi.h>
+#endif
 
 HMODULE coree_module_handle = NULL;
 
@@ -68,6 +71,7 @@ mono_get_module_file_name (HMODULE module_handle)
 }
 
 /* Entry point called by LdrLoadDll of ntdll.dll after _CorValidateImage. */
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 BOOL STDMETHODCALLTYPE _CorDllMain(HINSTANCE hInst, DWORD dwReason, LPVOID lpReserved)
 {
        MonoAssembly* assembly;
@@ -134,8 +138,10 @@ BOOL STDMETHODCALLTYPE _CorDllMain(HINSTANCE hInst, DWORD dwReason, LPVOID lpRes
 
        return TRUE;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
 
 /* Called by ntdll.dll reagardless of entry point after _CorValidateImage. */
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 __int32 STDMETHODCALLTYPE _CorExeMain(void)
 {
        MonoError error;
@@ -207,6 +213,7 @@ __int32 STDMETHODCALLTYPE _CorExeMain(void)
        /* return does not terminate the process. */
        ExitProcess (mono_environment_exitcode_get ());
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
 
 /* Called by msvcrt.dll when shutting down. */
 void STDMETHODCALLTYPE CorExitProcess(int exitCode)
@@ -223,6 +230,7 @@ void STDMETHODCALLTYPE CorExitProcess(int exitCode)
 }
 
 /* Called by ntdll.dll before _CorDllMain and _CorExeMain. */
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 STDAPI _CorValidateImage(PVOID *ImageBase, LPCWSTR FileName)
 {
        IMAGE_DOS_HEADER* DosHeader;
@@ -385,6 +393,7 @@ STDAPI _CorValidateImage(PVOID *ImageBase, LPCWSTR FileName)
 
        return STATUS_SUCCESS;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
 
 /* Called by ntdll.dll. */
 STDAPI_(VOID) _CorImageUnloading(PVOID ImageBase)
@@ -406,6 +415,7 @@ STDAPI CorBindToRuntime(LPCWSTR pwszVersion, LPCWSTR pwszBuildFlavor, REFCLSID r
        return CorBindToRuntimeEx (pwszVersion, pwszBuildFlavor, 0, rclsid, riid, ppv);
 }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 HMODULE WINAPI MonoLoadImage(LPCWSTR FileName)
 {
        HANDLE FileHandle;
@@ -482,6 +492,7 @@ CloseFile:
        CloseHandle(FileHandle);
        return NULL;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
 
 typedef struct _EXPORT_FIXUP
 {
@@ -499,14 +510,14 @@ typedef struct _EXPORT_FIXUP
 
 /* Has to be binary ordered. */
 static const EXPORT_FIXUP ExportFixups[] = {
-       {"CorBindToRuntime", &CorBindToRuntime},
-       {"CorBindToRuntimeEx", &CorBindToRuntimeEx},
-       {"CorExitProcess", &CorExitProcess},
-       {"_CorDllMain", &_CorDllMain},
-       {"_CorExeMain", &_CorExeMain},
-       {"_CorImageUnloading", &_CorImageUnloading},
-       {"_CorValidateImage", &_CorValidateImage},
-       {NULL, NULL}
+       {"CorBindToRuntime", {&CorBindToRuntime}},
+       {"CorBindToRuntimeEx", {&CorBindToRuntimeEx}},
+       {"CorExitProcess", {&CorExitProcess}},
+       {"_CorDllMain", {&_CorDllMain}},
+       {"_CorExeMain", {&_CorExeMain}},
+       {"_CorImageUnloading", {&_CorImageUnloading}},
+       {"_CorValidateImage", {&_CorValidateImage}},
+       {NULL, {NULL}}
 };
 
 #define EXPORT_FIXUP_COUNT (sizeof(ExportFixups) / sizeof(EXPORT_FIXUP) - 1)
@@ -795,7 +806,15 @@ STDAPI MonoFixupExe(HMODULE ModuleHandle)
                        ImportDesc = (IMAGE_IMPORT_DESCRIPTOR*)((DWORD_PTR)DosHeader + ImportDir->VirtualAddress);
                        while (ImportDesc->Name && ImportDesc->OriginalFirstThunk)
                        {
-                               ImportModuleHandle = LoadLibraryA((PCSTR)((DWORD_PTR)DosHeader + ImportDesc->Name));
+                               gchar *file_utf8 = (gchar *)((DWORD_PTR)DosHeader + ImportDesc->Name);
+
+                               gunichar2 *file_utf16 = g_utf8_to_utf16 (file_utf8, (glong)strlen (file_utf8), NULL, NULL, NULL);
+                               ImportModuleHandle = NULL;
+                               if (file_utf16 != NULL) {
+                                       ImportModuleHandle = LoadLibraryW(file_utf16);
+                                       g_free (file_utf16);
+                               }
+
                                if (ImportModuleHandle == NULL)
                                        return E_FAIL;
 
@@ -828,8 +847,9 @@ STDAPI MonoFixupExe(HMODULE ModuleHandle)
        return S_OK;
 }
 
-static void
-mono_set_act_ctx (const char* file_name)
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+void
+mono_coree_set_act_ctx (const char* file_name)
 {
        typedef HANDLE (WINAPI* CREATEACTCTXW_PROC) (PCACTCTXW pActCtx);
        typedef BOOL (WINAPI* ACTIVATEACTCTX_PROC) (HANDLE hActCtx, ULONG_PTR* lpCookie);
@@ -888,6 +908,7 @@ mono_set_act_ctx (const char* file_name)
        if (handle != INVALID_HANDLE_VALUE)
                ActivateActCtx_proc (handle, &cookie);
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
 
 void
 mono_load_coree (const char* exe_file_name)
@@ -901,7 +922,7 @@ mono_load_coree (const char* exe_file_name)
                return;
 
        if (!init_from_coree && exe_file_name)
-               mono_set_act_ctx (exe_file_name);
+               mono_coree_set_act_ctx (exe_file_name);
 
        /* ntdll.dll loads mscoree.dll from the system32 directory. */
        required_size = GetSystemDirectory (NULL, 0);
index a1d48eb3d4431fdb2792d47eae84c5644cd9489f..d76c0376adc8620dd1a35a940bf35eb631b93f80 100644 (file)
@@ -1545,10 +1545,6 @@ mono_reflection_get_custom_attrs_info_checked (MonoObject *obj, MonoError *error
                MonoReflectionMethod *rmethod = (MonoReflectionMethod*)obj;
                cinfo = mono_custom_attrs_from_method_checked (rmethod->method, error);
                return_val_if_nok (error, NULL);
-       } else if ((strcmp ("MonoGenericMethod", klass->name) == 0) || (strcmp ("MonoGenericCMethod", klass->name) == 0)) {
-               MonoReflectionMethod *rmethod = (MonoReflectionMethod*)obj;
-               cinfo = mono_custom_attrs_from_method_checked (rmethod->method, error);
-               return_val_if_nok (error, NULL);
        } else if (strcmp ("ParameterInfo", klass->name) == 0 || strcmp ("MonoParameterInfo", klass->name) == 0) {
                MonoReflectionParameter *param = (MonoReflectionParameter*)obj;
                MonoClass *member_class = mono_object_class (param->MemberImpl);
@@ -1568,22 +1564,11 @@ mono_reflection_get_custom_attrs_info_checked (MonoObject *obj, MonoError *error
                } 
 #ifndef DISABLE_REFLECTION_EMIT
                else if (mono_is_sre_method_on_tb_inst (member_class)) {/*XXX This is a workaround for Compiler Context*/
-                       MonoMethod *method = mono_reflection_method_on_tb_inst_get_handle ((MonoReflectionMethodOnTypeBuilderInst*)param->MemberImpl, error);
-                       return_val_if_nok (error, NULL);
-                       cinfo = mono_custom_attrs_from_param_checked (method, param->PositionImpl + 1, error);
-                       return_val_if_nok (error, NULL);
+                       // FIXME: Is this still needed ?
+                       g_assert_not_reached ();
                } else if (mono_is_sre_ctor_on_tb_inst (member_class)) { /*XX This is a workaround for Compiler Context*/
-                       MonoReflectionCtorOnTypeBuilderInst *c = (MonoReflectionCtorOnTypeBuilderInst*)param->MemberImpl;
-                       MonoMethod *method = NULL;
-                       if (mono_is_sre_ctor_builder (mono_object_class (c->cb)))
-                               method = ((MonoReflectionCtorBuilder *)c->cb)->mhandle;
-                       else if (mono_is_sr_mono_cmethod (mono_object_class (c->cb)))
-                               method = ((MonoReflectionMethod *)c->cb)->method;
-                       else
-                               g_error ("mono_reflection_get_custom_attrs_info:: can't handle a CTBI with base_method of type %s", mono_type_get_full_name (member_class));
-
-                       cinfo = mono_custom_attrs_from_param_checked (method, param->PositionImpl + 1, error);
-                       return_val_if_nok (error, NULL);
+                       // FIXME: Is this still needed ?
+                       g_assert_not_reached ();
                } 
 #endif
                else {
index f418b2078cee4af6f2da49eb191d887c99d458bb..b7e48f95d44aebf774a53df0f23ca8fc3521e7e7 100644 (file)
@@ -649,11 +649,6 @@ mono_debug_symfile_get_seq_points (MonoDebugMethodInfo *minfo, char **source_fil
                        if (source_files)
                                (*source_files) [i] = (*source_file_list)->len - 1;
                }
-               if ((*source_file_list)->len == 0 && stm.file) {
-                       MonoDebugSourceInfo *info = get_source_info (symfile, stm.file);
-
-                       g_ptr_array_add (*source_file_list, info);
-               }
        }                               
 
        if (n_seq_points) {
index 1f555ed4e324daf757f982df42c12e13733d4ac2..b845fc2708e7186d19458c90c47ce86045dcdb94 100644 (file)
@@ -339,7 +339,6 @@ struct _MonoDomain {
        /* Needed by Thread:GetDomainID() */
        gint32             domain_id;
        gint32             shadow_serial;
-       unsigned char      inet_family_hint; // used in socket-io.c as a cache
        GSList             *domain_assemblies;
        MonoAssembly       *entry_assembly;
        char               *friendly_name;
index bb40725ac1f401e085deccb0dc901a0b083a6ecd..dfb3c29eefc5af88d07cdc37c168c66c6f39a58c 100644 (file)
@@ -522,7 +522,7 @@ mono_init_internal (const char *filename, const char *exe_filename, const char *
        if (domain)
                g_assert_not_reached ();
 
-#ifdef HOST_WIN32
+#if defined(HOST_WIN32) && G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
        /* Avoid system error message boxes. */
        SetErrorMode (SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
 #endif
@@ -1175,6 +1175,12 @@ mono_domain_free (MonoDomain *domain, gboolean force)
        g_slist_free (domain->domain_assemblies);
        domain->domain_assemblies = NULL;
 
+       /* 
+        * Send this after the assemblies have been unloaded and the domain is still in a 
+        * usable state.
+        */
+       mono_profiler_appdomain_event (domain, MONO_PROFILE_END_UNLOAD);
+
        if (free_domain_hook)
                free_domain_hook (domain);
 
index 17f0f8e82fba2642e8296010cd2c33d41c5d4284..9906f43b31838ec448675aeab80c281ee262d8c1 100644 (file)
@@ -347,7 +347,6 @@ mono_dynamic_image_create (MonoDynamicAssembly *assembly, char *assembly_name, c
        image->handleref_managed = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_REFLECTION, "dynamic module reference-to-token table");
        image->tokens = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_REFLECTION, "dynamic module tokens table");
        image->generic_def_objects = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_REFLECTION, "dynamic module generic definitions table");
-       image->methodspec = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_REFLECTION, "dynamic module method specifications table");
        image->typespec = g_hash_table_new ((GHashFunc)mono_metadata_type_hash, (GCompareFunc)mono_metadata_type_equal);
        image->typeref = g_hash_table_new ((GHashFunc)mono_metadata_type_hash, (GCompareFunc)mono_metadata_type_equal);
        image->blob_cache = g_hash_table_new ((GHashFunc)mono_blob_entry_hash, (GCompareFunc)mono_blob_entry_equal);
@@ -469,7 +468,6 @@ mono_dynamic_image_release_gc_roots (MonoDynamicImage *image)
        release_hashtable (&image->tokens);
        release_hashtable (&image->remapped_tokens);
        release_hashtable (&image->generic_def_objects);
-       release_hashtable (&image->methodspec);
 }
 
 // Free dynamic image pass one: Free resources but not image itself
@@ -480,8 +478,6 @@ mono_dynamic_image_free (MonoDynamicImage *image)
        GList *list;
        int i;
 
-       if (di->methodspec)
-               mono_g_hash_table_destroy (di->methodspec);
        if (di->typespec)
                g_hash_table_destroy (di->typespec);
        if (di->typeref)
index 02b738556c597c72fbc7ed9fe76a5acead5d97eb..b4be09844ac59ec3c482c2bb27d7620acacd7cc4 100644 (file)
@@ -976,8 +976,12 @@ mono_exception_get_native_backtrace (MonoException *exc)
        domain = mono_domain_get ();
        len = mono_array_length (arr);
        text = g_string_new_len (NULL, len * 20);
-       messages = backtrace_symbols (mono_array_addr (arr, gpointer, 0), len);
-
+       uint32_t gchandle = mono_gchandle_new (&arr->obj, TRUE); /* pinned */
+       void* addr = mono_array_addr (arr, gpointer, 0);
+       MONO_ENTER_GC_SAFE;
+       messages = backtrace_symbols (addr, len);
+       MONO_EXIT_GC_SAFE;
+       mono_gchandle_free (gchandle);
 
        for (i = 0; i < len; ++i) {
                gpointer ip = mono_array_get (arr, gpointer, i);
diff --git a/mono/metadata/file-io-internals.h b/mono/metadata/file-io-internals.h
new file mode 100644 (file)
index 0000000..3fe5970
--- /dev/null
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#ifndef __MONO_FILE_IO_INTERNALS_H__
+#define __MONO_FILE_IO_INTERNALS_H__
+
+#include <config.h>
+#include <glib.h>
+#include "mono/metadata/object.h"
+#include "mono/metadata/object-internals.h"
+
+gboolean
+mono_file_io_move_file (gunichar2 *path, gunichar2 *dest, gint32 *error);
+
+gboolean
+mono_file_io_copy_file (gunichar2 *path, gunichar2 *dest, gboolean overwrite, gint32 *error);
+
+gint64
+mono_file_io_get_file_size (HANDLE handle, gint32 *error);
+
+gboolean
+mono_file_io_lock_file (HANDLE handle, gint64 position, gint64 length, gint32 *error);
+
+gboolean
+mono_file_io_replace_file (gunichar2 *destinationFileName, gunichar2 *sourceFileName,
+                          gunichar2 *destinationBackupFileName, guint32 flags, gint32 *error);
+
+gboolean
+mono_file_io_unlock_file (HANDLE handle, gint64 position, gint64 length, gint32 *error);
+
+#endif /* __MONO_FILE_IO_INTERNALS_H__ */
diff --git a/mono/metadata/file-io-windows-internals.h b/mono/metadata/file-io-windows-internals.h
new file mode 100644 (file)
index 0000000..df372e8
--- /dev/null
@@ -0,0 +1,15 @@
+/*
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#ifndef _MONO_METADATA_FILEIO_WINDOWS_H_
+#define _MONO_METADATA_FILEIO_WINDOWS_H_
+
+#include <config.h>
+#include <glib.h>
+
+#ifdef HOST_WIN32
+#include "mono/metadata/file-io.h"
+#include "mono/metadata/file-io-internals.h"
+#endif /* HOST_WIN32 */
+#endif /* _MONO_METADATA_FILEIO_WINDOWS_H_ */
diff --git a/mono/metadata/file-io-windows-uwp.c b/mono/metadata/file-io-windows-uwp.c
new file mode 100644 (file)
index 0000000..2ece546
--- /dev/null
@@ -0,0 +1,121 @@
+/*
+ * file-io-windows-uwp.c: UWP file-io support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+
+#if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
+#include <Windows.h>
+#include "mono/metadata/file-io-windows-internals.h"
+
+gboolean
+mono_file_io_move_file (gunichar2 *path, gunichar2 *dest, gint32 *error)
+{
+       gboolean result = FALSE;
+       MONO_ENTER_GC_SAFE;
+
+       result = MoveFileEx (path, dest, MOVEFILE_COPY_ALLOWED);
+       if (result == FALSE) {
+               *error=GetLastError ();
+       }
+
+       MONO_EXIT_GC_SAFE;
+       return result;
+}
+
+gboolean
+mono_file_io_replace_file (gunichar2 *destinationFileName, gunichar2 *sourceFileName,
+                          gunichar2 *destinationBackupFileName, guint32 flags, gint32 *error)
+{
+       gboolean result = FALSE;
+       MONO_ENTER_GC_SAFE;
+
+       result = ReplaceFile (destinationFileName, sourceFileName, destinationBackupFileName, flags, NULL, NULL);
+       if (result == FALSE) {
+               *error=GetLastError ();
+       }
+
+       MONO_EXIT_GC_SAFE;
+       return result;
+}
+
+gboolean
+mono_file_io_copy_file (gunichar2 *path, gunichar2 *dest, gboolean overwrite, gint32 *error)
+{
+       gboolean                                                result = FALSE;
+       COPYFILE2_EXTENDED_PARAMETERS   copy_param = {0};
+
+       copy_param.dwSize = sizeof (COPYFILE2_EXTENDED_PARAMETERS);
+       copy_param.dwCopyFlags = (!overwrite) ? COPY_FILE_FAIL_IF_EXISTS : 0;
+
+       MONO_ENTER_GC_SAFE;
+
+       result = SUCCEEDED (CopyFile2 (path, dest, &copy_param));
+       if (result == FALSE) {
+               *error=GetLastError ();
+       }
+
+       MONO_EXIT_GC_SAFE;
+       return result;
+}
+
+gint64
+mono_file_io_get_file_size (HANDLE handle, gint32 *error)
+{
+       LARGE_INTEGER length;
+
+       MONO_ENTER_GC_SAFE;
+
+       if (!GetFileSizeEx (handle, &length)) {
+               *error=GetLastError ();
+               length.QuadPart = INVALID_FILE_SIZE;
+       }
+
+       MONO_EXIT_GC_SAFE;
+       return length.QuadPart;
+}
+
+gboolean
+mono_file_io_lock_file (HANDLE handle, gint64 position, gint64 length, gint32 *error)
+{
+       gboolean result = FALSE;
+       MONO_ENTER_GC_SAFE;
+
+       result = LockFile (handle, position & 0xFFFFFFFF, position >> 32,
+                          length & 0xFFFFFFFF, length >> 32);
+
+       if (result == FALSE) {
+               *error = GetLastError ();
+       }
+
+       MONO_EXIT_GC_SAFE;
+       return result;
+}
+
+gboolean
+mono_file_io_unlock_file (HANDLE handle, gint64 position, gint64 length, gint32 *error)
+{
+       gboolean result = FALSE;
+       MONO_ENTER_GC_SAFE;
+
+       result = UnlockFile (handle, position & 0xFFFFFFFF, position >> 32,
+                            length & 0xFFFFFFFF, length >> 32);
+
+       if (result == FALSE) {
+               *error = GetLastError ();
+       }
+
+       MONO_EXIT_GC_SAFE;
+       return result;
+}
+
+#else /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_file_io_windows_uwp_quiet_lnk4221(void) {}
+#endif
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
diff --git a/mono/metadata/file-io-windows.c b/mono/metadata/file-io-windows.c
new file mode 100644 (file)
index 0000000..fcd76cc
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * file-io-windows.c: Windows File IO internal calls.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#include <config.h>
+#include <glib.h>
+
+#if defined(HOST_WIN32)
+#include <WinSock2.h>
+#include <Windows.h>
+#include "mono/metadata/file-io-windows-internals.h"
+
+gunichar2
+ves_icall_System_IO_MonoIO_get_VolumeSeparatorChar ()
+{
+       return (gunichar2) ':'; /* colon */
+}
+
+gunichar2
+ves_icall_System_IO_MonoIO_get_DirectorySeparatorChar ()
+{
+       return (gunichar2) '\\';        /* backslash */
+}
+
+gunichar2
+ves_icall_System_IO_MonoIO_get_AltDirectorySeparatorChar ()
+{
+       return (gunichar2) '/'; /* forward slash */
+}
+
+gunichar2
+ves_icall_System_IO_MonoIO_get_PathSeparator ()
+{
+       return (gunichar2) ';'; /* semicolon */
+}
+
+void ves_icall_System_IO_MonoIO_DumpHandles (void)
+{
+       return;
+}
+#endif /* HOST_WIN32 */
index 1e0422e35fbc0f069b63b3136850af188a785384..dd722f289a958c6a8c6452a9fc6bb073d7268fe5 100644 (file)
@@ -29,6 +29,7 @@
 #include <mono/metadata/object.h>
 #include <mono/io-layer/io-layer.h>
 #include <mono/metadata/file-io.h>
+#include <mono/metadata/file-io-internals.h>
 #include <mono/metadata/exception.h>
 #include <mono/metadata/appdomain.h>
 #include <mono/metadata/marshal.h>
@@ -606,33 +607,55 @@ ves_icall_System_IO_MonoIO_SetCurrentDirectory (MonoString *path,
        return(ret);
 }
 
-MonoBoolean
-ves_icall_System_IO_MonoIO_MoveFile (MonoString *path, MonoString *dest,
-                                    gint32 *error)
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+gboolean
+mono_file_io_move_file (gunichar2 *path, gunichar2 *dest, gint32 *error)
 {
-       gboolean ret;
+       gboolean result = FALSE;
        MONO_ENTER_GC_SAFE;
-       
+
+       result = MoveFile (path, dest);
+       if (result == FALSE) {
+               *error=GetLastError ();
+       }
+
+       MONO_EXIT_GC_SAFE;
+       return result;
+}
+#endif /* HAVE_CLASSIC_WINAPI_SUPPORT */
+
+MonoBoolean
+ves_icall_System_IO_MonoIO_MoveFile (MonoString *path, MonoString *dest, gint32 *error)
+{
        *error=ERROR_SUCCESS;
+       return mono_file_io_move_file (mono_string_chars (path), mono_string_chars (dest), error);
+}
 
-       ret=MoveFile (mono_string_chars (path), mono_string_chars (dest));
-       if(ret==FALSE) {
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+gboolean
+mono_file_io_replace_file (gunichar2 *destinationFileName, gunichar2 *sourceFileName,
+                          gunichar2 *destinationBackupFileName, guint32 flags, gint32 *error)
+{
+       gboolean result = FALSE;
+       MONO_ENTER_GC_SAFE;
+
+       result = ReplaceFile (destinationFileName, sourceFileName, destinationBackupFileName, flags, NULL, NULL);
+       if (result == FALSE) {
                *error=GetLastError ();
        }
 
        MONO_EXIT_GC_SAFE;
-       return(ret);
+       return result;
 }
+#endif /* HAVE_CLASSIC_WINAPI_SUPPORT */
 
 MonoBoolean
 ves_icall_System_IO_MonoIO_ReplaceFile (MonoString *sourceFileName, MonoString *destinationFileName,
                                        MonoString *destinationBackupFileName, MonoBoolean ignoreMetadataErrors,
                                        gint32 *error)
 {
-       gboolean ret;
        gunichar2 *utf16_sourceFileName = NULL, *utf16_destinationFileName = NULL, *utf16_destinationBackupFileName = NULL;
        guint32 replaceFlags = REPLACEFILE_WRITE_THROUGH;
-       MONO_ENTER_GC_SAFE;
 
        if (sourceFileName)
                utf16_sourceFileName = mono_string_chars (sourceFileName);
@@ -646,31 +669,33 @@ ves_icall_System_IO_MonoIO_ReplaceFile (MonoString *sourceFileName, MonoString *
                replaceFlags |= REPLACEFILE_IGNORE_MERGE_ERRORS;
 
        /* FIXME: source and destination file names must not be NULL, but apparently they might be! */
-       ret = ReplaceFile (utf16_destinationFileName, utf16_sourceFileName, utf16_destinationBackupFileName,
-                        replaceFlags, NULL, NULL);
-       if (ret == FALSE)
-               *error = GetLastError ();
+       return mono_file_io_replace_file (utf16_destinationFileName, utf16_sourceFileName,
+                                         utf16_destinationBackupFileName, replaceFlags, error);
+}
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+gboolean
+mono_file_io_copy_file (gunichar2 *path, gunichar2 *dest, gboolean overwrite, gint32 *error)
+{
+       gboolean result = FALSE;
+       MONO_ENTER_GC_SAFE;
+
+       result = CopyFile (path, dest, !overwrite);
+       if (result == FALSE) {
+               *error=GetLastError ();
+       }
 
        MONO_EXIT_GC_SAFE;
-       return ret;
+       return result;
 }
+#endif /* HAVE_CLASSIC_WINAPI_SUPPORT */
 
 MonoBoolean
 ves_icall_System_IO_MonoIO_CopyFile (MonoString *path, MonoString *dest,
                                     MonoBoolean overwrite, gint32 *error)
 {
-       gboolean ret;
-       MONO_ENTER_GC_SAFE;
-       
        *error=ERROR_SUCCESS;
-       
-       ret=CopyFile (mono_string_chars (path), mono_string_chars (dest), !overwrite);
-       if(ret==FALSE) {
-               *error=GetLastError ();
-       }
-       
-       MONO_EXIT_GC_SAFE;
-       return(ret);
+       return mono_file_io_copy_file (mono_string_chars (path), mono_string_chars (dest), overwrite, error);
 }
 
 MonoBoolean
@@ -948,23 +973,31 @@ ves_icall_System_IO_MonoIO_Flush (HANDLE handle, gint32 *error)
        return(ret);
 }
 
-gint64 
-ves_icall_System_IO_MonoIO_GetLength (HANDLE handle, gint32 *error)
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+gint64
+mono_file_io_get_file_size (HANDLE handle, gint32 *error)
 {
        gint64 length;
        guint32 length_hi;
+
        MONO_ENTER_GC_SAFE;
 
-       *error=ERROR_SUCCESS;
-       
        length = GetFileSize (handle, &length_hi);
        if(length==INVALID_FILE_SIZE) {
                *error=GetLastError ();
        }
-       
+
        MONO_EXIT_GC_SAFE;
        return length | ((gint64)length_hi << 32);
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+gint64
+ves_icall_System_IO_MonoIO_GetLength (HANDLE handle, gint32 *error)
+{
+       *error=ERROR_SUCCESS;
+       return mono_file_io_get_file_size (handle, error);
+}
 
 /* FIXME make gc suspendable */
 MonoBoolean
@@ -1113,48 +1146,34 @@ ves_icall_System_IO_MonoIO_DuplicateHandle (HANDLE source_process_handle, HANDLE
        return(TRUE);
 }
 
+#ifndef HOST_WIN32
 gunichar2 
 ves_icall_System_IO_MonoIO_get_VolumeSeparatorChar ()
 {
-#if defined (TARGET_WIN32)
-       return (gunichar2) ':'; /* colon */
-#else
        return (gunichar2) '/'; /* forward slash */
-#endif
 }
 
 gunichar2 
 ves_icall_System_IO_MonoIO_get_DirectorySeparatorChar ()
 {
-#if defined (TARGET_WIN32)
-       return (gunichar2) '\\';        /* backslash */
-#else
        return (gunichar2) '/'; /* forward slash */
-#endif
 }
 
 gunichar2 
 ves_icall_System_IO_MonoIO_get_AltDirectorySeparatorChar ()
 {
-#if defined (TARGET_WIN32)
-       return (gunichar2) '/'; /* forward slash */
-#else
        if (IS_PORTABILITY_SET)
                return (gunichar2) '\\';        /* backslash */
        else
                return (gunichar2) '/'; /* forward slash */
-#endif
 }
 
 gunichar2 
 ves_icall_System_IO_MonoIO_get_PathSeparator ()
 {
-#if defined (TARGET_WIN32)
-       return (gunichar2) ';'; /* semicolon */
-#else
        return (gunichar2) ':'; /* colon */
-#endif
 }
+#endif /* !HOST_WIN32 */
 
 static const gunichar2
 invalid_path_chars [] = {
@@ -1197,38 +1216,56 @@ ves_icall_System_IO_MonoIO_get_InvalidPathChars ()
        return chars;
 }
 
-void ves_icall_System_IO_MonoIO_Lock (HANDLE handle, gint64 position,
-                                     gint64 length, gint32 *error)
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+gboolean
+mono_file_io_lock_file (HANDLE handle, gint64 position, gint64 length, gint32 *error)
 {
-       gboolean ret;
+       gboolean result = FALSE;
        MONO_ENTER_GC_SAFE;
-       
-       *error=ERROR_SUCCESS;
-       
-       ret=LockFile (handle, position & 0xFFFFFFFF, position >> 32,
-                     length & 0xFFFFFFFF, length >> 32);
-       if (ret == FALSE) {
+
+       result = LockFile (handle, position & 0xFFFFFFFF, position >> 32,
+                          length & 0xFFFFFFFF, length >> 32);
+
+       if (result == FALSE) {
                *error = GetLastError ();
        }
 
        MONO_EXIT_GC_SAFE;
+       return result;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
 
-void ves_icall_System_IO_MonoIO_Unlock (HANDLE handle, gint64 position,
-                                       gint64 length, gint32 *error)
+void ves_icall_System_IO_MonoIO_Lock (HANDLE handle, gint64 position,
+                                     gint64 length, gint32 *error)
 {
-       gboolean ret;
-       MONO_ENTER_GC_SAFE;
-       
        *error=ERROR_SUCCESS;
+       mono_file_io_lock_file (handle, position, length, error);
+}
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+gboolean
+mono_file_io_unlock_file (HANDLE handle, gint64 position, gint64 length, gint32 *error)
+{
+       gboolean result = FALSE;
+       MONO_ENTER_GC_SAFE;
        
-       ret=UnlockFile (handle, position & 0xFFFFFFFF, position >> 32,
-                       length & 0xFFFFFFFF, length >> 32);
-       if (ret == FALSE) {
+       result = UnlockFile (handle, position & 0xFFFFFFFF, position >> 32,
+                            length & 0xFFFFFFFF, length >> 32);
+
+       if (result == FALSE) {
                *error = GetLastError ();
        }
 
        MONO_EXIT_GC_SAFE;
+       return result;
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+void ves_icall_System_IO_MonoIO_Unlock (HANDLE handle, gint64 position,
+                                       gint64 length, gint32 *error)
+{
+       *error=ERROR_SUCCESS;
+       mono_file_io_unlock_file (handle, position, length, error);
 }
 
 //Support for io-layer free mmap'd files.
@@ -1274,11 +1311,12 @@ mono_filesize_from_fd (int fd)
 
 #endif
 
+#ifndef HOST_WIN32
 void mono_w32handle_dump (void);
 
 void ves_icall_System_IO_MonoIO_DumpHandles (void)
 {
-#ifndef HOST_WIN32
+
        mono_w32handle_dump ();
-#endif
 }
+#endif /* !HOST_WIN32 */
index cd9408df98bbd073b054eeff706deb64b7a9765f..d3d81f272a8820b14d5710c4bee0a7b532548485 100644 (file)
@@ -103,8 +103,6 @@ extern void mono_gc_set_stack_end (void *stack_end);
 gboolean mono_object_is_alive (MonoObject* obj);
 gboolean mono_gc_is_finalizer_thread (MonoThread *thread);
 gpointer mono_gc_out_of_memory (size_t size);
-void     mono_gc_enable_events (void);
-void     mono_gc_enable_alloc_events (void);
 
 void mono_gchandle_set_target (guint32 gchandle, MonoObject *obj);
 
index 46eaf5e224af7ad3bd1ac05a365d4415ad0d910b..ae4329be666865957ba53ad41f60586c4c2cc065 100644 (file)
@@ -560,8 +560,6 @@ mono_domain_finalize (MonoDomain *domain, guint32 timeout)
                mono_gc_finalize_threadpool_threads ();
        }
 
-       mono_profiler_appdomain_event (domain, MONO_PROFILE_END_UNLOAD);
-
 done:
        if (InterlockedDecrement (&req->ref) == 0) {
                mono_coop_sem_destroy (&req->done);
index 4be4c632d10e53115c39384faec8f8aa2d0ab2e6..44327aed131a7f85595486d2465e19293180d58f 100644 (file)
@@ -45,6 +45,29 @@ Combine: MonoDefaults, GENERATE_GET_CLASS_WITH_CACHE, TYPED_HANDLE_DECL and frie
        We could then generate neat type safe wrappers.
 */
 
+/*
+ * NOTE: Async suspend
+ * 
+ * If we are running with cooperative GC, all the handle stack
+ * manipulation will complete before a GC thread scans the handle
+ * stack. If we are using async suspend, however, a thread may be
+ * trying to allocate a new handle, or unwind the handle stack when
+ * the GC stops the world.
+ *
+ * In particular, we need to ensure that if the mutator thread is
+ * suspended while manipulating the handle stack, the stack is in a
+ * good enough state to be scanned.  In particular, the size of each
+ * chunk should be updated before an object is written into the
+ * handle, and chunks to be scanned (between bottom and top) should
+ * always be valid.
+ *
+ * Note that the handle stack is scanned PRECISELY (see
+ * sgen_client_scan_thread_data ()).  That means there should not be
+ * stale objects scanned.  So when we manipulate the size of a chunk,
+ * wemust ensure that the newly scannable slot is either null or
+ * points to a valid value.
+ */
+
 const MonoObjectHandle mono_null_value_handle = NULL;
 
 #define THIS_IS_AN_OK_NUMBER_OF_HANDLES 100
@@ -59,13 +82,28 @@ mono_handle_new (MonoObject *object)
 
 retry:
        if (G_LIKELY (top->size < OBJECTS_PER_HANDLES_CHUNK)) {
-               MonoObject **h = &top->objects [top->size++];
+               int idx = top->size;
+               /* can be interrupted anywhere here, so:
+                * 1. make sure the new slot is null
+                * 2. make the new slot scannable (increment size)
+                * 3. put a valid object in there
+                *
+                * (have to do 1 then 3 so that if we're interrupted
+                * between 1 and 2, the object is still live)
+                */
+               top->objects [idx] = NULL;
+               mono_memory_write_barrier ();
+               top->size++;
+               mono_memory_write_barrier ();
+               MonoObject **h = &top->objects [idx];
                *h = object;
                return h;
        }
        if (G_LIKELY (top->next)) {
+               top->next->size = 0;
+               /* make sure size == 0 is visible to a GC thread before it sees the new top */
+               mono_memory_write_barrier ();
                top = top->next;
-               top->size = 0;
                handles->top = top;
                goto retry;
        }
@@ -73,6 +111,8 @@ retry:
        new_chunk->size = 0;
        new_chunk->prev = top;
        new_chunk->next = NULL;
+       /* make sure size == 0 before new chunk is visible */
+       mono_memory_write_barrier ();
        top->next = new_chunk;
        handles->top = new_chunk;
        goto retry;
@@ -86,9 +126,10 @@ mono_handle_stack_alloc (void)
        HandleStack *stack = g_new (HandleStack, 1);
        HandleChunk *chunk = g_new (HandleChunk, 1);
 
-       stack->top = stack->bottom = chunk;
        chunk->size = 0;
        chunk->prev = chunk->next = NULL;
+       mono_memory_write_barrier ();
+       stack->top = stack->bottom = chunk;
        return stack;
 }
 
@@ -98,6 +139,8 @@ mono_handle_stack_free (HandleStack *stack)
        if (!stack)
                return;
        HandleChunk *c = stack->bottom;
+       stack->top = stack->bottom = NULL;
+       mono_memory_write_barrier ();
        while (c) {
                HandleChunk *next = c->next;
                g_free (c);
@@ -110,6 +153,8 @@ mono_handle_stack_free (HandleStack *stack)
 void
 mono_handle_stack_scan (HandleStack *stack, GcScanFunc func, gpointer gc_data)
 {
+       /* if we're running, we know the world is stopped.
+        */
        HandleChunk *cur = stack->bottom;
        HandleChunk *last = stack->top;
 
index 102f9f4da7244fbb8aac1b0909d239bd1a49b190..76a43969eba0dd99bd64b78cf7b5674444699784 100644 (file)
@@ -91,8 +91,9 @@ static inline void
 mono_stack_mark_pop (MonoThreadInfo *info, HandleStackMark *stackmark)
 {
        HandleStack *handles = (HandleStack *)info->handle_stack;
-       handles->top = stackmark->chunk;
        handles->top->size = stackmark->size;
+       mono_memory_write_barrier ();
+       handles->top = stackmark->chunk;
 }
 
 /*
index 7c71dc55064e6cb13c8cfc7a79dd08640f67d0bd..c90a85a3c3d4c28297ffac4faef0d189b766412d 100644 (file)
@@ -78,12 +78,250 @@ ICALL(NATIVEMETHODS_10, "TerminateProcess", ves_icall_Microsoft_Win32_NativeMeth
 ICALL(NATIVEMETHODS_11, "WaitForInputIdle", ves_icall_Microsoft_Win32_NativeMethods_WaitForInputIdle)
 #endif /* !DISABLE_PROCESS_HANDLING */
 
+#if HAVE_BTLS
+ICALL_TYPE(BTLS_BIO, "Mono.Btls.MonoBtlsBio", BTLS_BIO_1)
+ICALL(BTLS_BIO_1, "mono_btls_bio_flush", mono_btls_bio_flush)
+ICALL(BTLS_BIO_2, "mono_btls_bio_free", mono_btls_bio_free)
+ICALL(BTLS_BIO_3, "mono_btls_bio_hexdump", mono_btls_bio_hexdump)
+ICALL(BTLS_BIO_4, "mono_btls_bio_indent", mono_btls_bio_indent)
+ICALL(BTLS_BIO_5, "mono_btls_bio_print_errors", mono_btls_bio_print_errors)
+ICALL(BTLS_BIO_6, "mono_btls_bio_read", mono_btls_bio_read)
+ICALL(BTLS_BIO_7, "mono_btls_bio_write", mono_btls_bio_write)
+
+ICALL_TYPE(BTLS_BIO_MEM, "Mono.Btls.MonoBtlsBioMemory", BTLS_BIO_MEM_1)
+ICALL(BTLS_BIO_MEM_1, "mono_btls_bio_mem_get_data", mono_btls_bio_mem_get_data)
+ICALL(BTLS_BIO_MEM_2, "mono_btls_bio_mem_new", mono_btls_bio_mem_new)
+
+ICALL_TYPE(BTLS_BIO_MONO, "Mono.Btls.MonoBtlsBioMono", BTLS_BIO_MONO_1)
+ICALL(BTLS_BIO_MONO_1, "mono_btls_bio_mono_initialize", mono_btls_bio_mono_initialize)
+ICALL(BTLS_BIO_MONO_2, "mono_btls_bio_mono_new", mono_btls_bio_mono_new)
+
+ICALL_TYPE(BTLS_ERROR, "Mono.Btls.MonoBtlsError", BTLS_ERROR_1)
+ICALL(BTLS_ERROR_1, "mono_btls_error_clear_error", mono_btls_error_clear_error)
+ICALL(BTLS_ERROR_2, "mono_btls_error_get_error", mono_btls_error_get_error)
+ICALL(BTLS_ERROR_3, "mono_btls_error_get_error_string_n", mono_btls_error_get_error_string_n)
+ICALL(BTLS_ERROR_4, "mono_btls_error_peek_error", mono_btls_error_peek_error)
+
+ICALL_TYPE(BTLS_KEY, "Mono.Btls.MonoBtlsKey", BTLS_KEY_1)
+ICALL(BTLS_KEY_1, "mono_btls_key_free", mono_btls_key_free)
+ICALL(BTLS_KEY_2, "mono_btls_key_get_bits", mono_btls_key_get_bits)
+ICALL(BTLS_KEY_3, "mono_btls_key_get_bytes", mono_btls_key_get_bytes)
+ICALL(BTLS_KEY_4, "mono_btls_key_is_rsa", mono_btls_key_is_rsa)
+ICALL(BTLS_KEY_5, "mono_btls_key_up_ref", mono_btls_key_up_ref)
+
+ICALL_TYPE(BTLS_OBJECT, "Mono.Btls.MonoBtlsObject", BTLS_OBJECT_1)
+ICALL(BTLS_OBJECT_1, "mono_btls_free", mono_btls_free)
+
+ICALL_TYPE(BTLS_PKCS12, "Mono.Btls.MonoBtlsPkcs12", BTLS_PKCS12_1)
+ICALL(BTLS_PKCS12_1, "mono_btls_pkcs12_add_cert", mono_btls_pkcs12_add_cert)
+ICALL(BTLS_PKCS12_2, "mono_btls_pkcs12_free", mono_btls_pkcs12_free)
+ICALL(BTLS_PKCS12_3, "mono_btls_pkcs12_get_cert", mono_btls_pkcs12_get_cert)
+ICALL(BTLS_PKCS12_4, "mono_btls_pkcs12_get_certs", mono_btls_pkcs12_get_certs)
+ICALL(BTLS_PKCS12_5, "mono_btls_pkcs12_get_count", mono_btls_pkcs12_get_count)
+ICALL(BTLS_PKCS12_6, "mono_btls_pkcs12_get_private_key", mono_btls_pkcs12_get_private_key)
+ICALL(BTLS_PKCS12_7, "mono_btls_pkcs12_has_private_key", mono_btls_pkcs12_has_private_key)
+ICALL(BTLS_PKCS12_8, "mono_btls_pkcs12_import", mono_btls_pkcs12_import)
+ICALL(BTLS_PKCS12_9, "mono_btls_pkcs12_new", mono_btls_pkcs12_new)
+ICALL(BTLS_PKCS12_10, "mono_btls_pkcs12_up_ref", mono_btls_pkcs12_up_ref)
+
+ICALL_TYPE(BTLS_SSL, "Mono.Btls.MonoBtlsSsl", BTLS_SSL_1)
+ICALL(BTLS_SSL_1, "mono_btls_ssl_accept", mono_btls_ssl_accept)
+ICALL(BTLS_SSL_2, "mono_btls_ssl_add_chain_certificate", mono_btls_ssl_add_chain_certificate)
+ICALL(BTLS_SSL_3, "mono_btls_ssl_close", mono_btls_ssl_close)
+ICALL(BTLS_SSL_4, "mono_btls_ssl_connect", mono_btls_ssl_connect)
+ICALL(BTLS_SSL_5, "mono_btls_ssl_destroy", mono_btls_ssl_destroy)
+ICALL(BTLS_SSL_6, "mono_btls_ssl_get_cipher", mono_btls_ssl_get_cipher)
+ICALL(BTLS_SSL_7, "mono_btls_ssl_get_ciphers", mono_btls_ssl_get_ciphers)
+ICALL(BTLS_SSL_8, "mono_btls_ssl_get_error", mono_btls_ssl_get_error)
+ICALL(BTLS_SSL_9, "mono_btls_ssl_get_peer_certificate", mono_btls_ssl_get_peer_certificate)
+ICALL(BTLS_SSL_10, "mono_btls_ssl_get_version", mono_btls_ssl_get_version)
+ICALL(BTLS_SSL_11, "mono_btls_ssl_handshake", mono_btls_ssl_handshake)
+ICALL(BTLS_SSL_12, "mono_btls_ssl_new", mono_btls_ssl_new)
+ICALL(BTLS_SSL_13, "mono_btls_ssl_print_errors_cb", mono_btls_ssl_print_errors_cb)
+ICALL(BTLS_SSL_14, "mono_btls_ssl_read", mono_btls_ssl_read)
+ICALL(BTLS_SSL_15, "mono_btls_ssl_set_bio", mono_btls_ssl_set_bio)
+ICALL(BTLS_SSL_16, "mono_btls_ssl_set_cipher_list", mono_btls_ssl_set_cipher_list)
+ICALL(BTLS_SSL_17, "mono_btls_ssl_set_max_version", mono_btls_ssl_set_max_version)
+ICALL(BTLS_SSL_18, "mono_btls_ssl_set_min_version", mono_btls_ssl_set_min_version)
+ICALL(BTLS_SSL_19, "mono_btls_ssl_set_server_name", mono_btls_ssl_set_server_name)
+ICALL(BTLS_SSL_20, "mono_btls_ssl_set_verify_param", mono_btls_ssl_set_verify_param)
+ICALL(BTLS_SSL_21, "mono_btls_ssl_use_certificate", mono_btls_ssl_use_certificate)
+ICALL(BTLS_SSL_22, "mono_btls_ssl_use_private_key", mono_btls_ssl_use_private_key)
+ICALL(BTLS_SSL_23, "mono_btls_ssl_write", mono_btls_ssl_write)
+
+ICALL_TYPE(BTLS_SSL_CTX, "Mono.Btls.MonoBtlsSslCtx", BTLS_SSL_CTX_1)
+ICALL(BTLS_SSL_CTX_1, "mono_btls_ssl_ctx_debug_printf", mono_btls_ssl_ctx_debug_printf)
+ICALL(BTLS_SSL_CTX_2, "mono_btls_ssl_ctx_free", mono_btls_ssl_ctx_free)
+ICALL(BTLS_SSL_CTX_3, "mono_btls_ssl_ctx_get_ctx", mono_btls_ssl_ctx_get_ctx)
+ICALL(BTLS_SSL_CTX_4, "mono_btls_ssl_ctx_initialize", mono_btls_ssl_ctx_initialize)
+ICALL(BTLS_SSL_CTX_5, "mono_btls_ssl_ctx_is_cipher_supported", mono_btls_ssl_ctx_is_cipher_supported)
+ICALL(BTLS_SSL_CTX_6, "mono_btls_ssl_ctx_is_debug_enabled", mono_btls_ssl_ctx_is_debug_enabled)
+ICALL(BTLS_SSL_CTX_7, "mono_btls_ssl_ctx_new", mono_btls_ssl_ctx_new)
+ICALL(BTLS_SSL_CTX_8, "mono_btls_ssl_ctx_peek_store", mono_btls_ssl_ctx_peek_store)
+ICALL(BTLS_SSL_CTX_9, "mono_btls_ssl_ctx_set_cert_select_callback", mono_btls_ssl_ctx_set_cert_select_callback)
+ICALL(BTLS_SSL_CTX_10, "mono_btls_ssl_ctx_set_cert_verify_callback", mono_btls_ssl_ctx_set_cert_verify_callback)
+ICALL(BTLS_SSL_CTX_11, "mono_btls_ssl_ctx_set_ciphers", mono_btls_ssl_ctx_set_ciphers)
+ICALL(BTLS_SSL_CTX_12, "mono_btls_ssl_ctx_set_debug_bio", mono_btls_ssl_ctx_set_debug_bio)
+ICALL(BTLS_SSL_CTX_13, "mono_btls_ssl_ctx_set_max_version", mono_btls_ssl_ctx_set_max_version)
+ICALL(BTLS_SSL_CTX_14, "mono_btls_ssl_ctx_set_min_version", mono_btls_ssl_ctx_set_min_version)
+ICALL(BTLS_SSL_CTX_15, "mono_btls_ssl_ctx_set_verify_param", mono_btls_ssl_ctx_set_verify_param)
+ICALL(BTLS_SSL_CTX_16, "mono_btls_ssl_ctx_up_ref", mono_btls_ssl_ctx_up_ref)
+
+ICALL_TYPE(BTLS_X509, "Mono.Btls.MonoBtlsX509", BTLS_X509_1)
+ICALL(BTLS_X509_1, "mono_btls_x509_add_explicit_trust", mono_btls_x509_add_explicit_trust)
+ICALL(BTLS_X509_2, "mono_btls_x509_add_reject_object", mono_btls_x509_add_reject_object)
+ICALL(BTLS_X509_3, "mono_btls_x509_add_trust_object", mono_btls_x509_add_trust_object)
+ICALL(BTLS_X509_4, "mono_btls_x509_cmp", mono_btls_x509_cmp)
+ICALL(BTLS_X509_5, "mono_btls_x509_dup", mono_btls_x509_dup)
+ICALL(BTLS_X509_6, "mono_btls_x509_free", mono_btls_x509_free)
+ICALL(BTLS_X509_7, "mono_btls_x509_from_data", mono_btls_x509_from_data)
+ICALL(BTLS_X509_8, "mono_btls_x509_get_hash", mono_btls_x509_get_hash)
+ICALL(BTLS_X509_9, "mono_btls_x509_get_issuer_name", mono_btls_x509_get_issuer_name)
+ICALL(BTLS_X509_10, "mono_btls_x509_get_issuer_name_string", mono_btls_x509_get_issuer_name_string)
+ICALL(BTLS_X509_11, "mono_btls_x509_get_not_after", mono_btls_x509_get_not_after)
+ICALL(BTLS_X509_12, "mono_btls_x509_get_not_before", mono_btls_x509_get_not_before)
+ICALL(BTLS_X509_13, "mono_btls_x509_get_pubkey", mono_btls_x509_get_pubkey)
+ICALL(BTLS_X509_14, "mono_btls_x509_get_public_key", mono_btls_x509_get_public_key)
+ICALL(BTLS_X509_15, "mono_btls_x509_get_public_key_algorithm", mono_btls_x509_get_public_key_algorithm)
+ICALL(BTLS_X509_16, "mono_btls_x509_get_public_key_asn1", mono_btls_x509_get_public_key_asn1)
+ICALL(BTLS_X509_17, "mono_btls_x509_get_public_key_parameters", mono_btls_x509_get_public_key_parameters)
+ICALL(BTLS_X509_18, "mono_btls_x509_get_raw_data", mono_btls_x509_get_raw_data)
+ICALL(BTLS_X509_19, "mono_btls_x509_get_serial_number", mono_btls_x509_get_serial_number)
+ICALL(BTLS_X509_20, "mono_btls_x509_get_signature_algorithm", mono_btls_x509_get_signature_algorithm)
+ICALL(BTLS_X509_21, "mono_btls_x509_get_subject_key_identifier", mono_btls_x509_get_subject_key_identifier)
+ICALL(BTLS_X509_22, "mono_btls_x509_get_subject_name", mono_btls_x509_get_subject_name)
+ICALL(BTLS_X509_23, "mono_btls_x509_get_subject_name_string", mono_btls_x509_get_subject_name_string)
+ICALL(BTLS_X509_24, "mono_btls_x509_get_version", mono_btls_x509_get_version)
+ICALL(BTLS_X509_25, "mono_btls_x509_print", mono_btls_x509_print)
+ICALL(BTLS_X509_26, "mono_btls_x509_up_ref", mono_btls_x509_up_ref)
+
+ICALL_TYPE(BTLS_X509_CHAIN, "Mono.Btls.MonoBtlsX509Chain", BTLS_X509_CHAIN_1)
+ICALL(BTLS_X509_CHAIN_1, "mono_btls_x509_chain_add_cert", mono_btls_x509_chain_add_cert)
+ICALL(BTLS_X509_CHAIN_2, "mono_btls_x509_chain_free", mono_btls_x509_chain_free)
+ICALL(BTLS_X509_CHAIN_3, "mono_btls_x509_chain_from_certs", mono_btls_x509_chain_from_certs)
+ICALL(BTLS_X509_CHAIN_4, "mono_btls_x509_chain_get_cert", mono_btls_x509_chain_get_cert)
+ICALL(BTLS_X509_CHAIN_5, "mono_btls_x509_chain_get_count", mono_btls_x509_chain_get_count)
+ICALL(BTLS_X509_CHAIN_6, "mono_btls_x509_chain_new", mono_btls_x509_chain_new)
+ICALL(BTLS_X509_CHAIN_7, "mono_btls_x509_chain_peek_certs", mono_btls_x509_chain_peek_certs)
+ICALL(BTLS_X509_CHAIN_8, "mono_btls_x509_chain_up_ref", mono_btls_x509_chain_up_ref)
+
+ICALL_TYPE(BTLS_X509_CRL, "Mono.Btls.MonoBtlsX509Crl", BTLS_X509_CRL_1)
+ICALL(BTLS_X509_CRL_1, "mono_btls_x509_crl_free", mono_btls_x509_crl_free)
+ICALL(BTLS_X509_CRL_2, "mono_btls_x509_crl_from_data", mono_btls_x509_crl_from_data)
+ICALL(BTLS_X509_CRL_3, "mono_btls_x509_crl_get_by_cert", mono_btls_x509_crl_get_by_cert)
+ICALL(BTLS_X509_CRL_4, "mono_btls_x509_crl_get_by_serial", mono_btls_x509_crl_get_by_serial)
+ICALL(BTLS_X509_CRL_5, "mono_btls_x509_crl_get_issuer", mono_btls_x509_crl_get_issuer)
+ICALL(BTLS_X509_CRL_6, "mono_btls_x509_crl_get_last_update", mono_btls_x509_crl_get_last_update)
+ICALL(BTLS_X509_CRL_7, "mono_btls_x509_crl_get_next_update", mono_btls_x509_crl_get_next_update)
+ICALL(BTLS_X509_CRL_8, "mono_btls_x509_crl_get_revoked", mono_btls_x509_crl_get_revoked)
+ICALL(BTLS_X509_CRL_9, "mono_btls_x509_crl_get_revoked_count", mono_btls_x509_crl_get_revoked_count)
+ICALL(BTLS_X509_CRL_10, "mono_btls_x509_crl_get_version", mono_btls_x509_crl_get_version)
+ICALL(BTLS_X509_CRL_11, "mono_btls_x509_crl_ref", mono_btls_x509_crl_ref)
+
+ICALL_TYPE(BTLS_X509_LOOKUP, "Mono.Btls.MonoBtlsX509Lookup", BTLS_X509_LOOKUP_1)
+ICALL(BTLS_X509_LOOKUP_1, "mono_btls_x509_lookup_add_dir", mono_btls_x509_lookup_add_dir)
+ICALL(BTLS_X509_LOOKUP_2, "mono_btls_x509_lookup_add_mono", mono_btls_x509_lookup_add_mono)
+ICALL(BTLS_X509_LOOKUP_3, "mono_btls_x509_lookup_by_fingerprint", mono_btls_x509_lookup_by_fingerprint)
+ICALL(BTLS_X509_LOOKUP_4, "mono_btls_x509_lookup_by_subject", mono_btls_x509_lookup_by_subject)
+ICALL(BTLS_X509_LOOKUP_5, "mono_btls_x509_lookup_free", mono_btls_x509_lookup_free)
+ICALL(BTLS_X509_LOOKUP_6, "mono_btls_x509_lookup_init", mono_btls_x509_lookup_init)
+ICALL(BTLS_X509_LOOKUP_7, "mono_btls_x509_lookup_load_file", mono_btls_x509_lookup_load_file)
+ICALL(BTLS_X509_LOOKUP_8, "mono_btls_x509_lookup_mono_init", mono_btls_x509_lookup_mono_init)
+ICALL(BTLS_X509_LOOKUP_9, "mono_btls_x509_lookup_new", mono_btls_x509_lookup_new)
+ICALL(BTLS_X509_LOOKUP_10, "mono_btls_x509_lookup_peek_lookup", mono_btls_x509_lookup_peek_lookup)
+ICALL(BTLS_X509_LOOKUP_11, "mono_btls_x509_lookup_shutdown", mono_btls_x509_lookup_shutdown)
+ICALL(BTLS_X509_LOOKUP_12, "mono_btls_x509_lookup_up_ref", mono_btls_x509_lookup_up_ref)
+
+ICALL_TYPE(BTLS_X509_LOOKUP_MONO, "Mono.Btls.MonoBtlsX509LookupMono", BTLS_X509_LOOKUP_MONO_1)
+ICALL(BTLS_X509_LOOKUP_MONO_1, "mono_btls_x509_lookup_mono_free", mono_btls_x509_lookup_mono_free)
+ICALL(BTLS_X509_LOOKUP_MONO_2, "mono_btls_x509_lookup_mono_init", mono_btls_x509_lookup_mono_init)
+ICALL(BTLS_X509_LOOKUP_MONO_3, "mono_btls_x509_lookup_mono_new", mono_btls_x509_lookup_mono_new)
+
+ICALL_TYPE(BTLS_X509_NAME, "Mono.Btls.MonoBtlsX509Name", BTLS_X509_NAME_1)
+ICALL(BTLS_X509_NAME_1, "mono_btls_x509_name_copy", mono_btls_x509_name_copy)
+ICALL(BTLS_X509_NAME_2, "mono_btls_x509_name_free", mono_btls_x509_name_free)
+ICALL(BTLS_X509_NAME_3, "mono_btls_x509_name_from_data", mono_btls_x509_name_from_data)
+ICALL(BTLS_X509_NAME_4, "mono_btls_x509_name_from_name", mono_btls_x509_name_from_name)
+ICALL(BTLS_X509_NAME_5, "mono_btls_x509_name_get_entry_count", mono_btls_x509_name_get_entry_count)
+ICALL(BTLS_X509_NAME_6, "mono_btls_x509_name_get_entry_oid", mono_btls_x509_name_get_entry_oid)
+ICALL(BTLS_X509_NAME_7, "mono_btls_x509_name_get_entry_oid_data", mono_btls_x509_name_get_entry_oid_data)
+ICALL(BTLS_X509_NAME_8, "mono_btls_x509_name_get_entry_type", mono_btls_x509_name_get_entry_type)
+ICALL(BTLS_X509_NAME_9, "mono_btls_x509_name_get_entry_value", mono_btls_x509_name_get_entry_value)
+ICALL(BTLS_X509_NAME_10, "mono_btls_x509_name_get_raw_data", mono_btls_x509_name_get_raw_data)
+ICALL(BTLS_X509_NAME_11, "mono_btls_x509_name_hash", mono_btls_x509_name_hash)
+ICALL(BTLS_X509_NAME_12, "mono_btls_x509_name_hash_old", mono_btls_x509_name_hash_old)
+ICALL(BTLS_X509_NAME_13, "mono_btls_x509_name_peek_name", mono_btls_x509_name_peek_name)
+ICALL(BTLS_X509_NAME_14, "mono_btls_x509_name_print_bio", mono_btls_x509_name_print_bio)
+ICALL(BTLS_X509_NAME_15, "mono_btls_x509_name_print_string", mono_btls_x509_name_print_string)
+
+ICALL_TYPE(BTLS_X509_REVOKED, "Mono.Btls.MonoBtlsX509Revoked", BTLS_X509_REVOKED_1)
+ICALL(BTLS_X509_REVOKED_1, "mono_btls_x509_revoked_free", mono_btls_x509_revoked_free)
+ICALL(BTLS_X509_REVOKED_2, "mono_btls_x509_revoked_get_reason", mono_btls_x509_revoked_get_reason)
+ICALL(BTLS_X509_REVOKED_2a, "mono_btls_x509_revoked_get_revocation_date", mono_btls_x509_revoked_get_revocation_date)
+ICALL(BTLS_X509_REVOKED_3, "mono_btls_x509_revoked_get_sequence", mono_btls_x509_revoked_get_sequence)
+ICALL(BTLS_X509_REVOKED_4, "mono_btls_x509_revoked_get_serial_number", mono_btls_x509_revoked_get_serial_number)
+ICALL(BTLS_X509_REVOKED_5, "mono_btls_x509_revoked_new", mono_btls_x509_revoked_new)
+
+ICALL_TYPE(BTLS_X509_STORE, "Mono.Btls.MonoBtlsX509Store", BTLS_X509_STORE_1)
+ICALL(BTLS_X509_STORE_1, "mono_btls_x509_store_add_cert", mono_btls_x509_store_add_cert)
+ICALL(BTLS_X509_STORE_2, "mono_btls_x509_store_free", mono_btls_x509_store_free)
+ICALL(BTLS_X509_STORE_3, "mono_btls_x509_store_from_ctx", mono_btls_x509_store_from_ctx)
+ICALL(BTLS_X509_STORE_4, "mono_btls_x509_store_from_ssl_ctx", mono_btls_x509_store_from_ssl_ctx)
+ICALL(BTLS_X509_STORE_5, "mono_btls_x509_store_get_count", mono_btls_x509_store_get_count)
+ICALL(BTLS_X509_STORE_6, "mono_btls_x509_store_load_locations", mono_btls_x509_store_load_locations)
+ICALL(BTLS_X509_STORE_7, "mono_btls_x509_store_new", mono_btls_x509_store_new)
+ICALL(BTLS_X509_STORE_8, "mono_btls_x509_store_peek_store", mono_btls_x509_store_peek_store)
+ICALL(BTLS_X509_STORE_9, "mono_btls_x509_store_set_default_paths", mono_btls_x509_store_set_default_paths)
+ICALL(BTLS_X509_STORE_10, "mono_btls_x509_store_up_ref", mono_btls_x509_store_up_ref)
+
+ICALL_TYPE(BTLS_X509_STORE_CTX, "Mono.Btls.MonoBtlsX509StoreCtx", BTLS_X509_STORE_CTX_1)
+ICALL(BTLS_X509_STORE_CTX_1, "mono_btls_x509_store_ctx_free", mono_btls_x509_store_ctx_free)
+ICALL(BTLS_X509_STORE_CTX_2, "mono_btls_x509_store_ctx_from_ptr", mono_btls_x509_store_ctx_from_ptr)
+ICALL(BTLS_X509_STORE_CTX_3, "mono_btls_x509_store_ctx_get_by_subject", mono_btls_x509_store_ctx_get_by_subject)
+ICALL(BTLS_X509_STORE_CTX_4, "mono_btls_x509_store_ctx_get_chain", mono_btls_x509_store_ctx_get_chain)
+ICALL(BTLS_X509_STORE_CTX_5, "mono_btls_x509_store_ctx_get_current_cert", mono_btls_x509_store_ctx_get_current_cert)
+ICALL(BTLS_X509_STORE_CTX_6, "mono_btls_x509_store_ctx_get_current_issuer", mono_btls_x509_store_ctx_get_current_issuer)
+ICALL(BTLS_X509_STORE_CTX_7, "mono_btls_x509_store_ctx_get_error", mono_btls_x509_store_ctx_get_error)
+ICALL(BTLS_X509_STORE_CTX_8, "mono_btls_x509_store_ctx_get_error_depth", mono_btls_x509_store_ctx_get_error_depth)
+ICALL(BTLS_X509_STORE_CTX_9, "mono_btls_x509_store_ctx_get_untrusted", mono_btls_x509_store_ctx_get_untrusted)
+ICALL(BTLS_X509_STORE_CTX_10, "mono_btls_x509_store_ctx_get_verify_param", mono_btls_x509_store_ctx_get_verify_param)
+ICALL(BTLS_X509_STORE_CTX_11, "mono_btls_x509_store_ctx_init", mono_btls_x509_store_ctx_init)
+ICALL(BTLS_X509_STORE_CTX_12, "mono_btls_x509_store_ctx_new", mono_btls_x509_store_ctx_new)
+ICALL(BTLS_X509_STORE_CTX_13, "mono_btls_x509_store_ctx_set_param", mono_btls_x509_store_ctx_set_param)
+ICALL(BTLS_X509_STORE_CTX_15, "mono_btls_x509_store_ctx_up_ref", mono_btls_x509_store_ctx_up_ref)
+ICALL(BTLS_X509_STORE_CTX_16, "mono_btls_x509_store_ctx_verify_cert", mono_btls_x509_store_ctx_verify_cert)
+
+ICALL_TYPE(BTLS_X509_VERIFY_PARAM, "Mono.Btls.MonoBtlsX509VerifyParam", BTLS_X509_VERIFY_PARAM_1)
+ICALL(BTLS_X509_VERIFY_PARAM_1, "mono_btls_x509_verify_param_add_host", mono_btls_x509_verify_param_add_host)
+ICALL(BTLS_X509_VERIFY_PARAM_2, "mono_btls_x509_verify_param_can_modify", mono_btls_x509_verify_param_can_modify)
+ICALL(BTLS_X509_VERIFY_PARAM_3, "mono_btls_x509_verify_param_copy", mono_btls_x509_verify_param_copy)
+ICALL(BTLS_X509_VERIFY_PARAM_4, "mono_btls_x509_verify_param_free", mono_btls_x509_verify_param_free)
+ICALL(BTLS_X509_VERIFY_PARAM_5, "mono_btls_x509_verify_param_from_store_ctx", mono_btls_x509_verify_param_from_store_ctx)
+ICALL(BTLS_X509_VERIFY_PARAM_6, "mono_btls_x509_verify_param_get_depth", mono_btls_x509_verify_param_get_depth)
+ICALL(BTLS_X509_VERIFY_PARAM_7, "mono_btls_x509_verify_param_get_flags", mono_btls_x509_verify_param_get_flags)
+ICALL(BTLS_X509_VERIFY_PARAM_8, "mono_btls_x509_verify_param_get_mono_flags", mono_btls_x509_verify_param_get_mono_flags)
+ICALL(BTLS_X509_VERIFY_PARAM_9, "mono_btls_x509_verify_param_get_peername", mono_btls_x509_verify_param_get_peername)
+ICALL(BTLS_X509_VERIFY_PARAM_10, "mono_btls_x509_verify_param_lookup", mono_btls_x509_verify_param_lookup)
+ICALL(BTLS_X509_VERIFY_PARAM_11, "mono_btls_x509_verify_param_new", mono_btls_x509_verify_param_new)
+ICALL(BTLS_X509_VERIFY_PARAM_12, "mono_btls_x509_verify_param_peek_param", mono_btls_x509_verify_param_peek_param)
+ICALL(BTLS_X509_VERIFY_PARAM_13, "mono_btls_x509_verify_param_set_depth", mono_btls_x509_verify_param_set_depth)
+ICALL(BTLS_X509_VERIFY_PARAM_14, "mono_btls_x509_verify_param_set_flags", mono_btls_x509_verify_param_set_flags)
+ICALL(BTLS_X509_VERIFY_PARAM_15, "mono_btls_x509_verify_param_set_host", mono_btls_x509_verify_param_set_host)
+ICALL(BTLS_X509_VERIFY_PARAM_16, "mono_btls_x509_verify_param_set_mono_flags", mono_btls_x509_verify_param_set_mono_flags)
+ICALL(BTLS_X509_VERIFY_PARAM_17, "mono_btls_x509_verify_param_set_name", mono_btls_x509_verify_param_set_name)
+ICALL(BTLS_X509_VERIFY_PARAM_18, "mono_btls_x509_verify_param_set_purpose", mono_btls_x509_verify_param_set_purpose)
+ICALL(BTLS_X509_VERIFY_PARAM_19, "mono_btls_x509_verify_param_set_time", mono_btls_x509_verify_param_set_time)
+#endif
+
 #ifndef DISABLE_COM
 ICALL_TYPE(COMPROX, "Mono.Interop.ComInteropProxy", COMPROX_1)
 ICALL(COMPROX_1, "AddProxy", ves_icall_Mono_Interop_ComInteropProxy_AddProxy)
 ICALL(COMPROX_2, "FindProxy", ves_icall_Mono_Interop_ComInteropProxy_FindProxy)
 #endif
 
+ICALL_TYPE(TLS_PROVIDER_FACTORY, "Mono.Net.Security.MonoTlsProviderFactory", TLS_PROVIDER_FACTORY_1)
+ICALL(TLS_PROVIDER_FACTORY_1, "IsBtlsSupported", ves_icall_Mono_TlsProviderFactory_IsBtlsSupported)
+
 ICALL_TYPE(RUNTIME, "Mono.Runtime", RUNTIME_1)
 ICALL(RUNTIME_1, "GetDisplayName", ves_icall_Mono_Runtime_GetDisplayName)
 ICALL(RUNTIME_12, "GetNativeStackTrace", ves_icall_Mono_Runtime_GetNativeStackTrace)
@@ -171,13 +409,13 @@ ICALL_TYPE (COMPO_W, "System.ComponentModel.Win32Exception", COMPO_W_1)
 ICALL (COMPO_W_1, "W32ErrorMessage", ves_icall_System_ComponentModel_Win32Exception_W32ErrorMessage)
 
 ICALL_TYPE(DEFAULTC, "System.Configuration.DefaultConfig", DEFAULTC_1)
-HANDLES(ICALL(DEFAULTC_1, "get_bundled_machine_config", get_bundled_machine_config))
+HANDLES(ICALL(DEFAULTC_1, "get_bundled_machine_config", ves_icall_System_Configuration_DefaultConfig_get_bundled_machine_config))
 ICALL(DEFAULTC_2, "get_machine_config_path", ves_icall_System_Configuration_DefaultConfig_get_machine_config_path)
 
 /* Note that the below icall shares the same function as DefaultConfig uses */
 ICALL_TYPE(INTCFGHOST, "System.Configuration.InternalConfigurationHost", INTCFGHOST_1)
 ICALL(INTCFGHOST_1, "get_bundled_app_config", get_bundled_app_config)
-ICALL(INTCFGHOST_2, "get_bundled_machine_config", get_bundled_machine_config)
+HANDLES(ICALL(INTCFGHOST_2, "get_bundled_machine_config", ves_icall_System_Configuration_InternalConfigurationHost_get_bundled_machine_config))
 
 ICALL_TYPE(CONSOLE, "System.ConsoleDriver", CONSOLE_1)
 ICALL(CONSOLE_1, "InternalKeyAvailable", ves_icall_System_ConsoleDriver_InternalKeyAvailable )
@@ -280,6 +518,7 @@ ICALL(ENV_13, "get_Platform", ves_icall_System_Environment_get_Platform)
 ICALL(ENV_14, "get_ProcessorCount", mono_cpu_count)
 ICALL(ENV_15, "get_TickCount", ves_icall_System_Environment_get_TickCount)
 ICALL(ENV_16, "get_UserName", ves_icall_System_Environment_get_UserName)
+HANDLES(ICALL(ENV_16b, "get_bundled_machine_config", get_bundled_machine_config))
 ICALL(ENV_16m, "internalBroadcastSettingChange", ves_icall_System_Environment_BroadcastSettingChange)
 HANDLES(ICALL(ENV_17, "internalGetEnvironmentVariable_native", ves_icall_System_Environment_GetEnvironmentVariable_native))
 HANDLES(ICALL(ENV_18, "internalGetGacPath", ves_icall_System_Environment_GetGacPath))
@@ -287,16 +526,16 @@ HANDLES(ICALL(ENV_19, "internalGetHome", ves_icall_System_Environment_InternalGe
 ICALL(ENV_20, "set_ExitCode", mono_environment_exitcode_set)
 
 ICALL_TYPE(GC, "System.GC", GC_0)
-ICALL(GC_0, "CollectionCount", mono_gc_collection_count)
+ICALL(GC_0, "GetCollectionCount", mono_gc_collection_count)
 ICALL(GC_0a, "GetGeneration", mono_gc_get_generation)
+ICALL(GC_0b, "GetMaxGeneration", mono_gc_max_generation)
 ICALL(GC_1, "GetTotalMemory", ves_icall_System_GC_GetTotalMemory)
 ICALL(GC_2, "InternalCollect", ves_icall_System_GC_InternalCollect)
 ICALL(GC_3, "KeepAlive", ves_icall_System_GC_KeepAlive)
-ICALL(GC_4, "ReRegisterForFinalize", ves_icall_System_GC_ReRegisterForFinalize)
 ICALL(GC_4a, "RecordPressure", mono_gc_add_memory_pressure)
-ICALL(GC_5, "SuppressFinalize", ves_icall_System_GC_SuppressFinalize)
 ICALL(GC_6, "WaitForPendingFinalizers", ves_icall_System_GC_WaitForPendingFinalizers)
-ICALL(GC_7, "get_MaxGeneration", mono_gc_max_generation)
+ICALL(GC_6b, "_ReRegisterForFinalize", ves_icall_System_GC_ReRegisterForFinalize)
+ICALL(GC_7, "_SuppressFinalize", ves_icall_System_GC_SuppressFinalize)
 ICALL(GC_9, "get_ephemeron_tombstone", ves_icall_System_GC_get_ephemeron_tombstone)
 ICALL(GC_8, "register_ephemeron_array", ves_icall_System_GC_register_ephemeron_array)
 
@@ -439,8 +678,8 @@ ICALL(MCATTR_3, "IsDefinedInternal", custom_attrs_defined_internal)
 
 #ifndef DISABLE_SOCKETS
 ICALL_TYPE(NDNS, "System.Net.Dns", NDNS_1)
-ICALL(NDNS_1, "GetHostByAddr_internal(string,string&,string[]&,string[]&)", ves_icall_System_Net_Dns_GetHostByAddr_internal)
-ICALL(NDNS_2, "GetHostByName_internal(string,string&,string[]&,string[]&)", ves_icall_System_Net_Dns_GetHostByName_internal)
+ICALL(NDNS_1, "GetHostByAddr_internal(string,string&,string[]&,string[]&,int)", ves_icall_System_Net_Dns_GetHostByAddr_internal)
+ICALL(NDNS_2, "GetHostByName_internal(string,string&,string[]&,string[]&,int)", ves_icall_System_Net_Dns_GetHostByName_internal)
 ICALL(NDNS_3, "GetHostName_internal(string&)", ves_icall_System_Net_Dns_GetHostName_internal)
 
 #if defined(PLATFORM_MACOSX) || defined(PLATFORM_BSD)
@@ -454,7 +693,7 @@ ICALL(SOCK_2, "Available_internal(intptr,int&)", ves_icall_System_Net_Sockets_So
 ICALL(SOCK_3, "Bind_internal(intptr,System.Net.SocketAddress,int&)", ves_icall_System_Net_Sockets_Socket_Bind_internal)
 ICALL(SOCK_4, "Blocking_internal(intptr,bool,int&)", ves_icall_System_Net_Sockets_Socket_Blocking_internal)
 ICALL(SOCK_5, "Close_internal(intptr,int&)", ves_icall_System_Net_Sockets_Socket_Close_internal)
-ICALL(SOCK_6, "Connect_internal(intptr,System.Net.SocketAddress,int&)", ves_icall_System_Net_Sockets_Socket_Connect_internal)
+ICALL(SOCK_6, "Connect_internal(intptr,System.Net.SocketAddress,int&,bool)", ves_icall_System_Net_Sockets_Socket_Connect_internal)
 ICALL (SOCK_6a, "Disconnect_internal(intptr,bool,int&)", ves_icall_System_Net_Sockets_Socket_Disconnect_internal)
 ICALL(SOCK_7, "GetSocketOption_arr_internal(intptr,System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,byte[]&,int&)", ves_icall_System_Net_Sockets_Socket_GetSocketOption_arr_internal)
 ICALL(SOCK_8, "GetSocketOption_obj_internal(intptr,System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,object&,int&)", ves_icall_System_Net_Sockets_Socket_GetSocketOption_obj_internal)
@@ -462,15 +701,15 @@ ICALL(SOCK_21, "IOControl_internal(intptr,int,byte[],byte[],int&)", ves_icall_Sy
 ICALL(SOCK_9, "Listen_internal(intptr,int,int&)", ves_icall_System_Net_Sockets_Socket_Listen_internal)
 ICALL(SOCK_10, "LocalEndPoint_internal(intptr,int,int&)", ves_icall_System_Net_Sockets_Socket_LocalEndPoint_internal)
 ICALL(SOCK_11, "Poll_internal", ves_icall_System_Net_Sockets_Socket_Poll_internal)
-ICALL(SOCK_13, "ReceiveFrom_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,System.Net.SocketAddress&,int&)", ves_icall_System_Net_Sockets_Socket_ReceiveFrom_internal)
-ICALL(SOCK_11a, "Receive_internal(intptr,System.Net.Sockets.Socket/WSABUF[],System.Net.Sockets.SocketFlags,int&)", ves_icall_System_Net_Sockets_Socket_Receive_array_internal)
-ICALL(SOCK_12, "Receive_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,int&)", ves_icall_System_Net_Sockets_Socket_Receive_internal)
+ICALL(SOCK_13, "ReceiveFrom_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,System.Net.SocketAddress&,int&,bool)", ves_icall_System_Net_Sockets_Socket_ReceiveFrom_internal)
+ICALL(SOCK_11a, "Receive_internal(intptr,System.Net.Sockets.Socket/WSABUF[],System.Net.Sockets.SocketFlags,int&,bool)", ves_icall_System_Net_Sockets_Socket_Receive_array_internal)
+ICALL(SOCK_12, "Receive_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,int&,bool)", ves_icall_System_Net_Sockets_Socket_Receive_internal)
 ICALL(SOCK_14, "RemoteEndPoint_internal(intptr,int,int&)", ves_icall_System_Net_Sockets_Socket_RemoteEndPoint_internal)
 ICALL(SOCK_15, "Select_internal(System.Net.Sockets.Socket[]&,int,int&)", ves_icall_System_Net_Sockets_Socket_Select_internal)
-ICALL(SOCK_15a, "SendFile_internal(intptr,string,byte[],byte[],System.Net.Sockets.TransmitFileOptions)", ves_icall_System_Net_Sockets_Socket_SendFile_internal)
-ICALL(SOCK_16, "SendTo_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,System.Net.SocketAddress,int&)", ves_icall_System_Net_Sockets_Socket_SendTo_internal)
-ICALL(SOCK_16a, "Send_internal(intptr,System.Net.Sockets.Socket/WSABUF[],System.Net.Sockets.SocketFlags,int&)", ves_icall_System_Net_Sockets_Socket_Send_array_internal)
-ICALL(SOCK_17, "Send_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,int&)", ves_icall_System_Net_Sockets_Socket_Send_internal)
+ICALL(SOCK_15a, "SendFile_internal(intptr,string,byte[],byte[],System.Net.Sockets.TransmitFileOptions,int&,bool)", ves_icall_System_Net_Sockets_Socket_SendFile_internal)
+ICALL(SOCK_16, "SendTo_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,System.Net.SocketAddress,int&,bool)", ves_icall_System_Net_Sockets_Socket_SendTo_internal)
+ICALL(SOCK_16a, "Send_internal(intptr,System.Net.Sockets.Socket/WSABUF[],System.Net.Sockets.SocketFlags,int&,bool)", ves_icall_System_Net_Sockets_Socket_Send_array_internal)
+ICALL(SOCK_17, "Send_internal(intptr,byte[],int,int,System.Net.Sockets.SocketFlags,int&,bool)", ves_icall_System_Net_Sockets_Socket_Send_internal)
 ICALL(SOCK_18, "SetSocketOption_internal(intptr,System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,object,byte[],int,int&)", ves_icall_System_Net_Sockets_Socket_SetSocketOption_internal)
 ICALL(SOCK_19, "Shutdown_internal(intptr,System.Net.Sockets.SocketShutdown,int&)", ves_icall_System_Net_Sockets_Socket_Shutdown_internal)
 ICALL(SOCK_20, "Socket_internal(System.Net.Sockets.AddressFamily,System.Net.Sockets.SocketType,System.Net.Sockets.ProtocolType,int&)", ves_icall_System_Net_Sockets_Socket_Socket_internal)
@@ -544,19 +783,12 @@ ICALL(DYNM_1, "create_dynamic_method", ves_icall_DynamicMethod_create_dynamic_me
 ICALL_TYPE(ENUMB, "System.Reflection.Emit.EnumBuilder", ENUMB_1)
 ICALL(ENUMB_1, "setup_enum_type", ves_icall_EnumBuilder_setup_enum_type)
 
-ICALL_TYPE(GPARB, "System.Reflection.Emit.GenericTypeParameterBuilder", GPARB_1)
-ICALL(GPARB_1, "initialize", ves_icall_GenericTypeParameterBuilder_initialize_generic_parameter)
-
-ICALL_TYPE(METHODB, "System.Reflection.Emit.MethodBuilder", METHODB_1)
-ICALL(METHODB_1, "MakeGenericMethod", ves_icall_MethodBuilder_MakeGenericMethod)
-
 ICALL_TYPE(MODULEB, "System.Reflection.Emit.ModuleBuilder", MODULEB_10)
 ICALL(MODULEB_10, "GetRegisteredToken", ves_icall_ModuleBuilder_GetRegisteredToken)
 ICALL(MODULEB_8, "RegisterToken", ves_icall_ModuleBuilder_RegisterToken)
 ICALL(MODULEB_1, "WriteToFile", ves_icall_ModuleBuilder_WriteToFile)
 ICALL(MODULEB_2, "basic_init", ves_icall_ModuleBuilder_basic_init)
 ICALL(MODULEB_3, "build_metadata", ves_icall_ModuleBuilder_build_metadata)
-ICALL(MODULEB_4, "create_modified_type", ves_icall_ModuleBuilder_create_modified_type)
 ICALL(MODULEB_5, "getMethodToken", ves_icall_ModuleBuilder_getMethodToken)
 ICALL(MODULEB_6, "getToken", ves_icall_ModuleBuilder_getToken)
 ICALL(MODULEB_7, "getUSIndex", ves_icall_ModuleBuilder_getUSIndex)
@@ -566,17 +798,8 @@ ICALL_TYPE(SIGH, "System.Reflection.Emit.SignatureHelper", SIGH_1)
 ICALL(SIGH_1, "get_signature_field", ves_icall_SignatureHelper_get_signature_field)
 ICALL(SIGH_2, "get_signature_local", ves_icall_SignatureHelper_get_signature_local)
 
-#ifndef DISABLE_REFLECTION_EMIT
-ICALL_TYPE(SYMBOLTYPE, "System.Reflection.Emit.SymbolType", SYMBOLTYPE_1)
-ICALL(SYMBOLTYPE_1, "create_unmanaged_type", ves_icall_SymbolType_create_unmanaged_type)
-#endif
-
 ICALL_TYPE(TYPEB, "System.Reflection.Emit.TypeBuilder", TYPEB_1)
-ICALL(TYPEB_1, "create_generic_class", ves_icall_TypeBuilder_create_generic_class)
-ICALL(TYPEB_3, "create_runtime_class", ves_icall_TypeBuilder_create_runtime_class)
-ICALL(TYPEB_4, "get_IsGenericParameter", ves_icall_TypeBuilder_get_IsGenericParameter)
-ICALL(TYPEB_5, "get_event_info", ves_icall_TypeBuilder_get_event_info)
-ICALL(TYPEB_7, "setup_internal_class", ves_icall_TypeBuilder_setup_internal_class)
+ICALL(TYPEB_1, "create_runtime_class", ves_icall_TypeBuilder_create_runtime_class)
 
 ICALL_TYPE(EVENTI, "System.Reflection.EventInfo", EVENTI_1)
 ICALL(EVENTI_1, "internal_from_handle_type", ves_icall_System_Reflection_EventInfo_internal_from_handle_type)
@@ -627,10 +850,6 @@ ICALL(MFIELD_6, "ResolveType", ves_icall_MonoField_ResolveType)
 ICALL(MFIELD_4, "SetValueInternal", ves_icall_MonoField_SetValueInternal)
 ICALL(MFIELD_7, "get_core_clr_security_level", ves_icall_MonoField_get_core_clr_security_level)
 
-ICALL_TYPE(MGENCL, "System.Reflection.MonoGenericClass", MGENCL_5)
-ICALL(MGENCL_5, "initialize", mono_reflection_generic_class_initialize)
-ICALL(MGENCL_6, "register_with_runtime", mono_reflection_register_with_runtime)
-
 ICALL_TYPE(MMETH, "System.Reflection.MonoMethod", MMETH_2)
 ICALL(MMETH_2, "GetGenericArguments", ves_icall_MonoMethod_GetGenericArguments)
 ICALL(MMETH_3, "GetGenericMethodDefinition_impl", ves_icall_MonoMethod_GetGenericMethodDefinition)
diff --git a/mono/metadata/icall-internals.h b/mono/metadata/icall-internals.h
new file mode 100644 (file)
index 0000000..e2ec776
--- /dev/null
@@ -0,0 +1,82 @@
+/*
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#ifndef __MONO_METADATA_ICALL_INTERNALS_H__
+#define __MONO_METADATA_ICALL_INTERNALS_H__
+
+#include <config.h>
+#include <glib.h>
+#include <mono/metadata/object-internals.h>
+
+// On Windows platform implementation of bellow methods are hosted in separate source file
+// icall-windows.c or icall-windows-*.c. On other platforms the implementation is still keept
+// in icall.c still declared as static and in some places even inlined.
+#ifdef HOST_WIN32
+void
+mono_icall_make_platform_path (gchar *path);
+
+const gchar *
+mono_icall_get_file_path_prefix (const gchar *path);
+
+gpointer
+mono_icall_module_get_hinstance (MonoReflectionModule *module);
+
+MonoString *
+mono_icall_get_machine_name (void);
+
+int
+mono_icall_get_platform (void);
+
+MonoString *
+mono_icall_get_new_line (void);
+
+MonoBoolean
+mono_icall_is_64bit_os (void);
+
+MonoArray *
+mono_icall_get_environment_variable_names (void);
+
+void
+mono_icall_set_environment_variable (MonoString *name, MonoString *value);
+
+MonoString *
+mono_icall_get_windows_folder_path (int folder);
+
+void
+mono_icall_broadcast_setting_change (void);
+
+void
+mono_icall_write_windows_debug_string (MonoString *message);
+
+MonoBoolean
+mono_icall_close_process (gpointer handle);
+
+gint32
+mono_icall_wait_for_input_idle (gpointer handle, gint32 milliseconds);
+#endif  /* HOST_WIN32 */
+
+// On platforms not using classic WIN API support the  implementation of bellow methods are hosted in separate source file
+// icall-windows-*.c. On platforms using classic WIN API the implementation is still keept in icall.c and still declared
+// static and in some places even inlined.
+#if !G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+MonoArray *
+mono_icall_get_logical_drives (void);
+
+guint32
+mono_icall_drive_info_get_drive_type (MonoString *root_path_name);
+
+MonoBoolean
+mono_icall_get_process_working_set_size (gpointer handle, gsize *min, gsize *max);
+
+MonoBoolean
+mono_icall_set_process_working_set_size (gpointer handle, gsize min, gsize max);
+
+gint32
+mono_icall_get_priority_class (gpointer handle);
+
+MonoBoolean
+mono_icall_set_priority_class (gpointer handle, gint32 priorityClass);
+#endif  /* !G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+#endif /* __MONO_METADATA_ICALL_INTERNALS_H__ */
diff --git a/mono/metadata/icall-windows-internals.h b/mono/metadata/icall-windows-internals.h
new file mode 100644 (file)
index 0000000..0093767
--- /dev/null
@@ -0,0 +1,18 @@
+/*
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#ifndef __MONO_METADATA_ICALL_WINDOWS_INTERNALS_H__
+#define __MONO_METADATA_ICALL_WINDOWS_INTERNALS_H__
+
+#include <config.h>
+#include <glib.h>
+
+#ifdef HOST_WIN32
+#include "mono/metadata/icall-internals.h"
+#include "mono/metadata/object.h"
+#include "mono/metadata/object-internals.h"
+#include "mono/metadata/class.h"
+#include "mono/metadata/class-internals.h"
+#endif /* HOST_WIN32 */
+#endif /* __MONO_METADATA_ICALL_WINDOWS_INTERNALS_H__ */
diff --git a/mono/metadata/icall-windows-uwp.c b/mono/metadata/icall-windows-uwp.c
new file mode 100644 (file)
index 0000000..f273198
--- /dev/null
@@ -0,0 +1,158 @@
+/*
+ * icall-windows-uwp.c: UWP icall support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+
+#if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
+#include <Windows.h>
+#include "mono/metadata/icall-windows-internals.h"
+
+MonoString *
+mono_icall_get_machine_name (void)
+{
+       g_unsupported_api ("GetComputerName");
+       return mono_string_new (mono_domain_get (), "mono");
+}
+
+MonoString *
+mono_icall_get_windows_folder_path (int folder)
+{
+       g_unsupported_api ("SHGetFolderPath");
+       return mono_string_new (mono_domain_get (), "");
+}
+
+MonoArray *
+mono_icall_get_logical_drives (void)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("GetLogicalDriveStrings");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "GetLogicalDriveStrings");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return NULL;
+}
+
+void
+mono_icall_broadcast_setting_change (void)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("SendMessageTimeout");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "SendMessageTimeout");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return;
+}
+
+guint32
+mono_icall_drive_info_get_drive_type (MonoString *root_path_name)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("GetDriveType");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "GetDriveType");
+       mono_error_set_pending_exception (&mono_error);
+
+       return DRIVE_UNKNOWN;
+}
+
+gint32
+mono_icall_wait_for_input_idle (gpointer handle, gint32 milliseconds)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("WaitForInputIdle");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "WaitForInputIdle");
+       mono_error_set_pending_exception (&mono_error);
+
+       return WAIT_TIMEOUT;
+}
+
+MonoBoolean
+mono_icall_get_process_working_set_size (gpointer handle, gsize *min, gsize *max)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("GetProcessWorkingSetSize");
+
+       mono_error_set_not_supported(&mono_error, G_UNSUPPORTED_API, "GetProcessWorkingSetSize");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+MonoBoolean
+mono_icall_set_process_working_set_size (gpointer handle, gsize min, gsize max)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("SetProcessWorkingSetSize");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "SetProcessWorkingSetSize");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+gint32
+mono_icall_get_priority_class (gpointer handle)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("GetPriorityClass");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "GetPriorityClass");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+MonoBoolean
+mono_icall_set_priority_class (gpointer handle, gint32 priorityClass)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("SetPriorityClass");
+
+       mono_error_set_not_supported(&mono_error, G_UNSUPPORTED_API, "SetPriorityClass");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+#else /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_icall_windows_uwp_quiet_lnk4221(void) {}
+#endif
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
diff --git a/mono/metadata/icall-windows.c b/mono/metadata/icall-windows.c
new file mode 100644 (file)
index 0000000..6c80211
--- /dev/null
@@ -0,0 +1,221 @@
+/*
+ * icall-windows.c: Windows icall support.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#include <config.h>
+#include <glib.h>
+
+#if defined(HOST_WIN32)
+#include <WinSock2.h>
+#include <Windows.h>
+#include "mono/metadata/icall-windows-internals.h"
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+#include <shlobj.h>
+#endif
+
+void
+mono_icall_make_platform_path (gchar *path)
+{
+       for (size_t i = strlen (path); i > 0; i--)
+               if (path [i-1] == '\\')
+                       path [i-1] = '/';
+}
+
+const gchar *
+mono_icall_get_file_path_prefix (const gchar *path)
+{
+       if (*path == '/' && *(path + 1) == '/') {
+               return "file:";
+       } else {
+               return "file:///";
+       }
+}
+
+gpointer
+mono_icall_module_get_hinstance (MonoReflectionModule *module)
+{
+       if (module->image && module->image->is_module_handle)
+               return module->image->raw_data;
+
+       return (gpointer) (-1);
+}
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+MonoString *
+mono_icall_get_machine_name (void)
+{
+       gunichar2 *buf;
+       guint32 len;
+       MonoString *result;
+
+       len = MAX_COMPUTERNAME_LENGTH + 1;
+       buf = g_new (gunichar2, len);
+
+       result = NULL;
+       if (GetComputerName (buf, (PDWORD) &len)) {
+               MonoError error;
+               result = mono_string_new_utf16_checked (mono_domain_get (), buf, len, &error);
+               mono_error_set_pending_exception (&error);
+       }
+
+       g_free (buf);
+       return result;
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+int
+mono_icall_get_platform (void)
+{
+       /* Win32NT */
+       return 2;
+}
+
+MonoString *
+mono_icall_get_new_line (void)
+{
+       return mono_string_new (mono_domain_get (), "\r\n");
+}
+
+MonoBoolean
+mono_icall_is_64bit_os (void)
+{
+#if SIZEOF_VOID_P == 8
+       return TRUE;
+#else
+       gboolean isWow64Process = FALSE;
+       if (IsWow64Process (GetCurrentProcess (), &isWow64Process)) {
+               return (MonoBoolean)isWow64Process;
+       }
+       return FALSE;
+#endif
+}
+
+MonoArray *
+mono_icall_get_environment_variable_names (void)
+{
+       MonoError error;
+       MonoArray *names;
+       MonoDomain *domain;
+       MonoString *str;
+       WCHAR* env_strings;
+       WCHAR* env_string;
+       WCHAR* equal_str;
+       int n = 0;
+
+       env_strings = GetEnvironmentStrings();
+
+       if (env_strings) {
+               env_string = env_strings;
+               while (*env_string != '\0') {
+               /* weird case that MS seems to skip */
+                       if (*env_string != '=')
+                               n++;
+                       while (*env_string != '\0')
+                               env_string++;
+                       env_string++;
+               }
+       }
+
+       domain = mono_domain_get ();
+       names = mono_array_new_checked (domain, mono_defaults.string_class, n, &error);
+       if (mono_error_set_pending_exception (&error))
+               return NULL;
+
+       if (env_strings) {
+               n = 0;
+               env_string = env_strings;
+               while (*env_string != '\0') {
+                       /* weird case that MS seems to skip */
+                       if (*env_string != '=') {
+                               equal_str = wcschr(env_string, '=');
+                               g_assert(equal_str);
+                               str = mono_string_new_utf16_checked (domain, env_string, (gint32)(equal_str - env_string), &error);
+                               if (mono_error_set_pending_exception (&error))
+                                       return NULL;
+
+                               mono_array_setref (names, n, str);
+                               n++;
+                       }
+                       while (*env_string != '\0')
+                               env_string++;
+                       env_string++;
+               }
+
+               FreeEnvironmentStrings (env_strings);
+       }
+
+       return names;
+}
+
+void
+mono_icall_set_environment_variable (MonoString *name, MonoString *value)
+{
+       gunichar2 *utf16_name, *utf16_value;
+
+       utf16_name = mono_string_to_utf16 (name);
+       if ((value == NULL) || (mono_string_length (value) == 0) || (mono_string_chars (value)[0] == 0)) {
+               SetEnvironmentVariable (utf16_name, NULL);
+               g_free (utf16_name);
+               return;
+       }
+
+       utf16_value = mono_string_to_utf16 (value);
+
+       SetEnvironmentVariable (utf16_name, utf16_value);
+
+       g_free (utf16_name);
+       g_free (utf16_value);
+}
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+MonoString *
+mono_icall_get_windows_folder_path (int folder)
+{
+       #ifndef CSIDL_FLAG_CREATE
+               #define CSIDL_FLAG_CREATE       0x8000
+       #endif
+
+       WCHAR path [MAX_PATH];
+       /* Create directory if no existing */
+       if (SUCCEEDED (SHGetFolderPathW (NULL, folder | CSIDL_FLAG_CREATE, NULL, 0, path))) {
+               int len = 0;
+               while (path [len])
+                       ++ len;
+               MonoError error;
+               MonoString *res = mono_string_new_utf16_checked (mono_domain_get (), path, len, &error);
+               mono_error_set_pending_exception (&error);
+               return res;
+       }
+       return mono_string_new (mono_domain_get (), "");
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+void
+mono_icall_broadcast_setting_change (void)
+{
+       SendMessageTimeout (HWND_BROADCAST, WM_SETTINGCHANGE, (WPARAM)NULL, (LPARAM)L"Environment", SMTO_ABORTIFHUNG, 2000, 0);
+}
+
+gint32
+mono_icall_wait_for_input_idle (gpointer handle, gint32 milliseconds)
+{
+       return WaitForInputIdle (handle, milliseconds);
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+void
+mono_icall_write_windows_debug_string (MonoString *message)
+{
+       OutputDebugString (mono_string_chars (message));
+}
+
+MonoBoolean
+mono_icall_close_process (gpointer handle)
+{
+       return (MonoBoolean)(CloseHandle (handle));
+}
+#endif /* HOST_WIN32 */
index 6403f1975e91d48c89fe2a8b4a70a8d04940e351..b47bf989fd47f1a860d71fc38bab7bf1557715f4 100644 (file)
 #ifdef HAVE_UNISTD_H
 #include <unistd.h>
 #endif
-#if defined (HOST_WIN32)
-#include <stdlib.h>
-#endif
 #if defined (HAVE_WCHAR_H)
 #include <wchar.h>
 #endif
-
+#include "mono/metadata/icall-internals.h"
 #include "mono/utils/mono-membar.h"
 #include <mono/metadata/object.h>
 #include <mono/metadata/threads.h>
@@ -43,7 +40,9 @@
 #include <mono/metadata/threadpool-ms-io.h>
 #include <mono/metadata/monitor.h>
 #include <mono/metadata/reflection.h>
+#include <mono/metadata/image-internals.h>
 #include <mono/metadata/assembly.h>
+#include <mono/metadata/assembly-internals.h>
 #include <mono/metadata/tabledefs.h>
 #include <mono/metadata/exception.h>
 #include <mono/metadata/exception-internals.h>
 #include <mono/utils/mono-os-mutex.h>
 #include <mono/utils/mono-threads.h>
 
-#if defined (HOST_WIN32)
-#include <windows.h>
-#include <shlobj.h>
-#endif
 #include "decimal-ms.h"
 #include "number-ms.h"
 
 #include <sys/utsname.h>
 #endif
 
+#if HAVE_BTLS
+#include <btls/btls-ssl.h>
+#include <btls/btls-bio.h>
+#include <btls/btls-error.h>
+#include <btls/btls-key.h>
+#include <btls/btls-pkcs12.h>
+#include <btls/btls-x509-crl.h>
+#include <btls/btls-x509-chain.h>
+#include <btls/btls-x509-lookup.h>
+#include <btls/btls-x509-lookup-mono.h>
+#include <btls/btls-x509-name.h>
+#include <btls/btls-x509-revoked.h>
+#include <btls/btls-x509-store-ctx.h>
+#include <btls/btls-x509-verify-param.h>
+#endif
+
 extern MonoString* ves_icall_System_Environment_GetOSVersionString (void);
 
 ICALL_EXPORT MonoReflectionAssembly* ves_icall_System_Reflection_Assembly_GetCallingAssembly (void);
@@ -140,6 +151,20 @@ mono_class_init_checked (MonoClass *klass, MonoError *error)
                mono_error_set_for_class_failure (error, klass);
 }
 
+#ifndef HOST_WIN32
+static inline void
+mono_icall_make_platform_path (gchar *path)
+{
+       return;
+}
+
+static inline const gchar *
+mono_icall_get_file_path_prefix (const gchar *path)
+{
+       return "file://";
+}
+#endif /* HOST_WIN32 */
+
 ICALL_EXPORT MonoObject *
 ves_icall_System_Array_GetValueImpl (MonoArray *arr, guint32 pos)
 {
@@ -975,20 +1000,24 @@ ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_RunModuleConstructor (M
 ICALL_EXPORT MonoBoolean
 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_SufficientExecutionStack (void)
 {
+#if defined(TARGET_WIN32) || defined(HOST_WIN32)
+       // It does not work on win32
+#else
        guint8 *stack_addr;
        guint8 *current;
        size_t stack_size;
-       /* later make this configurable and per-arch */
-       int min_size = 4096 * 4 * sizeof (void*);
+       int min_size;
+       MonoInternalThread *thread;
+
        mono_thread_info_get_stack_bounds (&stack_addr, &stack_size);
        /* if we have no info we are optimistic and assume there is enough room */
        if (!stack_addr)
                return TRUE;
-#ifdef HOST_WIN32
-       // FIXME: Windows dynamically extends the stack, so stack_addr might be close
-       // to the current sp
-       return TRUE;
-#endif
+
+       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)
@@ -997,6 +1026,7 @@ ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_SufficientExecutionStac
                if (current - (stack_addr - stack_size) < min_size)
                        return FALSE;
        }
+#endif
        return TRUE;
 }
 
@@ -1407,7 +1437,7 @@ ves_icall_System_Type_internal_from_name (MonoString *name,
 
        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;
                }
        }
@@ -4420,8 +4450,8 @@ ves_icall_System_Reflection_Assembly_InternalGetType (MonoReflectionAssembly *as
                /* need to report exceptions ? */
                if (throwOnError && mono_class_has_failure (klass)) {
                        /* report SecurityException (or others) that occured when loading the assembly */
-                       MonoException *exc = mono_class_get_exception_for_failure (klass);
-                       mono_set_pending_exception (exc);
+                       mono_error_set_for_class_failure (&error, klass);
+                       mono_error_set_pending_exception (&error);
                        return NULL;
                }
        }
@@ -4482,25 +4512,13 @@ ves_icall_System_Reflection_Assembly_get_code_base (MonoReflectionAssembly *asse
 
        replace_shadow_path (domain, dirname, &absolute);
        g_free (dirname);
-#if HOST_WIN32
-       {
-               gint i;
-               for (i = strlen (absolute) - 1; i >= 0; i--)
-                       if (absolute [i] == '\\')
-                               absolute [i] = '/';
-       }
-#endif
+
+       mono_icall_make_platform_path (absolute);
+
        if (escaped) {
                uri = g_filename_to_uri (absolute, NULL, NULL);
        } else {
-               const char *prepend = "file://";
-#if HOST_WIN32
-               if (*absolute == '/' && *(absolute + 1) == '/') {
-                       prepend = "file:";
-               } else {
-                       prepend = "file:///";
-               }
-#endif
+               const gchar *prepend = mono_icall_get_file_path_prefix (absolute);
                uri = g_strconcat (prepend, absolute, NULL);
        }
 
@@ -4830,8 +4848,8 @@ ves_icall_System_Reflection_Assembly_GetManifestResourceInternal (MonoReflection
                g_assert ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE);
                file_idx = impl >> MONO_IMPLEMENTATION_BITS;
 
-               module = mono_image_load_file_for_image (assembly->assembly->image, file_idx);
-               if (!module)
+               module = mono_image_load_file_for_image_checked (assembly->assembly->image, file_idx, &error);
+               if (mono_error_set_pending_exception (&error) || !module)
                        return NULL;
        }
        else
@@ -5031,7 +5049,9 @@ ves_icall_System_Reflection_Assembly_GetModulesInternal (MonoReflectionAssembly
                        mono_array_setref (res, j, rm);
                }
                else {
-                       MonoImage *m = mono_image_load_file_for_image (image, i + 1);
+                       MonoImage *m = mono_image_load_file_for_image_checked (image, i + 1, &error);
+                       if (mono_error_set_pending_exception (&error))
+                               return NULL;
                        if (!m) {
                                MonoString *fname = mono_string_new (mono_domain_get (), mono_metadata_string_heap (image, cols [MONO_FILE_NAME]));
                                mono_set_pending_exception (mono_get_exception_file_not_found2 (NULL, fname));
@@ -5287,25 +5307,14 @@ fill_reflection_assembly_name (MonoDomain *domain, MonoReflectionAssemblyName *a
 
        codebase = NULL;
        if (absolute != NULL && *absolute != '\0') {
-               const gchar *prepend = "file://";
                gchar *result;
 
                codebase = g_strdup (absolute);
 
-#if HOST_WIN32
-               {
-                       gint i;
-                       for (i = strlen (codebase) - 1; i >= 0; i--)
-                               if (codebase [i] == '\\')
-                                       codebase [i] = '/';
+               mono_icall_make_platform_path (codebase);
+
+               const gchar *prepend = mono_icall_get_file_path_prefix (codebase);
 
-                       if (*codebase == '/' && *(codebase + 1) == '/') {
-                               prepend = "file:";
-                       } else {
-                               prepend = "file:///";
-                       }
-               }
-#endif
                result = g_strconcat (prepend, codebase, NULL);
                g_free (codebase);
                codebase = result;
@@ -5555,7 +5564,9 @@ ves_icall_System_Reflection_Assembly_GetTypes (MonoReflectionAssembly *assembly,
        /* Append data from all modules in the assembly */
        for (i = 0; i < table->rows; ++i) {
                if (!(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA)) {
-                       MonoImage *loaded_image = mono_assembly_load_module (image->assembly, i + 1);
+                       MonoImage *loaded_image = mono_assembly_load_module_checked (image->assembly, i + 1, &error);
+                       if (mono_error_set_pending_exception (&error))
+                               return NULL;
                        if (loaded_image) {
                                MonoArray *ex2;
                                MonoArray *res2;
@@ -5716,15 +5727,18 @@ ves_icall_System_Reflection_Module_GetGuidInternal (MonoReflectionModuleHandle r
        return mono_string_new_handle (domain, image->guid, error);
 }
 
+#ifndef HOST_WIN32
+static inline gpointer
+mono_icall_module_get_hinstance (MonoReflectionModule *module)
+{
+       return (gpointer) (-1);
+}
+#endif /* HOST_WIN32 */
+
 ICALL_EXPORT gpointer
 ves_icall_System_Reflection_Module_GetHINSTANCE (MonoReflectionModule *module)
 {
-#ifdef HOST_WIN32
-       if (module->image && module->image->is_module_handle)
-               return module->image->raw_data;
-#endif
-
-       return (gpointer) (-1);
+       return mono_icall_module_get_hinstance (module);
 }
 
 ICALL_EXPORT void
@@ -6127,7 +6141,6 @@ static void
 check_for_invalid_type (MonoClass *klass, MonoError *error)
 {
        char *name;
-       MonoString *str;
 
        mono_error_init (error);
 
@@ -6135,10 +6148,7 @@ check_for_invalid_type (MonoClass *klass, MonoError *error)
                return;
 
        name = mono_type_get_full_name (klass);
-       str =  mono_string_new (mono_domain_get (), name);
-       g_free (name);
-       mono_error_set_exception_instance (error, mono_get_exception_type_load (str, NULL));
-
+       mono_error_set_type_load_name (error, name, g_strdup (""), "");
 }
 ICALL_EXPORT MonoReflectionType *
 ves_icall_RuntimeType_make_array_type (MonoReflectionType *type, int rank)
@@ -6149,7 +6159,8 @@ ves_icall_RuntimeType_make_array_type (MonoReflectionType *type, int rank)
 
        klass = mono_class_from_mono_type (type->type);
        check_for_invalid_type (klass, &error);
-       mono_error_set_pending_exception (&error);
+       if (mono_error_set_pending_exception (&error))
+               return NULL;
 
        if (rank == 0) //single dimentional array
                aklass = mono_array_class_get (klass, 1);
@@ -6454,28 +6465,11 @@ ves_icall_System_Environment_get_UserName (void)
        return mono_string_new (mono_domain_get (), g_get_user_name ());
 }
 
-
-ICALL_EXPORT MonoString *
-ves_icall_System_Environment_get_MachineName (void)
+#ifndef HOST_WIN32
+static MonoString *
+mono_icall_get_machine_name (void)
 {
-#if defined (HOST_WIN32)
-       gunichar2 *buf;
-       guint32 len;
-       MonoString *result;
-
-       len = MAX_COMPUTERNAME_LENGTH + 1;
-       buf = g_new (gunichar2, len);
-
-       result = NULL;
-       if (GetComputerName (buf, (PDWORD) &len)) {
-               MonoError error;
-               result = mono_string_new_utf16_checked (mono_domain_get (), buf, len, &error);
-               mono_error_set_pending_exception (&error);
-       }
-
-       g_free (buf);
-       return result;
-#elif !defined(DISABLE_SOCKETS)
+#if !defined(DISABLE_SOCKETS)
        MonoString *result;
        char *buf;
        int n;
@@ -6498,14 +6492,19 @@ ves_icall_System_Environment_get_MachineName (void)
        return mono_string_new (mono_domain_get (), "mono");
 #endif
 }
+#endif /* !HOST_WIN32 */
 
-ICALL_EXPORT int
-ves_icall_System_Environment_get_Platform (void)
+ICALL_EXPORT MonoString *
+ves_icall_System_Environment_get_MachineName (void)
+{
+       return mono_icall_get_machine_name ();
+}
+
+#ifndef HOST_WIN32
+static inline int
+mono_icall_get_platform (void)
 {
-#if defined (TARGET_WIN32)
-       /* Win32NT */
-       return 2;
-#elif defined(__MACH__)
+#if defined(__MACH__)
        /* OSX */
        //
        // Notice that the value is hidden from user code, and only exposed
@@ -6520,29 +6519,36 @@ ves_icall_System_Environment_get_Platform (void)
        return 4;
 #endif
 }
+#endif /* !HOST_WIN32 */
+
+ICALL_EXPORT int
+ves_icall_System_Environment_get_Platform (void)
+{
+       return mono_icall_get_platform ();
+}
+
+#ifndef HOST_WIN32
+static inline MonoString *
+mono_icall_get_new_line (void)
+{
+       return mono_string_new (mono_domain_get (), "\n");
+}
+#endif /* !HOST_WIN32 */
 
 ICALL_EXPORT MonoString *
 ves_icall_System_Environment_get_NewLine (void)
 {
-#if defined (HOST_WIN32)
-       return mono_string_new (mono_domain_get (), "\r\n");
-#else
-       return mono_string_new (mono_domain_get (), "\n");
-#endif
+       return mono_icall_get_new_line ();
 }
 
-ICALL_EXPORT MonoBoolean
-ves_icall_System_Environment_GetIs64BitOperatingSystem (void)
+#ifndef HOST_WIN32
+static inline MonoBoolean
+mono_icall_is_64bit_os (void)
 {
 #if SIZEOF_VOID_P == 8
        return TRUE;
 #else
-#ifdef HOST_WIN32
-       gboolean isWow64Process = FALSE;
-       if (IsWow64Process (GetCurrentProcess (), &isWow64Process)) {
-               return (MonoBoolean)isWow64Process;
-       }
-#elif defined(HAVE_SYS_UTSNAME_H)
+#if defined(HAVE_SYS_UTSNAME_H)
        struct utsname name;
 
        if (uname (&name) >= 0) {
@@ -6552,6 +6558,13 @@ ves_icall_System_Environment_GetIs64BitOperatingSystem (void)
        return FALSE;
 #endif
 }
+#endif /* !HOST_WIN32 */
+
+ICALL_EXPORT MonoBoolean
+ves_icall_System_Environment_GetIs64BitOperatingSystem (void)
+{
+       return mono_icall_is_64bit_os ();
+}
 
 ICALL_EXPORT MonoStringHandle
 ves_icall_System_Environment_GetEnvironmentVariable_native (const gchar *utf8_name, MonoError *error)
@@ -6602,65 +6615,10 @@ ves_icall_System_Environment_GetCoomandLineArgs (void)
        return result;
 }
 
-ICALL_EXPORT MonoArray *
-ves_icall_System_Environment_GetEnvironmentVariableNames (void)
+#ifndef HOST_WIN32
+static MonoArray *
+mono_icall_get_environment_variable_names (void)
 {
-#ifdef HOST_WIN32
-       MonoError error;
-       MonoArray *names;
-       MonoDomain *domain;
-       MonoString *str;
-       WCHAR* env_strings;
-       WCHAR* env_string;
-       WCHAR* equal_str;
-       int n = 0;
-
-       env_strings = GetEnvironmentStrings();
-
-       if (env_strings) {
-               env_string = env_strings;
-               while (*env_string != '\0') {
-               /* weird case that MS seems to skip */
-                       if (*env_string != '=')
-                               n++;
-                       while (*env_string != '\0')
-                               env_string++;
-                       env_string++;
-               }
-       }
-
-       domain = mono_domain_get ();
-       names = mono_array_new_checked (domain, mono_defaults.string_class, n, &error);
-       if (mono_error_set_pending_exception (&error))
-               return NULL;
-
-       if (env_strings) {
-               n = 0;
-               env_string = env_strings;
-               while (*env_string != '\0') {
-                       /* weird case that MS seems to skip */
-                       if (*env_string != '=') {
-                               equal_str = wcschr(env_string, '=');
-                               g_assert(equal_str);
-                               MonoError error;
-                               str = mono_string_new_utf16_checked (domain, env_string, equal_str-env_string, &error);
-                               if (mono_error_set_pending_exception (&error))
-                                       return NULL;
-
-                               mono_array_setref (names, n, str);
-                               n++;
-                       }
-                       while (*env_string != '\0')
-                               env_string++;
-                       env_string++;
-               }
-
-               FreeEnvironmentStrings (env_strings);
-       }
-
-       return names;
-
-#else
        MonoError error;
        MonoArray *names;
        MonoDomain *domain;
@@ -6691,34 +6649,22 @@ ves_icall_System_Environment_GetEnvironmentVariableNames (void)
        }
 
        return names;
-#endif
 }
+#endif /* !HOST_WIN32 */
 
-ICALL_EXPORT void
-ves_icall_System_Environment_InternalSetEnvironmentVariable (MonoString *name, MonoString *value)
+ICALL_EXPORT MonoArray *
+ves_icall_System_Environment_GetEnvironmentVariableNames (void)
+{
+       return mono_icall_get_environment_variable_names ();
+}
+
+#ifndef HOST_WIN32
+static void
+mono_icall_set_environment_variable (MonoString *name, MonoString *value)
 {
-#ifdef HOST_WIN32
-       gunichar2 *utf16_name, *utf16_value;
-#else
        gchar *utf8_name, *utf8_value;
        MonoError error;
-#endif
-
-#ifdef HOST_WIN32
-       utf16_name = mono_string_to_utf16 (name);
-       if ((value == NULL) || (mono_string_length (value) == 0) || (mono_string_chars (value)[0] == 0)) {
-               SetEnvironmentVariable (utf16_name, NULL);
-               g_free (utf16_name);
-               return;
-       }
-
-       utf16_value = mono_string_to_utf16 (value);
 
-       SetEnvironmentVariable (utf16_name, utf16_value);
-
-       g_free (utf16_name);
-       g_free (utf16_value);
-#else
        utf8_name = mono_string_to_utf8_checked (name, &error); /* FIXME: this should be ascii */
        if (mono_error_set_pending_exception (&error))
                return;
@@ -6739,7 +6685,13 @@ ves_icall_System_Environment_InternalSetEnvironmentVariable (MonoString *name, M
 
        g_free (utf8_name);
        g_free (utf8_value);
-#endif
+}
+#endif /* !HOST_WIN32 */
+
+ICALL_EXPORT void
+ves_icall_System_Environment_InternalSetEnvironmentVariable (MonoString *name, MonoString *value)
+{
+       mono_icall_set_environment_variable (name, value);
 }
 
 ICALL_EXPORT void
@@ -6771,36 +6723,27 @@ ves_icall_System_Environment_GetGacPath (MonoError *error)
        return mono_string_new_handle (mono_domain_get (), mono_assembly_getrootdir (), error);
 }
 
-ICALL_EXPORT MonoString*
-ves_icall_System_Environment_GetWindowsFolderPath (int folder)
+#ifndef HOST_WIN32
+static inline MonoString *
+mono_icall_get_windows_folder_path (int folder)
 {
-#if defined (HOST_WIN32)
-       #ifndef CSIDL_FLAG_CREATE
-               #define CSIDL_FLAG_CREATE       0x8000
-       #endif
-
-       WCHAR path [MAX_PATH];
-       /* Create directory if no existing */
-       if (SUCCEEDED (SHGetFolderPathW (NULL, folder | CSIDL_FLAG_CREATE, NULL, 0, path))) {
-               int len = 0;
-               while (path [len])
-                       ++ len;
-               MonoError error;
-               MonoString *res = mono_string_new_utf16_checked (mono_domain_get (), path, len, &error);
-               mono_error_set_pending_exception (&error);
-               return res;
-       }
-#else
        g_warning ("ves_icall_System_Environment_GetWindowsFolderPath should only be called on Windows!");
-#endif
        return mono_string_new (mono_domain_get (), "");
 }
+#endif /* !HOST_WIN32 */
 
-ICALL_EXPORT MonoArray *
-ves_icall_System_Environment_GetLogicalDrives (void)
+ICALL_EXPORT MonoString*
+ves_icall_System_Environment_GetWindowsFolderPath (int folder)
+{
+       return mono_icall_get_windows_folder_path (folder);
+}
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+static MonoArray *
+mono_icall_get_logical_drives (void)
 {
        MonoError error;
-        gunichar2 buf [256], *ptr, *dname;
+       gunichar2 buf [256], *ptr, *dname;
        gunichar2 *u16;
        guint initial_size = 127, size = 128;
        gint ndrives;
@@ -6855,6 +6798,13 @@ leave:
 
        return result;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+ICALL_EXPORT MonoArray *
+ves_icall_System_Environment_GetLogicalDrives (void)
+{
+       return mono_icall_get_logical_drives ();
+}
 
 ICALL_EXPORT MonoString *
 ves_icall_System_IO_DriveInfo_GetDriveFormat (MonoString *path)
@@ -6916,7 +6866,7 @@ ves_icall_System_Text_EncodingHelper_InternalCodePage (gint32 *int_code_page)
        *int_code_page = -1;
 
        g_get_charset (&cset);
-       c = codepage = strdup (cset);
+       c = codepage = g_strdup (cset);
        for (c = codepage; *c; c++){
                if (isascii (*c) && isalpha (*c))
                        *c = tolower (*c);
@@ -6963,12 +6913,18 @@ ves_icall_System_Environment_get_HasShutdownStarted (void)
        return FALSE;
 }
 
+#ifndef HOST_WIN32
+static inline void
+mono_icall_broadcast_setting_change (void)
+{
+       return;
+}
+#endif /* !HOST_WIN32 */
+
 ICALL_EXPORT void
 ves_icall_System_Environment_BroadcastSettingChange (void)
 {
-#ifdef HOST_WIN32
-       SendMessageTimeout (HWND_BROADCAST, WM_SETTINGCHANGE, (WPARAM)NULL, (LPARAM)L"Environment", SMTO_ABORTIFHUNG, 2000, 0);
-#endif
+       mono_icall_broadcast_setting_change ();
 }
 
 ICALL_EXPORT
@@ -7157,12 +7113,21 @@ ves_icall_System_IO_DriveInfo_GetDiskFreeSpace (MonoString *path_name, guint64 *
        return result;
 }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+static inline guint32
+mono_icall_drive_info_get_drive_type (MonoString *root_path_name)
+{
+       return GetDriveType (mono_string_chars (root_path_name));
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
 ICALL_EXPORT guint32
 ves_icall_System_IO_DriveInfo_GetDriveType (MonoString *root_path_name)
 {
-       return GetDriveType (mono_string_chars (root_path_name));
+       return mono_icall_drive_info_get_drive_type (root_path_name);
 }
-#endif
+
+#endif /* PLATFORM_NO_DRIVEINFO */
 
 ICALL_EXPORT gpointer
 ves_icall_RuntimeMethodHandle_GetFunctionPointer (MonoMethod *method)
@@ -7181,15 +7146,8 @@ ves_icall_System_Configuration_DefaultConfig_get_machine_config_path (void)
 
        path = g_build_path (G_DIR_SEPARATOR_S, mono_get_config_dir (), "mono", mono_get_runtime_info ()->framework_version, "machine.config", NULL);
 
-#if defined (HOST_WIN32)
-       /* Avoid mixing '/' and '\\' */
-       {
-               gint i;
-               for (i = strlen (path) - 1; i >= 0; i--)
-                       if (path [i] == '/')
-                               path [i] = '\\';
-       }
-#endif
+       mono_icall_make_platform_path (path);
+
        mcpath = mono_string_new (mono_domain_get (), path);
        g_free (path);
 
@@ -7243,7 +7201,6 @@ get_bundled_app_config (void)
        return mono_string_new (mono_domain_get (), app_config);
 }
 
-/* this is an icall */
 static MonoStringHandle
 get_bundled_machine_config (MonoError *error)
 {
@@ -7257,6 +7214,19 @@ get_bundled_machine_config (MonoError *error)
        return mono_string_new_handle (mono_domain_get (), machine_config, error);
 }
 
+static MonoStringHandle
+ves_icall_System_Configuration_DefaultConfig_get_bundled_machine_config (MonoError *error)
+{
+       return get_bundled_machine_config (error);
+}
+
+static MonoStringHandle
+ves_icall_System_Configuration_InternalConfigurationHost_get_bundled_machine_config (MonoError *error)
+{
+       return get_bundled_machine_config (error);
+}
+
+
 ICALL_EXPORT MonoString *
 ves_icall_System_Web_Util_ICalls_get_machine_install_dir (void)
 {
@@ -7265,15 +7235,8 @@ ves_icall_System_Web_Util_ICalls_get_machine_install_dir (void)
 
        path = g_path_get_dirname (mono_get_config_dir ());
 
-#if defined (HOST_WIN32)
-       /* Avoid mixing '/' and '\\' */
-       {
-               gint i;
-               for (i = strlen (path) - 1; i >= 0; i--)
-                       if (path [i] == '/')
-                               path [i] = '\\';
-       }
-#endif
+       mono_icall_make_platform_path (path);
+
        ipath = mono_string_new (mono_domain_get (), path);
        g_free (path);
 
@@ -7328,14 +7291,18 @@ ves_icall_System_Diagnostics_Debugger_Log (int level, MonoString *category, Mono
                mono_get_runtime_callbacks ()->debug_log (level, category, message);
 }
 
+#ifndef HOST_WIN32
+static inline void
+mono_icall_write_windows_debug_string (MonoString *message)
+{
+       g_warning ("WriteWindowsDebugString called and HOST_WIN32 not defined!\n");
+}
+#endif /* !HOST_WIN32 */
+
 ICALL_EXPORT void
 ves_icall_System_Diagnostics_DefaultTraceListener_WriteWindowsDebugString (MonoString *message)
 {
-#if defined (HOST_WIN32)
-       OutputDebugString (mono_string_chars (message));
-#else
-       g_warning ("WriteWindowsDebugString called and HOST_WIN32 not defined!\n");
-#endif
+       mono_icall_write_windows_debug_string (message);
 }
 
 /* Only used for value types */
@@ -7392,6 +7359,7 @@ ves_icall_MonoMethod_get_base_method (MonoReflectionMethod *m, gboolean definiti
                klass = klass->generic_class->container_class;
        }
 
+retry:
        if (definition) {
                /* At the end of the loop, klass points to the eldest class that has this virtual function slot. */
                for (parent = klass->parent; parent != NULL; parent = parent->parent) {
@@ -7478,14 +7446,38 @@ ves_icall_MonoMethod_get_base_method (MonoReflectionMethod *m, gboolean definiti
        result = klass->vtable [slot];
        if (result == NULL) {
                /* It is an abstract method */
+               gboolean found = FALSE;
                gpointer iter = NULL;
-               while ((result = mono_class_get_methods (klass, &iter)))
-                       if (result->slot == slot)
+               while ((result = mono_class_get_methods (klass, &iter))) {
+                       if (result->slot == slot) {
+                               found = TRUE;
                                break;
+                       }
+               }
+               /* found might be FALSE if we looked in an abstract class
+                * that doesn't override an abstract method of its
+                * parent: 
+                *   abstract class Base {
+                *     public abstract void Foo ();
+                *   }
+                *   abstract class Derived : Base { }
+                *   class Child : Derived {
+                *     public override void Foo () { }
+                *  }
+                *
+                *  if m was Child.Foo and we ask for the base method,
+                *  then we get here with klass == Derived and found == FALSE
+                */
+               /* but it shouldn't be the case that if we're looking
+                * for the definition and didn't find a result; the
+                * loop above should've taken us as far as we could
+                * go! */
+               g_assert (!(definition && !found));
+               if (!found)
+                       goto retry;
        }
 
-       if (result == NULL)
-               return m;
+       g_assert (result != NULL);
 
        ret = mono_method_get_object_checked (mono_domain_get (), result, NULL, &error);
        mono_error_set_pending_exception (&error);
@@ -7988,14 +7980,18 @@ ves_icall_Microsoft_Win32_NativeMethods_GetExitCodeProcess (gpointer handle, gin
        return GetExitCodeProcess (handle, (guint32*) exitcode);
 }
 
+#ifndef HOST_WIN32
+static inline MonoBoolean
+mono_icall_close_process (gpointer handle)
+{
+       return CloseProcess (handle);
+}
+#endif /* !HOST_WIN32 */
+
 ICALL_EXPORT MonoBoolean
 ves_icall_Microsoft_Win32_NativeMethods_CloseProcess (gpointer handle)
 {
-#if defined(TARGET_WIN32) || defined(HOST_WIN32)
-       return CloseHandle (handle);
-#else
-       return CloseProcess (handle);
-#endif
+       return mono_icall_close_process (handle);
 }
 
 ICALL_EXPORT MonoBoolean
@@ -8004,27 +8000,46 @@ ves_icall_Microsoft_Win32_NativeMethods_TerminateProcess (gpointer handle, gint3
        return TerminateProcess (handle, exitcode);
 }
 
+#ifndef HOST_WIN32
+static inline gint32
+mono_icall_wait_for_input_idle (gpointer handle, gint32 milliseconds)
+{
+       return WAIT_TIMEOUT;
+}
+#endif /* !HOST_WIN32 */
+
 ICALL_EXPORT gint32
 ves_icall_Microsoft_Win32_NativeMethods_WaitForInputIdle (gpointer handle, gint32 milliseconds)
 {
-#ifdef HOST_WIN32
-       return WaitForInputIdle (handle, milliseconds);
-#else
-       /*TODO: Not implemented*/
-       return WAIT_TIMEOUT;
-#endif
+       return mono_icall_wait_for_input_idle (handle, milliseconds);
+}
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+static inline MonoBoolean
+mono_icall_get_process_working_set_size (gpointer handle, gsize *min, gsize *max)
+{
+       return GetProcessWorkingSetSize (handle, min, max);
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
 
 ICALL_EXPORT MonoBoolean
 ves_icall_Microsoft_Win32_NativeMethods_GetProcessWorkingSetSize (gpointer handle, gsize *min, gsize *max)
 {
-       return GetProcessWorkingSetSize (handle, min, max);
+       return mono_icall_get_process_working_set_size (handle, min, max);
+}
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+static inline MonoBoolean
+mono_icall_set_process_working_set_size (gpointer handle, gsize min, gsize max)
+{
+       return SetProcessWorkingSetSize (handle, min, max);
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
 
 ICALL_EXPORT MonoBoolean
 ves_icall_Microsoft_Win32_NativeMethods_SetProcessWorkingSetSize (gpointer handle, gsize min, gsize max)
 {
-       return SetProcessWorkingSetSize (handle, min, max);
+       return mono_icall_set_process_working_set_size (handle, min, max);
 }
 
 ICALL_EXPORT MonoBoolean
@@ -8039,16 +8054,42 @@ ves_icall_Microsoft_Win32_NativeMethods_GetCurrentProcessId (void)
        return mono_process_current_pid ();
 }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+static inline gint32
+mono_icall_get_priority_class (gpointer handle)
+{
+       return GetPriorityClass (handle);
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
 ICALL_EXPORT gint32
 ves_icall_Microsoft_Win32_NativeMethods_GetPriorityClass (gpointer handle)
 {
-       return GetPriorityClass (handle);
+       return mono_icall_get_priority_class (handle);
+}
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+static inline MonoBoolean
+mono_icall_set_priority_class (gpointer handle, gint32 priorityClass)
+{
+       return SetPriorityClass (handle, priorityClass);
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
 
 ICALL_EXPORT MonoBoolean
 ves_icall_Microsoft_Win32_NativeMethods_SetPriorityClass (gpointer handle, gint32 priorityClass)
 {
-       return SetPriorityClass (handle, priorityClass);
+       return mono_icall_set_priority_class (handle, priorityClass);
+}
+
+ICALL_EXPORT MonoBoolean
+ves_icall_Mono_TlsProviderFactory_IsBtlsSupported (void)
+{
+#if HAVE_BTLS
+       return TRUE;
+#else
+       return FALSE;
+#endif
 }
 
 #ifndef DISABLE_ICALL_TABLES
index 959575f6a0a4a8c8996720693fd4a39d412b0c4a..6281e3b241c35eb37cbb5d1ead242c7ab41ccb16 100644 (file)
 MonoImage *
 mono_find_image_owner (void *ptr);
 
+MonoImage*
+mono_image_load_file_for_image_checked (MonoImage *image, int fileidx, MonoError *error);
+
+MonoImage*
+mono_image_load_module_checked (MonoImage *image, int idx, MonoError *error);
+
 #endif /* __MONO_METADATA_IMAGE_INTERNALS_H__ */
index 50eaded2e37279442560273998901d1e3cbb82ea..7f3260c0babc5887fef8335e55367356f1e08d6d 100644 (file)
@@ -28,6 +28,7 @@
 #include "marshal.h"
 #include "coree.h"
 #include <mono/io-layer/io-layer.h>
+#include <mono/utils/checked-build.h>
 #include <mono/utils/mono-logger-internals.h>
 #include <mono/utils/mono-path.h>
 #include <mono/utils/mono-mmap.h>
@@ -66,18 +67,43 @@ enum {
 };
 static GHashTable *loaded_images_hashes [4] = {NULL, NULL, NULL, NULL};
 
-static GHashTable *get_loaded_images_hash (gboolean refonly)
+static GHashTable *
+get_loaded_images_hash (gboolean refonly)
 {
        int idx = refonly ? IMAGES_HASH_PATH_REFONLY : IMAGES_HASH_PATH;
        return loaded_images_hashes [idx];
 }
 
-static GHashTable *get_loaded_images_by_name_hash (gboolean refonly)
+static GHashTable *
+get_loaded_images_by_name_hash (gboolean refonly)
 {
        int idx = refonly ? IMAGES_HASH_NAME_REFONLY : IMAGES_HASH_NAME;
        return loaded_images_hashes [idx];
 }
 
+// Change the assembly set in `image` to the assembly set in `assemblyImage`. Halt if overwriting is attempted.
+// Can be used on modules loaded through either the "file" or "module" mechanism
+static gboolean
+assign_assembly_parent_for_netmodule (MonoImage *image, MonoImage *assemblyImage, MonoError *error)
+{
+       // Assembly to assign
+       MonoAssembly *assembly = assemblyImage->assembly;
+
+       while (1) {
+               // Assembly currently assigned
+               MonoAssembly *assemblyOld = image->assembly;
+               if (assemblyOld) {
+                       if (assemblyOld == assembly)
+                               return TRUE;
+                       mono_error_set_bad_image (error, assemblyImage, "Attempted to load module %s which has already been loaded by assembly %s. This is not supported in Mono.", image->name, assemblyOld->image->name);
+                       return FALSE;
+               }
+               gpointer result = InterlockedExchangePointer((gpointer *)&image->assembly, assembly);
+               if (result == assembly)
+                       return TRUE;
+       }
+}
+
 static gboolean debug_assembly_unload = FALSE;
 
 #define mono_images_lock() if (mutex_inited) mono_os_mutex_lock (&images_mutex)
@@ -632,13 +658,13 @@ load_modules (MonoImage *image)
 }
 
 /**
- * mono_image_load_module:
+ * mono_image_load_module_checked:
  *
  *   Load the module with the one-based index IDX from IMAGE and return it. Return NULL if
- * it cannot be loaded.
+ * it cannot be loaded. NULL without MonoError being set will be interpreted as "not found".
  */
 MonoImage*
-mono_image_load_module (MonoImage *image, int idx)
+mono_image_load_module_checked (MonoImage *image, int idx, MonoError *error)
 {
        MonoTableInfo *t;
        MonoTableInfo *file_table;
@@ -648,6 +674,8 @@ mono_image_load_module (MonoImage *image, int idx)
        GList *list_iter, *valid_modules = NULL;
        MonoImageOpenStatus status;
 
+       mono_error_init (error);
+
        if ((image->module_count == 0) || (idx > image->module_count || idx <= 0))
                return NULL;
        if (image->modules_loaded [idx - 1])
@@ -683,10 +711,18 @@ mono_image_load_module (MonoImage *image, int idx)
                }
                if (valid) {
                        module_ref = g_build_filename (base_dir, name, NULL);
-                       image->modules [idx - 1] = mono_image_open_full (module_ref, &status, refonly);
-                       if (image->modules [idx - 1]) {
-                               mono_image_addref (image->modules [idx - 1]);
-                               image->modules [idx - 1]->assembly = image->assembly;
+                       MonoImage *moduleImage = mono_image_open_full (module_ref, &status, refonly);
+                       if (moduleImage) {
+                               if (!assign_assembly_parent_for_netmodule (moduleImage, image, error)) {
+                                       mono_image_close (moduleImage);
+                                       g_free (module_ref);
+                                       g_free (base_dir);
+                                       g_list_free (valid_modules);
+                                       return NULL;
+                               }
+
+                               image->modules [idx - 1] = image;
+
 #ifdef HOST_WIN32
                                if (image->modules [idx - 1]->is_module_handle)
                                        mono_image_fixup_vtable (image->modules [idx - 1]);
@@ -705,6 +741,15 @@ mono_image_load_module (MonoImage *image, int idx)
        return image->modules [idx - 1];
 }
 
+MonoImage*
+mono_image_load_module (MonoImage *image, int idx)
+{
+       MonoError error;
+       MonoImage *result = mono_image_load_module_checked (image, idx, &error);
+       mono_error_assert_ok (&error);
+       return result;
+}
+
 static gpointer
 class_key_extract (gpointer value)
 {
@@ -1653,6 +1698,17 @@ mono_wrapper_caches_free (MonoWrapperCaches *cache)
        free_hash (cache->thunk_invoke_cache);
 }
 
+static void
+mono_image_close_except_pools_all (MonoImage**images, int image_count)
+{
+       for (int i = 0; i < image_count; ++i) {
+               if (images [i]) {
+                       if (!mono_image_close_except_pools (images [i]))
+                               images [i] = NULL;
+               }
+       }
+}
+
 /*
  * Returns whether mono_image_close_finish() must be called as well.
  * We must unload images in two steps because clearing the domain in
@@ -1773,7 +1829,6 @@ mono_image_close_except_pools (MonoImage *image)
                g_free (image->name);
                g_free (image->guid);
                g_free (image->version);
-               g_free (image->files);
        }
 
        if (image->method_cache)
@@ -1852,12 +1907,8 @@ mono_image_close_except_pools (MonoImage *image)
                g_free (image->image_info);
        }
 
-       for (i = 0; i < image->module_count; ++i) {
-               if (image->modules [i]) {
-                       if (!mono_image_close_except_pools (image->modules [i]))
-                               image->modules [i] = NULL;
-               }
-       }
+       mono_image_close_except_pools_all (image->files, image->file_count);
+       mono_image_close_except_pools_all (image->modules, image->module_count);
        if (image->modules_loaded)
                g_free (image->modules_loaded);
 
@@ -1876,6 +1927,17 @@ mono_image_close_except_pools (MonoImage *image)
        return TRUE;
 }
 
+static void
+mono_image_close_all (MonoImage**images, int image_count)
+{
+       for (int i = 0; i < image_count; ++i) {
+               if (images [i])
+                       mono_image_close_finish (images [i]);
+       }
+       if (images)
+               g_free (images);
+}
+
 void
 mono_image_close_finish (MonoImage *image)
 {
@@ -1891,12 +1953,8 @@ mono_image_close_finish (MonoImage *image)
                image->references = NULL;
        }
 
-       for (i = 0; i < image->module_count; ++i) {
-               if (image->modules [i])
-                       mono_image_close_finish (image->modules [i]);
-       }
-       if (image->modules)
-               g_free (image->modules);
+       mono_image_close_all (image->files, image->file_count);
+       mono_image_close_all (image->modules, image->module_count);
 
 #ifndef DISABLE_PERFCOUNTERS
        mono_perfcounters->loader_bytes -= mono_mempool_get_allocated (image->mempool);
@@ -2153,8 +2211,9 @@ mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size)
        return data;
 }
 
+// Returning NULL with no error set will be interpeted as "not found"
 MonoImage*
-mono_image_load_file_for_image (MonoImage *image, int fileidx)
+mono_image_load_file_for_image_checked (MonoImage *image, int fileidx, MonoError *error)
 {
        char *base_dir, *name;
        MonoImage *res;
@@ -2162,6 +2221,8 @@ mono_image_load_file_for_image (MonoImage *image, int fileidx)
        const char *fname;
        guint32 fname_id;
 
+       mono_error_init (error);
+
        if (fileidx < 1 || fileidx > t->rows)
                return NULL;
 
@@ -2189,14 +2250,21 @@ mono_image_load_file_for_image (MonoImage *image, int fileidx)
        } else {
                int i;
                /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */
-               res->assembly = image->assembly;
+               if (!assign_assembly_parent_for_netmodule (res, image, error)) {
+                       mono_image_unlock (image);
+                       mono_image_close (res);
+                       return NULL;
+               }
+
                for (i = 0; i < res->module_count; ++i) {
                        if (res->modules [i] && !res->modules [i]->assembly)
                                res->modules [i]->assembly = image->assembly;
                }
 
-               if (!image->files)
+               if (!image->files) {
                        image->files = g_new0 (MonoImage*, t->rows);
+                       image->file_count = t->rows;
+               }
                image->files [fileidx - 1] = res;
                mono_image_unlock (image);
                /* vtable fixup can't happen with the image lock held */
@@ -2212,6 +2280,15 @@ done:
        return res;
 }
 
+MonoImage*
+mono_image_load_file_for_image (MonoImage *image, int fileidx)
+{
+       MonoError error;
+       MonoImage *result = mono_image_load_file_for_image_checked (image, fileidx, &error);
+       mono_error_assert_ok (&error);
+       return result;
+}
+
 /**
  * mono_image_get_strong_name:
  * @image: a MonoImage
@@ -2450,6 +2527,31 @@ mono_image_strdup (MonoImage *image, const char *s)
        return res;
 }
 
+char*
+mono_image_strdup_vprintf (MonoImage *image, const char *format, va_list args)
+{
+       char *buf;
+       mono_image_lock (image);
+       buf = mono_mempool_strdup_vprintf (image->mempool, format, args);
+       mono_image_unlock (image);
+#ifndef DISABLE_PERFCOUNTERS
+       mono_perfcounters->loader_bytes += strlen (buf);
+#endif
+       return buf;
+}
+
+char*
+mono_image_strdup_printf (MonoImage *image, const char *format, ...)
+{
+       char *buf;
+       va_list args;
+
+       va_start (args, format);
+       buf = mono_image_strdup_vprintf (image, format, args);
+       va_end (args);
+       return buf;
+}
+
 GList*
 g_list_prepend_image (MonoImage *image, GList *list, gpointer data)
 {
@@ -2522,6 +2624,7 @@ mono_image_property_lookup (MonoImage *image, gpointer subject, guint32 property
 void
 mono_image_property_insert (MonoImage *image, gpointer subject, guint32 property, gpointer value)
 {
+       CHECKED_METADATA_STORE_LOCAL (image->mempool, value);
        mono_image_lock (image);
        mono_property_hash_insert (image->property_hash, subject, property, value);
        mono_image_unlock (image);
index c3ad58b3431c00e04a95676339e5f07ea2e3291f..b158ec26834acc9962eb16361ee9cb94ba8dd243 100644 (file)
@@ -3,6 +3,7 @@
 
 #include <stdio.h>
 #include <mono/utils/mono-publib.h>
+#include <mono/utils/mono-error.h>
 
 MONO_BEGIN_DECLS
 
@@ -50,9 +51,9 @@ MONO_API int           mono_image_ensure_section_idx (MonoImage *image,
 
 MONO_API uint32_t       mono_image_get_entry_point    (MonoImage *image);
 MONO_API const char   *mono_image_get_resource       (MonoImage *image, uint32_t offset, uint32_t *size);
-MONO_API MonoImage*    mono_image_load_file_for_image (MonoImage *image, int fileidx);
+MONO_RT_EXTERNAL_ONLY MONO_API MonoImage*    mono_image_load_file_for_image (MonoImage *image, int fileidx);
 
-MONO_API MonoImage*    mono_image_load_module (MonoImage *image, int idx);
+MONO_RT_EXTERNAL_ONLY MONO_API MonoImage*    mono_image_load_module (MonoImage *image, int idx);
 
 MONO_API const char*   mono_image_get_name       (MonoImage *image);
 MONO_API const char*   mono_image_get_filename   (MonoImage *image);
index 64e7d06e56ffdded117edf0dc1ebf5233ba48bfa..3d85497bfe0a094a8154c6277ba693e8a910f157 100644 (file)
@@ -194,7 +194,7 @@ field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
        fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
 
        if (!mono_verifier_verify_memberref_field_signature (image, cols [MONO_MEMBERREF_SIGNATURE], NULL)) {
-               mono_error_set_bad_image (error, image, "Bad field '%s' signature 0x%08x", class_index, token);
+               mono_error_set_bad_image (error, image, "Bad field '%u' signature 0x%08x", class_index, token);
                return NULL;
        }
 
@@ -209,7 +209,7 @@ field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
                klass = mono_class_get_and_inflate_typespec_checked (image, MONO_TOKEN_TYPE_SPEC | nindex, context, error);
                break;
        default:
-               mono_error_set_bad_image (error, image, "Bad field field '%s' signature 0x%08x", class_index, token);
+               mono_error_set_bad_image (error, image, "Bad field field '%u' signature 0x%08x", class_index, token);
        }
 
        if (!klass)
@@ -1123,6 +1123,14 @@ cached_module_load (const char *name, int flags, char **err)
        return res;
 }
 
+void
+mono_loader_register_module (const char *name, MonoDl *module)
+{
+       if (!global_module_map)
+               global_module_map = g_hash_table_new (g_str_hash, g_str_equal);
+       g_hash_table_insert (global_module_map, g_strdup (name), module);
+}
+
 static MonoDl *internal_module;
 
 static gboolean
@@ -2133,8 +2141,6 @@ mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
        g_assert (method != NULL);
        g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
 
-       if (method->is_inflated)
-               method = ((MonoMethodInflated *) method)->declaring;
        data = (void **)((MonoMethodWrapper *)method)->method_data;
        g_assert (data != NULL);
        g_assert (id <= GPOINTER_TO_UINT (*data));
index a2c6d349ddf15fcc186278750843b8289e4a6c96..6382c774ae3fd431d61f741df0456253a4847d44 100644 (file)
@@ -4,6 +4,7 @@
 #include <mono/metadata/metadata.h>
 #include <mono/metadata/image.h>
 #include <mono/utils/mono-error.h>
+#include <mono/utils/mono-dl.h>
 
 MONO_BEGIN_DECLS
 
@@ -63,6 +64,8 @@ mono_lookup_internal_call (MonoMethod *method);
 void*
 mono_lookup_internal_call_full (MonoMethod *method, mono_bool *uses_handles);
 
+void
+mono_loader_register_module (const char *name, MonoDl *module);
 
 MONO_API const char*
 mono_lookup_icall_symbol (MonoMethod *m);
index 66f7d6b560d084cac2f07ffc20249e62b699c8f9..551f8a751e8e1d58edac3c6186346d64fd46100c 100644 (file)
@@ -141,8 +141,9 @@ mono_locks_lock_released (RuntimeLocks kind, gpointer lock)
        add_record (RECORD_LOCK_RELEASED, kind, lock);
 }
 #else
-       #ifdef _MSC_VER
-               // Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
-               void __mono_win32_lock_tracer_quiet_lnk4221(void) {}
-       #endif
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_lock_tracer_quiet_lnk4221(void) {}
+#endif
 #endif /* LOCK_TRACER */
diff --git a/mono/metadata/marshal-internals.h b/mono/metadata/marshal-internals.h
new file mode 100644 (file)
index 0000000..e19613a
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#ifndef __MONO_METADATA_MARSHAL_INTERNALS_H__
+#define __MONO_METADATA_MARSHAL_INTERNALS_H__
+
+#include <config.h>
+#include <glib.h>
+#include <mono/metadata/object-internals.h>
+
+// On Windows platform implementation of bellow methods are hosted in separate source file
+// masrshal-windows.c or marshal-windows-*.c. On other platforms the implementation is still keept
+// in marshal.c still declared as static and in some places even inlined.
+#ifdef HOST_WIN32
+void*
+mono_marshal_alloc_co_task_mem (size_t size);
+
+void
+mono_marshal_free_co_task_mem (void *ptr);
+
+gpointer
+mono_marshal_realloc_co_task_mem (gpointer ptr, size_t size);
+
+void*
+mono_marshal_alloc_hglobal (size_t size);
+
+gpointer
+mono_marshal_realloc_hglobal (gpointer ptr, size_t size);
+
+void
+mono_marshal_free_hglobal (void *ptr);
+
+gpointer
+mono_string_to_lpstr (MonoString *s);
+#endif  /* HOST_WIN32 */
+
+#endif /* __MONO_METADATA_MARSHAL_INTERNALS_H__ */
diff --git a/mono/metadata/marshal-windows-internals.h b/mono/metadata/marshal-windows-internals.h
new file mode 100644 (file)
index 0000000..d6b3f45
--- /dev/null
@@ -0,0 +1,17 @@
+/*
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#ifndef __MONO_METADATA_MARSHAL_WINDOWS_INTERNALS_H__
+#define __MONO_METADATA_MARSHAL_WINDOWS_INTERNALS_H__
+
+#include <config.h>
+#include <glib.h>
+
+#ifdef HOST_WIN32
+#include "mono/metadata/marshal.h"
+#include "mono/metadata/marshal-internals.h"
+#include "mono/metadata/exception.h"
+#endif /* HOST_WIN32 */
+
+#endif /* __MONO_METADATA_MARSHAL_WINDOWS_INTERNALS_H__ */
diff --git a/mono/metadata/marshal-windows-uwp.c b/mono/metadata/marshal-windows-uwp.c
new file mode 100644 (file)
index 0000000..a2fa813
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * marshal-windows-uwp.c: UWP marshal support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+
+#if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
+#include <Windows.h>
+#include "mono/metadata/marshal-windows-internals.h"
+
+void *
+mono_marshal_alloc_hglobal (size_t size)
+{
+       return HeapAlloc (GetProcessHeap (), 0, size);
+}
+
+gpointer
+mono_marshal_realloc_hglobal (gpointer ptr, size_t size)
+{
+       return HeapReAlloc (GetProcessHeap (), 0, ptr, size);
+}
+
+void
+mono_marshal_free_hglobal (gpointer ptr)
+{
+       HeapFree (GetProcessHeap (), 0, ptr);
+       return;
+}
+
+#else /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_marshal_windows_uwp_quiet_lnk4221(void) {}
+#endif
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
diff --git a/mono/metadata/marshal-windows.c b/mono/metadata/marshal-windows.c
new file mode 100644 (file)
index 0000000..db9d8be
--- /dev/null
@@ -0,0 +1,125 @@
+/*
+ * marshal-windows.c: Windows marshal support.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#include <config.h>
+#include <glib.h>
+
+#if defined(HOST_WIN32)
+#include <WinSock2.h>
+#include <Windows.h>
+#include <objbase.h>
+#include "mono/metadata/marshal-windows-internals.h"
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+void*
+mono_marshal_alloc_hglobal (size_t size)
+{
+       return GlobalAlloc (GMEM_FIXED, size);
+}
+
+gpointer
+mono_marshal_realloc_hglobal (gpointer ptr, size_t size)
+{
+       return GlobalReAlloc (ptr, size, GMEM_MOVEABLE);
+}
+
+void
+mono_marshal_free_hglobal (gpointer ptr)
+{
+       GlobalFree (ptr);
+       return;
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+void*
+mono_marshal_alloc_co_task_mem (size_t size)
+{
+       return CoTaskMemAlloc (size);
+}
+
+void
+mono_marshal_free_co_task_mem (void *ptr)
+{
+       CoTaskMemFree (ptr);
+       return;
+}
+
+gpointer
+mono_marshal_realloc_co_task_mem (gpointer ptr, size_t size)
+{
+       return CoTaskMemRealloc (ptr, size);
+}
+
+gpointer
+ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalAnsi (MonoString *string)
+{
+       MonoError error;
+       char* tres, *ret;
+       size_t len;
+       tres = mono_string_to_utf8_checked (string, &error);
+       if (mono_error_set_pending_exception (&error))
+               return NULL;
+       if (!tres)
+               return tres;
+
+       /*
+        * mono_string_to_utf8_checked() returns a memory area at least as large as the size of the
+        * MonoString, even if it contains NULL characters. The copy we allocate here has to be equally
+        * large.
+        */
+       len = MAX (strlen (tres) + 1, string->length);
+       ret = ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal ((gpointer)len);
+       memcpy (ret, tres, len);
+       g_free (tres);
+       return ret;
+}
+
+gpointer
+ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalUni (MonoString *string)
+{
+       if (string == NULL)
+               return NULL;
+       else {
+               size_t len = ((mono_string_length (string) + 1) * 2);
+               gunichar2 *res = ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal ((gpointer)len);
+
+               memcpy (res, mono_string_chars (string), mono_string_length (string) * 2);
+               res [mono_string_length (string)] = 0;
+               return res;
+       }
+}
+
+gpointer
+mono_string_to_lpstr (MonoString *s)
+{
+       char *as, *tmp;
+       glong len;
+       GError *error = NULL;
+
+       if (s == NULL)
+               return NULL;
+
+       if (!s->length) {
+               as = CoTaskMemAlloc (1);
+               as [0] = '\0';
+               return as;
+       }
+
+       tmp = g_utf16_to_utf8 (mono_string_chars (s), s->length, NULL, &len, &error);
+       if (error) {
+               MonoException *exc = mono_get_exception_argument ("string", error->message);
+               g_error_free (error);
+               mono_set_pending_exception (exc);
+               return NULL;
+       } else {
+               as = CoTaskMemAlloc (len + 1);
+               memcpy (as, tmp, len + 1);
+               g_free (tmp);
+               return as;
+       }
+}
+
+#endif /* HOST_WIN32 */
index b457211c83da5d2ffd2116bae62c9acb98e4e408..a725148ad78c8b9aef410fb93b77ee9bca0e011c 100644 (file)
@@ -20,6 +20,7 @@
 #include "loader.h"
 #include "cil-coff.h"
 #include "metadata/marshal.h"
+#include "metadata/marshal-internals.h"
 #include "metadata/method-builder.h"
 #include "metadata/tabledefs.h"
 #include "metadata/exception.h"
@@ -106,8 +107,10 @@ mono_marshal_string_to_utf16 (MonoString *s);
 static void *
 mono_marshal_string_to_utf16_copy (MonoString *s);
 
+#ifndef HOST_WIN32
 static gpointer
 mono_string_to_lpstr (MonoString *string_obj);
+#endif
 
 static MonoStringBuilder *
 mono_string_utf8_to_builder2 (char *text);
@@ -1076,42 +1079,16 @@ mono_string_builder_to_utf16 (MonoStringBuilder *sb)
 }
 
 /* This is a JIT icall, it sets the pending exception and returns NULL on error. */
+#ifndef HOST_WIN32
 static gpointer
 mono_string_to_lpstr (MonoString *s)
 {
-#ifdef TARGET_WIN32
-       char *as, *tmp;
-       glong len;
-       GError *error = NULL;
-
-       if (s == NULL)
-               return NULL;
-
-       if (!s->length) {
-               as = CoTaskMemAlloc (1);
-               as [0] = '\0';
-               return as;
-       }
-
-       tmp = g_utf16_to_utf8 (mono_string_chars (s), s->length, NULL, &len, &error);
-       if (error) {
-               MonoException *exc = mono_get_exception_argument ("string", error->message);
-               g_error_free (error);
-               mono_set_pending_exception (exc);
-               return NULL;
-       } else {
-               as = CoTaskMemAlloc (len + 1);
-               memcpy (as, tmp, len + 1);
-               g_free (tmp);
-               return as;
-       }
-#else
        MonoError error;
        char *result = mono_string_to_utf8_checked (s, &error);
        mono_error_set_pending_exception (&error);
        return result;
-#endif
-}      
+}
+#endif /* HOST_WIN32 */
 
 gpointer
 mono_string_to_ansibstr (MonoString *string_obj)
@@ -2691,6 +2668,11 @@ mono_marshal_method_from_wrapper (MonoMethod *wrapper)
                        return info->d.runtime_invoke.method;
                else
                        return NULL;
+       case MONO_WRAPPER_DELEGATE_INVOKE:
+               if (info)
+                       return info->d.delegate_invoke.method;
+               else
+                       return NULL;
        default:
                return NULL;
        }
@@ -9360,7 +9342,8 @@ mono_marshal_get_synchronized_wrapper (MonoMethod *method)
 #endif
 
        if (method->klass->valuetype && !(method->flags & MONO_METHOD_ATTR_STATIC)) {
-               mono_class_set_failure (method->klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+               /* FIXME Is this really the best way to signal an error here?  Isn't this called much later after class setup? -AK */
+               mono_class_set_type_load_failure (method->klass, "");
 #ifndef DISABLE_JIT
                /* This will throw the type load exception when the wrapper is compiled */
                mono_mb_emit_byte (mb, CEE_LDNULL);
@@ -10514,6 +10497,18 @@ mono_marshal_get_array_accessor_wrapper (MonoMethod *method)
        return res;     
 }
 
+#ifndef HOST_WIN32
+static inline void*
+mono_marshal_alloc_co_task_mem (size_t size)
+{
+       if ((gulong)size == 0)
+               /* This returns a valid pointer for size 0 on MS.NET */
+               size = 4;
+
+       return g_try_malloc ((gulong)size);
+}
+#endif
+
 void*
 mono_marshal_alloc (gulong size, MonoError *error)
 {
@@ -10521,13 +10516,10 @@ mono_marshal_alloc (gulong size, MonoError *error)
 
        mono_error_init (error);
 
-#ifdef HOST_WIN32
-       res = CoTaskMemAlloc (size);
-#else
-       res = g_try_malloc ((gulong)size);
+       res = mono_marshal_alloc_co_task_mem (size);
        if (!res)
-               mono_error_set_out_of_memory (error, "Could not allocate %i bytes", size);
-#endif
+               mono_error_set_out_of_memory (error, "Could not allocate %lu bytes", size);
+
        return res;
 }
 
@@ -10545,14 +10537,19 @@ ves_icall_marshal_alloc (gulong size)
        return ret;
 }
 
-void
-mono_marshal_free (gpointer ptr)
+#ifndef HOST_WIN32
+static inline void
+mono_marshal_free_co_task_mem (void *ptr)
 {
-#ifdef HOST_WIN32
-       CoTaskMemFree (ptr);
-#else
        g_free (ptr);
+       return;
+}
 #endif
+
+void
+mono_marshal_free (gpointer ptr)
+{
+       mono_marshal_free_co_task_mem (ptr);
 }
 
 void
@@ -10951,35 +10948,14 @@ ves_icall_System_Runtime_InteropServices_Marshal_OffsetOf (MonoReflectionType *t
        return info->fields [match_index].offset;
 }
 
+#ifndef HOST_WIN32
 gpointer
 ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalAnsi (MonoString *string)
 {
        MonoError error;
-#ifdef HOST_WIN32
-       char* tres, *ret;
-       size_t len;
-       tres = mono_string_to_utf8_checked (string, &error);
-       if (mono_error_set_pending_exception (&error))
-               return NULL;
-       if (!tres)
-               return tres;
-
-       /*
-        * mono_string_to_utf8_checked() returns a memory area at least as large as the size of the
-        * MonoString, even if it contains NULL characters. The copy we allocate here has to be equally
-        * large.
-        */
-       len = MAX (strlen (tres) + 1, string->length);
-       ret = ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (len);
-       memcpy (ret, tres, len);
-       g_free (tres);
-       return ret;
-
-#else
        char *ret = mono_string_to_utf8_checked (string, &error);
        mono_error_set_pending_exception (&error);
        return ret;
-#endif
 }
 
 gpointer
@@ -10988,17 +10964,14 @@ ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalUni (MonoString
        if (string == NULL)
                return NULL;
        else {
-#ifdef TARGET_WIN32
-               gunichar2 *res = ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal 
-                       ((mono_string_length (string) + 1) * 2);
-#else
                gunichar2 *res = (gunichar2 *)g_malloc ((mono_string_length (string) + 1) * 2);
-#endif
+
                memcpy (res, mono_string_chars (string), mono_string_length (string) * 2);
                res [mono_string_length (string)] = 0;
                return res;
        }
 }
+#endif /* !HOST_WIN32 */
 
 static void
 mono_struct_delete_old (MonoClass *klass, char *ptr)
@@ -11067,6 +11040,14 @@ ves_icall_System_Runtime_InteropServices_Marshal_DestroyStructure (gpointer src,
        mono_struct_delete_old (klass, (char *)src);
 }
 
+#ifndef HOST_WIN32
+static inline void *
+mono_marshal_alloc_hglobal (size_t size)
+{
+       return g_try_malloc (size);
+}
+#endif
+
 void*
 ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (gpointer size)
 {
@@ -11077,11 +11058,8 @@ ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (gpointer size)
                /* This returns a valid pointer for size 0 on MS.NET */
                s = 4;
 
-#ifdef HOST_WIN32
-       res = GlobalAlloc (GMEM_FIXED, s);
-#else
-       res = g_try_malloc (s);
-#endif
+       res = mono_marshal_alloc_hglobal (s);
+
        if (!res) {
                mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
                return NULL;
@@ -11090,6 +11068,14 @@ ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (gpointer size)
        return res;
 }
 
+#ifndef HOST_WIN32
+static inline gpointer
+mono_marshal_realloc_hglobal (gpointer ptr, size_t size)
+{
+       return g_try_realloc (ptr, size);
+}
+#endif
+
 gpointer
 ves_icall_System_Runtime_InteropServices_Marshal_ReAllocHGlobal (gpointer ptr, gpointer size)
 {
@@ -11101,11 +11087,8 @@ ves_icall_System_Runtime_InteropServices_Marshal_ReAllocHGlobal (gpointer ptr, g
                return NULL;
        }
 
-#ifdef HOST_WIN32
-       res = GlobalReAlloc (ptr, s, GMEM_MOVEABLE);
-#else
-       res = g_try_realloc (ptr, s);
-#endif
+       res = mono_marshal_realloc_hglobal (ptr, s);
+
        if (!res) {
                mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
                return NULL;
@@ -11114,30 +11097,26 @@ ves_icall_System_Runtime_InteropServices_Marshal_ReAllocHGlobal (gpointer ptr, g
        return res;
 }
 
-void
-ves_icall_System_Runtime_InteropServices_Marshal_FreeHGlobal (void *ptr)
+#ifndef HOST_WIN32
+static inline void
+mono_marshal_free_hglobal (gpointer ptr)
 {
-#ifdef HOST_WIN32
-       GlobalFree (ptr);
-#else
        g_free (ptr);
+       return;
+}
 #endif
+
+void
+ves_icall_System_Runtime_InteropServices_Marshal_FreeHGlobal (void *ptr)
+{
+       mono_marshal_free_hglobal (ptr);
 }
 
 void*
 ves_icall_System_Runtime_InteropServices_Marshal_AllocCoTaskMem (int size)
 {
-       void *res;
+       void *res = mono_marshal_alloc_co_task_mem (size);
 
-#ifdef HOST_WIN32
-       res = CoTaskMemAlloc (size);
-#else
-       if ((gulong)size == 0)
-               /* This returns a valid pointer for size 0 on MS.NET */
-               size = 4;
-
-       res = g_try_malloc ((gulong)size);
-#endif
        if (!res) {
                mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
                return NULL;
@@ -11148,23 +11127,23 @@ ves_icall_System_Runtime_InteropServices_Marshal_AllocCoTaskMem (int size)
 void
 ves_icall_System_Runtime_InteropServices_Marshal_FreeCoTaskMem (void *ptr)
 {
-#ifdef HOST_WIN32
-       CoTaskMemFree (ptr);
-#else
-       g_free (ptr);
-#endif
+       mono_marshal_free_co_task_mem (ptr);
+       return;
 }
 
+#ifndef HOST_WIN32
+static inline gpointer
+mono_marshal_realloc_co_task_mem (gpointer ptr, size_t size)
+{
+       return g_try_realloc (ptr, (gulong)size);
+}
+#endif
+
 gpointer
 ves_icall_System_Runtime_InteropServices_Marshal_ReAllocCoTaskMem (gpointer ptr, int size)
 {
-       void *res;
+       void *res = mono_marshal_realloc_co_task_mem (ptr, size);
 
-#ifdef HOST_WIN32
-       res = CoTaskMemRealloc (ptr, size);
-#else
-       res = g_try_realloc (ptr, (gulong)size);
-#endif
        if (!res) {
                mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
                return NULL;
@@ -11323,6 +11302,9 @@ mono_marshal_load_type_info (MonoClass* klass)
                j++;
        }
 
+       if (klass->byval_arg.type == MONO_TYPE_PTR)
+               info->native_size = sizeof (gpointer);
+
        if (layout != TYPE_ATTRIBUTE_AUTO_LAYOUT) {
                info->native_size = MAX (native_size, info->native_size);
                /*
index b1ea15c1f22a611073b76af96b4ffc94dc614d2f..4896a237fe49060fcad67b280e3ac7c9820dc638 100644 (file)
@@ -57,6 +57,12 @@ g_slist_append_mempool (MonoMemPool *mp, GSList *list, gpointer data)
                return new_list;
 }
 
+char*
+mono_mempool_strdup_vprintf (MonoMemPool *pool, const char *format, va_list args);
+
+char*
+mono_mempool_strdup_printf (MonoMemPool *pool, const char *format, ...) MONO_ATTR_FORMAT_PRINTF(2,3);;
+
 long
 mono_mempool_get_bytes_allocated (void);
 
index 214c9e2128fd5349d51d9d9f46c6e542e9751db3..7a871f034bfd58b28de0092507c84d2cc6c41b37 100644 (file)
@@ -198,25 +198,27 @@ static mono_mutex_t mempool_tracing_lock;
 static void
 mono_backtrace (int size)
 {
-        void *array[BACKTRACE_DEPTH];
-        char **names;
-        int i, symbols;
-        static gboolean inited;
-
-        if (!inited) {
-            mono_os_mutex_init_recursive (&mempool_tracing_lock);
-            inited = TRUE;
-        }
-
-        mono_os_mutex_lock (&mempool_tracing_lock);
-        g_print ("Allocating %d bytes\n", size);
-        symbols = backtrace (array, BACKTRACE_DEPTH);
-        names = backtrace_symbols (array, symbols);
-        for (i = 1; i < symbols; ++i) {
-                g_print ("\t%s\n", names [i]);
-        }
-        g_free (names);
-        mono_os_mutex_unlock (&mempool_tracing_lock);
+       void *array[BACKTRACE_DEPTH];
+       char **names;
+       int i, symbols;
+       static gboolean inited;
+
+       if (!inited) {
+               mono_os_mutex_init_recursive (&mempool_tracing_lock);
+               inited = TRUE;
+       }
+
+       mono_os_mutex_lock (&mempool_tracing_lock);
+       g_print ("Allocating %d bytes\n", size);
+       MONO_ENTER_GC_SAFE;
+       symbols = backtrace (array, BACKTRACE_DEPTH);
+       names = backtrace_symbols (array, symbols);
+       MONO_EXIT_GC_SAFE;
+       for (i = 1; i < symbols; ++i) {
+               g_print ("\t%s\n", names [i]);
+       }
+       g_free (names);
+       mono_os_mutex_unlock (&mempool_tracing_lock);
 }
 
 #endif
@@ -381,6 +383,35 @@ mono_mempool_strdup (MonoMemPool *pool,
        return res;
 }
 
+char*
+mono_mempool_strdup_vprintf (MonoMemPool *pool, const char *format, va_list args)
+{
+       size_t buflen;
+       char *buf;
+       va_list args2;
+       va_copy (args2, args);
+       int len = vsnprintf (NULL, 0, format, args2);
+       va_end (args2);
+
+       if (len >= 0 && (buf = (char*)mono_mempool_alloc (pool, (buflen = (size_t) (len + 1)))) != NULL) {
+               vsnprintf (buf, buflen, format, args);
+       } else {
+               buf = NULL;
+       }
+       return buf;
+}
+
+char*
+mono_mempool_strdup_printf (MonoMemPool *pool, const char *format, ...)
+{
+       char *buf;
+       va_list args;
+       va_start (args, format);
+       buf = mono_mempool_strdup_vprintf (pool, format, args);
+       va_end (args);
+       return buf;
+}
+
 /**
  * mono_mempool_get_allocated:
  *
index a1b9eb841781775dcf0fdc3cc5d768ddcfde08e8..a68897538aec5f910d666a786c38532051f87d5d 100644 (file)
@@ -175,10 +175,12 @@ typedef struct {
 
 struct _MonoImage {
        /*
-        * The number of assemblies which reference this MonoImage though their 'image'
-        * field plus the number of images which reference this MonoImage through their 
-        * 'modules' field, plus the number of threads holding temporary references to
-        * this image between calls of mono_image_open () and mono_image_close ().
+        * This count is incremented during these situations:
+        *   - An assembly references this MonoImage though its 'image' field
+        *   - This MonoImage is present in the 'files' field of an image
+        *   - This MonoImage is present in the 'modules' field of an image
+        *   - A thread is holding a temporary reference to this MonoImage between
+        *     calls to mono_image_open and mono_image_close ()
         */
        int   ref_count;
 
@@ -258,16 +260,16 @@ struct _MonoImage {
        MonoAssembly **references;
        int nreferences;
 
-       /* Code files in the assembly. */
+       /* Code files in the assembly. The main assembly has a "file" table and also a "module"
+        * table, where the module table is a subset of the file table. We track both lists,
+        * and because we can lazy-load them at different times we reference-increment both.
+        */
        MonoImage **modules;
        guint32 module_count;
        gboolean *modules_loaded;
 
-       /*
-        * Files in the assembly. Items are either NULL or alias items in modules, so this does not impact ref_count.
-        * Protected by the image lock.
-        */
        MonoImage **files;
+       guint32 file_count;
 
        gpointer aot_module;
 
@@ -497,7 +499,6 @@ struct _MonoDynamicImage {
        GHashTable *method_aux_hash;
        GHashTable *vararg_aux_hash;
        MonoGHashTable *generic_def_objects;
-       MonoGHashTable *methodspec;
        /*
         * Maps final token values to the object they describe.
         */
@@ -637,6 +638,12 @@ mono_image_alloc0 (MonoImage *image, guint size);
 char*
 mono_image_strdup (MonoImage *image, const char *s);
 
+char*
+mono_image_strdup_vprintf (MonoImage *image, const char *format, va_list args);
+
+char*
+mono_image_strdup_printf (MonoImage *image, const char *format, ...) MONO_ATTR_FORMAT_PRINTF(2,3);;
+
 GList*
 g_list_prepend_image (MonoImage *image, GList *list, gpointer data);
 
index 27115ccc9c1b1e384c9245ff8e976882159a9ed1..f9e2bc514889b5f1fb78f1898467f7bbc2408ce1 100644 (file)
@@ -2789,6 +2789,9 @@ free_inflated_method (MonoMethodInflated *imethod)
        if (method->signature)
                mono_metadata_free_inflated_signature (method->signature);
 
+       if (method->wrapper_type)
+               g_free (((MonoMethodWrapper*)method)->method_data);
+
        g_free (method);
 }
 
diff --git a/mono/metadata/mono-security-windows-internals.h b/mono/metadata/mono-security-windows-internals.h
new file mode 100644 (file)
index 0000000..a7cc247
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#ifndef __MONO_METADATA_MONO_SECURITY_WINDOWS_INTERNALS_H__
+#define __MONO_METADATA_MONO_SECURITY_WINDOWS_INTERNALS_H__
+
+#include <config.h>
+#include <glib.h>
+
+#ifdef HOST_WIN32
+#include "mono/metadata/security.h"
+#include "mono/metadata/object.h"
+#include "mono/metadata/object-internals.h"
+#include "mono/metadata/metadata.h"
+#include "mono/metadata/metadata-internals.h"
+
+gint32
+mono_security_win_get_token_name (gpointer token, gunichar2 ** uniname);
+
+gboolean
+mono_security_win_is_machine_protected (gunichar2 *path);
+
+gboolean
+mono_security_win_is_user_protected (gunichar2 *path);
+
+gboolean
+mono_security_win_protect_machine (gunichar2 *path);
+
+gboolean
+mono_security_win_protect_user (gunichar2 *path);
+#endif /* HOST_WIN32 */
+
+#endif /* __MONO_METADATA_MONO_SECURITY_WINDOWS_INTERNALS_H__ */
diff --git a/mono/metadata/mono-security-windows-uwp.c b/mono/metadata/mono-security-windows-uwp.c
new file mode 100644 (file)
index 0000000..791e76c
--- /dev/null
@@ -0,0 +1,179 @@
+/*
+ * mono-security-windows-uwp.c: UWP security support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+
+#if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
+#include <Windows.h>
+#include "mono/metadata/mono-security-windows-internals.h"
+
+gpointer
+ves_icall_System_Security_Principal_WindowsIdentity_GetCurrentToken (void)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("OpenThreadToken, OpenProcessToken");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "OpenThreadToken, OpenProcessToken");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return NULL;
+}
+
+MonoArray*
+ves_icall_System_Security_Principal_WindowsIdentity_GetRoles (gpointer token)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("GetTokenInformation");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "GetTokenInformation");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return NULL;
+}
+
+gpointer
+ves_icall_System_Security_Principal_WindowsImpersonationContext_DuplicateToken (gpointer token)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("DuplicateToken");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "DuplicateToken");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return NULL;
+}
+
+gboolean
+ves_icall_System_Security_Principal_WindowsImpersonationContext_SetCurrentToken (gpointer token)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("ImpersonateLoggedOnUser");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "ImpersonateLoggedOnUser");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+gboolean
+ves_icall_System_Security_Principal_WindowsImpersonationContext_RevertToSelf (void)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("RevertToSelf");
+
+       mono_error_set_not_supported(&mono_error, G_UNSUPPORTED_API, "RevertToSelf");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+gint32
+mono_security_win_get_token_name (gpointer token, gunichar2 ** uniname)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("GetTokenInformation");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "GetTokenInformation");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return 0;
+}
+
+gboolean
+mono_security_win_is_machine_protected (gunichar2 *path)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("GetNamedSecurityInfo, LocalFree");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "GetNamedSecurityInfo, LocalFree");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+gboolean
+mono_security_win_is_user_protected (gunichar2 *path)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("GetNamedSecurityInfo, LocalFree");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "GetNamedSecurityInfo, LocalFree");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+gboolean
+mono_security_win_protect_machine (gunichar2 *path)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("BuildTrusteeWithSid, SetEntriesInAcl, SetNamedSecurityInfo, LocalFree, FreeSid");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "BuildTrusteeWithSid, SetEntriesInAcl, SetNamedSecurityInfo, LocalFree, FreeSid");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+gboolean
+mono_security_win_protect_user (gunichar2 *path)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("BuildTrusteeWithSid, SetEntriesInAcl, SetNamedSecurityInfo, LocalFree");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "BuildTrusteeWithSid, SetEntriesInAcl, SetNamedSecurityInfo, LocalFree");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+#else /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_mono_security_windows_uwp_quiet_lnk4221(void) {}
+#endif
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
diff --git a/mono/metadata/mono-security-windows.c b/mono/metadata/mono-security-windows.c
new file mode 100644 (file)
index 0000000..fda26d3
--- /dev/null
@@ -0,0 +1,495 @@
+/*
+ * mono-security-windows.c: Windows security support.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#include <config.h>
+#include <glib.h>
+
+#if defined(HOST_WIN32)
+#include <WinSock2.h>
+#include <Windows.h>
+#include "mono/metadata/mono-security-windows-internals.h"
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+#include <aclapi.h>
+#include <accctrl.h>
+#endif
+
+#ifndef PROTECTED_DACL_SECURITY_INFORMATION
+#define PROTECTED_DACL_SECURITY_INFORMATION    0x80000000L
+#endif
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+static gunichar2*
+GetSidName (gunichar2 *server, PSID sid, gint32 *size)
+{
+       gunichar2 *uniname = NULL;
+       DWORD cchName = 0;
+       DWORD cchDomain = 0;
+       SID_NAME_USE peUse; /* out */
+
+       LookupAccountSid (server, sid, NULL, &cchName, NULL,
+               &cchDomain, &peUse);
+
+       if ((cchName > 0) && (cchDomain > 0)) {
+               gunichar2 *user = g_malloc0 ((cchName + 1) * 2);
+               gunichar2 *domain = g_malloc0 ((cchDomain + 1) * 2);
+
+               LookupAccountSid (server, sid, user, &cchName, domain,
+                       &cchDomain, &peUse);
+
+               if (cchName > 0) {
+                       if (cchDomain > 0) {
+                               /* domain/machine name included (+ sepearator) */
+                               *size = cchName + cchDomain + 1;
+                               uniname = g_malloc0 ((*size + 1) * 2);
+                               memcpy (uniname, domain, cchDomain * 2);
+                               *(uniname + cchDomain) = '\\';
+                               memcpy (uniname + cchDomain + 1, user, cchName * 2);
+                               g_free (user);
+                       }
+                       else {
+                               /* no domain / machine */
+                               *size = cchName;
+                               uniname = user;
+                       }
+               }
+               else {
+                       /* nothing -> return NULL */
+                       g_free (user);
+               }
+
+               g_free (domain);
+       }
+
+       return uniname;
+}
+
+gpointer
+ves_icall_System_Security_Principal_WindowsIdentity_GetCurrentToken (void)
+{
+       gpointer token = NULL;
+
+       /* Note: This isn't a copy of the Token - we must not close it!!!
+        * http://www.develop.com/kbrown/book/html/whatis_windowsprincipal.html
+        */
+
+       /* thread may be impersonating somebody */
+       if (OpenThreadToken (GetCurrentThread (), MAXIMUM_ALLOWED, 1, &token) == 0) {
+               /* if not take the process identity */
+               OpenProcessToken (GetCurrentProcess (), MAXIMUM_ALLOWED, &token);
+       }
+
+       return token;
+}
+
+gint32
+mono_security_win_get_token_name (gpointer token, gunichar2 ** uniname)
+{
+       gint32 size = 0;
+
+       GetTokenInformation (token, TokenUser, NULL, size, (PDWORD)&size);
+       if (size > 0) {
+               TOKEN_USER *tu = g_malloc0 (size);
+               if (GetTokenInformation (token, TokenUser, tu, size, (PDWORD)&size)) {
+                       *uniname = GetSidName (NULL, tu->User.Sid, &size);
+               }
+               g_free (tu);
+       }
+
+       return size;
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+MonoString*
+ves_icall_System_Security_Principal_WindowsIdentity_GetTokenName (gpointer token)
+{
+       MonoError error;
+       MonoString *result = NULL;
+       gunichar2 *uniname = NULL;
+       gint32 size = 0;
+
+       mono_error_init (&error);
+
+       size = mono_security_win_get_token_name (token, &uniname);
+
+       if (size > 0) {
+               result = mono_string_new_utf16_checked (mono_domain_get (), uniname, size, &error);
+       }
+       else
+               result = mono_string_new (mono_domain_get (), "");
+
+       if (uniname)
+               g_free (uniname);
+
+       mono_error_set_pending_exception (&error);
+       return result;
+}
+
+gpointer
+ves_icall_System_Security_Principal_WindowsIdentity_GetUserToken (MonoString *username)
+{
+       gpointer token = NULL;
+
+       /* TODO: MS has something like this working in Windows 2003 (client and
+        * server) but works only for domain accounts (so it's quite limiting).
+        * http://www.develop.com/kbrown/book/html/howto_logonuser.html
+        */
+       g_warning ("Unsupported on Win32 (anyway requires W2K3 minimum)");
+       return token;
+}
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+MonoArray*
+ves_icall_System_Security_Principal_WindowsIdentity_GetRoles (gpointer token)
+{
+       MonoError error;
+       MonoArray *array = NULL;
+       MonoDomain *domain = mono_domain_get ();
+
+       gint32 size = 0;
+
+       GetTokenInformation (token, TokenGroups, NULL, size, (PDWORD)&size);
+       if (size > 0) {
+               TOKEN_GROUPS *tg = g_malloc0 (size);
+               if (GetTokenInformation (token, TokenGroups, tg, size, (PDWORD)&size)) {
+                       int i=0;
+                       int num = tg->GroupCount;
+
+                       array = mono_array_new_checked (domain, mono_get_string_class (), num, &error);
+                       if (mono_error_set_pending_exception (&error)) {
+                               g_free (tg);
+                               return NULL;
+                       }
+
+                       for (i=0; i < num; i++) {
+                               gint32 size = 0;
+                               gunichar2 *uniname = GetSidName (NULL, tg->Groups [i].Sid, &size);
+
+                               if (uniname) {
+                                       MonoString *str = mono_string_new_utf16_checked (domain, uniname, size, &error);
+                                       if (!is_ok (&error)) {
+                                               g_free (uniname);
+                                               g_free (tg);
+                                               mono_error_set_pending_exception (&error);
+                                               return NULL;
+                                       }
+                                       mono_array_setref (array, i, str);
+                                       g_free (uniname);
+                               }
+                       }
+               }
+               g_free (tg);
+       }
+
+       if (!array) {
+               /* return empty array of string, i.e. string [0] */
+               array = mono_array_new_checked (domain, mono_get_string_class (), 0, &error);
+               mono_error_set_pending_exception (&error);
+       }
+       return array;
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+gboolean
+ves_icall_System_Security_Principal_WindowsImpersonationContext_CloseToken (gpointer token)
+{
+       gboolean result = TRUE;
+       result = (CloseHandle (token) != 0);
+       return result;
+}
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+gpointer
+ves_icall_System_Security_Principal_WindowsImpersonationContext_DuplicateToken (gpointer token)
+{
+       gpointer dupe = NULL;
+
+       if (DuplicateToken (token, SecurityImpersonation, &dupe) == 0) {
+               dupe = NULL;
+       }
+       return dupe;
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+gboolean
+ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupId (gpointer user, gpointer group)
+{
+       gboolean result = FALSE;
+
+       /* The convertion from an ID to a string is done in managed code for Windows */
+       g_warning ("IsMemberOfGroupId should never be called on Win32");
+       return result;
+}
+
+gboolean
+ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupName (gpointer user, MonoString *group)
+{
+       gboolean result = FALSE;
+
+       /* Windows version use a cache built using WindowsIdentity._GetRoles */
+       g_warning ("IsMemberOfGroupName should never be called on Win32");
+       return result;
+}
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+static PSID
+GetAdministratorsSid (void)
+{
+       SID_IDENTIFIER_AUTHORITY admins = { SECURITY_NT_AUTHORITY };
+       PSID pSid = NULL;
+       if (!AllocateAndInitializeSid (&admins, 2, SECURITY_BUILTIN_DOMAIN_RID,
+               DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &pSid))
+               return NULL;
+       /* Note: this SID must be freed with FreeSid () */
+       return pSid;
+}
+
+static PSID
+GetEveryoneSid (void)
+{
+       SID_IDENTIFIER_AUTHORITY everyone = { SECURITY_WORLD_SID_AUTHORITY };
+       PSID pSid = NULL;
+       if (!AllocateAndInitializeSid (&everyone, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &pSid))
+               return NULL;
+       /* Note: this SID must be freed with FreeSid () */
+       return pSid;
+}
+
+static PSID
+GetCurrentUserSid (void)
+{
+       PSID sid = NULL;
+       guint32 size = 0;
+       gpointer token = ves_icall_System_Security_Principal_WindowsIdentity_GetCurrentToken ();
+
+       GetTokenInformation (token, TokenUser, NULL, size, (PDWORD)&size);
+       if (size > 0) {
+               TOKEN_USER *tu = g_malloc0 (size);
+               if (GetTokenInformation (token, TokenUser, tu, size, (PDWORD)&size)) {
+                       DWORD length = GetLengthSid (tu->User.Sid);
+                       sid = (PSID) g_malloc0 (length);
+                       if (!CopySid (length, sid, tu->User.Sid)) {
+                               g_free (sid);
+                               sid = NULL;
+                       }
+               }
+               g_free (tu);
+       }
+       /* Note: this SID must be freed with g_free () */
+       return sid;
+}
+
+static ACCESS_MASK
+GetRightsFromSid (PSID sid, PACL acl)
+{
+       ACCESS_MASK rights = 0;
+       TRUSTEE trustee;
+
+       BuildTrusteeWithSidW (&trustee, sid);
+       if (GetEffectiveRightsFromAcl (acl, &trustee, &rights) != ERROR_SUCCESS)
+               return 0;
+
+       return rights;
+}
+
+gboolean
+mono_security_win_is_machine_protected (gunichar2 *path)
+{
+       gboolean success = FALSE;
+       PACL pDACL = NULL;
+       PSECURITY_DESCRIPTOR pSD = NULL;
+       PSID pEveryoneSid = NULL;
+
+       DWORD dwRes = GetNamedSecurityInfoW (path, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, &pSD);
+       if (dwRes != ERROR_SUCCESS)
+               return FALSE;
+
+       /* We check that Everyone is still limited to READ-ONLY -
+       but not if new entries have been added by an Administrator */
+
+       pEveryoneSid = GetEveryoneSid ();
+       if (pEveryoneSid) {
+               ACCESS_MASK rights = GetRightsFromSid (pEveryoneSid, pDACL);
+               /* http://msdn.microsoft.com/library/en-us/security/security/generic_access_rights.asp?frame=true */
+               success = (rights == (READ_CONTROL | SYNCHRONIZE | FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES));
+               FreeSid (pEveryoneSid);
+       }
+       /* Note: we don't need to check our own access -
+       we'll know soon enough when reading the file */
+
+       if (pSD)
+               LocalFree (pSD);
+
+       return success;
+}
+
+gboolean
+mono_security_win_is_user_protected (gunichar2 *path)
+{
+       gboolean success = FALSE;
+       PACL pDACL = NULL;
+       PSID pEveryoneSid = NULL;
+       PSECURITY_DESCRIPTOR pSecurityDescriptor = NULL;
+
+       DWORD dwRes = GetNamedSecurityInfoW (path, SE_FILE_OBJECT,
+               DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, &pSecurityDescriptor);
+       if (dwRes != ERROR_SUCCESS)
+               return FALSE;
+
+       /* We check that our original entries in the ACL are in place -
+       but not if new entries have been added by the user */
+
+       /* Everyone should be denied */
+       pEveryoneSid = GetEveryoneSid ();
+       if (pEveryoneSid) {
+               ACCESS_MASK rights = GetRightsFromSid (pEveryoneSid, pDACL);
+               success = (rights == 0);
+               FreeSid (pEveryoneSid);
+       }
+       /* Note: we don't need to check our own access -
+       we'll know soon enough when reading the file */
+
+       if (pSecurityDescriptor)
+               LocalFree (pSecurityDescriptor);
+
+       return success;
+}
+
+gboolean
+mono_security_win_protect_machine (gunichar2 *path)
+{
+       PSID pEveryoneSid = GetEveryoneSid ();
+       PSID pAdminsSid = GetAdministratorsSid ();
+       DWORD retval = -1;
+
+       if (pEveryoneSid && pAdminsSid) {
+               PACL pDACL = NULL;
+               EXPLICIT_ACCESS ea [2];
+               ZeroMemory (&ea, 2 * sizeof (EXPLICIT_ACCESS));
+
+               /* grant all access to the BUILTIN\Administrators group */
+               BuildTrusteeWithSidW (&ea [0].Trustee, pAdminsSid);
+               ea [0].grfAccessPermissions = GENERIC_ALL;
+               ea [0].grfAccessMode = SET_ACCESS;
+               ea [0].grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
+               ea [0].Trustee.TrusteeForm = TRUSTEE_IS_SID;
+               ea [0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
+
+               /* read-only access everyone */
+               BuildTrusteeWithSidW (&ea [1].Trustee, pEveryoneSid);
+               ea [1].grfAccessPermissions = GENERIC_READ;
+               ea [1].grfAccessMode = SET_ACCESS;
+               ea [1].grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
+               ea [1].Trustee.TrusteeForm = TRUSTEE_IS_SID;
+               ea [1].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
+
+               retval = SetEntriesInAcl (2, ea, NULL, &pDACL);
+               if (retval == ERROR_SUCCESS) {
+                       /* with PROTECTED_DACL_SECURITY_INFORMATION we */
+                       /* remove any existing ACL (like inherited ones) */
+                       retval = SetNamedSecurityInfo (path, SE_FILE_OBJECT,
+                               DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
+                               NULL, NULL, pDACL, NULL);
+               }
+               if (pDACL)
+                       LocalFree (pDACL);
+       }
+
+       if (pEveryoneSid)
+               FreeSid (pEveryoneSid);
+       if (pAdminsSid)
+               FreeSid (pAdminsSid);
+       return (retval == ERROR_SUCCESS);
+}
+
+gboolean
+mono_security_win_protect_user (gunichar2 *path)
+{
+       DWORD retval = -1;
+
+       PSID pCurrentSid = GetCurrentUserSid ();
+       if (pCurrentSid) {
+               PACL pDACL = NULL;
+               EXPLICIT_ACCESS ea;
+               ZeroMemory (&ea, sizeof (EXPLICIT_ACCESS));
+
+               /* grant exclusive access to the current user */
+               BuildTrusteeWithSidW (&ea.Trustee, pCurrentSid);
+               ea.grfAccessPermissions = GENERIC_ALL;
+               ea.grfAccessMode = SET_ACCESS;
+               ea.grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
+               ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
+               ea.Trustee.TrusteeType = TRUSTEE_IS_USER;
+
+               retval = SetEntriesInAcl (1, &ea, NULL, &pDACL);
+               if (retval == ERROR_SUCCESS) {
+                       /* with PROTECTED_DACL_SECURITY_INFORMATION we
+                          remove any existing ACL (like inherited ones) */
+                       retval = SetNamedSecurityInfo (path, SE_FILE_OBJECT,
+                               DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
+                               NULL, NULL, pDACL, NULL);
+               }
+
+               if (pDACL)
+                       LocalFree (pDACL);
+               g_free (pCurrentSid); /* g_malloc0 */
+       }
+
+       return (retval == ERROR_SUCCESS);
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+MonoBoolean
+ves_icall_Mono_Security_Cryptography_KeyPairPersistence_CanSecure (MonoString *root)
+{
+       gint32 flags;
+
+       /* ACL are nice... unless you have FAT or other uncivilized filesystem */
+       if (!GetVolumeInformation (mono_string_chars (root), NULL, 0, NULL, NULL, (LPDWORD)&flags, NULL, 0))
+               return FALSE;
+       return ((flags & FS_PERSISTENT_ACLS) == FS_PERSISTENT_ACLS);
+}
+
+MonoBoolean
+ves_icall_Mono_Security_Cryptography_KeyPairPersistence_IsMachineProtected (MonoString *path)
+{
+       gboolean ret = FALSE;
+
+       /* no one, but the owner, should have write access to the directory */
+       ret = mono_security_win_is_machine_protected (mono_string_chars (path));
+       return (MonoBoolean)ret;
+}
+
+MonoBoolean
+ves_icall_Mono_Security_Cryptography_KeyPairPersistence_IsUserProtected (MonoString *path)
+{
+       gboolean ret = FALSE;
+
+       /* no one, but the user, should have access to the directory */
+       ret = mono_security_win_is_user_protected (mono_string_chars (path));
+       return (MonoBoolean)ret;
+}
+
+MonoBoolean
+ves_icall_Mono_Security_Cryptography_KeyPairPersistence_ProtectMachine (MonoString *path)
+{
+       gboolean ret = FALSE;
+
+       /* read/write to owner, read to everyone else */
+       ret = mono_security_win_protect_machine (mono_string_chars (path));
+       return (MonoBoolean)ret;
+}
+
+MonoBoolean
+ves_icall_Mono_Security_Cryptography_KeyPairPersistence_ProtectUser (MonoString *path)
+{
+       gboolean ret = FALSE;
+
+       /* read/write to user, no access to everyone else */
+       ret = mono_security_win_protect_user (mono_string_chars (path));
+       return (MonoBoolean)ret;
+}
+#endif /* HOST_WIN32 */
index 865b9ca1e04236ec1a7c7840436fca8c6e02de8a..09b8cd44abe6deaba2428602aa257022dbf21a88 100644 (file)
 #include <mono/io-layer/io-layer.h>
 #include <mono/utils/strenc.h>
 
-#ifdef HOST_WIN32
-
-#include <aclapi.h>
-#include <accctrl.h>
-
-#ifndef PROTECTED_DACL_SECURITY_INFORMATION
-#define PROTECTED_DACL_SECURITY_INFORMATION    0x80000000L
-#endif
-
-#else
-
+#ifndef HOST_WIN32
 #include <config.h>
 #ifdef HAVE_GRP_H
 #include <grp.h>
 #endif
 
 #endif /* defined(__GNUC__) */
-
-#endif /* not HOST_WIN32 */
-
+#endif /* !HOST_WIN32 */
 
 /* internal functions - reuse driven */
 
-#ifdef HOST_WIN32
-
 /* ask a server to translate a SID into a textual representation */
-static gunichar2*
-GetSidName (gunichar2 *server, PSID sid, gint32 *size) 
-{
-       gunichar2 *uniname = NULL;
-       DWORD cchName = 0;
-       DWORD cchDomain = 0;
-       SID_NAME_USE peUse; /* out */
-
-       LookupAccountSid (server, sid, NULL, &cchName, NULL, 
-               &cchDomain, &peUse); 
-       
-       if ((cchName > 0) && (cchDomain > 0)) {
-               gunichar2 *user = g_malloc0 ((cchName + 1) * 2);
-               gunichar2 *domain = g_malloc0 ((cchDomain + 1) * 2);
-
-               LookupAccountSid (server, sid, user, &cchName, domain,
-                       &cchDomain, &peUse);
-
-               if (cchName > 0) {
-                       if (cchDomain > 0) {
-                               /* domain/machine name included (+ sepearator) */
-                               *size = cchName + cchDomain + 1;
-                               uniname = g_malloc0 ((*size + 1) * 2);
-                               memcpy (uniname, domain, cchDomain * 2);
-                               *(uniname + cchDomain) = '\\';
-                               memcpy (uniname + cchDomain + 1, user, cchName * 2);
-                               g_free (user);
-                       }
-                       else {
-                               /* no domain / machine */
-                               *size = cchName;
-                               uniname = user;
-                       }
-               }
-               else {
-                       /* nothing -> return NULL */
-                       g_free (user);
-               }
-
-               g_free (domain);
-       }
-
-       return uniname;
-}
-
-
-#else /* not HOST_WIN32 */
-
+#ifndef HOST_WIN32
 #define MONO_SYSCONF_DEFAULT_SIZE      ((size_t) 1024)
 
 /*
@@ -133,7 +72,6 @@ static size_t mono_sysconf (int name)
        return (size == -1) ? MONO_SYSCONF_DEFAULT_SIZE : size;
 }
 
-
 static gchar*
 GetTokenName (uid_t uid)
 {
@@ -174,7 +112,6 @@ GetTokenName (uid_t uid)
        return uname;
 }
 
-
 static gboolean
 IsMemberInList (uid_t user, struct group *g) 
 {
@@ -201,7 +138,6 @@ IsMemberInList (uid_t user, struct group *g)
        return result;
 }
 
-
 static gboolean
 IsDefaultGroup (uid_t user, gid_t group)
 {
@@ -241,7 +177,6 @@ IsDefaultGroup (uid_t user, gid_t group)
        return result;
 }
 
-
 static gboolean
 IsMemberOf (gid_t user, struct group *g) 
 {
@@ -255,37 +190,34 @@ IsMemberOf (gid_t user, struct group *g)
        /* is the user in the group list */
        return IsMemberInList (user, g);
 }
-
-#endif
-
+#endif /* !HOST_WIN32 */
 
 /* ICALLS */
 
-
 /* System.Security.Principal.WindowsIdentity */
 
-
+#ifndef HOST_WIN32
 gpointer
 ves_icall_System_Security_Principal_WindowsIdentity_GetCurrentToken (void)
 {
-       gpointer token = NULL;
+       return GINT_TO_POINTER (geteuid ());
+}
+
+static gint32
+internal_get_token_name (gpointer token, gunichar2 ** uniname)
+{
+       gint32 size = 0;
 
-#ifdef HOST_WIN32
-       /* Note: This isn't a copy of the Token - we must not close it!!!
-        * http://www.develop.com/kbrown/book/html/whatis_windowsprincipal.html
-        */
+       gchar *uname = GetTokenName ((uid_t) GPOINTER_TO_INT (token));
 
-       /* thread may be impersonating somebody */
-       if (OpenThreadToken (GetCurrentThread (), MAXIMUM_ALLOWED, 1, &token) == 0) {
-               /* if not take the process identity */
-               OpenProcessToken (GetCurrentProcess (), MAXIMUM_ALLOWED, &token);
+       if (uname) {
+               size = strlen (uname);
+               *uniname = g_utf8_to_utf16 (uname, size, NULL, NULL, NULL);
+               g_free (uname);
        }
-#else
-       token = GINT_TO_POINTER (geteuid ());
-#endif
-       return token;
-}
 
+       return size;
+}
 
 MonoString*
 ves_icall_System_Security_Principal_WindowsIdentity_GetTokenName (gpointer token)
@@ -296,24 +228,8 @@ ves_icall_System_Security_Principal_WindowsIdentity_GetTokenName (gpointer token
        gint32 size = 0;
 
        mono_error_init (&error);
-#ifdef HOST_WIN32
-       GetTokenInformation (token, TokenUser, NULL, size, (PDWORD)&size);
-       if (size > 0) {
-               TOKEN_USER *tu = g_malloc0 (size);
-               if (GetTokenInformation (token, TokenUser, tu, size, (PDWORD)&size)) {
-                       uniname = GetSidName (NULL, tu->User.Sid, &size);
-               }
-               g_free (tu);
-       }
-#else 
-       gchar *uname = GetTokenName ((uid_t) GPOINTER_TO_INT (token));
 
-       if (uname) {
-               size = strlen (uname);
-               uniname = g_utf8_to_utf16 (uname, size, NULL, NULL, NULL);
-               g_free (uname);
-       }
-#endif /* HOST_WIN32 */
+       size = internal_get_token_name (token, &uniname);
 
        if (size > 0) {
                result = mono_string_new_utf16_checked (mono_domain_get (), uniname, size, &error);
@@ -327,22 +243,12 @@ ves_icall_System_Security_Principal_WindowsIdentity_GetTokenName (gpointer token
        mono_error_set_pending_exception (&error);
        return result;
 }
+#endif  /* !HOST_WIN32 */
 
-
+#ifndef HOST_WIN32
 gpointer
 ves_icall_System_Security_Principal_WindowsIdentity_GetUserToken (MonoString *username)
 {
-#ifdef HOST_WIN32
-       gpointer token = NULL;
-
-       /* TODO: MS has something like this working in Windows 2003 (client and
-        * server) but works only for domain accounts (so it's quite limiting).
-        * http://www.develop.com/kbrown/book/html/howto_logonuser.html
-        */
-       g_warning ("Unsupported on Win32 (anyway requires W2K3 minimum)");
-
-#else /* HOST_WIN32*/
-
 #ifdef HAVE_GETPWNAM_R
        struct passwd pwd;
        size_t fbufsize;
@@ -380,59 +286,26 @@ ves_icall_System_Security_Principal_WindowsIdentity_GetUserToken (MonoString *us
        g_free (fbuf);
 #endif
        g_free (utf8_name);
-#endif
+
        return token;
 }
-
+#endif /* HOST_WIN32 */
 
 /* http://www.dotnet247.com/247reference/msgs/39/195403.aspx
 // internal static string[] WindowsIdentity._GetRoles (IntPtr token)
 */
+
+#ifndef HOST_WIN32
 MonoArray*
-ves_icall_System_Security_Principal_WindowsIdentity_GetRoles (gpointer token) 
+ves_icall_System_Security_Principal_WindowsIdentity_GetRoles (gpointer token)
 {
        MonoError error;
        MonoArray *array = NULL;
-       MonoDomain *domain = mono_domain_get (); 
-#ifdef HOST_WIN32
-       gint32 size = 0;
-
-       GetTokenInformation (token, TokenGroups, NULL, size, (PDWORD)&size);
-       if (size > 0) {
-               TOKEN_GROUPS *tg = g_malloc0 (size);
-               if (GetTokenInformation (token, TokenGroups, tg, size, (PDWORD)&size)) {
-                       int i=0;
-                       int num = tg->GroupCount;
-
-                       array = mono_array_new_checked (domain, mono_get_string_class (), num, &error);
-                       if (mono_error_set_pending_exception (&error)) {
-                               g_free (tg);
-                               return NULL;
-                       }
+       MonoDomain *domain = mono_domain_get ();
 
-                       for (i=0; i < num; i++) {
-                               gint32 size = 0;
-                               gunichar2 *uniname = GetSidName (NULL, tg->Groups [i].Sid, &size);
-
-                               if (uniname) {
-                                       MonoString *str = mono_string_new_utf16_checked (domain, uniname, size, &error);
-                                       if (!is_ok (&error)) {
-                                               g_free (uniname);
-                                               g_free (tg);
-                                               mono_error_set_pending_exception (&error);
-                                               return NULL;
-                                       }
-                                       mono_array_setref (array, i, str);
-                                       g_free (uniname);
-                               }
-                       }
-               }
-               g_free (tg);
-       }
-#else
        /* POSIX-compliant systems should use IsMemberOfGroupId or IsMemberOfGroupName */
        g_warning ("WindowsIdentity._GetRoles should never be called on POSIX");
-#endif
+
        if (!array) {
                /* return empty array of string, i.e. string [0] */
                array = mono_array_new_checked (domain, mono_get_string_class (), 0, &error);
@@ -440,39 +313,27 @@ ves_icall_System_Security_Principal_WindowsIdentity_GetRoles (gpointer token)
        }
        return array;
 }
-
+#endif /* !HOST_WIN32 */
 
 /* System.Security.Principal.WindowsImpersonationContext */
 
-
+#ifndef HOST_WIN32
 gboolean
 ves_icall_System_Security_Principal_WindowsImpersonationContext_CloseToken (gpointer token)
 {
-       gboolean result = TRUE;
-
-#ifdef HOST_WIN32
-       result = (CloseHandle (token) != 0);
-#endif
-       return result;
+       return TRUE;
 }
+#endif /* !HOST_WIN32 */
 
-
+#ifndef HOST_WIN32
 gpointer
 ves_icall_System_Security_Principal_WindowsImpersonationContext_DuplicateToken (gpointer token)
 {
-       gpointer dupe = NULL;
-
-#ifdef HOST_WIN32
-       if (DuplicateToken (token, SecurityImpersonation, &dupe) == 0) {
-               dupe = NULL;
-       }
-#else
-       dupe = token;
-#endif
-       return dupe;
+       return token;
 }
+#endif /* !HOST_WIN32 */
 
-
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 gboolean
 ves_icall_System_Security_Principal_WindowsImpersonationContext_SetCurrentToken (gpointer token)
 {
@@ -480,28 +341,22 @@ ves_icall_System_Security_Principal_WindowsImpersonationContext_SetCurrentToken
        return (ImpersonateLoggedOnUser (token) != 0);
 }
 
-
 gboolean
 ves_icall_System_Security_Principal_WindowsImpersonationContext_RevertToSelf (void)
 {
        /* Posix version implemented in /mono/mono/io-layer/security.c */
        return (RevertToSelf () != 0);
 }
-
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
 
 /* System.Security.Principal.WindowsPrincipal */
 
+#ifndef HOST_WIN32
 gboolean
 ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupId (gpointer user, gpointer group)
 {
        gboolean result = FALSE;
 
-#ifdef HOST_WIN32
-       /* The convertion from an ID to a string is done in managed code for Windows */
-       g_warning ("IsMemberOfGroupId should never be called on Win32");
-
-#else /* HOST_WIN32 */
-
 #ifdef HAVE_GETGRGID_R
        struct group grp;
        size_t fbufsize;
@@ -533,22 +388,13 @@ ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupId (gpointer
        g_free (fbuf);
 #endif
 
-#endif /* HOST_WIN32 */
-
        return result;
 }
 
-
 gboolean
 ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupName (gpointer user, MonoString *group)
 {
        gboolean result = FALSE;
-
-#ifdef HOST_WIN32
-       /* Windows version use a cache built using WindowsIdentity._GetRoles */
-       g_warning ("IsMemberOfGroupName should never be called on Win32");
-
-#else /* HOST_WIN32 */
        gchar *utf8_groupname;
 
        utf8_groupname = mono_unicode_to_external (mono_string_chars (group));
@@ -581,232 +427,15 @@ ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupName (gpoint
 #endif
                g_free (utf8_groupname);
        }
-#endif /* HOST_WIN32 */
 
        return result;
 }
-
+#endif /* !HOST_WIN32 */
 
 /* Mono.Security.Cryptography IO related internal calls */
 
-#ifdef HOST_WIN32
-
-static PSID
-GetAdministratorsSid (void) 
-{
-       SID_IDENTIFIER_AUTHORITY admins = SECURITY_NT_AUTHORITY;
-       PSID pSid = NULL;
-       if (!AllocateAndInitializeSid (&admins, 2, SECURITY_BUILTIN_DOMAIN_RID, 
-               DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &pSid)) 
-               return NULL;
-       /* Note: this SID must be freed with FreeSid () */
-       return pSid;
-}
-
-
-static PSID
-GetEveryoneSid (void)
-{
-       SID_IDENTIFIER_AUTHORITY everyone = SECURITY_WORLD_SID_AUTHORITY;
-       PSID pSid = NULL;
-       if (!AllocateAndInitializeSid (&everyone, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &pSid))
-               return NULL;
-       /* Note: this SID must be freed with FreeSid () */
-       return pSid;
-}
-
-
-static PSID
-GetCurrentUserSid (void) 
-{
-       PSID sid = NULL;
-       guint32 size = 0;
-       gpointer token = ves_icall_System_Security_Principal_WindowsIdentity_GetCurrentToken ();
-
-       GetTokenInformation (token, TokenUser, NULL, size, (PDWORD)&size);
-       if (size > 0) {
-               TOKEN_USER *tu = g_malloc0 (size);
-               if (GetTokenInformation (token, TokenUser, tu, size, (PDWORD)&size)) {
-                       DWORD length = GetLengthSid (tu->User.Sid);
-                       sid = (PSID) g_malloc0 (length);
-                       if (!CopySid (length, sid, tu->User.Sid)) {
-                               g_free (sid);
-                               sid = NULL;
-                       }
-               }
-               g_free (tu);
-       }
-       /* Note: this SID must be freed with g_free () */
-       return sid;
-}
-
-
-static ACCESS_MASK
-GetRightsFromSid (PSID sid, PACL acl) 
-{
-       ACCESS_MASK rights = 0;
-       TRUSTEE trustee;
-
-       BuildTrusteeWithSidW (&trustee, sid);
-       if (GetEffectiveRightsFromAcl (acl, &trustee, &rights) != ERROR_SUCCESS)
-               return 0;
-
-       return rights;
-}
-
-
-static gboolean 
-IsMachineProtected (gunichar2 *path)
-{
-       gboolean success = FALSE;
-       PACL pDACL = NULL;
-       PSECURITY_DESCRIPTOR pSD = NULL;
-       PSID pEveryoneSid = NULL;
-
-       DWORD dwRes = GetNamedSecurityInfoW (path, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, &pSD);
-       if (dwRes != ERROR_SUCCESS)
-               return FALSE;
-
-       /* We check that Everyone is still limited to READ-ONLY -
-       but not if new entries have been added by an Administrator */
-
-       pEveryoneSid = GetEveryoneSid ();
-       if (pEveryoneSid) {
-               ACCESS_MASK rights = GetRightsFromSid (pEveryoneSid, pDACL);
-               /* http://msdn.microsoft.com/library/en-us/security/security/generic_access_rights.asp?frame=true */
-               success = (rights == (READ_CONTROL | SYNCHRONIZE | FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES));
-               FreeSid (pEveryoneSid);
-       }
-       /* Note: we don't need to check our own access - 
-       we'll know soon enough when reading the file */
-
-       if (pSD)
-               LocalFree (pSD);
-
-       return success;
-}
-
-
-static gboolean 
-IsUserProtected (gunichar2 *path)
-{
-       gboolean success = FALSE;
-       PACL pDACL = NULL;
-       PSID pEveryoneSid = NULL;
-       PSECURITY_DESCRIPTOR pSecurityDescriptor = NULL;
-
-       DWORD dwRes = GetNamedSecurityInfoW (path, SE_FILE_OBJECT, 
-               DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, &pSecurityDescriptor);
-       if (dwRes != ERROR_SUCCESS)
-               return FALSE;
-
-       /* We check that our original entries in the ACL are in place -
-       but not if new entries have been added by the user */
-
-       /* Everyone should be denied */
-       pEveryoneSid = GetEveryoneSid ();
-       if (pEveryoneSid) {
-               ACCESS_MASK rights = GetRightsFromSid (pEveryoneSid, pDACL);
-               success = (rights == 0);
-               FreeSid (pEveryoneSid);
-       }
-       /* Note: we don't need to check our own access - 
-       we'll know soon enough when reading the file */
-
-       if (pSecurityDescriptor)
-               LocalFree (pSecurityDescriptor);
-
-       return success;
-}
-
-
-static gboolean 
-ProtectMachine (gunichar2 *path)
-{
-       PSID pEveryoneSid = GetEveryoneSid ();
-       PSID pAdminsSid = GetAdministratorsSid ();
-       DWORD retval = -1;
-
-       if (pEveryoneSid && pAdminsSid) {
-               PACL pDACL = NULL;
-               EXPLICIT_ACCESS ea [2];
-               ZeroMemory (&ea, 2 * sizeof (EXPLICIT_ACCESS));
-
-               /* grant all access to the BUILTIN\Administrators group */
-               BuildTrusteeWithSidW (&ea [0].Trustee, pAdminsSid);
-               ea [0].grfAccessPermissions = GENERIC_ALL;
-               ea [0].grfAccessMode = SET_ACCESS;
-               ea [0].grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
-               ea [0].Trustee.TrusteeForm = TRUSTEE_IS_SID;
-               ea [0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
-
-               /* read-only access everyone */
-               BuildTrusteeWithSidW (&ea [1].Trustee, pEveryoneSid);
-               ea [1].grfAccessPermissions = GENERIC_READ;
-               ea [1].grfAccessMode = SET_ACCESS;
-               ea [1].grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
-               ea [1].Trustee.TrusteeForm = TRUSTEE_IS_SID;
-               ea [1].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
-
-               retval = SetEntriesInAcl (2, ea, NULL, &pDACL);
-               if (retval == ERROR_SUCCESS) {
-                       /* with PROTECTED_DACL_SECURITY_INFORMATION we */
-                       /* remove any existing ACL (like inherited ones) */
-                       retval = SetNamedSecurityInfo (path, SE_FILE_OBJECT, 
-                               DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
-                               NULL, NULL, pDACL, NULL);
-               }
-               if (pDACL)
-                       LocalFree (pDACL);
-       }
-
-       if (pEveryoneSid)
-               FreeSid (pEveryoneSid);
-       if (pAdminsSid)
-               FreeSid (pAdminsSid);
-       return (retval == ERROR_SUCCESS);
-}
-
-
-static gboolean 
-ProtectUser (gunichar2 *path)
-{
-       DWORD retval = -1;
-
-       PSID pCurrentSid = GetCurrentUserSid ();
-       if (pCurrentSid) {
-               PACL pDACL = NULL;
-               EXPLICIT_ACCESS ea;
-               ZeroMemory (&ea, sizeof (EXPLICIT_ACCESS));
-
-               /* grant exclusive access to the current user */
-               BuildTrusteeWithSidW (&ea.Trustee, pCurrentSid);
-               ea.grfAccessPermissions = GENERIC_ALL;
-               ea.grfAccessMode = SET_ACCESS;
-               ea.grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
-               ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
-               ea.Trustee.TrusteeType = TRUSTEE_IS_USER;
-
-               retval = SetEntriesInAcl (1, &ea, NULL, &pDACL);
-               if (retval == ERROR_SUCCESS) {
-                       /* with PROTECTED_DACL_SECURITY_INFORMATION we
-                          remove any existing ACL (like inherited ones) */
-                       retval = SetNamedSecurityInfo (path, SE_FILE_OBJECT, 
-                               DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
-                               NULL, NULL, pDACL, NULL);
-               }
-
-               if (pDACL)
-                       LocalFree (pDACL);
-               g_free (pCurrentSid); /* g_malloc0 */
-       }
-
-       return (retval == ERROR_SUCCESS);
-}
-
-#else
-
-static gboolean 
+#ifndef HOST_WIN32
+static gboolean
 IsProtected (MonoString *path, gint32 protection) 
 {
        gboolean result = FALSE;
@@ -822,7 +451,7 @@ IsProtected (MonoString *path, gint32 protection)
 }
 
 
-static gboolean 
+static gboolean
 Protect (MonoString *path, gint32 file_mode, gint32 add_dir_mode)
 {
        gboolean result = FALSE;
@@ -840,85 +469,53 @@ Protect (MonoString *path, gint32 file_mode, gint32 add_dir_mode)
        return result;
 }
 
-#endif /* not HOST_WIN32 */
-
-
 MonoBoolean
 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_CanSecure (MonoString *root)
 {
-#if HOST_WIN32
-       gint32 flags;
-
-       /* ACL are nice... unless you have FAT or other uncivilized filesystem */
-       if (!GetVolumeInformation (mono_string_chars (root), NULL, 0, NULL, NULL, (LPDWORD)&flags, NULL, 0))
-               return FALSE;
-       return ((flags & FS_PERSISTENT_ACLS) == FS_PERSISTENT_ACLS);
-#else
        /* we assume some kind of security is applicable outside Windows */
        return TRUE;
-#endif
 }
 
-
 MonoBoolean
 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_IsMachineProtected (MonoString *path)
 {
        gboolean ret = FALSE;
 
        /* no one, but the owner, should have write access to the directory */
-#ifdef HOST_WIN32
-       ret = IsMachineProtected (mono_string_chars (path));
-#else
        ret = IsProtected (path, (S_IWGRP | S_IWOTH));
-#endif
-       return ret;
+       return (MonoBoolean)ret;
 }
 
-
 MonoBoolean
 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_IsUserProtected (MonoString *path)
 {
        gboolean ret = FALSE;
 
        /* no one, but the user, should have access to the directory */
-#ifdef HOST_WIN32
-       ret = IsUserProtected (mono_string_chars (path));
-#else
        ret = IsProtected (path, (S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH));
-#endif
-       return ret;
+       return (MonoBoolean)ret;
 }
 
-
 MonoBoolean
 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_ProtectMachine (MonoString *path)
 {
        gboolean ret = FALSE;
 
        /* read/write to owner, read to everyone else */
-#ifdef HOST_WIN32
-       ret = ProtectMachine (mono_string_chars (path));
-#else
        ret = Protect (path, (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH), (S_IXUSR | S_IXGRP | S_IXOTH));
-#endif
-       return ret;
+       return (MonoBoolean)ret;
 }
 
-
 MonoBoolean
 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_ProtectUser (MonoString *path)
 {
        gboolean ret = FALSE;
        
        /* read/write to user, no access to everyone else */
-#ifdef HOST_WIN32
-       ret = ProtectUser (mono_string_chars (path));
-#else
        ret = Protect (path, (S_IRUSR | S_IWUSR), S_IXUSR);
-#endif
-       return ret;
+       return (MonoBoolean)ret;
 }
-
+#endif /* !HOST_WIN32 */
 
 /*
  * Returns TRUE if there is "something" where the Authenticode signature is 
@@ -930,7 +527,7 @@ MonoBoolean
 ves_icall_System_Security_Policy_Evidence_IsAuthenticodePresent (MonoReflectionAssembly *refass)
 {
        if (refass && refass->assembly && refass->assembly->image) {
-               return mono_image_has_authenticode_entry (refass->assembly->image);
+               return (MonoBoolean)mono_image_has_authenticode_entry (refass->assembly->image);
        }
        return FALSE;
 }
index 1ab1e0ebb2d3279e98a411d2151779e1bdfc1062..b3224372ddef5b678b1d512be8e23fa527bbdf8e 100644 (file)
@@ -26,6 +26,10 @@ mono_gc_base_init (void)
 
        mono_counters_init ();
 
+#ifndef HOST_WIN32
+       mono_w32handle_init ();
+#endif
+
        memset (&cb, 0, sizeof (cb));
        /* TODO: This casts away an incompatible pointer type warning in the same
                 manner that boehm-gc does it. This is probably worth investigating
@@ -107,16 +111,6 @@ mono_object_is_alive (MonoObject* o)
        return TRUE;
 }
 
-void
-mono_gc_enable_events (void)
-{
-}
-
-void
-mono_gc_enable_alloc_events (void)
-{
-}
-
 int
 mono_gc_register_root (char *start, size_t size, void *descr, MonoGCRootSource source, const char *msg)
 {
@@ -467,6 +461,16 @@ mono_gc_get_logfile (void)
        return NULL;
 }
 
+void
+mono_gc_params_set (const char* options)
+{
+}
+
+void
+mono_gc_debug_set (const char* options)
+{
+}
+
 void
 mono_gc_conservatively_scan_area (void *start, void *end)
 {
@@ -552,8 +556,9 @@ mono_gc_is_null (void)
        return TRUE;
 }
 #else
-       #ifdef _MSC_VER
-               // Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
-               void __mono_win32_null_gc_quiet_lnk4221(void) {}
-       #endif
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_null_gc_quiet_lnk4221(void) {}
+#endif
 #endif /* HAVE_NULL_GC */
index d28bd6c9f7997479f5cf34cbce3c6f37b1f43faa..b2cdf6a9fe9cb65c3665ab51b725630c161e7d7c 100644 (file)
@@ -381,6 +381,7 @@ struct _MonoInternalThread {
        gpointer thread_pinning_ref;
        gsize abort_protected_block_count;
        gint32 priority;
+       GPtrArray *owned_mutexes;
        /* 
         * These fields are used to avoid having to increment corlib versions
         * when a new field is added to this structure.
@@ -1179,12 +1180,16 @@ typedef struct {
        guint32 attrs;
 } MonoReflectionGenericParam;
 
+typedef struct {
+       MonoReflectionType type;
+       MonoReflectionTypeBuilder *tb;
+} MonoReflectionEnumBuilder;
+
 typedef struct _MonoReflectionGenericClass MonoReflectionGenericClass;
 struct _MonoReflectionGenericClass {
        MonoReflectionType type;
        MonoReflectionType *generic_type; /*Can be either a MonoType or a TypeBuilder*/
        MonoArray *type_arguments;
-       guint32 initialized;
 };
 
 typedef struct {
@@ -1281,26 +1286,6 @@ typedef struct {
        MonoArray *modopts;
 } MonoReflectionSigHelper;
 
-typedef struct {
-       MonoObject object;
-       MonoReflectionGenericClass *inst;
-       MonoObject *fb; /*can be either a MonoField or a FieldBuilder*/
-} MonoReflectionFieldOnTypeBuilderInst;
-
-typedef struct {
-       MonoObject object;
-       MonoReflectionGenericClass *inst;
-       MonoObject *cb; /*can be either a MonoCMethod or ConstructorBuilder*/
-} MonoReflectionCtorOnTypeBuilderInst;
-
-typedef struct {
-       MonoObject object;
-       MonoReflectionType *inst;
-       MonoObject *mb; /*can be either a MonoMethod or MethodBuilder*/
-       MonoArray *method_args;
-       MonoReflectionMethodBuilder *generic_method_definition;
-} MonoReflectionMethodOnTypeBuilderInst;
-
 typedef struct {
        MonoObject object;
        MonoBoolean visible;
@@ -1356,12 +1341,6 @@ void          mono_dynamic_image_release_gc_roots (MonoDynamicImage *image);
 
 void        mono_reflection_setup_internal_class  (MonoReflectionTypeBuilder *tb);
 
-MonoReflectionType*
-ves_icall_TypeBuilder_create_runtime_class (MonoReflectionTypeBuilder *tb);
-
-void
-ves_icall_TypeBuilder_setup_internal_class (MonoReflectionTypeBuilder *tb);
-
 void        mono_reflection_get_dynamic_overrides (MonoClass *klass, MonoMethod ***overrides, int *num_overrides, MonoError *error);
 
 void mono_reflection_destroy_dynamic_method (MonoReflectionDynamicMethod *mb);
@@ -1784,25 +1763,19 @@ ves_icall_AssemblyBuilder_basic_init (MonoReflectionAssemblyBuilder *assemblyb);
 MonoReflectionModule*
 ves_icall_AssemblyBuilder_InternalAddModule (MonoReflectionAssemblyBuilder *ab, MonoString *fileName);
 
-void
-ves_icall_TypeBuilder_create_generic_class (MonoReflectionTypeBuilder *tb);
-
 MonoArray*
 ves_icall_CustomAttributeBuilder_GetBlob (MonoReflectionAssembly *assembly, MonoObject *ctor, MonoArray *ctorArgs, MonoArray *properties, MonoArray *propValues, MonoArray *fields, MonoArray* fieldValues);
 
 void
 ves_icall_DynamicMethod_create_dynamic_method (MonoReflectionDynamicMethod *mb);
 
-MonoBoolean
-ves_icall_TypeBuilder_get_IsGenericParameter (MonoReflectionTypeBuilder *tb);
+MonoReflectionType*
+ves_icall_TypeBuilder_create_runtime_class (MonoReflectionTypeBuilder *tb);
 
 void
 ves_icall_EnumBuilder_setup_enum_type (MonoReflectionType *enumtype,
                                                                           MonoReflectionType *t);
 
-MonoReflectionType*
-ves_icall_ModuleBuilder_create_modified_type (MonoReflectionTypeBuilder *tb, MonoString *smodifiers);
-
 void
 ves_icall_ModuleBuilder_basic_init (MonoReflectionModuleBuilder *moduleb);
 
@@ -1812,10 +1785,4 @@ ves_icall_ModuleBuilder_getUSIndex (MonoReflectionModuleBuilder *module, MonoStr
 void
 ves_icall_ModuleBuilder_set_wrappers_type (MonoReflectionModuleBuilder *moduleb, MonoReflectionType *type);
 
-void
-ves_icall_GenericTypeParameterBuilder_initialize_generic_parameter (MonoReflectionGenericParam *gparam);
-
-MonoReflectionMethod*
-ves_icall_MethodBuilder_MakeGenericMethod (MonoReflectionMethod *rmethod, MonoArray *types);
-
 #endif /* __MONO_OBJECT_INTERNALS_H__ */
index 9db69581fbcc77704b0230f94bf300466255d509..61c9d61f7e586ba19550a965b89147833c85db05 100644 (file)
@@ -1890,7 +1890,7 @@ mono_class_create_runtime_vtable (MonoDomain *domain, MonoClass *klass, MonoErro
                if (mono_class_has_failure (element_class)) {
                        /*Can happen if element_class only got bad after mono_class_setup_vtable*/
                        if (!mono_class_has_failure (klass))
-                               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+                               mono_class_set_type_load_failure (klass, "");
                        mono_domain_unlock (domain);
                        mono_loader_unlock ();
                        mono_error_set_for_class_failure (error, klass);
@@ -5457,7 +5457,7 @@ mono_class_get_allocation_ftn (MonoVTable *vtable, gboolean for_box, gboolean *p
 
        *pass_size_in_words = FALSE;
 
-       if (mono_class_has_finalizer (vtable->klass) || mono_class_is_marshalbyref (vtable->klass) || (mono_profiler_get_events () & MONO_PROFILE_ALLOCATIONS))
+       if (mono_class_has_finalizer (vtable->klass) || mono_class_is_marshalbyref (vtable->klass))
                return ves_icall_object_new_specific;
 
        if (vtable->gc_descr != MONO_GC_DESCRIPTOR_NULL) {
@@ -5822,7 +5822,7 @@ mono_array_new_full_checked (MonoDomain *domain, MonoClass *array_class, uintptr
                o = (MonoObject *)mono_gc_alloc_vector (vtable, byte_len, len);
 
        if (G_UNLIKELY (!o)) {
-               mono_error_set_out_of_memory (error, "Could not allocate %i bytes", byte_len);
+               mono_error_set_out_of_memory (error, "Could not allocate %zd bytes", (gsize) byte_len);
                return NULL;
        }
 
@@ -5936,7 +5936,7 @@ mono_array_new_specific_checked (MonoVTable *vtable, uintptr_t n, MonoError *err
        o = (MonoObject *)mono_gc_alloc_vector (vtable, byte_len, n);
 
        if (G_UNLIKELY (!o)) {
-               mono_error_set_out_of_memory (error, "Could not allocate %i bytes", byte_len);
+               mono_error_set_out_of_memory (error, "Could not allocate %zd bytes", (gsize) byte_len);
                return NULL;
        }
 
@@ -6094,7 +6094,7 @@ mono_string_new_size_checked (MonoDomain *domain, gint32 len, MonoError *error)
        s = (MonoString *)mono_gc_alloc_string (vtable, size, len);
 
        if (G_UNLIKELY (!s)) {
-               mono_error_set_out_of_memory (error, "Could not allocate %i bytes", size);
+               mono_error_set_out_of_memory (error, "Could not allocate %zd bytes", size);
                return NULL;
        }
 
diff --git a/mono/metadata/process-internals.h b/mono/metadata/process-internals.h
new file mode 100644 (file)
index 0000000..cfc34e8
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#ifndef __MONO_METADATA_PROCESS_INTERNALS_H__
+#define __MONO_METADATA_PROCESS_INTERNALS_H__
+
+#include <config.h>
+#include <glib.h>
+
+// On Windows platform implementation of bellow methods are hosted in separate source file
+// process-windows.c or process-windows-*.c. On other platforms the implementation is still keept
+// in process.c still declared as static and in some places even inlined.
+#ifdef HOST_WIN32
+gchar*
+mono_process_quote_path (const gchar *path);
+
+gchar*
+mono_process_unquote_application_name (gchar *path);
+
+gboolean
+mono_process_get_shell_arguments (MonoProcessStartInfo *proc_start_info, gunichar2 **shell_path,
+                                 MonoString **cmd);
+#endif  /* HOST_WIN32 */
+
+// On platforms not using classic WIN API support the  implementation of bellow methods are hosted in separate source file
+// process-windows-*.c. On platforms using classic WIN API the implementation is still keept in process.c and still declared
+// static and in some places even inlined.
+#if !G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+void
+process_get_fileversion (MonoObject *filever, gunichar2 *filename, MonoError *error);
+
+void
+mono_process_init_startup_info (HANDLE stdin_handle, HANDLE stdout_handle,
+                               HANDLE stderr_handle,STARTUPINFO *startinfo);
+
+gboolean
+mono_process_create_process (MonoProcInfo *mono_process_info, gunichar2 *shell_path, MonoString *cmd,
+                            guint32 creation_flags, gchar *env_vars, gunichar2 *dir, STARTUPINFO *start_info,
+                            PROCESS_INFORMATION *process_info);
+#endif  /* !G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+// Shared between all platforms and implemented in process.c.
+gboolean
+mono_process_complete_path (const gunichar2 *appname, gchar **completed);
+
+#endif /* __MONO_METADATA_PROCESS_INTERNALS_H__ */
diff --git a/mono/metadata/process-windows-internals.h b/mono/metadata/process-windows-internals.h
new file mode 100644 (file)
index 0000000..68721fa
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#ifndef __MONO_METADATA_PROCESS_WINDOWS_INTERNALS_H__
+#define __MONO_METADATA_PROCESS_WINDOWS_INTERNALS_H__
+
+#include <config.h>
+#include <glib.h>
+
+#ifdef HOST_WIN32
+#include "mono/metadata/process.h"
+#include "mono/metadata/process-internals.h"
+#include "mono/metadata/object.h"
+#include "mono/metadata/object-internals.h"
+#include "mono/metadata/exception.h"
+
+// On platforms not using classic WIN API support the  implementation of bellow methods are hosted in separate source file
+// process-windows-*.c. On platforms using classic WIN API the implementation is still keept in process.c and still declared
+// static and in some places even inlined.
+#if !G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+gboolean
+mono_process_win_enum_processes (DWORD *pids, DWORD count, DWORD *needed);
+#endif  /* !G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+#endif /* HOST_WIN32 */
+
+#endif /* __MONO_METADATA_PROCESS_WINDOWS_INTERNALS_H__ */
diff --git a/mono/metadata/process-windows-uwp.c b/mono/metadata/process-windows-uwp.c
new file mode 100644 (file)
index 0000000..905555f
--- /dev/null
@@ -0,0 +1,157 @@
+/*
+ * process-windows-uwp.c: UWP process support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+
+#if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
+#include <Windows.h>
+#include "mono/metadata/process-windows-internals.h"
+
+gboolean
+mono_process_win_enum_processes (DWORD *pids, DWORD count, DWORD *needed)
+{
+       g_unsupported_api ("EnumProcesses");
+       *needed = 0;
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+HANDLE
+ves_icall_System_Diagnostics_Process_GetProcess_internal (guint32 pid)
+{
+       HANDLE handle;
+
+       /* GetCurrentProcess returns a pseudo-handle, so use
+        * OpenProcess instead
+        */
+       handle = OpenProcess (PROCESS_ALL_ACCESS, TRUE, pid);
+       if (handle == NULL)
+               /* FIXME: Throw an exception */
+               return NULL;
+       return handle;
+}
+
+void
+process_get_fileversion (MonoObject *filever, gunichar2 *filename, MonoError *error)
+{
+       g_unsupported_api ("GetFileVersionInfoSize, GetFileVersionInfo, VerQueryValue, VerLanguageName");
+
+       mono_error_init (error);
+       mono_error_set_not_supported (error, G_UNSUPPORTED_API, "GetFileVersionInfoSize, GetFileVersionInfo, VerQueryValue, VerLanguageName");
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+}
+
+MonoObject*
+process_add_module (HANDLE process, HMODULE mod, gunichar2 *filename, gunichar2 *modulename, MonoClass *proc_class, MonoError *error)
+{
+       g_unsupported_api ("GetModuleInformation");
+
+       mono_error_init (error);
+       mono_error_set_not_supported (error, G_UNSUPPORTED_API, "GetModuleInformation");
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return NULL;
+}
+
+MonoArray *
+ves_icall_System_Diagnostics_Process_GetModules_internal (MonoObject *this_obj, HANDLE process)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("EnumProcessModules, GetModuleBaseName, GetModuleFileNameEx");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "EnumProcessModules, GetModuleBaseName, GetModuleFileNameEx");
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return NULL;
+}
+
+MonoBoolean
+ves_icall_System_Diagnostics_Process_ShellExecuteEx_internal (MonoProcessStartInfo *proc_start_info, MonoProcInfo *process_info)
+{
+       MonoError mono_error;
+       mono_error_init (&mono_error);
+
+       g_unsupported_api ("ShellExecuteEx");
+
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, "ShellExecuteEx");
+       mono_error_set_pending_exception (&mono_error);
+
+       process_info->pid = (guint32)(-ERROR_NOT_SUPPORTED);
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+MonoString *
+ves_icall_System_Diagnostics_Process_ProcessName_internal (HANDLE process)
+{
+       MonoError error;
+       MonoString *string;
+       gunichar2 name[MAX_PATH];
+       guint32 len;
+
+       len = GetModuleFileName (NULL, name, G_N_ELEMENTS (name));
+       if (len == 0)
+               return NULL;
+
+       string = mono_string_new_utf16_checked (mono_domain_get (), name, len, &error);
+       if (!mono_error_ok (&error))
+               mono_error_set_pending_exception (&error);
+
+       return string;
+}
+
+void
+mono_process_init_startup_info (HANDLE stdin_handle, HANDLE stdout_handle, HANDLE stderr_handle, STARTUPINFO *startinfo)
+{
+       startinfo->cb = sizeof(STARTUPINFO);
+       startinfo->dwFlags = 0;
+       startinfo->hStdInput = INVALID_HANDLE_VALUE;
+       startinfo->hStdOutput = INVALID_HANDLE_VALUE;
+       startinfo->hStdError = INVALID_HANDLE_VALUE;
+       return;
+}
+
+gboolean
+mono_process_create_process (MonoProcInfo *mono_process_info, gunichar2 *shell_path, MonoString *cmd, guint32 creation_flags,
+                            gchar *env_vars, gunichar2 *dir, STARTUPINFO *start_info, PROCESS_INFORMATION *process_info)
+{
+       MonoError       mono_error;
+       gchar           *api_name = "";
+
+       if (mono_process_info->username) {
+               api_name = "CreateProcessWithLogonW";
+       } else {
+               api_name = "CreateProcess";
+       }
+
+       memset (&process_info, 0, sizeof (PROCESS_INFORMATION));
+       g_unsupported_api (api_name);
+
+       mono_error_init (&mono_error);
+       mono_error_set_not_supported (&mono_error, G_UNSUPPORTED_API, api_name);
+       mono_error_set_pending_exception (&mono_error);
+
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return FALSE;
+}
+
+#else /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_process_windows_uwp_quiet_lnk4221(void) {}
+#endif
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
diff --git a/mono/metadata/process-windows.c b/mono/metadata/process-windows.c
new file mode 100644 (file)
index 0000000..847612d
--- /dev/null
@@ -0,0 +1,129 @@
+/*
+ * process-windows.c: Windows process support.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+
+#include <config.h>
+#include <glib.h>
+
+#if defined(HOST_WIN32)
+#include <WinSock2.h>
+#include <Windows.h>
+#include "mono/metadata/process-windows-internals.h"
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+static inline gboolean
+mono_process_win_enum_processes (DWORD *pids, DWORD count, DWORD *needed)
+{
+       return EnumProcesses (pids, count, needed);
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+MonoArray *
+ves_icall_System_Diagnostics_Process_GetProcesses_internal (void)
+{
+       MonoError error;
+       MonoArray *procs;
+       gboolean ret;
+       DWORD needed;
+       int count;
+       DWORD *pids;
+
+       count = 512;
+       do {
+               pids = g_new0 (DWORD, count);
+               ret = mono_process_win_enum_processes (pids, count * sizeof (guint32), &needed);
+               if (ret == FALSE) {
+                       MonoException *exc;
+
+                       g_free (pids);
+                       pids = NULL;
+                       exc = mono_get_exception_not_supported ("This system does not support EnumProcesses");
+                       mono_set_pending_exception (exc);
+                       return NULL;
+               }
+               if (needed < (count * sizeof (guint32)))
+                       break;
+               g_free (pids);
+               pids = NULL;
+               count = (count * 3) / 2;
+       } while (TRUE);
+
+       count = needed / sizeof (guint32);
+       procs = mono_array_new_checked (mono_domain_get (), mono_get_int32_class (), count, &error);
+       if (mono_error_set_pending_exception (&error)) {
+               g_free (pids);
+               return NULL;
+       }
+
+       memcpy (mono_array_addr (procs, guint32, 0), pids, needed);
+       g_free (pids);
+       pids = NULL;
+
+       return procs;
+}
+
+gchar*
+mono_process_quote_path (const gchar *path)
+{
+       gchar *res = g_shell_quote (path);
+       gchar *q = res;
+       while (*q) {
+               if (*q == '\'')
+                       *q = '\"';
+               q++;
+       }
+       return res;
+}
+
+gchar*
+mono_process_unquote_application_name (gchar *appname)
+{
+       size_t len = strlen (appname);
+       if (len) {
+               if (appname[len-1] == '\"')
+                       appname[len-1] = '\0';
+               if (appname[0] == '\"')
+                       appname++;
+       }
+
+       return appname;
+}
+
+gboolean
+mono_process_get_shell_arguments (MonoProcessStartInfo *proc_start_info, gunichar2 **shell_path, MonoString **cmd)
+{
+       gchar           *spath = NULL;
+       gchar           *new_cmd, *cmd_utf8;
+       MonoError       mono_error;
+
+       *shell_path = NULL;
+       *cmd = proc_start_info->arguments;
+
+       mono_process_complete_path (mono_string_chars (proc_start_info->filename), &spath);
+       if (spath != NULL) {
+               /* Seems like our CreateProcess does not work as the windows one.
+                * This hack is needed to deal with paths containing spaces */
+               if (*cmd) {
+                       cmd_utf8 = mono_string_to_utf8_checked (*cmd, &mono_error);
+                       if (!mono_error_set_pending_exception (&mono_error)) {
+                               new_cmd = g_strdup_printf ("%s %s", spath, cmd_utf8);
+                               *cmd = mono_string_new_wrapper (new_cmd);
+                               g_free (cmd_utf8);
+                               g_free (new_cmd);
+                       } else {
+                               *cmd = NULL;
+                       }
+               }
+               else {
+                       *cmd = mono_string_new_wrapper (spath);
+               }
+
+               g_free (spath);
+       }
+
+       return (*cmd != NULL) ? TRUE : FALSE;
+}
+#endif /* HOST_WIN32 */
index 8178d283823e569dedf444dc828df54cdfbc324d..b1bff0b5ecad403e85d7f82ada5d42f06d08b8c5 100644 (file)
@@ -16,6 +16,7 @@
 
 #include <mono/metadata/object-internals.h>
 #include <mono/metadata/process.h>
+#include <mono/metadata/process-internals.h>
 #include <mono/metadata/assembly.h>
 #include <mono/metadata/appdomain.h>
 #include <mono/metadata/image.h>
 #define LOGDEBUG(...)  
 /* define LOGDEBUG(...) g_message(__VA_ARGS__)  */
 
-#ifdef _WIN32
+#if defined(HOST_WIN32) && G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 #include <shellapi.h>
 #endif
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 HANDLE
 ves_icall_System_Diagnostics_Process_GetProcess_internal (guint32 pid)
 {
@@ -50,6 +52,7 @@ ves_icall_System_Diagnostics_Process_GetProcess_internal (guint32 pid)
                return NULL;
        return handle;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT | HAVE_UWP_WINAPI_SUPPORT) */
 
 static MonoImage *system_assembly;
 
@@ -196,11 +199,11 @@ process_set_field_bool (MonoObject *obj, const gchar *fieldname,
 #define SFI_SPECIALBUILD       "\\StringFileInfo\\%02X%02X%02X%02X\\SpecialBuild"
 #define EMPTY_STRING           (gunichar2*)"\000\000"
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 static void
 process_module_string_read (MonoObject *filever, gpointer data,
-                                                       const gchar *fieldname,
-                                                       guchar lang_hi, guchar lang_lo,
-                                                       const gchar *key, MonoError *error)
+                           const gchar *fieldname, guchar lang_hi, guchar lang_lo,
+                           const gchar *key, MonoError *error)
 {
        gchar *lang_key_utf8;
        gunichar2 *lang_key, *buffer;
@@ -367,6 +370,7 @@ process_get_fileversion (MonoObject *filever, gunichar2 *filename, MonoError *er
                g_free (data);
        }
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
 
 static void
 process_get_assembly_fileversion (MonoObject *filever, MonoAssembly *assembly)
@@ -409,6 +413,7 @@ get_process_module (MonoAssembly *assembly, MonoClass *proc_class, MonoError *er
        return item;
 }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 static MonoObject*
 process_add_module (HANDLE process, HMODULE mod, gunichar2 *filename, gunichar2 *modulename, MonoClass *proc_class, MonoError *error)
 {
@@ -451,6 +456,7 @@ process_add_module (HANDLE process, HMODULE mod, gunichar2 *filename, gunichar2
 
        return item;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
 
 static GPtrArray*
 get_domain_assemblies (MonoDomain *domain)
@@ -476,6 +482,7 @@ get_domain_assemblies (MonoDomain *domain)
 }
 
 /* Returns an array of System.Diagnostics.ProcessModule */
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 MonoArray *
 ves_icall_System_Diagnostics_Process_GetModules_internal (MonoObject *this_obj, HANDLE process)
 {
@@ -489,16 +496,10 @@ ves_icall_System_Diagnostics_Process_GetModules_internal (MonoObject *this_obj,
        guint32 count = 0, module_count = 0, assembly_count = 0;
        guint32 i, num_added = 0;
        GPtrArray *assemblies = NULL;
-       static HANDLE current_process = 0;
-       
-       if (current_process == 0) {
-               int pid = mono_process_current_pid ();
-               current_process = ves_icall_System_Diagnostics_Process_GetProcess_internal (pid);
-       }
 
        stash_system_assembly (this_obj);
 
-       if (process == current_process) {
+       if (GetProcessId (process) == mono_process_current_pid ()) {
                assemblies = get_domain_assemblies (mono_domain_get ());
                assembly_count = assemblies->len;
        }
@@ -552,6 +553,7 @@ ves_icall_System_Diagnostics_Process_GetModules_internal (MonoObject *this_obj,
 
        return arr;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
 
 void
 ves_icall_System_Diagnostics_FileVersionInfo_GetVersionInfo_internal (MonoObject *this_obj, MonoString *filename)
@@ -575,53 +577,38 @@ ves_icall_System_Diagnostics_FileVersionInfo_GetVersionInfo_internal (MonoObject
 }
 
 /* Only used when UseShellExecute is false */
-static gchar *
-quote_path (const gchar *path)
+#ifndef HOST_WIN32
+static inline gchar *
+mono_process_quote_path (const gchar *path)
 {
-       gchar *res = g_shell_quote (path);
-#ifdef TARGET_WIN32
-       {
-       gchar *q = res;
-       while (*q) {
-               if (*q == '\'')
-                       *q = '\"';
-               q++;
-       }
-       }
-#endif
-       return res;
+       return g_shell_quote (path);
+}
+
+static inline gchar *
+mono_process_unquote_application_name (gchar *path)
+{
+       return path;
 }
+#endif /* !HOST_WIN32 */
 
 /* Only used when UseShellExecute is false */
-static gboolean
-complete_path (const gunichar2 *appname, gchar **completed)
+gboolean
+mono_process_complete_path (const gunichar2 *appname, gchar **completed)
 {
        gchar *utf8app, *utf8appmemory;
        gchar *found;
 
-       utf8appmemory = utf8app = g_utf16_to_utf8 (appname, -1, NULL, NULL, NULL);
-#ifdef TARGET_WIN32 // Should this happen on all platforms? 
-       {
-               // remove the quotes around utf8app.
-               size_t len;
-               len = strlen (utf8app);
-               if (len) {
-                       if (utf8app[len-1] == '\"')
-                               utf8app[len-1] = '\0';
-                       if (utf8app[0] == '\"')
-                               utf8app++;
-               }
-       }
-#endif
+       utf8appmemory = g_utf16_to_utf8 (appname, -1, NULL, NULL, NULL);
+       utf8app = mono_process_unquote_application_name (utf8appmemory);
 
        if (g_path_is_absolute (utf8app)) {
-               *completed = quote_path (utf8app);
+               *completed = mono_process_quote_path (utf8app);
                g_free (utf8appmemory);
                return TRUE;
        }
 
        if (g_file_test (utf8app, G_FILE_TEST_IS_EXECUTABLE) && !g_file_test (utf8app, G_FILE_TEST_IS_DIR)) {
-               *completed = quote_path (utf8app);
+               *completed = mono_process_quote_path (utf8app);
                g_free (utf8appmemory);
                return TRUE;
        }
@@ -633,12 +620,13 @@ complete_path (const gunichar2 *appname, gchar **completed)
                return FALSE;
        }
 
-       *completed = quote_path (found);
+       *completed = mono_process_quote_path (found);
        g_free (found);
        g_free (utf8appmemory);
        return TRUE;
 }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 MonoBoolean
 ves_icall_System_Diagnostics_Process_ShellExecuteEx_internal (MonoProcessStartInfo *proc_start_info, MonoProcInfo *process_info)
 {
@@ -690,62 +678,102 @@ ves_icall_System_Diagnostics_Process_ShellExecuteEx_internal (MonoProcessStartIn
 
        return ret;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+static inline void
+mono_process_init_startup_info (HANDLE stdin_handle, HANDLE stdout_handle, HANDLE stderr_handle, STARTUPINFO *startinfo)
+{
+       startinfo->cb = sizeof(STARTUPINFO);
+       startinfo->dwFlags = STARTF_USESTDHANDLES;
+       startinfo->hStdInput = stdin_handle;
+       startinfo->hStdOutput = stdout_handle;
+       startinfo->hStdError = stderr_handle;
+       return;
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+#ifndef HOST_WIN32
+static gboolean
+mono_process_get_shell_arguments (MonoProcessStartInfo *proc_start_info, gunichar2 **shell_path, MonoString **cmd)
+{
+       gchar *spath = NULL;
+
+       *shell_path = NULL;
+       *cmd = proc_start_info->arguments;
+
+       mono_process_complete_path (mono_string_chars (proc_start_info->filename), &spath);
+       if (spath != NULL) {
+               *shell_path = g_utf8_to_utf16 (spath, -1, NULL, NULL, NULL);
+               g_free (spath);
+       }
+
+       return (*shell_path != NULL) ? TRUE : FALSE;
+}
+#endif /* !HOST_WIN32 */
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+static gboolean
+mono_process_create_process (MonoProcInfo *mono_process_info, gunichar2 *shell_path,
+                            MonoString *cmd, guint32 creation_flags, gchar *env_vars,
+                            gunichar2 *dir, STARTUPINFO *start_info, PROCESS_INFORMATION *process_info)
+{
+       gboolean result = FALSE;
+
+       if (mono_process_info->username) {
+               guint32 logon_flags = mono_process_info->load_user_profile ? LOGON_WITH_PROFILE : 0;
+
+               result = CreateProcessWithLogonW (mono_string_chars (mono_process_info->username),
+                                                 mono_process_info->domain ? mono_string_chars (mono_process_info->domain) : NULL,
+                                                 (const gunichar2 *)mono_process_info->password,
+                                                 logon_flags,
+                                                 shell_path,
+                                                 cmd ? mono_string_chars (cmd) : NULL,
+                                                 creation_flags,
+                                                 env_vars, dir, start_info, process_info);
+
+       } else {
+
+               result = CreateProcess (shell_path,
+                                       cmd ? mono_string_chars (cmd): NULL,
+                                       NULL,
+                                       NULL,
+                                       TRUE,
+                                       creation_flags,
+                                       env_vars,
+                                       dir,
+                                       start_info,
+                                       process_info);
+
+       }
+
+       return result;
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
 
 MonoBoolean
-ves_icall_System_Diagnostics_Process_CreateProcess_internal (MonoProcessStartInfo *proc_start_info, HANDLE stdin_handle, HANDLE stdout_handle, HANDLE stderr_handle, MonoProcInfo *process_info)
+ves_icall_System_Diagnostics_Process_CreateProcess_internal (MonoProcessStartInfo *proc_start_info, HANDLE stdin_handle,
+                                                            HANDLE stdout_handle, HANDLE stderr_handle, MonoProcInfo *process_info)
 {
-       MonoError error G_GNUC_UNUSED;
        gboolean ret;
        gunichar2 *dir;
        STARTUPINFO startinfo={0};
        PROCESS_INFORMATION procinfo;
        gunichar2 *shell_path = NULL;
        gchar *env_vars = NULL;
-       gboolean free_shell_path = TRUE;
-       gchar *spath = NULL;
-       MonoString *cmd = proc_start_info->arguments;
-       guint32 creation_flags, logon_flags;
-       
-       startinfo.cb = sizeof(STARTUPINFO);
-       startinfo.dwFlags = STARTF_USESTDHANDLES;
-       startinfo.hStdInput = stdin_handle;
-       startinfo.hStdOutput = stdout_handle;
-       startinfo.hStdError = stderr_handle;
+       MonoString *cmd = NULL;
+       guint32 creation_flags;
+
+       mono_process_init_startup_info (stdin_handle, stdout_handle, stderr_handle, &startinfo);
 
        creation_flags = CREATE_UNICODE_ENVIRONMENT;
        if (proc_start_info->create_no_window)
                creation_flags |= CREATE_NO_WINDOW;
        
-       shell_path = mono_string_chars (proc_start_info->filename);
-       complete_path (shell_path, &spath);
-       if (spath == NULL) {
+       if (mono_process_get_shell_arguments (proc_start_info, &shell_path, &cmd) == FALSE) {
                process_info->pid = -ERROR_FILE_NOT_FOUND;
                return FALSE;
        }
-#ifdef TARGET_WIN32
-       /* Seems like our CreateProcess does not work as the windows one.
-        * This hack is needed to deal with paths containing spaces */
-       shell_path = NULL;
-       free_shell_path = FALSE;
-       if (cmd) {
-               gchar *newcmd, *tmp;
-               tmp = mono_string_to_utf8_checked (cmd, &error);
-               if (mono_error_set_pending_exception (&error)) {
-                       g_free (spath);
-                       return NULL;
-               }
-               newcmd = g_strdup_printf ("%s %s", spath, tmp);
-               cmd = mono_string_new_wrapper (newcmd);
-               g_free (tmp);
-               g_free (newcmd);
-       }
-       else {
-               cmd = mono_string_new_wrapper (spath);
-       }
-#else
-       shell_path = g_utf8_to_utf16 (spath, -1, NULL, NULL, NULL);
-#endif
-       g_free (spath);
 
        if (process_info->env_keys) {
                gint i, len; 
@@ -796,20 +824,10 @@ ves_icall_System_Diagnostics_Process_CreateProcess_internal (MonoProcessStartInf
        else
                dir = mono_string_chars (proc_start_info->working_directory);
 
-       if (process_info->username) {
-               logon_flags = process_info->load_user_profile ? LOGON_WITH_PROFILE : 0;
-               ret = CreateProcessWithLogonW (
-                       mono_string_chars (process_info->username),
-                       process_info->domain ? mono_string_chars (process_info->domain) : NULL,
-                       (const gunichar2 *)process_info->password, logon_flags, shell_path,
-                       cmd ? mono_string_chars (cmd) : NULL,
-                       creation_flags, env_vars, dir, &startinfo, &procinfo);
-       } else {
-               ret = CreateProcess (shell_path, cmd ? mono_string_chars (cmd): NULL, NULL, NULL, TRUE, creation_flags, env_vars, dir, &startinfo, &procinfo);
-       }
+       ret = mono_process_create_process (process_info, shell_path, cmd, creation_flags, env_vars, dir, &startinfo, &procinfo);
 
        g_free (env_vars);
-       if (free_shell_path)
+       if (shell_path != NULL)
                g_free (shell_path);
 
        if (ret) {
@@ -827,22 +845,24 @@ ves_icall_System_Diagnostics_Process_CreateProcess_internal (MonoProcessStartInf
        return ret;
 }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 MonoString *
 ves_icall_System_Diagnostics_Process_ProcessName_internal (HANDLE process)
 {
        MonoError error;
        MonoString *string;
+       gunichar2 name[MAX_PATH];
+       guint32 len;
        gboolean ok;
        HMODULE mod;
-       gunichar2 name[MAX_PATH];
        DWORD needed;
-       guint32 len;
-       
+
        ok = EnumProcessModules (process, &mod, sizeof(mod), &needed);
        if (!ok)
                return NULL;
        
        len = GetModuleBaseName (process, mod, name, MAX_PATH);
+
        if (len == 0)
                return NULL;
        
@@ -854,12 +874,13 @@ ves_icall_System_Diagnostics_Process_ProcessName_internal (HANDLE process)
        
        return string;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
 
+#ifndef HOST_WIN32
 /* Returns an array of pids */
 MonoArray *
 ves_icall_System_Diagnostics_Process_GetProcesses_internal (void)
 {
-#if !defined(HOST_WIN32)
        MonoError error;
        MonoArray *procs;
        gpointer *pidarray;
@@ -884,48 +905,8 @@ ves_icall_System_Diagnostics_Process_GetProcesses_internal (void)
        g_free (pidarray);
 
        return procs;
-#else
-       MonoError error;
-       MonoArray *procs;
-       gboolean ret;
-       DWORD needed;
-       int count;
-       guint32 *pids;
-
-       count = 512;
-       do {
-               pids = g_new0 (guint32, count);
-               ret = EnumProcesses (pids, count * sizeof (guint32), &needed);
-               if (ret == FALSE) {
-                       MonoException *exc;
-
-                       g_free (pids);
-                       pids = NULL;
-                       exc = mono_get_exception_not_supported ("This system does not support EnumProcesses");
-                       mono_set_pending_exception (exc);
-                       return NULL;
-               }
-               if (needed < (count * sizeof (guint32)))
-                       break;
-               g_free (pids);
-               pids = NULL;
-               count = (count * 3) / 2;
-       } while (TRUE);
-
-       count = needed / sizeof (guint32);
-       procs = mono_array_new_checked (mono_domain_get (), mono_get_int32_class (), count, &error);
-       if (mono_error_set_pending_exception (&error)) {
-               g_free (pids);
-               return NULL;
-       }
-
-       memcpy (mono_array_addr (procs, guint32, 0), pids, needed);
-       g_free (pids);
-       pids = NULL;
-       
-       return procs;
-#endif
 }
+#endif /* !HOST_WIN32 */
 
 gint64
 ves_icall_System_Diagnostics_Process_GetProcessData (int pid, gint32 data_type, gint32 *error)
index fb4cdeca08b8632bf1f746c8ea5bda5b26a1517a..0fd162dd98a86884d77a104587973a79cd5549a0 100644 (file)
@@ -273,7 +273,6 @@ mono_profiler_install_transition (MonoProfileMethodResult callback)
 void 
 mono_profiler_install_allocation (MonoProfileAllocFunc callback)
 {
-       mono_gc_enable_alloc_events ();
        if (!prof_list)
                return;
        prof_list->allocation_cb = callback;
@@ -876,7 +875,6 @@ mono_profiler_gc_roots (int num, void **objects, int *root_types, uintptr_t *ext
 void
 mono_profiler_install_gc (MonoProfileGCFunc callback, MonoProfileGCResizeFunc heap_resize_callback)
 {
-       mono_gc_enable_events ();
        if (!prof_list)
                return;
        prof_list->gc_event = callback;
@@ -970,7 +968,7 @@ mono_profiler_install_gc_finalize (MonoProfileGCFinalizeFunc begin, MonoProfileG
 
        prof_list->gc_finalize_begin = begin;
        prof_list->gc_finalize_object_begin = begin_obj;
-       prof_list->gc_finalize_object_begin = end_obj;
+       prof_list->gc_finalize_object_end = end_obj;
        prof_list->gc_finalize_end = end;
 }
 
index 0a5ea615a03f73a95bfc4822f98dd4307a265158..e17bf8692087481ac62bb52e93ba94263d8ecd34 100644 (file)
@@ -53,8 +53,6 @@ static MonoType* mono_reflection_get_type_with_rootimage (MonoImage *rootimage,
 /* Class lazy loading functions */
 static GENERATE_GET_CLASS_WITH_CACHE (mono_assembly, System.Reflection, MonoAssembly)
 static GENERATE_GET_CLASS_WITH_CACHE (mono_module, System.Reflection, MonoModule)
-static GENERATE_GET_CLASS_WITH_CACHE (mono_generic_method, System.Reflection, MonoGenericMethod);
-static GENERATE_GET_CLASS_WITH_CACHE (mono_generic_cmethod, System.Reflection, MonoGenericCMethod);
 static GENERATE_GET_CLASS_WITH_CACHE (mono_method, System.Reflection, MonoMethod);
 static GENERATE_GET_CLASS_WITH_CACHE (mono_cmethod, System.Reflection, MonoCMethod);
 static GENERATE_GET_CLASS_WITH_CACHE (mono_field, System.Reflection, MonoField);
@@ -325,36 +323,6 @@ mono_module_file_get_object_checked (MonoDomain *domain, MonoImage *image, int t
        return res;
 }
 
-static gboolean
-verify_safe_for_managed_space (MonoType *type)
-{
-       switch (type->type) {
-#ifdef DEBUG_HARDER
-       case MONO_TYPE_ARRAY:
-               return verify_safe_for_managed_space (&type->data.array->eklass->byval_arg);
-       case MONO_TYPE_PTR:
-               return verify_safe_for_managed_space (type->data.type);
-       case MONO_TYPE_SZARRAY:
-               return verify_safe_for_managed_space (&type->data.klass->byval_arg);
-       case MONO_TYPE_GENERICINST: {
-               MonoGenericInst *inst = type->data.generic_class->inst;
-               int i;
-               if (!inst->is_open)
-                       break;
-               for (i = 0; i < inst->type_argc; ++i)
-                       if (!verify_safe_for_managed_space (inst->type_argv [i]))
-                               return FALSE;
-               return TRUE;
-       }
-#endif
-       case MONO_TYPE_VAR:
-       case MONO_TYPE_MVAR:
-               return TRUE;
-       default:
-               return TRUE;
-       }
-}
-
 static MonoType*
 mono_type_normalize (MonoType *type)
 {
@@ -483,40 +451,10 @@ mono_type_get_object_checked (MonoDomain *domain, MonoType *type, MonoError *err
        if ((type->type == MONO_TYPE_GENERICINST) && type->data.generic_class->is_dynamic && !type->data.generic_class->container_class->wastypebuilder)
                g_assert (0);
 
-       if (!verify_safe_for_managed_space (type)) {
+       if (mono_class_get_ref_info (klass) && !klass->wastypebuilder && !type->byref) {
                mono_domain_unlock (domain);
                mono_loader_unlock ();
-               mono_error_set_generic_error (error, "System", "InvalidOperationException", "This type cannot be propagated to managed space");
-               return NULL;
-       }
-
-       if (mono_class_get_ref_info (klass) && !klass->wastypebuilder) {
-               gboolean is_type_done = TRUE;
-               /* Generic parameters have reflection_info set but they are not finished together with their enclosing type.
-                * We must ensure that once a type is finished we don't return a GenericTypeParameterBuilder.
-                * We can't simply close the types as this will interfere with other parts of the generics machinery.
-               */
-               if (klass->byval_arg.type == MONO_TYPE_MVAR || klass->byval_arg.type == MONO_TYPE_VAR) {
-                       MonoGenericParam *gparam = klass->byval_arg.data.generic_param;
-
-                       if (gparam->owner && gparam->owner->is_method) {
-                               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);
@@ -575,33 +513,6 @@ mono_method_get_object_checked (MonoDomain *domain, MonoMethod *method, MonoClas
 
        mono_error_init (error);
 
-       if (method->is_inflated) {
-               MonoReflectionGenericMethod *gret;
-
-               if (!refclass)
-                       refclass = method->klass;
-               CHECK_OBJECT (MonoReflectionMethod *, method, refclass);
-               if ((*method->name == '.') && (!strcmp (method->name, ".ctor") || !strcmp (method->name, ".cctor"))) {
-                       klass = mono_class_get_mono_generic_cmethod_class ();
-               } else {
-                       klass = mono_class_get_mono_generic_method_class ();
-               }
-               gret = (MonoReflectionGenericMethod*)mono_object_new_checked (domain, klass, error);
-               if (!mono_error_ok (error))
-                       goto leave;
-               gret->method.method = method;
-
-               MONO_OBJECT_SETREF (gret, method.name, mono_string_new (domain, method->name));
-
-               rt = mono_type_get_object_checked (domain, &refclass->byval_arg, error);
-               if (!mono_error_ok (error))
-                   goto leave;
-
-               MONO_OBJECT_SETREF (gret, method.reftype, rt);
-
-               CACHE_OBJECT (MonoReflectionMethod *, method, (MonoReflectionMethod*)gret, refclass);
-       }
-
        if (!refclass)
                refclass = method->klass;
 
@@ -2149,9 +2060,7 @@ mono_reflection_get_token_checked (MonoObject *obj, MonoError *error)
 
                token = mc->type_token;
        } else if (strcmp (klass->name, "MonoCMethod") == 0 ||
-                  strcmp (klass->name, "MonoMethod") == 0 ||
-                  strcmp (klass->name, "MonoGenericMethod") == 0 ||
-                  strcmp (klass->name, "MonoGenericCMethod") == 0) {
+                          strcmp (klass->name, "MonoMethod") == 0) {
                MonoReflectionMethod *m = (MonoReflectionMethod *)obj;
                if (m->method->is_inflated) {
                        MonoMethodInflated *inflated = (MonoMethodInflated *) m->method;
@@ -2214,7 +2123,6 @@ MonoType*
 mono_reflection_bind_generic_parameters (MonoReflectionType *type, int type_argc, MonoType **types, MonoError *error)
 {
        MonoClass *klass;
-       MonoReflectionTypeBuilder *tb = NULL;
        gboolean is_dynamic = FALSE;
        MonoClass *geninst;
 
@@ -2223,25 +2131,13 @@ mono_reflection_bind_generic_parameters (MonoReflectionType *type, int type_argc
        mono_loader_lock ();
 
        if (mono_is_sre_type_builder (mono_object_class (type))) {
-               tb = (MonoReflectionTypeBuilder *) type;
-
                is_dynamic = TRUE;
        } else if (mono_is_sre_generic_instance (mono_object_class (type))) {
                MonoReflectionGenericClass *rgi = (MonoReflectionGenericClass *) type;
                MonoReflectionType *gtd = rgi->generic_type;
 
-               if (mono_is_sre_type_builder (mono_object_class (gtd))) {
-                       tb = (MonoReflectionTypeBuilder *)gtd;
+               if (mono_is_sre_type_builder (mono_object_class (gtd)))
                        is_dynamic = TRUE;
-               }
-       }
-
-       /* FIXME: fix the CreateGenericParameters protocol to avoid the two stage setup of TypeBuilders */
-       if (tb && tb->generic_container) {
-               if (!mono_reflection_create_generic_class (tb, error)) {
-                       mono_loader_unlock ();
-                       return NULL;
-               }
        }
 
        MonoType *t = mono_reflection_type_get_handle (type, error);
@@ -2257,11 +2153,8 @@ mono_reflection_bind_generic_parameters (MonoReflectionType *type, int type_argc
                return NULL;
        }
 
-       if (klass->wastypebuilder) {
-               tb = (MonoReflectionTypeBuilder *) mono_class_get_ref_info (klass);
-
+       if (klass->wastypebuilder)
                is_dynamic = TRUE;
-       }
 
        mono_loader_unlock ();
 
@@ -2297,13 +2190,9 @@ reflection_bind_generic_method_parameters (MonoReflectionMethod *rmethod, MonoAr
 
        mono_error_init (error);
 
-       /*FIXME but this no longer should happen*/
-       if (!strcmp (rmethod->object.vtable->klass->name, "MethodBuilder")) {
-               method = mono_reflection_method_builder_to_mono_method ((MonoReflectionMethodBuilder*)rmethod, error);
-               return_val_if_nok (error, NULL);
-       } else {
-               method = rmethod->method;
-       }
+       g_assert (strcmp (rmethod->object.vtable->klass->name, "MethodBuilder"));
+
+       method = rmethod->method;
 
        klass = method->klass;
 
@@ -2350,17 +2239,7 @@ reflection_bind_generic_method_parameters (MonoReflectionMethod *rmethod, MonoAr
                return NULL;
        }
        
-       MonoReflectionMethod *ret = mono_method_get_object_checked (mono_object_domain (rmethod), inflated, NULL, error);
-       return ret;
-}
-
-MonoReflectionMethod*
-ves_icall_MethodBuilder_MakeGenericMethod (MonoReflectionMethod *rmethod, MonoArray *types)
-{
-       MonoError error;
-       MonoReflectionMethod *result = reflection_bind_generic_method_parameters (rmethod, types, &error);
-       mono_error_set_pending_exception (&error);
-       return result;
+       return mono_method_get_object_checked (mono_object_domain (rmethod), inflated, NULL, error);
 }
 
 MonoReflectionMethod*
index 30595ee5410e1a43cf886966b5e7175899ccf2ff..a29cf91a1cc2fb23cdd1dc9400203e7107d8ac36 100644 (file)
@@ -197,7 +197,10 @@ mono_remoting_marshal_init (void)
                register_icall (mono_marshal_xdomain_copy_out_value, "mono_marshal_xdomain_copy_out_value", "void object object", FALSE);
                register_icall (mono_remoting_wrapper, "mono_remoting_wrapper", "object ptr ptr", FALSE);
                register_icall (mono_upgrade_remote_class_wrapper, "mono_upgrade_remote_class_wrapper", "void object object", FALSE);
+
+#ifndef DISABLE_JIT
                register_icall (mono_compile_method_icall, "mono_compile_method_icall", "ptr ptr", FALSE);
+#endif
 
        }
 
index e3143cc564f100c57a79be6b7903fd167127eaaf..b93c72203221ac36fd6a656ca7a2d5fa4dff61a0 100644 (file)
@@ -160,13 +160,13 @@ set_type_load_exception_type (const char *format, MonoClass *klass)
 {
        char *type_name = mono_type_get_full_name (klass);
        char *parent_name = mono_type_get_full_name (klass->parent);
-       char *message = g_strdup_printf (format, type_name, parent_name);
+       char *message = mono_image_strdup_printf (klass->image, format, type_name, parent_name);
 
        g_free (parent_name);
        g_free (type_name);
        
-       mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, message);
-       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, message);
+       mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, "%s", message);
+       mono_class_set_type_load_failure (klass, "%s", message);
        // note: do not free string given to mono_class_set_failure
 }
 
@@ -183,13 +183,13 @@ set_type_load_exception_methods (const char *format, MonoMethod *override, MonoM
 {
        char *method_name = get_method_full_name (override);
        char *base_name = get_method_full_name (base);
-       char *message = g_strdup_printf (format, method_name, base_name);
+       char *message = mono_image_strdup_printf (override->klass->image, format, method_name, base_name);
 
        g_free (base_name);
        g_free (method_name);
 
-       mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, message);
-       mono_class_set_failure (override->klass, MONO_EXCEPTION_TYPE_LOAD, message);
+       mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, "%s", message);
+       mono_class_set_type_load_failure (override->klass, "%s", message);
        // note: do not free string given to mono_class_set_failure
 }
 
@@ -561,7 +561,7 @@ get_argument_exception (const char *format, MonoMethod *caller, MonoMethod *call
        g_free (callee_name);
        g_free (caller_name);
 
-       mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, message);
+       mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, "%s", message);
        ex = mono_get_exception_argument ("method", message);
        g_free (message);
 
@@ -586,7 +586,7 @@ get_field_access_exception (const char *format, MonoMethod *caller, MonoClassFie
        g_free (field_name);
        g_free (caller_name);
 
-       mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, message);
+       mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, "%s", message);
        ex = mono_get_exception_field_access_msg (message);
        g_free (message);
 
@@ -611,7 +611,7 @@ get_method_access_exception (const char *format, MonoMethod *caller, MonoMethod
        g_free (callee_name);
        g_free (caller_name);
 
-       mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, message);
+       mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, "%s", message);
        ex = mono_get_exception_method_access_msg (message);
        g_free (message);
 
index 332ed1df8f69815856f3e4af7d43b2167692664b..eee26b706018d4efcd05204190364373da3d096f 100644 (file)
@@ -84,6 +84,7 @@ extern void mono_sgen_init_stw (void);
 
 enum {
        INTERNAL_MEM_EPHEMERON_LINK = INTERNAL_MEM_FIRST_CLIENT,
+       INTERNAL_MEM_MOVED_OBJECT,
        INTERNAL_MEM_MAX
 };
 
index c902fcdbe5a92ad3aa5427b21c4bceed9ce42e0a..725a7eccc638d2b2bf8b0c30b57f9f9e27f8d73e 100644 (file)
@@ -16,6 +16,7 @@
 #include "sgen/sgen-client.h"
 #include "sgen/sgen-cardtable.h"
 #include "sgen/sgen-pinning.h"
+#include "sgen/sgen-thread-pool.h"
 #include "metadata/marshal.h"
 #include "metadata/method-builder.h"
 #include "metadata/abi-details.h"
@@ -917,20 +918,12 @@ mono_gc_clear_domain (MonoDomain * domain)
  * Allocation
  */
 
-static gboolean alloc_events = FALSE;
-
-void
-mono_gc_enable_alloc_events (void)
-{
-       alloc_events = TRUE;
-}
-
 void*
 mono_gc_alloc_obj (MonoVTable *vtable, size_t size)
 {
        MonoObject *obj = sgen_alloc_obj (vtable, size);
 
-       if (G_UNLIKELY (alloc_events)) {
+       if (G_UNLIKELY (mono_profiler_events & MONO_PROFILE_ALLOCATIONS)) {
                if (obj)
                        mono_profiler_allocation (obj);
        }
@@ -943,7 +936,7 @@ mono_gc_alloc_pinned_obj (MonoVTable *vtable, size_t size)
 {
        MonoObject *obj = sgen_alloc_obj_pinned (vtable, size);
 
-       if (G_UNLIKELY (alloc_events)) {
+       if (G_UNLIKELY (mono_profiler_events & MONO_PROFILE_ALLOCATIONS)) {
                if (obj)
                        mono_profiler_allocation (obj);
        }
@@ -956,7 +949,7 @@ mono_gc_alloc_mature (MonoVTable *vtable, size_t size)
 {
        MonoObject *obj = sgen_alloc_obj_mature (vtable, size);
 
-       if (G_UNLIKELY (alloc_events)) {
+       if (G_UNLIKELY (mono_profiler_events & MONO_PROFILE_ALLOCATIONS)) {
                if (obj)
                        mono_profiler_allocation (obj);
        }
@@ -1753,7 +1746,7 @@ mono_gc_alloc_vector (MonoVTable *vtable, size_t size, uintptr_t max_length)
        UNLOCK_GC;
 
  done:
-       if (G_UNLIKELY (alloc_events))
+       if (G_UNLIKELY (mono_profiler_events & MONO_PROFILE_ALLOCATIONS))
                mono_profiler_allocation (&arr->obj);
 
        SGEN_ASSERT (6, SGEN_ALIGN_UP (size) == SGEN_ALIGN_UP (sgen_client_par_object_get_size (vtable, (GCObject*)arr)), "Vector has incorrect size.");
@@ -1801,7 +1794,7 @@ mono_gc_alloc_array (MonoVTable *vtable, size_t size, uintptr_t max_length, uint
        UNLOCK_GC;
 
  done:
-       if (G_UNLIKELY (alloc_events))
+       if (G_UNLIKELY (mono_profiler_events & MONO_PROFILE_ALLOCATIONS))
                mono_profiler_allocation (&arr->obj);
 
        SGEN_ASSERT (6, SGEN_ALIGN_UP (size) == SGEN_ALIGN_UP (sgen_client_par_object_get_size (vtable, (GCObject*)arr)), "Array has incorrect size.");
@@ -1842,7 +1835,7 @@ mono_gc_alloc_string (MonoVTable *vtable, size_t size, gint32 len)
        UNLOCK_GC;
 
  done:
-       if (G_UNLIKELY (alloc_events))
+       if (G_UNLIKELY (mono_profiler_events & MONO_PROFILE_ALLOCATIONS))
                mono_profiler_allocation (&str->object);
 
        return str;
@@ -2061,22 +2054,45 @@ sgen_client_collecting_major_3 (SgenPointerQueue *fin_ready_queue, SgenPointerQu
 static void *moved_objects [MOVED_OBJECTS_NUM];
 static int moved_objects_idx = 0;
 
+static SgenPointerQueue moved_objects_queue = SGEN_POINTER_QUEUE_INIT (INTERNAL_MEM_MOVED_OBJECT);
+
 void
 mono_sgen_register_moved_object (void *obj, void *destination)
 {
-       g_assert (mono_profiler_events & MONO_PROFILE_GC_MOVES);
+       /*
+        * This function can be called from SGen's worker threads. We want to try
+        * and avoid exposing those threads to the profiler API, so queue up move
+        * events and send them later when the main GC thread calls
+        * mono_sgen_gc_event_moves ().
+        *
+        * TODO: Once SGen has multiple worker threads, we need to switch to a
+        * lock-free data structure for the queue as multiple threads will be
+        * adding to it at the same time.
+        */
+       if (sgen_thread_pool_is_thread_pool_thread (mono_native_thread_id_get ())) {
+               sgen_pointer_queue_add (&moved_objects_queue, obj);
+               sgen_pointer_queue_add (&moved_objects_queue, destination);
+       } else {
+               if (moved_objects_idx == MOVED_OBJECTS_NUM) {
+                       mono_profiler_gc_moves (moved_objects, moved_objects_idx);
+                       moved_objects_idx = 0;
+               }
 
-       if (moved_objects_idx == MOVED_OBJECTS_NUM) {
-               mono_profiler_gc_moves (moved_objects, moved_objects_idx);
-               moved_objects_idx = 0;
+               moved_objects [moved_objects_idx++] = obj;
+               moved_objects [moved_objects_idx++] = destination;
        }
-       moved_objects [moved_objects_idx++] = obj;
-       moved_objects [moved_objects_idx++] = destination;
 }
 
 void
 mono_sgen_gc_event_moves (void)
 {
+       while (!sgen_pointer_queue_is_empty (&moved_objects_queue)) {
+               void *dst = sgen_pointer_queue_pop (&moved_objects_queue);
+               void *src = sgen_pointer_queue_pop (&moved_objects_queue);
+
+               mono_sgen_register_moved_object (src, dst);
+       }
+
        if (moved_objects_idx) {
                mono_profiler_gc_moves (moved_objects, moved_objects_idx);
                moved_objects_idx = 0;
@@ -2208,12 +2224,9 @@ sgen_client_thread_register (SgenThreadInfo* info, void *stack_bottom_fallback)
        info->client_info.signal = 0;
 #endif
 
-       /* On win32, stack_start_limit should be 0, since the stack can grow dynamically */
        mono_thread_info_get_stack_bounds (&staddr, &stsize);
        if (staddr) {
-#ifndef HOST_WIN32
                info->client_info.stack_start_limit = staddr;
-#endif
                info->client_info.stack_end = staddr + stsize;
        } else {
                gsize stack_bottom = (gsize)stack_bottom_fallback;
@@ -2301,7 +2314,7 @@ sgen_thread_detach (SgenThreadInfo *p)
         * so we assume that if the domain is still registered, we can detach
         * the thread
         */
-       if (mono_domain_get ())
+       if (mono_thread_internal_current_is_attached ())
                mono_thread_detach_internal (mono_thread_internal_current ());
 }
 
@@ -2515,11 +2528,6 @@ mono_gc_get_generation (MonoObject *obj)
        return 1;
 }
 
-void
-mono_gc_enable_events (void)
-{
-}
-
 const char *
 mono_gc_get_gc_name (void)
 {
@@ -2791,6 +2799,7 @@ sgen_client_description_for_internal_mem_type (int type)
 {
        switch (type) {
        case INTERNAL_MEM_EPHEMERON_LINK: return "ephemeron-link";
+       case INTERNAL_MEM_MOVED_OBJECT: return "moved-object";
        default:
                return NULL;
        }
@@ -2973,6 +2982,10 @@ mono_gc_base_init (void)
 
        mono_counters_init ();
 
+#ifndef HOST_WIN32
+       mono_w32handle_init ();
+#endif
+
 #ifdef HEAVY_STATISTICS
        mono_counters_register ("los marked cards", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &los_marked_cards);
        mono_counters_register ("los array cards scanned ", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &los_array_cards);
@@ -3001,6 +3014,9 @@ void
 mono_gc_base_cleanup (void)
 {
        sgen_thread_pool_shutdown ();
+
+       // We should have consumed any outstanding moves.
+       g_assert (sgen_pointer_queue_is_empty (&moved_objects_queue));
 }
 
 gboolean
index 501ceb76d5b8c5a987d26b28891e01ca701cdb53..cdfbb64c027bec5dcb8bb4859e9f64d0bcdfd248 100644 (file)
@@ -1030,7 +1030,7 @@ processing_after_callback (int generation)
                        for (j = 0; j < api_sccs [i]->num_objs; ++j) {
                                GCVTable vtable = SGEN_LOAD_VTABLE (api_sccs [i]->objs [j]);
                                mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC,
-                                       "OBJECT %s (%p) SCC [%d] %s",
+                                       "OBJECT %s.%s (%p) SCC [%d] %s",
                                                sgen_client_vtable_get_namespace (vtable), sgen_client_vtable_get_name (vtable), api_sccs [i]->objs [j],
                                                i,
                                                api_sccs [i]->is_alive  ? "ALIVE" : "DEAD");
index 32bab7ebcb8655cc6adf94c918beb880ce7a8a72..aab29b6466c453eeb89eba799141674c467ad615 100644 (file)
@@ -67,9 +67,10 @@ mono_gc_get_restart_signal (void)
        return -1;
 }
 #else
-       #ifdef _MSC_VER
-               // Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
-               void __mono_win32_sgen_os_coop_quiet_lnk4221(void) {}
-       #endif
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_sgen_os_coop_quiet_lnk4221(void) {}
+#endif
 #endif /* USE_COOP_GC */
 #endif
index 8b78616129a9da8ed7a593fab28349e1143bd791..d78be35069def5fb17d4524afe7d82987cf4e250 100644 (file)
@@ -21,7 +21,7 @@ sgen_resume_thread (SgenThreadInfo *info)
 
        CloseHandle (handle);
 
-       return result != (DWORD)-1;
+       return result != (DWORD)-1 && result > 0;
 }
 
 gboolean
diff --git a/mono/metadata/socket-io-windows-internals.h b/mono/metadata/socket-io-windows-internals.h
new file mode 100644 (file)
index 0000000..b76f9cb
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+* socket-io-windows-internals.h: Windows specific socket code.
+*
+* Copyright 2016 Microsoft
+* Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#ifndef __MONO_METADATA_SOCKET_IO_WINDOWS_INTERNALS_H__
+#define __MONO_METADATA_SOCKET_IO_WINDOWS_INTERNALS_H__
+
+#include <config.h>
+#include <glib.h>
+#include <mono/io-layer/io-layer.h>
+
+SOCKET alertable_accept (SOCKET s, struct sockaddr *addr, int *addrlen, gboolean blocking);
+int alertable_connect (SOCKET s, const struct sockaddr *name, int namelen, gboolean blocking);
+int alertable_recv (SOCKET s, char *buf, int len, int flags, gboolean blocking);
+int alertable_recvfrom (SOCKET s, char *buf, int len, int flags, struct sockaddr *from, int *fromlen, gboolean blocking);
+int alertable_WSARecv (SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount, LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, LPWSAOVERLAPPED lpOverlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, gboolean blocking);
+int alertable_send (SOCKET s, char *buf, int len, int flags, gboolean blocking);
+int alertable_sendto (SOCKET s, const char *buf, int len, int flags, const struct sockaddr *to, int tolen, gboolean blocking);
+int alertable_WSASend (SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount, LPDWORD lpNumberOfBytesRecvd, DWORD lpFlags, LPWSAOVERLAPPED lpOverlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, gboolean blocking);
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT | HAVE_UWP_WINAPI_SUPPORT)
+BOOL alertable_TransmitFile (SOCKET hSocket, HANDLE hFile, DWORD nNumberOfBytesToWrite, DWORD nNumberOfBytesPerSend, LPOVERLAPPED lpOverlapped, LPTRANSMIT_FILE_BUFFERS lpTransmitBuffers, DWORD dwReserved, gboolean blocking);
+#endif
+
+#endif // __MONO_METADATA_SOCKET_IO_WINDOWS_INTERNALS_H__
diff --git a/mono/metadata/socket-io-windows.c b/mono/metadata/socket-io-windows.c
new file mode 100644 (file)
index 0000000..125dbeb
--- /dev/null
@@ -0,0 +1,209 @@
+/*
+* socket-io-windows.c: Windows specific socket code.
+*
+* Copyright 2016 Microsoft
+* Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+
+#include "mono/metadata/socket-io-windows-internals.h"
+
+#define LOGDEBUG(...)  
+
+static gboolean set_blocking (SOCKET sock, gboolean block)
+{
+       u_long non_block = block ? 0 : 1;
+       return ioctlsocket (sock, FIONBIO, &non_block) != SOCKET_ERROR;
+}
+
+static DWORD get_socket_timeout (SOCKET sock, int optname)
+{
+       DWORD timeout = 0;
+       int optlen = sizeof (DWORD);
+       if (getsockopt (sock, SOL_SOCKET, optname, (char *)&timeout, &optlen) == SOCKET_ERROR) {
+               WSASetLastError (0);
+               return WSA_INFINITE;
+       }
+       if (timeout == 0)
+               timeout = WSA_INFINITE; // 0 means infinite
+       return timeout;
+}
+
+/*
+* Performs an alertable wait for the specified event (FD_ACCEPT_BIT,
+* FD_CONNECT_BIT, FD_READ_BIT, FD_WRITE_BIT) on the specified socket.
+* Returns TRUE if the event is fired without errors. Calls WSASetLastError()
+* with WSAEINTR and returns FALSE if the thread is alerted. If the event is
+* fired but with an error WSASetLastError() is called to set the error and the
+* function returns FALSE.
+*/
+static gboolean alertable_socket_wait (SOCKET sock, int event_bit)
+{
+       static char *EVENT_NAMES[] = { "FD_READ", "FD_WRITE", NULL /*FD_OOB*/, "FD_ACCEPT", "FD_CONNECT", "FD_CLOSE" };
+       gboolean success = FALSE;
+       int error = -1;
+       DWORD timeout = WSA_INFINITE;
+       if (event_bit == FD_READ_BIT || event_bit == FD_WRITE_BIT) {
+               timeout = get_socket_timeout (sock, event_bit == FD_READ_BIT ? SO_RCVTIMEO : SO_SNDTIMEO);
+       }
+       WSASetLastError (0);
+       WSAEVENT event = WSACreateEvent ();
+       if (event != WSA_INVALID_EVENT) {
+               if (WSAEventSelect (sock, event, (1 << event_bit) | FD_CLOSE) != SOCKET_ERROR) {
+                       LOGDEBUG (g_message ("%06d - Calling WSAWaitForMultipleEvents () on socket %d", GetCurrentThreadId (), sock));
+                       DWORD ret = WSAWaitForMultipleEvents (1, &event, TRUE, timeout, TRUE);
+                       if (ret == WSA_WAIT_IO_COMPLETION) {
+                               LOGDEBUG (g_message ("%06d - WSAWaitForMultipleEvents () returned WSA_WAIT_IO_COMPLETION for socket %d", GetCurrentThreadId (), sock));
+                               error = WSAEINTR;
+                       } else if (ret == WSA_WAIT_TIMEOUT) {
+                               error = WSAETIMEDOUT;
+                       } else {
+                               g_assert (ret == WSA_WAIT_EVENT_0);
+                               WSANETWORKEVENTS ne = { 0 };
+                               if (WSAEnumNetworkEvents (sock, event, &ne) != SOCKET_ERROR) {
+                                       if (ne.lNetworkEvents & (1 << event_bit) && ne.iErrorCode[event_bit]) {
+                                               LOGDEBUG (g_message ("%06d - %s error %d on socket %d", GetCurrentThreadId (), EVENT_NAMES[event_bit], ne.iErrorCode[event_bit], sock));
+                                               error = ne.iErrorCode[event_bit];
+                                       } else if (ne.lNetworkEvents & FD_CLOSE_BIT && ne.iErrorCode[FD_CLOSE_BIT]) {
+                                               LOGDEBUG (g_message ("%06d - FD_CLOSE error %d on socket %d", GetCurrentThreadId (), ne.iErrorCode[FD_CLOSE_BIT], sock));
+                                               error = ne.iErrorCode[FD_CLOSE_BIT];
+                                       } else {
+                                               LOGDEBUG (g_message ("%06d - WSAEnumNetworkEvents () finished successfully on socket %d", GetCurrentThreadId (), sock));
+                                               success = TRUE;
+                                               error = 0;
+                                       }
+                               }
+                       }
+                       WSAEventSelect (sock, NULL, 0);
+               }
+               WSACloseEvent (event);
+       }
+       if (error != -1) {
+               WSASetLastError (error);
+       }
+       return success;
+}
+
+#define ALERTABLE_SOCKET_CALL(event_bit, blocking, repeat, ret, op, sock, ...) \
+       LOGDEBUG (g_message ("%06d - Performing %s " #op " () on socket %d", GetCurrentThreadId (), blocking ? "blocking" : "non-blocking", sock)); \
+       if (blocking) { \
+               if (set_blocking(sock, FALSE)) { \
+                       while (-1 == (int) (ret = op (sock, __VA_ARGS__))) { \
+                               int _error = WSAGetLastError ();\
+                               if (_error != WSAEWOULDBLOCK && _error != WSA_IO_PENDING) \
+                                       break; \
+                               if (!alertable_socket_wait (sock, event_bit) || !repeat) \
+                                       break; \
+                       } \
+                       int _saved_error = WSAGetLastError (); \
+                       set_blocking (sock, TRUE); \
+                       WSASetLastError (_saved_error); \
+               } \
+       } else { \
+               ret = op (sock, __VA_ARGS__); \
+       } \
+       int _saved_error = WSAGetLastError (); \
+       LOGDEBUG (g_message ("%06d - Finished %s " #op " () on socket %d (ret = %d, WSAGetLastError() = %d)", GetCurrentThreadId (), \
+               blocking ? "blocking" : "non-blocking", sock, ret, _saved_error)); \
+       WSASetLastError (_saved_error);
+
+SOCKET alertable_accept (SOCKET s, struct sockaddr *addr, int *addrlen, gboolean blocking)
+{
+       SOCKET newsock = INVALID_SOCKET;
+       ALERTABLE_SOCKET_CALL (FD_ACCEPT_BIT, blocking, TRUE, newsock, accept, s, addr, addrlen);
+       return newsock;
+}
+
+int alertable_connect (SOCKET s, const struct sockaddr *name, int namelen, gboolean blocking)
+{
+       int ret = SOCKET_ERROR;
+       ALERTABLE_SOCKET_CALL (FD_CONNECT_BIT, blocking, FALSE, ret, connect, s, name, namelen);
+       ret = WSAGetLastError () != 0 ? SOCKET_ERROR : 0;
+       return ret;
+}
+
+int alertable_recv (SOCKET s, char *buf, int len, int flags, gboolean blocking)
+{
+       int ret = SOCKET_ERROR;
+       ALERTABLE_SOCKET_CALL (FD_READ_BIT, blocking, TRUE, ret, recv, s, buf, len, flags);
+       return ret;
+}
+
+int alertable_recvfrom (SOCKET s, char *buf, int len, int flags, struct sockaddr *from, int *fromlen, gboolean blocking)
+{
+       int ret = SOCKET_ERROR;
+       ALERTABLE_SOCKET_CALL (FD_READ_BIT, blocking, TRUE, ret, recvfrom, s, buf, len, flags, from, fromlen);
+       return ret;
+}
+
+int alertable_WSARecv (SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount, LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, LPWSAOVERLAPPED lpOverlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, gboolean blocking)
+{
+       int ret = SOCKET_ERROR;
+       ALERTABLE_SOCKET_CALL (FD_READ_BIT, blocking, TRUE, ret, WSARecv, s, lpBuffers, dwBufferCount, lpNumberOfBytesRecvd, lpFlags, lpOverlapped, lpCompletionRoutine);
+       return ret;
+}
+
+int alertable_send (SOCKET s, char *buf, int len, int flags, gboolean blocking)
+{
+       int ret = SOCKET_ERROR;
+       ALERTABLE_SOCKET_CALL (FD_WRITE_BIT, blocking, FALSE, ret, send, s, buf, len, flags);
+       return ret;
+}
+
+int alertable_sendto (SOCKET s, const char *buf, int len, int flags, const struct sockaddr *to, int tolen, gboolean blocking)
+{
+       int ret = SOCKET_ERROR;
+       ALERTABLE_SOCKET_CALL (FD_WRITE_BIT, blocking, FALSE, ret, sendto, s, buf, len, flags, to, tolen);
+       return ret;
+}
+
+int alertable_WSASend (SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount, LPDWORD lpNumberOfBytesRecvd, DWORD lpFlags, LPWSAOVERLAPPED lpOverlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, gboolean blocking)
+{
+       int ret = SOCKET_ERROR;
+       ALERTABLE_SOCKET_CALL (FD_WRITE_BIT, blocking, FALSE, ret, WSASend, s, lpBuffers, dwBufferCount, lpNumberOfBytesRecvd, lpFlags, lpOverlapped, lpCompletionRoutine);
+       return ret;
+}
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT | HAVE_UWP_WINAPI_SUPPORT)
+BOOL alertable_TransmitFile (SOCKET hSocket, HANDLE hFile, DWORD nNumberOfBytesToWrite, DWORD nNumberOfBytesPerSend, LPOVERLAPPED lpOverlapped, LPTRANSMIT_FILE_BUFFERS lpTransmitBuffers, DWORD dwReserved, gboolean blocking)
+{
+       LOGDEBUG (g_message ("%06d - Performing %s TransmitFile () on socket %d", GetCurrentThreadId (), blocking ? "blocking" : "non-blocking", hSocket));
+
+       int error = 0;
+       if (blocking) {
+               g_assert (lpOverlapped == NULL);
+               OVERLAPPED overlapped = { 0 };
+               overlapped.hEvent = WSACreateEvent ();
+               if (overlapped.hEvent == WSA_INVALID_EVENT)
+                       return FALSE;
+               if (!TransmitFile (hSocket, hFile, nNumberOfBytesToWrite, nNumberOfBytesPerSend, &overlapped, lpTransmitBuffers, dwReserved)) {
+                       error = WSAGetLastError ();
+                       if (error == WSA_IO_PENDING) {
+                               error = 0;
+                               // NOTE: .NET's Socket.SendFile() doesn't honor the Socket's SendTimeout so we shouldn't either
+                               DWORD ret = WaitForSingleObjectEx (overlapped.hEvent, INFINITE, TRUE);
+                               if (ret == WAIT_IO_COMPLETION) {
+                                       LOGDEBUG (g_message ("%06d - WaitForSingleObjectEx () returned WSA_WAIT_IO_COMPLETION for socket %d", GetCurrentThreadId (), hSocket));
+                                       error = WSAEINTR;
+                               } else if (ret == WAIT_TIMEOUT) {
+                                       error = WSAETIMEDOUT;
+                               } else if (ret != WAIT_OBJECT_0) {
+                                       error = GetLastError ();
+                               }
+                       }
+               }
+               WSACloseEvent (overlapped.hEvent);
+       } else {
+               if (!TransmitFile (hSocket, hFile, nNumberOfBytesToWrite, nNumberOfBytesPerSend, lpOverlapped, lpTransmitBuffers, dwReserved)) {
+                       error = WSAGetLastError ();
+               }
+       }
+
+       LOGDEBUG (g_message ("%06d - Finished %s TransmitFile () on socket %d (ret = %d, WSAGetLastError() = %d)", GetCurrentThreadId (), \
+               blocking ? "blocking" : "non-blocking", hSocket, error == 0, error));
+       WSASetLastError (error);
+
+       return error == 0;
+}
+#endif /* #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT | HAVE_UWP_WINAPI_SUPPORT) */
index d4d168da76691a76c3f041b40cf2c45dde95d775..2df84e99c8f9658a398e4c089d1155be2e64906a 100644 (file)
 #include <ifaddrs.h>
 #endif
 
+#if defined(_MSC_VER) && G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT | HAVE_UWP_WINAPI_SUPPORT)
+#include <MSWSock.h>
+#endif
+
 #include "mono/io-layer/socket-wrappers.h"
+#ifdef HOST_WIN32
+#include "mono/metadata/socket-io-windows-internals.h"
+#endif
 
 #define LOGDEBUG(...)  
 /* define LOGDEBUG(...) g_message(__VA_ARGS__)  */
@@ -588,61 +595,6 @@ get_socket_assembly (void)
        return domain->socket_assembly;
 }
 
-static gint32
-get_family_hint (MonoError *error)
-{
-       MonoDomain *domain = mono_domain_get ();
-
-       mono_error_init (error);
-
-       if (!domain->inet_family_hint) {
-               MonoImage *socket_assembly;
-               MonoClass *socket_class;
-               MonoClassField *ipv6_field, *ipv4_field;
-               gint32 ipv6_enabled = -1, ipv4_enabled = -1;
-               MonoVTable *vtable;
-
-               socket_assembly = get_socket_assembly ();
-               g_assert (socket_assembly);
-
-               socket_class = mono_class_load_from_name (socket_assembly, "System.Net.Sockets", "Socket");
-
-               ipv4_field = mono_class_get_field_from_name (socket_class, "ipv4_supported");
-               g_assert (ipv4_field);
-
-               ipv6_field = mono_class_get_field_from_name (socket_class, "ipv6_supported");
-               g_assert (ipv6_field);
-
-               vtable = mono_class_vtable (mono_domain_get (), socket_class);
-               g_assert (vtable);
-
-               mono_runtime_class_init_full (vtable, error);
-               return_val_if_nok (error, -1);
-
-               mono_field_static_get_value_checked (vtable, ipv4_field, &ipv4_enabled, error);
-               return_val_if_nok (error, -1);
-               mono_field_static_get_value_checked (vtable, ipv6_field, &ipv6_enabled, error);
-               return_val_if_nok (error, -1);
-
-               mono_domain_lock (domain);
-               if (ipv4_enabled == 1 && ipv6_enabled == 1) {
-                       domain->inet_family_hint = 1;
-               } else if (ipv4_enabled == 1) {
-                       domain->inet_family_hint = 2;
-               } else {
-                       domain->inet_family_hint = 3;
-               }
-               mono_domain_unlock (domain);
-       }
-       switch (domain->inet_family_hint) {
-       case 1: return PF_UNSPEC;
-       case 2: return PF_INET;
-       case 3: return PF_INET6;
-       default:
-               return PF_UNSPEC;
-       }
-}
-
 gpointer
 ves_icall_System_Net_Sockets_Socket_Socket_internal (MonoObject *this_obj, gint32 family, gint32 type, gint32 proto, gint32 *werror)
 {
@@ -765,7 +717,7 @@ ves_icall_System_Net_Sockets_Socket_Accept_internal (SOCKET sock, gint32 *werror
        {
                MonoInternalThread *curthread = mono_thread_internal_current ();
                curthread->interrupt_on_stop = (gpointer)TRUE;
-               newsock = _wapi_accept (sock, NULL, 0);
+               newsock = alertable_accept (sock, NULL, 0, blocking);
                curthread->interrupt_on_stop = (gpointer)FALSE;
        }
 #else
@@ -1303,7 +1255,7 @@ ves_icall_System_Net_Sockets_Socket_Poll_internal (SOCKET sock, gint mode,
 }
 
 void
-ves_icall_System_Net_Sockets_Socket_Connect_internal (SOCKET sock, MonoObject *sockaddr, gint32 *werror)
+ves_icall_System_Net_Sockets_Socket_Connect_internal (SOCKET sock, MonoObject *sockaddr, gint32 *werror, gboolean blocking)
 {
        MonoError error;
        struct sockaddr *sa;
@@ -1331,7 +1283,11 @@ ves_icall_System_Net_Sockets_Socket_Connect_internal (SOCKET sock, MonoObject *s
 
        MONO_ENTER_GC_SAFE;
 
+#ifdef HOST_WIN32
+       ret = alertable_connect (sock, sa, sa_size, blocking);
+#else
        ret = _wapi_connect (sock, sa, sa_size);
+#endif
 
        MONO_EXIT_GC_SAFE;
 
@@ -1345,6 +1301,7 @@ ves_icall_System_Net_Sockets_Socket_Connect_internal (SOCKET sock, MonoObject *s
        g_free (sa);
 }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT | HAVE_UWP_WINAPI_SUPPORT)
 /* These #defines from mswsock.h from wine.  Defining them here allows
  * us to build this file on a mingw box that doesn't know the magic
  * numbers, but still run on a newer windows box that does.
@@ -1435,9 +1392,10 @@ ves_icall_System_Net_Sockets_Socket_Disconnect_internal (SOCKET sock, MonoBoolea
        if (interrupted)
                *werror = WSAEINTR;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT | HAVE_UWP_WINAPI_SUPPORT) */
 
 gint32
-ves_icall_System_Net_Sockets_Socket_Receive_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *werror)
+ves_icall_System_Net_Sockets_Socket_Receive_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *werror, gboolean blocking)
 {
        int ret;
        guchar *buf;
@@ -1469,7 +1427,7 @@ ves_icall_System_Net_Sockets_Socket_Receive_internal (SOCKET sock, MonoArray *bu
 #ifdef HOST_WIN32
        {
                curthread->interrupt_on_stop = (gpointer)TRUE;
-               ret = _wapi_recv (sock, buf, count, recvflags);
+               ret = alertable_recv (sock, buf, count, recvflags, blocking);
                curthread->interrupt_on_stop = (gpointer)FALSE;
        }
 #else
@@ -1492,7 +1450,7 @@ ves_icall_System_Net_Sockets_Socket_Receive_internal (SOCKET sock, MonoArray *bu
 }
 
 gint32
-ves_icall_System_Net_Sockets_Socket_Receive_array_internal (SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *werror)
+ves_icall_System_Net_Sockets_Socket_Receive_array_internal (SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *werror, gboolean blocking)
 {
        int ret, count;
        gboolean interrupted;
@@ -1519,7 +1477,11 @@ ves_icall_System_Net_Sockets_Socket_Receive_array_internal (SOCKET sock, MonoArr
 
        MONO_ENTER_GC_SAFE;
 
+#ifdef HOST_WIN32
+       ret = alertable_WSARecv (sock, wsabufs, count, &recv, &recvflags, NULL, NULL, blocking);
+#else
        ret = WSARecv (sock, wsabufs, count, &recv, &recvflags, NULL, NULL);
+#endif
 
        MONO_EXIT_GC_SAFE;
 
@@ -1537,7 +1499,7 @@ ves_icall_System_Net_Sockets_Socket_Receive_array_internal (SOCKET sock, MonoArr
 }
 
 gint32
-ves_icall_System_Net_Sockets_Socket_ReceiveFrom_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject **sockaddr, gint32 *werror)
+ves_icall_System_Net_Sockets_Socket_ReceiveFrom_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject **sockaddr, gint32 *werror, gboolean blocking)
 {
        MonoError error;
        int ret;
@@ -1579,7 +1541,11 @@ ves_icall_System_Net_Sockets_Socket_ReceiveFrom_internal (SOCKET sock, MonoArray
 
        MONO_ENTER_GC_SAFE;
 
+#ifdef HOST_WIN32
+       ret = alertable_recvfrom (sock, buf, count, recvflags, sa, &sa_size, blocking);
+#else
        ret = _wapi_recvfrom (sock, buf, count, recvflags, sa, &sa_size);
+#endif
 
        MONO_EXIT_GC_SAFE;
 
@@ -1617,7 +1583,7 @@ ves_icall_System_Net_Sockets_Socket_ReceiveFrom_internal (SOCKET sock, MonoArray
 }
 
 gint32
-ves_icall_System_Net_Sockets_Socket_Send_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *werror)
+ves_icall_System_Net_Sockets_Socket_Send_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *werror, gboolean blocking)
 {
        int ret;
        guchar *buf;
@@ -1651,7 +1617,11 @@ ves_icall_System_Net_Sockets_Socket_Send_internal (SOCKET sock, MonoArray *buffe
 
        MONO_ENTER_GC_SAFE;
 
+#ifdef HOST_WIN32
+       ret = alertable_send (sock, buf, count, sendflags, blocking);
+#else
        ret = _wapi_send (sock, buf, count, sendflags);
+#endif
 
        MONO_EXIT_GC_SAFE;
 
@@ -1669,7 +1639,7 @@ ves_icall_System_Net_Sockets_Socket_Send_internal (SOCKET sock, MonoArray *buffe
 }
 
 gint32
-ves_icall_System_Net_Sockets_Socket_Send_array_internal (SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *werror)
+ves_icall_System_Net_Sockets_Socket_Send_array_internal (SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *werror, gboolean blocking)
 {
        int ret, count;
        DWORD sent;
@@ -1696,7 +1666,11 @@ ves_icall_System_Net_Sockets_Socket_Send_array_internal (SOCKET sock, MonoArray
 
        MONO_ENTER_GC_SAFE;
 
+#ifdef HOST_WIN32
+       ret = alertable_WSASend (sock, wsabufs, count, &sent, sendflags, NULL, NULL, blocking);
+#else
        ret = WSASend (sock, wsabufs, count, &sent, sendflags, NULL, NULL);
+#endif
 
        MONO_EXIT_GC_SAFE;
 
@@ -1714,7 +1688,7 @@ ves_icall_System_Net_Sockets_Socket_Send_array_internal (SOCKET sock, MonoArray
 }
 
 gint32
-ves_icall_System_Net_Sockets_Socket_SendTo_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject *sockaddr, gint32 *werror)
+ves_icall_System_Net_Sockets_Socket_SendTo_internal (SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject *sockaddr, gint32 *werror, gboolean blocking)
 {
        MonoError error;
        int ret;
@@ -1762,7 +1736,11 @@ ves_icall_System_Net_Sockets_Socket_SendTo_internal (SOCKET sock, MonoArray *buf
 
        MONO_ENTER_GC_SAFE;
 
+#ifdef HOST_WIN32
+       ret = alertable_sendto (sock, buf, count, sendflags, sa, sa_size, blocking);
+#else
        ret = _wapi_sendto (sock, buf, count, sendflags, sa, sa_size);
+#endif
 
        MONO_EXIT_GC_SAFE;
 
@@ -1787,7 +1765,7 @@ Socket_to_SOCKET (MonoObject *sockobj)
        MonoSafeHandle *safe_handle;
        MonoClassField *field;
        
-       field = mono_class_get_field_from_name (sockobj->vtable->klass, "safe_handle");
+       field = mono_class_get_field_from_name (sockobj->vtable->klass, "m_Handle");
        safe_handle = ((MonoSafeHandle *)(*(gpointer *)(((char *)sockobj) + field->offset)));
 
        if (safe_handle == NULL)
@@ -2613,50 +2591,18 @@ leave2:
        return is_ok (error);
 }
 
-static int
-get_addrinfo_family_hint (MonoError *error)
-{
-       int hint;
-
-       mono_error_init (error);
-
-       hint = get_family_hint (error);
-       return_val_if_nok (error, 0);
-
-       switch (hint) {
-       case PF_UNSPEC:
-               return MONO_HINT_UNSPECIFIED;
-       case PF_INET:
-               return MONO_HINT_IPV4;
-#ifdef PF_INET6
-       case PF_INET6:
-               return MONO_HINT_IPV6;
-#endif
-       default:
-               g_error ("invalid hint");
-               return 0;
-       }
-}
-
 MonoBoolean
-ves_icall_System_Net_Dns_GetHostByName_internal (MonoString *host, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list)
+ves_icall_System_Net_Dns_GetHostByName_internal (MonoString *host, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list, gint32 hint)
 {
        MonoError error;
        gboolean add_local_ips = FALSE, add_info_ok = TRUE;
        gchar this_hostname [256];
        MonoAddressInfo *info = NULL;
-       int hint;
 
        char *hostname = mono_string_to_utf8_checked (host, &error);
        if (mono_error_set_pending_exception (&error))
                return FALSE;
 
-       hint = get_addrinfo_family_hint (&error);
-       if (!mono_error_ok (&error)) {
-               mono_error_set_pending_exception (&error);
-               return FALSE;
-       }
-
        if (*hostname == '\0') {
                add_local_ips = TRUE;
                *h_name = host;
@@ -2691,14 +2637,14 @@ ves_icall_System_Net_Dns_GetHostByName_internal (MonoString *host, MonoString **
 }
 
 MonoBoolean
-ves_icall_System_Net_Dns_GetHostByAddr_internal (MonoString *addr, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list)
+ves_icall_System_Net_Dns_GetHostByAddr_internal (MonoString *addr, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list, gint32 hint)
 {
        char *address;
        struct sockaddr_in saddr;
        struct sockaddr_in6 saddr6;
        MonoAddressInfo *info = NULL;
        MonoError error;
-       gint32 family, hint;
+       gint32 family;
        gchar hostname [NI_MAXHOST] = { 0 };
        gboolean ret;
 
@@ -2745,11 +2691,6 @@ ves_icall_System_Net_Dns_GetHostByAddr_internal (MonoString *addr, MonoString **
        if (!ret)
                return FALSE;
 
-       hint = get_addrinfo_family_hint (&error);
-       if (!mono_error_ok (&error)) {
-               mono_error_set_pending_exception (&error);
-               return FALSE;
-       }
        if (mono_get_address_info (hostname, 0, hint | MONO_HINT_CANONICAL_NAME | MONO_HINT_CONFIGURED_ONLY, &info) != 0)
                return FALSE;
 
@@ -2773,11 +2714,11 @@ ves_icall_System_Net_Dns_GetHostName_internal (MonoString **h_name)
        return TRUE;
 }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT | HAVE_UWP_WINAPI_SUPPORT)
 gboolean
-ves_icall_System_Net_Sockets_Socket_SendFile_internal (SOCKET sock, MonoString *filename, MonoArray *pre_buffer, MonoArray *post_buffer, gint flags)
+ves_icall_System_Net_Sockets_Socket_SendFile_internal (SOCKET sock, MonoString *filename, MonoArray *pre_buffer, MonoArray *post_buffer, gint flags, gint32 *werror, gboolean blocking)
 {
        HANDLE file;
-       gint32 werror;
        gboolean ret;
        gboolean interrupted;
        TRANSMIT_FILE_BUFFERS buffers;
@@ -2787,10 +2728,10 @@ ves_icall_System_Net_Sockets_Socket_SendFile_internal (SOCKET sock, MonoString *
 
        /* FIXME: replace file by a proper fd that we can call open and close on, as they are interruptible */
 
-       file = ves_icall_System_IO_MonoIO_Open (filename, FileMode_Open, FileAccess_Read, FileShare_Read, 0, &werror);
+       file = ves_icall_System_IO_MonoIO_Open (filename, FileMode_Open, FileAccess_Read, FileShare_Read, 0, werror);
 
        if (file == INVALID_HANDLE_VALUE) {
-               SetLastError (werror);
+               SetLastError (*werror);
                return FALSE;
        }
 
@@ -2813,14 +2754,21 @@ ves_icall_System_Net_Sockets_Socket_SendFile_internal (SOCKET sock, MonoString *
 
        MONO_ENTER_GC_SAFE;
 
+#ifdef HOST_WIN32
+       ret = alertable_TransmitFile (sock, file, 0, 0, NULL, &buffers, flags, blocking);
+#else
        ret = TransmitFile (sock, file, 0, 0, NULL, &buffers, flags);
+#endif
 
        MONO_EXIT_GC_SAFE;
 
+       if (!ret)
+               *werror = WSAGetLastError ();
+
        mono_thread_info_uninstall_interrupt (&interrupted);
        if (interrupted) {
                CloseHandle (file);
-               SetLastError (WSAEINTR);
+               *werror = WSAEINTR;
                return FALSE;
        }
 
@@ -2830,8 +2778,12 @@ ves_icall_System_Net_Sockets_Socket_SendFile_internal (SOCKET sock, MonoString *
 
        MONO_EXIT_GC_SAFE;
 
+       if (*werror)
+               return FALSE;
+
        return ret;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT | HAVE_UWP_WINAPI_SUPPORT) */
 
 gboolean
 ves_icall_System_Net_Sockets_Socket_SupportPortReuse (MonoProtocolType proto)
index e228f0a2e63df038682a3d004622f541cf928284..7a8c9361ad6334ca7843275c0eb43f9ac99ebe18 100644 (file)
@@ -169,25 +169,25 @@ extern void ves_icall_System_Net_Sockets_Socket_Listen_internal(SOCKET sock, gui
 extern MonoObject *ves_icall_System_Net_Sockets_Socket_LocalEndPoint_internal(SOCKET sock, gint32 af, gint32 *error);
 extern MonoObject *ves_icall_System_Net_Sockets_Socket_RemoteEndPoint_internal(SOCKET sock, gint32 af, gint32 *error);
 extern void ves_icall_System_Net_Sockets_Socket_Bind_internal(SOCKET sock, MonoObject *sockaddr, gint32 *error);
-extern void ves_icall_System_Net_Sockets_Socket_Connect_internal(SOCKET sock, MonoObject *sockaddr, gint32 *error);
-extern gint32 ves_icall_System_Net_Sockets_Socket_Receive_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *error);
-extern gint32 ves_icall_System_Net_Sockets_Socket_Receive_array_internal(SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *error);
-extern gint32 ves_icall_System_Net_Sockets_Socket_ReceiveFrom_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject **sockaddr, gint32 *error);
-extern gint32 ves_icall_System_Net_Sockets_Socket_Send_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *error);
-extern gint32 ves_icall_System_Net_Sockets_Socket_Send_array_internal(SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *error);
-extern gint32 ves_icall_System_Net_Sockets_Socket_SendTo_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject *sockaddr, gint32 *error);
+extern void ves_icall_System_Net_Sockets_Socket_Connect_internal(SOCKET sock, MonoObject *sockaddr, gint32 *error, gboolean blocking);
+extern gint32 ves_icall_System_Net_Sockets_Socket_Receive_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *error, gboolean blocking);
+extern gint32 ves_icall_System_Net_Sockets_Socket_Receive_array_internal(SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *error, gboolean blocking);
+extern gint32 ves_icall_System_Net_Sockets_Socket_ReceiveFrom_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject **sockaddr, gint32 *error, gboolean blocking);
+extern gint32 ves_icall_System_Net_Sockets_Socket_Send_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, gint32 *error, gboolean blocking);
+extern gint32 ves_icall_System_Net_Sockets_Socket_Send_array_internal(SOCKET sock, MonoArray *buffers, gint32 flags, gint32 *error, gboolean blocking);
+extern gint32 ves_icall_System_Net_Sockets_Socket_SendTo_internal(SOCKET sock, MonoArray *buffer, gint32 offset, gint32 count, gint32 flags, MonoObject *sockaddr, gint32 *error, gboolean blocking);
 extern void ves_icall_System_Net_Sockets_Socket_Select_internal(MonoArray **sockets, gint32 timeout, gint32 *error);
 extern void ves_icall_System_Net_Sockets_Socket_Shutdown_internal(SOCKET sock, gint32 how, gint32 *error);
 extern void ves_icall_System_Net_Sockets_Socket_GetSocketOption_obj_internal(SOCKET sock, gint32 level, gint32 name, MonoObject **obj_val, gint32 *error);
 extern void ves_icall_System_Net_Sockets_Socket_GetSocketOption_arr_internal(SOCKET sock, gint32 level, gint32 name, MonoArray **byte_val, gint32 *error);
 extern void ves_icall_System_Net_Sockets_Socket_SetSocketOption_internal(SOCKET sock, gint32 level, gint32 name, MonoObject *obj_val, MonoArray *byte_val, gint32 int_val, gint32 *error);
 extern int ves_icall_System_Net_Sockets_Socket_IOControl_internal (SOCKET sock, gint32 code, MonoArray *input, MonoArray *output, gint32 *error);
-extern MonoBoolean ves_icall_System_Net_Dns_GetHostByName_internal(MonoString *host, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list);
-extern MonoBoolean ves_icall_System_Net_Dns_GetHostByAddr_internal(MonoString *addr, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list);
+extern MonoBoolean ves_icall_System_Net_Dns_GetHostByName_internal(MonoString *host, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list, gint32 hint);
+extern MonoBoolean ves_icall_System_Net_Dns_GetHostByAddr_internal(MonoString *addr, MonoString **h_name, MonoArray **h_aliases, MonoArray **h_addr_list, gint32 hint);
 extern MonoBoolean ves_icall_System_Net_Dns_GetHostName_internal(MonoString **h_name);
 extern MonoBoolean ves_icall_System_Net_Sockets_Socket_Poll_internal (SOCKET sock, gint mode, gint timeout, gint32 *error);
 extern void ves_icall_System_Net_Sockets_Socket_Disconnect_internal(SOCKET sock, MonoBoolean reuse, gint32 *error);
-extern gboolean ves_icall_System_Net_Sockets_Socket_SendFile_internal (SOCKET sock, MonoString *filename, MonoArray *pre_buffer, MonoArray *post_buffer, gint flags);
+extern gboolean ves_icall_System_Net_Sockets_Socket_SendFile_internal (SOCKET sock, MonoString *filename, MonoArray *pre_buffer, MonoArray *post_buffer, gint flags, gint32 *error, gboolean blocking);
 void icall_cancel_blocking_socket_operation (MonoThread *thread);
 extern gboolean ves_icall_System_Net_Sockets_Socket_SupportPortReuse (MonoProtocolType proto);
 
index ef91c85b0ace8172ccd7a7aa23727f40a6fe643d..1d9e50ba93ce86dd692da0586f8e951df4c590de 100644 (file)
@@ -591,7 +591,6 @@ handle_enum:
        return idx;
 }
 
-
 guint32
 mono_dynimage_encode_field_signature (MonoDynamicImage *assembly, MonoReflectionFieldBuilder *fb, MonoError *error)
 {
@@ -605,9 +604,6 @@ mono_dynimage_encode_field_signature (MonoDynamicImage *assembly, MonoReflection
        MonoType *type;
        MonoClass *klass;
 
-       mono_reflection_init_type_builder_generics (fb->type, error);
-       return_val_if_nok (error, 0);
-
        type = mono_reflection_type_get_handle ((MonoReflectionType*)fb->type, error);
        return_val_if_nok (error, 0);
        klass = mono_class_from_mono_type (type);
@@ -806,32 +802,6 @@ mono_image_typedef_or_ref (MonoDynamicImage *assembly, MonoType *type)
        return mono_dynimage_encode_typedef_or_ref_full (assembly, type, TRUE);
 }
 
-guint32
-mono_dynimage_encode_generic_method_definition_sig (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *mb)
-{
-       SigBuffer buf;
-       int i;
-       guint32 nparams = mono_array_length (mb->generic_params);
-       guint32 idx;
-
-       if (!assembly->save)
-               return 0;
-
-       sigbuffer_init (&buf, 32);
-
-       sigbuffer_add_value (&buf, 0xa);
-       sigbuffer_add_value (&buf, nparams);
-
-       for (i = 0; i < nparams; i++) {
-               sigbuffer_add_value (&buf, MONO_TYPE_MVAR);
-               sigbuffer_add_value (&buf, i);
-       }
-
-       idx = sigbuffer_add_to_blob_cached (assembly, &buf);
-       sigbuffer_free (&buf);
-       return idx;
-}
-
 guint32
 mono_dynimage_encode_generic_method_sig (MonoDynamicImage *assembly, MonoGenericContext *context)
 {
@@ -858,84 +828,6 @@ mono_dynimage_encode_generic_method_sig (MonoDynamicImage *assembly, MonoGeneric
        return idx;
 }
 
-#ifndef DISABLE_REFLECTION_EMIT
-guint32
-mono_dynimage_encode_generic_typespec (MonoDynamicImage *assembly, MonoReflectionTypeBuilder *tb, MonoError *error)
-{
-       MonoDynamicTable *table;
-       MonoClass *klass;
-       MonoType *type;
-       guint32 *values;
-       guint32 token;
-       SigBuffer buf;
-       int count, i;
-
-       /*
-        * We're creating a TypeSpec for the TypeBuilder of a generic type declaration,
-        * ie. what we'd normally use as the generic type in a TypeSpec signature.
-        * Because of this, we must not insert it into the `typeref' hash table.
-        */
-       type = mono_reflection_type_get_handle ((MonoReflectionType*)tb, error);
-       return_val_if_nok (error, 0);
-       token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->typespec, type));
-       if (token)
-               return token;
-
-       sigbuffer_init (&buf, 32);
-
-       g_assert (tb->generic_params);
-       klass = mono_class_from_mono_type (type);
-
-       if (tb->generic_container) {
-               if (!mono_reflection_create_generic_class (tb, error))
-                       goto fail;
-       }
-
-       sigbuffer_add_value (&buf, MONO_TYPE_GENERICINST);
-       g_assert (klass->generic_container);
-       sigbuffer_add_value (&buf, klass->byval_arg.type);
-       sigbuffer_add_value (&buf, mono_dynimage_encode_typedef_or_ref_full (assembly, &klass->byval_arg, FALSE));
-
-       count = mono_array_length (tb->generic_params);
-       sigbuffer_add_value (&buf, count);
-       for (i = 0; i < count; i++) {
-               MonoReflectionGenericParam *gparam;
-
-               gparam = mono_array_get (tb->generic_params, MonoReflectionGenericParam *, i);
-               MonoType *gparam_type = mono_reflection_type_get_handle ((MonoReflectionType*)gparam, error);
-               if (!is_ok (error))
-                       goto fail;
-
-               encode_type (assembly, gparam_type, &buf);
-       }
-
-       table = &assembly->tables [MONO_TABLE_TYPESPEC];
-
-       if (assembly->save) {
-               token = sigbuffer_add_to_blob_cached (assembly, &buf);
-               alloc_table (table, table->rows + 1);
-               values = table->values + table->next_idx * MONO_TYPESPEC_SIZE;
-               values [MONO_TYPESPEC_SIGNATURE] = token;
-       }
-       sigbuffer_free (&buf);
-
-       token = MONO_TYPEDEFORREF_TYPESPEC | (table->next_idx << MONO_TYPEDEFORREF_BITS);
-       g_hash_table_insert (assembly->typespec, type, GUINT_TO_POINTER(token));
-       table->next_idx ++;
-       return token;
-fail:
-       sigbuffer_free (&buf);
-       return 0;
-}
-#else /*DISABLE_REFLECTION_EMIT*/
-guint32
-mono_dynimage_encode_generic_typespec (MonoDynamicImage *assembly, MonoReflectionTypeBuilder *tb, MonoError *error)
-{
-       g_assert_not_reached ();
-       return 0;
-}
-#endif /*DISABLE_REFLECTION_EMIT*/
-
 #ifndef DISABLE_REFLECTION_EMIT
 guint32
 mono_dynimage_encode_reflection_sighelper (MonoDynamicImage *assembly, MonoReflectionSigHelper *helper, MonoError *error)
index 87d823a22e0f48b55626f6627714f3e55410063a..5f902cd7cc086bf64cd4957f526171ee6ac29aab 100644 (file)
@@ -74,15 +74,6 @@ mono_is_sr_mono_cmethod (MonoClass *klass);
 gboolean
 mono_is_sr_mono_property (MonoClass *klass);
 
-gboolean
-mono_reflection_create_generic_class (MonoReflectionTypeBuilder *tb, MonoError *error);
-
-MonoMethod*
-mono_reflection_method_builder_to_mono_method (MonoReflectionMethodBuilder *mb, MonoError *error);
-
-MonoMethod*
-mono_reflection_method_on_tb_inst_get_handle (MonoReflectionMethodOnTypeBuilderInst *m, MonoError *error);
-
 gpointer
 mono_reflection_resolve_object (MonoImage *image, MonoObject *obj, MonoClass **handle_class, MonoGenericContext *context, MonoError *error);
 
@@ -98,9 +89,6 @@ mono_reflection_methodbuilder_from_method_builder (ReflectionMethodBuilder *rmb,
 gboolean
 mono_reflection_methodbuilder_from_ctor_builder (ReflectionMethodBuilder *rmb, MonoReflectionCtorBuilder *mb,
                                                 MonoError *error);
-
-void
-mono_reflection_init_type_builder_generics (MonoObject *type, MonoError *error);
                                                            
 guint32
 mono_reflection_resolution_scope_from_image (MonoDynamicImage *assembly, MonoImage *image);
@@ -129,15 +117,9 @@ guint32
 mono_dynimage_encode_method_builder_signature (MonoDynamicImage *assembly, ReflectionMethodBuilder *mb,
                                               MonoError *error);
 
-guint32
-mono_dynimage_encode_generic_method_definition_sig (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *mb);
-
 guint32
 mono_dynimage_encode_generic_method_sig (MonoDynamicImage *assembly, MonoGenericContext *context);
 
-guint32
-mono_dynimage_encode_generic_typespec (MonoDynamicImage *assembly, MonoReflectionTypeBuilder *tb, MonoError *error);
-
 guint32
 mono_dynimage_encode_typedef_or_ref_full (MonoDynamicImage *assembly, MonoType *type, gboolean try_typespec);
 
index ff2f93a767be1a8ef630b34a058a2fa076a48db5..3256f8cb1990d4e3b18a5d2e8e92d668ada6fa08 100644 (file)
@@ -705,7 +705,6 @@ mono_image_get_field_info (MonoReflectionFieldBuilder *fb, MonoDynamicImage *ass
        values [MONO_FIELD_SIGNATURE] = mono_dynimage_encode_field_signature (assembly, fb, error);
        return_if_nok (error);
 
-
        if (fb->offset != -1) {
                table = &assembly->tables [MONO_TABLE_FIELDLAYOUT];
                table->rows ++;
@@ -1691,9 +1690,6 @@ fixup_method (MonoReflectionILGen *ilgen, gpointer value, MonoDynamicImage *asse
 {
        guint32 code_idx = GPOINTER_TO_UINT (value);
        MonoReflectionILTokenInfo *iltoken;
-       MonoReflectionFieldBuilder *field;
-       MonoReflectionCtorBuilder *ctor;
-       MonoReflectionMethodBuilder *method;
        MonoReflectionTypeBuilder *tb;
        MonoReflectionArrayMethod *am;
        guint32 i, idx = 0;
@@ -1705,8 +1701,7 @@ fixup_method (MonoReflectionILGen *ilgen, gpointer value, MonoDynamicImage *asse
                switch (target [3]) {
                case MONO_TABLE_FIELD:
                        if (!strcmp (iltoken->member->vtable->klass->name, "FieldBuilder")) {
-                               field = (MonoReflectionFieldBuilder *)iltoken->member;
-                               idx = field->table_idx;
+                               g_assert_not_reached ();
                        } else if (!strcmp (iltoken->member->vtable->klass->name, "MonoField")) {
                                MonoClassField *f = ((MonoReflectionField*)iltoken->member)->field;
                                idx = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->field_to_table_idx, f));
@@ -1716,11 +1711,9 @@ fixup_method (MonoReflectionILGen *ilgen, gpointer value, MonoDynamicImage *asse
                        break;
                case MONO_TABLE_METHOD:
                        if (!strcmp (iltoken->member->vtable->klass->name, "MethodBuilder")) {
-                               method = (MonoReflectionMethodBuilder *)iltoken->member;
-                               idx = method->table_idx;
+                               g_assert_not_reached ();
                        } else if (!strcmp (iltoken->member->vtable->klass->name, "ConstructorBuilder")) {
-                               ctor = (MonoReflectionCtorBuilder *)iltoken->member;
-                               idx = ctor->table_idx;
+                               g_assert_not_reached ();
                        } else if (!strcmp (iltoken->member->vtable->klass->name, "MonoMethod") || 
                                           !strcmp (iltoken->member->vtable->klass->name, "MonoCMethod")) {
                                MonoMethod *m = ((MonoReflectionMethod*)iltoken->member)->method;
@@ -1730,47 +1723,67 @@ fixup_method (MonoReflectionILGen *ilgen, gpointer value, MonoDynamicImage *asse
                        }
                        break;
                case MONO_TABLE_TYPEDEF:
-                       if (strcmp (iltoken->member->vtable->klass->name, "TypeBuilder"))
+                       if (!strcmp (iltoken->member->vtable->klass->name, "TypeBuilder")) {
+                               g_assert_not_reached ();
+                       } else if (!strcmp (iltoken->member->vtable->klass->name, "RuntimeType")) {
+                               MonoClass *k = mono_class_from_mono_type (((MonoReflectionType*)iltoken->member)->type);
+                               MonoObject *obj = mono_class_get_ref_info (k);
+                               g_assert (obj);
+                               g_assert (!strcmp (obj->vtable->klass->name, "TypeBuilder"));
+                               tb = (MonoReflectionTypeBuilder*)obj;
+                               idx = tb->table_idx;
+                       } else {
                                g_assert_not_reached ();
-                       tb = (MonoReflectionTypeBuilder *)iltoken->member;
-                       idx = tb->table_idx;
+                       }
                        break;
                case MONO_TABLE_MEMBERREF:
                        if (!strcmp (iltoken->member->vtable->klass->name, "MonoArrayMethod")) {
                                am = (MonoReflectionArrayMethod*)iltoken->member;
                                idx = am->table_idx;
                        } else if (!strcmp (iltoken->member->vtable->klass->name, "MonoMethod") ||
-                                  !strcmp (iltoken->member->vtable->klass->name, "MonoCMethod") ||
-                                  !strcmp (iltoken->member->vtable->klass->name, "MonoGenericMethod") ||
-                                  !strcmp (iltoken->member->vtable->klass->name, "MonoGenericCMethod")) {
+                                          !strcmp (iltoken->member->vtable->klass->name, "MonoCMethod")) {
                                MonoMethod *m = ((MonoReflectionMethod*)iltoken->member)->method;
                                g_assert (m->klass->generic_class || m->klass->generic_container);
                                continue;
                        } else if (!strcmp (iltoken->member->vtable->klass->name, "FieldBuilder")) {
+                               g_assert_not_reached ();
                                continue;
                        } else if (!strcmp (iltoken->member->vtable->klass->name, "MonoField")) {
                                continue;
                        } else if (!strcmp (iltoken->member->vtable->klass->name, "MethodBuilder") ||
                                        !strcmp (iltoken->member->vtable->klass->name, "ConstructorBuilder")) {
+                               g_assert_not_reached ();
                                continue;
                        } else if (!strcmp (iltoken->member->vtable->klass->name, "FieldOnTypeBuilderInst")) {
+                               g_assert_not_reached ();
                                continue;
                        } else if (!strcmp (iltoken->member->vtable->klass->name, "MethodOnTypeBuilderInst")) {
+                               g_assert_not_reached ();
                                continue;
                        } else if (!strcmp (iltoken->member->vtable->klass->name, "ConstructorOnTypeBuilderInst")) {
+                               g_assert_not_reached ();
                                continue;
                        } else {
                                g_assert_not_reached ();
                        }
                        break;
                case MONO_TABLE_METHODSPEC:
-                       if (!strcmp (iltoken->member->vtable->klass->name, "MonoGenericMethod")) {
+                       if (!strcmp (iltoken->member->vtable->klass->name, "MonoMethod")) {
                                MonoMethod *m = ((MonoReflectionMethod*)iltoken->member)->method;
                                g_assert (mono_method_signature (m)->generic_param_count);
                                continue;
                        } else if (!strcmp (iltoken->member->vtable->klass->name, "MethodBuilder")) {
+                               g_assert_not_reached ();
                                continue;
                        } else if (!strcmp (iltoken->member->vtable->klass->name, "MethodOnTypeBuilderInst")) {
+                               g_assert_not_reached ();
+                               continue;
+                       } else {
+                               g_assert_not_reached ();
+                       }
+                       break;
+               case MONO_TABLE_TYPESPEC:
+                       if (!strcmp (iltoken->member->vtable->klass->name, "RuntimeType")) {
                                continue;
                        } else {
                                g_assert_not_reached ();
index c15bd42b74aabd2b63709a831bcd20cc338e128d..3bdacdb2248ae3d64b3670fabe21b4583fc011d4 100644 (file)
 #include "mono/utils/checked-build.h"
 #include "mono/utils/mono-digest.h"
 
-void
-mono_sre_generic_param_table_entry_free (GenericParamTableEntry *entry)
-{
-       mono_gc_deregister_root ((char*) &entry->gparam);
-       g_free (entry);
-}
-
 static GENERATE_GET_CLASS_WITH_CACHE (marshal_as_attribute, System.Runtime.InteropServices, MarshalAsAttribute);
+static GENERATE_GET_CLASS_WITH_CACHE (module_builder, System.Reflection.Emit, ModuleBuilder);
 
 #ifndef DISABLE_REFLECTION_EMIT
 static guint32 mono_image_get_methodref_token (MonoDynamicImage *assembly, MonoMethod *method, gboolean create_typespec);
-static guint32 mono_image_get_methodbuilder_token (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *mb, gboolean create_open_instance, MonoError *error);
-static guint32 mono_image_get_ctorbuilder_token (MonoDynamicImage *assembly, MonoReflectionCtorBuilder *cb, MonoError *error);
 static guint32 mono_image_get_sighelper_token (MonoDynamicImage *assembly, MonoReflectionSigHelper *helper, MonoError *error);
 static gboolean ensure_runtime_vtable (MonoClass *klass, MonoError  *error);
-static guint32 mono_image_get_methodref_token_for_methodbuilder (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *method, MonoError *error);
 static void reflection_methodbuilder_from_dynamic_method (ReflectionMethodBuilder *rmb, MonoReflectionDynamicMethod *mb);
+static gboolean reflection_setup_internal_class (MonoReflectionTypeBuilder *tb, MonoError *error);
 
 static gpointer register_assembly (MonoDomain *domain, MonoReflectionAssembly *res, MonoAssembly *assembly);
 #endif
@@ -61,17 +53,17 @@ static MonoReflectionType *mono_reflection_type_get_underlying_system_type (Mono
 static gboolean is_sre_array (MonoClass *klass);
 static gboolean is_sre_byref (MonoClass *klass);
 static gboolean is_sre_pointer (MonoClass *klass);
+static gboolean is_sre_generic_instance (MonoClass *klass);
 static gboolean is_sre_type_builder (MonoClass *klass);
 static gboolean is_sre_method_builder (MonoClass *klass);
 static gboolean is_sre_field_builder (MonoClass *klass);
+static gboolean is_sre_gparam_builder (MonoClass *klass);
+static gboolean is_sre_enum_builder (MonoClass *klass);
 static gboolean is_sr_mono_method (MonoClass *klass);
-static gboolean is_sr_mono_generic_method (MonoClass *klass);
-static gboolean is_sr_mono_generic_cmethod (MonoClass *klass);
 static gboolean is_sr_mono_field (MonoClass *klass);
 
 static guint32 mono_image_get_methodspec_token (MonoDynamicImage *assembly, MonoMethod *method);
 static guint32 mono_image_get_inflated_method_token (MonoDynamicImage *assembly, MonoMethod *m);
-static MonoMethod * inflate_method (MonoReflectionType *type, MonoObject *obj, MonoError *error);
 
 #define mono_type_array_get_and_resolve(array, index, error) mono_reflection_type_get_handle ((MonoReflectionType*)mono_array_get (array, gpointer, index), error)
 
@@ -363,7 +355,6 @@ mono_save_custom_attrs (MonoImage *image, void *obj, MonoArray *cattrs)
 }
 #endif
 
-
 guint32
 mono_reflection_resolution_scope_from_image (MonoDynamicImage *assembly, MonoImage *image)
 {
@@ -684,52 +675,6 @@ mono_image_get_methodref_token (MonoDynamicImage *assembly, MonoMethod *method,
        return token;
 }
 
-static guint32
-mono_image_get_methodref_token_for_methodbuilder (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *method, MonoError *error)
-{
-       guint32 token, parent, sig;
-       ReflectionMethodBuilder rmb;
-       MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)method->type;
-       
-       mono_error_init (error);
-       token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, method));
-       if (token)
-               return token;
-
-       if (!mono_reflection_methodbuilder_from_method_builder (&rmb, method, error))
-               return 0;
-
-       /*
-        * A methodref signature can't contain an unmanaged calling convention.
-        * Since some flags are encoded as part of call_conv, we need to check against it.
-       */
-       if ((rmb.call_conv & ~0x60) != MONO_CALL_DEFAULT && (rmb.call_conv & ~0x60) != MONO_CALL_VARARG)
-               rmb.call_conv = (rmb.call_conv & 0x60) | MONO_CALL_DEFAULT;
-
-       sig = mono_dynimage_encode_method_builder_signature (assembly, &rmb, error);
-       return_val_if_nok (error, 0);
-
-       if (tb->generic_params) {
-               parent = mono_dynimage_encode_generic_typespec (assembly, tb, error);
-               return_val_if_nok (error, 0);
-       } else {
-               MonoType *t = mono_reflection_type_get_handle ((MonoReflectionType*)rmb.type, error);
-               return_val_if_nok (error, 0);
-
-               parent = mono_image_typedef_or_ref (assembly, t);
-       }
-
-       char *name = mono_string_to_utf8_checked (method->name, error);
-       return_val_if_nok (error, 0);
-
-       token = mono_image_add_memberef_row (assembly, parent, name, sig);
-       g_free (name);
-
-       g_hash_table_insert (assembly->handleref, method, GUINT_TO_POINTER(token));
-
-       return token;
-}
-
 static guint32
 mono_image_get_varargs_method_token (MonoDynamicImage *assembly, guint32 original,
                                     const gchar *name, guint32 sig)
@@ -754,107 +699,6 @@ mono_image_get_varargs_method_token (MonoDynamicImage *assembly, guint32 origina
        return token;
 }
 
-static guint32
-mono_image_get_methodspec_token_for_generic_method_definition (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *mb, MonoError *error)
-{
-       MonoDynamicTable *table;
-       guint32 *values;
-       guint32 token, mtoken = 0;
-
-       mono_error_init (error);
-       token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->methodspec, mb));
-       if (token)
-               return token;
-
-       table = &assembly->tables [MONO_TABLE_METHODSPEC];
-
-       mtoken = mono_image_get_methodref_token_for_methodbuilder (assembly, mb, error);
-       if (!mono_error_ok (error))
-               return 0;
-
-       switch (mono_metadata_token_table (mtoken)) {
-       case MONO_TABLE_MEMBERREF:
-               mtoken = (mono_metadata_token_index (mtoken) << MONO_METHODDEFORREF_BITS) | MONO_METHODDEFORREF_METHODREF;
-               break;
-       case MONO_TABLE_METHOD:
-               mtoken = (mono_metadata_token_index (mtoken) << MONO_METHODDEFORREF_BITS) | MONO_METHODDEFORREF_METHODDEF;
-               break;
-       default:
-               g_assert_not_reached ();
-       }
-
-       if (assembly->save) {
-               alloc_table (table, table->rows + 1);
-               values = table->values + table->next_idx * MONO_METHODSPEC_SIZE;
-               values [MONO_METHODSPEC_METHOD] = mtoken;
-               values [MONO_METHODSPEC_SIGNATURE] = mono_dynimage_encode_generic_method_definition_sig (assembly, mb);
-       }
-
-       token = MONO_TOKEN_METHOD_SPEC | table->next_idx;
-       table->next_idx ++;
-
-       mono_g_hash_table_insert (assembly->methodspec, mb, GUINT_TO_POINTER(token));
-       return token;
-}
-
-static guint32
-mono_image_get_methodbuilder_token (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *mb, gboolean create_methodspec, MonoError *error)
-{
-       guint32 token;
-
-       mono_error_init (error);
-
-       if (mb->generic_params && create_methodspec) 
-               return mono_image_get_methodspec_token_for_generic_method_definition (assembly, mb, error);
-
-       token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->handleref_managed, mb));
-       if (token)
-               return token;
-
-       token = mono_image_get_methodref_token_for_methodbuilder (assembly, mb, error);
-       if (!mono_error_ok (error))
-               return 0;
-       mono_g_hash_table_insert (assembly->handleref_managed, mb, GUINT_TO_POINTER(token));
-       return token;
-}
-
-static guint32
-mono_image_get_ctorbuilder_token (MonoDynamicImage *assembly, MonoReflectionCtorBuilder *mb, MonoError *error)
-{
-       guint32 token, parent, sig;
-       ReflectionMethodBuilder rmb;
-       char *name;
-       MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)mb->type;
-       
-       mono_error_init (error);
-       
-       token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->handleref_managed, mb));
-       if (token)
-               return token;
-
-       if (!mono_reflection_methodbuilder_from_ctor_builder (&rmb, mb, error))
-               return 0;
-
-       if (tb->generic_params) {
-               parent = mono_dynimage_encode_generic_typespec (assembly, tb, error);
-               return_val_if_nok (error, 0);
-       } else {
-               MonoType * type = mono_reflection_type_get_handle ((MonoReflectionType*)tb, error);
-               return_val_if_nok (error, 0);
-               parent = mono_image_typedef_or_ref (assembly, type);
-       }
-       
-       name = mono_string_to_utf8_checked (rmb.name, error);
-       return_val_if_nok (error, 0);
-       sig = mono_dynimage_encode_method_builder_signature (assembly, &rmb, error);
-       return_val_if_nok (error, 0);
-
-       token = mono_image_add_memberef_row (assembly, parent, name, sig);
-
-       g_free (name);
-       mono_g_hash_table_insert (assembly->handleref_managed, mb, GUINT_TO_POINTER(token));
-       return token;
-}
 #endif
 
 static gboolean
@@ -890,221 +734,6 @@ mono_image_get_fieldref_token (MonoDynamicImage *assembly, MonoObject *f, MonoCl
        return token;
 }
 
-static guint32
-mono_image_get_field_on_inst_token (MonoDynamicImage *assembly, MonoReflectionFieldOnTypeBuilderInst *f, MonoError *error)
-{
-       guint32 token;
-       MonoClass *klass;
-       MonoGenericClass *gclass;
-       MonoType *type;
-       char *name;
-
-       token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->handleref_managed, f));
-       if (token)
-               return token;
-       if (is_sre_field_builder (mono_object_class (f->fb))) {
-               MonoReflectionFieldBuilder *fb = (MonoReflectionFieldBuilder *)f->fb;
-               type = mono_reflection_type_get_handle ((MonoReflectionType*)f->inst, error);
-               return_val_if_nok (error, 0);
-               klass = mono_class_from_mono_type (type);
-               gclass = type->data.generic_class;
-               g_assert (gclass->is_dynamic);
-
-               guint32 sig_token = mono_dynimage_encode_field_signature (assembly, fb, error);
-               return_val_if_nok (error, 0);
-               name = mono_string_to_utf8_checked (fb->name, error);
-               return_val_if_nok (error, 0);
-               token = mono_image_get_memberref_token (assembly, &klass->byval_arg, name, sig_token);
-               g_free (name);          
-       } else if (is_sr_mono_field (mono_object_class (f->fb))) {
-               guint32 sig;
-               MonoClassField *field = ((MonoReflectionField *)f->fb)->field;
-
-               type = mono_reflection_type_get_handle ((MonoReflectionType*)f->inst, error);
-               return_val_if_nok (error, 0);
-               klass = mono_class_from_mono_type (type);
-
-               sig = mono_dynimage_encode_fieldref_signature (assembly, field->parent->image, field->type);
-               token = mono_image_get_memberref_token (assembly, &klass->byval_arg, field->name, sig);
-       } else {
-               char *name = mono_type_get_full_name (mono_object_class (f->fb));
-               g_error ("mono_image_get_field_on_inst_token: don't know how to handle %s", name);
-       }
-
-       mono_g_hash_table_insert (assembly->handleref_managed, f, GUINT_TO_POINTER (token));
-       return token;
-}
-
-static guint32
-mono_image_get_ctor_on_inst_token (MonoDynamicImage *assembly, MonoReflectionCtorOnTypeBuilderInst *c, gboolean create_methodspec, MonoError *error)
-{
-       guint32 sig, token;
-       MonoClass *klass;
-       MonoGenericClass *gclass;
-       MonoType *type;
-
-       mono_error_init (error);
-
-       /* A ctor cannot be a generic method, so we can ignore create_methodspec */
-
-       token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->handleref_managed, c));
-       if (token)
-               return token;
-
-       if (mono_is_sre_ctor_builder (mono_object_class (c->cb))) {
-               MonoReflectionCtorBuilder *cb = (MonoReflectionCtorBuilder *)c->cb;
-               ReflectionMethodBuilder rmb;
-               char *name;
-
-               type = mono_reflection_type_get_handle ((MonoReflectionType*)c->inst, error);
-               return_val_if_nok (error, 0);
-               klass = mono_class_from_mono_type (type);
-
-               gclass = type->data.generic_class;
-               g_assert (gclass->is_dynamic);
-
-               if (!mono_reflection_methodbuilder_from_ctor_builder (&rmb, cb, error))
-                       return 0;
-
-               sig = mono_dynimage_encode_method_builder_signature (assembly, &rmb, error);
-               return_val_if_nok (error, 0);
-
-               name = mono_string_to_utf8_checked (rmb.name, error);
-               return_val_if_nok (error, 0);
-
-               token = mono_image_get_memberref_token (assembly, &klass->byval_arg, name, sig);
-               g_free (name);
-       } else if (mono_is_sr_mono_cmethod (mono_object_class (c->cb))) {
-               MonoMethod *mm = ((MonoReflectionMethod *)c->cb)->method;
-
-               type = mono_reflection_type_get_handle ((MonoReflectionType*)c->inst, error);
-               return_val_if_nok (error, 0);
-               klass = mono_class_from_mono_type (type);
-
-               sig = mono_dynimage_encode_method_signature (assembly, mono_method_signature (mm));
-               token = mono_image_get_memberref_token (assembly, &klass->byval_arg, mm->name, sig);
-       } else {
-               char *name = mono_type_get_full_name (mono_object_class (c->cb));
-               g_error ("mono_image_get_method_on_inst_token: don't know how to handle %s", name);
-       }
-
-
-       mono_g_hash_table_insert (assembly->handleref_managed, c, GUINT_TO_POINTER (token));
-       return token;
-}
-
-MonoMethod*
-mono_reflection_method_on_tb_inst_get_handle (MonoReflectionMethodOnTypeBuilderInst *m, MonoError *error)
-{
-       MonoClass *klass;
-       MonoGenericContext tmp_context;
-       MonoType **type_argv;
-       MonoGenericInst *ginst;
-       MonoMethod *method, *inflated;
-       int count, i;
-
-       mono_error_init (error);
-
-       mono_reflection_init_type_builder_generics ((MonoObject*)m->inst, error);
-       return_val_if_nok (error, NULL);
-
-       method = inflate_method (m->inst, (MonoObject*)m->mb, error);
-       return_val_if_nok (error, NULL);
-
-       klass = method->klass;
-
-       if (m->method_args == NULL)
-               return method;
-
-       if (method->is_inflated)
-               method = ((MonoMethodInflated *) method)->declaring;
-
-       count = mono_array_length (m->method_args);
-
-       type_argv = g_new0 (MonoType *, count);
-       for (i = 0; i < count; i++) {
-               MonoReflectionType *garg = (MonoReflectionType *)mono_array_get (m->method_args, gpointer, i);
-               type_argv [i] = mono_reflection_type_get_handle (garg, error);
-               return_val_if_nok (error, NULL);
-       }
-       ginst = mono_metadata_get_generic_inst (count, type_argv);
-       g_free (type_argv);
-
-       tmp_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
-       tmp_context.method_inst = ginst;
-
-       inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, error);
-       mono_error_assert_ok (error);
-       return inflated;
-}
-
-static guint32
-mono_image_get_method_on_inst_token (MonoDynamicImage *assembly, MonoReflectionMethodOnTypeBuilderInst *m, gboolean create_methodspec, MonoError *error)
-{
-       guint32 sig, token = 0;
-       MonoType *type;
-       MonoClass *klass;
-
-       mono_error_init (error);
-
-       if (m->method_args) {
-               MonoMethod *inflated;
-
-               inflated = mono_reflection_method_on_tb_inst_get_handle (m, error);
-               return_val_if_nok (error, 0);
-
-               if (create_methodspec)
-                       token = mono_image_get_methodspec_token (assembly, inflated);
-               else
-                       token = mono_image_get_inflated_method_token (assembly, inflated);
-               return token;
-       }
-
-       token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->handleref_managed, m));
-       if (token)
-               return token;
-
-       if (is_sre_method_builder (mono_object_class (m->mb))) {
-               MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder *)m->mb;
-               MonoGenericClass *gclass;
-               ReflectionMethodBuilder rmb;
-               char *name;
-
-               type = mono_reflection_type_get_handle ((MonoReflectionType*)m->inst, error);
-               return_val_if_nok (error, 0);
-               klass = mono_class_from_mono_type (type);
-               gclass = type->data.generic_class;
-               g_assert (gclass->is_dynamic);
-
-               if (!mono_reflection_methodbuilder_from_method_builder (&rmb, mb, error))
-                       return 0;
-
-               sig = mono_dynimage_encode_method_builder_signature (assembly, &rmb, error);
-               return_val_if_nok (error, 0);
-
-               name = mono_string_to_utf8_checked (rmb.name, error);
-               return_val_if_nok (error, 0);
-
-               token = mono_image_get_memberref_token (assembly, &klass->byval_arg, name, sig);
-               g_free (name);          
-       } else if (is_sr_mono_method (mono_object_class (m->mb))) {
-               MonoMethod *mm = ((MonoReflectionMethod *)m->mb)->method;
-
-               type = mono_reflection_type_get_handle ((MonoReflectionType*)m->inst, error);
-               return_val_if_nok (error, 0);
-               klass = mono_class_from_mono_type (type);
-
-               sig = mono_dynimage_encode_method_signature (assembly, mono_method_signature (mm));
-               token = mono_image_get_memberref_token (assembly, &klass->byval_arg, mm->name, sig);
-       } else {
-               char *name = mono_type_get_full_name (mono_object_class (m->mb));
-               g_error ("mono_image_get_method_on_inst_token: don't know how to handle %s", name);
-       }
-
-       mono_g_hash_table_insert (assembly->handleref_managed, m, GUINT_TO_POINTER (token));
-       return token;
-}
-
 static guint32
 method_encode_methodspec (MonoDynamicImage *assembly, MonoMethod *method)
 {
@@ -1191,138 +820,6 @@ mono_image_get_inflated_method_token (MonoDynamicImage *assembly, MonoMethod *m)
        return token;
 }
 
-/*
- * Return a copy of TYPE, adding the custom modifiers in MODREQ and MODOPT.
- */
-static MonoType*
-add_custom_modifiers (MonoDynamicImage *assembly, MonoType *type, MonoArray *modreq, MonoArray *modopt, MonoError *error)
-{
-       int i, count, len, pos;
-       MonoType *t;
-
-       mono_error_init (error);
-
-       count = 0;
-       if (modreq)
-               count += mono_array_length (modreq);
-       if (modopt)
-               count += mono_array_length (modopt);
-
-       if (count == 0)
-               return mono_metadata_type_dup (NULL, type);
-
-       len = MONO_SIZEOF_TYPE + ((gint32)count) * sizeof (MonoCustomMod);
-       t = (MonoType *)g_malloc (len);
-       memcpy (t, type, MONO_SIZEOF_TYPE);
-
-       t->num_mods = count;
-       pos = 0;
-       if (modreq) {
-               for (i = 0; i < mono_array_length (modreq); ++i) {
-                       MonoType *mod = mono_type_array_get_and_resolve (modreq, i, error);
-                       if (!is_ok (error))
-                               goto fail;
-                       t->modifiers [pos].required = 1;
-                       t->modifiers [pos].token = mono_image_typedef_or_ref (assembly, mod);
-                       pos ++;
-               }
-       }
-       if (modopt) {
-               for (i = 0; i < mono_array_length (modopt); ++i) {
-                       MonoType *mod = mono_type_array_get_and_resolve (modopt, i, error);
-                       if (!is_ok (error))
-                               goto fail;
-                       t->modifiers [pos].required = 0;
-                       t->modifiers [pos].token = mono_image_typedef_or_ref (assembly, mod);
-                       pos ++;
-               }
-       }
-
-       return t;
-fail:
-       g_free (t);
-       return NULL;
-}
-
-void
-mono_reflection_init_type_builder_generics (MonoObject *type, MonoError *error)
-{
-       MonoReflectionTypeBuilder *tb;
-
-       mono_error_init (error);
-
-       if (!is_sre_type_builder(mono_object_class (type)))
-               return;
-       tb = (MonoReflectionTypeBuilder *)type;
-
-       if (tb && tb->generic_container)
-               mono_reflection_create_generic_class (tb, error);
-}
-
-static guint32
-mono_image_get_generic_field_token (MonoDynamicImage *assembly, MonoReflectionFieldBuilder *fb, MonoError *error)
-{
-       MonoDynamicTable *table;
-       MonoType *custom = NULL, *type;
-       guint32 *values;
-       guint32 token, pclass, parent, sig;
-       gchar *name;
-
-       mono_error_init (error);
-
-       token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->handleref_managed, fb));
-       if (token)
-               return token;
-
-       MonoType *typeb = mono_reflection_type_get_handle (fb->typeb, error);
-       return_val_if_nok (error, 0);
-       /* FIXME: is this call necessary? */
-       mono_class_from_mono_type (typeb);
-
-       /*FIXME this is one more layer of ugliness due how types are created.*/
-       mono_reflection_init_type_builder_generics (fb->type, error);
-       return_val_if_nok (error, 0);
-
-       /* fb->type does not include the custom modifiers */
-       /* FIXME: We should do this in one place when a fieldbuilder is created */
-       type = mono_reflection_type_get_handle ((MonoReflectionType*)fb->type, error);
-       return_val_if_nok (error, 0);
-
-       if (fb->modreq || fb->modopt) {
-               type = custom = add_custom_modifiers (assembly, type, fb->modreq, fb->modopt, error);
-               return_val_if_nok (error, 0);
-       }
-
-       sig = mono_dynimage_encode_fieldref_signature (assembly, NULL, type);
-       g_free (custom);
-
-       parent = mono_dynimage_encode_generic_typespec (assembly, (MonoReflectionTypeBuilder *) fb->typeb, error);
-       return_val_if_nok (error, 0);
-       g_assert ((parent & MONO_TYPEDEFORREF_MASK) == MONO_TYPEDEFORREF_TYPESPEC);
-       
-       pclass = MONO_MEMBERREF_PARENT_TYPESPEC;
-       parent >>= MONO_TYPEDEFORREF_BITS;
-
-       table = &assembly->tables [MONO_TABLE_MEMBERREF];
-
-       name = mono_string_to_utf8_checked (fb->name, error);
-       return_val_if_nok (error, 0);
-
-       if (assembly->save) {
-               alloc_table (table, table->rows + 1);
-               values = table->values + table->next_idx * MONO_MEMBERREF_SIZE;
-               values [MONO_MEMBERREF_CLASS] = pclass | (parent << MONO_MEMBERREF_PARENT_BITS);
-               values [MONO_MEMBERREF_NAME] = string_heap_insert (&assembly->sheap, name);
-               values [MONO_MEMBERREF_SIGNATURE] = sig;
-       }
-
-       token = MONO_TOKEN_MEMBER_REF | table->next_idx;
-       table->next_idx ++;
-       mono_g_hash_table_insert (assembly->handleref_managed, fb, GUINT_TO_POINTER(token));
-       g_free (name);
-       return token;
-}
-
 static guint32 
 mono_image_get_sighelper_token (MonoDynamicImage *assembly, MonoReflectionSigHelper *helper, MonoError *error)
 {
@@ -1573,6 +1070,10 @@ mono_image_create_method_token (MonoDynamicImage *assembly, MonoObject *obj, Mon
                        if (!is_ok (error)) goto fail;
                }
 
+               // FIXME: This doesn't work, we don't use 'sig' for anything
+               // The token fixup doesn't work either
+               g_assert_not_reached ();
+
                sig_token = mono_dynimage_encode_method_builder_signature (assembly, &rmb, error);
                if (!is_ok (error))
                        goto fail;
@@ -1632,81 +1133,14 @@ mono_image_create_token (MonoDynamicImage *assembly, MonoObject *obj,
                return 0;
        }
 
-       if (strcmp (klass->name, "MethodBuilder") == 0) {
-               MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder *)obj;
-               MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)mb->type;
-
-               if (tb->module->dynamic_image == assembly && !tb->generic_params && !mb->generic_params)
-                       token = mb->table_idx | MONO_TOKEN_METHOD_DEF;
-               else {
-                       token = mono_image_get_methodbuilder_token (assembly, mb, create_open_instance, error);
-                       if (!mono_error_ok (error))
-                               return 0;
-               }
-               /*g_print ("got token 0x%08x for %s\n", token, mono_string_to_utf8 (mb->name));*/
-       } else if (strcmp (klass->name, "ConstructorBuilder") == 0) {
-               MonoReflectionCtorBuilder *mb = (MonoReflectionCtorBuilder *)obj;
-               MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)mb->type;
-
-               if (tb->module->dynamic_image == assembly && !tb->generic_params)
-                       token = mb->table_idx | MONO_TOKEN_METHOD_DEF;
-               else {
-                       token = mono_image_get_ctorbuilder_token (assembly, mb, error);
-                       if (!mono_error_ok (error))
-                               return 0;
-               }
-               /*g_print ("got token 0x%08x for %s\n", token, mono_string_to_utf8 (mb->name));*/
-       } else if (strcmp (klass->name, "FieldBuilder") == 0) {
-               MonoReflectionFieldBuilder *fb = (MonoReflectionFieldBuilder *)obj;
-               MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)fb->typeb;
-               if (tb->generic_params) {
-                       token = mono_image_get_generic_field_token (assembly, fb, error);
-                       return_val_if_nok (error, 0);
-               } else {
-                       if (tb->module->dynamic_image == assembly) {
-                               token = fb->table_idx | MONO_TOKEN_FIELD_DEF;
-                       } else {
-                               token = mono_image_get_fieldref_token (assembly, (MonoObject*)fb, fb->handle);
-                       }
-               }
-       } else if (strcmp (klass->name, "TypeBuilder") == 0) {
-               MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)obj;
-               if (create_open_instance && tb->generic_params) {
-                       MonoType *type;
-                       mono_reflection_init_type_builder_generics (obj, error);
-                       return_val_if_nok (error, 0);
-                       type = mono_reflection_type_get_handle ((MonoReflectionType *)obj, error);
-                       return_val_if_nok (error, 0);
-                       token = mono_dynimage_encode_typedef_or_ref_full (assembly, type, TRUE);
-                       token = mono_metadata_token_from_dor (token);
-               } else if (tb->module->dynamic_image == assembly) {
-                       token = tb->table_idx | MONO_TOKEN_TYPE_DEF;
-               } else {
-                       MonoType *type;
-                       type = mono_reflection_type_get_handle ((MonoReflectionType *)obj, error);
-                       return_val_if_nok (error, 0);
-                       token = mono_metadata_token_from_dor (mono_image_typedef_or_ref (assembly, type));
-               }
-       } else if (strcmp (klass->name, "RuntimeType") == 0) {
+       if (strcmp (klass->name, "RuntimeType") == 0) {
                MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj, error);
                return_val_if_nok (error, 0);
                MonoClass *mc = mono_class_from_mono_type (type);
                token = mono_metadata_token_from_dor (
                        mono_dynimage_encode_typedef_or_ref_full (assembly, type, mc->generic_container == NULL || create_open_instance));
-       } else if (strcmp (klass->name, "GenericTypeParameterBuilder") == 0) {
-               MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj, error);
-               return_val_if_nok (error, 0);
-               token = mono_metadata_token_from_dor (
-                       mono_image_typedef_or_ref (assembly, type));
-       } else if (strcmp (klass->name, "MonoGenericClass") == 0) {
-               MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj, error);
-               return_val_if_nok (error, 0);
-               token = mono_metadata_token_from_dor (
-                       mono_image_typedef_or_ref (assembly, type));
        } else if (strcmp (klass->name, "MonoCMethod") == 0 ||
-                  strcmp (klass->name, "MonoMethod") == 0 ||
-                  strcmp (klass->name, "MonoGenericMethod") == 0 ||
-                  strcmp (klass->name, "MonoGenericCMethod") == 0) {
+                          strcmp (klass->name, "MonoMethod") == 0) {
                MonoReflectionMethod *m = (MonoReflectionMethod *)obj;
                if (m->method->is_inflated) {
                        if (create_open_instance)
@@ -1758,25 +1192,6 @@ mono_image_create_token (MonoDynamicImage *assembly, MonoObject *obj,
                return_val_if_nok (error, 0);
                token = mono_metadata_token_from_dor (
                        mono_image_typedef_or_ref (assembly, type));
-       } else if (strcmp (klass->name, "FieldOnTypeBuilderInst") == 0) {
-               MonoReflectionFieldOnTypeBuilderInst *f = (MonoReflectionFieldOnTypeBuilderInst*)obj;
-               token = mono_image_get_field_on_inst_token (assembly, f, error);
-               return_val_if_nok (error, 0);
-       } else if (strcmp (klass->name, "ConstructorOnTypeBuilderInst") == 0) {
-               MonoReflectionCtorOnTypeBuilderInst *c = (MonoReflectionCtorOnTypeBuilderInst*)obj;
-               token = mono_image_get_ctor_on_inst_token (assembly, c, create_open_instance, error);
-               if (!mono_error_ok (error))
-                       return 0;
-       } else if (strcmp (klass->name, "MethodOnTypeBuilderInst") == 0) {
-               MonoReflectionMethodOnTypeBuilderInst *m = (MonoReflectionMethodOnTypeBuilderInst*)obj;
-               token = mono_image_get_method_on_inst_token (assembly, m, create_open_instance, error);
-               if (!mono_error_ok (error))
-                       return 0;
-       } else if (is_sre_array (klass) || is_sre_byref (klass) || is_sre_pointer (klass)) {
-               MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj, error);
-               return_val_if_nok (error, 0);
-               token = mono_metadata_token_from_dor (
-                               mono_image_typedef_or_ref (assembly, type));
        } else {
                g_error ("requested token for %s\n", klass->name);
        }
@@ -1996,7 +1411,7 @@ is_sre_pointer (MonoClass *klass)
 static gboolean
 is_sre_generic_instance (MonoClass *klass)
 {
-       check_corlib_type_cached (klass, "System.Reflection", "MonoGenericClass");
+       check_corlib_type_cached (klass, "System.Reflection.Emit", "TypeBuilderInstantiation");
 }
 
 static gboolean
@@ -2023,6 +1438,18 @@ is_sre_field_builder (MonoClass *klass)
        check_corlib_type_cached (klass, "System.Reflection.Emit", "FieldBuilder");
 }
 
+static gboolean
+is_sre_gparam_builder (MonoClass *klass)
+{
+       check_corlib_type_cached (klass, "System.Reflection.Emit", "GenericTypeParameterBuilder");
+}
+
+static gboolean
+is_sre_enum_builder (MonoClass *klass)
+{
+       check_corlib_type_cached (klass, "System.Reflection.Emit", "EnumBuilder");
+}
+
 gboolean
 mono_is_sre_method_on_tb_inst (MonoClass *klass)
 {
@@ -2126,60 +1553,64 @@ mono_reflection_type_get_handle (MonoReflectionType* ref, MonoError *error)
                g_assert (res);
                gclass->type.type = res;
                return res;
-       }
+       } else if (is_sre_gparam_builder (klass)) {
+               MonoReflectionGenericParam *gparam = (MonoReflectionGenericParam *)ref;
+               MonoGenericParamFull *param;
+               MonoImage *image;
+               MonoClass *pklass;
 
-       g_error ("Cannot handle corlib user type %s", mono_type_full_name (&mono_object_class(ref)->byval_arg));
-       return NULL;
-}
+               image = &gparam->tbuilder->module->dynamic_image->image;
 
-void
-ves_icall_SymbolType_create_unmanaged_type (MonoReflectionType *type)
-{
-       MonoError error;
-       mono_reflection_type_get_handle (type, &error);
-       mono_error_set_pending_exception (&error);
-}
+               param = mono_image_new0 (image, MonoGenericParamFull, 1);
 
-static gboolean
-reflection_register_with_runtime (MonoReflectionType *type, MonoError *error)
-{
-       MonoDomain *domain = mono_object_domain ((MonoObject*)type);
-       MonoClass *klass;
+               param->info.name = mono_string_to_utf8_image (image, gparam->name, error);
+               mono_error_assert_ok (error);
+               param->param.num = gparam->index;
 
-       mono_error_init (error);
+               if (gparam->mbuilder) {
+                       if (!gparam->mbuilder->generic_container) {
+                               gparam->mbuilder->generic_container = (MonoGenericContainer *)mono_image_alloc0 (image, sizeof (MonoGenericContainer));
+                               gparam->mbuilder->generic_container->is_method = TRUE;
+                               /*
+                                * Cannot set owner.method, since the MonoMethod is not created yet.
+                                * Set the image field instead, so type_in_image () works.
+                                */
+                               gparam->mbuilder->generic_container->is_anonymous = TRUE;
+                               gparam->mbuilder->generic_container->owner.image = image;
+                       }
+                       param->param.owner = gparam->mbuilder->generic_container;
+               } else if (gparam->tbuilder) {
+                       MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)(gparam->tbuilder), error);
+                       mono_error_assert_ok (error);
+                       MonoClass *owner = mono_class_from_mono_type (type);
+                       g_assert (owner->generic_container);
+                       param->param.owner = owner->generic_container;
+               }
 
-       MonoType *res = mono_reflection_type_get_handle (type, error);
+               pklass = mono_class_from_generic_parameter_internal ((MonoGenericParam *) param);
 
-       if (!res && is_ok (error)) {
-               mono_error_set_argument (error, NULL, "Invalid generic instantiation, one or more arguments are not proper user types");
-       }
-       return_val_if_nok (error, FALSE);
+               gparam->type.type = &pklass->byval_arg;
 
-       klass = mono_class_from_mono_type (res);
+               mono_class_set_ref_info (pklass, gparam);
+               mono_image_append_class_to_reflection_info_set (pklass);
 
-       mono_loader_lock (); /*same locking as mono_type_get_object_checked */
-       mono_domain_lock (domain);
+               return &pklass->byval_arg;
+       } else if (is_sre_enum_builder (klass)) {
+               MonoReflectionEnumBuilder *ebuilder = (MonoReflectionEnumBuilder *)ref;
 
-       if (!image_is_dynamic (klass->image)) {
-               mono_class_setup_supertypes (klass);
-       } else {
-               if (!domain->type_hash)
-                       domain->type_hash = mono_g_hash_table_new_type ((GHashFunc)mono_metadata_type_hash, 
-                                       (GCompareFunc)mono_metadata_type_equal, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DOMAIN, "domain reflection types table");
-               mono_g_hash_table_insert (domain->type_hash, res, type);
-       }
-       mono_domain_unlock (domain);
-       mono_loader_unlock ();
+               return mono_reflection_type_get_handle ((MonoReflectionType*)ebuilder->tb, error);
+       } else if (is_sre_type_builder (klass)) {
+               MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)ref;
 
-       return TRUE;
-}
+               /* This happens when a finished type references an unfinished one. Have to create the minimal type */
+               reflection_setup_internal_class (tb, error);
+               mono_error_assert_ok (error);
+               g_assert (ref->type);
+               return ref->type;
+       }
 
-void
-mono_reflection_register_with_runtime (MonoReflectionType *type)
-{
-       MonoError error;
-       (void) reflection_register_with_runtime (type, &error);
-       mono_error_set_pending_exception (&error);
+       g_error ("Cannot handle corlib user type %s", mono_type_full_name (&mono_object_class(ref)->byval_arg));
+       return NULL;
 }
 
 /**
@@ -2309,12 +1740,6 @@ get_field_name_and_type (MonoObject *field, char **name, MonoType **type, MonoEr
 
 #else /* DISABLE_REFLECTION_EMIT */
 
-void
-mono_reflection_register_with_runtime (MonoReflectionType *type)
-{
-       /* This is empty */
-}
-
 static gboolean
 is_sre_type_builder (MonoClass *klass)
 {
@@ -2345,12 +1770,6 @@ mono_is_sre_ctor_on_tb_inst (MonoClass *klass)
        return FALSE;
 }
 
-void
-mono_reflection_init_type_builder_generics (MonoObject *type, MonoError *error)
-{
-       mono_error_init (error);
-}
-
 #endif /* !DISABLE_REFLECTION_EMIT */
 
 
@@ -2378,22 +1797,10 @@ mono_is_sr_mono_cmethod (MonoClass *klass)
        check_corlib_type_cached (klass, "System.Reflection", "MonoCMethod");
 }
 
-static gboolean
-is_sr_mono_generic_method (MonoClass *klass)
-{
-       check_corlib_type_cached (klass, "System.Reflection", "MonoGenericMethod");
-}
-
-static gboolean
-is_sr_mono_generic_cmethod (MonoClass *klass)
-{
-       check_corlib_type_cached (klass, "System.Reflection", "MonoGenericCMethod");
-}
-
 gboolean
 mono_class_is_reflection_method_or_constructor (MonoClass *klass)
 {
-       return is_sr_mono_method (klass) || mono_is_sr_mono_cmethod (klass) || is_sr_mono_generic_method (klass) || is_sr_mono_generic_cmethod (klass);
+       return is_sr_mono_method (klass) || mono_is_sr_mono_cmethod (klass);
 }
 
 gboolean
@@ -2959,6 +2366,7 @@ reflection_setup_internal_class (MonoReflectionTypeBuilder *tb, MonoError *error
        tb->type.type = &klass->byval_arg;
 
        if (tb->nesting_type) {
+               reflection_setup_internal_class ((MonoReflectionTypeBuilder*)tb->nesting_type, error);
                g_assert (tb->nesting_type->type);
                MonoType *nesting_type = mono_reflection_type_get_handle (tb->nesting_type, error);
                if (!is_ok (error)) goto failure;
@@ -2978,50 +2386,30 @@ failure:
 }
 
 /**
- * ves_icall_TypeBuilder_setup_internal_class:
- * @tb: a TypeBuilder object
- *
- * (icall)
- * Creates a MonoClass that represents the TypeBuilder.
- * This is a trick that lets us simplify a lot of reflection code
- * (and will allow us to support Build and Run assemblies easier).
- *
- */
-void
-ves_icall_TypeBuilder_setup_internal_class (MonoReflectionTypeBuilder *tb)
-{
-       MonoError error;
-       (void) reflection_setup_internal_class (tb, &error);
-       mono_error_set_pending_exception (&error);
-}
-
-/**
- * mono_reflection_create_generic_class:
+ * reflection_create_generic_class:
  * @tb: a TypeBuilder object
  * @error: set on error
  *
  * Creates the generic class after all generic parameters have been added.
  * On success returns TRUE, on failure returns FALSE and sets @error.
- * 
  */
-gboolean
-mono_reflection_create_generic_class (MonoReflectionTypeBuilder *tb, MonoError *error)
+static gboolean
+reflection_create_generic_class (MonoReflectionTypeBuilder *tb, MonoError *error)
 {
-
        MonoClass *klass;
        int count, i;
 
        mono_error_init (error);
 
+       reflection_setup_internal_class (tb, error);
+
        klass = mono_class_from_mono_type (tb->type.type);
 
        count = tb->generic_params ? mono_array_length (tb->generic_params) : 0;
 
-       if (klass->generic_container || (count == 0))
+       if (count == 0)
                return TRUE;
 
-       g_assert (tb->generic_container && (tb->generic_container->owner.klass == klass));
-
        klass->generic_container = (MonoGenericContainer *)mono_image_alloc0 (klass->image, sizeof (MonoGenericContainer));
 
        klass->generic_container->owner.klass = klass;
@@ -3292,14 +2680,14 @@ reflection_methodbuilder_to_mono_method (MonoClass *klass,
 
        if (rmb->generic_params) {
                int count = mono_array_length (rmb->generic_params);
-               MonoGenericContainer *container = rmb->generic_container;
-
-               g_assert (container);
+               MonoGenericContainer *container;
 
+               container = (MonoGenericContainer *)mono_image_alloc0 (klass->image, sizeof (MonoGenericContainer));
+               container->is_method = TRUE;
+               container->is_anonymous = FALSE;
                container->type_argc = count;
                container->type_params = image_g_new0 (image, MonoGenericParamFull, count);
                container->owner.method = m;
-               container->is_anonymous = FALSE; // Method is now known, container is no longer anonymous
 
                m->is_generic = TRUE;
                mono_method_set_generic_container (m, container);
@@ -3311,6 +2699,12 @@ reflection_methodbuilder_to_mono_method (MonoClass *klass,
                        mono_error_assert_ok (error);
                        MonoGenericParamFull *param = (MonoGenericParamFull *) gp_type->data.generic_param;
                        container->type_params [i] = *param;
+                       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;
                }
 
                /*
@@ -3442,20 +2836,20 @@ ctorbuilder_to_mono_method (MonoClass *klass, MonoReflectionCtorBuilder* mb, Mon
        MonoMethodSignature *sig;
 
        mono_loader_lock ();
+
+       if (!mono_reflection_methodbuilder_from_ctor_builder (&rmb, mb, error))
+               return NULL;
+
        g_assert (klass->image != NULL);
        sig = ctor_builder_to_signature (klass->image, mb, error);
        mono_loader_unlock ();
        return_val_if_nok (error, NULL);
 
-       if (!mono_reflection_methodbuilder_from_ctor_builder (&rmb, mb, error))
-               return NULL;
-
        mb->mhandle = reflection_methodbuilder_to_mono_method (klass, &rmb, sig, error);
        return_val_if_nok (error, NULL);
        mono_save_custom_attrs (klass->image, mb->mhandle, mb->cattrs);
 
-       /* If we are in a generic class, we might be called multiple times from inflate_method */
-       if (!((MonoDynamicImage*)(MonoDynamicImage*)klass->image)->save && !klass->generic_container) {
+       if (!((MonoDynamicImage*)(MonoDynamicImage*)klass->image)->save) {
                /* ilgen is no longer needed */
                mb->ilgen = NULL;
        }
@@ -3472,154 +2866,28 @@ methodbuilder_to_mono_method (MonoClass *klass, MonoReflectionMethodBuilder* mb,
        mono_error_init (error);
 
        mono_loader_lock ();
+
+       if (!mono_reflection_methodbuilder_from_method_builder (&rmb, mb, error))
+               return NULL;
+
        g_assert (klass->image != NULL);
        sig = method_builder_to_signature (klass->image, mb, error);
        mono_loader_unlock ();
        return_val_if_nok (error, NULL);
 
-       if (!mono_reflection_methodbuilder_from_method_builder (&rmb, mb, error))
-               return NULL;
-
        mb->mhandle = reflection_methodbuilder_to_mono_method (klass, &rmb, sig, error);
        return_val_if_nok (error, NULL);
        mono_save_custom_attrs (klass->image, mb->mhandle, mb->cattrs);
 
-       /* If we are in a generic class, we might be called multiple times from inflate_method */
-       if (!((MonoDynamicImage*)(MonoDynamicImage*)klass->image)->save && !klass->generic_container) {
+       if (!((MonoDynamicImage*)(MonoDynamicImage*)klass->image)->save)
                /* ilgen is no longer needed */
                mb->ilgen = NULL;
-       }
        return mb->mhandle;
 }
 #endif
 
 #ifndef DISABLE_REFLECTION_EMIT
 
-static MonoMethod *
-inflate_mono_method (MonoClass *klass, MonoMethod *method, MonoObject *obj)
-{
-       MonoMethodInflated *imethod;
-       MonoGenericContext *context;
-       int i;
-
-       /*
-        * With generic code sharing the klass might not be inflated.
-        * This can happen because classes inflated with their own
-        * type arguments are "normalized" to the uninflated class.
-        */
-       if (!klass->generic_class)
-               return method;
-
-       context = mono_class_get_context (klass);
-
-       if (klass->method.count && klass->methods) {
-               /* Find the already created inflated method */
-               for (i = 0; i < klass->method.count; ++i) {
-                       g_assert (klass->methods [i]->is_inflated);
-                       if (((MonoMethodInflated*)klass->methods [i])->declaring == method)
-                               break;
-               }
-               g_assert (i < klass->method.count);
-               imethod = (MonoMethodInflated*)klass->methods [i];
-       } else {
-               MonoError error;
-               imethod = (MonoMethodInflated *) mono_class_inflate_generic_method_full_checked (method, klass, context, &error);
-               mono_error_assert_ok (&error);
-       }
-
-       if (method->is_generic && image_is_dynamic (method->klass->image)) {
-               MonoDynamicImage *image = (MonoDynamicImage*)method->klass->image;
-
-               mono_image_lock ((MonoImage*)image);
-               mono_g_hash_table_insert (image->generic_def_objects, imethod, obj);
-               mono_image_unlock ((MonoImage*)image);
-       }
-       return (MonoMethod *) imethod;
-}
-
-static MonoMethod *
-inflate_method (MonoReflectionType *type, MonoObject *obj, MonoError *error)
-{
-       MonoMethod *method;
-       MonoClass *gklass;
-
-       mono_error_init (error);
-
-       MonoClass *type_class = mono_object_class (type);
-
-       if (is_sre_generic_instance (type_class)) {
-               MonoReflectionGenericClass *mgc = (MonoReflectionGenericClass*)type;
-               MonoType *generic_type = mono_reflection_type_get_handle ((MonoReflectionType*)mgc->generic_type, error);
-               return_val_if_nok (error, NULL);
-               gklass = mono_class_from_mono_type (generic_type);
-       } else if (is_sre_type_builder (type_class)) {
-               MonoType *t = mono_reflection_type_get_handle (type, error);
-               return_val_if_nok (error, NULL);
-               gklass = mono_class_from_mono_type (t);
-       } else if (type->type) {
-               gklass = mono_class_from_mono_type (type->type);
-               gklass = mono_class_get_generic_type_definition (gklass);
-       } else {
-               g_error ("Can't handle type %s", mono_type_get_full_name (mono_object_class (type)));
-       }
-
-       if (!strcmp (obj->vtable->klass->name, "MethodBuilder"))
-               if (((MonoReflectionMethodBuilder*)obj)->mhandle)
-                       method = ((MonoReflectionMethodBuilder*)obj)->mhandle;
-               else {
-                       method = methodbuilder_to_mono_method (gklass, (MonoReflectionMethodBuilder *) obj, error);
-                       if (!method)
-                               return NULL;
-               }
-       else if (!strcmp (obj->vtable->klass->name, "ConstructorBuilder")) {
-               method = ctorbuilder_to_mono_method (gklass, (MonoReflectionCtorBuilder *) obj, error);
-               if (!method)
-                       return NULL;
-       } else if (!strcmp (obj->vtable->klass->name, "MonoMethod") || !strcmp (obj->vtable->klass->name, "MonoCMethod"))
-               method = ((MonoReflectionMethod *) obj)->method;
-       else {
-               method = NULL; /* prevent compiler warning */
-               g_error ("can't handle type %s", obj->vtable->klass->name);
-       }
-
-       MonoType *t = mono_reflection_type_get_handle (type, error);
-       return_val_if_nok (error, NULL);
-       return inflate_mono_method (mono_class_from_mono_type (t), method, obj);
-}
-
-static void
-reflection_generic_class_initialize (MonoReflectionGenericClass *type, MonoError *error)
-{
-       MonoGenericClass *gclass;
-       MonoClass *klass, *gklass;
-       MonoType *gtype;
-
-       mono_error_init (error);
-
-       gtype = mono_reflection_type_get_handle ((MonoReflectionType*)type, error);
-       return_if_nok (error);
-       klass = mono_class_from_mono_type (gtype);
-       g_assert (gtype->type == MONO_TYPE_GENERICINST);
-       gclass = gtype->data.generic_class;
-
-       if (!gclass->is_dynamic)
-               return;
-
-       gklass = gclass->container_class;
-       mono_class_init (gklass);
-
-       /* Mark this as needing synchronization with its generic container */
-       gclass->need_sync = TRUE;
-}
-
-void
-mono_reflection_generic_class_initialize (MonoReflectionGenericClass *type, MonoArray *fields)
-{
-       MonoError error;
-       reflection_generic_class_initialize (type, &error);
-       mono_error_set_pending_exception (&error);
-}
-
 /**
  * fix_partial_generic_class:
  * @klass: a generic instantiation MonoClass
@@ -3788,7 +3056,7 @@ ensure_runtime_vtable (MonoClass *klass, MonoError *error)
                }
        } else if (klass->generic_class){
                if (!ensure_generic_class_runtime_vtable (klass, error)) {
-                       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+                       mono_class_set_type_load_failure (klass, "Could not initialize vtable for generic class due to: %s", mono_error_get_message (error));
                        return FALSE;
                }
        }
@@ -3825,7 +3093,7 @@ mono_reflection_method_get_handle (MonoObject *method, MonoError *error)
 {
        mono_error_init (error);
        MonoClass *klass = mono_object_class (method);
-       if (is_sr_mono_method (klass) || is_sr_mono_generic_method (klass)) {
+       if (is_sr_mono_method (klass)) {
                MonoReflectionMethod *sr_method = (MonoReflectionMethod*)method;
                return sr_method->method;
        }
@@ -3834,26 +3102,11 @@ mono_reflection_method_get_handle (MonoObject *method, MonoError *error)
                return mb->mhandle;
        }
        if (mono_is_sre_method_on_tb_inst (klass)) {
-               MonoReflectionMethodOnTypeBuilderInst *m = (MonoReflectionMethodOnTypeBuilderInst*)method;
-               MonoMethod *result;
-               /*FIXME move this to a proper method and unify with resolve_object*/
-               if (m->method_args) {
-                       result = mono_reflection_method_on_tb_inst_get_handle (m, error);
-               } else {
-                       MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)m->inst, error);
-                       return_val_if_nok (error, NULL);
-                       MonoClass *inflated_klass = mono_class_from_mono_type (type);
-                       MonoMethod *mono_method;
+               MonoClass *handle_class;
 
-                       if (is_sre_method_builder (mono_object_class (m->mb)))
-                               mono_method = ((MonoReflectionMethodBuilder *)m->mb)->mhandle;
-                       else if (is_sr_mono_method (mono_object_class (m->mb)))
-                               mono_method = ((MonoReflectionMethod *)m->mb)->method;
-                       else
-                               g_error ("resolve_object:: can't handle a MTBI with base_method of type %s", mono_type_get_full_name (mono_object_class (m->mb)));
+               MonoMethod *result =  mono_reflection_resolve_object (NULL, method, &handle_class, NULL, error);
+               return_val_if_nok (error, NULL);
 
-                       result = inflate_mono_method (inflated_klass, mono_method, (MonoObject*)m->mb);
-               }
                return result;
        }
 
@@ -3935,8 +3188,7 @@ typebuilder_setup_fields (MonoClass *klass, MonoError *error)
 
        if (tb->class_size) {
                if ((tb->packing_size & 0xffffff00) != 0) {
-                       char *err_msg = g_strdup_printf ("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;
@@ -4060,68 +3312,6 @@ typebuilder_setup_properties (MonoClass *klass, MonoError *error)
        }
 }
 
-static MonoReflectionEvent *
-reflection_event_builder_get_event_info (MonoReflectionTypeBuilder *tb, MonoReflectionEventBuilder *eb, MonoError *error)
-{
-       mono_error_init (error);
-
-       MonoEvent *event = g_new0 (MonoEvent, 1);
-       MonoClass *klass;
-
-       MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)tb, error);
-       if (!is_ok (error)) {
-               g_free (event);
-               return NULL;
-       }
-       klass = mono_class_from_mono_type (type);
-
-       event->parent = klass;
-       event->attrs = eb->attrs;
-       event->name = mono_string_to_utf8_checked (eb->name, error);
-       if (!is_ok (error)) {
-               g_free (event);
-               return NULL;
-       }
-       if (eb->add_method)
-               event->add = eb->add_method->mhandle;
-       if (eb->remove_method)
-               event->remove = eb->remove_method->mhandle;
-       if (eb->raise_method)
-               event->raise = eb->raise_method->mhandle;
-
-#ifndef MONO_SMALL_CONFIG
-       if (eb->other_methods) {
-               int j;
-               event->other = g_new0 (MonoMethod*, mono_array_length (eb->other_methods) + 1);
-               for (j = 0; j < mono_array_length (eb->other_methods); ++j) {
-                       MonoReflectionMethodBuilder *mb = 
-                               mono_array_get (eb->other_methods,
-                                               MonoReflectionMethodBuilder*, j);
-                       event->other [j] = mb->mhandle;
-               }
-       }
-#endif
-
-       MonoReflectionEvent *ev_obj = mono_event_get_object_checked (mono_object_domain (tb), klass, event, error);
-       if (!is_ok (error)) {
-#ifndef MONO_SMALL_CONFIG
-               g_free (event->other);
-#endif
-               g_free (event);
-               return NULL;
-       }
-       return ev_obj;
-}
-
-MonoReflectionEvent *
-ves_icall_TypeBuilder_get_event_info (MonoReflectionTypeBuilder *tb, MonoReflectionEventBuilder *eb)
-{
-       MonoError error;
-       MonoReflectionEvent *result = reflection_event_builder_get_event_info (tb, eb, &error);
-       mono_error_set_pending_exception (&error);
-       return result;
-}
-
 static void
 typebuilder_setup_events (MonoClass *klass, MonoError *error)
 {
@@ -4193,7 +3383,7 @@ remove_instantiations_of_and_ensure_contents (gpointer key,
                MonoClass *inst_klass = mono_class_from_mono_type (type);
                //Ensure it's safe to use it.
                if (!fix_partial_generic_class (inst_klass, error)) {
-                       mono_class_set_failure (inst_klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+                       mono_class_set_type_load_failure (inst_klass, "Could not initialized generic type instance due to: %s", mono_error_get_message (error));
                        // Marked the class with failure, but since some other instantiation already failed,
                        // just report that one, and swallow the error from this one.
                        if (already_failed)
@@ -4215,6 +3405,9 @@ ves_icall_TypeBuilder_create_runtime_class (MonoReflectionTypeBuilder *tb)
 
        mono_error_init (&error);
 
+       reflection_create_generic_class (tb, &error);
+       mono_error_assert_ok (&error);
+
        domain = mono_object_domain (tb);
        klass = mono_class_from_mono_type (tb->type.type);
 
@@ -4248,22 +3441,6 @@ ves_icall_TypeBuilder_create_runtime_class (MonoReflectionTypeBuilder *tb)
        mono_class_setup_supertypes (klass);
        mono_class_setup_mono_type (klass);
 
-#if 0
-       if (!((MonoDynamicImage*)klass->image)->run) {
-               if (klass->generic_container) {
-                       /* FIXME: The code below can't handle generic classes */
-                       klass->wastypebuilder = TRUE;
-                       mono_loader_unlock ();
-                       mono_domain_unlock (domain);
-
-                       res = mono_type_get_object_checked (mono_object_domain (tb), &klass->byval_arg, &error);
-                       mono_error_set_pending_exception (&error);
-
-                       return res;
-               }
-       }
-#endif
-
        /* enums are done right away */
        if (!klass->enumtype)
                if (!ensure_runtime_vtable (klass, &error))
@@ -4273,6 +3450,12 @@ ves_icall_TypeBuilder_create_runtime_class (MonoReflectionTypeBuilder *tb)
                for (i = 0; i < mono_array_length (tb->subtypes); ++i) {
                        MonoReflectionTypeBuilder *subtb = mono_array_get (tb->subtypes, MonoReflectionTypeBuilder*, i);
                        mono_class_alloc_ext (klass);
+
+                       if (!subtb->type.type) {
+                               reflection_setup_internal_class (subtb, &error);
+                               mono_error_assert_ok (&error);
+                       }
+
                        MonoType *subtype = mono_reflection_type_get_handle ((MonoReflectionType*)subtb, &error);
                        if (!is_ok (&error)) goto failure;
                        klass->ext->nested_classes = g_list_prepend_image (klass->image, klass->ext->nested_classes, mono_class_from_mono_type (subtype));
@@ -4311,6 +3494,16 @@ ves_icall_TypeBuilder_create_runtime_class (MonoReflectionTypeBuilder *tb)
 
        klass->wastypebuilder = TRUE;
 
+       if (tb->generic_params) {
+               for (i = 0; i < mono_array_length (tb->generic_params); i++) {
+                       MonoReflectionGenericParam *gparam = (MonoReflectionGenericParam *)mono_array_get (tb->generic_params, gpointer, i);
+                       MonoType *param_type = mono_reflection_type_get_handle ((MonoReflectionType*)gparam, &error);
+                       MonoClass *gklass = mono_class_from_mono_type (param_type);
+
+                       gklass->wastypebuilder = TRUE;
+               }
+       }
+
        /* 
         * If we are a generic TypeBuilder, there might be instantiations in the type cache
         * which have type System.Reflection.MonoGenericClass, but after the type is created, 
@@ -4332,7 +3525,7 @@ ves_icall_TypeBuilder_create_runtime_class (MonoReflectionTypeBuilder *tb)
        mono_loader_unlock ();
 
        if (klass->enumtype && !mono_class_is_valid_enum (klass)) {
-               mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+               mono_class_set_type_load_failure (klass, "Not a valid enumeration");
                mono_error_set_type_load_class (&error, klass, "Not a valid enumeration");
                goto failure_unlocked;
        }
@@ -4346,7 +3539,7 @@ ves_icall_TypeBuilder_create_runtime_class (MonoReflectionTypeBuilder *tb)
        return res;
 
 failure:
-       mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
+       mono_class_set_type_load_failure (klass, "TypeBuilder could not create runtime class due to: %s", mono_error_get_message (&error));
        klass->wastypebuilder = TRUE;
        mono_domain_unlock (domain);
        mono_loader_unlock ();
@@ -4355,69 +3548,6 @@ failure_unlocked:
        return NULL;
 }
 
-static gboolean
-reflection_initialize_generic_parameter (MonoReflectionGenericParam *gparam, MonoError *error)
-{
-       MonoGenericParamFull *param;
-       MonoImage *image;
-       MonoClass *pklass;
-
-       mono_error_init (error);
-
-       image = &gparam->tbuilder->module->dynamic_image->image;
-
-       param = mono_image_new0 (image, MonoGenericParamFull, 1);
-
-       param->info.name = mono_string_to_utf8_image (image, gparam->name, error);
-       mono_error_assert_ok (error);
-       param->param.num = gparam->index;
-
-       if (gparam->mbuilder) {
-               if (!gparam->mbuilder->generic_container) {
-                       MonoType *tb = mono_reflection_type_get_handle ((MonoReflectionType*)gparam->mbuilder->type, error);
-                       return_val_if_nok (error, FALSE);
-
-                       MonoClass *klass = mono_class_from_mono_type (tb);
-                       gparam->mbuilder->generic_container = (MonoGenericContainer *)mono_image_alloc0 (klass->image, sizeof (MonoGenericContainer));
-                       gparam->mbuilder->generic_container->is_method = TRUE;
-                       /* 
-                        * Cannot set owner.method, since the MonoMethod is not created yet.
-                        * Set the image field instead, so type_in_image () works.
-                        */
-                       gparam->mbuilder->generic_container->is_anonymous = TRUE;
-                       gparam->mbuilder->generic_container->owner.image = klass->image;
-               }
-               param->param.owner = gparam->mbuilder->generic_container;
-       } else if (gparam->tbuilder) {
-               if (!gparam->tbuilder->generic_container) {
-                       MonoType *tb = mono_reflection_type_get_handle ((MonoReflectionType*)gparam->tbuilder, error);
-                       return_val_if_nok (error, FALSE);
-                       MonoClass *klass = mono_class_from_mono_type (tb);
-                       gparam->tbuilder->generic_container = (MonoGenericContainer *)mono_image_alloc0 (klass->image, sizeof (MonoGenericContainer));
-                       gparam->tbuilder->generic_container->owner.klass = klass;
-               }
-               param->param.owner = gparam->tbuilder->generic_container;
-       }
-
-       pklass = mono_class_from_generic_parameter_internal ((MonoGenericParam *) param);
-
-       gparam->type.type = &pklass->byval_arg;
-
-       mono_class_set_ref_info (pklass, gparam);
-       mono_image_append_class_to_reflection_info_set (pklass);
-
-       return TRUE;
-}
-
-void
-ves_icall_GenericTypeParameterBuilder_initialize_generic_parameter (MonoReflectionGenericParam *gparam)
-{
-       MonoError error;
-       (void) reflection_initialize_generic_parameter (gparam, &error);
-       mono_error_set_pending_exception (&error);
-}
-
-
 typedef struct {
        MonoMethod *handle;
        MonoDomain *domain;
@@ -4646,16 +3776,17 @@ ensure_complete_type (MonoClass *klass, MonoError *error)
 gpointer
 mono_reflection_resolve_object (MonoImage *image, MonoObject *obj, MonoClass **handle_class, MonoGenericContext *context, MonoError *error)
 {
+       MonoClass *oklass = obj->vtable->klass;
        gpointer result = NULL;
 
        mono_error_init (error);
 
-       if (strcmp (obj->vtable->klass->name, "String") == 0) {
+       if (strcmp (oklass->name, "String") == 0) {
                result = mono_string_intern_checked ((MonoString*)obj, error);
                return_val_if_nok (error, NULL);
                *handle_class = mono_defaults.string_class;
                g_assert (result);
-       } else if (strcmp (obj->vtable->klass->name, "RuntimeType") == 0) {
+       } else if (strcmp (oklass->name, "RuntimeType") == 0) {
                MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)obj, error);
                return_val_if_nok (error, NULL);
                MonoClass *mc = mono_class_from_mono_type (type);
@@ -4675,10 +3806,8 @@ mono_reflection_resolve_object (MonoImage *image, MonoObject *obj, MonoClass **h
                }
                *handle_class = mono_defaults.typehandle_class;
                g_assert (result);
-       } else if (strcmp (obj->vtable->klass->name, "MonoMethod") == 0 ||
-                  strcmp (obj->vtable->klass->name, "MonoCMethod") == 0 ||
-                  strcmp (obj->vtable->klass->name, "MonoGenericCMethod") == 0 ||
-                  strcmp (obj->vtable->klass->name, "MonoGenericMethod") == 0) {
+       } else if (strcmp (oklass->name, "MonoMethod") == 0 ||
+                          strcmp (oklass->name, "MonoCMethod") == 0) {
                result = ((MonoReflectionMethod*)obj)->method;
                if (context) {
                        result = mono_class_inflate_generic_method_checked ((MonoMethod *)result, context, error);
@@ -4686,48 +3815,7 @@ mono_reflection_resolve_object (MonoImage *image, MonoObject *obj, MonoClass **h
                }
                *handle_class = mono_defaults.methodhandle_class;
                g_assert (result);
-       } else if (strcmp (obj->vtable->klass->name, "MethodBuilder") == 0) {
-               MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder*)obj;
-               result = mb->mhandle;
-               if (!result) {
-                       /* Type is not yet created */
-                       MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)mb->type;
-
-                       mono_domain_try_type_resolve_checked (mono_domain_get (), NULL, (MonoObject*)tb, error);
-                       return_val_if_nok (error, NULL);
-
-                       /*
-                        * Hopefully this has been filled in by calling CreateType() on the
-                        * TypeBuilder.
-                        */
-                       /*
-                        * TODO: This won't work if the application finishes another 
-                        * TypeBuilder instance instead of this one.
-                        */
-                       result = mb->mhandle;
-               }
-               if (context) {
-                       result = mono_class_inflate_generic_method_checked ((MonoMethod *)result, context, error);
-                       mono_error_assert_ok (error);
-               }
-               *handle_class = mono_defaults.methodhandle_class;
-       } else if (strcmp (obj->vtable->klass->name, "ConstructorBuilder") == 0) {
-               MonoReflectionCtorBuilder *cb = (MonoReflectionCtorBuilder*)obj;
-
-               result = cb->mhandle;
-               if (!result) {
-                       MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)cb->type;
-
-                       mono_domain_try_type_resolve_checked (mono_domain_get (), NULL, (MonoObject*)tb, error);
-                       return_val_if_nok (error, NULL);
-                       result = cb->mhandle;
-               }
-               if (context) {
-                       result = mono_class_inflate_generic_method_checked ((MonoMethod *)result, context, error);
-                       mono_error_assert_ok (error);
-               }
-               *handle_class = mono_defaults.methodhandle_class;
-       } else if (strcmp (obj->vtable->klass->name, "MonoField") == 0) {
+       } else if (strcmp (oklass->name, "MonoField") == 0) {
                MonoClassField *field = ((MonoReflectionField*)obj)->field;
 
                ensure_complete_type (field->parent, error);
@@ -4752,31 +3840,7 @@ mono_reflection_resolve_object (MonoImage *image, MonoObject *obj, MonoClass **h
                }
                *handle_class = mono_defaults.fieldhandle_class;
                g_assert (result);
-       } else if (strcmp (obj->vtable->klass->name, "FieldBuilder") == 0) {
-               MonoReflectionFieldBuilder *fb = (MonoReflectionFieldBuilder*)obj;
-               result = fb->handle;
-
-               if (!result) {
-                       MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)fb->typeb;
-
-                       mono_domain_try_type_resolve_checked (mono_domain_get (), NULL, (MonoObject*)tb, error);
-                       return_val_if_nok (error, NULL);
-                       result = fb->handle;
-               }
-
-               if (fb->handle && fb->handle->parent->generic_container) {
-                       MonoClass *klass = fb->handle->parent;
-                       MonoType *type = mono_class_inflate_generic_type_checked (&klass->byval_arg, context, error);
-                       return_val_if_nok (error, NULL);
-
-                       MonoClass *inflated = mono_class_from_mono_type (type);
-
-                       result = mono_class_get_field_from_name (inflated, mono_field_get_name (fb->handle));
-                       g_assert (result);
-                       mono_metadata_free_type (type);
-               }
-               *handle_class = mono_defaults.fieldhandle_class;
-       } else if (strcmp (obj->vtable->klass->name, "TypeBuilder") == 0) {
+       } else if (strcmp (oklass->name, "TypeBuilder") == 0) {
                MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)obj;
                MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)tb, error);
                return_val_if_nok (error, NULL);
@@ -4794,7 +3858,7 @@ mono_reflection_resolve_object (MonoImage *image, MonoObject *obj, MonoClass **h
                        g_assert (result);
                }
                *handle_class = mono_defaults.typehandle_class;
-       } else if (strcmp (obj->vtable->klass->name, "SignatureHelper") == 0) {
+       } else if (strcmp (oklass->name, "SignatureHelper") == 0) {
                MonoReflectionSigHelper *helper = (MonoReflectionSigHelper*)obj;
                MonoMethodSignature *sig;
                int nargs, i;
@@ -4830,112 +3894,13 @@ mono_reflection_resolve_object (MonoImage *image, MonoObject *obj, MonoClass **h
 
                result = sig;
                *handle_class = NULL;
-       } else if (strcmp (obj->vtable->klass->name, "DynamicMethod") == 0) {
+       } else if (strcmp (oklass->name, "DynamicMethod") == 0) {
                MonoReflectionDynamicMethod *method = (MonoReflectionDynamicMethod*)obj;
                /* Already created by the managed code */
                g_assert (method->mhandle);
                result = method->mhandle;
                *handle_class = mono_defaults.methodhandle_class;
-       } else if (strcmp (obj->vtable->klass->name, "GenericTypeParameterBuilder") == 0) {
-               MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)obj, error);
-               return_val_if_nok (error, NULL);
-               type = mono_class_inflate_generic_type_checked (type, context, error);
-               return_val_if_nok (error, NULL);
-
-               result = mono_class_from_mono_type (type);
-               *handle_class = mono_defaults.typehandle_class;
-               g_assert (result);
-               mono_metadata_free_type (type);
-       } else if (strcmp (obj->vtable->klass->name, "MonoGenericClass") == 0) {
-               MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)obj, error);
-               return_val_if_nok (error, NULL);
-               type = mono_class_inflate_generic_type_checked (type, context, error);
-               return_val_if_nok (error, NULL);
-
-               result = mono_class_from_mono_type (type);
-               *handle_class = mono_defaults.typehandle_class;
-               g_assert (result);
-               mono_metadata_free_type (type);
-       } else if (strcmp (obj->vtable->klass->name, "FieldOnTypeBuilderInst") == 0) {
-               MonoReflectionFieldOnTypeBuilderInst *f = (MonoReflectionFieldOnTypeBuilderInst*)obj;
-               MonoClass *inflated;
-               MonoType *type;
-               MonoClassField *field;
-
-               if (is_sre_field_builder (mono_object_class (f->fb)))
-                       field = ((MonoReflectionFieldBuilder*)f->fb)->handle;
-               else if (is_sr_mono_field (mono_object_class (f->fb)))
-                       field = ((MonoReflectionField*)f->fb)->field;
-               else
-                       g_error ("resolve_object:: can't handle a FTBI with base_method of type %s", mono_type_get_full_name (mono_object_class (f->fb)));
-
-               MonoType *finst = mono_reflection_type_get_handle ((MonoReflectionType*)f->inst, error);
-               return_val_if_nok (error, NULL);
-               type = mono_class_inflate_generic_type_checked (finst, context, error);
-               return_val_if_nok (error, NULL);
-
-               inflated = mono_class_from_mono_type (type);
-
-               result = field = mono_class_get_field_from_name (inflated, mono_field_get_name (field));
-               ensure_complete_type (field->parent, error);
-               if (!is_ok (error)) {
-                       mono_metadata_free_type (type);
-                       return NULL;
-               }
-
-               g_assert (result);
-               mono_metadata_free_type (type);
-               *handle_class = mono_defaults.fieldhandle_class;
-       } else if (strcmp (obj->vtable->klass->name, "ConstructorOnTypeBuilderInst") == 0) {
-               MonoReflectionCtorOnTypeBuilderInst *c = (MonoReflectionCtorOnTypeBuilderInst*)obj;
-               MonoType *cinst = mono_reflection_type_get_handle ((MonoReflectionType*)c->inst, error);
-               return_val_if_nok (error, NULL);
-               MonoType *type = mono_class_inflate_generic_type_checked (cinst, context, error);
-               return_val_if_nok (error, NULL);
-
-               MonoClass *inflated_klass = mono_class_from_mono_type (type);
-               MonoMethod *method;
-
-               if (mono_is_sre_ctor_builder (mono_object_class (c->cb)))
-                       method = ((MonoReflectionCtorBuilder *)c->cb)->mhandle;
-               else if (mono_is_sr_mono_cmethod (mono_object_class (c->cb)))
-                       method = ((MonoReflectionMethod *)c->cb)->method;
-               else
-                       g_error ("resolve_object:: can't handle a CTBI with base_method of type %s", mono_type_get_full_name (mono_object_class (c->cb)));
-
-               result = inflate_mono_method (inflated_klass, method, (MonoObject*)c->cb);
-               *handle_class = mono_defaults.methodhandle_class;
-               mono_metadata_free_type (type);
-       } else if (strcmp (obj->vtable->klass->name, "MethodOnTypeBuilderInst") == 0) {
-               MonoReflectionMethodOnTypeBuilderInst *m = (MonoReflectionMethodOnTypeBuilderInst*)obj;
-               if (m->method_args) {
-                       result = mono_reflection_method_on_tb_inst_get_handle (m, error);
-                       return_val_if_nok (error, NULL);
-                       if (context) {
-                               result = mono_class_inflate_generic_method_checked ((MonoMethod *)result, context, error);
-                               mono_error_assert_ok (error);
-                       }
-               } else {
-                       MonoType *minst = mono_reflection_type_get_handle ((MonoReflectionType*)m->inst, error);
-                       return_val_if_nok (error, NULL);
-                       MonoType *type = mono_class_inflate_generic_type_checked (minst, context, error);
-                       return_val_if_nok (error, NULL);
-
-                       MonoClass *inflated_klass = mono_class_from_mono_type (type);
-                       MonoMethod *method;
-
-                       if (is_sre_method_builder (mono_object_class (m->mb)))
-                               method = ((MonoReflectionMethodBuilder *)m->mb)->mhandle;
-                       else if (is_sr_mono_method (mono_object_class (m->mb)))
-                               method = ((MonoReflectionMethod *)m->mb)->method;
-                       else
-                               g_error ("resolve_object:: can't handle a MTBI with base_method of type %s", mono_type_get_full_name (mono_object_class (m->mb)));
-
-                       result = inflate_mono_method (inflated_klass, method, (MonoObject*)m->mb);
-                       mono_metadata_free_type (type);
-               }
-               *handle_class = mono_defaults.methodhandle_class;
-       } else if (strcmp (obj->vtable->klass->name, "MonoArrayMethod") == 0) {
+       } else if (strcmp (oklass->name, "MonoArrayMethod") == 0) {
                MonoReflectionArrayMethod *m = (MonoReflectionArrayMethod*)obj;
                MonoType *mtype;
                MonoClass *klass;
@@ -4964,23 +3929,30 @@ mono_reflection_resolve_object (MonoImage *image, MonoObject *obj, MonoClass **h
 
                result = method;
                *handle_class = mono_defaults.methodhandle_class;
-       } else if (is_sre_array (mono_object_get_class(obj)) ||
-                               is_sre_byref (mono_object_get_class(obj)) ||
-                               is_sre_pointer (mono_object_get_class(obj))) {
-               MonoReflectionType *ref_type = (MonoReflectionType *)obj;
-               MonoType *type = mono_reflection_type_get_handle (ref_type, error);
-               return_val_if_nok (error, NULL);
-
-               if (context) {
-                       MonoType *inflated = mono_class_inflate_generic_type_checked (type, context, error);
-                       return_val_if_nok (error, NULL);
-
-                       result = mono_class_from_mono_type (inflated);
-                       mono_metadata_free_type (inflated);
-               } else {
-                       result = mono_class_from_mono_type (type);
+       } else if (is_sre_method_builder (oklass) ||
+                          mono_is_sre_ctor_builder (oklass) ||
+                          is_sre_field_builder (oklass) ||
+                          is_sre_gparam_builder (oklass) ||
+                          is_sre_generic_instance (oklass) ||
+                          is_sre_array (oklass) ||
+                          is_sre_byref (oklass) ||
+                          is_sre_pointer (oklass) ||
+                          !strcmp (oklass->name, "FieldOnTypeBuilderInst") ||
+                          !strcmp (oklass->name, "MethodOnTypeBuilderInst") ||
+                          !strcmp (oklass->name, "ConstructorOnTypeBuilderInst")) {
+               static MonoMethod *resolve_method;
+               if (!resolve_method) {
+                       MonoMethod *m = mono_class_get_method_from_name_flags (mono_class_get_module_builder_class (), "RuntimeResolve", 1, 0);
+                       g_assert (m);
+                       mono_memory_barrier ();
+                       resolve_method = m;
                }
-               *handle_class = mono_defaults.typehandle_class;
+               void *args [16];
+               args [0] = obj;
+               obj = mono_runtime_invoke_checked (resolve_method, NULL, args, error);
+               mono_error_assert_ok (error);
+               g_assert (obj);
+               return mono_reflection_resolve_object (image, obj, handle_class, context, error);
        } else {
                g_print ("%s\n", obj->vtable->klass->name);
                g_assert_not_reached ();
@@ -4997,19 +3969,6 @@ mono_reflection_get_custom_attrs_blob (MonoReflectionAssembly *assembly, MonoObj
        return NULL;
 }
 
-void
-ves_icall_TypeBuilder_setup_internal_class (MonoReflectionTypeBuilder *tb)
-{
-       g_assert_not_reached ();
-}
-
-gboolean
-mono_reflection_create_generic_class (MonoReflectionTypeBuilder *tb, MonoError *error)
-{
-       g_assert_not_reached ();
-       return FALSE;
-}
-
 void
 mono_reflection_dynimage_basic_init (MonoReflectionAssemblyBuilder *assemblyb)
 {
@@ -5044,12 +4003,6 @@ mono_image_create_token (MonoDynamicImage *assembly, MonoObject *obj,
        return 0;
 }
 
-void
-mono_reflection_generic_class_initialize (MonoReflectionGenericClass *type, MonoArray *fields)
-{
-       g_assert_not_reached ();
-}
-
 void
 mono_reflection_get_dynamic_overrides (MonoClass *klass, MonoMethod ***overrides, int *num_overrides, MonoError *error)
 {
@@ -5058,13 +4011,6 @@ mono_reflection_get_dynamic_overrides (MonoClass *klass, MonoMethod ***overrides
        *num_overrides = 0;
 }
 
-MonoReflectionEvent *
-ves_icall_TypeBuilder_get_event_info (MonoReflectionTypeBuilder *tb, MonoReflectionEventBuilder *eb)
-{
-       g_assert_not_reached ();
-       return NULL;
-}
-
 MonoReflectionType*
 ves_icall_TypeBuilder_create_runtime_class (MonoReflectionTypeBuilder *tb)
 {
@@ -5072,12 +4018,6 @@ ves_icall_TypeBuilder_create_runtime_class (MonoReflectionTypeBuilder *tb)
        return NULL;
 }
 
-void
-ves_icall_GenericTypeParameterBuilder_initialize_generic_parameter (MonoReflectionGenericParam *gparam)
-{
-       g_assert_not_reached ();
-}
-
 void 
 ves_icall_DynamicMethod_create_dynamic_method (MonoReflectionDynamicMethod *mb)
 {
@@ -5094,27 +4034,12 @@ mono_reflection_type_get_handle (MonoReflectionType* ref, MonoError *error)
 
 #endif /* DISABLE_REFLECTION_EMIT */
 
-#ifndef DISABLE_REFLECTION_EMIT
-MonoMethod*
-mono_reflection_method_builder_to_mono_method (MonoReflectionMethodBuilder *mb, MonoError *error)
-{
-       MonoType *tb;
-       MonoClass *klass;
-
-       tb = mono_reflection_type_get_handle ((MonoReflectionType*)mb->type, error);
-       return_val_if_nok (error, NULL);
-       klass = mono_class_from_mono_type (tb);
-
-       return methodbuilder_to_mono_method (klass, mb, error);
-}
-#else /* DISABLE_REFLECTION_EMIT */
-MonoMethod*
-mono_reflection_method_builder_to_mono_method (MonoReflectionMethodBuilder *mb, MonoError *error)
+void
+mono_sre_generic_param_table_entry_free (GenericParamTableEntry *entry)
 {
-       g_assert_not_reached ();
-       return NULL;
+       mono_gc_deregister_root ((char*) &entry->gparam);
+       g_free (entry);
 }
-#endif /* DISABLE_REFLECTION_EMIT */
 
 gint32
 ves_icall_ModuleBuilder_getToken (MonoReflectionModuleBuilder *mb, MonoObject *obj, gboolean create_open_instance)
@@ -5175,21 +4100,6 @@ ves_icall_ModuleBuilder_GetRegisteredToken (MonoReflectionModuleBuilder *mb, gui
        return obj;
 }
 
-/**
- * ves_icall_TypeBuilder_create_generic_class:
- * @tb: a TypeBuilder object
- *
- * (icall)
- * Creates the generic class after all generic parameters have been added.
- */
-void
-ves_icall_TypeBuilder_create_generic_class (MonoReflectionTypeBuilder *tb)
-{
-       MonoError error;
-       (void) mono_reflection_create_generic_class (tb, &error);
-       mono_error_set_pending_exception (&error);
-}
-
 #ifndef DISABLE_REFLECTION_EMIT
 MonoArray*
 ves_icall_CustomAttributeBuilder_GetBlob (MonoReflectionAssembly *assembly, MonoObject *ctor, MonoArray *ctorArgs, MonoArray *properties, MonoArray *propValues, MonoArray *fields, MonoArray* fieldValues)
@@ -5207,12 +4117,6 @@ ves_icall_AssemblyBuilder_basic_init (MonoReflectionAssemblyBuilder *assemblyb)
        mono_reflection_dynimage_basic_init (assemblyb);
 }
 
-MonoBoolean
-ves_icall_TypeBuilder_get_IsGenericParameter (MonoReflectionTypeBuilder *tb)
-{
-       return mono_type_is_generic_parameter (tb->type.type);
-}
-
 void
 ves_icall_EnumBuilder_setup_enum_type (MonoReflectionType *enumtype,
                                                                           MonoReflectionType *t)
@@ -5220,77 +4124,6 @@ ves_icall_EnumBuilder_setup_enum_type (MonoReflectionType *enumtype,
        enumtype->type = t->type;
 }
 
-MonoReflectionType*
-ves_icall_ModuleBuilder_create_modified_type (MonoReflectionTypeBuilder *tb, MonoString *smodifiers)
-{
-       MonoError error;
-       MonoReflectionType *ret;
-       MonoClass *klass;
-       int isbyref = 0, rank;
-       char *p;
-       char *str = mono_string_to_utf8_checked (smodifiers, &error);
-       if (mono_error_set_pending_exception (&error))
-               return NULL;
-
-       klass = mono_class_from_mono_type (tb->type.type);
-       p = str;
-       /* logic taken from mono_reflection_parse_type(): keep in sync */
-       while (*p) {
-               switch (*p) {
-               case '&':
-                       if (isbyref) { /* only one level allowed by the spec */
-                               g_free (str);
-                               return NULL;
-                       }
-                       isbyref = 1;
-                       p++;
-
-                       g_free (str);
-
-                       ret = mono_type_get_object_checked (mono_object_domain (tb), &klass->this_arg, &error);
-                       mono_error_set_pending_exception (&error);
-
-                       return ret;
-               case '*':
-                       klass = mono_ptr_class_get (&klass->byval_arg);
-                       mono_class_init (klass);
-                       p++;
-                       break;
-               case '[':
-                       rank = 1;
-                       p++;
-                       while (*p) {
-                               if (*p == ']')
-                                       break;
-                               if (*p == ',')
-                                       rank++;
-                               else if (*p != '*') { /* '*' means unknown lower bound */
-                                       g_free (str);
-                                       return NULL;
-                               }
-                               ++p;
-                       }
-                       if (*p != ']') {
-                               g_free (str);
-                               return NULL;
-                       }
-                       p++;
-                       klass = mono_array_class_get (klass, rank);
-                       mono_class_init (klass);
-                       break;
-               default:
-                       break;
-               }
-       }
-
-       g_free (str);
-
-       ret = mono_type_get_object_checked (mono_object_domain (tb), &klass->byval_arg, &error);
-       mono_error_set_pending_exception (&error);
-
-       return ret;
-}
-
 void
 ves_icall_ModuleBuilder_basic_init (MonoReflectionModuleBuilder *moduleb)
 {
index 462fd69a77f172521b3ff983aae71160b2099aa4..d22470415e84e1891759e5a31df748eacde76531 100644 (file)
@@ -162,7 +162,7 @@ typedef struct {
 
 typedef struct {
        gint32 ref;
-       MonoCoopSem sem;
+       MonoCoopCond cond;
 } ThreadPoolDomainCleanupSemaphore;
 
 typedef enum {
@@ -439,7 +439,7 @@ domain_get (MonoDomain *domain, gboolean create)
                ThreadPoolDomainCleanupSemaphore *cleanup_semaphore;
                cleanup_semaphore = g_new0 (ThreadPoolDomainCleanupSemaphore, 1);
                cleanup_semaphore->ref = 2;
-               mono_coop_sem_init (&cleanup_semaphore->sem, 0);
+               mono_coop_cond_init (&cleanup_semaphore->cond);
 
                g_assert(!domain->cleanup_semaphore);
                domain->cleanup_semaphore = cleanup_semaphore;
@@ -658,7 +658,7 @@ worker_thread (gpointer data)
                tpdomain->outstanding_request --;
                g_assert (tpdomain->outstanding_request >= 0);
 
-               mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] worker running in domain %p",
+               mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] worker running in domain %p (outstanding requests %d) ",
                        mono_native_thread_id_get (), tpdomain->domain, tpdomain->outstanding_request);
 
                g_assert (tpdomain->domain);
@@ -702,11 +702,12 @@ worker_thread (gpointer data)
                        g_assert (removed);
 
                        cleanup_semaphore = (ThreadPoolDomainCleanupSemaphore*) tpdomain->domain->cleanup_semaphore;
+                       g_assert (cleanup_semaphore);
+
+                       mono_coop_cond_signal (&cleanup_semaphore->cond);
 
-                       g_assert(cleanup_semaphore);
-                       mono_coop_sem_post (&cleanup_semaphore->sem);
                        if (InterlockedDecrement (&cleanup_semaphore->ref) == 0) {
-                               mono_coop_sem_destroy (&cleanup_semaphore->sem);
+                               mono_coop_cond_destroy (&cleanup_semaphore->cond);
                                g_free (cleanup_semaphore);
                                tpdomain->domain->cleanup_semaphore = NULL;
                        }
@@ -777,7 +778,7 @@ worker_try_create (void)
        if ((thread = mono_thread_create_internal (mono_get_root_domain (), worker_thread, NULL, TRUE, 0, &error)) != NULL) {
                threadpool->worker_creation_current_count += 1;
 
-               mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker, created %p, now = %d count = %d", mono_native_thread_id_get (), thread->tid, now, threadpool->worker_creation_current_count);
+               mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_THREADPOOL, "[%p] try create worker, created %p, now = %d count = %d", mono_native_thread_id_get (), GUINT_TO_POINTER(thread->tid), now, threadpool->worker_creation_current_count);
                mono_coop_mutex_unlock (&threadpool->worker_creation_lock);
                return TRUE;
        }
@@ -1453,10 +1454,10 @@ mono_threadpool_ms_end_invoke (MonoAsyncResult *ares, MonoArray **out_args, Mono
 gboolean
 mono_threadpool_ms_remove_domain_jobs (MonoDomain *domain, int timeout)
 {
-       gint res;
-       gint64 now, end;
+       gint64 end;
        ThreadPoolDomain *tpdomain;
        ThreadPoolDomainCleanupSemaphore *cleanup_semaphore;
+       gboolean ret;
 
        g_assert (domain);
        g_assert (timeout >= -1);
@@ -1493,29 +1494,41 @@ mono_threadpool_ms_remove_domain_jobs (MonoDomain *domain, int timeout)
                return TRUE;
        }
 
-       mono_coop_mutex_unlock(&threadpool->domains_lock);
-
        g_assert (domain->cleanup_semaphore);
-
        cleanup_semaphore = (ThreadPoolDomainCleanupSemaphore*) domain->cleanup_semaphore;
 
-       if (timeout == -1) {
-               res = mono_coop_sem_wait (&cleanup_semaphore->sem, MONO_SEM_FLAGS_NONE);
-               g_assert (res == MONO_SEM_TIMEDWAIT_RET_SUCCESS);
-       } else {
-               now = mono_msec_ticks();
-               if (now > end)
-                       return FALSE;
-               res = mono_coop_sem_timedwait (&cleanup_semaphore->sem, end - now, MONO_SEM_FLAGS_NONE);
-       }
+       ret = TRUE;
+
+       do {
+               if (timeout == -1) {
+                       mono_coop_cond_wait (&cleanup_semaphore->cond, &threadpool->domains_lock);
+               } else {
+                       gint64 now;
+                       gint res;
+
+                       now = mono_msec_ticks();
+                       if (now > end) {
+                               ret = FALSE;
+                               break;
+                       }
+
+                       res = mono_coop_cond_timedwait (&cleanup_semaphore->cond, &threadpool->domains_lock, end - now);
+                       if (res != 0) {
+                               ret = FALSE;
+                               break;
+                       }
+               }
+       } while (tpdomain->outstanding_request != 0);
 
        if (InterlockedDecrement (&cleanup_semaphore->ref) == 0) {
-               mono_coop_sem_destroy (&cleanup_semaphore->sem);
+               mono_coop_cond_destroy (&cleanup_semaphore->cond);
                g_free (cleanup_semaphore);
                domain->cleanup_semaphore = NULL;
        }
 
-       return res == MONO_SEM_TIMEDWAIT_RET_SUCCESS;
+       mono_coop_mutex_unlock(&threadpool->domains_lock);
+
+       return ret;
 }
 
 void
index ad472a0b9c06030dcc1e3cba4a235bc9c6287517..a7fd76f1f1c435ef6cc7888fdf1153f2a9ff6df8 100644 (file)
@@ -260,4 +260,13 @@ void mono_threads_begin_abort_protected_block (void);
 void mono_threads_end_abort_protected_block (void);
 MonoException* mono_thread_try_resume_interruption (void);
 
+gboolean
+mono_thread_internal_current_is_attached (void);
+
+void
+mono_thread_internal_describe (MonoInternalThread *internal, GString *str);
+
+gboolean
+mono_thread_internal_is_current (MonoInternalThread *internal);
+
 #endif /* _MONO_METADATA_THREADS_TYPES_H_ */
index 8d8510f5fb0edca44e597ccf064b725d2ea02ffc..2ae43aab0ae3be675b979e4cb5756fc1d6ed169a 100644 (file)
@@ -46,6 +46,7 @@
 #include <mono/utils/mono-error-internals.h>
 #include <mono/utils/w32handle.h>
 #include <mono/metadata/w32event.h>
+#include <mono/metadata/w32mutex.h>
 
 #include <mono/metadata/gc-internals.h>
 #include <mono/metadata/reflection-internals.h>
 #include <signal.h>
 #endif
 
+#if defined(HOST_WIN32)
+#include <objbase.h>
+#endif
+
 #if defined(PLATFORM_ANDROID) && !defined(TARGET_ARM64) && !defined(TARGET_AMD64)
 #define USE_TKILL_ON_ANDROID 1
 #endif
@@ -874,20 +879,10 @@ static guint32 WINAPI start_wrapper_internal(StartInfo *start_info, gsize *stack
         * for the current thead */
        mono_thread_cleanup_apartment_state ();
 
-       thread_cleanup (internal);
+       mono_thread_detach_internal (internal);
 
        internal->tid = 0;
 
-       /* Remove the reference to the thread object in the TLS data,
-        * so the thread object can be finalized.  This won't be
-        * reached if the thread threw an uncaught exception, so those
-        * thread handles will stay referenced :-( (This is due to
-        * missing support for scanning thread-specific data in the
-        * Boehm GC - the io-layer keeps a GC-visible hash of pointers
-        * to TLS data.)
-        */
-       SET_CURRENT_OBJECT (NULL);
-
        return(0);
 }
 
@@ -915,6 +910,7 @@ create_thread (MonoThread *thread, MonoInternalThread *internal, MonoObject *sta
        HANDLE thread_handle;
        MonoNativeThreadId tid;
        gboolean ret;
+       gsize stack_set_size;
 
        if (start_delegate)
                g_assert (!start_func && !start_func_arg);
@@ -956,9 +952,11 @@ create_thread (MonoThread *thread, MonoInternalThread *internal, MonoObject *sta
        mono_coop_sem_init (&start_info->registered, 0);
 
        if (stack_size == 0)
-               stack_size = default_stacksize_for_thread (internal);
+               stack_set_size = default_stacksize_for_thread (internal);
+       else
+               stack_set_size = 0;
 
-       thread_handle = mono_threads_create_thread (start_wrapper, start_info, stack_size, &tid);
+       thread_handle = mono_threads_create_thread (start_wrapper, start_info, &stack_set_size, &tid);
 
        if (thread_handle == NULL) {
                /* The thread couldn't be created, so set an exception */
@@ -972,6 +970,8 @@ create_thread (MonoThread *thread, MonoInternalThread *internal, MonoObject *sta
                goto done;
        }
 
+       internal->stack_size = (int) stack_set_size;
+
        THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Launching thread %p (%"G_GSIZE_FORMAT")", __func__, mono_native_thread_id_get (), internal, (gsize)internal->tid));
 
        /*
@@ -1075,7 +1075,7 @@ mono_thread_attach_full (MonoDomain *domain, gboolean force_attach)
        MonoNativeThreadId tid;
        gsize stack_ptr;
 
-       if ((internal = mono_thread_internal_current ())) {
+       if (mono_thread_internal_current_is_attached ()) {
                if (domain != mono_domain_get ())
                        mono_domain_set (domain, TRUE);
                /* Already attached */
@@ -1127,6 +1127,10 @@ mono_thread_detach_internal (MonoInternalThread *thread)
 
        THREAD_DEBUG (g_message ("%s: mono_thread_detach for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
 
+#ifndef HOST_WIN32
+       mono_w32mutex_abandon ();
+#endif
+
        thread_cleanup (thread);
 
        SET_CURRENT_OBJECT (NULL);
@@ -1168,6 +1172,18 @@ mono_thread_detach_if_exiting (void)
        return FALSE;
 }
 
+gboolean
+mono_thread_internal_current_is_attached (void)
+{
+       MonoInternalThread *internal;
+
+       internal = GET_CURRENT_OBJECT ();
+       if (!internal)
+               return FALSE;
+
+       return TRUE;
+}
+
 void
 mono_thread_exit (void)
 {
@@ -1175,13 +1191,12 @@ mono_thread_exit (void)
 
        THREAD_DEBUG (g_message ("%s: mono_thread_exit for %p (%"G_GSIZE_FORMAT")", __func__, thread, (gsize)thread->tid));
 
-       thread_cleanup (thread);
-       SET_CURRENT_OBJECT (NULL);
-       mono_domain_unset ();
+       mono_thread_detach_internal (thread);
 
        /* we could add a callback here for embedders to use. */
        if (mono_thread_get_main () && (thread == mono_thread_get_main ()->internal_thread))
                exit (mono_environment_exitcode_get ());
+
        mono_thread_info_exit ();
 }
 
@@ -2923,34 +2938,14 @@ wait_for_tids (struct wait_data *wait, guint32 timeout)
                return;
 
        for(i=0; i<wait->num; i++) {
-               gsize tid = wait->threads[i]->tid;
+               MonoInternalThread *internal;
 
-               /*
-                * On !win32, when the thread handle becomes signalled, it just means the thread has exited user code,
-                * it can still run io-layer etc. code. So wait for it to really exit.
-                * FIXME: This won't join threads which are not in the joinable_hash yet.
-                */
-               mono_thread_join ((gpointer)tid);
+               internal = wait->threads [i];
 
                mono_threads_lock ();
-               if(mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
-                       /* This thread must have been killed, because
-                        * it hasn't cleaned itself up. (It's just
-                        * possible that the thread exited before the
-                        * parent thread had a chance to store the
-                        * handle, and now there is another pointer to
-                        * the already-exited thread stored.  In this
-                        * case, we'll just get two
-                        * mono_profiler_thread_end() calls for the
-                        * same thread.)
-                        */
-       
-                       mono_threads_unlock ();
-                       THREAD_DEBUG (g_message ("%s: cleaning up after thread %p (%"G_GSIZE_FORMAT")", __func__, wait->threads[i], tid));
-                       thread_cleanup (wait->threads[i]);
-               } else {
-                       mono_threads_unlock ();
-               }
+               if (mono_g_hash_table_lookup (threads, (gpointer) internal->tid) == internal)
+                       g_error ("%s: failed to call mono_thread_detach_internal on thread %p, InternalThread: %p", __func__, internal->tid, internal);
+               mono_threads_unlock ();
        }
 }
 
@@ -2986,15 +2981,14 @@ static void wait_for_tids_or_state_change (struct wait_data *wait, guint32 timeo
                return;
        
        if (ret < wait->num) {
-               gsize tid = wait->threads[ret]->tid;
+               MonoInternalThread *internal;
+
+               internal = wait->threads [ret];
+
                mono_threads_lock ();
-               if (mono_g_hash_table_lookup (threads, (gpointer)tid)!=NULL) {
-                       /* See comment in wait_for_tids about thread cleanup */
-                       mono_threads_unlock ();
-                       THREAD_DEBUG (g_message ("%s: cleaning up after thread %"G_GSIZE_FORMAT, __func__, tid));
-                       thread_cleanup (wait->threads [ret]);
-               } else
-                       mono_threads_unlock ();
+               if (mono_g_hash_table_lookup (threads, (gpointer) internal->tid) == internal)
+                       g_error ("%s: failed to call mono_thread_detach_internal on thread %p, InternalThread: %p", __func__, internal->tid, internal);
+               mono_threads_unlock ();
        }
 }
 
@@ -3122,8 +3116,8 @@ mono_threads_set_shutting_down (void)
                        UNLOCK_THREAD (current_thread);
                }
 
-               /*since we're killing the thread, unset the current domain.*/
-               mono_domain_unset ();
+               /*since we're killing the thread, detach it.*/
+               mono_thread_detach_internal (current_thread);
 
                /* Wake up other threads potentially waiting for us */
                mono_thread_info_exit ();
@@ -3383,7 +3377,7 @@ get_thread_dump (MonoThreadInfo *info, gpointer ud)
 #if 0
 /* This no longer works with remote unwinding */
        g_string_append_printf (text, " tid=0x%p this=0x%p ", (gpointer)(gsize)thread->tid, thread);
-       mono_thread_info_describe (info, text);
+       mono_thread_internal_describe (thread, text);
        g_string_append (text, "\n");
 #endif
 
@@ -4932,7 +4926,7 @@ mono_threads_join_threads (void)
                        if (thread != pthread_self ()) {
                                MONO_ENTER_GC_SAFE;
                                /* This shouldn't block */
-                               pthread_join (thread, NULL);
+                               mono_native_thread_join (thread);
                                MONO_EXIT_GC_SAFE;
                        }
                } else {
@@ -4968,7 +4962,7 @@ mono_thread_join (gpointer tid)
                return;
        thread = (pthread_t)tid;
        MONO_ENTER_GC_SAFE;
-       pthread_join (thread, NULL);
+       mono_native_thread_join (thread);
        MONO_EXIT_GC_SAFE;
 #endif
 }
@@ -5136,6 +5130,7 @@ mono_thread_try_resume_interruption (void)
        return mono_thread_resume_interruption ();
 }
 
+#if 0
 /* Returns TRUE if the current thread is ready to be interrupted. */
 gboolean
 mono_threads_is_ready_to_be_interrupted (void)
@@ -5156,4 +5151,32 @@ mono_threads_is_ready_to_be_interrupted (void)
 
        UNLOCK_THREAD (thread);
        return TRUE;
-}
\ No newline at end of file
+}
+#endif
+
+void
+mono_thread_internal_describe (MonoInternalThread *internal, GString *text)
+{
+       g_string_append_printf (text, ", thread handle : %p", internal->handle);
+
+       if (internal->thread_info) {
+               g_string_append (text, ", state : ");
+               mono_thread_info_describe_interrupt_token ((MonoThreadInfo*) internal->thread_info, text);
+       }
+
+       if (internal->owned_mutexes) {
+               int i;
+
+               g_string_append (text, ", owns : [");
+               for (i = 0; i < internal->owned_mutexes->len; i++)
+                       g_string_append_printf (text, i == 0 ? "%p" : ", %p", g_ptr_array_index (internal->owned_mutexes, i));
+               g_string_append (text, "]");
+       }
+}
+
+gboolean
+mono_thread_internal_is_current (MonoInternalThread *internal)
+{
+       g_assert (internal);
+       return mono_native_thread_id_equals (mono_native_thread_id_get (), MONO_UINT_TO_NATIVE_THREAD_ID (internal->tid));
+}
index 5ffdda1af9403cbd99b089d174ae4c6058a73028..fbf1f6177a8bcb06ce95bf8b5e94b8785144b0f3 100644 (file)
@@ -8,12 +8,12 @@
  */
 
 #include "w32mutex.h"
-#include "w32mutex-utils.h"
 
 #include <pthread.h>
 
 #include "w32handle-namespace.h"
 #include "mono/io-layer/io-layer.h"
+#include "mono/metadata/object-internals.h"
 #include "mono/utils/mono-logger-internals.h"
 #include "mono/utils/mono-threads.h"
 #include "mono/utils/w32handle.h"
@@ -29,6 +29,35 @@ struct MonoW32HandleNamedMutex {
        MonoW32HandleNamespace sharedns;
 };
 
+static void
+thread_own_mutex (MonoInternalThread *internal, gpointer handle)
+{
+       mono_w32handle_ref (handle);
+
+       /* if we are not on the current thread, there is a
+        * race condition when allocating internal->owned_mutexes */
+       g_assert (mono_thread_internal_is_current (internal));
+
+       if (!internal->owned_mutexes)
+               internal->owned_mutexes = g_ptr_array_new ();
+
+       g_ptr_array_add (internal->owned_mutexes, handle);
+}
+
+static void
+thread_disown_mutex (MonoInternalThread *internal, gpointer handle)
+{
+       gboolean removed;
+
+       g_assert (mono_thread_internal_is_current (internal));
+
+       g_assert (internal->owned_mutexes);
+       removed = g_ptr_array_remove (internal->owned_mutexes, handle);
+       g_assert (removed);
+
+       mono_w32handle_unref (handle);
+}
+
 static gboolean
 mutex_handle_own (gpointer handle, MonoW32HandleType type, guint32 *statuscode)
 {
@@ -41,15 +70,20 @@ mutex_handle_own (gpointer handle, MonoW32HandleType type, guint32 *statuscode)
                return FALSE;
        }
 
-       mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: owning %s handle %p, tid %p, recursion %u",
-               __func__, mono_w32handle_ops_typename (type), handle, (gpointer) mutex_handle->tid, mutex_handle->recursion);
+       mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: owning %s handle %p, before: [tid: %p, recursion: %d], after: [tid: %p, recursion: %d], abandoned: %s",
+               __func__, mono_w32handle_ops_typename (type), handle, (gpointer) mutex_handle->tid, mutex_handle->recursion, (gpointer) pthread_self (), mutex_handle->recursion + 1, mutex_handle->abandoned ? "true" : "false");
+
+       if (mutex_handle->recursion != 0) {
+               g_assert (pthread_equal (pthread_self (), mutex_handle->tid));
+               mutex_handle->recursion++;
+       } else {
+               mutex_handle->tid = pthread_self ();
+               mutex_handle->recursion = 1;
 
-       mono_thread_info_own_mutex (mono_thread_info_current (), handle);
+               thread_own_mutex (mono_thread_internal_current (), handle);
+       }
 
-       mutex_handle->tid = pthread_self ();
-       mutex_handle->recursion++;
        if (mutex_handle->abandoned) {
-               mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: mutex handle %p was abandoned", __func__, handle);
                mutex_handle->abandoned = FALSE;
                *statuscode = WAIT_ABANDONED_0;
        }
@@ -77,8 +111,8 @@ mutex_handle_is_owned (gpointer handle, MonoW32HandleType type)
                        __func__, mono_w32handle_ops_typename (type), handle, (gpointer) pthread_self ());
                return TRUE;
        } else {
-               mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: %s handle %p not owned by %p, but locked %d times by %p",
-                       __func__, mono_w32handle_ops_typename (type), handle, (gpointer) pthread_self (), mutex_handle->recursion, (gpointer) mutex_handle->tid);
+               mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: %s handle %p not owned by %p, tid: %p recursion: %d",
+                       __func__, mono_w32handle_ops_typename (type), handle, (gpointer) pthread_self (), (gpointer) mutex_handle->tid, mutex_handle->recursion);
                return FALSE;
        }
 }
@@ -363,8 +397,8 @@ ves_icall_System_Threading_Mutex_ReleaseMutex_internal (gpointer handle)
                return FALSE;
        }
 
-       mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: releasing %s handle %p",
-               __func__, mono_w32handle_ops_typename (type), handle);
+       mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: releasing %s handle %p, tid: %p recursion: %d",
+               __func__, mono_w32handle_ops_typename (type), handle, (gpointer) mutex_handle->tid, mutex_handle->recursion);
 
        thr_ret = mono_w32handle_lock_handle (handle);
        g_assert (thr_ret == 0);
@@ -378,7 +412,7 @@ ves_icall_System_Threading_Mutex_ReleaseMutex_internal (gpointer handle)
                ret = FALSE;
 
                mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: we don't own %s handle %p (owned by %ld, me %ld)",
-                       __func__, mono_w32handle_ops_typename (type), handle, mutex_handle->tid, tid);
+                           __func__, mono_w32handle_ops_typename (type), handle, (long)mutex_handle->tid, (long)tid);
        } else {
                ret = TRUE;
 
@@ -386,10 +420,10 @@ ves_icall_System_Threading_Mutex_ReleaseMutex_internal (gpointer handle)
                mutex_handle->recursion--;
 
                if (mutex_handle->recursion == 0) {
-                       mono_thread_info_disown_mutex (mono_thread_info_current (), handle);
+                       thread_disown_mutex (mono_thread_internal_current (), handle);
 
-                       mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unlocking %s handle %p",
-                               __func__, mono_w32handle_ops_typename (type), handle);
+                       mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unlocking %s handle %p, tid: %p recusion : %d",
+                               __func__, mono_w32handle_ops_typename (type), handle, (gpointer) mutex_handle->tid, mutex_handle->recursion);
 
                        mutex_handle->tid = 0;
                        mono_w32handle_set_signal_state (handle, TRUE, FALSE);
@@ -441,45 +475,69 @@ cleanup:
 }
 
 void
-mono_w32mutex_abandon (gpointer handle, MonoNativeThreadId tid)
+mono_w32mutex_abandon (void)
 {
-       MonoW32HandleType type;
-       MonoW32HandleMutex *mutex_handle;
-       int thr_ret;
+       MonoInternalThread *internal;
 
-       switch (type = mono_w32handle_get_type (handle)) {
-       case MONO_W32HANDLE_MUTEX:
-       case MONO_W32HANDLE_NAMEDMUTEX:
-               break;
-       default:
-               g_assert_not_reached ();
-       }
+       g_assert (mono_thread_internal_current_is_attached ());
 
-       if (!mono_w32handle_lookup (handle, type, (gpointer *)&mutex_handle)) {
-               g_warning ("%s: error looking up %s handle %p",
-                       __func__, mono_w32handle_ops_typename (type), handle);
+       internal = mono_thread_internal_current ();
+       g_assert (internal);
+
+       if (!internal->owned_mutexes)
                return;
-       }
 
-       mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: abandon %s handle %p",
-               __func__, mono_w32handle_ops_typename (type), handle);
+       while (internal->owned_mutexes->len) {
+               MonoW32HandleType type;
+               MonoW32HandleMutex *mutex_handle;
+               MonoNativeThreadId tid;
+               gpointer handle;
+               int thr_ret;
+
+               handle = g_ptr_array_index (internal->owned_mutexes, 0);
+
+               switch (type = mono_w32handle_get_type (handle)) {
+               case MONO_W32HANDLE_MUTEX:
+               case MONO_W32HANDLE_NAMEDMUTEX:
+                       break;
+               default:
+                       g_assert_not_reached ();
+               }
 
-       thr_ret = mono_w32handle_lock_handle (handle);
-       g_assert (thr_ret == 0);
+               if (!mono_w32handle_lookup (handle, type, (gpointer *)&mutex_handle)) {
+                       g_error ("%s: error looking up %s handle %p",
+                               __func__, mono_w32handle_ops_typename (type), handle);
+               }
+
+               mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: abandoning %s handle %p",
+                       __func__, mono_w32handle_ops_typename (type), handle);
+
+               tid = MONO_UINT_TO_NATIVE_THREAD_ID (internal->tid);
+
+               if (!pthread_equal (mutex_handle->tid, tid))
+                       g_error ("%s: trying to release mutex %p acquired by thread %p from thread %p",
+                               __func__, handle, (gpointer) mutex_handle->tid, (gpointer) tid);
+
+               thr_ret = mono_w32handle_lock_handle (handle);
+               g_assert (thr_ret == 0);
 
-       if (pthread_equal (mutex_handle->tid, tid)) {
                mutex_handle->recursion = 0;
                mutex_handle->tid = 0;
                mutex_handle->abandoned = TRUE;
 
                mono_w32handle_set_signal_state (handle, TRUE, FALSE);
 
+               thread_disown_mutex (internal, handle);
+
                mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: abandoned %s handle %p",
                        __func__, mono_w32handle_ops_typename (type), handle);
+
+               thr_ret = mono_w32handle_unlock_handle (handle);
+               g_assert (thr_ret == 0);
        }
 
-       thr_ret = mono_w32handle_unlock_handle (handle);
-       g_assert (thr_ret == 0);
+       g_ptr_array_free (internal->owned_mutexes, TRUE);
+       internal->owned_mutexes = NULL;
 }
 
 MonoW32HandleNamespace*
diff --git a/mono/metadata/w32mutex-utils.h b/mono/metadata/w32mutex-utils.h
deleted file mode 100644 (file)
index a7bad8c..0000000
+++ /dev/null
@@ -1,20 +0,0 @@
-
-/* This is just a hack so we can call mono_w32mutex_abandon
- * from mono/utils/mono-threads-posix.c, without importing
- * the whole object.h
- * In the best of all world, mutex owning + disowning + abandoning
- * should be done in metadata/ */
-
-#ifndef _MONO_METADATA_W32MUTEX_UTILS_H_
-#define _MONO_METADATA_W32MUTEX_UTILS_H_
-
-#include <config.h>
-#include <glib.h>
-
-#include "mono/utils/mono-threads.h"
-
-void
-mono_w32mutex_abandon (gpointer handle, MonoNativeThreadId tid);
-
-#endif /* _MONO_METADATA_W32MUTEX_UTILS_H_ */
-
index 3c636192c5e390cbd6eaa3dce9892a535dd61f16..917b36f1dd37fe3415cc36c58487ea3b7d3f1d1c 100644 (file)
@@ -25,4 +25,9 @@ typedef struct MonoW32HandleNamedMutex MonoW32HandleNamedMutex;
 MonoW32HandleNamespace*
 mono_w32mutex_get_namespace (MonoW32HandleNamedMutex *mutex);
 
+#ifndef HOST_WIN32
+void
+mono_w32mutex_abandon (void);
+#endif
+
 #endif /* _MONO_METADATA_W32MUTEX_H_ */
index 1f99d8fdff35769bebde8d60c0a742256be27a7d..21e7921127aae4b0c69731225cecaeef9d58e4f8 100644 (file)
@@ -184,7 +184,7 @@ namedsem_create (gint32 initial, gint32 max, const gunichar2 *name)
        gchar *utf8_name;
 
        mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: creating %s handle, initial %d max %d name \"%s\"",
-               __func__, mono_w32handle_ops_typename (MONO_W32HANDLE_NAMEDSEM), initial, max, name);
+                   __func__, mono_w32handle_ops_typename (MONO_W32HANDLE_NAMEDSEM), initial, max, (const char*)name);
 
        /* w32 seems to guarantee that opening named objects can't race each other */
        mono_w32handle_namespace_lock ();
index d7c6b621a5cec0c9adbb964abe371f25c1a27c8b..bd6bdc97e8e3fcc7d749d0464a758e30e559e846 100644 (file)
@@ -17,6 +17,7 @@ mono_w32semaphore_init (void)
 {
 }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT | HAVE_UWP_WINAPI_SUPPORT)
 gpointer
 ves_icall_System_Threading_Semaphore_CreateSemaphore_internal (gint32 initialCount, gint32 maximumCount, MonoString *name, gint32 *error)
 { 
@@ -28,6 +29,7 @@ ves_icall_System_Threading_Semaphore_CreateSemaphore_internal (gint32 initialCou
 
        return sem;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT | HAVE_UWP_WINAPI_SUPPORT) */
 
 MonoBoolean
 ves_icall_System_Threading_Semaphore_ReleaseSemaphore_internal (gpointer handle, gint32 releaseCount, gint32 *prevcount)
index 62e771c78b912a21c14142bccfcf772d1b1fde9e..488b3cd0c4e2b9baad71d2b42eeb3599f74e1bdb 100755 (executable)
@@ -373,6 +373,7 @@ darwin_sources = \
 
 windows_sources = \
        mini-windows.c \
+       mini-windows.h \
        mini-windows-dllmain.c
 
 posix_sources = \
index 3ad4c53b921a65b03ba65022f3af609fc8234614..309e5ed029be1e731da99cbae98df6186eb0d628 100644 (file)
@@ -219,6 +219,7 @@ typedef struct MonoAotCompile {
        gboolean gas_line_numbers;
        /* Whenever to emit an object file directly from llc */
        gboolean llvm_owriter;
+       gboolean llvm_owriter_supported;
        MonoImageWriter *w;
        MonoDwarfWriter *dwarf;
        FILE *fp;
@@ -879,6 +880,7 @@ arch_init (MonoAotCompile *acfg)
 {
        acfg->llc_args = g_string_new ("");
        acfg->as_args = g_string_new ("");
+       acfg->llvm_owriter_supported = TRUE;
 
        /*
         * The prefix LLVM likes to put in front of symbol names on darwin.
@@ -941,6 +943,10 @@ arch_init (MonoAotCompile *acfg)
 #ifdef MONOTOUCH
        acfg->global_symbols = TRUE;
 #endif
+
+#ifdef TARGET_ANDROID
+       acfg->llvm_owriter_supported = FALSE;
+#endif
 }
 
 #ifdef TARGET_ARM64
@@ -3838,13 +3844,14 @@ add_wrappers (MonoAotCompile *acfg)
                csig->params [1] = &mono_defaults.exception_class->byval_arg;
                add_method (acfg, get_runtime_invoke_sig (csig));
 
-               /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
-               csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
+               /* Assembly runtime-invoke (string, Assembly, bool) [DoAssemblyResolve] */
+               csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
                csig->hasthis = 1;
                csig->ret = &(mono_class_load_from_name (
                                                                                        mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
                csig->params [0] = &mono_defaults.string_class->byval_arg;
-               csig->params [1] = &mono_defaults.boolean_class->byval_arg;
+               csig->params [1] = &(mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
+               csig->params [2] = &mono_defaults.boolean_class->byval_arg;
                add_method (acfg, get_runtime_invoke_sig (csig));
 
                /* runtime-invoke used by finalizers */
@@ -8889,13 +8896,13 @@ emit_extra_methods (MonoAotCompile *acfg)
 static void
 generate_aotid (guint8* aotid)
 {
-       gpointer *rand_handle;
+       gpointer rand_handle;
        MonoError error;
 
        mono_rand_open ();
        rand_handle = mono_rand_init (NULL, 0);
 
-       mono_rand_try_get_bytes (rand_handle, aotid, 16, &error);
+       mono_rand_try_get_bytes (&rand_handle, aotid, 16, &error);
        mono_error_assert_ok (&error);
 
        mono_rand_close (rand_handle);
@@ -9807,7 +9814,7 @@ compile_methods (MonoAotCompile *acfg)
                        user_data [1] = acfg;
                        user_data [2] = frag;
                        
-                       handle = mono_threads_create_thread (compile_thread_main, (gpointer) user_data, 0, NULL);
+                       handle = mono_threads_create_thread (compile_thread_main, (gpointer) user_data, NULL, NULL);
                        g_ptr_array_add (threads, handle);
                }
                g_free (methods);
@@ -9963,16 +9970,23 @@ compile_asm (MonoAotCompile *acfg)
                wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
 #else
        // Default (linux)
-       char *args = g_strdup_printf ("%s -shared -o %s %s %s %s", LD_OPTIONS,
-               wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
-               wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
-
-       if (acfg->llvm) {
-               command = g_strdup_printf ("clang++ %s", args);
+       if (acfg->aot_opts.tool_prefix) {
+               /* Cross compiling */
+               command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
+                                                                  wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
+                                                                  wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
        } else {
-               command = g_strdup_printf ("\"%sld\" %s", tool_prefix, args);
+               char *args = g_strdup_printf ("%s -shared -o %s %s %s %s", LD_OPTIONS,
+                                                                         wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
+                                                                         wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
+
+               if (acfg->llvm) {
+                       command = g_strdup_printf ("clang++ %s", args);
+               } else {
+                       command = g_strdup_printf ("\"%sld\" %s", tool_prefix, args);
+               }
+               g_free (args);
        }
-       g_free (args);
 
 #endif
        aot_printf (acfg, "Executing the native linker: %s\n", command);
@@ -10500,19 +10514,6 @@ mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
                        aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outputfile= option.");
                        return 1;
                }
-
-               /*
-                * Emit all LLVM code into a separate assembly/object file and link with it
-                * normally.
-                */
-               if (!acfg->aot_opts.asm_only) {
-                       acfg->llvm_owriter = TRUE;
-               } else if (acfg->aot_opts.llvm_outfile) {
-                       int len = strlen (acfg->aot_opts.llvm_outfile);
-
-                       if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
-                               acfg->llvm_owriter = TRUE;
-               }
        }
 
        if (mono_aot_mode_is_full (&acfg->aot_opts))
@@ -10545,6 +10546,22 @@ mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
 
        arch_init (acfg);
 
+       if (mono_use_llvm || acfg->aot_opts.llvm) {
+
+               /*
+                * Emit all LLVM code into a separate assembly/object file and link with it
+                * normally.
+                */
+               if (!acfg->aot_opts.asm_only && acfg->llvm_owriter_supported) {
+                       acfg->llvm_owriter = TRUE;
+               } else if (acfg->aot_opts.llvm_outfile) {
+                       int len = strlen (acfg->aot_opts.llvm_outfile);
+
+                       if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
+                               acfg->llvm_owriter = TRUE;
+               }
+       }
+
        if (acfg->llvm && acfg->thumb_mixed)
                acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
        if (acfg->aot_opts.llvm_only)
index 9a4d566c754d088e31d81b3679ad2617c3fd6532..0da4ad6168d75584271a6ed781aac682d494c79d 100644 (file)
@@ -4025,32 +4025,6 @@ find_aot_method_in_amodule (MonoAotModule *amodule, MonoMethod *method, guint32
                        break;
                }
 
-               /*
-                * Special case: wrappers of shared generic methods.
-                * This is needed because of the way mini_get_shared_method () works,
-                * we could end up with multiple copies of the same wrapper.
-                */
-               if (m && method->wrapper_type && method->wrapper_type == m->wrapper_type &&
-                       method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
-                       MonoMethod *w1 = mono_marshal_method_from_wrapper (method);
-                       MonoMethod *w2 = mono_marshal_method_from_wrapper (m);
-
-                       if ((w1 == w2) || (w1->is_inflated && ((MonoMethodInflated *)w1)->declaring == w2)) {
-                               index = value;
-                               break;
-                       }
-               }
-               if (m && method->wrapper_type && method->wrapper_type == m->wrapper_type &&
-                       method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
-                       WrapperInfo *info1 = mono_marshal_get_wrapper_info (method);
-                       WrapperInfo *info2 = mono_marshal_get_wrapper_info (m);
-
-                       if (info1 && info2 && info1->subtype == info2->subtype && info1->d.delegate_invoke.method == info2->d.delegate_invoke.method) {
-                               index = value;
-                               break;
-                       }
-               }
-
                /* Methods decoded needlessly */
                if (m) {
                        //printf ("%d %s %s %p\n", n_extra_decodes, mono_method_full_name (method, TRUE), mono_method_full_name (m, TRUE), orig_p);
index 7aa562c591db78c8118002b5f80503112154414c..8ba135ce1321da6d05b39b6e080ac940c4c03162 100644 (file)
@@ -71,6 +71,7 @@
 #include <mono/utils/mono-time.h>
 #include <mono/utils/mono-threads.h>
 #include <mono/utils/networking.h>
+#include <mono/utils/mono-proclib.h>
 #include "debugger-agent.h"
 #include "mini.h"
 #include "seq-points.h"
@@ -271,7 +272,7 @@ typedef struct {
 #define HEADER_LENGTH 11
 
 #define MAJOR_VERSION 2
-#define MINOR_VERSION 43
+#define MINOR_VERSION 44
 
 typedef enum {
        CMD_SET_VM = 1,
@@ -499,6 +500,7 @@ typedef enum {
        CMD_STACK_FRAME_GET_THIS = 2,
        CMD_STACK_FRAME_SET_VALUES = 3,
        CMD_STACK_FRAME_GET_DOMAIN = 4,
+       CMD_STACK_FRAME_SET_THIS = 5,
 } CmdStackFrame;
 
 typedef enum {
@@ -931,7 +933,7 @@ mono_debugger_agent_parse_options (char *options)
                /* Waiting for deferred attachment */
                agent_config.defer = TRUE;
                if (agent_config.address == NULL) {
-                       agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (getpid () % 1000));
+                       agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (mono_process_current_pid () % 1000));
                }
        }
 
@@ -1627,7 +1629,7 @@ stop_debugger_thread (void)
 static void
 start_debugger_thread (void)
 {
-       debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, 0, NULL);
+       debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, NULL, NULL);
        g_assert (debugger_thread_handle);
 }
 
@@ -9269,6 +9271,25 @@ frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
                        buffer_add_domainid (buf, frame->domain);
                break;
        }
+       case CMD_STACK_FRAME_SET_THIS: {
+               guint8 *val_buf;
+               MonoType *t;
+               MonoDebugVarInfo *var;
+
+               t = &frame->actual_method->klass->byval_arg;
+               /* Checked by the sender */
+               g_assert (MONO_TYPE_ISSTRUCT (t));
+               var = jit->this_var;
+               g_assert (var);
+
+               val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
+               err = decode_value (t, frame->domain, val_buf, p, &p, end);
+               if (err != ERR_NONE)
+                       return err;
+
+               set_var (&frame->actual_method->klass->this_arg, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
+               break;
+       }
        default:
                return ERR_NOT_IMPLEMENTED;
        }
@@ -9688,6 +9709,7 @@ static const char* stack_frame_cmds_str[] = {
        "GET_THIS",
        "SET_VALUES",
        "GET_DOMAIN",
+       "SET_THIS"
 };
 
 static const char* array_cmds_str[] = {
index a6d2bd117b1f75181421b9e0b65ddb23265e5fd7..e31628dc795b53151c8028fd03e04d7386e705c8 100644 (file)
@@ -1434,6 +1434,10 @@ mono_jit_parse_options (int argc, char * argv[])
                        
                        if (!mono_debugger_insert_breakpoint (argv [++i], FALSE))
                                fprintf (stderr, "Error: invalid method name '%s'\n", argv [i]);
+               } else if (strncmp (argv[i], "--gc-params=", 12) == 0) {
+                       mono_gc_params_set (argv[i] + 12);
+               } else if (strncmp (argv[i], "--gc-debug=", 11) == 0) {
+                       mono_gc_debug_set (argv[i] + 11);
                } else if (strcmp (argv [i], "--llvm") == 0) {
 #ifndef MONO_ARCH_LLVM_SUPPORTED
                        fprintf (stderr, "Mono Warning: --llvm not supported on this platform.\n");
@@ -1500,6 +1504,7 @@ switch_gc (char* argv[], const char* target_gc)
 
 #ifdef HAVE_EXECVP
        execvp (path->str, argv);
+       fprintf (stderr, "Error: Failed to switch to %s gc. mono-%s is not installed.\n", target_gc, target_gc);
 #else
        fprintf (stderr, "Error: --gc=<NAME> option not supported on this platform.\n");
 #endif
@@ -1678,6 +1683,10 @@ mono_main (int argc, char* argv[])
                        switch_gc (argv, "sgen");
                } else if (strcmp (argv [i], "--gc=boehm") == 0) {
                        switch_gc (argv, "boehm");
+               } else if (strncmp (argv[i], "--gc-params=", 12) == 0) {
+                       mono_gc_params_set (argv[i] + 12);
+               } else if (strncmp (argv[i], "--gc-debug=", 11) == 0) {
+                       mono_gc_debug_set (argv[i] + 11);
                }
 #ifdef TARGET_OSX
                else if (strcmp (argv [i], "--arch=32") == 0) {
@@ -2112,7 +2121,7 @@ mono_main (int argc, char* argv[])
                        exit (1);
                }
 
-#ifdef HOST_WIN32
+#if defined(HOST_WIN32) && G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
                /* Detach console when executing IMAGE_SUBSYSTEM_WINDOWS_GUI on win32 */
                if (!enable_debugging && !mono_compile_aot && ((MonoCLIImageInfo*)(mono_assembly_get_image (assembly)->image_info))->cli_header.nt.pe_subsys_required == IMAGE_SUBSYSTEM_WINDOWS_GUI)
                        FreeConsole ();
index 919682acca6a9c5fb1d2d38456f16fabb01a9227..dbef0887519b5e12e85ba3320e952eef4a086c15 100644 (file)
@@ -152,6 +152,7 @@ void win32_seh_set_handler(int type, MonoW32ExceptionHandler handler)
 
 #endif /* TARGET_WIN32 */
 
+#ifndef DISABLE_JIT
 /*
  * mono_arch_get_restore_context:
  *
@@ -285,6 +286,7 @@ mono_arch_get_call_filter (MonoTrampInfo **info, gboolean aot)
 
        return start;
 }
+#endif /* !DISABLE_JIT */
 
 /* 
  * The first few arguments are dummy, to force the other arguments to be passed on
@@ -350,6 +352,7 @@ mono_amd64_resume_unwind (guint64 dummy1, guint64 dummy2, guint64 dummy3, guint6
        mono_resume_unwind (&ctx);
 }
 
+#ifndef DISABLE_JIT
 /*
  * get_throw_trampoline:
  *
@@ -496,6 +499,7 @@ mono_arch_get_throw_corlib_exception (MonoTrampInfo **info, gboolean aot)
 {
        return get_throw_trampoline (info, FALSE, TRUE, FALSE, FALSE, "throw_corlib_exception", aot);
 }
+#endif /* !DISABLE_JIT */
 
 /*
  * mono_arch_unwind_frame:
@@ -833,6 +837,7 @@ mono_amd64_get_original_ip (void)
        return lmf->rip;
 }
 
+#ifndef DISABLE_JIT
 GSList*
 mono_amd64_get_exception_trampolines (gboolean aot)
 {
@@ -851,6 +856,7 @@ mono_amd64_get_exception_trampolines (gboolean aot)
 
        return tramps;
 }
+#endif /* !DISABLE_JIT */
 
 void
 mono_arch_exceptions_init (void)
@@ -878,7 +884,7 @@ mono_arch_exceptions_init (void)
        }
 }
 
-#ifdef TARGET_WIN32
+#if defined(TARGET_WIN32) && !defined(DISABLE_JIT)
 
 /*
  * The mono_arch_unwindinfo* methods are used to build and add
@@ -1118,9 +1124,9 @@ mono_arch_unwindinfo_install_unwind_info (gpointer* monoui, gpointer code, guint
        RtlInstallFunctionTableCallback (((DWORD64)code) | 0x3, (DWORD64)code, code_size, MONO_GET_RUNTIME_FUNCTION_CALLBACK, code, NULL);
 }
 
-#endif
+#endif /* defined(TARGET_WIN32) !defined(DISABLE_JIT) */
 
-#if MONO_SUPPORT_TASKLETS
+#if MONO_SUPPORT_TASKLETS && !defined(DISABLE_JIT)
 MonoContinuationRestore
 mono_tasklets_arch_restore (void)
 {
@@ -1172,7 +1178,7 @@ mono_tasklets_arch_restore (void)
        saved = start;
        return (MonoContinuationRestore)saved;
 }
-#endif
+#endif /* MONO_SUPPORT_TASKLETS && !defined(DISABLE_JIT) */
 
 /*
  * mono_arch_setup_resume_sighandler_ctx:
@@ -1190,3 +1196,56 @@ mono_arch_setup_resume_sighandler_ctx (MonoContext *ctx, gpointer func)
                MONO_CONTEXT_SET_SP (ctx, (guint64)MONO_CONTEXT_GET_SP (ctx) - 8);
        MONO_CONTEXT_SET_IP (ctx, func);
 }
+
+#ifdef DISABLE_JIT
+gpointer
+mono_arch_get_restore_context (MonoTrampInfo **info, gboolean aot)
+{
+       g_assert_not_reached ();
+       return NULL;
+}
+
+gpointer
+mono_arch_get_call_filter (MonoTrampInfo **info, gboolean aot)
+{
+       g_assert_not_reached ();
+       return NULL;
+}
+
+gpointer
+mono_arch_get_throw_exception (MonoTrampInfo **info, gboolean aot)
+{
+       g_assert_not_reached ();
+       return NULL;
+}
+
+gpointer
+mono_arch_get_rethrow_exception (MonoTrampInfo **info, gboolean aot)
+{
+       g_assert_not_reached ();
+       return NULL;
+}
+
+gpointer
+mono_arch_get_throw_corlib_exception (MonoTrampInfo **info, gboolean aot)
+{
+       g_assert_not_reached ();
+       return NULL;
+}
+
+GSList*
+mono_amd64_get_exception_trampolines (gboolean aot)
+{
+       g_assert_not_reached ();
+       return NULL;
+}
+#endif /* DISABLE_JIT */
+
+#if !MONO_SUPPORT_TASKLETS || defined(DISABLE_JIT)
+MonoContinuationRestore
+mono_tasklets_arch_restore (void)
+{
+       g_assert_not_reached ();
+       return NULL;
+}
+#endif /* !MONO_SUPPORT_TASKLETS || defined(DISABLE_JIT) */
index 80638b5048e6edf80854c7509ee3b7d18292cd5c..018619449191a8cf24899b7d1cba6f55519a85d0 100644 (file)
@@ -1272,7 +1272,6 @@ class Tests
                c.throw_catch_t ();
                return 0;
        }
-
 }
 
 #if !__MOBILE__
index 88f8c2ebb22b780a3c461daf2d8b62e6370f3e68..65151b07024e8d1a2199d9b76119cd07be48c527 100644 (file)
@@ -1907,6 +1907,40 @@ public class Tests
                bool success = zz == 0xAAAAAAAAAAAAAAAA;
                return success ? 20 : 1;
        }
+
+       void gsharedvt_try_at_offset_0<T> (ref T disposable)
+               where T : class, IDisposable {
+                       try {
+                               disposable.Dispose ();
+                       } finally {
+                               disposable = null;
+                       }
+               }
+
+       [MethodImplAttribute (MethodImplOptions.NoInlining)]
+       static DateTimeOffset gsharedvt_vphi_inner<T> (T t) {
+               return DateTimeOffset.MinValue;
+       }
+
+       static DateTimeOffset gsharedvt_vphi<T> (T t) {
+               int[] arr = new int [10];
+
+               try {
+                       DateTimeOffset v;
+                       if (arr [0] == 0)
+                               v = gsharedvt_vphi_inner (t);
+                       else
+                               v = gsharedvt_vphi_inner (t);
+                       return v;
+               } catch {
+                       return DateTimeOffset.MinValue;
+               }
+       }
+
+       static int test_0_gsharedvt_vphi_volatile () {
+               gsharedvt_vphi (0);
+               return 0;
+       }
 }
 
 // #13191
index abfa1ffe73b3cf93737bc63885693e13034587f3..ba9d6531367042081ba87410847ee375d5302d00 100644 (file)
@@ -100,11 +100,48 @@ alloc_dreg (MonoCompile *cfg, MonoStackType stack_type)
        }
 }
 
+/*
+ * Macros used to generate intermediate representation macros
+ *
+ * The macros use a `MonoConfig` object as its context, and among other
+ * things it is used to associate instructions with the memory pool with 
+ * it.
+ * 
+ * The macros come in three variations with slightly different
+ * features, the patter is: NEW_OP, EMIT_NEW_OP, MONO_EMIT_NEW_OP,
+ * the differences are as follows:
+ *
+ * `NEW_OP`: these are the basic macros to setup an instruction that is
+ * passed as an argument.
+ *
+ * `EMIT_NEW_OP`: these macros in addition to creating the instruction
+ * add the instruction to the current basic block in the `MonoConfig`
+ * object passed.   Usually these are used when further customization of
+ * the `inst` parameter is desired before the instruction is added to the
+ * MonoConfig current basic block.
+ *
+ * `MONO_EMIT_NEW_OP`: These variations of the instructions are used when
+ * you are merely interested in emitting the instruction into the `MonoConfig`
+ * parameter. 
+ */
 #undef MONO_INST_NEW
 /* 
  * FIXME: zeroing out some fields is not needed with the new IR, but the old 
  * JIT code still uses the left and right fields, so it has to stay.
  */
+
+/*
+ * MONO_INST_NEW: create a new MonoInst instance that is allocated on the MonoConfig pool.
+ *
+ * @cfg: the MonoConfig object that will be used as the context for the 
+ * instruction.
+ * @dest: this is the place where the instance of the `MonoInst` is stored.
+ * @op: the value that should be stored in the MonoInst.opcode field
+ *
+ * This initializes an empty MonoInst that has been nulled out, it is allocated
+ * from the memory pool associated with the MonoConfig, but it is not linked anywhere.
+ * the cil_code is set to the cfg->ip address. 
+ */
 #define MONO_INST_NEW(cfg,dest,op) do {        \
                (dest) = (MonoInst *)mono_mempool_alloc ((cfg)->mempool, sizeof (MonoInst));    \
                (dest)->inst_c0 = (dest)->inst_c1 = 0; \
index 04373359fb46ead9bc1ea8d96249d33ee4c15948..e19b91c5fcab116663a5971c7d925362daaeaadf 100644 (file)
@@ -171,6 +171,8 @@ mono_strength_reduction_division (MonoCompile *cfg, MonoInst *ins)
                                ins->inst_imm = power2;
                                break;
                        }
+                       if (cfg->backend->disable_div_with_mul)
+                               break;
                        allocated_vregs = TRUE;
                        /*
                         * Replacement of unsigned division with multiplication,
@@ -243,6 +245,8 @@ mono_strength_reduction_division (MonoCompile *cfg, MonoInst *ins)
                                break;
                        }
 
+                       if (cfg->backend->disable_div_with_mul)
+                               break;
                        /*
                         * Replacement of signed division with multiplication,
                         * shifts and additions Hacker's Delight, chapter 10-6.
index 8d2f5bd17121d78ef98c4fba3c8e1f427d4b86da..8d73080631e424bf475d8bab179cde569b069fa9 100644 (file)
@@ -1,8 +1,24 @@
+/*
+ * main.c: The main entry point for the mono executable
+ *
+ * The main entry point does a few things:
+ * 
+ *   * It probes whether the executable has a bundle appended
+ *     at the end, and if so, registers the various bundled
+ *     resources with Mono and executes the contained bundle
+ *
+ *   * Parses the MONO_ENV_OPTIONS variable to treat the
+ *     contents of the variable as command line arguments for
+ *     the mono runtime
+ *
+ *   * Launches Mono, by calling mono_main.
+ */
 #include <config.h>
 #include <fcntl.h>
 #include <mono/metadata/assembly.h>
 #include <mono/metadata/mono-config.h>
 #include <mono/utils/mono-mmap.h>
+#include <mono/utils/mono-dl.h>
 #include "mini.h"
 
 #ifdef HAVE_UNISTD_H
@@ -29,6 +45,51 @@ mono_main_with_options (int argc, char *argv [])
        return mono_main (argc, argv);
 }
 
+/*
+ * The Mono executable can initialize itself from a payload attached
+ * at the end of the main program.   The payload contains the
+ * main assembly, one or more managed assemblies, configuration
+ * files and other assets that are used instead of launching a
+ * program from the command line.
+ *
+ * The startup sequence probes for a magical signature at the end of
+ * the executable, if the 16 characters "xmonkeysloveplay" are found,
+ * the code expects the 64-bits just before it to contain an offset
+ * within the executable with a directory of assets.
+ *
+ * All pointers in the file format are encoded as little-endian values
+ *
+ * The format of the file is thus:
+ *
+ * Location        Content
+ * --------        -------
+ * lenght-16       Optional "xmonkeysloveplay", indicating that a
+ *                 bundled payload is contained in the executable.
+ * length-24       pointer to the directory in the file, address DIR
+ *
+ * DIR             32-bit value with the number of entries in the directory
+ * DIR+4           First directory entry.
+ *
+ * Each directory entry is made up of:
+ * 4-bytes         uint32_t containing the size of a string (STR)
+ * STRING          UTF8 encoded and \0 terminated string
+ * 8-bytes         uint64_t offset in the file with the payload associated with STRING
+ * 4-bytes         uint32_t size of the asset
+ *
+ * The following are the known directory entries, without the quotes:
+ * "assembly:NAME"  An assembly with the name NAME, assembly is in the payload
+ * "config:NAME"    A configuration file (usually file.dll.config) in the payload that is
+ *                  loaded as the config file for an assembly
+ * "systemconfig:"  Treats as a Mono system configuration, payload contains the config file.
+ * "options:"       The payload contains command line options to initialize Mono, as if you 
+                    had set them on MONO_ENV_OPTIONS
+ * "config_dir:DIR" Configures the MONO_PATH to point to point to DIR
+ * "machineconfig:" The payload contains the machine.config file to use at runtime
+ * "env:"           Sets the environment variable to the value encoded in the payload
+ *                  payload contains: 1-byte lenght for the \0 terminated variable,
+ *                  followed by the value.
+ * "library:NAME"   Bundled dynamic library NAME, payload contains the dynamic library
+ */
 #define STREAM_INT(x) GUINT32_TO_LE((*(uint32_t*)x))
 #define STREAM_LONG(x) GUINT64_TO_LE((*(uint64_t*)x))
 
@@ -64,6 +125,64 @@ load_from_region (int fd, uint64_t offset, uint64_t size)
        return buffer;
 }
 
+/* Did we initialize the temporary directory for dynamic libraries */
+static int bundle_save_library_initialized;
+
+/* List of bundled libraries we unpacked */
+static GSList *bundle_library_paths;
+
+/* Directory where we unpacked dynamic libraries */
+static char *bundled_dylibrary_directory;
+
+static void
+delete_bundled_libraries ()
+{
+       GSList *list;
+
+       for (list = bundle_library_paths; list != NULL; list = list->next){
+               unlink (list->data);
+       }
+       rmdir (bundled_dylibrary_directory);
+}
+
+static void
+bundle_save_library_initialize ()
+{
+       bundle_save_library_initialized = 1;
+       char *path = g_build_filename (g_get_tmp_dir (), "mono-bundle-XXXXXX", NULL);
+       bundled_dylibrary_directory = g_mkdtemp (path);
+       g_free (path);
+       if (bundled_dylibrary_directory == NULL)
+               return;
+       atexit (delete_bundled_libraries);
+}
+
+static void
+save_library (int fd, uint64_t offset, uint64_t size, const char *destfname)
+{
+       MonoDl *lib;
+       char *file, *buffer, *err, *internal_path;
+       if (!bundle_save_library_initialized)
+               bundle_save_library_initialize ();
+       
+       file = g_build_filename (bundled_dylibrary_directory, destfname, NULL);
+       buffer = load_from_region (fd, offset, size);
+       g_file_set_contents (file, buffer, size, NULL);
+
+       lib = mono_dl_open (file, MONO_DL_LAZY, &err);
+       if (lib == NULL){
+               fprintf (stderr, "Error loading shared library: %s %s\n", file, err);
+               exit (1);
+       }
+       // Register the name with "." as this is how it will be found when embedded
+       internal_path = g_build_filename (".", destfname, NULL);
+       mono_loader_register_module (internal_path, lib);
+       g_free (internal_path);
+       bundle_library_paths = g_slist_append (bundle_library_paths, file);
+       
+       g_free (buffer);
+}
+
 static gboolean
 probe_embedded (const char *program, int *ref_argc, char **ref_argv [])
 {
@@ -150,13 +269,15 @@ probe_embedded (const char *program, int *ref_argc, char **ref_argv [])
                        uint8_t count = *data++;
                        char *value = data + count + 1;
                        g_setenv (data, value, FALSE);
+               } else if (strncmp (kind, "library:", strlen ("library:")) == 0){
+                       save_library (fd, offset, item_size, kind + strlen ("library:"));
                } else {
                        fprintf (stderr, "Unknown stream on embedded package: %s\n", kind);
                        exit (1);
                }
        }
        g_array_append_val (assemblies, last);
-       
+
        mono_register_bundled_assemblies ((const MonoBundledAssembly **) assemblies->data);
        new_argv = g_new (char *, (*ref_argc)+1);
        for (j = 0; j < *ref_argc; j++)
index 1b55991ff0290da9607e57336770694cab92c4db..0929e7dc70050bcb549e1fd4fd4cb898d2fdbca2 100644 (file)
@@ -6125,8 +6125,13 @@ mini_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSign
                        return NULL;
        } else if (cmethod->klass == mono_defaults.monitor_class) {
                gboolean is_enter = FALSE;
+               gboolean is_v4 = FALSE;
 
-               if (!strcmp (cmethod->name, "Enter") && mono_method_signature (cmethod)->param_count == 1)
+               if (!strcmp (cmethod->name, "Enter") && fsig->param_count == 2 && fsig->params [1]->byref) {
+                       is_enter = TRUE;
+                       is_v4 = TRUE;
+               }
+               if (!strcmp (cmethod->name, "Enter") && fsig->param_count == 1)
                        is_enter = TRUE;
 
                if (is_enter) {
@@ -6138,10 +6143,10 @@ mini_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSign
 
                        NEW_BBLOCK (cfg, end_bb);
 
-                       ins = mono_emit_jit_icall (cfg, (gpointer)mono_monitor_enter_fast, args);
+                       ins = mono_emit_jit_icall (cfg, is_v4 ? (gpointer)mono_monitor_enter_v4_fast : (gpointer)mono_monitor_enter_fast, args);
                        MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ICOMPARE_IMM, -1, ins->dreg, 0);
                        MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBNE_UN, end_bb);
-                       ins = mono_emit_jit_icall (cfg, (gpointer)mono_monitor_enter, args);
+                       ins = mono_emit_jit_icall (cfg, is_v4 ? (gpointer)mono_monitor_enter_v4 : (gpointer)mono_monitor_enter, args);
                        MONO_START_BB (cfg, end_bb);
                        return ins;
                }
@@ -8474,7 +8479,8 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
 
        /* we use a separate basic block for the initialization code */
        NEW_BBLOCK (cfg, init_localsbb);
-       cfg->bb_init = init_localsbb;
+       if (cfg->method == method)
+               cfg->bb_init = init_localsbb;
        init_localsbb->real_offset = cfg->real_offset;
        start_bblock->next_bb = init_localsbb;
        init_localsbb->next_bb = cfg->cbb;
@@ -13680,7 +13686,10 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
        if (cfg->method == method) {
                MonoBasicBlock *bb;
                for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
-                       bb->region = mono_find_block_region (cfg, bb->real_offset);
+                       if (bb == cfg->bb_init)
+                               bb->region = -1;
+                       else
+                               bb->region = mono_find_block_region (cfg, bb->real_offset);
                        if (cfg->spvars)
                                mono_create_spvar_for_region (cfg, bb->region);
                        if (cfg->verbose_level > 2)
index bc1b5021a01789137c35ed9956bea63247af10ba..e19467f8945dc90d4f2b27a41abd00b30e430501 100644 (file)
@@ -934,7 +934,15 @@ arm_patch_full (MonoCompile *cfg, MonoDomain *domain, guint8 *code, guint8 *targ
 {
        switch (relocation) {
        case MONO_R_ARM64_B:
-               arm_b (code, target);
+               if (arm_is_bl_disp (code, target)) {
+                       arm_b (code, target);
+               } else {
+                       gpointer thunk;
+
+                       thunk = create_thunk (cfg, domain, code, target);
+                       g_assert (arm_is_bl_disp (code, thunk));
+                       arm_b (code, thunk);
+               }
                break;
        case MONO_R_ARM64_BCC: {
                int cond;
@@ -966,7 +974,7 @@ arm_patch_full (MonoCompile *cfg, MonoDomain *domain, guint8 *code, guint8 *targ
 
                        thunk = create_thunk (cfg, domain, code, target);
                        g_assert (arm_is_bl_disp (code, thunk));
-                       arm_bl (code, thunk);                   
+                       arm_bl (code, thunk);
                }
                break;
        default:
index 265be946e51a8309da60e9c35721695acc315a7e..903739445c1a86806640ce725f856958421865f6 100644 (file)
@@ -1290,7 +1290,10 @@ build_native_trace (MonoError *error)
 #if defined (HAVE_BACKTRACE_SYMBOLS) && defined (TARGET_ARM)
        MonoArray *res;
        void *native_trace [MAX_UNMANAGED_BACKTRACE];
-       int size = backtrace (native_trace, MAX_UNMANAGED_BACKTRACE);
+       int size = -1;
+       MONO_ENTER_GC_SAFE;
+       size = backtrace (native_trace, MAX_UNMANAGED_BACKTRACE);
+       MONO_EXIT_GC_SAFE;
        int i;
 
        if (!size)
@@ -2504,7 +2507,7 @@ mono_print_thread_dump_internal (void *sigctx, MonoContext *start_ctx)
                g_string_append (text, "\n\"<unnamed thread>\"");
 
        g_string_append_printf (text, " tid=0x%p this=0x%p ", (gpointer)(gsize)thread->tid, thread);
-       mono_thread_info_describe ((MonoThreadInfo*) thread->thread_info, text);
+       mono_thread_internal_describe (thread, text);
        g_string_append (text, "\n");
 
 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
index aca368c9dba9e1ad8ef382fa8e7532a93981ffe5..736493198ed3b9556beb77bd842805959f7e862e 100644 (file)
@@ -3436,6 +3436,24 @@ mini_get_shared_method_full (MonoMethod *method, gboolean all_vt, gboolean is_gs
        MonoGenericContext *context = mono_method_get_context (method);
        MonoGenericInst *inst;
 
+       /*
+        * Instead of creating a shared version of the wrapper, create a shared version of the original
+        * method and construct a wrapper for it. Otherwise, we could end up with two copies of the
+        * same wrapper, breaking AOT which assumes wrappers are unique.
+        * FIXME: Add other cases.
+        */
+       if (method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
+               MonoMethod *wrapper = mono_marshal_method_from_wrapper (method);
+
+               return mono_marshal_get_synchronized_wrapper (mini_get_shared_method_full (wrapper, all_vt, is_gsharedvt));
+       }
+       if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
+               WrapperInfo *info = mono_marshal_get_wrapper_info (method);
+
+               if (info->subtype == WRAPPER_SUBTYPE_NONE)
+                       return mono_marshal_get_delegate_invoke (mini_get_shared_method_full (info->d.delegate_invoke.method, all_vt, is_gsharedvt), NULL);
+       }
+
        if (method->is_generic || (method->klass->generic_container && !method->is_inflated)) {
                declaring_method = method;
        } else {
index 2ae3051b52074b80362733162ba2fcfa9fb5dc37..117260ff2c69be08a4c753aab164357cb23af4d1 100644 (file)
@@ -148,6 +148,7 @@ typedef struct {
        LLVMValueRef rgctx_arg;
        LLVMValueRef this_arg;
        LLVMTypeRef *vreg_types;
+       gboolean *is_vphi;
        LLVMTypeRef method_type;
        LLVMBasicBlockRef init_bb, inited_bb;
        gboolean *is_dead;
@@ -170,6 +171,7 @@ typedef struct {
        GPtrArray *bblock_list;
        char *method_name;
        GHashTable *jit_callees;
+       LLVMValueRef long_bb_break_var;
 } EmitContext;
 
 typedef struct {
@@ -1739,6 +1741,8 @@ get_handler_clause (MonoCompile *cfg, MonoBasicBlock *bb)
 static MonoExceptionClause *
 get_most_deep_clause (MonoCompile *cfg, EmitContext *ctx, MonoBasicBlock *bb)
 {
+       if (bb == cfg->bb_init)
+               return NULL;
        // Since they're sorted by nesting we just need
        // the first one that the bb is a member of
        for (int i = 0; i < cfg->header->num_clauses; i++) {
@@ -4150,14 +4154,36 @@ process_bb (EmitContext *ctx, MonoBasicBlock *bb)
                if (nins > 1000) {
                        /*
                         * Some steps in llc are non-linear in the size of basic blocks, see #5714.
-                        * Start a new bblock. If the llvm optimization passes merge these, we
-                        * can work around that by doing a volatile load + cond branch from
-                        * localloc-ed memory.
+                        * Start a new bblock.
+                        * Prevent the bblocks to be merged by doing a volatile load + cond branch
+                        * from localloc-ed memory.
                         */
                        if (!cfg->llvm_only)
-                               set_failure (ctx, "basic block too long");
+                               ;//set_failure (ctx, "basic block too long");
+
+                       if (!ctx->long_bb_break_var) {
+                               ctx->long_bb_break_var = build_alloca_llvm_type_name (ctx, LLVMInt32Type (), 0, "long_bb_break");
+                               mono_llvm_build_store (ctx->alloca_builder, LLVMConstInt (LLVMInt32Type (), 0, FALSE), ctx->long_bb_break_var, TRUE, LLVM_BARRIER_NONE);
+                       }
+
                        cbb = gen_bb (ctx, "CONT_LONG_BB");
-                       LLVMBuildBr (ctx->builder, cbb);
+                       LLVMBasicBlockRef dummy_bb = gen_bb (ctx, "CONT_LONG_BB_DUMMY");
+
+                       LLVMValueRef load = mono_llvm_build_load (builder, ctx->long_bb_break_var, "", TRUE);
+                       /*
+                        * The long_bb_break_var is initialized to 0 in the prolog, so this branch will always go to 'cbb'
+                        * but llvm doesn't know that, so the branch is not going to be eliminated.
+                        */
+                       LLVMValueRef cmp = LLVMBuildICmp (builder, LLVMIntEQ, load, LLVMConstInt (LLVMInt32Type (), 0, FALSE), "");
+
+                       LLVMBuildCondBr (builder, cmp, cbb, dummy_bb);
+
+                       /* Emit a dummy false bblock which does nothing but contains a volatile store so it cannot be eliminated */
+                       ctx->builder = builder = create_builder (ctx);
+                       LLVMPositionBuilderAtEnd (builder, dummy_bb);
+                       mono_llvm_build_store (builder, LLVMConstInt (LLVMInt32Type (), 1, FALSE), ctx->long_bb_break_var, TRUE, LLVM_BARRIER_NONE);
+                       LLVMBuildBr (builder, cbb);
+
                        ctx->builder = builder = create_builder (ctx);
                        LLVMPositionBuilderAtEnd (builder, cbb);
                        ctx->bblocks [bb->block_num].end_bblock = cbb;
@@ -6543,7 +6569,7 @@ process_bb (EmitContext *ctx, MonoBasicBlock *bb)
 
                /* Convert the value to the type required by phi nodes */
                if (spec [MONO_INST_DEST] != ' ' && !MONO_IS_STORE_MEMBASE (ins) && ctx->vreg_types [ins->dreg]) {
-                       if (!values [ins->dreg])
+                       if (ctx->is_vphi [ins->dreg])
                                /* vtypes */
                                values [ins->dreg] = addresses [ins->dreg];
                        else
@@ -6692,6 +6718,7 @@ free_ctx (EmitContext *ctx)
        g_free (ctx->values);
        g_free (ctx->addresses);
        g_free (ctx->vreg_types);
+       g_free (ctx->is_vphi);
        g_free (ctx->vreg_cli_types);
        g_free (ctx->is_dead);
        g_free (ctx->unreachable);
@@ -6752,6 +6779,7 @@ mono_llvm_emit_method (MonoCompile *cfg)
         */
        ctx->addresses = g_new0 (LLVMValueRef, cfg->next_vreg);
        ctx->vreg_types = g_new0 (LLVMTypeRef, cfg->next_vreg);
+       ctx->is_vphi = g_new0 (gboolean, cfg->next_vreg);
        ctx->vreg_cli_types = g_new0 (MonoType*, cfg->next_vreg);
        ctx->phi_values = g_ptr_array_sized_new (256);
        /* 
@@ -7100,8 +7128,11 @@ emit_method_inner (EmitContext *ctx)
                                for (i = 0; i < ins->inst_phi_args [0]; i++) {
                                        int sreg1 = ins->inst_phi_args [i + 1];
                                        
-                                       if (sreg1 != -1)
+                                       if (sreg1 != -1) {
+                                               if (ins->opcode == OP_VPHI)
+                                                       ctx->is_vphi [sreg1] = TRUE;
                                                ctx->vreg_types [sreg1] = phi_type;
+                                       }
                                }
                                break;
                                }
index 8af84338759ecf8629b8b541dfb679058df08b2e..ea7474dd28bbfbfdd1a6bf703467bf5e23b37141 100644 (file)
@@ -2175,12 +2175,6 @@ mono_arch_decompose_long_opts (MonoCompile *cfg, MonoInst *ins)
        int tmp5 = -1;
 
        switch (ins->opcode) {
-#if 0
-       case OP_LCOMPARE:
-       case OP_LCOMPARE_IMM:
-               mono_print_ins (ins);
-               g_assert_not_reached ();
-#endif
        case OP_LADD:
                tmp1 = mono_alloc_ireg (cfg);
                MONO_EMIT_NEW_BIALU (cfg, OP_IADD, ins->dreg+1, ins->sreg1+1, ins->sreg2+1);
@@ -2217,17 +2211,6 @@ mono_arch_decompose_long_opts (MonoCompile *cfg, MonoInst *ins)
                NULLIFY_INS(ins);
                break;
 
-       case OP_LMUL:
-       case OP_LDIV:
-       case OP_LDIV_UN:
-       case OP_LREM:
-       case OP_LREM_UN:
-       case OP_LSHL:
-       case OP_LSHR:
-       case OP_LSHR_UN:
-               mono_print_ins (ins);
-               g_assert_not_reached ();
-
        case OP_LNEG:
                tmp1 = mono_alloc_ireg (cfg);
                MONO_EMIT_NEW_BIALU (cfg, OP_ISUB, ins->dreg+1, mips_zero, ins->sreg1+1);
@@ -2237,27 +2220,6 @@ mono_arch_decompose_long_opts (MonoCompile *cfg, MonoInst *ins)
                NULLIFY_INS(ins);
                break;
 
-#if 0
-       case OP_LNOT:
-#endif
-#if 0
-       case OP_LCONV_TO_I1:
-       case OP_LCONV_TO_I2:
-       case OP_LCONV_TO_I4:
-       case OP_LCONV_TO_I8:
-       case OP_LCONV_TO_R4:
-       case OP_LCONV_TO_R8:
-       case OP_LCONV_TO_U4:
-       case OP_LCONV_TO_U8:
-       case OP_LCONV_TO_U2:
-       case OP_LCONV_TO_U1:
-       case OP_LCONV_TO_I:
-       case OP_LCONV_TO_OVF_I:
-       case OP_LCONV_TO_OVF_U:
-#endif
-               mono_print_ins (ins);
-               g_assert_not_reached ();
-
        case OP_LADD_OVF:
                tmp1 = mono_alloc_ireg (cfg);
                tmp2 = mono_alloc_ireg (cfg);
@@ -2310,11 +2272,6 @@ mono_arch_decompose_long_opts (MonoCompile *cfg, MonoInst *ins)
                NULLIFY_INS(ins);
                break;
 
-       case OP_LMUL_OVF:
-       case OP_LMUL_OVF_UN:
-               mono_print_ins (ins);
-               g_assert_not_reached ();
-
        case OP_LSUB_OVF:
                tmp1 = mono_alloc_ireg (cfg);
                tmp2 = mono_alloc_ireg (cfg);
@@ -2361,60 +2318,6 @@ mono_arch_decompose_long_opts (MonoCompile *cfg, MonoInst *ins)
                MONO_EMIT_NEW_COMPARE_EXC (cfg, NE_UN, tmp2, mips_zero, "OverflowException");
                NULLIFY_INS(ins);
                break;
-#if 0
-       case OP_LCONV_TO_OVF_I1_UN:
-       case OP_LCONV_TO_OVF_I2_UN:
-       case OP_LCONV_TO_OVF_I4_UN:
-       case OP_LCONV_TO_OVF_I8_UN:
-       case OP_LCONV_TO_OVF_U1_UN:
-       case OP_LCONV_TO_OVF_U2_UN:
-       case OP_LCONV_TO_OVF_U4_UN:
-       case OP_LCONV_TO_OVF_U8_UN:
-       case OP_LCONV_TO_OVF_I_UN:
-       case OP_LCONV_TO_OVF_U_UN:
-       case OP_LCONV_TO_OVF_I1:
-       case OP_LCONV_TO_OVF_U1:
-       case OP_LCONV_TO_OVF_I2:
-       case OP_LCONV_TO_OVF_U2:
-       case OP_LCONV_TO_OVF_I4:
-       case OP_LCONV_TO_OVF_U4:
-       case OP_LCONV_TO_OVF_I8:
-       case OP_LCONV_TO_OVF_U8:
-#endif
-       case OP_LCEQ:
-       case OP_LCGT:
-       case OP_LCGT_UN:
-       case OP_LCLT:
-       case OP_LCLT_UN:
-#if 0
-       case OP_LCONV_TO_R_UN:
-       case OP_LCONV_TO_U:
-#endif
-       case OP_LMUL_IMM:
-       case OP_LSHL_IMM:
-       case OP_LSHR_IMM:
-       case OP_LSHR_UN_IMM:
-       case OP_LDIV_IMM:
-       case OP_LDIV_UN_IMM:
-       case OP_LREM_IMM:
-       case OP_LREM_UN_IMM:
-       case OP_LBEQ:
-       case OP_LBGE:
-       case OP_LBGT:
-       case OP_LBLE:
-       case OP_LBLT:
-       case OP_LBNE_UN:
-       case OP_LBGE_UN:
-       case OP_LBGT_UN:
-       case OP_LBLE_UN:
-       case OP_LBLT_UN:
-               mono_print_ins (ins);
-               g_assert_not_reached ();
-#if 0
-       case OP_LCONV_TO_R8_2:
-       case OP_LCONV_TO_R4_2:
-       case OP_LCONV_TO_R_UN_2:
-#endif
        case OP_LCONV_TO_OVF_I4_2:
                tmp1 = mono_alloc_ireg (cfg);
 
@@ -2424,14 +2327,6 @@ mono_arch_decompose_long_opts (MonoCompile *cfg, MonoInst *ins)
                MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, ins->dreg, ins->sreg1);
                NULLIFY_INS(ins);
                break;
-
-       case OP_LMIN_UN:
-       case OP_LMAX_UN:
-       case OP_LMIN:
-       case OP_LMAX:
-               mono_print_ins (ins);
-               g_assert_not_reached ();
-
        default:
                break;
        }
index 06c533aee46cffa33e738dfd1b665dd6685f85e9..df179bd2545334cd8cf1eca629efc0f54b487a43 100644 (file)
@@ -233,6 +233,15 @@ typedef struct MonoCompileArch {
 #define MONO_ARCH_EMULATE_FREM 1
 #endif
 
+/*
+ * mips backend misses some instructions that enable emitting of optimal
+ * code on other targets and, additionally, the register allocator gets
+ * confused by this optimization, failing to allocate all hw regs.
+ */
+#if SIZEOF_REGISTER == 4
+#define MONO_ARCH_NO_DIV_WITH_MUL
+#endif
+
 #if SIZEOF_REGISTER == 8
 #define MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS
 #endif
index 6f6e266a3b025d72fd9998435b46a8b053747b31..bdd3149c25bf25581ed0449fa8630a8eec6f02b0 100644 (file)
@@ -140,11 +140,15 @@ mono_gdb_render_native_backtraces (pid_t crashed_pid)
 static GHashTable *mono_saved_signal_handlers = NULL;
 
 static struct sigaction *
-get_saved_signal_handler (int signo)
+get_saved_signal_handler (int signo, gboolean remove)
 {
-       if (mono_saved_signal_handlers)
+       if (mono_saved_signal_handlers) {
                /* The hash is only modified during startup, so no need for locking */
-               return (struct sigaction *)g_hash_table_lookup (mono_saved_signal_handlers, GINT_TO_POINTER (signo));
+               struct sigaction *handler = g_hash_table_lookup (mono_saved_signal_handlers, GINT_TO_POINTER (signo));
+               if (remove && handler)
+                       g_hash_table_remove (mono_saved_signal_handlers, GINT_TO_POINTER (signo));
+               return handler;
+       }
        return NULL;
 }
 
@@ -167,21 +171,14 @@ save_old_signal_handler (int signo, struct sigaction *old_action)
        handler_to_save->sa_flags = old_action->sa_flags;
        
        if (!mono_saved_signal_handlers)
-               mono_saved_signal_handlers = g_hash_table_new (NULL, NULL);
+               mono_saved_signal_handlers = g_hash_table_new_full (NULL, NULL, NULL, g_free);
        g_hash_table_insert (mono_saved_signal_handlers, GINT_TO_POINTER (signo), handler_to_save);
 }
 
-static void
-free_saved_sig_handler_func (gpointer key, gpointer value, gpointer user_data)
-{
-       g_free (value);
-}
-
 static void
 free_saved_signal_handlers (void)
 {
        if (mono_saved_signal_handlers) {
-               g_hash_table_foreach (mono_saved_signal_handlers, free_saved_sig_handler_func, NULL);
                g_hash_table_destroy (mono_saved_signal_handlers);
                mono_saved_signal_handlers = NULL;
        }
@@ -198,7 +195,7 @@ gboolean
 MONO_SIG_HANDLER_SIGNATURE (mono_chain_signal)
 {
        int signal = MONO_SIG_HANDLER_GET_SIGNO ();
-       struct sigaction *saved_handler = (struct sigaction *)get_saved_signal_handler (signal);
+       struct sigaction *saved_handler = (struct sigaction *)get_saved_signal_handler (signal, FALSE);
 
        if (saved_handler && saved_handler->sa_handler) {
                if (!(saved_handler->sa_flags & SA_SIGINFO)) {
@@ -338,14 +335,8 @@ MONO_SIG_HANDLER_FUNC (static, profiler_signal_handler)
 
        /* See the comment in mono_runtime_shutdown_stat_profiler (). */
        if (mono_native_thread_id_get () == sampling_thread) {
-#ifdef HAVE_CLOCK_NANOSLEEP
-               if (mono_profiler_get_sampling_mode () == MONO_PROFILER_STAT_MODE_PROCESS) {
-                       InterlockedIncrement (&profiler_interrupt_signals_received);
-                       return;
-               }
-#endif
-
-               g_error ("%s: Unexpected profiler signal received by the sampler thread", __func__);
+               InterlockedIncrement (&profiler_interrupt_signals_received);
+               return;
        }
 
        InterlockedIncrement (&profiler_signals_received);
@@ -453,7 +444,7 @@ static void
 remove_signal_handler (int signo)
 {
        struct sigaction sa;
-       struct sigaction *saved_action = get_saved_signal_handler (signo);
+       struct sigaction *saved_action = get_saved_signal_handler (signo, TRUE);
 
        if (!saved_action) {
                sa.sa_handler = SIG_DFL;
@@ -764,7 +755,7 @@ mono_runtime_shutdown_stat_profiler (void)
 {
        InterlockedWrite (&sampling_thread_running, 0);
 
-#ifdef HAVE_CLOCK_NANOSLEEP
+#ifndef PLATFORM_MACOSX
        /*
         * There is a slight problem when we're using CLOCK_PROCESS_CPUTIME_ID: If
         * we're shutting down and there's largely no activity in the process other
@@ -777,28 +768,22 @@ mono_runtime_shutdown_stat_profiler (void)
         * sampling_thread_running upon an interrupt and return immediately if it's
         * zero. profiler_signal_handler () has a special case to ignore the signal
         * for the sampler thread.
-        *
-        * We do not need to do this on platforms where we use a regular sleep
-        * based on a monotonic clock. The sleep will return in a reasonable amount
-        * of time in those cases.
         */
-       if (mono_profiler_get_sampling_mode () == MONO_PROFILER_STAT_MODE_PROCESS) {
-               MonoThreadInfo *info;
-
-               // Did it shut down already?
-               if ((info = mono_thread_info_lookup (sampling_thread))) {
-                       while (!InterlockedRead (&sampling_thread_exiting)) {
-                               mono_threads_pthread_kill (info, profiler_signal);
-                               mono_thread_info_usleep (10 * 1000 /* 10ms */);
-                       }
+       MonoThreadInfo *info;
 
-                       // Make sure info can be freed.
-                       mono_hazard_pointer_clear (mono_hazard_pointer_get (), 1);
+       // Did it shut down already?
+       if ((info = mono_thread_info_lookup (sampling_thread))) {
+               while (!InterlockedRead (&sampling_thread_exiting)) {
+                       mono_threads_pthread_kill (info, profiler_signal);
+                       mono_thread_info_usleep (10 * 1000 /* 10ms */);
                }
+
+               // Make sure info can be freed.
+               mono_hazard_pointer_clear (mono_hazard_pointer_get (), 1);
        }
 #endif
 
-       pthread_join (sampling_thread, NULL);
+       mono_native_thread_join (sampling_thread);
 
        /*
         * We can't safely remove the signal handler because we have no guarantee
index a9c87011153b35ba64bf2d25f057801ea21ee03a..231b44d65ecda7a9d32996d8283a86df082d2682 100644 (file)
@@ -2405,10 +2405,9 @@ mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObjec
                         */
                        mono_class_setup_vtable (method->klass);
                        if (mono_class_has_failure (method->klass)) {
-                               MonoException *fail_exc = mono_class_get_exception_for_failure (method->klass);
+                               mono_error_set_for_class_failure (error, method->klass);
                                if (exc)
-                                       *exc = (MonoObject*)fail_exc;
-                               mono_error_set_exception_instance (error, fail_exc);
+                                       *exc = (MonoObject*)mono_class_get_exception_for_failure (method->klass);
                                return NULL;
                        }
                }
@@ -3744,6 +3743,8 @@ register_icalls (void)
                                ves_icall_get_trace);
        mono_add_internal_call ("Mono.Runtime::mono_runtime_install_handlers",
                                mono_runtime_install_handlers);
+       mono_add_internal_call ("Mono.Runtime::mono_runtime_cleanup_handlers",
+                               mono_runtime_cleanup_handlers);
 
 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
        mono_add_internal_call ("System.Diagnostics.Debugger::Mono_UnhandledException_internal",
index 77775169fd7d0d5a615fdd69e4b2dd761566f948..122334e6ea6519613d4bd8e741fac583c13bafc7 100644 (file)
@@ -366,12 +366,9 @@ mini_add_method_trampoline (MonoMethod *m, gpointer compiled_method, gboolean ad
 
        if (callee_array_helper) {
                add_static_rgctx_tramp = FALSE;
-               /* FIXME: ji->from_aot is not set for llvm methods */
-               if (ji && (ji->from_aot || mono_aot_only)) {
-                       /* In AOT mode, compiled_method points to one of the InternalArray methods in Array. */
-                       if (!mono_llvm_only && mono_method_needs_static_rgctx_invoke (jinfo_get_method (ji), TRUE))
-                               add_static_rgctx_tramp = TRUE;
-               }
+               /* In AOT mode, compiled_method points to one of the InternalArray methods in Array. */
+               if (ji && !mono_llvm_only && mono_method_needs_static_rgctx_invoke (jinfo_get_method (ji), TRUE))
+                       add_static_rgctx_tramp = TRUE;
        }
 
        if (mono_llvm_only)
diff --git a/mono/mini/mini-windows-uwp.c b/mono/mini/mini-windows-uwp.c
new file mode 100644 (file)
index 0000000..c2367aa
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * mini-windows-uwp.c: UWP profiler stat support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+#include <config.h>
+#include <glib.h>
+
+#if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
+#include <Windows.h>
+
+void
+mono_runtime_setup_stat_profiler (void)
+{
+       g_unsupported_api ("OpenThread, GetThreadContext");
+       SetLastError (ERROR_NOT_SUPPORTED);
+       return;
+}
+
+void
+mono_runtime_shutdown_stat_profiler (void)
+{
+       g_unsupported_api ("OpenThread, GetThreadContext");
+       SetLastError (ERROR_NOT_SUPPORTED);
+       return;
+}
+
+static gboolean
+mono_setup_thread_context(DWORD thread_id, MonoContext *mono_context)
+{
+       memset (mono_context, 0, sizeof (MonoContext));
+       return FALSE;
+}
+
+#else /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_mini_windows_uwp_quiet_lnk4221(void) {}
+#endif
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
index e7764e91beb749709474b294aef00cb5c30932ce..2aa3a7b75d1bc21d177500be8388a7448a6991fd 100644 (file)
@@ -44,6 +44,7 @@
 #include <mono/utils/dtrace.h>
 
 #include "mini.h"
+#include "mini-windows.h"
 #include <string.h>
 #include <ctype.h>
 #include "trace.h"
@@ -51,7 +52,7 @@
 
 #include "jit-icalls.h"
 
-#ifdef _WIN32
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 #include <mmsystem.h>
 #endif
 
@@ -91,16 +92,17 @@ MONO_SIG_HANDLER_SIGNATURE (mono_chain_signal)
        return TRUE;
 }
 
-static HANDLE win32_main_thread;
-static MMRESULT win32_timer;
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+static MMRESULT        g_timer_event = 0;
+static HANDLE g_timer_main_thread = INVALID_HANDLE_VALUE;
 
-static void CALLBACK
-win32_time_proc (UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2)
+static VOID
+thread_timer_expired (HANDLE thread)
 {
        CONTEXT context;
 
        context.ContextFlags = CONTEXT_CONTROL;
-       if (GetThreadContext (win32_main_thread, &context)) {
+       if (GetThreadContext (thread, &context)) {
 #ifdef _WIN64
                mono_profiler_stat_hit ((guchar *) context.Rip, &context);
 #else
@@ -109,57 +111,75 @@ win32_time_proc (UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2)
        }
 }
 
-void
-mono_runtime_setup_stat_profiler (void)
+static VOID CALLBACK
+timer_event_proc (UINT uID, UINT uMsg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
 {
-       static int inited = 0;
-       TIMECAPS timecaps;
+       thread_timer_expired ((HANDLE)dwUser);
+}
 
-       if (inited)
-               return;
+static VOID
+stop_profiler_timer_event (void)
+{
+       if (g_timer_event != 0) {
+
+               timeKillEvent (g_timer_event);
+               g_timer_event = 0;
+       }
+
+       if (g_timer_main_thread != INVALID_HANDLE_VALUE) {
+
+               CloseHandle (g_timer_main_thread);
+               g_timer_main_thread = INVALID_HANDLE_VALUE;
+       }
+}
+
+static VOID
+start_profiler_timer_event (void)
+{
+       g_return_if_fail (g_timer_main_thread == INVALID_HANDLE_VALUE && g_timer_event == 0);
+
+       TIMECAPS timecaps;
 
-       inited = 1;
        if (timeGetDevCaps (&timecaps, sizeof (timecaps)) != TIMERR_NOERROR)
                return;
 
-       if ((win32_main_thread = OpenThread (READ_CONTROL | THREAD_GET_CONTEXT, FALSE, GetCurrentThreadId ())) == NULL)
+       g_timer_main_thread = OpenThread (READ_CONTROL | THREAD_GET_CONTEXT, FALSE, GetCurrentThreadId ());
+       if (g_timer_main_thread == NULL)
                return;
 
        if (timeBeginPeriod (1) != TIMERR_NOERROR)
                return;
 
-       if ((win32_timer = timeSetEvent (1, 0, (LPTIMECALLBACK)win32_time_proc, (DWORD_PTR)NULL, TIME_PERIODIC)) == 0) {
+       g_timer_event = timeSetEvent (1, 0, (LPTIMECALLBACK)timer_event_proc, (DWORD_PTR)g_timer_main_thread, TIME_PERIODIC | TIME_KILL_SYNCHRONOUS);
+       if (g_timer_event == 0) {
                timeEndPeriod (1);
                return;
        }
 }
 
+void
+mono_runtime_setup_stat_profiler (void)
+{
+       start_profiler_timer_event ();
+       return;
+}
+
 void
 mono_runtime_shutdown_stat_profiler (void)
 {
+       stop_profiler_timer_event ();
+       return;
 }
 
 gboolean
-mono_thread_state_init_from_handle (MonoThreadUnwindState *tctx, MonoThreadInfo *info)
+mono_setup_thread_context(DWORD thread_id, MonoContext *mono_context)
 {
-       DWORD id = mono_thread_info_get_tid (info);
        HANDLE handle;
        CONTEXT context;
-       DWORD result;
-       MonoContext *ctx;
-       MonoJitTlsData *jit_tls;
-       void *domain;
-       MonoLMF *lmf = NULL;
-       gpointer *addr;
-
-       tctx->valid = FALSE;
-       tctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] = NULL;
-       tctx->unwind_data [MONO_UNWIND_DATA_LMF] = NULL;
-       tctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = NULL;
 
-       g_assert (id != GetCurrentThreadId ());
+       g_assert (thread_id != GetCurrentThreadId ());
 
-       handle = OpenThread (THREAD_ALL_ACCESS, FALSE, id);
+       handle = OpenThread (THREAD_ALL_ACCESS, FALSE, thread_id);
        g_assert (handle);
 
        context.ContextFlags = CONTEXT_INTEGER | CONTEXT_CONTROL;
@@ -172,10 +192,29 @@ mono_thread_state_init_from_handle (MonoThreadUnwindState *tctx, MonoThreadInfo
        g_assert (context.ContextFlags & CONTEXT_INTEGER);
        g_assert (context.ContextFlags & CONTEXT_CONTROL);
 
-       ctx = &tctx->ctx;
+       memset (mono_context, 0, sizeof (MonoContext));
+       mono_sigctx_to_monoctx (&context, mono_context);
 
-       memset (ctx, 0, sizeof (MonoContext));
-       mono_sigctx_to_monoctx (&context, ctx);
+       CloseHandle (handle);
+       return TRUE;
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+gboolean
+mono_thread_state_init_from_handle (MonoThreadUnwindState *tctx, MonoThreadInfo *info)
+{
+       DWORD id = mono_thread_info_get_tid (info);
+       MonoJitTlsData *jit_tls;
+       void *domain;
+       MonoLMF *lmf = NULL;
+       gpointer *addr;
+
+       tctx->valid = FALSE;
+       tctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] = NULL;
+       tctx->unwind_data [MONO_UNWIND_DATA_LMF] = NULL;
+       tctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = NULL;
+
+       mono_setup_thread_context(id, &tctx->ctx);
 
        /* mono_set_jit_tls () sets this */
        jit_tls = mono_thread_info_tls_get (info, TLS_KEY_JIT_TLS);
@@ -203,4 +242,3 @@ mono_thread_state_init_from_handle (MonoThreadUnwindState *tctx, MonoThreadInfo
 
        return TRUE;
 }
-
diff --git a/mono/mini/mini-windows.h b/mono/mini/mini-windows.h
new file mode 100644 (file)
index 0000000..337b1ab
--- /dev/null
@@ -0,0 +1,15 @@
+#ifndef __MONO_MINI_WINDOWS_H__
+#define __MONO_MINI_WINDOWS_H__
+
+#include <config.h>
+#include <glib.h>
+
+#ifdef HOST_WIN32
+#include "Windows.h"
+#include "mini.h"
+#include "mono/utils/mono-context.h"
+
+gboolean
+mono_setup_thread_context(DWORD thread_id, MonoContext *mono_context);
+#endif /* HOST_WIN32 */
+#endif /* __MONO_MINI_WINDOWS_H__ */
index 0dd4af7a71ede59872342fd943775750d3a50d52..51ca3d5c79cc415a49c4f92c14bccba3c6be9bec 100644 (file)
@@ -1052,7 +1052,7 @@ mini_method_verify (MonoCompile *cfg, MonoMethod *method, gboolean fail_compile)
                                        else if (info->exception_type == MONO_EXCEPTION_FIELD_ACCESS)
                                                mono_error_set_generic_error (&cfg->error, "System", "FieldAccessException", "%s", msg);
                                        else if (info->exception_type == MONO_EXCEPTION_UNVERIFIABLE_IL)
-                                               mono_error_set_generic_error (&cfg->error, "System.Security", "VerificationException", msg);
+                                               mono_error_set_generic_error (&cfg->error, "System.Security", "VerificationException", "%s", msg);
                                        if (!mono_error_ok (&cfg->error)) {
                                                mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
                                                g_free (msg);
@@ -3175,6 +3175,9 @@ init_backend (MonoBackend *backend)
 #ifdef MONO_ARCH_DYN_CALL_PARAM_AREA
        backend->dyn_call_param_area = MONO_ARCH_DYN_CALL_PARAM_AREA;
 #endif
+#ifdef MONO_ARCH_NO_DIV_WITH_MUL
+       backend->disable_div_with_mul = 1;
+#endif
 }
 
 /*
@@ -4053,7 +4056,7 @@ void
 mono_cfg_set_exception_invalid_program (MonoCompile *cfg, char *msg)
 {
        mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
-       mono_error_set_generic_error (&cfg->error, "System", "InvalidProgramException", msg);
+       mono_error_set_generic_error (&cfg->error, "System", "InvalidProgramException", "%s", msg);
 }
 
 #endif /* DISABLE_JIT */
@@ -4397,9 +4400,8 @@ mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain, in
 
        vtable = mono_class_vtable (target_domain, method->klass);
        if (!vtable) {
-               ex = mono_class_get_exception_for_failure (method->klass);
-               g_assert (ex);
-               mono_error_set_exception_instance (error, ex);
+               g_assert (mono_class_has_failure (method->klass));
+               mono_error_set_for_class_failure (error, method->klass);
                return NULL;
        }
 
index d3a550946013f217c8c53ccb20b118d2d844badf..a7bba5a62e4660dafca5a516e2cd9fe762e50cf2 100644 (file)
@@ -1496,6 +1496,7 @@ typedef struct {
        guint            need_got_var : 1;
        guint            need_div_check : 1;
        guint            no_unaligned_access : 1;
+       guint            disable_div_with_mul : 1;
        int              monitor_enter_adjustment;
        int              dyn_call_param_area;
 } MonoBackend;
index cf769a9e5305d3319ac8e1eed0e4167cc6102b6c..7d7cc41aa618c99bb060fd69eedcf9441ba4b559 100644 (file)
@@ -33,6 +33,7 @@
 
 #define IS_REX(inst) (((inst) >= 0x40) && ((inst) <= 0x4f))
 
+#ifndef DISABLE_JIT
 /*
  * mono_arch_get_unbox_trampoline:
  * @m: method pointer
@@ -110,6 +111,7 @@ mono_arch_get_static_rgctx_trampoline (MonoMethod *m, MonoMethodRuntimeGenericCo
 
        return start;
 }
+#endif /* !DISABLE_JIT */
 
 #ifdef _WIN64
 // Workaround lack of Valgrind support for 64-bit Windows
@@ -171,6 +173,7 @@ mono_arch_patch_callsite (guint8 *method_start, guint8 *orig_code, guint8 *addr)
        }
 }
 
+#ifndef DISABLE_JIT
 guint8*
 mono_arch_create_llvm_native_thunk (MonoDomain *domain, guint8 *addr)
 {
@@ -190,6 +193,7 @@ mono_arch_create_llvm_native_thunk (MonoDomain *domain, guint8 *addr)
        mono_profiler_code_buffer_new (thunk_start, thunk_code - thunk_start, MONO_PROFILER_CODE_BUFFER_HELPER, NULL);
        return addr;
 }
+#endif /* !DISABLE_JIT */
 
 void
 mono_arch_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
@@ -208,6 +212,7 @@ mono_arch_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *a
        InterlockedExchangePointer (plt_jump_table_entry, addr);
 }
 
+#ifndef DISABLE_JIT
 static void
 stack_unaligned (MonoTrampolineType tramp_type)
 {
@@ -756,6 +761,7 @@ mono_arch_invalidate_method (MonoJitInfo *ji, void *func, gpointer func_arg)
        x86_push_imm (code, (guint64)func_arg);
        amd64_call_reg (code, AMD64_R11);
 }
+#endif /* !DISABLE_JIT */
 
 gpointer
 mono_amd64_handler_block_trampoline_helper (void)
@@ -764,6 +770,7 @@ mono_amd64_handler_block_trampoline_helper (void)
        return jit_tls->handler_block_return_address;
 }
 
+#ifndef DISABLE_JIT
 gpointer
 mono_arch_create_handler_block_trampoline (MonoTrampInfo **info, gboolean aot)
 {
@@ -832,6 +839,7 @@ mono_arch_create_handler_block_trampoline (MonoTrampInfo **info, gboolean aot)
 
        return buf;
 }
+#endif /* !DISABLE_JIT */
 
 /*
  * mono_arch_get_call_target:
@@ -862,6 +870,7 @@ mono_arch_get_plt_info_offset (guint8 *plt_entry, mgreg_t *regs, guint8 *code)
        return *(guint32*)(plt_entry + 6);
 }
 
+#ifndef DISABLE_JIT
 /*
  * mono_arch_create_sdb_trampoline:
  *
@@ -960,3 +969,69 @@ mono_arch_create_sdb_trampoline (gboolean single_step, MonoTrampInfo **info, gbo
 
        return buf;
 }
+#endif /* !DISABLE_JIT */
+
+#ifdef DISABLE_JIT
+gpointer
+mono_arch_get_unbox_trampoline (MonoMethod *m, gpointer addr)
+{
+       g_assert_not_reached ();
+       return NULL;
+}
+
+gpointer
+mono_arch_get_static_rgctx_trampoline (MonoMethod *m, MonoMethodRuntimeGenericContext *mrgctx, gpointer addr)
+{
+       g_assert_not_reached ();
+       return NULL;
+}
+
+gpointer
+mono_arch_create_rgctx_lazy_fetch_trampoline (guint32 slot, MonoTrampInfo **info, gboolean aot)
+{
+       g_assert_not_reached ();
+       return NULL;
+}
+
+guchar*
+mono_arch_create_generic_trampoline (MonoTrampolineType tramp_type, MonoTrampInfo **info, gboolean aot)
+{
+       g_assert_not_reached ();
+       return NULL;
+}
+
+gpointer
+mono_arch_create_specific_trampoline (gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
+{
+       g_assert_not_reached ();
+       return NULL;
+}
+
+gpointer
+mono_arch_create_general_rgctx_lazy_fetch_trampoline (MonoTrampInfo **info, gboolean aot)
+{
+       g_assert_not_reached ();
+       return NULL;
+}
+
+gpointer
+mono_arch_create_handler_block_trampoline (MonoTrampInfo **info, gboolean aot)
+{
+        g_assert_not_reached ();
+        return NULL;
+}
+
+void
+mono_arch_invalidate_method (MonoJitInfo *ji, void *func, gpointer func_arg)
+{
+       g_assert_not_reached ();
+       return;
+}
+
+guint8*
+mono_arch_create_sdb_trampoline (gboolean single_step, MonoTrampInfo **info, gboolean aot)
+{
+       g_assert_not_reached ();
+       return NULL;
+}
+#endif /* DISABLE_JIT */
index 3d7eb62e4004b07a10c4644c3086e9eedf21b66a..4f6c4acb204fc26e059d4c7c08d3e4c6315c8938 100644 (file)
@@ -73,10 +73,10 @@ libmono_profiler_iomap_la_LDFLAGS = $(prof_ldflags)
 libmono_profiler_iomap_static_la_SOURCES = mono-profiler-iomap.c
 libmono_profiler_iomap_static_la_LDFLAGS = -static
 
-libmono_profiler_log_la_SOURCES = proflog.c
+libmono_profiler_log_la_SOURCES = mono-profiler-log.c
 libmono_profiler_log_la_LIBADD = $(monodir)/mono/mini/$(LIBMONO_LA) $(GLIB_LIBS) $(Z_LIBS)
 libmono_profiler_log_la_LDFLAGS = $(prof_ldflags)
-libmono_profiler_log_static_la_SOURCES = proflog.c
+libmono_profiler_log_static_la_SOURCES = mono-profiler-log.c
 libmono_profiler_log_static_la_LDFLAGS = -static
 
 if HAVE_VTUNE
@@ -88,7 +88,7 @@ libmono_profiler_vtune_static_la_SOURCES = mono-profiler-vtune.c
 libmono_profiler_vtune_static_la_LDFLAGS = -static
 endif
 
-mprof_report_SOURCES = decode.c
+mprof_report_SOURCES = mprof-report.c
 mprof_report_LDADD = $(Z_LIBS) $(GLIB_LIBS) $(LIBICONV)
 
 PLOG_TESTS_SRC=test-alloc.cs test-busy.cs test-monitor.cs test-excleave.cs \
@@ -110,6 +110,7 @@ testlog: $(PLOG_TESTS)
 
 check-local: $(check_targets)
 
-EXTRA_DIST=utils.c utils.h proflog.h \
-       $(PLOG_TESTS_SRC) ptestrunner.pl \
+EXTRA_DIST=mono-profiler-log.h \
+       $(PLOG_TESTS_SRC) \
+       ptestrunner.pl \
        $(suppression_DATA)
diff --git a/mono/profiler/decode.c b/mono/profiler/decode.c
deleted file mode 100644 (file)
index 3381504..0000000
+++ /dev/null
@@ -1,4258 +0,0 @@
-/*
- * decode.c: mprof-report program source: decode and analyze the log profiler data
- *
- * Authors:
- *   Paolo Molaro (lupus@ximian.com)
- *   Alex Rønne Petersen (alexrp@xamarin.com)
- *
- * Copyright 2010 Novell, Inc (http://www.novell.com)
- * Licensed under the MIT license. See LICENSE file in the project root for full license information.
- */
-
-/*
- * The Coverage XML output schema
- * <coverage>
- *   <assembly/>
- *   <class/>
- *   <method>
- *     <statement/>
- *   </method>
- * </coverage>
- *
- * Elements:
- *   <coverage> - The root element of the documentation. It can contain any number of
- *                <assembly>, <class> or <method> elements.
- *                Attributes:
- *                   - version: The version number for the file format - (eg: "0.3")
- *   <assembly> - Contains data about assemblies. Has no child elements
- *                Attributes:
- *                   - name: The name of the assembly - (eg: "System.Xml")
- *                   - guid: The GUID of the assembly
- *                   - filename: The filename of the assembly
- *                   - method-count: The number of methods in the assembly
- *                   - full: The number of fully covered methods
- *                   - partial: The number of partially covered methods
- *   <class> - Contains data about classes. Has no child elements
- *             Attributes:
- *                - name: The name of the class
- *                - method-count: The number of methods in the class
- *                - full: The number of fully covered methods
- *                - partial: The number of partially covered methods
- *   <method> - Contains data about methods. Can contain any number of <statement> elements
- *              Attributes:
- *                 - assembly: The name of the parent assembly
- *                 - class: The name of the parent class
- *                 - name: The name of the method, with all it's parameters
- *                 - filename: The name of the source file containing this method
- *                 - token
- *   <statement> - Contains data about IL statements. Has no child elements
- *                 Attributes:
- *                    - offset: The offset of the statement in the IL code after the previous
- *                              statement's offset
- *                    - counter: 1 if the line was covered, 0 if it was not
- *                    - line: The line number in the parent method's file
- *                    - column: The column on the line
- */
-#include <config.h>
-#include "utils.c"
-#include "proflog.h"
-#include <string.h>
-#include <assert.h>
-#include <stdio.h>
-#if !defined(__APPLE__) && !defined(__FreeBSD__)
-#include <malloc.h>
-#endif
-#include <unistd.h>
-#include <stdlib.h>
-#if defined (HAVE_SYS_ZLIB)
-#include <zlib.h>
-#endif
-#include <glib.h>
-#include <mono/metadata/profiler.h>
-#include <mono/metadata/object.h>
-#include <mono/metadata/debug-helpers.h>
-#include <mono/utils/mono-counters.h>
-
-#define HASH_SIZE 9371
-#define SMALL_HASH_SIZE 31
-
-#if defined(__native_client__) || defined(__native_client_codegen__)
-volatile int __nacl_thread_suspension_needed = 0;
-void __nacl_suspend_thread_if_needed() {}
-#endif
-
-static int debug = 0;
-static int collect_traces = 0;
-static int show_traces = 0;
-static int trace_max = 6;
-static int verbose = 0;
-static uintptr_t *tracked_objects = 0;
-static int num_tracked_objects = 0;
-static uintptr_t thread_filter = 0;
-static uint64_t find_size = 0;
-static const char* find_name = NULL;
-static uint64_t time_from = 0;
-static uint64_t time_to = 0xffffffffffffffffULL;
-static int use_time_filter = 0;
-static uint64_t startup_time = 0;
-static FILE* outfile = NULL;
-static FILE* coverage_outfile = NULL;
-
-static int32_t
-read_int16 (unsigned char *p)
-{
-       int32_t value = *p++;
-       value |= (*p++) << 8;
-       return value;
-}
-
-static int32_t
-read_int32 (unsigned char *p)
-{
-       int32_t value = *p++;
-       value |= (*p++) << 8;
-       value |= (*p++) << 16;
-       value |= (uint32_t)(*p++) << 24;
-       return value;
-}
-
-static int64_t
-read_int64 (unsigned char *p)
-{
-       uint64_t value = *p++;
-       value |= (*p++) << 8;
-       value |= (*p++) << 16;
-       value |= (uint64_t)(*p++) << 24;
-       value |= (uint64_t)(*p++) << 32;
-       value |= (uint64_t)(*p++) << 40;
-       value |= (uint64_t)(*p++) << 48;
-       value |= (uint64_t)(*p++) << 54;
-       return value;
-}
-
-static char*
-pstrdup (const char *s)
-{
-       int len = strlen (s) + 1;
-       char *p = (char *)malloc (len);
-       memcpy (p, s, len);
-       return p;
-}
-
-typedef struct _CounterValue CounterValue;
-struct _CounterValue {
-       uint64_t timestamp;
-       unsigned char *buffer;
-       CounterValue *next;
-};
-
-typedef struct _Counter Counter;
-struct _Counter {
-       int index;
-       const char *section;
-       const char *name;
-       int type;
-       int unit;
-       int variance;
-       CounterValue *values;
-       CounterValue *values_last;
-};
-
-typedef struct _CounterList CounterList;
-struct _CounterList {
-       Counter *counter;
-       CounterList *next;
-};
-
-typedef struct _CounterSection CounterSection;
-struct _CounterSection {
-       const char *value;
-       CounterList *counters;
-       CounterList *counters_last;
-       CounterSection *next;
-};
-
-typedef struct _CounterTimestamp CounterTimestamp;
-struct _CounterTimestamp {
-       uint64_t value;
-       CounterSection *sections;
-       CounterSection *sections_last;
-       CounterTimestamp *next;
-};
-
-static CounterList *counters = NULL;
-static CounterSection *counters_sections = NULL;
-static CounterTimestamp *counters_timestamps = NULL;
-
-enum {
-       COUNTERS_SORT_TIME,
-       COUNTERS_SORT_CATEGORY
-};
-
-static int counters_sort_mode = COUNTERS_SORT_TIME;
-
-static void
-add_counter_to_section (Counter *counter)
-{
-       CounterSection *csection, *s;
-       CounterList *clist;
-
-       clist = (CounterList *)calloc (1, sizeof (CounterList));
-       clist->counter = counter;
-
-       for (csection = counters_sections; csection; csection = csection->next) {
-               if (strcmp (csection->value, counter->section) == 0) {
-                       /* If section exist */
-                       if (!csection->counters)
-                               csection->counters = clist;
-                       else
-                               csection->counters_last->next = clist;
-                       csection->counters_last = clist;
-                       return;
-               }
-       }
-
-       /* If section does not exist */
-       csection = (CounterSection *)calloc (1, sizeof (CounterSection));
-       csection->value = counter->section;
-       csection->counters = clist;
-       csection->counters_last = clist;
-
-       if (!counters_sections) {
-               counters_sections = csection;
-       } else {
-               s = counters_sections;
-               while (s->next)
-                       s = s->next;
-               s->next = csection;
-       }
-}
-
-static void
-add_counter (const char *section, const char *name, int type, int unit, int variance, int index)
-{
-       CounterList *list, *l;
-       Counter *counter;
-
-       for (list = counters; list; list = list->next)
-               if (list->counter->index == index)
-                       return;
-
-       counter = (Counter *)calloc (1, sizeof (Counter));
-       counter->section = section;
-       counter->name = name;
-       counter->type = type;
-       counter->unit = unit;
-       counter->variance = variance;
-       counter->index = index;
-
-       list = (CounterList *)calloc (1, sizeof (CounterList));
-       list->counter = counter;
-
-       if (!counters) {
-               counters = list;
-       } else {
-               l = counters;
-               while (l->next)
-                       l = l->next;
-               l->next = list;
-       }
-
-       if (counters_sort_mode == COUNTERS_SORT_CATEGORY || !verbose)
-               add_counter_to_section (counter);
-}
-
-static void
-add_counter_to_timestamp (uint64_t timestamp, Counter *counter)
-{
-       CounterTimestamp *ctimestamp, *t;
-       CounterSection *csection;
-       CounterList *clist;
-
-       clist = (CounterList *)calloc (1, sizeof (CounterList));
-       clist->counter = counter;
-
-       for (ctimestamp = counters_timestamps; ctimestamp; ctimestamp = ctimestamp->next) {
-               if (ctimestamp->value == timestamp) {
-                       for (csection = ctimestamp->sections; csection; csection = csection->next) {
-                               if (strcmp (csection->value, counter->section) == 0) {
-                                       /* if timestamp exist and section exist */
-                                       if (!csection->counters)
-                                               csection->counters = clist;
-                                       else
-                                               csection->counters_last->next = clist;
-                                       csection->counters_last = clist;
-                                       return;
-                               }
-                       }
-
-                       /* if timestamp exist and section does not exist */
-                       csection = (CounterSection *)calloc (1, sizeof (CounterSection));
-                       csection->value = counter->section;
-                       csection->counters = clist;
-                       csection->counters_last = clist;
-
-                       if (!ctimestamp->sections)
-                               ctimestamp->sections = csection;
-                       else
-                               ctimestamp->sections_last->next = csection;
-                       ctimestamp->sections_last = csection;
-                       return;
-               }
-       }
-
-       /* If timestamp do not exist and section does not exist */
-       csection = (CounterSection *)calloc (1, sizeof (CounterSection));
-       csection->value = counter->section;
-       csection->counters = clist;
-       csection->counters_last = clist;
-
-       ctimestamp = (CounterTimestamp *)calloc (1, sizeof (CounterTimestamp));
-       ctimestamp->value = timestamp;
-       ctimestamp->sections = csection;
-       ctimestamp->sections_last = csection;
-
-       if (!counters_timestamps) {
-               counters_timestamps = ctimestamp;
-       } else {
-               t = counters_timestamps;
-               while (t->next)
-                       t = t->next;
-               t->next = ctimestamp;
-       }
-}
-
-static void
-add_counter_value (int index, CounterValue *value)
-{
-       CounterList *list;
-
-       for (list = counters; list; list = list->next) {
-               if (list->counter->index == index) {
-                       if (!list->counter->values)
-                               list->counter->values = value;
-                       else
-                               list->counter->values_last->next = value;
-                       list->counter->values_last = value;
-
-                       if (counters_sort_mode == COUNTERS_SORT_TIME)
-                               add_counter_to_timestamp (value->timestamp, list->counter);
-
-                       return;
-               }
-       }
-}
-
-static const char*
-section_name (int section)
-{
-       switch (section) {
-       case MONO_COUNTER_JIT: return "Mono JIT";
-       case MONO_COUNTER_GC: return "Mono GC";
-       case MONO_COUNTER_METADATA: return "Mono Metadata";
-       case MONO_COUNTER_GENERICS: return "Mono Generics";
-       case MONO_COUNTER_SECURITY: return "Mono Security";
-       case MONO_COUNTER_RUNTIME: return "Mono Runtime";
-       case MONO_COUNTER_SYSTEM: return "Mono System";
-       case MONO_COUNTER_PROFILER: return "Mono Profiler";
-       default: return "<unknown>";
-       }
-}
-
-static const char*
-type_name (int type)
-{
-       switch (type) {
-       case MONO_COUNTER_INT: return "Int";
-       case MONO_COUNTER_UINT: return "UInt";
-       case MONO_COUNTER_WORD: return "Word";
-       case MONO_COUNTER_LONG: return "Long";
-       case MONO_COUNTER_ULONG: return "ULong";
-       case MONO_COUNTER_DOUBLE: return "Double";
-       case MONO_COUNTER_STRING: return "String";
-       case MONO_COUNTER_TIME_INTERVAL: return "Time Interval";
-       default: return "<unknown>";
-       }
-}
-
-static const char*
-unit_name (int unit)
-{
-       switch (unit) {
-       case MONO_COUNTER_RAW: return "Raw";
-       case MONO_COUNTER_BYTES: return "Bytes";
-       case MONO_COUNTER_TIME: return "Time";
-       case MONO_COUNTER_COUNT: return "Count";
-       case MONO_COUNTER_PERCENTAGE: return "Percentage";
-       default: return "<unknown>";
-       }
-}
-
-static const char*
-variance_name (int variance)
-{
-       switch (variance) {
-       case MONO_COUNTER_MONOTONIC: return "Monotonic";
-       case MONO_COUNTER_CONSTANT: return "Constant";
-       case MONO_COUNTER_VARIABLE: return "Variable";
-       default: return "<unknown>";
-       }
-}
-
-static void
-dump_counters_value (Counter *counter, const char *key_format, const char *key, void *value)
-{
-       char format[32];
-
-       if (value == NULL) {
-               snprintf (format, sizeof (format), "%s : %%s\n", key_format);
-               fprintf (outfile, format, key, "<null>");
-       } else {
-               switch (counter->type) {
-               case MONO_COUNTER_INT:
-#if SIZEOF_VOID_P == 4
-               case MONO_COUNTER_WORD:
-#endif
-                       snprintf (format, sizeof (format), "%s : %%d\n", key_format);
-                       fprintf (outfile, format, key, *(int32_t*)value);
-                       break;
-               case MONO_COUNTER_UINT:
-                       snprintf (format, sizeof (format), "%s : %%u\n", key_format);
-                       fprintf (outfile, format, key, *(uint32_t*)value);
-                       break;
-               case MONO_COUNTER_LONG:
-#if SIZEOF_VOID_P == 8
-               case MONO_COUNTER_WORD:
-#endif
-               case MONO_COUNTER_TIME_INTERVAL:
-                       if (counter->type == MONO_COUNTER_LONG && counter->unit == MONO_COUNTER_TIME) {
-                               snprintf (format, sizeof (format), "%s : %%0.3fms\n", key_format);
-                               fprintf (outfile, format, key, (double)*(int64_t*)value / 10000.0);
-                       } else if (counter->type == MONO_COUNTER_TIME_INTERVAL) {
-                               snprintf (format, sizeof (format), "%s : %%0.3fms\n", key_format);
-                               fprintf (outfile, format, key, (double)*(int64_t*)value / 1000.0);
-                       } else {
-                               snprintf (format, sizeof (format), "%s : %%u\n", key_format);
-                               fprintf (outfile, format, key, *(int64_t*)value);
-                       }
-                       break;
-               case MONO_COUNTER_ULONG:
-                       snprintf (format, sizeof (format), "%s : %%llu\n", key_format);
-                       fprintf (outfile, format, key, *(uint64_t*)value);
-                       break;
-               case MONO_COUNTER_DOUBLE:
-                       snprintf (format, sizeof (format), "%s : %%f\n", key_format);
-                       fprintf (outfile, format, key, *(double*)value);
-                       break;
-               case MONO_COUNTER_STRING:
-                       snprintf (format, sizeof (format), "%s : %%s\n", key_format);
-                       fprintf (outfile, format, key, *(char*)value);
-                       break;
-               }
-       }
-}
-
-static void
-dump_counters (void)
-{
-       Counter *counter;
-       CounterValue *cvalue;
-       CounterTimestamp *ctimestamp;
-       CounterSection *csection;
-       CounterList *clist;
-       char strtimestamp[17];
-       int i, section_printed;
-
-       fprintf (outfile, "\nCounters:\n");
-
-       if (!verbose) {
-               char counters_to_print[][64] = {
-                       "Methods from AOT",
-                       "Methods JITted using mono JIT",
-                       "Methods JITted using LLVM",
-                       "Total time spent JITting (sec)",
-                       "User Time",
-                       "System Time",
-                       "Total Time",
-                       "Working Set",
-                       "Private Bytes",
-                       "Virtual Bytes",
-                       "Page Faults",
-                       "CPU Load Average - 1min",
-                       "CPU Load Average - 5min",
-                       "CPU Load Average - 15min",
-                       ""
-               };
-
-               for (csection = counters_sections; csection; csection = csection->next) {
-                       section_printed = 0;
-
-                       for (clist = csection->counters; clist; clist = clist->next) {
-                               counter = clist->counter;
-                               if (!counter->values_last)
-                                       continue;
-
-                               for (i = 0; counters_to_print [i][0] != 0; i++) {
-                                       if (strcmp (counters_to_print [i], counter->name) == 0) {
-                                               if (!section_printed) {
-                                                       fprintf (outfile, "\t%s:\n", csection->value);
-                                                       section_printed = 1;
-                                               }
-
-                                               dump_counters_value (counter, "\t\t%-30s", counter->name, counter->values_last->buffer);
-                                               break;
-                                       }
-                               }
-                       }
-               }
-       } else if (counters_sort_mode == COUNTERS_SORT_TIME) {
-               for (ctimestamp = counters_timestamps; ctimestamp; ctimestamp = ctimestamp->next) {
-                       fprintf (outfile, "\t%llu:%02llu:%02llu:%02llu.%03llu:\n",
-                               (unsigned long long) (ctimestamp->value / 1000 / 60 / 60 / 24 % 1000),
-                               (unsigned long long) (ctimestamp->value / 1000 / 60 / 60 % 24),
-                               (unsigned long long) (ctimestamp->value / 1000 / 60 % 60),
-                               (unsigned long long) (ctimestamp->value / 1000 % 60),
-                               (unsigned long long) (ctimestamp->value % 1000));
-
-                       for (csection = ctimestamp->sections; csection; csection = csection->next) {
-                               fprintf (outfile, "\t\t%s:\n", csection->value);
-
-                               for (clist = csection->counters; clist; clist = clist->next) {
-                                       counter = clist->counter;
-                                       for (cvalue = counter->values; cvalue; cvalue = cvalue->next) {
-                                               if (cvalue->timestamp != ctimestamp->value)
-                                                       continue;
-
-                                               dump_counters_value (counter, "\t\t\t%-30s", counter->name, cvalue->buffer);
-                                       }
-                               }
-                       }
-               }
-       } else if (counters_sort_mode == COUNTERS_SORT_CATEGORY) {
-               for (csection = counters_sections; csection; csection = csection->next) {
-                       fprintf (outfile, "\t%s:\n", csection->value);
-
-                       for (clist = csection->counters; clist; clist = clist->next) {
-                               counter = clist->counter;
-                               fprintf (outfile, "\t\t%s: [type: %s, unit: %s, variance: %s]\n",
-                                       counter->name, type_name (counter->type), unit_name (counter->unit), variance_name (counter->variance));
-
-                               for (cvalue = counter->values; cvalue; cvalue = cvalue->next) {
-                                       snprintf (strtimestamp, sizeof (strtimestamp), "%llu:%02llu:%02llu:%02llu.%03llu",
-                                               (unsigned long long) (cvalue->timestamp / 1000 / 60 / 60 / 24 % 1000),
-                                               (unsigned long long) (cvalue->timestamp / 1000 / 60 / 60 % 24),
-                                               (unsigned long long) (cvalue->timestamp / 1000 / 60 % 60),
-                                               (unsigned long long) (cvalue->timestamp / 1000 % 60),
-                                               (unsigned long long) (cvalue->timestamp % 1000));
-
-                                       dump_counters_value (counter, "\t\t\t%s", strtimestamp, cvalue->buffer);
-                               }
-                       }
-               }
-       }
-}
-
-static int num_images;
-typedef struct _ImageDesc ImageDesc;
-struct _ImageDesc {
-       ImageDesc *next;
-       intptr_t image;
-       char *filename;
-};
-
-static ImageDesc* image_hash [SMALL_HASH_SIZE] = {0};
-
-static void
-add_image (intptr_t image, char *name)
-{
-       int slot = ((image >> 2) & 0xffff) % SMALL_HASH_SIZE;
-       ImageDesc *cd = (ImageDesc *)malloc (sizeof (ImageDesc));
-       cd->image = image;
-       cd->filename = pstrdup (name);
-       cd->next = image_hash [slot];
-       image_hash [slot] = cd;
-       num_images++;
-}
-
-static int num_assemblies;
-
-typedef struct _AssemblyDesc AssemblyDesc;
-struct _AssemblyDesc {
-       AssemblyDesc *next;
-       intptr_t assembly;
-       char *asmname;
-};
-
-static AssemblyDesc* assembly_hash [SMALL_HASH_SIZE] = {0};
-
-static void
-add_assembly (intptr_t assembly, char *name)
-{
-       int slot = ((assembly >> 2) & 0xffff) % SMALL_HASH_SIZE;
-       AssemblyDesc *cd = (AssemblyDesc *)malloc (sizeof (AssemblyDesc));
-       cd->assembly = assembly;
-       cd->asmname = pstrdup (name);
-       cd->next = assembly_hash [slot];
-       assembly_hash [slot] = cd;
-       num_assemblies++;
-}
-
-typedef struct _BackTrace BackTrace;
-typedef struct {
-       uint64_t count;
-       BackTrace *bt;
-} CallContext;
-
-typedef struct {
-       int count;
-       int size;
-       CallContext *traces;
-} TraceDesc;
-
-typedef struct _ClassDesc ClassDesc;
-struct _ClassDesc {
-       ClassDesc *next;
-       intptr_t klass;
-       char *name;
-       intptr_t allocs;
-       uint64_t alloc_size;
-       TraceDesc traces;
-};
-
-static ClassDesc* class_hash [HASH_SIZE] = {0};
-static int num_classes = 0;
-
-static ClassDesc*
-add_class (intptr_t klass, const char *name)
-{
-       int slot = ((klass >> 2) & 0xffff) % HASH_SIZE;
-       ClassDesc *cd;
-       cd = class_hash [slot];
-       while (cd && cd->klass != klass)
-               cd = cd->next;
-       /* we resolved an unknown class (unless we had the code unloaded) */
-       if (cd) {
-               /*printf ("resolved unknown: %s\n", name);*/
-               g_free (cd->name);
-               cd->name = pstrdup (name);
-               return cd;
-       }
-       cd = (ClassDesc *)calloc (sizeof (ClassDesc), 1);
-       cd->klass = klass;
-       cd->name = pstrdup (name);
-       cd->next = class_hash [slot];
-       cd->allocs = 0;
-       cd->alloc_size = 0;
-       cd->traces.count = 0;
-       cd->traces.size = 0;
-       cd->traces.traces = NULL;
-       class_hash [slot] = cd;
-       num_classes++;
-       return cd;
-}
-
-static ClassDesc *
-lookup_class (intptr_t klass)
-{
-       int slot = ((klass >> 2) & 0xffff) % HASH_SIZE;
-       ClassDesc *cd = class_hash [slot];
-       while (cd && cd->klass != klass)
-               cd = cd->next;
-       if (!cd) {
-               char buf [128];
-               snprintf (buf, sizeof (buf), "unresolved class %p", (void*)klass);
-               return add_class (klass, buf);
-       }
-       return cd;
-}
-
-typedef struct _MethodDesc MethodDesc;
-struct _MethodDesc {
-       MethodDesc *next;
-       intptr_t method;
-       char *name;
-       intptr_t code;
-       int len;
-       int recurse_count;
-       int sample_hits;
-       int ignore_jit; /* when this is set, we collect the metadata but don't count this method fot jit time and code size, when filtering events */
-       uint64_t calls;
-       uint64_t total_time;
-       uint64_t callee_time;
-       uint64_t self_time;
-       TraceDesc traces;
-};
-
-static MethodDesc* method_hash [HASH_SIZE] = {0};
-static int num_methods = 0;
-
-static MethodDesc*
-add_method (intptr_t method, const char *name, intptr_t code, int len)
-{
-       int slot = ((method >> 2) & 0xffff) % HASH_SIZE;
-       MethodDesc *cd;
-       cd = method_hash [slot];
-       while (cd && cd->method != method)
-               cd = cd->next;
-       /* we resolved an unknown method (unless we had the code unloaded) */
-       if (cd) {
-               cd->code = code;
-               cd->len = len;
-               /*printf ("resolved unknown: %s\n", name);*/
-               g_free (cd->name);
-               cd->name = pstrdup (name);
-               return cd;
-       }
-       cd = (MethodDesc *)calloc (sizeof (MethodDesc), 1);
-       cd->method = method;
-       cd->name = pstrdup (name);
-       cd->code = code;
-       cd->len = len;
-       cd->calls = 0;
-       cd->total_time = 0;
-       cd->traces.count = 0;
-       cd->traces.size = 0;
-       cd->traces.traces = NULL;
-       cd->next = method_hash [slot];
-       method_hash [slot] = cd;
-       num_methods++;
-       return cd;
-}
-
-static MethodDesc *
-lookup_method (intptr_t method)
-{
-       int slot = ((method >> 2) & 0xffff) % HASH_SIZE;
-       MethodDesc *cd = method_hash [slot];
-       while (cd && cd->method != method)
-               cd = cd->next;
-       if (!cd) {
-               char buf [128];
-               snprintf (buf, sizeof (buf), "unknown method %p", (void*)method);
-               return add_method (method, buf, 0, 0);
-       }
-       return cd;
-}
-
-static int num_stat_samples = 0;
-static int size_stat_samples = 0;
-uintptr_t *stat_samples = NULL;
-int *stat_sample_desc = NULL;
-
-static void
-add_stat_sample (int type, uintptr_t ip) {
-       if (num_stat_samples == size_stat_samples) {
-               size_stat_samples *= 2;
-               if (!size_stat_samples)
-               size_stat_samples = 32;
-               stat_samples = (uintptr_t *)realloc (stat_samples, size_stat_samples * sizeof (uintptr_t));
-               stat_sample_desc = (int *)realloc (stat_sample_desc, size_stat_samples * sizeof (int));
-       }
-       stat_samples [num_stat_samples] = ip;
-       stat_sample_desc [num_stat_samples++] = type;
-}
-
-static MethodDesc*
-lookup_method_by_ip (uintptr_t ip)
-{
-       int i;
-       MethodDesc* m;
-       /* dumb */
-       for (i = 0; i < HASH_SIZE; ++i) {
-               m = method_hash [i];
-               while (m) {
-                       //printf ("checking %p against %p-%p\n", (void*)ip, (void*)(m->code), (void*)(m->code + m->len));
-                       if (ip >= (uintptr_t)m->code && ip < (uintptr_t)m->code + m->len) {
-                               return m;
-                       }
-                       m = m->next;
-               }
-       }
-       return NULL;
-}
-
-static int
-compare_method_samples (const void *a, const void *b)
-{
-       MethodDesc *const *A = (MethodDesc *const *)a;
-       MethodDesc *const *B = (MethodDesc *const *)b;
-       if ((*A)->sample_hits == (*B)->sample_hits)
-               return 0;
-       if ((*B)->sample_hits < (*A)->sample_hits)
-               return -1;
-       return 1;
-}
-
-typedef struct _UnmanagedSymbol UnmanagedSymbol;
-struct _UnmanagedSymbol {
-       UnmanagedSymbol *parent;
-       char *name;
-       int is_binary;
-       uintptr_t addr;
-       uintptr_t size;
-       uintptr_t sample_hits;
-};
-
-static UnmanagedSymbol **usymbols = NULL;
-static int usymbols_size = 0;
-static int usymbols_num = 0;
-
-static int
-compare_usymbol_addr (const void *a, const void *b)
-{
-       UnmanagedSymbol *const *A = (UnmanagedSymbol *const *)a;
-       UnmanagedSymbol *const *B = (UnmanagedSymbol *const *)b;
-       if ((*B)->addr == (*A)->addr)
-               return 0;
-       if ((*B)->addr > (*A)->addr)
-               return -1;
-       return 1;
-}
-
-static int
-compare_usymbol_samples (const void *a, const void *b)
-{
-       UnmanagedSymbol *const *A = (UnmanagedSymbol *const *)a;
-       UnmanagedSymbol *const *B = (UnmanagedSymbol *const *)b;
-       if ((*B)->sample_hits == (*A)->sample_hits)
-               return 0;
-       if ((*B)->sample_hits < (*A)->sample_hits)
-               return -1;
-       return 1;
-}
-
-static void
-add_unmanaged_symbol (uintptr_t addr, char *name, uintptr_t size)
-{
-       UnmanagedSymbol *sym;
-       if (usymbols_num == usymbols_size) {
-               int new_size = usymbols_size * 2;
-               if (!new_size)
-                       new_size = 16;
-               usymbols = (UnmanagedSymbol **)realloc (usymbols, sizeof (void*) * new_size);
-               usymbols_size = new_size;
-       }
-       sym = (UnmanagedSymbol *)calloc (sizeof (UnmanagedSymbol), 1);
-       sym->addr = addr;
-       sym->name = name;
-       sym->size = size;
-       usymbols [usymbols_num++] = sym;
-}
-
-/* only valid after the symbols are sorted */
-static UnmanagedSymbol*
-lookup_unmanaged_symbol (uintptr_t addr)
-{
-       int r = usymbols_num - 1;
-       int l = 0;
-       UnmanagedSymbol *sym;
-       int last_best = -1;
-       while (r >= l) {
-               int m = (l + r) / 2;
-               sym = usymbols [m];
-               if (addr == sym->addr)
-                       return sym;
-               if (addr < sym->addr) {
-                       r = m - 1;
-               } else if (addr > sym->addr) {
-                       l = m + 1;
-                       last_best = m;
-               }
-       }
-       if (last_best >= 0 && (addr - usymbols [last_best]->addr) < 4096)
-               return usymbols [last_best];
-       return NULL;
-}
-
-/* we use the same structure for binaries */
-static UnmanagedSymbol **ubinaries = NULL;
-static int ubinaries_size = 0;
-static int ubinaries_num = 0;
-
-static void
-add_unmanaged_binary (uintptr_t addr, char *name, uintptr_t size)
-{
-       UnmanagedSymbol *sym;
-       if (ubinaries_num == ubinaries_size) {
-               int new_size = ubinaries_size * 2;
-               if (!new_size)
-                       new_size = 16;
-               ubinaries = (UnmanagedSymbol **)realloc (ubinaries, sizeof (void*) * new_size);
-               ubinaries_size = new_size;
-       }
-       sym = (UnmanagedSymbol *)calloc (sizeof (UnmanagedSymbol), 1);
-       sym->addr = addr;
-       sym->name = name;
-       sym->size = size;
-       sym->is_binary = 1;
-       ubinaries [ubinaries_num++] = sym;
-}
-
-static UnmanagedSymbol*
-lookup_unmanaged_binary (uintptr_t addr)
-{
-       int i;
-       for (i = 0; i < ubinaries_num; ++i) {
-               UnmanagedSymbol *ubin = ubinaries [i];
-               if (addr >= ubin->addr && addr < ubin->addr + ubin->size) {
-                       return ubin;
-               }
-       }
-       return NULL;
-}
-
-static const char*
-sample_type_name (int type)
-{
-       switch (type) {
-       case SAMPLE_CYCLES: return "cycles";
-       case SAMPLE_INSTRUCTIONS: return "instructions retired";
-       case SAMPLE_CACHE_MISSES: return "cache misses";
-       case SAMPLE_CACHE_REFS: return "cache references";
-       case SAMPLE_BRANCHES: return "executed branches";
-       case SAMPLE_BRANCH_MISSES: return "unpredicted branches";
-       }
-       return "unknown";
-}
-
-static void
-set_usym_parent (UnmanagedSymbol** cachedus, int count)
-{
-       int i;
-       for (i = 0; i < count; ++i) {
-               UnmanagedSymbol *ubin = lookup_unmanaged_binary (cachedus [i]->addr);
-               if (ubin == cachedus [i])
-                       continue;
-               cachedus [i]->parent = ubin;
-       }
-}
-
-static void
-print_usym (UnmanagedSymbol* um)
-{
-       if (um->parent)
-               fprintf (outfile, "\t%6zd %6.2f %-36s in %s\n", um->sample_hits, um->sample_hits*100.0/num_stat_samples, um->name, um->parent->name);
-       else
-               fprintf (outfile, "\t%6zd %6.2f %s\n", um->sample_hits, um->sample_hits*100.0/num_stat_samples, um->name);
-}
-
-static int
-sym_percent (uintptr_t sample_hits)
-{
-       double pc;
-       if (verbose)
-               return 1;
-       pc = sample_hits*100.0/num_stat_samples;
-       return pc >= 0.1;
-}
-
-static void
-dump_samples (void)
-{
-       int i, u;
-       int count = 0, msize = 0;
-       int unmanaged_hits = 0;
-       int unresolved_hits = 0;
-       MethodDesc** cachedm = NULL;
-       int ucount = 0, usize = 0;
-       UnmanagedSymbol** cachedus = NULL;
-       if (!num_stat_samples)
-               return;
-       qsort (usymbols, usymbols_num, sizeof (UnmanagedSymbol*), compare_usymbol_addr);
-       for (i = 0; i < num_stat_samples; ++i) {
-               MethodDesc *m = lookup_method_by_ip (stat_samples [i]);
-               if (m) {
-                       if (!m->sample_hits) {
-                               if (count == msize) {
-                                       msize *= 2;
-                                       if (!msize)
-                                               msize = 4;
-                                       cachedm = (MethodDesc **)realloc (cachedm, sizeof (void*) * msize);
-                               }
-                               cachedm [count++] = m;
-                       }
-                       m->sample_hits++;
-               } else {
-                       UnmanagedSymbol *usym = lookup_unmanaged_symbol (stat_samples [i]);
-                       if (!usym) {
-                               unresolved_hits++;
-                               //printf ("unmanaged hit at %p\n", (void*)stat_samples [i]);
-                               usym = lookup_unmanaged_binary (stat_samples [i]);
-                       }
-                       if (usym) {
-                               if (!usym->sample_hits) {
-                                       if (ucount == usize) {
-                                               usize *= 2;
-                                               if (!usize)
-                                                       usize = 4;
-                                               cachedus = (UnmanagedSymbol **)realloc (cachedus, sizeof (void*) * usize);
-                                       }
-                                       cachedus [ucount++] = usym;
-                               }
-                               usym->sample_hits++;
-                       }
-                       unmanaged_hits++;
-               }
-       }
-       qsort (cachedm, count, sizeof (MethodDesc*), compare_method_samples);
-       qsort (cachedus, ucount, sizeof (UnmanagedSymbol*), compare_usymbol_samples);
-       set_usym_parent (cachedus, ucount);
-       fprintf (outfile, "\nStatistical samples summary\n");
-       fprintf (outfile, "\tSample type: %s\n", sample_type_name (stat_sample_desc [0]));
-       fprintf (outfile, "\tUnmanaged hits:  %6d (%4.1f%%)\n", unmanaged_hits, (100.0*unmanaged_hits)/num_stat_samples);
-       fprintf (outfile, "\tManaged hits:    %6d (%4.1f%%)\n", num_stat_samples - unmanaged_hits, (100.0*(num_stat_samples-unmanaged_hits))/num_stat_samples);
-       fprintf (outfile, "\tUnresolved hits: %6d (%4.1f%%)\n", unresolved_hits, (100.0*unresolved_hits)/num_stat_samples);
-       fprintf (outfile, "\t%6s %6s %s\n", "Hits", "%", "Method name");
-       i = 0;
-       u = 0;
-       while (i < count || u < ucount) {
-               if (i < count) {
-                       MethodDesc *m = cachedm [i];
-                       if (u < ucount) {
-                               UnmanagedSymbol *um = cachedus [u];
-                               if (um->sample_hits > m->sample_hits) {
-                                       if (!sym_percent (um->sample_hits))
-                                               break;
-                                       print_usym (um);
-                                       u++;
-                                       continue;
-                               }
-                       }
-                       if (!sym_percent (m->sample_hits))
-                               break;
-                       fprintf (outfile, "\t%6d %6.2f %s\n", m->sample_hits, m->sample_hits*100.0/num_stat_samples, m->name);
-                       i++;
-                       continue;
-               }
-               if (u < ucount) {
-                       UnmanagedSymbol *um = cachedus [u];
-                       if (!sym_percent (um->sample_hits))
-                               break;
-                       print_usym (um);
-                       u++;
-                       continue;
-               }
-       }
-}
-
-typedef struct _HeapClassDesc HeapClassDesc;
-typedef struct {
-       HeapClassDesc *klass;
-       uint64_t count;
-} HeapClassRevRef;
-
-struct _HeapClassDesc {
-       ClassDesc *klass;
-       int64_t count;
-       int64_t total_size;
-       HeapClassRevRef *rev_hash;
-       int rev_hash_size;
-       int rev_count;
-       uintptr_t pinned_references;
-       uintptr_t root_references;
-};
-
-static int
-add_rev_class_hashed (HeapClassRevRef *rev_hash, uintptr_t size, HeapClassDesc *hklass, uint64_t value)
-{
-       uintptr_t i;
-       uintptr_t start_pos;
-       start_pos = (hklass->klass->klass >> 2) % size;
-       assert (start_pos < size);
-       i = start_pos;
-       do {
-               if (rev_hash [i].klass == hklass) {
-                       rev_hash [i].count += value;
-                       return 0;
-               } else if (!rev_hash [i].klass) {
-                       rev_hash [i].klass = hklass;
-                       rev_hash [i].count += value;
-                       start_pos = 0;
-                       for (i = 0; i < size; ++i)
-                               if (rev_hash [i].klass && rev_hash [i].klass->klass == hklass->klass)
-                                       start_pos ++;
-                       assert (start_pos == 1);
-                       return 1;
-               }
-               /* wrap around */
-               if (++i == size)
-                       i = 0;
-       } while (i != start_pos);
-       /* should not happen */
-       printf ("failed revref store\n");
-       return 0;
-}
-
-static void
-add_heap_class_rev (HeapClassDesc *from, HeapClassDesc *to)
-{
-       uintptr_t i;
-       if (to->rev_count * 2 >= to->rev_hash_size) {
-               HeapClassRevRef *n;
-               uintptr_t old_size = to->rev_hash_size;
-               to->rev_hash_size *= 2;
-               if (to->rev_hash_size == 0)
-                       to->rev_hash_size = 4;
-               n = (HeapClassRevRef *)calloc (sizeof (HeapClassRevRef) * to->rev_hash_size, 1);
-               for (i = 0; i < old_size; ++i) {
-                       if (to->rev_hash [i].klass)
-                               add_rev_class_hashed (n, to->rev_hash_size, to->rev_hash [i].klass, to->rev_hash [i].count);
-               }
-               if (to->rev_hash)
-                       g_free (to->rev_hash);
-               to->rev_hash = n;
-       }
-       to->rev_count += add_rev_class_hashed (to->rev_hash, to->rev_hash_size, from, 1);
-}
-
-typedef struct {
-       uintptr_t objaddr;
-       HeapClassDesc *hklass;
-       uintptr_t num_refs;
-       uintptr_t refs [0];
-} HeapObjectDesc;
-
-typedef struct _HeapShot HeapShot;
-struct _HeapShot {
-       HeapShot *next;
-       uint64_t timestamp;
-       int class_count;
-       int hash_size;
-       HeapClassDesc **class_hash;
-       HeapClassDesc **sorted;
-       HeapObjectDesc **objects_hash;
-       uintptr_t objects_count;
-       uintptr_t objects_hash_size;
-       uintptr_t num_roots;
-       uintptr_t *roots;
-       uintptr_t *roots_extra;
-       int *roots_types;
-};
-
-static HeapShot *heap_shots = NULL;
-static int num_heap_shots = 0;
-
-static HeapShot*
-new_heap_shot (uint64_t timestamp)
-{
-       HeapShot *hs = (HeapShot *)calloc (sizeof (HeapShot), 1);
-       hs->hash_size = 4;
-       hs->class_hash = (HeapClassDesc **)calloc (sizeof (void*), hs->hash_size);
-       hs->timestamp = timestamp;
-       num_heap_shots++;
-       hs->next = heap_shots;
-       heap_shots = hs;
-       return hs;
-}
-
-static HeapClassDesc*
-heap_class_lookup (HeapShot *hs, ClassDesc *klass)
-{
-       int i;
-       unsigned int start_pos;
-       start_pos = ((uintptr_t)klass->klass >> 2) % hs->hash_size;
-       i = start_pos;
-       do {
-               HeapClassDesc* cd = hs->class_hash [i];
-               if (!cd)
-                       return NULL;
-               if (cd->klass == klass)
-                       return cd;
-               /* wrap around */
-               if (++i == hs->hash_size)
-                       i = 0;
-       } while (i != start_pos);
-       return NULL;
-}
-
-static int
-add_heap_hashed (HeapClassDesc **hash, HeapClassDesc **retv, uintptr_t hsize, ClassDesc *klass, uint64_t size, uint64_t count)
-{
-       uintptr_t i;
-       uintptr_t start_pos;
-       start_pos = ((uintptr_t)klass->klass >> 2) % hsize;
-       i = start_pos;
-       do {
-               if (hash [i] && hash [i]->klass == klass) {
-                       hash [i]->total_size += size;
-                       hash [i]->count += count;
-                       *retv = hash [i];
-                       return 0;
-               } else if (!hash [i]) {
-                       if (*retv) {
-                               hash [i] = *retv;
-                               return 1;
-                       }
-                       hash [i] = (HeapClassDesc *)calloc (sizeof (HeapClassDesc), 1);
-                       hash [i]->klass = klass;
-                       hash [i]->total_size += size;
-                       hash [i]->count += count;
-                       *retv = hash [i];
-                       return 1;
-               }
-               /* wrap around */
-               if (++i == hsize)
-                       i = 0;
-       } while (i != start_pos);
-       /* should not happen */
-       printf ("failed heap class store\n");
-       return 0;
-}
-
-static HeapClassDesc*
-add_heap_shot_class (HeapShot *hs, ClassDesc *klass, uint64_t size)
-{
-       HeapClassDesc *res;
-       int i;
-       if (hs->class_count * 2 >= hs->hash_size) {
-               HeapClassDesc **n;
-               int old_size = hs->hash_size;
-               hs->hash_size *= 2;
-               if (hs->hash_size == 0)
-                       hs->hash_size = 4;
-               n = (HeapClassDesc **)calloc (sizeof (void*) * hs->hash_size, 1);
-               for (i = 0; i < old_size; ++i) {
-                       res = hs->class_hash [i];
-                       if (hs->class_hash [i])
-                               add_heap_hashed (n, &res, hs->hash_size, hs->class_hash [i]->klass, hs->class_hash [i]->total_size, hs->class_hash [i]->count);
-               }
-               if (hs->class_hash)
-                       g_free (hs->class_hash);
-               hs->class_hash = n;
-       }
-       res = NULL;
-       hs->class_count += add_heap_hashed (hs->class_hash, &res, hs->hash_size, klass, size, 1);
-       //if (res->count == 1)
-       //      printf ("added heap class: %s\n", res->klass->name);
-       return res;
-}
-
-static HeapObjectDesc*
-alloc_heap_obj (uintptr_t objaddr, HeapClassDesc *hklass, uintptr_t num_refs)
-{
-       HeapObjectDesc* ho = (HeapObjectDesc *)calloc (sizeof (HeapObjectDesc) + num_refs * sizeof (uintptr_t), 1);
-       ho->objaddr = objaddr;
-       ho->hklass = hklass;
-       ho->num_refs = num_refs;
-       return ho;
-}
-
-static uintptr_t
-heap_shot_find_obj_slot (HeapShot *hs, uintptr_t objaddr)
-{
-       uintptr_t i;
-       uintptr_t start_pos;
-       HeapObjectDesc **hash = hs->objects_hash;
-       start_pos = ((uintptr_t)objaddr >> 3) % hs->objects_hash_size;
-       i = start_pos;
-       do {
-               if (hash [i] && hash [i]->objaddr == objaddr) {
-                       return i;
-               } else if (!hash [i]) {
-                       break; /* fail */
-               }
-               /* wrap around */
-               if (++i == hs->objects_hash_size)
-                       i = 0;
-       } while (i != start_pos);
-       /* should not happen */
-       //printf ("failed heap obj slot\n");
-       return -1;
-}
-
-static HeapObjectDesc*
-heap_shot_obj_add_refs (HeapShot *hs, uintptr_t objaddr, uintptr_t num, uintptr_t *ref_offset)
-{
-       HeapObjectDesc **hash = hs->objects_hash;
-       uintptr_t i = heap_shot_find_obj_slot (hs, objaddr);
-       if (i >= 0) {
-               HeapObjectDesc* ho = alloc_heap_obj (objaddr, hash [i]->hklass, hash [i]->num_refs + num);
-               *ref_offset = hash [i]->num_refs;
-               memcpy (ho->refs, hash [i]->refs, hash [i]->num_refs * sizeof (uintptr_t));
-               g_free (hash [i]);
-               hash [i] = ho;
-               return ho;
-       }
-       /* should not happen */
-       printf ("failed heap obj update\n");
-       return NULL;
-
-}
-
-static uintptr_t
-add_heap_hashed_obj (HeapObjectDesc **hash, uintptr_t hsize, HeapObjectDesc *obj)
-{
-       uintptr_t i;
-       uintptr_t start_pos;
-       start_pos = ((uintptr_t)obj->objaddr >> 3) % hsize;
-       i = start_pos;
-       do {
-               if (hash [i] && hash [i]->objaddr == obj->objaddr) {
-                       printf ("duplicate object!\n");
-                       return 0;
-               } else if (!hash [i]) {
-                       hash [i] = obj;
-                       return 1;
-               }
-               /* wrap around */
-               if (++i == hsize)
-                       i = 0;
-       } while (i != start_pos);
-       /* should not happen */
-       printf ("failed heap obj store\n");
-       return 0;
-}
-
-static void
-add_heap_shot_obj (HeapShot *hs, HeapObjectDesc *obj)
-{
-       uintptr_t i;
-       if (hs->objects_count * 2 >= hs->objects_hash_size) {
-               HeapObjectDesc **n;
-               uintptr_t old_size = hs->objects_hash_size;
-               hs->objects_hash_size *= 2;
-               if (hs->objects_hash_size == 0)
-                       hs->objects_hash_size = 4;
-               n = (HeapObjectDesc **)calloc (sizeof (void*) * hs->objects_hash_size, 1);
-               for (i = 0; i < old_size; ++i) {
-                       if (hs->objects_hash [i])
-                               add_heap_hashed_obj (n, hs->objects_hash_size, hs->objects_hash [i]);
-               }
-               if (hs->objects_hash)
-                       g_free (hs->objects_hash);
-               hs->objects_hash = n;
-       }
-       hs->objects_count += add_heap_hashed_obj (hs->objects_hash, hs->objects_hash_size, obj);
-}
-
-static void
-heap_shot_resolve_reverse_refs (HeapShot *hs)
-{
-       uintptr_t i;
-       for (i = 0; i < hs->objects_hash_size; ++i) {
-               uintptr_t r;
-               HeapObjectDesc *ho = hs->objects_hash [i];
-               if (!ho)
-                       continue;
-               for (r = 0; r < ho->num_refs; ++r) {
-                       uintptr_t oi = heap_shot_find_obj_slot (hs, ho->refs [r]);
-                       add_heap_class_rev (ho->hklass, hs->objects_hash [oi]->hklass);
-               }
-       }
-}
-
-#define MARK_GRAY 1
-#define MARK_BLACK 2
-
-static void
-heap_shot_mark_objects (HeapShot *hs)
-{
-       uintptr_t i, oi, r;
-       unsigned char *marks;
-       HeapObjectDesc *obj, *ref;
-       int marked_some;
-       uintptr_t num_marked = 0, num_unmarked;
-       for (i = 0; i < hs->num_roots; ++i) {
-               HeapClassDesc *cd;
-               oi = heap_shot_find_obj_slot (hs, hs->roots [i]);
-               if (oi == -1) {
-                       continue;
-               }
-               obj = hs->objects_hash [oi];
-               cd = obj->hklass;
-               if (hs->roots_types [i] & MONO_PROFILE_GC_ROOT_PINNING)
-                       cd->pinned_references++;
-               cd->root_references++;
-       }
-       if (!debug)
-               return;
-       /* consistency checks: it seems not all the objects are walked in the heap in some cases */
-       marks = (unsigned char *)calloc (hs->objects_hash_size, 1);
-       if (!marks)
-               return;
-       for (i = 0; i < hs->num_roots; ++i) {
-               oi = heap_shot_find_obj_slot (hs, hs->roots [i]);
-               if (oi == -1) {
-                       fprintf (outfile, "root type 0x%x for obj %p (%s) not found in heap\n", hs->roots_types [i], (void*)hs->roots [i], lookup_class (hs->roots_extra [i])->name);
-                       continue;
-               }
-               obj = hs->objects_hash [oi];
-               if (!marks [oi]) {
-                       marks [oi] = obj->num_refs? MARK_GRAY: MARK_BLACK;
-                       num_marked++;
-               }
-       }
-       marked_some = 1;
-       while (marked_some) {
-               marked_some = 0;
-               for (i = 0; i < hs->objects_hash_size; ++i) {
-                       if (marks [i] != MARK_GRAY)
-                               continue;
-                       marks [i] = MARK_BLACK;
-                       obj = hs->objects_hash [i];
-                       for (r = 0; r < obj->num_refs; ++r) {
-                               oi = heap_shot_find_obj_slot (hs, obj->refs [r]);
-                               if (oi == -1) {
-                                       fprintf (outfile, "referenced obj %p not found in heap\n", (void*)obj->refs [r]);
-                                       continue;
-                               }
-                               ref = hs->objects_hash [oi];
-                               if (!marks [oi]) {
-                                       marks [oi] = ref->num_refs? MARK_GRAY: MARK_BLACK;
-                               }
-                       }
-                       marked_some++;
-               }
-       }
-
-       num_unmarked = 0;
-       for (i = 0; i < hs->objects_hash_size; ++i) {
-               if (hs->objects_hash [i] && !marks [i]) {
-                       num_unmarked++;
-                       fprintf (outfile, "object %p (%s) unmarked\n", (void*)hs->objects_hash [i], hs->objects_hash [i]->hklass->klass->name);
-               }
-       }
-       fprintf (outfile, "Total unmarked: %zd/%zd\n", num_unmarked, hs->objects_count);
-       g_free (marks);
-}
-
-static void
-heap_shot_free_objects (HeapShot *hs)
-{
-       uintptr_t i;
-       for (i = 0; i < hs->objects_hash_size; ++i) {
-               HeapObjectDesc *ho = hs->objects_hash [i];
-               if (ho)
-                       g_free (ho);
-       }
-       if (hs->objects_hash)
-               g_free (hs->objects_hash);
-       hs->objects_hash = NULL;
-       hs->objects_hash_size = 0;
-       hs->objects_count = 0;
-}
-
-
-struct _BackTrace {
-       BackTrace *next;
-       unsigned int hash;
-       int count;
-       int id;
-       MethodDesc *methods [1];
-};
-
-static BackTrace *backtrace_hash [HASH_SIZE];
-static BackTrace **backtraces = NULL;
-static int num_backtraces = 0;
-static int next_backtrace = 0;
-
-static int
-hash_backtrace (int count, MethodDesc **methods)
-{
-       int hash = count;
-       int i;
-       for (i = 0; i < count; ++i) {
-               hash = (hash << 5) - hash + methods [i]->method;
-       }
-       return hash;
-}
-
-static int
-compare_backtrace (BackTrace *bt, int count, MethodDesc **methods)
-{
-       int i;
-       if (bt->count != count)
-               return 0;
-       for (i = 0; i < count; ++i)
-               if (methods [i] != bt->methods [i])
-                       return 0;
-       return 1;
-}
-
-static BackTrace*
-add_backtrace (int count, MethodDesc **methods)
-{
-       int hash = hash_backtrace (count, methods);
-       int slot = (hash & 0xffff) % HASH_SIZE;
-       BackTrace *bt = backtrace_hash [slot];
-       while (bt) {
-               if (bt->hash == hash && compare_backtrace (bt, count, methods))
-                       return bt;
-               bt = bt->next;
-       }
-       bt = (BackTrace *)malloc (sizeof (BackTrace) + ((count - 1) * sizeof (void*)));
-       bt->next = backtrace_hash [slot];
-       backtrace_hash [slot] = bt;
-       if (next_backtrace == num_backtraces) {
-               num_backtraces *= 2;
-               if (!num_backtraces)
-                       num_backtraces = 16;
-               backtraces = (BackTrace **)realloc (backtraces, sizeof (void*) * num_backtraces);
-       }
-       bt->id = next_backtrace++;
-       backtraces [bt->id] = bt;
-       bt->count = count;
-       bt->hash = hash;
-       for (slot = 0; slot < count; ++slot)
-               bt->methods [slot] = methods [slot];
-
-       return bt;
-}
-
-typedef struct _MonitorDesc MonitorDesc;
-typedef struct _ThreadContext ThreadContext;
-typedef struct _DomainContext DomainContext;
-typedef struct _RemCtxContext RemCtxContext;
-
-typedef struct {
-       FILE *file;
-#if defined (HAVE_SYS_ZLIB)
-       gzFile gzfile;
-#endif
-       unsigned char *buf;
-       int size;
-       int data_version;
-       int version_major;
-       int version_minor;
-       int timer_overhead;
-       int pid;
-       int port;
-       char *args;
-       char *arch;
-       char *os;
-       uint64_t startup_time;
-       ThreadContext *threads;
-       ThreadContext *current_thread;
-       DomainContext *domains;
-       DomainContext *current_domain;
-       RemCtxContext *remctxs;
-       RemCtxContext *current_remctx;
-} ProfContext;
-
-struct _ThreadContext {
-       ThreadContext *next;
-       intptr_t thread_id;
-       char *name;
-       /* emulated stack */
-       MethodDesc **stack;
-       uint64_t *time_stack;
-       uint64_t *callee_time_stack;
-       uint64_t last_time;
-       uint64_t contention_start;
-       MonitorDesc *monitor;
-       int stack_size;
-       int stack_id;
-       HeapShot *current_heap_shot;
-       uintptr_t num_roots;
-       uintptr_t size_roots;
-       uintptr_t *roots;
-       uintptr_t *roots_extra;
-       int *roots_types;
-       uint64_t gc_start_times [3];
-};
-
-struct _DomainContext {
-       DomainContext *next;
-       intptr_t domain_id;
-       const char *friendly_name;
-};
-
-struct _RemCtxContext {
-       RemCtxContext *next;
-       intptr_t remctx_id;
-       intptr_t domain_id;
-};
-
-static void
-ensure_buffer (ProfContext *ctx, int size)
-{
-       if (ctx->size < size) {
-               ctx->buf = (unsigned char *)realloc (ctx->buf, size);
-               ctx->size = size;
-       }
-}
-
-static int
-load_data (ProfContext *ctx, int size)
-{
-       ensure_buffer (ctx, size);
-#if defined (HAVE_SYS_ZLIB)
-       if (ctx->gzfile) {
-               int r = gzread (ctx->gzfile, ctx->buf, size);
-               if (r == 0)
-                       return size == 0? 1: 0;
-               return r == size;
-       } else
-#endif
-       {
-               int r = fread (ctx->buf, size, 1, ctx->file);
-               if (r == 0)
-                       return size == 0? 1: 0;
-               return r;
-       }
-}
-
-static ThreadContext*
-get_thread (ProfContext *ctx, intptr_t thread_id)
-{
-       ThreadContext *thread;
-       if (ctx->current_thread && ctx->current_thread->thread_id == thread_id)
-               return ctx->current_thread;
-       thread = ctx->threads;
-       while (thread) {
-               if (thread->thread_id == thread_id) {
-                       return thread;
-               }
-               thread = thread->next;
-       }
-       thread = (ThreadContext *)calloc (sizeof (ThreadContext), 1);
-       thread->next = ctx->threads;
-       ctx->threads = thread;
-       thread->thread_id = thread_id;
-       thread->last_time = 0;
-       thread->stack_id = 0;
-       thread->stack_size = 32;
-       thread->stack = (MethodDesc **)malloc (thread->stack_size * sizeof (void*));
-       thread->time_stack = (uint64_t *)malloc (thread->stack_size * sizeof (uint64_t));
-       thread->callee_time_stack = (uint64_t *)malloc (thread->stack_size * sizeof (uint64_t));
-       return thread;
-}
-
-static DomainContext *
-get_domain (ProfContext *ctx, intptr_t domain_id)
-{
-       if (ctx->current_domain && ctx->current_domain->domain_id == domain_id)
-               return ctx->current_domain;
-
-       DomainContext *domain = ctx->domains;
-
-       while (domain) {
-               if (domain->domain_id == domain_id)
-                       return domain;
-
-               domain = domain->next;
-       }
-
-       domain = (DomainContext *)calloc (sizeof (DomainContext), 1);
-       domain->next = ctx->domains;
-       ctx->domains = domain;
-       domain->domain_id = domain_id;
-
-       return domain;
-}
-
-static RemCtxContext *
-get_remctx (ProfContext *ctx, intptr_t remctx_id)
-{
-       if (ctx->current_remctx && ctx->current_remctx->remctx_id == remctx_id)
-               return ctx->current_remctx;
-
-       RemCtxContext *remctx = ctx->remctxs;
-
-       while (remctx) {
-               if (remctx->remctx_id == remctx_id)
-                       return remctx;
-
-               remctx = remctx->next;
-       }
-
-       remctx = (RemCtxContext *)calloc (sizeof (RemCtxContext), 1);
-       remctx->next = ctx->remctxs;
-       ctx->remctxs = remctx;
-       remctx->remctx_id = remctx_id;
-
-       return remctx;
-}
-
-static ThreadContext*
-load_thread (ProfContext *ctx, intptr_t thread_id)
-{
-       ThreadContext *thread = get_thread (ctx, thread_id);
-       ctx->current_thread = thread;
-       return thread;
-}
-
-static void
-ensure_thread_stack (ThreadContext *thread)
-{
-       if (thread->stack_id == thread->stack_size) {
-               thread->stack_size *= 2;
-               thread->stack = (MethodDesc **)realloc (thread->stack, thread->stack_size * sizeof (void*));
-               thread->time_stack = (uint64_t *)realloc (thread->time_stack, thread->stack_size * sizeof (uint64_t));
-               thread->callee_time_stack = (uint64_t *)realloc (thread->callee_time_stack, thread->stack_size * sizeof (uint64_t));
-       }
-}
-
-static int
-add_trace_hashed (CallContext *traces, int size, BackTrace *bt, uint64_t value)
-{
-       int i;
-       unsigned int start_pos;
-       start_pos = bt->hash % size;
-       i = start_pos;
-       do {
-               if (traces [i].bt == bt) {
-                       traces [i].count += value;
-                       return 0;
-               } else if (!traces [i].bt) {
-                       traces [i].bt = bt;
-                       traces [i].count += value;
-                       return 1;
-               }
-               /* wrap around */
-               if (++i == size)
-                       i = 0;
-       } while (i != start_pos);
-       /* should not happen */
-       printf ("failed trace store\n");
-       return 0;
-}
-
-static void
-add_trace_bt (BackTrace *bt, TraceDesc *trace, uint64_t value)
-{
-       int i;
-       if (!collect_traces)
-               return;
-       if (trace->count * 2 >= trace->size) {
-               CallContext *n;
-               int old_size = trace->size;
-               trace->size *= 2;
-               if (trace->size == 0)
-                       trace->size = 4;
-               n = (CallContext *)calloc (sizeof (CallContext) * trace->size, 1);
-               for (i = 0; i < old_size; ++i) {
-                       if (trace->traces [i].bt)
-                               add_trace_hashed (n, trace->size, trace->traces [i].bt, trace->traces [i].count);
-               }
-               if (trace->traces)
-                       g_free (trace->traces);
-               trace->traces = n;
-       }
-       trace->count += add_trace_hashed (trace->traces, trace->size, bt, value);
-}
-
-static BackTrace*
-add_trace_thread (ThreadContext *thread, TraceDesc *trace, uint64_t value)
-{
-       BackTrace *bt;
-       int count = thread->stack_id;
-       if (!collect_traces)
-               return NULL;
-       if (count > trace_max)
-               count = trace_max;
-       bt = add_backtrace (count, thread->stack + thread->stack_id - count);
-       add_trace_bt (bt, trace, value);
-       return bt;
-}
-
-static BackTrace*
-add_trace_methods (MethodDesc **methods, int count, TraceDesc *trace, uint64_t value)
-{
-       BackTrace *bt;
-       if (!collect_traces)
-               return NULL;
-       if (count > trace_max)
-               count = trace_max;
-       bt = add_backtrace (count, methods);
-       add_trace_bt (bt, trace, value);
-       return bt;
-}
-
-static void
-thread_add_root (ThreadContext *ctx, uintptr_t obj, int root_type, uintptr_t extra_info)
-{
-       if (ctx->num_roots == ctx->size_roots) {
-               int new_size = ctx->size_roots * 2;
-               if (!new_size)
-                       new_size = 4;
-               ctx->roots = (uintptr_t *)realloc (ctx->roots, new_size * sizeof (uintptr_t));
-               ctx->roots_extra = (uintptr_t *)realloc (ctx->roots_extra, new_size * sizeof (uintptr_t));
-               ctx->roots_types = (int *)realloc (ctx->roots_types, new_size * sizeof (int));
-               ctx->size_roots = new_size;
-       }
-       ctx->roots_types [ctx->num_roots] = root_type;
-       ctx->roots_extra [ctx->num_roots] = extra_info;
-       ctx->roots [ctx->num_roots++] = obj;
-}
-
-static int
-compare_callc (const void *a, const void *b)
-{
-       const CallContext *A = (const CallContext *)a;
-       const CallContext *B = (const CallContext *)b;
-       if (B->count == A->count)
-               return 0;
-       if (B->count < A->count)
-               return -1;
-       return 1;
-}
-
-static void
-sort_context_array (TraceDesc* traces)
-{
-       int i, j;
-       for (i = 0, j = 0; i < traces->size; ++i) {
-               if (traces->traces [i].bt) {
-                       traces->traces [j].bt = traces->traces [i].bt;
-                       traces->traces [j].count = traces->traces [i].count;
-                       j++;
-               }
-       }
-       qsort (traces->traces, traces->count, sizeof (CallContext), compare_callc);
-}
-
-static void
-push_method (ThreadContext *thread, MethodDesc *method, uint64_t timestamp)
-{
-       ensure_thread_stack (thread);
-       thread->time_stack [thread->stack_id] = timestamp;
-       thread->callee_time_stack [thread->stack_id] = 0;
-       thread->stack [thread->stack_id++] = method;
-       method->recurse_count++;
-}
-
-static void
-pop_method (ThreadContext *thread, MethodDesc *method, uint64_t timestamp)
-{
-       method->recurse_count--;
-       if (thread->stack_id > 0 && thread->stack [thread->stack_id - 1] == method) {
-               uint64_t tdiff;
-               thread->stack_id--;
-               method->calls++;
-               if (timestamp < thread->time_stack [thread->stack_id])
-                       fprintf (outfile, "time went backwards for %s\n", method->name);
-               tdiff = timestamp - thread->time_stack [thread->stack_id];
-               if (thread->callee_time_stack [thread->stack_id] > tdiff)
-                       fprintf (outfile, "callee time bigger for %s\n", method->name);
-               method->self_time += tdiff - thread->callee_time_stack [thread->stack_id];
-               method->callee_time += thread->callee_time_stack [thread->stack_id];
-               if (thread->stack_id)
-                       thread->callee_time_stack [thread->stack_id - 1] += tdiff;
-               //fprintf (outfile, "method %s took %d\n", method->name, (int)(tdiff/1000));
-       } else {
-               fprintf (outfile, "unmatched leave at stack pos: %d for method %s\n", thread->stack_id, method->name);
-       }
-}
-
-typedef struct {
-       uint64_t total_time;
-       uint64_t max_time;
-       int count;
-} GCDesc;
-static GCDesc gc_info [3];
-static uint64_t max_heap_size;
-static uint64_t gc_object_moves;
-static int gc_resizes;
-typedef struct {
-       uint64_t created;
-       uint64_t destroyed;
-       uint64_t live;
-       uint64_t max_live;
-       TraceDesc traces;
-       TraceDesc destroy_traces;
-} HandleInfo;
-static HandleInfo handle_info [4];
-
-static const char*
-gc_event_name (int ev)
-{
-       switch (ev) {
-       case MONO_GC_EVENT_START: return "start";
-       case MONO_GC_EVENT_MARK_START: return "mark start";
-       case MONO_GC_EVENT_MARK_END: return "mark end";
-       case MONO_GC_EVENT_RECLAIM_START: return "reclaim start";
-       case MONO_GC_EVENT_RECLAIM_END: return "reclaim end";
-       case MONO_GC_EVENT_END: return "end";
-       case MONO_GC_EVENT_PRE_STOP_WORLD: return "pre stop";
-       case MONO_GC_EVENT_PRE_STOP_WORLD_LOCKED: return "pre stop lock";
-       case MONO_GC_EVENT_POST_STOP_WORLD: return "post stop";
-       case MONO_GC_EVENT_PRE_START_WORLD: return "pre start";
-       case MONO_GC_EVENT_POST_START_WORLD: return "post start";
-       case MONO_GC_EVENT_POST_START_WORLD_UNLOCKED: return "post start unlock";
-       default:
-               return "unknown";
-       }
-}
-
-static const char*
-sync_point_name (int type)
-{
-       switch (type) {
-       case SYNC_POINT_PERIODIC: return "periodic";
-       case SYNC_POINT_WORLD_STOP: return "world stop";
-       case SYNC_POINT_WORLD_START: return "world start";
-       default:
-               return "unknown";
-       }
-}
-
-static uint64_t clause_summary [MONO_EXCEPTION_CLAUSE_FAULT + 1];
-static uint64_t throw_count = 0;
-static TraceDesc exc_traces;
-
-static const char*
-clause_name (int type)
-{
-       switch (type) {
-       case MONO_EXCEPTION_CLAUSE_NONE: return "catch";
-       case MONO_EXCEPTION_CLAUSE_FILTER: return "filter";
-       case MONO_EXCEPTION_CLAUSE_FINALLY: return "finally";
-       case MONO_EXCEPTION_CLAUSE_FAULT: return "fault";
-       default: return "invalid";
-       }
-}
-
-static uint64_t monitor_contention;
-static uint64_t monitor_failed;
-static uint64_t monitor_acquired;
-
-struct _MonitorDesc {
-       MonitorDesc *next;
-       uintptr_t objid;
-       uintptr_t contentions;
-       uint64_t wait_time;
-       uint64_t max_wait_time;
-       TraceDesc traces;
-};
-
-static MonitorDesc* monitor_hash [SMALL_HASH_SIZE] = {0};
-static int num_monitors = 0;
-
-static MonitorDesc*
-lookup_monitor (uintptr_t objid)
-{
-       int slot = ((objid >> 3) & 0xffff) % SMALL_HASH_SIZE;
-       MonitorDesc *cd = monitor_hash [slot];
-       while (cd && cd->objid != objid)
-               cd = cd->next;
-       if (!cd) {
-               cd = (MonitorDesc *)calloc (sizeof (MonitorDesc), 1);
-               cd->objid = objid;
-               cd->next = monitor_hash [slot];
-               monitor_hash [slot] = cd;
-               num_monitors++;
-       }
-       return cd;
-}
-
-static const char*
-monitor_ev_name (int ev)
-{
-       switch (ev) {
-       case MONO_PROFILER_MONITOR_CONTENTION: return "contended";
-       case MONO_PROFILER_MONITOR_DONE: return "acquired";
-       case MONO_PROFILER_MONITOR_FAIL: return "not taken";
-       default: return "invalid";
-       }
-}
-
-static const char*
-get_handle_name (int htype)
-{
-       switch (htype) {
-       case 0: return "weak";
-       case 1: return "weaktrack";
-       case 2: return "normal";
-       case 3: return "pinned";
-       default: return "unknown";
-       }
-}
-
-static const char*
-get_root_name (int rtype)
-{
-       switch (rtype & MONO_PROFILE_GC_ROOT_TYPEMASK) {
-       case MONO_PROFILE_GC_ROOT_STACK: return "stack";
-       case MONO_PROFILE_GC_ROOT_FINALIZER: return "finalizer";
-       case MONO_PROFILE_GC_ROOT_HANDLE: return "handle";
-       case MONO_PROFILE_GC_ROOT_OTHER: return "other";
-       case MONO_PROFILE_GC_ROOT_MISC: return "misc";
-       default: return "unknown";
-       }
-}
-
-static MethodDesc**
-decode_bt (ProfContext *ctx, MethodDesc** sframes, int *size, unsigned char *p, unsigned char **endp, intptr_t ptr_base, intptr_t *method_base)
-{
-       MethodDesc **frames;
-       int i;
-       if (ctx->data_version < 13)
-               decode_uleb128 (p, &p); /* flags */
-       int count = decode_uleb128 (p, &p);
-       if (count > *size)
-               frames = (MethodDesc **)malloc (count * sizeof (void*));
-       else
-               frames = sframes;
-       for (i = 0; i < count; ++i) {
-               intptr_t ptrdiff = decode_sleb128 (p, &p);
-               if (ctx->data_version > 12) {
-                       *method_base += ptrdiff;
-                       frames [i] = lookup_method (*method_base);
-               } else {
-                       frames [i] = lookup_method (ptr_base + ptrdiff);
-               }
-       }
-       *size = count;
-       *endp = p;
-       return frames;
-}
-
-static void
-tracked_creation (uintptr_t obj, ClassDesc *cd, uint64_t size, BackTrace *bt, uint64_t timestamp)
-{
-       int i;
-       for (i = 0; i < num_tracked_objects; ++i) {
-               if (tracked_objects [i] != obj)
-                       continue;
-               fprintf (outfile, "Object %p created (%s, %llu bytes) at %.3f secs.\n", (void*)obj, cd->name, (unsigned long long) size, (timestamp - startup_time)/1000000000.0);
-               if (bt && bt->count) {
-                       int k;
-                       for (k = 0; k < bt->count; ++k)
-                               fprintf (outfile, "\t%s\n", bt->methods [k]->name);
-               }
-       }
-}
-
-static void
-track_handle (uintptr_t obj, int htype, uint32_t handle, BackTrace *bt, uint64_t timestamp)
-{
-       int i;
-       for (i = 0; i < num_tracked_objects; ++i) {
-               if (tracked_objects [i] != obj)
-                       continue;
-               fprintf (outfile, "Object %p referenced from handle %u at %.3f secs.\n", (void*)obj, handle, (timestamp - startup_time) / 1000000000.0);
-               if (bt && bt->count) {
-                       int k;
-                       for (k = 0; k < bt->count; ++k)
-                               fprintf (outfile, "\t%s\n", bt->methods [k]->name);
-               }
-       }
-}
-
-static void
-track_move (uintptr_t src, uintptr_t dst)
-{
-       int i;
-       for (i = 0; i < num_tracked_objects; ++i) {
-               if (tracked_objects [i] == src)
-                       fprintf (outfile, "Object %p moved to %p\n", (void*)src, (void*)dst);
-               else if (tracked_objects [i] == dst)
-                       fprintf (outfile, "Object %p moved from %p\n", (void*)dst, (void*)src);
-       }
-}
-
-static void
-track_obj_reference (uintptr_t obj, uintptr_t parent, ClassDesc *cd)
-{
-       int i;
-       for (i = 0; i < num_tracked_objects; ++i) {
-               if (tracked_objects [i] == obj)
-                       fprintf (outfile, "Object %p referenced from %p (%s).\n", (void*)obj, (void*)parent, cd->name);
-       }
-}
-
-static void
-found_object (uintptr_t obj)
-{
-       num_tracked_objects ++;
-       tracked_objects = (uintptr_t *)realloc (tracked_objects, num_tracked_objects * sizeof (tracked_objects [0]));
-       tracked_objects [num_tracked_objects - 1] = obj;
-}
-
-static int num_jit_helpers = 0;
-static int jit_helpers_code_size = 0;
-
-static const char*
-code_buffer_desc (int type)
-{
-       switch (type) {
-       case MONO_PROFILER_CODE_BUFFER_METHOD:
-               return "method";
-       case MONO_PROFILER_CODE_BUFFER_METHOD_TRAMPOLINE:
-               return "method trampoline";
-       case MONO_PROFILER_CODE_BUFFER_UNBOX_TRAMPOLINE:
-               return "unbox trampoline";
-       case MONO_PROFILER_CODE_BUFFER_IMT_TRAMPOLINE:
-               return "imt trampoline";
-       case MONO_PROFILER_CODE_BUFFER_GENERICS_TRAMPOLINE:
-               return "generics trampoline";
-       case MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE:
-               return "specific trampoline";
-       case MONO_PROFILER_CODE_BUFFER_HELPER:
-               return "misc helper";
-       case MONO_PROFILER_CODE_BUFFER_MONITOR:
-               return "monitor/lock";
-       case MONO_PROFILER_CODE_BUFFER_DELEGATE_INVOKE:
-               return "delegate invoke";
-       case MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING:
-               return "exception handling";
-       default:
-               return "unspecified";
-       }
-}
-
-typedef struct _CoverageAssembly CoverageAssembly;
-struct _CoverageAssembly {
-       char *name;
-       char *guid;
-       char *filename;
-       int number_of_methods;
-       int fully_covered;
-       int partially_covered;
-};
-
-typedef struct _CoverageClass CoverageClass;
-struct _CoverageClass {
-       char *assembly_name;
-       char *class_name;
-       int number_of_methods;
-       int fully_covered;
-       int partially_covered;
-};
-
-typedef struct _CoverageCoverage CoverageCoverage;
-struct _CoverageCoverage {
-       int method_id;
-       int offset;
-       int count;
-       int line;
-       int column;
-};
-
-typedef struct _CoverageMethod CoverageMethod;
-struct _CoverageMethod {
-       char *assembly_name;
-       char *class_name;
-       char *method_name;
-       char *method_signature;
-       char *filename;
-       int token;
-       int n_statements;
-       int method_id;
-       GPtrArray *coverage;
-};
-static GPtrArray *coverage_assemblies = NULL;
-static GPtrArray *coverage_methods = NULL;
-static GPtrArray *coverage_statements = NULL;
-static GHashTable *coverage_methods_hash = NULL;
-static GPtrArray *coverage_classes = NULL;
-static GHashTable *coverage_assembly_classes = NULL;
-
-static void
-gather_coverage_statements (void)
-{
-       for (guint i = 0; i < coverage_statements->len; i++) {
-               CoverageCoverage *coverage = (CoverageCoverage *)coverage_statements->pdata[i];
-               CoverageMethod *method = (CoverageMethod *)g_hash_table_lookup (coverage_methods_hash, GINT_TO_POINTER (coverage->method_id));
-               if (method == NULL) {
-                       fprintf (outfile, "Cannot find method with ID: %d\n", coverage->method_id);
-                       continue;
-               }
-
-               g_ptr_array_add (method->coverage, coverage);
-       }
-}
-
-static void
-coverage_add_assembly (CoverageAssembly *assembly)
-{
-       if (coverage_assemblies == NULL)
-               coverage_assemblies = g_ptr_array_new ();
-
-       g_ptr_array_add (coverage_assemblies, assembly);
-}
-
-static void
-coverage_add_method (CoverageMethod *method)
-{
-       if (coverage_methods == NULL) {
-               coverage_methods = g_ptr_array_new ();
-               coverage_methods_hash = g_hash_table_new (NULL, NULL);
-       }
-
-       g_ptr_array_add (coverage_methods, method);
-       g_hash_table_insert (coverage_methods_hash, GINT_TO_POINTER (method->method_id), method);
-}
-
-static void
-coverage_add_class (CoverageClass *klass)
-{
-       GPtrArray *classes = NULL;
-
-       if (coverage_classes == NULL) {
-               coverage_classes = g_ptr_array_new ();
-               coverage_assembly_classes = g_hash_table_new (g_str_hash, g_str_equal);
-       }
-
-       g_ptr_array_add (coverage_classes, klass);
-       classes = (GPtrArray *)g_hash_table_lookup (coverage_assembly_classes, klass->assembly_name);
-       if (classes == NULL) {
-               classes = g_ptr_array_new ();
-               g_hash_table_insert (coverage_assembly_classes, klass->assembly_name, classes);
-       }
-       g_ptr_array_add (classes, klass);
-}
-
-static void
-coverage_add_coverage (CoverageCoverage *coverage)
-{
-       if (coverage_statements == NULL)
-               coverage_statements = g_ptr_array_new ();
-
-       g_ptr_array_add (coverage_statements, coverage);
-}
-
-#define OBJ_ADDR(diff) ((obj_base + diff) << 3)
-#define LOG_TIME(base,diff) /*fprintf("outfile, time %llu + %llu near offset %d\n", base, diff, p - ctx->buf)*/
-
-
-/* Stats */
-#define BUFFER_HEADER_SIZE 48
-
-typedef struct {
-       int count, min_size, max_size, bytes;
-} EventStat;
-
-static int buffer_count;
-static EventStat stats [256];
-
-static void
-record_event_stats (int type, int size)
-{
-       ++stats [type].count;
-       if (!stats [type].min_size)
-               stats [type].min_size = size;
-       stats [type].min_size = MIN (stats [type].min_size, size);
-       stats [type].max_size = MAX (stats [type].max_size, size);
-       stats [type].bytes += size;
-}
-
-static int
-decode_buffer (ProfContext *ctx)
-{
-       unsigned char *p;
-       unsigned char *end;
-       intptr_t thread_id;
-       intptr_t ptr_base;
-       intptr_t obj_base;
-       intptr_t method_base;
-       uint64_t time_base;
-       uint64_t file_offset;
-       int len, i;
-       ThreadContext *thread;
-
-#ifdef HAVE_SYS_ZLIB
-       if (ctx->gzfile)
-               file_offset = gztell (ctx->gzfile);
-       else
-#endif
-               file_offset = ftell (ctx->file);
-       if (!load_data (ctx, 48))
-               return 0;
-       p = ctx->buf;
-       if (read_int32 (p) != BUF_ID) {
-               fprintf (outfile, "Incorrect buffer id: 0x%x\n", read_int32 (p));
-               for (i = 0; i < 48; ++i) {
-                       fprintf (outfile, "0x%x%s", p [i], i % 8?" ":"\n");
-               }
-               return 0;
-       }
-       len = read_int32 (p + 4);
-       time_base = read_int64 (p + 8);
-       ptr_base = read_int64 (p + 16);
-       obj_base = read_int64 (p + 24);
-       thread_id = read_int64 (p + 32);
-       method_base = read_int64 (p + 40);
-       if (debug)
-               fprintf (outfile, "buf: thread:%zx, len: %d, time: %llu, file offset: %llu\n", thread_id, len, (unsigned long long) time_base, (unsigned long long) file_offset);
-       thread = load_thread (ctx, thread_id);
-       if (!load_data (ctx, len))
-               return 0;
-
-       ++buffer_count;
-
-       if (!startup_time) {
-               startup_time = time_base;
-               if (use_time_filter) {
-                       time_from += startup_time;
-                       time_to += startup_time;
-               }
-       }
-       for (i = 0; i < thread->stack_id; ++i)
-               thread->stack [i]->recurse_count++;
-       p = ctx->buf;
-       end = p + len;
-       while (p < end) {
-               unsigned char *start = p;
-               unsigned char event = *p;
-               switch (*p & 0xf) {
-               case TYPE_GC: {
-                       int subtype = *p & 0xf0;
-                       uint64_t tdiff = decode_uleb128 (p + 1, &p);
-                       LOG_TIME (time_base, tdiff);
-                       time_base += tdiff;
-                       if (subtype == TYPE_GC_RESIZE) {
-                               uint64_t new_size = decode_uleb128 (p, &p);
-                               if (debug)
-                                       fprintf (outfile, "gc heap resized to %llu\n", (unsigned long long) new_size);
-                               gc_resizes++;
-                               if (new_size > max_heap_size)
-                                       max_heap_size = new_size;
-                       } else if (subtype == TYPE_GC_EVENT) {
-                               uint64_t ev;
-                               if (ctx->data_version > 12)
-                                       ev = *p++;
-                               else
-                                       ev = decode_uleb128 (p, &p);
-                               int gen;
-                               if (ctx->data_version > 12)
-                                       gen = *p++;
-                               else
-                                       gen = decode_uleb128 (p, &p);
-                               if (debug)
-                                       fprintf (outfile, "gc event for gen%d: %s at %llu (thread: 0x%zx)\n", gen, gc_event_name (ev), (unsigned long long) time_base, thread->thread_id);
-                               if (gen > 2) {
-                                       fprintf (outfile, "incorrect gc gen: %d\n", gen);
-                                       break;
-                               }
-                               if (ev == MONO_GC_EVENT_START) {
-                                       thread->gc_start_times [gen] = time_base;
-                                       gc_info [gen].count++;
-                               } else if (ev == MONO_GC_EVENT_END) {
-                                       tdiff = time_base - thread->gc_start_times [gen];
-                                       gc_info [gen].total_time += tdiff;
-                                       if (tdiff > gc_info [gen].max_time)
-                                               gc_info [gen].max_time = tdiff;
-                               }
-                       } else if (subtype == TYPE_GC_MOVE) {
-                               int j, num = decode_uleb128 (p, &p);
-                               gc_object_moves += num / 2;
-                               for (j = 0; j < num; j += 2) {
-                                       intptr_t obj1diff = decode_sleb128 (p, &p);
-                                       intptr_t obj2diff = decode_sleb128 (p, &p);
-                                       if (num_tracked_objects)
-                                               track_move (OBJ_ADDR (obj1diff), OBJ_ADDR (obj2diff));
-                                       if (debug) {
-                                               fprintf (outfile, "moved obj %p to %p\n", (void*)OBJ_ADDR (obj1diff), (void*)OBJ_ADDR (obj2diff));
-                                       }
-                               }
-                       } else if (subtype == TYPE_GC_HANDLE_CREATED || subtype == TYPE_GC_HANDLE_CREATED_BT) {
-                               int has_bt = subtype == TYPE_GC_HANDLE_CREATED_BT;
-                               int num_bt = 0;
-                               MethodDesc *sframes [8];
-                               MethodDesc **frames = sframes;
-                               int htype = decode_uleb128 (p, &p);
-                               uint32_t handle = decode_uleb128 (p, &p);
-                               intptr_t objdiff = decode_sleb128 (p, &p);
-                               if (has_bt) {
-                                       num_bt = 8;
-                                       frames = decode_bt (ctx, sframes, &num_bt, p, &p, ptr_base, &method_base);
-                                       if (!frames) {
-                                               fprintf (outfile, "Cannot load backtrace\n");
-                                               return 0;
-                                       }
-                               }
-                               if (htype > 3)
-                                       return 0;
-                               if ((thread_filter && thread_filter == thread->thread_id) || (time_base >= time_from && time_base < time_to)) {
-                                       handle_info [htype].created++;
-                                       handle_info [htype].live++;
-                                       if (handle_info [htype].live > handle_info [htype].max_live)
-                                               handle_info [htype].max_live = handle_info [htype].live;
-                                       BackTrace *bt;
-                                       if (has_bt)
-                                               bt = add_trace_methods (frames, num_bt, &handle_info [htype].traces, 1);
-                                       else
-                                               bt = add_trace_thread (thread, &handle_info [htype].traces, 1);
-                                       if (num_tracked_objects)
-                                               track_handle (OBJ_ADDR (objdiff), htype, handle, bt, time_base);
-                               }
-                               if (debug)
-                                       fprintf (outfile, "handle (%s) %u created for object %p\n", get_handle_name (htype), handle, (void*)OBJ_ADDR (objdiff));
-                               if (frames != sframes)
-                                       g_free (frames);
-                       } else if (subtype == TYPE_GC_HANDLE_DESTROYED || subtype == TYPE_GC_HANDLE_DESTROYED_BT) {
-                               int has_bt = subtype == TYPE_GC_HANDLE_DESTROYED_BT;
-                               int num_bt = 0;
-                               MethodDesc *sframes [8];
-                               MethodDesc **frames = sframes;
-                               int htype = decode_uleb128 (p, &p);
-                               uint32_t handle = decode_uleb128 (p, &p);
-                               if (has_bt) {
-                                       num_bt = 8;
-                                       frames = decode_bt (ctx, sframes, &num_bt, p, &p, ptr_base, &method_base);
-                                       if (!frames) {
-                                               fprintf (outfile, "Cannot load backtrace\n");
-                                               return 0;
-                                       }
-                               }
-                               if (htype > 3)
-                                       return 0;
-                               if ((thread_filter && thread_filter == thread->thread_id) || (time_base >= time_from && time_base < time_to)) {
-                                       handle_info [htype].destroyed ++;
-                                       handle_info [htype].live--;
-                                       BackTrace *bt;
-                                       if (has_bt)
-                                               bt = add_trace_methods (frames, num_bt, &handle_info [htype].destroy_traces, 1);
-                                       else
-                                               bt = add_trace_thread (thread, &handle_info [htype].destroy_traces, 1);
-                                       /* TODO: track_handle_free () - would need to record and keep track of the associated object address... */
-                               }
-                               if (debug)
-                                       fprintf (outfile, "handle (%s) %u destroyed\n", get_handle_name (htype), handle);
-                               if (frames != sframes)
-                                       g_free (frames);
-                       } else if (subtype == TYPE_GC_FINALIZE_START) {
-                               // TODO: Generate a finalizer report based on these events.
-                               if (debug)
-                                       fprintf (outfile, "gc finalizer queue being processed at %llu\n", (unsigned long long) time_base);
-                       } else if (subtype == TYPE_GC_FINALIZE_END) {
-                               if (debug)
-                                       fprintf (outfile, "gc finalizer queue finished processing at %llu\n", (unsigned long long) time_base);
-                       } else if (subtype == TYPE_GC_FINALIZE_OBJECT_START) {
-                               intptr_t objdiff = decode_sleb128 (p, &p);
-                               if (debug)
-                                       fprintf (outfile, "gc finalizing object %p at %llu\n", (void *) OBJ_ADDR (objdiff), (unsigned long long) time_base);
-                       } else if (subtype == TYPE_GC_FINALIZE_OBJECT_END) {
-                               intptr_t objdiff = decode_sleb128 (p, &p);
-                               if (debug)
-                                       fprintf (outfile, "gc finalized object %p at %llu\n", (void *) OBJ_ADDR (objdiff), (unsigned long long) time_base);
-                       }
-                       break;
-               }
-               case TYPE_METADATA: {
-                       int subtype = *p & 0xf0;
-                       const char *load_str = subtype == TYPE_END_LOAD ? "loaded" : "unloaded";
-                       uint64_t tdiff = decode_uleb128 (p + 1, &p);
-                       int mtype = *p++;
-                       intptr_t ptrdiff = decode_sleb128 (p, &p);
-                       LOG_TIME (time_base, tdiff);
-                       time_base += tdiff;
-                       if (mtype == TYPE_CLASS) {
-                               intptr_t imptrdiff = decode_sleb128 (p, &p);
-                               if (ctx->data_version < 13)
-                                       decode_uleb128 (p, &p); /* flags */
-                               if (debug)
-                                       fprintf (outfile, "%s class %p (%s in %p) at %llu\n", load_str, (void*)(ptr_base + ptrdiff), p, (void*)(ptr_base + imptrdiff), (unsigned long long) time_base);
-                               if (subtype == TYPE_END_LOAD)
-                                       add_class (ptr_base + ptrdiff, (char*)p);
-                               while (*p) p++;
-                               p++;
-                       } else if (mtype == TYPE_IMAGE) {
-                               if (ctx->data_version < 13)
-                                       decode_uleb128 (p, &p); /* flags */
-                               if (debug)
-                                       fprintf (outfile, "%s image %p (%s) at %llu\n", load_str, (void*)(ptr_base + ptrdiff), p, (unsigned long long) time_base);
-                               if (subtype == TYPE_END_LOAD)
-                                       add_image (ptr_base + ptrdiff, (char*)p);
-                               while (*p) p++;
-                               p++;
-                       } else if (mtype == TYPE_ASSEMBLY) {
-                               if (ctx->data_version < 13)
-                                       decode_uleb128 (p, &p); /* flags */
-                               if (debug)
-                                       fprintf (outfile, "%s assembly %p (%s) at %llu\n", load_str, (void*)(ptr_base + ptrdiff), p, (unsigned long long) time_base);
-                               if (subtype == TYPE_END_LOAD)
-                                       add_assembly (ptr_base + ptrdiff, (char*)p);
-                               while (*p) p++;
-                               p++;
-                       } else if (mtype == TYPE_DOMAIN) {
-                               if (ctx->data_version < 13)
-                                       decode_uleb128 (p, &p); /* flags */
-                               DomainContext *nd = get_domain (ctx, ptr_base + ptrdiff);
-                               /* no subtype means it's a name event, rather than start/stop */
-                               if (subtype == 0)
-                                       nd->friendly_name = pstrdup ((char *) p);
-                               if (debug) {
-                                       if (subtype == 0)
-                                               fprintf (outfile, "domain %p named at %llu: %s\n", (void *) (ptr_base + ptrdiff), (unsigned long long) time_base, p);
-                                       else
-                                               fprintf (outfile, "%s thread %p at %llu\n", load_str, (void *) (ptr_base + ptrdiff), (unsigned long long) time_base);
-                               }
-                               if (subtype == 0) {
-                                       while (*p) p++;
-                                       p++;
-                               }
-                       } else if (mtype == TYPE_CONTEXT) {
-                               if (ctx->data_version < 13)
-                                       decode_uleb128 (p, &p); /* flags */
-                               intptr_t domaindiff = decode_sleb128 (p, &p);
-                               if (debug)
-                                       fprintf (outfile, "%s context %p (%p) at %llu\n", load_str, (void*)(ptr_base + ptrdiff), (void *) (ptr_base + domaindiff), (unsigned long long) time_base);
-                               if (subtype == TYPE_END_LOAD)
-                                       get_remctx (ctx, ptr_base + ptrdiff)->domain_id = ptr_base + domaindiff;
-                       } else if (mtype == TYPE_THREAD) {
-                               if (ctx->data_version < 13)
-                                       decode_uleb128 (p, &p); /* flags */
-                               ThreadContext *nt = get_thread (ctx, ptr_base + ptrdiff);
-                               /* no subtype means it's a name event, rather than start/stop */
-                               if (subtype == 0)
-                                       nt->name = pstrdup ((char*)p);
-                               if (debug) {
-                                       if (subtype == 0)
-                                               fprintf (outfile, "thread %p named at %llu: %s\n", (void*)(ptr_base + ptrdiff), (unsigned long long) time_base, p);
-                                       else
-                                               fprintf (outfile, "%s thread %p at %llu\n", load_str, (void *) (ptr_base + ptrdiff), (unsigned long long) time_base);
-                               }
-                               if (subtype == 0) {
-                                       while (*p) p++;
-                                       p++;
-                               }
-                       }
-                       break;
-               }
-               case TYPE_ALLOC: {
-                       int has_bt = *p & TYPE_ALLOC_BT;
-                       uint64_t tdiff = decode_uleb128 (p + 1, &p);
-                       intptr_t ptrdiff = decode_sleb128 (p, &p);
-                       intptr_t objdiff = decode_sleb128 (p, &p);
-                       uint64_t len;
-                       int num_bt = 0;
-                       MethodDesc* sframes [8];
-                       MethodDesc** frames = sframes;
-                       ClassDesc *cd = lookup_class (ptr_base + ptrdiff);
-                       len = decode_uleb128 (p, &p);
-                       LOG_TIME (time_base, tdiff);
-                       time_base += tdiff;
-                       if (debug)
-                               fprintf (outfile, "alloced object %p, size %llu (%s) at %llu\n", (void*)OBJ_ADDR (objdiff), (unsigned long long) len, lookup_class (ptr_base + ptrdiff)->name, (unsigned long long) time_base);
-                       if (has_bt) {
-                               num_bt = 8;
-                               frames = decode_bt (ctx, sframes, &num_bt, p, &p, ptr_base, &method_base);
-                               if (!frames) {
-                                       fprintf (outfile, "Cannot load backtrace\n");
-                                       return 0;
-                               }
-                       }
-                       if ((thread_filter && thread_filter == thread->thread_id) || (time_base >= time_from && time_base < time_to)) {
-                               BackTrace *bt;
-                               cd->allocs++;
-                               cd->alloc_size += len;
-                               if (has_bt)
-                                       bt = add_trace_methods (frames, num_bt, &cd->traces, len);
-                               else
-                                       bt = add_trace_thread (thread, &cd->traces, len);
-                               if (find_size && len >= find_size) {
-                                       if (!find_name || strstr (cd->name, find_name))
-                                               found_object (OBJ_ADDR (objdiff));
-                               } else if (!find_size && find_name && strstr (cd->name, find_name)) {
-                                       found_object (OBJ_ADDR (objdiff));
-                               }
-                               if (num_tracked_objects)
-                                       tracked_creation (OBJ_ADDR (objdiff), cd, len, bt, time_base);
-                       }
-                       if (frames != sframes)
-                               g_free (frames);
-                       break;
-               }
-               case TYPE_METHOD: {
-                       int subtype = *p & 0xf0;
-                       uint64_t tdiff = decode_uleb128 (p + 1, &p);
-                       int64_t ptrdiff = decode_sleb128 (p, &p);
-                       LOG_TIME (time_base, tdiff);
-                       time_base += tdiff;
-                       method_base += ptrdiff;
-                       if (subtype == TYPE_JIT) {
-                               intptr_t codediff = decode_sleb128 (p, &p);
-                               int codelen = decode_uleb128 (p, &p);
-                               MethodDesc *jitted_method;
-                               if (debug)
-                                       fprintf (outfile, "jitted method %p (%s), size: %d, code: %p\n", (void*)(method_base), p, codelen, (void*)(ptr_base + codediff));
-                               jitted_method = add_method (method_base, (char*)p, ptr_base + codediff, codelen);
-                               if (!(time_base >= time_from && time_base < time_to))
-                                       jitted_method->ignore_jit = 1;
-                               while (*p) p++;
-                               p++;
-                       } else {
-                               MethodDesc *method;
-                               if ((thread_filter && thread_filter != thread->thread_id))
-                                       break;
-                               if (!(time_base >= time_from && time_base < time_to))
-                                       break;
-                               method = lookup_method (method_base);
-                               if (subtype == TYPE_ENTER) {
-                                       add_trace_thread (thread, &method->traces, 1);
-                                       push_method (thread, method, time_base);
-                               } else {
-                                       pop_method (thread, method, time_base);
-                               }
-                               if (debug)
-                                       fprintf (outfile, "%s method %s\n", subtype == TYPE_ENTER? "enter": subtype == TYPE_EXC_LEAVE? "exleave": "leave", method->name);
-                       }
-                       break;
-               }
-               case TYPE_HEAP: {
-                       int subtype = *p & 0xf0;
-                       if (subtype == TYPE_HEAP_OBJECT) {
-                               HeapObjectDesc *ho = NULL;
-                               int i;
-                               intptr_t objdiff;
-                               if (ctx->data_version > 12) {
-                                       uint64_t tdiff = decode_uleb128 (p + 1, &p);
-                                       LOG_TIME (time_base, tdiff);
-                                       time_base += tdiff;
-                                       objdiff = decode_sleb128 (p, &p);
-                               } else
-                                       objdiff = decode_sleb128 (p + 1, &p);
-                               intptr_t ptrdiff = decode_sleb128 (p, &p);
-                               uint64_t size = decode_uleb128 (p, &p);
-                               uintptr_t num = decode_uleb128 (p, &p);
-                               uintptr_t ref_offset = 0;
-                               uintptr_t last_obj_offset = 0;
-                               ClassDesc *cd = lookup_class (ptr_base + ptrdiff);
-                               if (size) {
-                                       HeapClassDesc *hcd = add_heap_shot_class (thread->current_heap_shot, cd, size);
-                                       if (collect_traces) {
-                                               ho = alloc_heap_obj (OBJ_ADDR (objdiff), hcd, num);
-                                               add_heap_shot_obj (thread->current_heap_shot, ho);
-                                               ref_offset = 0;
-                                       }
-                               } else {
-                                       if (collect_traces)
-                                               ho = heap_shot_obj_add_refs (thread->current_heap_shot, OBJ_ADDR (objdiff), num, &ref_offset);
-                               }
-                               for (i = 0; i < num; ++i) {
-                                       /* FIXME: use object distance to measure how good
-                                        * the GC is at keeping related objects close
-                                        */
-                                       uintptr_t offset = ctx->data_version > 1? last_obj_offset + decode_uleb128 (p, &p): -1;
-                                       intptr_t obj1diff = decode_sleb128 (p, &p);
-                                       last_obj_offset = offset;
-                                       if (collect_traces)
-                                               ho->refs [ref_offset + i] = OBJ_ADDR (obj1diff);
-                                       if (num_tracked_objects)
-                                               track_obj_reference (OBJ_ADDR (obj1diff), OBJ_ADDR (objdiff), cd);
-                               }
-                               if (debug && size)
-                                       fprintf (outfile, "traced object %p, size %llu (%s), refs: %zd\n", (void*)OBJ_ADDR (objdiff), (unsigned long long) size, cd->name, num);
-                       } else if (subtype == TYPE_HEAP_ROOT) {
-                               uintptr_t num;
-                               if (ctx->data_version > 12) {
-                                       uint64_t tdiff = decode_uleb128 (p + 1, &p);
-                                       LOG_TIME (time_base, tdiff);
-                                       time_base += tdiff;
-                                       num = decode_uleb128 (p, &p);
-                               } else
-                                       num = decode_uleb128 (p + 1, &p);
-                               uintptr_t gc_num G_GNUC_UNUSED = decode_uleb128 (p, &p);
-                               int i;
-                               for (i = 0; i < num; ++i) {
-                                       intptr_t objdiff = decode_sleb128 (p, &p);
-                                       int root_type;
-                                       if (ctx->data_version > 12)
-                                               root_type = *p++;
-                                       else
-                                               root_type = decode_uleb128 (p, &p);
-                                       /* we just discard the extra info for now */
-                                       uintptr_t extra_info = decode_uleb128 (p, &p);
-                                       if (debug)
-                                               fprintf (outfile, "object %p is a %s root\n", (void*)OBJ_ADDR (objdiff), get_root_name (root_type));
-                                       if (collect_traces)
-                                               thread_add_root (thread, OBJ_ADDR (objdiff), root_type, extra_info);
-                               }
-                       } else if (subtype == TYPE_HEAP_END) {
-                               uint64_t tdiff = decode_uleb128 (p + 1, &p);
-                               LOG_TIME (time_base, tdiff);
-                               time_base += tdiff;
-                               if (debug)
-                                       fprintf (outfile, "heap shot end\n");
-                               if (collect_traces) {
-                                       HeapShot *hs = thread->current_heap_shot;
-                                       if (hs && thread->num_roots) {
-                                               /* transfer the root ownershipt to the heapshot */
-                                               hs->num_roots = thread->num_roots;
-                                               hs->roots = thread->roots;
-                                               hs->roots_extra = thread->roots_extra;
-                                               hs->roots_types = thread->roots_types;
-                                       } else {
-                                               g_free (thread->roots);
-                                               g_free (thread->roots_extra);
-                                               g_free (thread->roots_types);
-                                       }
-                                       thread->num_roots = 0;
-                                       thread->size_roots = 0;
-                                       thread->roots = NULL;
-                                       thread->roots_extra = NULL;
-                                       thread->roots_types = NULL;
-                                       heap_shot_resolve_reverse_refs (hs);
-                                       heap_shot_mark_objects (hs);
-                                       heap_shot_free_objects (hs);
-                               }
-                               thread->current_heap_shot = NULL;
-                       } else if (subtype == TYPE_HEAP_START) {
-                               uint64_t tdiff = decode_uleb128 (p + 1, &p);
-                               LOG_TIME (time_base, tdiff);
-                               time_base += tdiff;
-                               if (debug)
-                                       fprintf (outfile, "heap shot start\n");
-                               thread->current_heap_shot = new_heap_shot (time_base);
-                       }
-                       break;
-               }
-               case TYPE_MONITOR: {
-                       int event = (*p >> 4) & 0x3;
-                       int has_bt = *p & TYPE_MONITOR_BT;
-                       uint64_t tdiff = decode_uleb128 (p + 1, &p);
-                       intptr_t objdiff = decode_sleb128 (p, &p);
-                       MethodDesc* sframes [8];
-                       MethodDesc** frames = sframes;
-                       int record;
-                       int num_bt = 0;
-                       LOG_TIME (time_base, tdiff);
-                       time_base += tdiff;
-                       record = (!thread_filter || thread_filter == thread->thread_id);
-                       if (!(time_base >= time_from && time_base < time_to))
-                               record = 0;
-                       if (event == MONO_PROFILER_MONITOR_CONTENTION) {
-                               MonitorDesc *mdesc = lookup_monitor (OBJ_ADDR (objdiff));
-                               if (record) {
-                                       monitor_contention++;
-                                       mdesc->contentions++;
-                                       thread->monitor = mdesc;
-                                       thread->contention_start = time_base;
-                               }
-                               if (has_bt) {
-                                       num_bt = 8;
-                                       frames = decode_bt (ctx, sframes, &num_bt, p, &p, ptr_base, &method_base);
-                                       if (!frames) {
-                                               fprintf (outfile, "Cannot load backtrace\n");
-                                               return 0;
-                                       }
-                                       if (record)
-                                               add_trace_methods (frames, num_bt, &mdesc->traces, 1);
-                               } else {
-                                       if (record)
-                                               add_trace_thread (thread, &mdesc->traces, 1);
-                               }
-                       } else if (event == MONO_PROFILER_MONITOR_FAIL) {
-                               if (record) {
-                                       monitor_failed++;
-                                       if (thread->monitor && thread->contention_start) {
-                                               uint64_t wait_time = time_base - thread->contention_start;
-                                               if (wait_time > thread->monitor->max_wait_time)
-                                                       thread->monitor->max_wait_time = wait_time;
-                                               thread->monitor->wait_time += wait_time;
-                                               thread->monitor = NULL;
-                                               thread->contention_start = 0;
-                                       }
-                               }
-                       } else if (event == MONO_PROFILER_MONITOR_DONE) {
-                               if (record) {
-                                       monitor_acquired++;
-                                       if (thread->monitor && thread->contention_start) {
-                                               uint64_t wait_time = time_base - thread->contention_start;
-                                               if (wait_time > thread->monitor->max_wait_time)
-                                                       thread->monitor->max_wait_time = wait_time;
-                                               thread->monitor->wait_time += wait_time;
-                                               thread->monitor = NULL;
-                                               thread->contention_start = 0;
-                                       }
-                               }
-                       }
-                       if (debug)
-                               fprintf (outfile, "monitor %s for object %p\n", monitor_ev_name (event), (void*)OBJ_ADDR (objdiff));
-                       if (frames != sframes)
-                               g_free (frames);
-                       break;
-               }
-               case TYPE_EXCEPTION: {
-                       int subtype = *p & 0x70;
-                       int has_bt = *p & TYPE_THROW_BT;
-                       uint64_t tdiff = decode_uleb128 (p + 1, &p);
-                       MethodDesc* sframes [8];
-                       MethodDesc** frames = sframes;
-                       int record;
-                       LOG_TIME (time_base, tdiff);
-                       time_base += tdiff;
-                       record = (!thread_filter || thread_filter == thread->thread_id);
-                       if (!(time_base >= time_from && time_base < time_to))
-                               record = 0;
-                       if (subtype == TYPE_CLAUSE) {
-                               int clause_type;
-                               if (ctx->data_version > 12)
-                                       clause_type = *p++;
-                               else
-                                       clause_type = decode_uleb128 (p, &p);
-                               int clause_num = decode_uleb128 (p, &p);
-                               int64_t ptrdiff = decode_sleb128 (p, &p);
-                               method_base += ptrdiff;
-                               if (record)
-                                       clause_summary [clause_type]++;
-                               if (debug)
-                                       fprintf (outfile, "clause %s (%d) in method %s\n", clause_name (clause_type), clause_num, lookup_method (method_base)->name);
-                       } else {
-                               intptr_t objdiff = decode_sleb128 (p, &p);
-                               if (record)
-                                       throw_count++;
-                               if (has_bt) {
-                                       has_bt = 8;
-                                       frames = decode_bt (ctx, sframes, &has_bt, p, &p, ptr_base, &method_base);
-                                       if (!frames) {
-                                               fprintf (outfile, "Cannot load backtrace\n");
-                                               return 0;
-                                       }
-                                       if (record)
-                                               add_trace_methods (frames, has_bt, &exc_traces, 1);
-                               } else {
-                                       if (record)
-                                               add_trace_thread (thread, &exc_traces, 1);
-                               }
-                               if (frames != sframes)
-                                       g_free (frames);
-                               if (debug)
-                                       fprintf (outfile, "throw %p\n", (void*)OBJ_ADDR (objdiff));
-                       }
-                       break;
-               }
-               case TYPE_RUNTIME: {
-                       int subtype = *p & 0xf0;
-                       uint64_t tdiff = decode_uleb128 (p + 1, &p);
-                       LOG_TIME (time_base, tdiff);
-                       time_base += tdiff;
-                       if (subtype == TYPE_JITHELPER) {
-                               int type;
-                               if (ctx->data_version > 12)
-                                       type = *p++;
-                               else
-                                       type = decode_uleb128 (p, &p);
-                               intptr_t codediff = decode_sleb128 (p, &p);
-                               int codelen = decode_uleb128 (p, &p);
-                               const char *name;
-                               if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
-                                       name = (const char *)p;
-                                       while (*p) p++;
-                                               p++;
-                               } else {
-                                       name = code_buffer_desc (type);
-                               }
-                               num_jit_helpers++;
-                               jit_helpers_code_size += codelen;
-                               if (debug)
-                                       fprintf (outfile, "jit helper %s, size: %d, code: %p\n", name, codelen, (void*)(ptr_base + codediff));
-                       }
-                       break;
-               }
-               case TYPE_SAMPLE: {
-                       int subtype = *p & 0xf0;
-                       if (subtype == TYPE_SAMPLE_HIT) {
-                               int i;
-                               int sample_type;
-                               uint64_t tstamp;
-                               if (ctx->data_version > 12) {
-                                       uint64_t tdiff = decode_uleb128 (p + 1, &p);
-                                       LOG_TIME (time_base, tdiff);
-                                       time_base += tdiff;
-                                       sample_type = *p++;
-                                       tstamp = time_base;
-                               } else {
-                                       sample_type = decode_uleb128 (p + 1, &p);
-                                       tstamp = decode_uleb128 (p, &p);
-                               }
-                               void *tid = (void *) thread_id;
-                               if (ctx->data_version > 10)
-                                       tid = (void *) (ptr_base + decode_sleb128 (p, &p));
-                               int count = decode_uleb128 (p, &p);
-                               for (i = 0; i < count; ++i) {
-                                       uintptr_t ip = ptr_base + decode_sleb128 (p, &p);
-                                       if ((tstamp >= time_from && tstamp < time_to))
-                                               add_stat_sample (sample_type, ip);
-                                       if (debug)
-                                               fprintf (outfile, "sample hit, type: %d at %p for thread %p\n", sample_type, (void*)ip, tid);
-                               }
-                               if (ctx->data_version > 5) {
-                                       count = decode_uleb128 (p, &p);
-                                       for (i = 0; i < count; ++i) {
-                                               MethodDesc *method;
-                                               int64_t ptrdiff = decode_sleb128 (p, &p);
-                                               method_base += ptrdiff;
-                                               method = lookup_method (method_base);
-                                               if (debug)
-                                                       fprintf (outfile, "sample hit bt %d: %s\n", i, method->name);
-                                               if (ctx->data_version < 13) {
-                                                       decode_sleb128 (p, &p); /* il offset */
-                                                       decode_sleb128 (p, &p); /* native offset */
-                                               }
-                                       }
-                               }
-                       } else if (subtype == TYPE_SAMPLE_USYM) {
-                               /* un unmanaged symbol description */
-                               uintptr_t addr;
-                               if (ctx->data_version > 12) {
-                                       uint64_t tdiff = decode_uleb128 (p + 1, &p);
-                                       LOG_TIME (time_base, tdiff);
-                                       time_base += tdiff;
-                                       addr = ptr_base + decode_sleb128 (p, &p);
-                               } else
-                                       addr = ptr_base + decode_sleb128 (p + 1, &p);
-                               uintptr_t size = decode_uleb128 (p, &p);
-                               char *name;
-                               name = pstrdup ((char*)p);
-                               add_unmanaged_symbol (addr, name, size);
-                               if (debug)
-                                       fprintf (outfile, "unmanaged symbol %s at %p\n", name, (void*)addr);
-                               while (*p) p++;
-                               p++;
-                       } else if (subtype == TYPE_SAMPLE_UBIN) {
-                               /* un unmanaged binary loaded in memory */
-                               uint64_t tdiff = decode_uleb128 (p + 1, &p);
-                               uintptr_t addr = decode_sleb128 (p, &p);
-                               uint64_t offset G_GNUC_UNUSED = decode_uleb128 (p, &p);
-                               uintptr_t size = decode_uleb128 (p, &p);
-                               char *name;
-                               LOG_TIME (time_base, tdiff);
-                               time_base += tdiff;
-                               name = pstrdup ((char*)p);
-                               add_unmanaged_binary (addr, name, size);
-                               if (debug)
-                                       fprintf (outfile, "unmanaged binary %s at %p\n", name, (void*)addr);
-                               while (*p) p++;
-                               p++;
-                       } else if (subtype == TYPE_SAMPLE_COUNTERS_DESC) {
-                               uint64_t i, len;
-                               if (ctx->data_version > 12) {
-                                       uint64_t tdiff = decode_uleb128 (p + 1, &p);
-                                       LOG_TIME (time_base, tdiff);
-                                       time_base += tdiff;
-                                       len = decode_uleb128 (p, &p);
-                               } else
-                                       len = decode_uleb128 (p + 1, &p);
-                               for (i = 0; i < len; i++) {
-                                       uint64_t type, unit, variance, index;
-                                       uint64_t section = decode_uleb128 (p, &p);
-                                       char *section_str, *name;
-                                       if (section != MONO_COUNTER_PERFCOUNTERS) {
-                                               section_str = (char*) section_name (section);
-                                       } else {
-                                               section_str = pstrdup ((char*)p);
-                                               while (*p++);
-                                       }
-                                       name = pstrdup ((char*)p);
-                                       while (*p++);
-                                       if (ctx->data_version > 12) {
-                                               type = *p++;
-                                               unit = *p++;
-                                               variance = *p++;
-                                       } else {
-                                               type = decode_uleb128 (p, &p);
-                                               unit = decode_uleb128 (p, &p);
-                                               variance = decode_uleb128 (p, &p);
-                                       }
-                                       index = decode_uleb128 (p, &p);
-                                       add_counter (section_str, name, (int)type, (int)unit, (int)variance, (int)index);
-                               }
-                       } else if (subtype == TYPE_SAMPLE_COUNTERS) {
-                               int i;
-                               CounterValue *value, *previous = NULL;
-                               CounterList *list;
-                               uint64_t timestamp; // milliseconds since startup
-                               if (ctx->data_version > 12) {
-                                       uint64_t tdiff = decode_uleb128 (p + 1, &p);
-                                       LOG_TIME (time_base, tdiff);
-                                       time_base += tdiff;
-                                       timestamp = (time_base - startup_time) / 1000 / 1000;
-                               } else
-                                       timestamp = decode_uleb128 (p + 1, &p);
-                               uint64_t time_between = timestamp / 1000 * 1000 * 1000 * 1000 + startup_time;
-                               while (1) {
-                                       uint64_t type, index = decode_uleb128 (p, &p);
-                                       if (index == 0)
-                                               break;
-
-                                       for (list = counters; list; list = list->next) {
-                                               if (list->counter->index == (int)index) {
-                                                       previous = list->counter->values_last;
-                                                       break;
-                                               }
-                                       }
-
-                                       if (ctx->data_version > 12)
-                                               type = *p++;
-                                       else
-                                               type = decode_uleb128 (p, &p);
-
-                                       value = (CounterValue *)calloc (1, sizeof (CounterValue));
-                                       value->timestamp = timestamp;
-
-                                       switch (type) {
-                                       case MONO_COUNTER_INT:
-#if SIZEOF_VOID_P == 4
-                                       case MONO_COUNTER_WORD:
-#endif
-                                               value->buffer = (unsigned char *)malloc (sizeof (int32_t));
-                                               *(int32_t*)value->buffer = (int32_t)decode_sleb128 (p, &p) + (previous ? (*(int32_t*)previous->buffer) : 0);
-                                               break;
-                                       case MONO_COUNTER_UINT:
-                                               value->buffer = (unsigned char *)malloc (sizeof (uint32_t));
-                                               *(uint32_t*)value->buffer = (uint32_t)decode_uleb128 (p, &p) + (previous ? (*(uint32_t*)previous->buffer) : 0);
-                                               break;
-                                       case MONO_COUNTER_LONG:
-#if SIZEOF_VOID_P == 8
-                                       case MONO_COUNTER_WORD:
-#endif
-                                       case MONO_COUNTER_TIME_INTERVAL:
-                                               value->buffer = (unsigned char *)malloc (sizeof (int64_t));
-                                               *(int64_t*)value->buffer = (int64_t)decode_sleb128 (p, &p) + (previous ? (*(int64_t*)previous->buffer) : 0);
-                                               break;
-                                       case MONO_COUNTER_ULONG:
-                                               value->buffer = (unsigned char *)malloc (sizeof (uint64_t));
-                                               *(uint64_t*)value->buffer = (uint64_t)decode_uleb128 (p, &p) + (previous ? (*(uint64_t*)previous->buffer) : 0);
-                                               break;
-                                       case MONO_COUNTER_DOUBLE:
-                                               value->buffer = (unsigned char *)malloc (sizeof (double));
-#if TARGET_BYTE_ORDER == G_LITTLE_ENDIAN
-                                               for (i = 0; i < sizeof (double); i++)
-#else
-                                               for (i = sizeof (double) - 1; i >= 0; i--)
-#endif
-                                                       value->buffer[i] = *p++;
-                                               break;
-                                       case MONO_COUNTER_STRING:
-                                               if (*p++ == 0) {
-                                                       value->buffer = NULL;
-                                               } else {
-                                                       value->buffer = (unsigned char*) pstrdup ((char*)p);
-                                                       while (*p++);
-                                               }
-                                               break;
-                                       }
-                                       if (time_between >= time_from && time_between <= time_to)
-                                               add_counter_value (index, value);
-                               }
-                       } else {
-                               return 0;
-                       }
-                       break;
-               }
-               case TYPE_COVERAGE:{
-                       int subtype = *p & 0xf0;
-                       switch (subtype) {
-                       case TYPE_COVERAGE_METHOD: {
-                               CoverageMethod *method = g_new0 (CoverageMethod, 1);
-                               const char *assembly, *klass, *name, *sig, *filename;
-                               int token, n_offsets, method_id;
-
-                               p++;
-
-                               if (ctx->data_version > 12) {
-                                       uint64_t tdiff = decode_uleb128 (p, &p);
-                                       LOG_TIME (time_base, tdiff);
-                                       time_base += tdiff;
-                               }
-
-                               assembly = (const char *)p; while (*p) p++; p++;
-                               klass = (const char *)p; while (*p) p++; p++;
-                               name = (const char *)p; while (*p) p++; p++;
-                               sig = (const char *)p; while (*p) p++; p++;
-                               filename = (const char *)p; while (*p) p++; p++;
-
-                               token = decode_uleb128 (p, &p);
-                               method_id = decode_uleb128 (p, &p);
-                               n_offsets = decode_uleb128 (p, &p);
-
-                               method->assembly_name = g_strdup (assembly);
-                               method->class_name = g_strdup (klass);
-                               method->method_name = g_strdup (name);
-                               method->method_signature = g_strdup (sig);
-                               method->filename = g_strdup (filename);
-                               method->token = token;
-                               method->n_statements = n_offsets;
-                               method->coverage = g_ptr_array_new ();
-                               method->method_id = method_id;
-
-                               coverage_add_method (method);
-
-                               break;
-                       }
-                       case TYPE_COVERAGE_STATEMENT: {
-                               CoverageCoverage *coverage = g_new0 (CoverageCoverage, 1);
-                               int offset, count, line, column, method_id;
-
-                               p++;
-
-                               if (ctx->data_version > 12) {
-                                       uint64_t tdiff = decode_uleb128 (p, &p);
-                                       LOG_TIME (time_base, tdiff);
-                                       time_base += tdiff;
-                               }
-
-                               method_id = decode_uleb128 (p, &p);
-                               offset = decode_uleb128 (p, &p);
-                               count = decode_uleb128 (p, &p);
-                               line = decode_uleb128 (p, &p);
-                               column = decode_uleb128 (p, &p);
-
-                               coverage->method_id = method_id;
-                               coverage->offset = offset;
-                               coverage->count = count;
-                               coverage->line = line;
-                               coverage->column = column;
-
-                               coverage_add_coverage (coverage);
-                               break;
-                       }
-                       case TYPE_COVERAGE_ASSEMBLY: {
-                               CoverageAssembly *assembly = g_new0 (CoverageAssembly, 1);
-                               char *name, *guid, *filename;
-                               int number_of_methods, fully_covered, partially_covered;
-                               p++;
-
-                               if (ctx->data_version > 12) {
-                                       uint64_t tdiff = decode_uleb128 (p, &p);
-                                       LOG_TIME (time_base, tdiff);
-                                       time_base += tdiff;
-                               }
-
-                               name = (char *)p; while (*p) p++; p++;
-                               guid = (char *)p; while (*p) p++; p++;
-                               filename = (char *)p; while (*p) p++; p++;
-                               number_of_methods = decode_uleb128 (p, &p);
-                               fully_covered = decode_uleb128 (p, &p);
-                               partially_covered = decode_uleb128 (p, &p);
-
-                               assembly->name = g_strdup (name);
-                               assembly->guid = g_strdup (guid);
-                               assembly->filename = g_strdup (filename);
-                               assembly->number_of_methods = number_of_methods;
-                               assembly->fully_covered = fully_covered;
-                               assembly->partially_covered = partially_covered;
-
-                               coverage_add_assembly (assembly);
-                               break;
-                       }
-                       case TYPE_COVERAGE_CLASS: {
-                               CoverageClass *klass = g_new0 (CoverageClass, 1);
-                               char *assembly_name, *class_name;
-                               int number_of_methods, fully_covered, partially_covered;
-                               p++;
-
-                               if (ctx->data_version > 12) {
-                                       uint64_t tdiff = decode_uleb128 (p, &p);
-                                       LOG_TIME (time_base, tdiff);
-                                       time_base += tdiff;
-                               }
-
-                               assembly_name = (char *)p; while (*p) p++; p++;
-                               class_name = (char *)p; while (*p) p++; p++;
-                               number_of_methods = decode_uleb128 (p, &p);
-                               fully_covered = decode_uleb128 (p, &p);
-                               partially_covered = decode_uleb128 (p, &p);
-
-                               klass->assembly_name = g_strdup (assembly_name);
-                               klass->class_name = g_strdup (class_name);
-                               klass->number_of_methods = number_of_methods;
-                               klass->fully_covered = fully_covered;
-                               klass->partially_covered = partially_covered;
-
-                               coverage_add_class (klass);
-                               break;
-                       }
-
-                       default:
-                               break;
-                       }
-                       break;
-               }
-               case TYPE_META: {
-                       int subtype = *p & 0xf0;
-                       uint64_t tdiff = decode_uleb128 (p + 1, &p);
-                       LOG_TIME (time_base, tdiff);
-                       time_base += tdiff;
-                       if (subtype == TYPE_SYNC_POINT) {
-                               int type = *p++;
-                               if (debug)
-                                       fprintf (outfile, "sync point %i (%s)\n", type, sync_point_name (type));
-                       }
-                       break;
-               }
-               default:
-                       fprintf (outfile, "unhandled profiler event: 0x%x at file offset: %llu + %lld (len: %d\n)\n", *p, (unsigned long long) file_offset, (long long) (p - ctx->buf), len);
-                       exit (1);
-               }
-               record_event_stats (event, p - start);
-       }
-       thread->last_time = time_base;
-       for (i = 0; i < thread->stack_id; ++i)
-               thread->stack [i]->recurse_count = 0;
-       return 1;
-}
-
-static int
-read_header_string (ProfContext *ctx, char **field)
-{
-       if (!load_data (ctx, 4))
-               return 0;
-
-       if (!load_data (ctx, read_int32 (ctx->buf)))
-               return 0;
-
-       *field = pstrdup ((const char *) ctx->buf);
-
-       return 1;
-}
-
-static ProfContext*
-load_file (char *name)
-{
-       unsigned char *p;
-       ProfContext *ctx = (ProfContext *)calloc (sizeof (ProfContext), 1);
-       if (strcmp (name, "-") == 0)
-               ctx->file = stdin;
-       else
-               ctx->file = fopen (name, "rb");
-       if (!ctx->file) {
-               printf ("Cannot open file: %s\n", name);
-               exit (1);
-       }
-#if defined (HAVE_SYS_ZLIB)
-       if (ctx->file != stdin)
-               ctx->gzfile = gzdopen (fileno (ctx->file), "rb");
-#endif
-       if (!load_data (ctx, 30))
-               return NULL;
-       p = ctx->buf;
-       if (read_int32 (p) != LOG_HEADER_ID || p [6] > LOG_DATA_VERSION)
-               return NULL;
-       ctx->version_major = p [4];
-       ctx->version_minor = p [5];
-       ctx->data_version = p [6];
-       /* reading 64 bit files on 32 bit systems not supported yet */
-       if (p [7] > sizeof (void*))
-               return NULL;
-       if (read_int32 (p + 20)) /* flags must be 0 */
-               return NULL;
-       ctx->startup_time = read_int64 (p + 8);
-       ctx->timer_overhead = read_int32 (p + 16);
-       ctx->pid = read_int32 (p + 24);
-       ctx->port = read_int16 (p + 28);
-       if (ctx->version_major >= 1) {
-               if (!read_header_string (ctx, &ctx->args))
-                       return NULL;
-               if (!read_header_string (ctx, &ctx->arch))
-                       return NULL;
-               if (!read_header_string (ctx, &ctx->os))
-                       return NULL;
-       } else {
-               if (!load_data (ctx, 2)) /* old opsys field, was never used */
-                       return NULL;
-       }
-       return ctx;
-}
-
-enum {
-       ALLOC_SORT_BYTES,
-       ALLOC_SORT_COUNT
-};
-static int alloc_sort_mode = ALLOC_SORT_BYTES;
-
-static int
-compare_class (const void *a, const void *b)
-{
-       ClassDesc *const *A = (ClassDesc *const *)a;
-       ClassDesc *const *B = (ClassDesc *const *)b;
-       uint64_t vala, valb;
-       if (alloc_sort_mode == ALLOC_SORT_BYTES) {
-               vala = (*A)->alloc_size;
-               valb = (*B)->alloc_size;
-       } else {
-               vala = (*A)->allocs;
-               valb = (*B)->allocs;
-       }
-       if (valb == vala)
-               return 0;
-       if (valb < vala)
-               return -1;
-       return 1;
-}
-
-static void
-dump_header (ProfContext *ctx)
-{
-       time_t st = ctx->startup_time / 1000;
-       char *t = ctime (&st);
-       fprintf (outfile, "\nMono log profiler data\n");
-       fprintf (outfile, "\tProfiler version: %d.%d\n", ctx->version_major, ctx->version_minor);
-       fprintf (outfile, "\tData version: %d\n", ctx->data_version);
-       if (ctx->version_major >= 1) {
-               fprintf (outfile, "\tArguments: %s\n", ctx->args);
-               fprintf (outfile, "\tArchitecture: %s\n", ctx->arch);
-               fprintf (outfile, "\tOperating system: %s\n", ctx->os);
-       }
-       fprintf (outfile, "\tMean timer overhead: %d nanoseconds\n", ctx->timer_overhead);
-       fprintf (outfile, "\tProgram startup: %s", t);
-       if (ctx->pid)
-               fprintf (outfile, "\tProgram ID: %d\n", ctx->pid);
-       if (ctx->port)
-               fprintf (outfile, "\tServer listening on: %d\n", ctx->port);
-}
-
-static void
-dump_traces (TraceDesc *traces, const char *desc)
-{
-       int j;
-       if (!show_traces)
-               return;
-       if (!traces->count)
-               return;
-       sort_context_array (traces);
-       for (j = 0; j < traces->count; ++j) {
-               int k;
-               BackTrace *bt;
-               bt = traces->traces [j].bt;
-               if (!bt->count)
-                       continue;
-               fprintf (outfile, "\t%llu %s from:\n", (unsigned long long) traces->traces [j].count, desc);
-               for (k = 0; k < bt->count; ++k)
-                       fprintf (outfile, "\t\t%s\n", bt->methods [k]->name);
-       }
-}
-
-static void
-dump_threads (ProfContext *ctx)
-{
-       ThreadContext *thread;
-       fprintf (outfile, "\nThread summary\n");
-       for (thread = ctx->threads; thread; thread = thread->next) {
-               if (thread->thread_id) {
-                       fprintf (outfile, "\tThread: %p, name: \"%s\"\n", (void*)thread->thread_id, thread->name? thread->name: "");
-               }
-       }
-}
-
-static void
-dump_domains (ProfContext *ctx)
-{
-       fprintf (outfile, "\nDomain summary\n");
-
-       for (DomainContext *domain = ctx->domains; domain; domain = domain->next)
-               fprintf (outfile, "\tDomain: %p, friendly name: \"%s\"\n", (void *) domain->domain_id, domain->friendly_name);
-}
-
-static void
-dump_remctxs (ProfContext *ctx)
-{
-       fprintf (outfile, "\nContext summary\n");
-
-       for (RemCtxContext *remctx = ctx->remctxs; remctx; remctx = remctx->next)
-               fprintf (outfile, "\tContext: %p, domain: %p\n", (void *) remctx->remctx_id, (void *) remctx->domain_id);
-}
-
-static void
-dump_exceptions (void)
-{
-       int i;
-       fprintf (outfile, "\nException summary\n");
-       fprintf (outfile, "\tThrows: %llu\n", (unsigned long long) throw_count);
-       dump_traces (&exc_traces, "throws");
-       for (i = 0; i <= MONO_EXCEPTION_CLAUSE_FAULT; ++i) {
-               if (!clause_summary [i])
-                       continue;
-               fprintf (outfile, "\tExecuted %s clauses: %llu\n", clause_name (i), (unsigned long long) clause_summary [i]);
-       }
-}
-
-static int
-compare_monitor (const void *a, const void *b)
-{
-       MonitorDesc *const *A = (MonitorDesc *const *)a;
-       MonitorDesc *const *B = (MonitorDesc *const *)b;
-       if ((*B)->wait_time == (*A)->wait_time)
-               return 0;
-       if ((*B)->wait_time < (*A)->wait_time)
-               return -1;
-       return 1;
-}
-
-static void
-dump_monitors (void)
-{
-       MonitorDesc **monitors;
-       int i, j;
-       if (!num_monitors)
-               return;
-       monitors = (MonitorDesc **)malloc (sizeof (void*) * num_monitors);
-       for (i = 0, j = 0; i < SMALL_HASH_SIZE; ++i) {
-               MonitorDesc *mdesc = monitor_hash [i];
-               while (mdesc) {
-                       monitors [j++] = mdesc;
-                       mdesc = mdesc->next;
-               }
-       }
-       qsort (monitors, num_monitors, sizeof (void*), compare_monitor);
-       fprintf (outfile, "\nMonitor lock summary\n");
-       for (i = 0; i < num_monitors; ++i) {
-               MonitorDesc *mdesc = monitors [i];
-               fprintf (outfile, "\tLock object %p: %d contentions\n", (void*)mdesc->objid, (int)mdesc->contentions);
-               fprintf (outfile, "\t\t%.6f secs total wait time, %.6f max, %.6f average\n",
-                       mdesc->wait_time/1000000000.0, mdesc->max_wait_time/1000000000.0, mdesc->wait_time/1000000000.0/mdesc->contentions);
-               dump_traces (&mdesc->traces, "contentions");
-       }
-       fprintf (outfile, "\tLock contentions: %llu\n", (unsigned long long) monitor_contention);
-       fprintf (outfile, "\tLock acquired: %llu\n", (unsigned long long) monitor_acquired);
-       fprintf (outfile, "\tLock failures: %llu\n", (unsigned long long) monitor_failed);
-}
-
-static void
-dump_gcs (void)
-{
-       int i;
-       fprintf (outfile, "\nGC summary\n");
-       fprintf (outfile, "\tGC resizes: %d\n", gc_resizes);
-       fprintf (outfile, "\tMax heap size: %llu\n", (unsigned long long) max_heap_size);
-       fprintf (outfile, "\tObject moves: %llu\n", (unsigned long long) gc_object_moves);
-       for (i = 0; i < 3; ++i) {
-               if (!gc_info [i].count)
-                       continue;
-               fprintf (outfile, "\tGen%d collections: %d, max time: %lluus, total time: %lluus, average: %lluus\n",
-                       i, gc_info [i].count,
-                       (unsigned long long) (gc_info [i].max_time / 1000),
-                       (unsigned long long) (gc_info [i].total_time / 1000),
-                       (unsigned long long) (gc_info [i].total_time / gc_info [i].count / 1000));
-       }
-       for (i = 0; i < 3; ++i) {
-               if (!handle_info [i].max_live)
-                       continue;
-               fprintf (outfile, "\tGC handles %s: created: %llu, destroyed: %llu, max: %llu\n",
-                       get_handle_name (i),
-                       (unsigned long long) (handle_info [i].created),
-                       (unsigned long long) (handle_info [i].destroyed),
-                       (unsigned long long) (handle_info [i].max_live));
-               dump_traces (&handle_info [i].traces, "created");
-               dump_traces (&handle_info [i].destroy_traces, "destroyed");
-       }
-}
-
-static void
-dump_jit (void)
-{
-       int i;
-       int code_size = 0;
-       int compiled_methods = 0;
-       MethodDesc* m;
-       fprintf (outfile, "\nJIT summary\n");
-       for (i = 0; i < HASH_SIZE; ++i) {
-               m = method_hash [i];
-               for (m = method_hash [i]; m; m = m->next) {
-                       if (!m->code || m->ignore_jit)
-                               continue;
-                       compiled_methods++;
-                       code_size += m->len;
-               }
-       }
-       fprintf (outfile, "\tCompiled methods: %d\n", compiled_methods);
-       fprintf (outfile, "\tGenerated code size: %d\n", code_size);
-       fprintf (outfile, "\tJIT helpers: %d\n", num_jit_helpers);
-       fprintf (outfile, "\tJIT helpers code size: %d\n", jit_helpers_code_size);
-}
-
-static void
-dump_allocations (void)
-{
-       int i, c;
-       intptr_t allocs = 0;
-       uint64_t size = 0;
-       int header_done = 0;
-       ClassDesc **classes = (ClassDesc **)malloc (num_classes * sizeof (void*));
-       ClassDesc *cd;
-       c = 0;
-       for (i = 0; i < HASH_SIZE; ++i) {
-               cd = class_hash [i];
-               while (cd) {
-                       classes [c++] = cd;
-                       cd = cd->next;
-               }
-       }
-       qsort (classes, num_classes, sizeof (void*), compare_class);
-       for (i = 0; i < num_classes; ++i) {
-               cd = classes [i];
-               if (!cd->allocs)
-                       continue;
-               allocs += cd->allocs;
-               size += cd->alloc_size;
-               if (!header_done++) {
-                       fprintf (outfile, "\nAllocation summary\n");
-                       fprintf (outfile, "%10s %10s %8s Type name\n", "Bytes", "Count", "Average");
-               }
-               fprintf (outfile, "%10llu %10zd %8llu %s\n",
-                       (unsigned long long) (cd->alloc_size),
-                       cd->allocs,
-                       (unsigned long long) (cd->alloc_size / cd->allocs),
-                       cd->name);
-               dump_traces (&cd->traces, "bytes");
-       }
-       if (allocs)
-               fprintf (outfile, "Total memory allocated: %llu bytes in %zd objects\n", (unsigned long long) size, allocs);
-}
-
-enum {
-       METHOD_SORT_TOTAL,
-       METHOD_SORT_SELF,
-       METHOD_SORT_CALLS
-};
-
-static int method_sort_mode = METHOD_SORT_TOTAL;
-
-static int
-compare_method (const void *a, const void *b)
-{
-       MethodDesc *const *A = (MethodDesc *const *)a;
-       MethodDesc *const *B = (MethodDesc *const *)b;
-       uint64_t vala, valb;
-       if (method_sort_mode == METHOD_SORT_SELF) {
-               vala = (*A)->self_time;
-               valb = (*B)->self_time;
-       } else if (method_sort_mode == METHOD_SORT_CALLS) {
-               vala = (*A)->calls;
-               valb = (*B)->calls;
-       } else {
-               vala = (*A)->total_time;
-               valb = (*B)->total_time;
-       }
-       if (vala == valb)
-               return 0;
-       if (valb < vala)
-               return -1;
-       return 1;
-}
-
-static void
-dump_metadata (void)
-{
-       fprintf (outfile, "\nMetadata summary\n");
-       fprintf (outfile, "\tLoaded images: %d\n", num_images);
-       if (verbose) {
-               ImageDesc *image;
-               int i;
-               for (i = 0; i < SMALL_HASH_SIZE; ++i) {
-                       image = image_hash [i];
-                       while (image) {
-                               fprintf (outfile, "\t\t%s\n", image->filename);
-                               image = image->next;
-                       }
-               }
-       }
-       fprintf (outfile, "\tLoaded assemblies: %d\n", num_assemblies);
-       if (verbose) {
-               AssemblyDesc *assembly;
-               int i;
-               for (i = 0; i < SMALL_HASH_SIZE; ++i) {
-                       assembly = assembly_hash [i];
-                       while (assembly) {
-                               fprintf (outfile, "\t\t%s\n", assembly->asmname);
-                               assembly = assembly->next;
-                       }
-               }
-       }
-}
-
-static void
-dump_methods (void)
-{
-       int i, c;
-       uint64_t calls = 0;
-       int header_done = 0;
-       MethodDesc **methods = (MethodDesc **)malloc (num_methods * sizeof (void*));
-       MethodDesc *cd;
-       c = 0;
-       for (i = 0; i < HASH_SIZE; ++i) {
-               cd = method_hash [i];
-               while (cd) {
-                       cd->total_time = cd->self_time + cd->callee_time;
-                       methods [c++] = cd;
-                       cd = cd->next;
-               }
-       }
-       qsort (methods, num_methods, sizeof (void*), compare_method);
-       for (i = 0; i < num_methods; ++i) {
-               uint64_t msecs;
-               uint64_t smsecs;
-               cd = methods [i];
-               if (!cd->calls)
-                       continue;
-               calls += cd->calls;
-               msecs = cd->total_time / 1000000;
-               smsecs = (cd->total_time - cd->callee_time) / 1000000;
-               if (!msecs && !verbose)
-                       continue;
-               if (!header_done++) {
-                       fprintf (outfile, "\nMethod call summary\n");
-                       fprintf (outfile, "%8s %8s %10s Method name\n", "Total(ms)", "Self(ms)", "Calls");
-               }
-               fprintf (outfile, "%8llu %8llu %10llu %s\n",
-                       (unsigned long long) (msecs),
-                       (unsigned long long) (smsecs),
-                       (unsigned long long) (cd->calls),
-                       cd->name);
-               dump_traces (&cd->traces, "calls");
-       }
-       if (calls)
-               fprintf (outfile, "Total calls: %llu\n", (unsigned long long) calls);
-}
-
-static int
-compare_heap_class (const void *a, const void *b)
-{
-       HeapClassDesc *const *A = (HeapClassDesc *const *)a;
-       HeapClassDesc *const *B = (HeapClassDesc *const *)b;
-       uint64_t vala, valb;
-       if (alloc_sort_mode == ALLOC_SORT_BYTES) {
-               vala = (*A)->total_size;
-               valb = (*B)->total_size;
-       } else {
-               vala = (*A)->count;
-               valb = (*B)->count;
-       }
-       if (valb == vala)
-               return 0;
-       if (valb < vala)
-               return -1;
-       return 1;
-}
-
-static int
-compare_rev_class (const void *a, const void *b)
-{
-       const HeapClassRevRef *A = (const HeapClassRevRef *)a;
-       const HeapClassRevRef *B = (const HeapClassRevRef *)b;
-       if (B->count == A->count)
-               return 0;
-       if (B->count < A->count)
-               return -1;
-       return 1;
-}
-
-static void
-dump_rev_claases (HeapClassRevRef *revs, int count)
-{
-       int j;
-       if (!show_traces)
-               return;
-       if (!count)
-               return;
-       for (j = 0; j < count; ++j) {
-               HeapClassDesc *cd = revs [j].klass;
-               fprintf (outfile, "\t\t%llu references from: %s\n",
-                       (unsigned long long) (revs [j].count),
-                       cd->klass->name);
-       }
-}
-
-static void
-heap_shot_summary (HeapShot *hs, int hs_num, HeapShot *last_hs)
-{
-       uint64_t size = 0;
-       uint64_t count = 0;
-       int ccount = 0;
-       int i;
-       HeapClassDesc *cd;
-       HeapClassDesc **sorted;
-       sorted = (HeapClassDesc **)malloc (sizeof (void*) * hs->class_count);
-       for (i = 0; i < hs->hash_size; ++i) {
-               cd = hs->class_hash [i];
-               if (!cd)
-                       continue;
-               count += cd->count;
-               size += cd->total_size;
-               sorted [ccount++] = cd;
-       }
-       hs->sorted = sorted;
-       qsort (sorted, ccount, sizeof (void*), compare_heap_class);
-       fprintf (outfile, "\n\tHeap shot %d at %.3f secs: size: %llu, object count: %llu, class count: %d, roots: %zd\n",
-               hs_num,
-               (hs->timestamp - startup_time)/1000000000.0,
-               (unsigned long long) (size),
-               (unsigned long long) (count),
-               ccount, hs->num_roots);
-       if (!verbose && ccount > 30)
-               ccount = 30;
-       fprintf (outfile, "\t%10s %10s %8s Class name\n", "Bytes", "Count", "Average");
-       for (i = 0; i < ccount; ++i) {
-               HeapClassRevRef *rev_sorted;
-               int j, k;
-               HeapClassDesc *ocd = NULL;
-               cd = sorted [i];
-               if (last_hs)
-                       ocd = heap_class_lookup (last_hs, cd->klass);
-               fprintf (outfile, "\t%10llu %10llu %8llu %s",
-                       (unsigned long long) (cd->total_size),
-                       (unsigned long long) (cd->count),
-                       (unsigned long long) (cd->total_size / cd->count),
-                       cd->klass->name);
-               if (ocd) {
-                       int64_t bdiff = cd->total_size - ocd->total_size;
-                       int64_t cdiff = cd->count - ocd->count;
-                       fprintf (outfile, " (bytes: %+lld, count: %+lld)\n", (long long) bdiff, (long long) cdiff);
-               } else {
-                       fprintf (outfile, "\n");
-               }
-               if (!collect_traces)
-                       continue;
-               rev_sorted = (HeapClassRevRef *)malloc (cd->rev_count * sizeof (HeapClassRevRef));
-               k = 0;
-               for (j = 0; j < cd->rev_hash_size; ++j) {
-                       if (cd->rev_hash [j].klass)
-                               rev_sorted [k++] = cd->rev_hash [j];
-               }
-               assert (cd->rev_count == k);
-               qsort (rev_sorted, cd->rev_count, sizeof (HeapClassRevRef), compare_rev_class);
-               if (cd->root_references)
-                       fprintf (outfile, "\t\t%zd root references (%zd pinning)\n", cd->root_references, cd->pinned_references);
-               dump_rev_claases (rev_sorted, cd->rev_count);
-               g_free (rev_sorted);
-       }
-       g_free (sorted);
-}
-
-static int
-compare_heap_shots (const void *a, const void *b)
-{
-       HeapShot *const *A = (HeapShot *const *)a;
-       HeapShot *const *B = (HeapShot *const *)b;
-       if ((*B)->timestamp == (*A)->timestamp)
-               return 0;
-       if ((*B)->timestamp > (*A)->timestamp)
-               return -1;
-       return 1;
-}
-
-static void
-dump_heap_shots (void)
-{
-       HeapShot **hs_sorted;
-       HeapShot *hs;
-       HeapShot *last_hs = NULL;
-       int i;
-       if (!heap_shots)
-               return;
-       hs_sorted = (HeapShot **)malloc (num_heap_shots * sizeof (void*));
-       fprintf (outfile, "\nHeap shot summary\n");
-       i = 0;
-       for (hs = heap_shots; hs; hs = hs->next)
-               hs_sorted [i++] = hs;
-       qsort (hs_sorted, num_heap_shots, sizeof (void*), compare_heap_shots);
-       for (i = 0; i < num_heap_shots; ++i) {
-               hs = hs_sorted [i];
-               heap_shot_summary (hs, i, last_hs);
-               last_hs = hs;
-       }
-}
-
-/* This is a very basic escape function that escapes < > and &
-   Ideally we'd use g_markup_escape_string but that function isn't
-        available in Mono's eglib. This was written without looking at the
-        source of that function in glib. */
-static char *
-escape_string_for_xml (const char *string)
-{
-       GString *string_builder = g_string_new (NULL);
-       const char *start, *p;
-
-       start = p = string;
-       while (*p) {
-               while (*p && *p != '&' && *p != '<' && *p != '>')
-                       p++;
-
-               g_string_append_len (string_builder, start, p - start);
-
-               if (*p == '\0')
-                       break;
-
-               switch (*p) {
-               case '<':
-                       g_string_append (string_builder, "&lt;");
-                       break;
-
-               case '>':
-                       g_string_append (string_builder, "&gt;");
-                       break;
-
-               case '&':
-                       g_string_append (string_builder, "&amp;");
-                       break;
-
-               default:
-                       break;
-               }
-
-               p++;
-               start = p;
-       }
-
-       return g_string_free (string_builder, FALSE);
-}
-
-static int
-sort_assemblies (gconstpointer a, gconstpointer b)
-{
-       CoverageAssembly *assembly_a = *(CoverageAssembly **)a;
-       CoverageAssembly *assembly_b = *(CoverageAssembly **)b;
-
-       if (assembly_a->name == NULL && assembly_b->name == NULL)
-               return 0;
-       else if (assembly_a->name == NULL)
-               return -1;
-       else if (assembly_b->name == NULL)
-               return 1;
-
-       return strcmp (assembly_a->name, assembly_b->name);
-}
-
-static void
-dump_coverage (void)
-{
-       if (!coverage_methods && !coverage_assemblies)
-               return;
-
-       gather_coverage_statements ();
-       fprintf (outfile, "\nCoverage Summary:\n");
-
-       if (coverage_outfile) {
-               fprintf (coverage_outfile, "<?xml version=\"1.0\"?>\n");
-               fprintf (coverage_outfile, "<coverage version=\"0.3\">\n");
-       }
-
-       g_ptr_array_sort (coverage_assemblies, sort_assemblies);
-
-       for (guint i = 0; i < coverage_assemblies->len; i++) {
-               CoverageAssembly *assembly = (CoverageAssembly *)coverage_assemblies->pdata[i];
-               GPtrArray *classes;
-
-               if (assembly->number_of_methods != 0) {
-                       int percentage = ((assembly->fully_covered + assembly->partially_covered) * 100) / assembly->number_of_methods;
-                       fprintf (outfile, "\t%s (%s) %d%% covered (%d methods - %d covered)\n", assembly->name, assembly->filename, percentage, assembly->number_of_methods, assembly->fully_covered);
-               } else
-                       fprintf (outfile, "\t%s (%s) ?%% covered (%d methods - %d covered)\n", assembly->name, assembly->filename, assembly->number_of_methods, assembly->fully_covered);
-
-               if (coverage_outfile) {
-                       char *escaped_name, *escaped_filename;
-                       escaped_name = escape_string_for_xml (assembly->name);
-                       escaped_filename = escape_string_for_xml (assembly->filename);
-
-                       fprintf (coverage_outfile, "\t<assembly name=\"%s\" guid=\"%s\" filename=\"%s\" method-count=\"%d\" full=\"%d\" partial=\"%d\"/>\n", escaped_name, assembly->guid, escaped_filename, assembly->number_of_methods, assembly->fully_covered, assembly->partially_covered);
-
-                       g_free (escaped_name);
-                       g_free (escaped_filename);
-               }
-
-               classes = (GPtrArray *)g_hash_table_lookup (coverage_assembly_classes, assembly->name);
-               if (classes) {
-                       for (guint j = 0; j < classes->len; j++) {
-                               CoverageClass *klass = (CoverageClass *)classes->pdata [j];
-
-                               if (klass->number_of_methods > 0) {
-                                       int percentage = ((klass->fully_covered + klass->partially_covered) * 100) / klass->number_of_methods;
-                                       fprintf (outfile, "\t\t%s %d%% covered (%d methods - %d covered)\n", klass->class_name, percentage, klass->number_of_methods, klass->fully_covered);
-                               } else
-                                       fprintf (outfile, "\t\t%s ?%% covered (%d methods - %d covered)\n", klass->class_name, klass->number_of_methods, klass->fully_covered);
-
-                               if (coverage_outfile) {
-                                       char *escaped_name;
-                                       escaped_name = escape_string_for_xml (klass->class_name);
-
-                                       fprintf (coverage_outfile, "\t\t<class name=\"%s\" method-count=\"%d\" full=\"%d\" partial=\"%d\"/>\n", escaped_name, klass->number_of_methods, klass->fully_covered, klass->partially_covered);
-                                       g_free (escaped_name);
-                               }
-                       }
-               }
-       }
-
-       for (guint i = 0; i < coverage_methods->len; i++) {
-               CoverageMethod *method = (CoverageMethod *)coverage_methods->pdata [i];
-
-               if (coverage_outfile) {
-                       char *escaped_assembly, *escaped_class, *escaped_method, *escaped_sig, *escaped_filename;
-
-                       escaped_assembly = escape_string_for_xml (method->assembly_name);
-                       escaped_class = escape_string_for_xml (method->class_name);
-                       escaped_method = escape_string_for_xml (method->method_name);
-                       escaped_sig = escape_string_for_xml (method->method_signature);
-                       escaped_filename = escape_string_for_xml (method->filename);
-
-                       fprintf (coverage_outfile, "\t<method assembly=\"%s\" class=\"%s\" name=\"%s (%s)\" filename=\"%s\" token=\"%d\">\n", escaped_assembly, escaped_class, escaped_method, escaped_sig, escaped_filename, method->token);
-
-                       g_free (escaped_assembly);
-                       g_free (escaped_class);
-                       g_free (escaped_method);
-                       g_free (escaped_sig);
-                       g_free (escaped_filename);
-
-                       for (guint j = 0; j < method->coverage->len; j++) {
-                               CoverageCoverage *coverage = (CoverageCoverage *)method->coverage->pdata [j];
-                               fprintf (coverage_outfile, "\t\t<statement offset=\"%d\" counter=\"%d\" line=\"%d\" column=\"%d\"/>\n", coverage->offset, coverage->count, coverage->line, coverage->column);
-                       }
-                       fprintf (coverage_outfile, "\t</method>\n");
-               }
-       }
-
-       if (coverage_outfile) {
-               fprintf (coverage_outfile, "</coverage>\n");
-               fclose (coverage_outfile);
-               coverage_outfile = NULL;
-       }
-}
-
-#define DUMP_EVENT_STAT(EVENT,SUBTYPE) dump_event (#EVENT, #SUBTYPE, EVENT, SUBTYPE);
-
-static void
-dump_event (const char *event_name, const char *subtype_name, int event, int subtype)
-{
-       int idx = event | subtype;
-       EventStat evt = stats [idx];
-       if (!evt.count)
-               return;
-
-       fprintf (outfile, "\t%16s\t%26s\tcount %6d\tmin %3d\tmax %6d\tbytes %d\n", event_name, subtype_name, evt.count, evt.min_size, evt.max_size, evt.bytes);
-}
-
-static void
-dump_stats (void)
-{
-       fprintf (outfile, "\nMlpd statistics\n");
-       fprintf (outfile, "\tBuffer count %d\toverhead %d (%d bytes per header)\n", buffer_count, buffer_count * BUFFER_HEADER_SIZE, BUFFER_HEADER_SIZE);
-       fprintf (outfile, "\nEvent details:\n");
-
-       DUMP_EVENT_STAT (TYPE_ALLOC, TYPE_ALLOC_NO_BT);
-       DUMP_EVENT_STAT (TYPE_ALLOC, TYPE_ALLOC_BT);
-
-       DUMP_EVENT_STAT (TYPE_GC, TYPE_GC_EVENT);
-       DUMP_EVENT_STAT (TYPE_GC, TYPE_GC_RESIZE);
-       DUMP_EVENT_STAT (TYPE_GC, TYPE_GC_MOVE);
-       DUMP_EVENT_STAT (TYPE_GC, TYPE_GC_HANDLE_CREATED);
-       DUMP_EVENT_STAT (TYPE_GC, TYPE_GC_HANDLE_DESTROYED);
-       DUMP_EVENT_STAT (TYPE_GC, TYPE_GC_HANDLE_CREATED_BT);
-       DUMP_EVENT_STAT (TYPE_GC, TYPE_GC_HANDLE_DESTROYED_BT);
-
-       DUMP_EVENT_STAT (TYPE_METADATA, TYPE_END_LOAD);
-       DUMP_EVENT_STAT (TYPE_METADATA, TYPE_END_UNLOAD);
-
-       DUMP_EVENT_STAT (TYPE_METHOD, TYPE_LEAVE);
-       DUMP_EVENT_STAT (TYPE_METHOD, TYPE_ENTER);
-       DUMP_EVENT_STAT (TYPE_METHOD, TYPE_EXC_LEAVE);
-       DUMP_EVENT_STAT (TYPE_METHOD, TYPE_JIT);
-
-       DUMP_EVENT_STAT (TYPE_EXCEPTION, TYPE_THROW_NO_BT);
-       DUMP_EVENT_STAT (TYPE_EXCEPTION, TYPE_THROW_BT);
-       DUMP_EVENT_STAT (TYPE_EXCEPTION, TYPE_CLAUSE);
-
-       DUMP_EVENT_STAT (TYPE_MONITOR, TYPE_MONITOR_NO_BT);
-       DUMP_EVENT_STAT (TYPE_MONITOR, TYPE_MONITOR_BT);
-
-       DUMP_EVENT_STAT (TYPE_HEAP, TYPE_HEAP_START);
-       DUMP_EVENT_STAT (TYPE_HEAP, TYPE_HEAP_END);
-       DUMP_EVENT_STAT (TYPE_HEAP, TYPE_HEAP_OBJECT);
-       DUMP_EVENT_STAT (TYPE_HEAP, TYPE_HEAP_ROOT);
-
-       DUMP_EVENT_STAT (TYPE_SAMPLE, TYPE_SAMPLE_HIT);
-       DUMP_EVENT_STAT (TYPE_SAMPLE, TYPE_SAMPLE_USYM);
-       DUMP_EVENT_STAT (TYPE_SAMPLE, TYPE_SAMPLE_UBIN);
-       DUMP_EVENT_STAT (TYPE_SAMPLE, TYPE_SAMPLE_COUNTERS_DESC);
-       DUMP_EVENT_STAT (TYPE_SAMPLE, TYPE_SAMPLE_COUNTERS);
-
-       DUMP_EVENT_STAT (TYPE_RUNTIME, TYPE_JITHELPER);
-
-       DUMP_EVENT_STAT (TYPE_COVERAGE, TYPE_COVERAGE_ASSEMBLY);
-       DUMP_EVENT_STAT (TYPE_COVERAGE, TYPE_COVERAGE_METHOD);
-       DUMP_EVENT_STAT (TYPE_COVERAGE, TYPE_COVERAGE_STATEMENT);
-       DUMP_EVENT_STAT (TYPE_COVERAGE, TYPE_COVERAGE_CLASS);
-
-       DUMP_EVENT_STAT (TYPE_META, TYPE_SYNC_POINT);
-}
-
-
-
-static void
-flush_context (ProfContext *ctx)
-{
-       ThreadContext *thread;
-       /* FIXME: sometimes there are leftovers: indagate */
-       for (thread = ctx->threads; thread; thread = thread->next) {
-               while (thread->stack_id) {
-                       if (debug)
-                               fprintf (outfile, "thread %p has %d items on stack\n", (void*)thread->thread_id, thread->stack_id);
-                       pop_method (thread, thread->stack [thread->stack_id - 1], thread->last_time);
-               }
-       }
-}
-
-static const char *reports = "header,jit,gc,sample,alloc,call,metadata,exception,monitor,thread,heapshot,counters,coverage";
-
-static const char*
-match_option (const char *p, const char *opt)
-{
-       int len = strlen (opt);
-       if (strncmp (p, opt, len) == 0) {
-               if (p [len] == ',')
-                       len++;
-               return p + len;
-       }
-       return p;
-}
-
-static int
-print_reports (ProfContext *ctx, const char *reps, int parse_only)
-{
-       const char *opt;
-       const char *p;
-       for (p = reps; *p; p = opt) {
-               if ((opt = match_option (p, "header")) != p) {
-                       if (!parse_only)
-                               dump_header (ctx);
-                       continue;
-               }
-               if ((opt = match_option (p, "thread")) != p) {
-                       if (!parse_only)
-                               dump_threads (ctx);
-                       continue;
-               }
-               if ((opt = match_option (p, "domain")) != p) {
-                       if (!parse_only)
-                               dump_domains (ctx);
-                       continue;
-               }
-               if ((opt = match_option (p, "context")) != p) {
-                       if (!parse_only)
-                               dump_remctxs (ctx);
-                       continue;
-               }
-               if ((opt = match_option (p, "gc")) != p) {
-                       if (!parse_only)
-                               dump_gcs ();
-                       continue;
-               }
-               if ((opt = match_option (p, "jit")) != p) {
-                       if (!parse_only)
-                               dump_jit ();
-                       continue;
-               }
-               if ((opt = match_option (p, "alloc")) != p) {
-                       if (!parse_only)
-                               dump_allocations ();
-                       continue;
-               }
-               if ((opt = match_option (p, "call")) != p) {
-                       if (!parse_only)
-                               dump_methods ();
-                       continue;
-               }
-               if ((opt = match_option (p, "metadata")) != p) {
-                       if (!parse_only)
-                               dump_metadata ();
-                       continue;
-               }
-               if ((opt = match_option (p, "exception")) != p) {
-                       if (!parse_only)
-                               dump_exceptions ();
-                       continue;
-               }
-               if ((opt = match_option (p, "monitor")) != p) {
-                       if (!parse_only)
-                               dump_monitors ();
-                       continue;
-               }
-               if ((opt = match_option (p, "heapshot")) != p) {
-                       if (!parse_only)
-                               dump_heap_shots ();
-                       continue;
-               }
-               if ((opt = match_option (p, "sample")) != p) {
-                       if (!parse_only)
-                               dump_samples ();
-                       continue;
-               }
-               if ((opt = match_option (p, "counters")) != p) {
-                       if (!parse_only)
-                               dump_counters ();
-                       continue;
-               }
-               if ((opt = match_option (p, "coverage")) != p) {
-                       if (!parse_only)
-                               dump_coverage ();
-                       continue;
-               }
-               if ((opt = match_option (p, "stats")) != p) {
-                       if (!parse_only)
-                               dump_stats ();
-                       continue;
-               }
-               return 0;
-       }
-       return 1;
-}
-
-static int
-add_find_spec (const char *p)
-{
-       if (p [0] == 'S' && p [1] == ':') {
-               char *vale;
-               find_size = strtoul (p + 2, &vale, 10);
-               return 1;
-       } else if (p [0] == 'T' && p [1] == ':') {
-               find_name = p + 2;
-               return 1;
-       }
-       return 0;
-}
-
-static void
-usage (void)
-{
-       printf ("Mono log profiler report version %d.%d\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR);
-       printf ("Usage: mprof-report [OPTIONS] FILENAME\n");
-       printf ("FILENAME can be '-' to read from standard input.\n");
-       printf ("Options:\n");
-       printf ("\t--help               display this help\n");
-       printf ("\t--out=FILE           write to FILE instead of stdout\n");
-       printf ("\t--traces             collect and show backtraces\n");
-       printf ("\t--maxframes=NUM      limit backtraces to NUM entries\n");
-       printf ("\t--reports=R1[,R2...] print the specified reports. Defaults are:\n");
-       printf ("\t                     %s\n", reports);
-       printf ("\t--method-sort=MODE   sort methods according to MODE: total, self, calls\n");
-       printf ("\t--alloc-sort=MODE    sort allocations according to MODE: bytes, count\n");
-       printf ("\t--counters-sort=MODE sort counters according to MODE: time, category\n");
-       printf ("\t                     only accessible in verbose mode\n");
-       printf ("\t--track=OB1[,OB2...] track what happens to objects OBJ1, O2 etc.\n");
-       printf ("\t--find=FINDSPEC      find and track objects matching FINFSPEC, where FINDSPEC is:\n");
-       printf ("\t                     S:minimum_size or T:partial_name\n");
-       printf ("\t--thread=THREADID    consider just the data for thread THREADID\n");
-       printf ("\t--time=FROM-TO       consider data FROM seconds from startup up to TO seconds\n");
-       printf ("\t--verbose            increase verbosity level\n");
-       printf ("\t--debug              display decoding debug info for mprof-report devs\n");
-       printf ("\t--coverage-out=FILE  write the coverage info to FILE as XML\n");
-}
-
-int
-main (int argc, char *argv[])
-{
-       ProfContext *ctx;
-       int i;
-       outfile = stdout;
-       for (i = 1; i < argc; ++i) {
-               if (strcmp ("--debug", argv [i]) == 0) {
-                       debug++;
-               } else if (strcmp ("--help", argv [i]) == 0) {
-                       usage ();
-                       return 0;
-               } else if (strncmp ("--alloc-sort=", argv [i], 13) == 0) {
-                       const char *val = argv [i] + 13;
-                       if (strcmp (val, "bytes") == 0) {
-                               alloc_sort_mode = ALLOC_SORT_BYTES;
-                       } else if (strcmp (val, "count") == 0) {
-                               alloc_sort_mode = ALLOC_SORT_COUNT;
-                       } else {
-                               usage ();
-                               return 1;
-                       }
-               } else if (strncmp ("--method-sort=", argv [i], 14) == 0) {
-                       const char *val = argv [i] + 14;
-                       if (strcmp (val, "total") == 0) {
-                               method_sort_mode = METHOD_SORT_TOTAL;
-                       } else if (strcmp (val, "self") == 0) {
-                               method_sort_mode = METHOD_SORT_SELF;
-                       } else if (strcmp (val, "calls") == 0) {
-                               method_sort_mode = METHOD_SORT_CALLS;
-                       } else {
-                               usage ();
-                               return 1;
-                       }
-               } else if (strncmp ("--counters-sort=", argv [i], 16) == 0) {
-                       const char *val = argv [i] + 16;
-                       if (strcmp (val, "time") == 0) {
-                               counters_sort_mode = COUNTERS_SORT_TIME;
-                       } else if (strcmp (val, "category") == 0) {
-                               counters_sort_mode = COUNTERS_SORT_CATEGORY;
-                       } else {
-                               usage ();
-                               return 1;
-                       }
-               } else if (strncmp ("--reports=", argv [i], 10) == 0) {
-                       const char *val = argv [i] + 10;
-                       if (!print_reports (NULL, val, 1)) {
-                               usage ();
-                               return 1;
-                       }
-                       reports = val;
-               } else if (strncmp ("--out=", argv [i], 6) == 0) {
-                       const char *val = argv [i] + 6;
-                       outfile = fopen (val, "w");
-                       if (!outfile) {
-                               printf ("Cannot open output file: %s\n", val);
-                               return 1;
-                       }
-               } else if (strncmp ("--maxframes=", argv [i], 12) == 0) {
-                       const char *val = argv [i] + 12;
-                       char *vale;
-                       trace_max = strtoul (val, &vale, 10);
-               } else if (strncmp ("--find=", argv [i], 7) == 0) {
-                       const char *val = argv [i] + 7;
-                       if (!add_find_spec (val)) {
-                               usage ();
-                               return 1;
-                       }
-               } else if (strncmp ("--track=", argv [i], 8) == 0) {
-                       const char *val = argv [i] + 8;
-                       char *vale;
-                       while (*val) {
-                               uintptr_t tracked_obj;
-                               if (*val == ',') {
-                                       val++;
-                                       continue;
-                               }
-                               tracked_obj = strtoul (val, &vale, 0);
-                               found_object (tracked_obj);
-                               val = vale;
-                       }
-               } else if (strncmp ("--thread=", argv [i], 9) == 0) {
-                       const char *val = argv [i] + 9;
-                       char *vale;
-                       thread_filter = strtoul (val, &vale, 0);
-               } else if (strncmp ("--time=", argv [i], 7) == 0) {
-                       char *val = pstrdup (argv [i] + 7);
-                       double from_secs, to_secs;
-                       char *top = strchr (val, '-');
-                       if (!top) {
-                               usage ();
-                               return 1;
-                       }
-                       *top++ = 0;
-                       from_secs = atof (val);
-                       to_secs = atof (top);
-                       g_free (val);
-                       if (from_secs > to_secs) {
-                               usage ();
-                               return 1;
-                       }
-                       time_from = from_secs * 1000000000;
-                       time_to = to_secs * 1000000000;
-                       use_time_filter = 1;
-               } else if (strcmp ("--verbose", argv [i]) == 0) {
-                       verbose++;
-               } else if (strcmp ("--traces", argv [i]) == 0) {
-                       show_traces = 1;
-                       collect_traces = 1;
-               } else if (strncmp ("--coverage-out=", argv [i], 15) == 0) {
-                       const char *val = argv [i] + 15;
-                       coverage_outfile = fopen (val, "w");
-                       if (!coverage_outfile) {
-                               printf ("Cannot open output file: %s\n", val);
-                               return 1;
-                       }
-               } else {
-                       break;
-               }
-       }
-       if (i >= argc) {
-               usage ();
-               return 2;
-       }
-       ctx = load_file (argv [i]);
-       if (!ctx) {
-               printf ("Not a log profiler data file (or unsupported version).\n");
-               return 1;
-       }
-       while (decode_buffer (ctx));
-       flush_context (ctx);
-       if (num_tracked_objects)
-               return 0;
-       print_reports (ctx, reports, 0);
-       return 0;
-}
diff --git a/mono/profiler/mono-profiler-log.c b/mono/profiler/mono-profiler-log.c
new file mode 100644 (file)
index 0000000..67741d9
--- /dev/null
@@ -0,0 +1,5029 @@
+/*
+ * mono-profiler-log.c: mono log profiler
+ *
+ * Authors:
+ *   Paolo Molaro (lupus@ximian.com)
+ *   Alex Rønne Petersen (alexrp@xamarin.com)
+ *
+ * Copyright 2010 Novell, Inc (http://www.novell.com)
+ * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+
+#include <config.h>
+#include <mono/metadata/assembly.h>
+#include <mono/metadata/debug-helpers.h>
+#include "../metadata/metadata-internals.h"
+#include <mono/metadata/mono-config.h>
+#include <mono/metadata/mono-gc.h>
+#include <mono/metadata/mono-perfcounters.h>
+#include <mono/metadata/profiler.h>
+#include <mono/utils/atomic.h>
+#include <mono/utils/hazard-pointer.h>
+#include <mono/utils/lock-free-alloc.h>
+#include <mono/utils/lock-free-queue.h>
+#include <mono/utils/mono-conc-hashtable.h>
+#include <mono/utils/mono-counters.h>
+#include <mono/utils/mono-linked-list-set.h>
+#include <mono/utils/mono-membar.h>
+#include <mono/utils/mono-mmap.h>
+#include <mono/utils/mono-os-mutex.h>
+#include <mono/utils/mono-os-semaphore.h>
+#include <mono/utils/mono-threads.h>
+#include <mono/utils/mono-threads-api.h>
+#include "mono-profiler-log.h"
+
+#ifdef HAVE_DLFCN_H
+#include <dlfcn.h>
+#endif
+#include <fcntl.h>
+#ifdef HAVE_LINK_H
+#include <link.h>
+#endif
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#if defined(__APPLE__)
+#include <mach/mach_time.h>
+#endif
+#include <netinet/in.h>
+#ifdef HAVE_SYS_MMAN_H
+#include <sys/mman.h>
+#endif
+#include <sys/socket.h>
+#if defined (HAVE_SYS_ZLIB)
+#include <zlib.h>
+#endif
+
+#define BUFFER_SIZE (4096 * 16)
+
+/* Worst-case size in bytes of a 64-bit value encoded with LEB128. */
+#define LEB128_SIZE 10
+
+/* Size of a value encoded as a single byte. */
+#undef BYTE_SIZE // mach/i386/vm_param.h on OS X defines this to 8, but it isn't used for anything.
+#define BYTE_SIZE 1
+
+/* Size in bytes of the event prefix (ID + time). */
+#define EVENT_SIZE (BYTE_SIZE + LEB128_SIZE)
+
+static volatile gint32 runtime_inited;
+static volatile gint32 in_shutdown;
+
+static gboolean no_counters;
+static int nocalls = 0;
+static int notraces = 0;
+static int use_zip = 0;
+static int do_report = 0;
+static int do_heap_shot = 0;
+static int max_call_depth = 100;
+static int command_port = 0;
+static int heapshot_requested = 0;
+static int sample_freq = 0;
+static int do_mono_sample = 0;
+static int do_debug = 0;
+static int do_coverage = 0;
+static gboolean only_coverage;
+static gboolean debug_coverage = FALSE;
+static MonoProfileSamplingMode sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
+static int max_allocated_sample_hits;
+
+// Statistics for internal profiler data structures.
+static gint32 sample_allocations_ctr,
+              buffer_allocations_ctr;
+
+// Statistics for profiler events.
+static gint32 sync_points_ctr,
+              heap_objects_ctr,
+              heap_starts_ctr,
+              heap_ends_ctr,
+              heap_roots_ctr,
+              gc_events_ctr,
+              gc_resizes_ctr,
+              gc_allocs_ctr,
+              gc_moves_ctr,
+              gc_handle_creations_ctr,
+              gc_handle_deletions_ctr,
+              finalize_begins_ctr,
+              finalize_ends_ctr,
+              finalize_object_begins_ctr,
+              finalize_object_ends_ctr,
+              image_loads_ctr,
+              image_unloads_ctr,
+              assembly_loads_ctr,
+              assembly_unloads_ctr,
+              class_loads_ctr,
+              class_unloads_ctr,
+              method_entries_ctr,
+              method_exits_ctr,
+              method_exception_exits_ctr,
+              method_jits_ctr,
+              code_buffers_ctr,
+              exception_throws_ctr,
+              exception_clauses_ctr,
+              monitor_contentions_ctr,
+              monitor_acquisitions_ctr,
+              monitor_failures_ctr,
+              thread_starts_ctr,
+              thread_ends_ctr,
+              thread_names_ctr,
+              domain_loads_ctr,
+              domain_unloads_ctr,
+              domain_names_ctr,
+              context_loads_ctr,
+              context_unloads_ctr,
+              sample_ubins_ctr,
+              sample_usyms_ctr,
+              sample_hits_ctr,
+              counter_descriptors_ctr,
+              counter_samples_ctr,
+              perfcounter_descriptors_ctr,
+              perfcounter_samples_ctr,
+              coverage_methods_ctr,
+              coverage_statements_ctr,
+              coverage_classes_ctr,
+              coverage_assemblies_ctr;
+
+static MonoLinkedListSet profiler_thread_list;
+
+/*
+ * file format:
+ * [header] [buffer]*
+ *
+ * The file is composed by a header followed by 0 or more buffers.
+ * Each buffer contains events that happened on a thread: for a given thread
+ * buffers that appear later in the file are guaranteed to contain events
+ * that happened later in time. Buffers from separate threads could be interleaved,
+ * though.
+ * Buffers are not required to be aligned.
+ *
+ * header format:
+ * [id: 4 bytes] constant value: LOG_HEADER_ID
+ * [major: 1 byte] [minor: 1 byte] major and minor version of the log profiler
+ * [format: 1 byte] version of the data format for the rest of the file
+ * [ptrsize: 1 byte] size in bytes of a pointer in the profiled program
+ * [startup time: 8 bytes] time in milliseconds since the unix epoch when the program started
+ * [timer overhead: 4 bytes] approximate overhead in nanoseconds of the timer
+ * [flags: 4 bytes] file format flags, should be 0 for now
+ * [pid: 4 bytes] pid of the profiled process
+ * [port: 2 bytes] tcp port for server if != 0
+ * [args size: 4 bytes] size of args
+ * [args: string] arguments passed to the profiler
+ * [arch size: 4 bytes] size of arch
+ * [arch: string] architecture the profiler is running on
+ * [os size: 4 bytes] size of os
+ * [os: string] operating system the profiler is running on
+ *
+ * The multiple byte integers are in little-endian format.
+ *
+ * buffer format:
+ * [buffer header] [event]*
+ * Buffers have a fixed-size header followed by 0 or more bytes of event data.
+ * Timing information and other values in the event data are usually stored
+ * as uleb128 or sleb128 integers. To save space, as noted for each item below,
+ * some data is represented as a difference between the actual value and
+ * either the last value of the same type (like for timing information) or
+ * as the difference from a value stored in a buffer header.
+ *
+ * For timing information the data is stored as uleb128, since timing
+ * increases in a monotonic way in each thread: the value is the number of
+ * nanoseconds to add to the last seen timing data in a buffer. The first value
+ * in a buffer will be calculated from the time_base field in the buffer head.
+ *
+ * Object or heap sizes are stored as uleb128.
+ * Pointer differences are stored as sleb128, instead.
+ *
+ * If an unexpected value is found, the rest of the buffer should be ignored,
+ * as generally the later values need the former to be interpreted correctly.
+ *
+ * buffer header format:
+ * [bufid: 4 bytes] constant value: BUF_ID
+ * [len: 4 bytes] size of the data following the buffer header
+ * [time_base: 8 bytes] time base in nanoseconds since an unspecified epoch
+ * [ptr_base: 8 bytes] base value for pointers
+ * [obj_base: 8 bytes] base value for object addresses
+ * [thread id: 8 bytes] system-specific thread ID (pthread_t for example)
+ * [method_base: 8 bytes] base value for MonoMethod pointers
+ *
+ * event format:
+ * [extended info: upper 4 bits] [type: lower 4 bits]
+ * [time diff: uleb128] nanoseconds since last timing
+ * [data]*
+ * The data that follows depends on type and the extended info.
+ * Type is one of the enum values in mono-profiler-log.h: TYPE_ALLOC, TYPE_GC,
+ * TYPE_METADATA, TYPE_METHOD, TYPE_EXCEPTION, TYPE_MONITOR, TYPE_HEAP.
+ * The extended info bits are interpreted based on type, see
+ * each individual event description below.
+ * strings are represented as a 0-terminated utf8 sequence.
+ *
+ * backtrace format:
+ * [num: uleb128] number of frames following
+ * [frame: sleb128]* mum MonoMethod* as a pointer difference from the last such
+ * pointer or the buffer method_base
+ *
+ * type alloc format:
+ * type: TYPE_ALLOC
+ * exinfo: flags: TYPE_ALLOC_BT
+ * [ptr: sleb128] class as a byte difference from ptr_base
+ * [obj: sleb128] object address as a byte difference from obj_base
+ * [size: uleb128] size of the object in the heap
+ * If the TYPE_ALLOC_BT flag is set, a backtrace follows.
+ *
+ * type GC format:
+ * type: TYPE_GC
+ * exinfo: one of TYPE_GC_EVENT, TYPE_GC_RESIZE, TYPE_GC_MOVE, TYPE_GC_HANDLE_CREATED[_BT],
+ * TYPE_GC_HANDLE_DESTROYED[_BT], TYPE_GC_FINALIZE_START, TYPE_GC_FINALIZE_END,
+ * TYPE_GC_FINALIZE_OBJECT_START, TYPE_GC_FINALIZE_OBJECT_END
+ * if exinfo == TYPE_GC_RESIZE
+ *     [heap_size: uleb128] new heap size
+ * if exinfo == TYPE_GC_EVENT
+ *     [event type: byte] GC event (MONO_GC_EVENT_* from profiler.h)
+ *     [generation: byte] GC generation event refers to
+ * if exinfo == TYPE_GC_MOVE
+ *     [num_objects: uleb128] number of object moves that follow
+ *     [objaddr: sleb128]+ num_objects object pointer differences from obj_base
+ *     num is always an even number: the even items are the old
+ *     addresses, the odd numbers are the respective new object addresses
+ * if exinfo == TYPE_GC_HANDLE_CREATED[_BT]
+ *     [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
+ *     upper bits reserved as flags
+ *     [handle: uleb128] GC handle value
+ *     [objaddr: sleb128] object pointer differences from obj_base
+ *     If exinfo == TYPE_GC_HANDLE_CREATED_BT, a backtrace follows.
+ * if exinfo == TYPE_GC_HANDLE_DESTROYED[_BT]
+ *     [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
+ *     upper bits reserved as flags
+ *     [handle: uleb128] GC handle value
+ *     If exinfo == TYPE_GC_HANDLE_DESTROYED_BT, a backtrace follows.
+ * if exinfo == TYPE_GC_FINALIZE_OBJECT_{START,END}
+ *     [object: sleb128] the object as a difference from obj_base
+ *
+ * type metadata format:
+ * type: TYPE_METADATA
+ * exinfo: one of: TYPE_END_LOAD, TYPE_END_UNLOAD (optional for TYPE_THREAD and TYPE_DOMAIN)
+ * [mtype: byte] metadata type, one of: TYPE_CLASS, TYPE_IMAGE, TYPE_ASSEMBLY, TYPE_DOMAIN,
+ * TYPE_THREAD, TYPE_CONTEXT
+ * [pointer: sleb128] pointer of the metadata type depending on mtype
+ * if mtype == TYPE_CLASS
+ *     [image: sleb128] MonoImage* as a pointer difference from ptr_base
+ *     [name: string] full class name
+ * if mtype == TYPE_IMAGE
+ *     [name: string] image file name
+ * if mtype == TYPE_ASSEMBLY
+ *     [name: string] assembly name
+ * if mtype == TYPE_DOMAIN && exinfo == 0
+ *     [name: string] domain friendly name
+ * if mtype == TYPE_CONTEXT
+ *     [domain: sleb128] domain id as pointer
+ * if mtype == TYPE_THREAD && exinfo == 0
+ *     [name: string] thread name
+ *
+ * type method format:
+ * type: TYPE_METHOD
+ * exinfo: one of: TYPE_LEAVE, TYPE_ENTER, TYPE_EXC_LEAVE, TYPE_JIT
+ * [method: sleb128] MonoMethod* as a pointer difference from the last such
+ * pointer or the buffer method_base
+ * if exinfo == TYPE_JIT
+ *     [code address: sleb128] pointer to the native code as a diff from ptr_base
+ *     [code size: uleb128] size of the generated code
+ *     [name: string] full method name
+ *
+ * type exception format:
+ * type: TYPE_EXCEPTION
+ * exinfo: TYPE_THROW_BT flag or one of: TYPE_CLAUSE
+ * if exinfo == TYPE_CLAUSE
+ *     [clause type: byte] MonoExceptionEnum enum value
+ *     [clause index: uleb128] index of the current clause
+ *     [method: sleb128] MonoMethod* as a pointer difference from the last such
+ *     pointer or the buffer method_base
+ * else
+ *     [object: sleb128] the exception object as a difference from obj_base
+ *     if exinfo has TYPE_THROW_BT set, a backtrace follows.
+ *
+ * type runtime format:
+ * type: TYPE_RUNTIME
+ * exinfo: one of: TYPE_JITHELPER
+ * if exinfo == TYPE_JITHELPER
+ *     [type: byte] MonoProfilerCodeBufferType enum value
+ *     [buffer address: sleb128] pointer to the native code as a diff from ptr_base
+ *     [buffer size: uleb128] size of the generated code
+ *     if type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE
+ *             [name: string] buffer description name
+ *
+ * type monitor format:
+ * type: TYPE_MONITOR
+ * exinfo: TYPE_MONITOR_BT flag and one of: MONO_PROFILER_MONITOR_(CONTENTION|FAIL|DONE)
+ * [object: sleb128] the lock object as a difference from obj_base
+ * if exinfo.low3bits == MONO_PROFILER_MONITOR_CONTENTION
+ *     If the TYPE_MONITOR_BT flag is set, a backtrace follows.
+ *
+ * type heap format
+ * type: TYPE_HEAP
+ * exinfo: one of TYPE_HEAP_START, TYPE_HEAP_END, TYPE_HEAP_OBJECT, TYPE_HEAP_ROOT
+ * if exinfo == TYPE_HEAP_OBJECT
+ *     [object: sleb128] the object as a difference from obj_base
+ *     [class: sleb128] the object MonoClass* as a difference from ptr_base
+ *     [size: uleb128] size of the object on the heap
+ *     [num_refs: uleb128] number of object references
+ *     each referenced objref is preceded by a uleb128 encoded offset: the
+ *     first offset is from the object address and each next offset is relative
+ *     to the previous one
+ *     [objrefs: sleb128]+ object referenced as a difference from obj_base
+ *     The same object can appear multiple times, but only the first time
+ *     with size != 0: in the other cases this data will only be used to
+ *     provide additional referenced objects.
+ * if exinfo == TYPE_HEAP_ROOT
+ *     [num_roots: uleb128] number of root references
+ *     [num_gc: uleb128] number of major gcs
+ *     [object: sleb128] the object as a difference from obj_base
+ *     [root_type: byte] the root_type: MonoProfileGCRootType (profiler.h)
+ *     [extra_info: uleb128] the extra_info value
+ *     object, root_type and extra_info are repeated num_roots times
+ *
+ * type sample format
+ * type: TYPE_SAMPLE
+ * exinfo: one of TYPE_SAMPLE_HIT, TYPE_SAMPLE_USYM, TYPE_SAMPLE_UBIN, TYPE_SAMPLE_COUNTERS_DESC, TYPE_SAMPLE_COUNTERS
+ * if exinfo == TYPE_SAMPLE_HIT
+ *     [thread: sleb128] thread id as difference from ptr_base
+ *     [count: uleb128] number of following instruction addresses
+ *     [ip: sleb128]* instruction pointer as difference from ptr_base
+ *     [mbt_count: uleb128] number of managed backtrace frames
+ *     [method: sleb128]* MonoMethod* as a pointer difference from the last such
+ *     pointer or the buffer method_base (the first such method can be also indentified by ip, but this is not neccessarily true)
+ * if exinfo == TYPE_SAMPLE_USYM
+ *     [address: sleb128] symbol address as a difference from ptr_base
+ *     [size: uleb128] symbol size (may be 0 if unknown)
+ *     [name: string] symbol name
+ * if exinfo == TYPE_SAMPLE_UBIN
+ *     [address: sleb128] address where binary has been loaded
+ *     [offset: uleb128] file offset of mapping (the same file can be mapped multiple times)
+ *     [size: uleb128] memory size
+ *     [name: string] binary name
+ * if exinfo == TYPE_SAMPLE_COUNTERS_DESC
+ *     [len: uleb128] number of counters
+ *     for i = 0 to len
+ *             [section: uleb128] section of counter
+ *             if section == MONO_COUNTER_PERFCOUNTERS:
+ *                     [section_name: string] section name of counter
+ *             [name: string] name of counter
+ *             [type: byte] type of counter
+ *             [unit: byte] unit of counter
+ *             [variance: byte] variance of counter
+ *             [index: uleb128] unique index of counter
+ * if exinfo == TYPE_SAMPLE_COUNTERS
+ *     while true:
+ *             [index: uleb128] unique index of counter
+ *             if index == 0:
+ *                     break
+ *             [type: byte] type of counter value
+ *             if type == string:
+ *                     if value == null:
+ *                             [0: uleb128] 0 -> value is null
+ *                     else:
+ *                             [1: uleb128] 1 -> value is not null
+ *                             [value: string] counter value
+ *             else:
+ *                     [value: uleb128/sleb128/double] counter value, can be sleb128, uleb128 or double (determined by using type)
+ *
+ * type coverage format
+ * type: TYPE_COVERAGE
+ * exinfo: one of TYPE_COVERAGE_METHOD, TYPE_COVERAGE_STATEMENT, TYPE_COVERAGE_ASSEMBLY, TYPE_COVERAGE_CLASS
+ * if exinfo == TYPE_COVERAGE_METHOD
+ *  [assembly: string] name of assembly
+ *  [class: string] name of the class
+ *  [name: string] name of the method
+ *  [signature: string] the signature of the method
+ *  [filename: string] the file path of the file that contains this method
+ *  [token: uleb128] the method token
+ *  [method_id: uleb128] an ID for this data to associate with the buffers of TYPE_COVERAGE_STATEMENTS
+ *  [len: uleb128] the number of TYPE_COVERAGE_BUFFERS associated with this method
+ * if exinfo == TYPE_COVERAGE_STATEMENTS
+ *  [method_id: uleb128] an the TYPE_COVERAGE_METHOD buffer to associate this with
+ *  [offset: uleb128] the il offset relative to the previous offset
+ *  [counter: uleb128] the counter for this instruction
+ *  [line: uleb128] the line of filename containing this instruction
+ *  [column: uleb128] the column containing this instruction
+ * if exinfo == TYPE_COVERAGE_ASSEMBLY
+ *  [name: string] assembly name
+ *  [guid: string] assembly GUID
+ *  [filename: string] assembly filename
+ *  [number_of_methods: uleb128] the number of methods in this assembly
+ *  [fully_covered: uleb128] the number of fully covered methods
+ *  [partially_covered: uleb128] the number of partially covered methods
+ *    currently partially_covered will always be 0, and fully_covered is the
+ *    number of methods that are fully and partially covered.
+ * if exinfo == TYPE_COVERAGE_CLASS
+ *  [name: string] assembly name
+ *  [class: string] class name
+ *  [number_of_methods: uleb128] the number of methods in this class
+ *  [fully_covered: uleb128] the number of fully covered methods
+ *  [partially_covered: uleb128] the number of partially covered methods
+ *    currently partially_covered will always be 0, and fully_covered is the
+ *    number of methods that are fully and partially covered.
+ *
+ * type meta format:
+ * type: TYPE_META
+ * exinfo: one of: TYPE_SYNC_POINT
+ * if exinfo == TYPE_SYNC_POINT
+ *     [type: byte] MonoProfilerSyncPointType enum value
+ */
+
+// Pending data to be written to the log, for a single thread.
+// Threads periodically flush their own LogBuffers by calling safe_send
+typedef struct _LogBuffer LogBuffer;
+struct _LogBuffer {
+       // Next (older) LogBuffer in processing queue
+       LogBuffer *next;
+
+       uint64_t time_base;
+       uint64_t last_time;
+       uintptr_t ptr_base;
+       uintptr_t method_base;
+       uintptr_t last_method;
+       uintptr_t obj_base;
+       uintptr_t thread_id;
+
+       // Bytes allocated for this LogBuffer
+       int size;
+
+       // Start of currently unused space in buffer
+       unsigned char* cursor;
+
+       // Pointer to start-of-structure-plus-size (for convenience)
+       unsigned char* buf_end;
+
+       // Start of data in buffer. Contents follow "buffer format" described above.
+       unsigned char buf [1];
+};
+
+typedef struct {
+       MonoLinkedListSetNode node;
+
+       // Convenience pointer to the profiler structure.
+       MonoProfiler *profiler;
+
+       // Was this thread added to the LLS?
+       gboolean attached;
+
+       // The current log buffer for this thread.
+       LogBuffer *buffer;
+
+       // Methods referenced by events in `buffer`, see `MethodInfo`.
+       GPtrArray *methods;
+
+       // Current call depth for enter/leave events.
+       int call_depth;
+
+       // Indicates whether this thread is currently writing to its `buffer`.
+       gboolean busy;
+
+       // Has this thread written a thread end event to `buffer`?
+       gboolean ended;
+} MonoProfilerThread;
+
+static uintptr_t
+thread_id (void)
+{
+       return (uintptr_t) mono_native_thread_id_get ();
+}
+
+static uintptr_t
+process_id (void)
+{
+#ifdef HOST_WIN32
+       return (uintptr_t) GetCurrentProcessId ();
+#else
+       return (uintptr_t) getpid ();
+#endif
+}
+
+#ifdef __APPLE__
+static mach_timebase_info_data_t timebase_info;
+#elif defined (HOST_WIN32)
+static LARGE_INTEGER pcounter_freq;
+#endif
+
+#define TICKS_PER_SEC 1000000000LL
+
+static uint64_t
+current_time (void)
+{
+#ifdef __APPLE__
+       uint64_t time = mach_absolute_time ();
+
+       time *= timebase_info.numer;
+       time /= timebase_info.denom;
+
+       return time;
+#elif defined (HOST_WIN32)
+       LARGE_INTEGER value;
+
+       QueryPerformanceCounter (&value);
+
+       return value.QuadPart * TICKS_PER_SEC / pcounter_freq.QuadPart;
+#elif defined (CLOCK_MONOTONIC)
+       struct timespec tspec;
+
+       clock_gettime (CLOCK_MONOTONIC, &tspec);
+
+       return ((uint64_t) tspec.tv_sec * TICKS_PER_SEC + tspec.tv_nsec);
+#else
+       struct timeval tv;
+
+       gettimeofday (&tv, NULL);
+
+       return ((uint64_t) tv.tv_sec * TICKS_PER_SEC + tv.tv_usec * 1000);
+#endif
+}
+
+static int timer_overhead;
+
+static void
+init_time (void)
+{
+#ifdef __APPLE__
+       mach_timebase_info (&timebase_info);
+#elif defined (HOST_WIN32)
+       QueryPerformanceFrequency (&pcounter_freq);
+#endif
+
+       uint64_t time_start = current_time ();
+
+       for (int i = 0; i < 256; ++i)
+               current_time ();
+
+       uint64_t time_end = current_time ();
+
+       timer_overhead = (time_end - time_start) / 256;
+}
+
+/*
+ * These macros should be used when writing an event to a log buffer. They take
+ * care of a bunch of stuff that can be repetitive and error-prone, such as
+ * acquiring/releasing the buffer lock, incrementing the event counter,
+ * expanding the log buffer, processing requests, etc. They also create a scope
+ * so that it's harder to leak the LogBuffer pointer, which can be problematic
+ * as the pointer is unstable when the buffer lock isn't acquired.
+ */
+
+#define ENTER_LOG(COUNTER, BUFFER, SIZE) \
+       do { \
+               MonoProfilerThread *thread__ = PROF_TLS_GET (); \
+               if (thread__->attached) \
+                       buffer_lock (); \
+               g_assert (!thread__->busy && "Why are we trying to write a new event while already writing one?"); \
+               thread__->busy = TRUE; \
+               InterlockedIncrement ((COUNTER)); \
+               LogBuffer *BUFFER = ensure_logbuf_unsafe (thread__, (SIZE))
+
+#define EXIT_LOG_EXPLICIT(SEND, REQUESTS) \
+               thread__->busy = FALSE; \
+               if ((SEND)) \
+                       send_log_unsafe (TRUE); \
+               if (thread__->attached) \
+                       buffer_unlock (); \
+               if ((REQUESTS)) \
+                       process_requests (); \
+       } while (0)
+
+// Pass these to EXIT_LOG_EXPLICIT () for easier reading.
+#define DO_SEND TRUE
+#define NO_SEND FALSE
+#define DO_REQUESTS TRUE
+#define NO_REQUESTS FALSE
+
+#define EXIT_LOG EXIT_LOG_EXPLICIT (DO_SEND, DO_REQUESTS)
+
+static volatile gint32 buffer_rwlock_count;
+static volatile gpointer buffer_rwlock_exclusive;
+
+// Can be used recursively.
+static void
+buffer_lock (void)
+{
+       /*
+        * If the thread holding the exclusive lock tries to modify the
+        * reader count, just make it a no-op. This way, we also avoid
+        * invoking the GC safe point macros below, which could break if
+        * done from a thread that is currently the initiator of STW.
+        *
+        * In other words, we rely on the fact that the GC thread takes
+        * the exclusive lock in the gc_event () callback when the world
+        * is about to stop.
+        */
+       if (InterlockedReadPointer (&buffer_rwlock_exclusive) != (gpointer) thread_id ()) {
+               MONO_ENTER_GC_SAFE;
+
+               while (InterlockedReadPointer (&buffer_rwlock_exclusive))
+                       mono_thread_info_yield ();
+
+               InterlockedIncrement (&buffer_rwlock_count);
+
+               MONO_EXIT_GC_SAFE;
+       }
+
+       mono_memory_barrier ();
+}
+
+static void
+buffer_unlock (void)
+{
+       mono_memory_barrier ();
+
+       // See the comment in buffer_lock ().
+       if (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id ())
+               return;
+
+       g_assert (InterlockedRead (&buffer_rwlock_count) && "Why are we trying to decrement a zero reader count?");
+
+       InterlockedDecrement (&buffer_rwlock_count);
+}
+
+// Cannot be used recursively.
+static void
+buffer_lock_excl (void)
+{
+       gpointer tid = (gpointer) thread_id ();
+
+       g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) != tid && "Why are we taking the exclusive lock twice?");
+
+       MONO_ENTER_GC_SAFE;
+
+       while (InterlockedCompareExchangePointer (&buffer_rwlock_exclusive, tid, 0))
+               mono_thread_info_yield ();
+
+       while (InterlockedRead (&buffer_rwlock_count))
+               mono_thread_info_yield ();
+
+       MONO_EXIT_GC_SAFE;
+
+       mono_memory_barrier ();
+}
+
+static void
+buffer_unlock_excl (void)
+{
+       mono_memory_barrier ();
+
+       g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) && "Why is the exclusive lock not held?");
+       g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id () && "Why does another thread hold the exclusive lock?");
+       g_assert (!InterlockedRead (&buffer_rwlock_count) && "Why are there readers when the exclusive lock is held?");
+
+       InterlockedWritePointer (&buffer_rwlock_exclusive, NULL);
+}
+
+typedef struct _BinaryObject BinaryObject;
+struct _BinaryObject {
+       BinaryObject *next;
+       void *addr;
+       char *name;
+};
+
+struct _MonoProfiler {
+       FILE* file;
+#if defined (HAVE_SYS_ZLIB)
+       gzFile gzfile;
+#endif
+       char *args;
+       uint64_t startup_time;
+       int pipe_output;
+       int command_port;
+       int server_socket;
+       int pipes [2];
+       MonoNativeThreadId helper_thread;
+       MonoNativeThreadId writer_thread;
+       MonoNativeThreadId dumper_thread;
+       volatile gint32 run_writer_thread;
+       MonoLockFreeAllocSizeClass writer_entry_size_class;
+       MonoLockFreeAllocator writer_entry_allocator;
+       MonoLockFreeQueue writer_queue;
+       MonoSemType writer_queue_sem;
+       MonoConcurrentHashTable *method_table;
+       mono_mutex_t method_table_mutex;
+       volatile gint32 run_dumper_thread;
+       MonoLockFreeQueue dumper_queue;
+       MonoSemType dumper_queue_sem;
+       MonoLockFreeAllocSizeClass sample_size_class;
+       MonoLockFreeAllocator sample_allocator;
+       MonoLockFreeQueue sample_reuse_queue;
+       BinaryObject *binary_objects;
+       GPtrArray *coverage_filters;
+};
+
+typedef struct {
+       MonoLockFreeQueueNode node;
+       GPtrArray *methods;
+       LogBuffer *buffer;
+} WriterQueueEntry;
+
+#define WRITER_ENTRY_BLOCK_SIZE (mono_pagesize ())
+
+typedef struct {
+       MonoMethod *method;
+       MonoJitInfo *ji;
+       uint64_t time;
+} MethodInfo;
+
+#ifdef HOST_WIN32
+
+#define PROF_TLS_SET(VAL) (TlsSetValue (profiler_tls, (VAL)))
+#define PROF_TLS_GET() ((MonoProfilerThread *) TlsGetValue (profiler_tls))
+#define PROF_TLS_INIT() (profiler_tls = TlsAlloc ())
+#define PROF_TLS_FREE() (TlsFree (profiler_tls))
+
+static DWORD profiler_tls;
+
+#elif HAVE_KW_THREAD
+
+#define PROF_TLS_SET(VAL) (profiler_tls = (VAL))
+#define PROF_TLS_GET() (profiler_tls)
+#define PROF_TLS_INIT()
+#define PROF_TLS_FREE()
+
+static __thread MonoProfilerThread *profiler_tls;
+
+#else
+
+#define PROF_TLS_SET(VAL) (pthread_setspecific (profiler_tls, (VAL)))
+#define PROF_TLS_GET() ((MonoProfilerThread *) pthread_getspecific (profiler_tls))
+#define PROF_TLS_INIT() (pthread_key_create (&profiler_tls, NULL))
+#define PROF_TLS_FREE() (pthread_key_delete (profiler_tls))
+
+static pthread_key_t profiler_tls;
+
+#endif
+
+static char*
+pstrdup (const char *s)
+{
+       int len = strlen (s) + 1;
+       char *p = (char *) g_malloc (len);
+       memcpy (p, s, len);
+       return p;
+}
+
+static void *
+alloc_buffer (int size)
+{
+       return mono_valloc (NULL, size, MONO_MMAP_READ | MONO_MMAP_WRITE | MONO_MMAP_ANON | MONO_MMAP_PRIVATE, MONO_MEM_ACCOUNT_PROFILER);
+}
+
+static void
+free_buffer (void *buf, int size)
+{
+       mono_vfree (buf, size, MONO_MEM_ACCOUNT_PROFILER);
+}
+
+static LogBuffer*
+create_buffer (uintptr_t tid)
+{
+       LogBuffer* buf = (LogBuffer *) alloc_buffer (BUFFER_SIZE);
+
+       InterlockedIncrement (&buffer_allocations_ctr);
+
+       buf->size = BUFFER_SIZE;
+       buf->time_base = current_time ();
+       buf->last_time = buf->time_base;
+       buf->buf_end = (unsigned char *) buf + buf->size;
+       buf->cursor = buf->buf;
+       buf->thread_id = tid;
+
+       return buf;
+}
+
+/*
+ * Must be called with the reader lock held if thread is the current thread, or
+ * the exclusive lock if thread is a different thread. However, if thread is
+ * the current thread, and init_thread () was called with add_to_lls = FALSE,
+ * then no locking is necessary.
+ */
+static void
+init_buffer_state (MonoProfilerThread *thread)
+{
+       thread->buffer = create_buffer (thread->node.key);
+       thread->methods = NULL;
+}
+
+static void
+clear_hazard_pointers (MonoThreadHazardPointers *hp)
+{
+       mono_hazard_pointer_clear (hp, 0);
+       mono_hazard_pointer_clear (hp, 1);
+       mono_hazard_pointer_clear (hp, 2);
+}
+
+static MonoProfilerThread *
+init_thread (MonoProfiler *prof, gboolean add_to_lls)
+{
+       MonoProfilerThread *thread = PROF_TLS_GET ();
+
+       /*
+        * Sometimes we may try to initialize a thread twice. One example is the
+        * main thread: We initialize it when setting up the profiler, but we will
+        * also get a thread_start () callback for it. Another example is when
+        * attaching new threads to the runtime: We may get a gc_alloc () callback
+        * for that thread's thread object (where we initialize it), soon followed
+        * by a thread_start () callback.
+        *
+        * These cases are harmless anyhow. Just return if we've already done the
+        * initialization work.
+        */
+       if (thread)
+               return thread;
+
+       thread = g_malloc (sizeof (MonoProfilerThread));
+       thread->node.key = thread_id ();
+       thread->profiler = prof;
+       thread->attached = add_to_lls;
+       thread->call_depth = 0;
+       thread->busy = 0;
+       thread->ended = FALSE;
+
+       init_buffer_state (thread);
+
+       /*
+        * Some internal profiler threads don't need to be cleaned up
+        * by the main thread on shutdown.
+        */
+       if (add_to_lls) {
+               MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
+               g_assert (mono_lls_insert (&profiler_thread_list, hp, &thread->node) && "Why can't we insert the thread in the LLS?");
+               clear_hazard_pointers (hp);
+       }
+
+       PROF_TLS_SET (thread);
+
+       return thread;
+}
+
+// Only valid if init_thread () was called with add_to_lls = FALSE.
+static void
+deinit_thread (MonoProfilerThread *thread)
+{
+       g_assert (!thread->attached && "Why are we manually freeing an attached thread?");
+
+       g_free (thread);
+       PROF_TLS_SET (NULL);
+}
+
+// Only valid if init_thread () was called with add_to_lls = FALSE.
+static LogBuffer *
+ensure_logbuf_unsafe (MonoProfilerThread *thread, int bytes)
+{
+       LogBuffer *old = thread->buffer;
+
+       if (old && old->cursor + bytes + 100 < old->buf_end)
+               return old;
+
+       LogBuffer *new_ = create_buffer (thread->node.key);
+       new_->next = old;
+       thread->buffer = new_;
+
+       return new_;
+}
+
+static void
+encode_uleb128 (uint64_t value, uint8_t *buf, uint8_t **endbuf)
+{
+       uint8_t *p = buf;
+
+       do {
+               uint8_t b = value & 0x7f;
+               value >>= 7;
+
+               if (value != 0) /* more bytes to come */
+                       b |= 0x80;
+
+               *p ++ = b;
+       } while (value);
+
+       *endbuf = p;
+}
+
+static void
+encode_sleb128 (intptr_t value, uint8_t *buf, uint8_t **endbuf)
+{
+       int more = 1;
+       int negative = (value < 0);
+       unsigned int size = sizeof (intptr_t) * 8;
+       uint8_t byte;
+       uint8_t *p = buf;
+
+       while (more) {
+               byte = value & 0x7f;
+               value >>= 7;
+
+               /* the following is unnecessary if the
+                * implementation of >>= uses an arithmetic rather
+                * than logical shift for a signed left operand
+                */
+               if (negative)
+                       /* sign extend */
+                       value |= - ((intptr_t) 1 <<(size - 7));
+
+               /* sign bit of byte is second high order bit (0x40) */
+               if ((value == 0 && !(byte & 0x40)) ||
+                   (value == -1 && (byte & 0x40)))
+                       more = 0;
+               else
+                       byte |= 0x80;
+
+               *p ++= byte;
+       }
+
+       *endbuf = p;
+}
+
+static void
+emit_byte (LogBuffer *logbuffer, int value)
+{
+       logbuffer->cursor [0] = value;
+       logbuffer->cursor++;
+
+       g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
+}
+
+static void
+emit_value (LogBuffer *logbuffer, int value)
+{
+       encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
+
+       g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
+}
+
+static void
+emit_time (LogBuffer *logbuffer, uint64_t value)
+{
+       uint64_t tdiff = value - logbuffer->last_time;
+       encode_uleb128 (tdiff, logbuffer->cursor, &logbuffer->cursor);
+       logbuffer->last_time = value;
+
+       g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
+}
+
+static void
+emit_event_time (LogBuffer *logbuffer, int event, uint64_t time)
+{
+       emit_byte (logbuffer, event);
+       emit_time (logbuffer, time);
+}
+
+static void
+emit_event (LogBuffer *logbuffer, int event)
+{
+       emit_event_time (logbuffer, event, current_time ());
+}
+
+static void
+emit_svalue (LogBuffer *logbuffer, int64_t value)
+{
+       encode_sleb128 (value, logbuffer->cursor, &logbuffer->cursor);
+
+       g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
+}
+
+static void
+emit_uvalue (LogBuffer *logbuffer, uint64_t value)
+{
+       encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
+
+       g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
+}
+
+static void
+emit_ptr (LogBuffer *logbuffer, void *ptr)
+{
+       if (!logbuffer->ptr_base)
+               logbuffer->ptr_base = (uintptr_t) ptr;
+
+       emit_svalue (logbuffer, (intptr_t) ptr - logbuffer->ptr_base);
+
+       g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
+}
+
+static void
+emit_method_inner (LogBuffer *logbuffer, void *method)
+{
+       if (!logbuffer->method_base) {
+               logbuffer->method_base = (intptr_t) method;
+               logbuffer->last_method = (intptr_t) method;
+       }
+
+       encode_sleb128 ((intptr_t) ((char *) method - (char *) logbuffer->last_method), logbuffer->cursor, &logbuffer->cursor);
+       logbuffer->last_method = (intptr_t) method;
+
+       g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
+}
+
+static void
+register_method_local (MonoMethod *method, MonoJitInfo *ji)
+{
+       MonoProfilerThread *thread = PROF_TLS_GET ();
+
+       if (!mono_conc_hashtable_lookup (thread->profiler->method_table, method)) {
+               MethodInfo *info = (MethodInfo *) g_malloc (sizeof (MethodInfo));
+
+               info->method = method;
+               info->ji = ji;
+               info->time = current_time ();
+
+               GPtrArray *arr = thread->methods ? thread->methods : (thread->methods = g_ptr_array_new ());
+               g_ptr_array_add (arr, info);
+       }
+}
+
+static void
+emit_method (LogBuffer *logbuffer, MonoMethod *method)
+{
+       register_method_local (method, NULL);
+       emit_method_inner (logbuffer, method);
+}
+
+static void
+emit_obj (LogBuffer *logbuffer, void *ptr)
+{
+       if (!logbuffer->obj_base)
+               logbuffer->obj_base = (uintptr_t) ptr >> 3;
+
+       emit_svalue (logbuffer, ((uintptr_t) ptr >> 3) - logbuffer->obj_base);
+
+       g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
+}
+
+static void
+emit_string (LogBuffer *logbuffer, const char *str, size_t size)
+{
+       size_t i = 0;
+       if (str) {
+               for (; i < size; i++) {
+                       if (str[i] == '\0')
+                               break;
+                       emit_byte (logbuffer, str [i]);
+               }
+       }
+       emit_byte (logbuffer, '\0');
+}
+
+static void
+emit_double (LogBuffer *logbuffer, double value)
+{
+       int i;
+       unsigned char buffer[8];
+       memcpy (buffer, &value, 8);
+#if G_BYTE_ORDER == G_BIG_ENDIAN
+       for (i = 7; i >= 0; i--)
+#else
+       for (i = 0; i < 8; i++)
+#endif
+               emit_byte (logbuffer, buffer[i]);
+}
+
+static char*
+write_int16 (char *buf, int32_t value)
+{
+       int i;
+       for (i = 0; i < 2; ++i) {
+               buf [i] = value;
+               value >>= 8;
+       }
+       return buf + 2;
+}
+
+static char*
+write_int32 (char *buf, int32_t value)
+{
+       int i;
+       for (i = 0; i < 4; ++i) {
+               buf [i] = value;
+               value >>= 8;
+       }
+       return buf + 4;
+}
+
+static char*
+write_int64 (char *buf, int64_t value)
+{
+       int i;
+       for (i = 0; i < 8; ++i) {
+               buf [i] = value;
+               value >>= 8;
+       }
+       return buf + 8;
+}
+
+static char *
+write_header_string (char *p, const char *str)
+{
+       size_t len = strlen (str) + 1;
+
+       p = write_int32 (p, len);
+       strcpy (p, str);
+
+       return p + len;
+}
+
+static void
+dump_header (MonoProfiler *profiler)
+{
+       const char *args = profiler->args;
+       const char *arch = mono_config_get_cpu ();
+       const char *os = mono_config_get_os ();
+
+       char *hbuf = g_malloc (
+               sizeof (gint32) /* header id */ +
+               sizeof (gint8) /* major version */ +
+               sizeof (gint8) /* minor version */ +
+               sizeof (gint8) /* data version */ +
+               sizeof (gint8) /* word size */ +
+               sizeof (gint64) /* startup time */ +
+               sizeof (gint32) /* timer overhead */ +
+               sizeof (gint32) /* flags */ +
+               sizeof (gint32) /* process id */ +
+               sizeof (gint16) /* command port */ +
+               sizeof (gint32) + strlen (args) + 1 /* arguments */ +
+               sizeof (gint32) + strlen (arch) + 1 /* architecture */ +
+               sizeof (gint32) + strlen (os) + 1 /* operating system */
+       );
+       char *p = hbuf;
+
+       p = write_int32 (p, LOG_HEADER_ID);
+       *p++ = LOG_VERSION_MAJOR;
+       *p++ = LOG_VERSION_MINOR;
+       *p++ = LOG_DATA_VERSION;
+       *p++ = sizeof (void *);
+       p = write_int64 (p, ((uint64_t) time (NULL)) * 1000);
+       p = write_int32 (p, timer_overhead);
+       p = write_int32 (p, 0); /* flags */
+       p = write_int32 (p, process_id ());
+       p = write_int16 (p, profiler->command_port);
+       p = write_header_string (p, args);
+       p = write_header_string (p, arch);
+       p = write_header_string (p, os);
+
+#if defined (HAVE_SYS_ZLIB)
+       if (profiler->gzfile) {
+               gzwrite (profiler->gzfile, hbuf, p - hbuf);
+       } else
+#endif
+       {
+               fwrite (hbuf, p - hbuf, 1, profiler->file);
+               fflush (profiler->file);
+       }
+
+       g_free (hbuf);
+}
+
+/*
+ * Must be called with the reader lock held if thread is the current thread, or
+ * the exclusive lock if thread is a different thread. However, if thread is
+ * the current thread, and init_thread () was called with add_to_lls = FALSE,
+ * then no locking is necessary.
+ */
+static void
+send_buffer (MonoProfilerThread *thread)
+{
+       WriterQueueEntry *entry = mono_lock_free_alloc (&thread->profiler->writer_entry_allocator);
+       entry->methods = thread->methods;
+       entry->buffer = thread->buffer;
+
+       mono_lock_free_queue_node_init (&entry->node, FALSE);
+
+       mono_lock_free_queue_enqueue (&thread->profiler->writer_queue, &entry->node);
+       mono_os_sem_post (&thread->profiler->writer_queue_sem);
+}
+
+static void
+free_thread (gpointer p)
+{
+       MonoProfilerThread *thread = p;
+
+       if (!thread->ended) {
+               /*
+                * The thread is being cleaned up by the main thread during
+                * shutdown. This typically happens for internal runtime
+                * threads. We need to synthesize a thread end event.
+                */
+
+               InterlockedIncrement (&thread_ends_ctr);
+
+               LogBuffer *buf = ensure_logbuf_unsafe (thread,
+                       EVENT_SIZE /* event */ +
+                       BYTE_SIZE /* type */ +
+                       LEB128_SIZE /* tid */
+               );
+
+               emit_event (buf, TYPE_END_UNLOAD | TYPE_METADATA);
+               emit_byte (buf, TYPE_THREAD);
+               emit_ptr (buf, (void *) thread->node.key);
+       }
+
+       send_buffer (thread);
+
+       g_free (thread);
+}
+
+static void
+remove_thread (MonoProfilerThread *thread)
+{
+       MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
+
+       if (mono_lls_remove (&profiler_thread_list, hp, &thread->node))
+               mono_thread_hazardous_try_free (thread, free_thread);
+
+       clear_hazard_pointers (hp);
+}
+
+static void
+dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
+{
+       char hbuf [128];
+       char *p = hbuf;
+
+       if (buf->next)
+               dump_buffer (profiler, buf->next);
+
+       if (buf->cursor - buf->buf) {
+               p = write_int32 (p, BUF_ID);
+               p = write_int32 (p, buf->cursor - buf->buf);
+               p = write_int64 (p, buf->time_base);
+               p = write_int64 (p, buf->ptr_base);
+               p = write_int64 (p, buf->obj_base);
+               p = write_int64 (p, buf->thread_id);
+               p = write_int64 (p, buf->method_base);
+
+#if defined (HAVE_SYS_ZLIB)
+               if (profiler->gzfile) {
+                       gzwrite (profiler->gzfile, hbuf, p - hbuf);
+                       gzwrite (profiler->gzfile, buf->buf, buf->cursor - buf->buf);
+               } else
+#endif
+               {
+                       fwrite (hbuf, p - hbuf, 1, profiler->file);
+                       fwrite (buf->buf, buf->cursor - buf->buf, 1, profiler->file);
+                       fflush (profiler->file);
+               }
+       }
+
+       free_buffer (buf, buf->size);
+}
+
+static void
+dump_buffer_threadless (MonoProfiler *profiler, LogBuffer *buf)
+{
+       for (LogBuffer *iter = buf; iter; iter = iter->next)
+               iter->thread_id = 0;
+
+       dump_buffer (profiler, buf);
+}
+
+static void
+process_requests (void)
+{
+       if (heapshot_requested)
+               mono_gc_collect (mono_gc_max_generation ());
+}
+
+// Only valid if init_thread () was called with add_to_lls = FALSE.
+static void
+send_log_unsafe (gboolean if_needed)
+{
+       MonoProfilerThread *thread = PROF_TLS_GET ();
+
+       if (!if_needed || (if_needed && thread->buffer->next)) {
+               if (!thread->attached)
+                       for (LogBuffer *iter = thread->buffer; iter; iter = iter->next)
+                               iter->thread_id = 0;
+
+               send_buffer (thread);
+               init_buffer_state (thread);
+       }
+}
+
+// Assumes that the exclusive lock is held.
+static void
+sync_point_flush (void)
+{
+       g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id () && "Why don't we hold the exclusive lock?");
+
+       MONO_LLS_FOREACH_SAFE (&profiler_thread_list, MonoProfilerThread, thread) {
+               g_assert (thread->attached && "Why is a thread in the LLS not attached?");
+
+               send_buffer (thread);
+               init_buffer_state (thread);
+       } MONO_LLS_FOREACH_SAFE_END
+}
+
+// Assumes that the exclusive lock is held.
+static void
+sync_point_mark (MonoProfilerSyncPointType type)
+{
+       g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id () && "Why don't we hold the exclusive lock?");
+
+       ENTER_LOG (&sync_points_ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               LEB128_SIZE /* type */
+       );
+
+       emit_event (logbuffer, TYPE_META | TYPE_SYNC_POINT);
+       emit_byte (logbuffer, type);
+
+       EXIT_LOG_EXPLICIT (NO_SEND, NO_REQUESTS);
+
+       send_log_unsafe (FALSE);
+}
+
+// Assumes that the exclusive lock is held.
+static void
+sync_point (MonoProfilerSyncPointType type)
+{
+       sync_point_flush ();
+       sync_point_mark (type);
+}
+
+static int
+gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
+{
+       /* account for object alignment in the heap */
+       size += 7;
+       size &= ~7;
+
+       ENTER_LOG (&heap_objects_ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               LEB128_SIZE /* obj */ +
+               LEB128_SIZE /* klass */ +
+               LEB128_SIZE /* size */ +
+               LEB128_SIZE /* num */ +
+               num * (
+                       LEB128_SIZE /* offset */ +
+                       LEB128_SIZE /* ref */
+               )
+       );
+
+       emit_event (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
+       emit_obj (logbuffer, obj);
+       emit_ptr (logbuffer, klass);
+       emit_value (logbuffer, size);
+       emit_value (logbuffer, num);
+
+       uintptr_t last_offset = 0;
+
+       for (int i = 0; i < num; ++i) {
+               emit_value (logbuffer, offsets [i] - last_offset);
+               last_offset = offsets [i];
+               emit_obj (logbuffer, refs [i]);
+       }
+
+       EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+
+       return 0;
+}
+
+static unsigned int hs_mode_ms = 0;
+static unsigned int hs_mode_gc = 0;
+static unsigned int hs_mode_ondemand = 0;
+static unsigned int gc_count = 0;
+static uint64_t last_hs_time = 0;
+static gboolean do_heap_walk = FALSE;
+
+static void
+heap_walk (MonoProfiler *profiler)
+{
+       ENTER_LOG (&heap_starts_ctr, logbuffer,
+               EVENT_SIZE /* event */
+       );
+
+       emit_event (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
+
+       EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+
+       mono_gc_walk_heap (0, gc_reference, NULL);
+
+       ENTER_LOG (&heap_ends_ctr, logbuffer,
+               EVENT_SIZE /* event */
+       );
+
+       emit_event (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
+
+       EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+}
+
+static void
+gc_roots (MonoProfiler *prof, int num, void **objects, int *root_types, uintptr_t *extra_info)
+{
+       ENTER_LOG (&heap_roots_ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               LEB128_SIZE /* num */ +
+               LEB128_SIZE /* collections */ +
+               num * (
+                       LEB128_SIZE /* object */ +
+                       LEB128_SIZE /* root type */ +
+                       LEB128_SIZE /* extra info */
+               )
+       );
+
+       emit_event (logbuffer, TYPE_HEAP_ROOT | TYPE_HEAP);
+       emit_value (logbuffer, num);
+       emit_value (logbuffer, mono_gc_collection_count (mono_gc_max_generation ()));
+
+       for (int i = 0; i < num; ++i) {
+               emit_obj (logbuffer, objects [i]);
+               emit_byte (logbuffer, root_types [i]);
+               emit_value (logbuffer, extra_info [i]);
+       }
+
+       EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+}
+
+static void
+gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation)
+{
+       ENTER_LOG (&gc_events_ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               BYTE_SIZE /* gc event */ +
+               BYTE_SIZE /* generation */
+       );
+
+       emit_event (logbuffer, TYPE_GC_EVENT | TYPE_GC);
+       emit_byte (logbuffer, ev);
+       emit_byte (logbuffer, generation);
+
+       EXIT_LOG_EXPLICIT (NO_SEND, NO_REQUESTS);
+
+       switch (ev) {
+       case MONO_GC_EVENT_START:
+               if (generation == mono_gc_max_generation ())
+                       gc_count++;
+
+               uint64_t now = current_time ();
+
+               if (hs_mode_ms && (now - last_hs_time) / 1000 * 1000 >= hs_mode_ms)
+                       do_heap_walk = TRUE;
+               else if (hs_mode_gc && !(gc_count % hs_mode_gc))
+                       do_heap_walk = TRUE;
+               else if (hs_mode_ondemand)
+                       do_heap_walk = heapshot_requested;
+               else if (!hs_mode_ms && !hs_mode_gc && generation == mono_gc_max_generation ())
+                       do_heap_walk = TRUE;
+               break;
+       case MONO_GC_EVENT_PRE_STOP_WORLD_LOCKED:
+               /*
+                * Ensure that no thread can be in the middle of writing to
+                * a buffer when the world stops...
+                */
+               buffer_lock_excl ();
+               break;
+       case MONO_GC_EVENT_POST_STOP_WORLD:
+               /*
+                * ... So that we now have a consistent view of all buffers.
+                * This allows us to flush them. We need to do this because
+                * they may contain object allocation events that need to be
+                * committed to the log file before any object move events
+                * that will be produced during this GC.
+                */
+               sync_point (SYNC_POINT_WORLD_STOP);
+               break;
+       case MONO_GC_EVENT_PRE_START_WORLD:
+               if (do_heap_shot && do_heap_walk) {
+                       heap_walk (profiler);
+
+                       do_heap_walk = FALSE;
+                       heapshot_requested = 0;
+                       last_hs_time = current_time ();
+               }
+               break;
+       case MONO_GC_EVENT_POST_START_WORLD_UNLOCKED:
+               /*
+                * Similarly, we must now make sure that any object moves
+                * written to the GC thread's buffer are flushed. Otherwise,
+                * object allocation events for certain addresses could come
+                * after the move events that made those addresses available.
+                */
+               sync_point_mark (SYNC_POINT_WORLD_START);
+
+               /*
+                * Finally, it is safe to allow other threads to write to
+                * their buffers again.
+                */
+               buffer_unlock_excl ();
+               break;
+       default:
+               break;
+       }
+}
+
+static void
+gc_resize (MonoProfiler *profiler, int64_t new_size)
+{
+       ENTER_LOG (&gc_resizes_ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               LEB128_SIZE /* new size */
+       );
+
+       emit_event (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
+       emit_value (logbuffer, new_size);
+
+       EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+}
+
+// If you alter MAX_FRAMES, you may need to alter SAMPLE_BLOCK_SIZE too.
+#define MAX_FRAMES 32
+
+typedef struct {
+       int count;
+       MonoMethod* methods [MAX_FRAMES];
+       int32_t il_offsets [MAX_FRAMES];
+       int32_t native_offsets [MAX_FRAMES];
+} FrameData;
+
+static int num_frames = MAX_FRAMES;
+
+static mono_bool
+walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
+{
+       FrameData *frame = (FrameData *)data;
+       if (method && frame->count < num_frames) {
+               frame->il_offsets [frame->count] = il_offset;
+               frame->native_offsets [frame->count] = native_offset;
+               frame->methods [frame->count++] = method;
+               //printf ("In %d %s at %d (native: %d)\n", frame->count, mono_method_get_name (method), il_offset, native_offset);
+       }
+       return frame->count == num_frames;
+}
+
+/*
+ * a note about stack walks: they can cause more profiler events to fire,
+ * so we need to make sure they don't happen after we started emitting an
+ * event, hence the collect_bt/emit_bt split.
+ */
+static void
+collect_bt (FrameData *data)
+{
+       data->count = 0;
+       mono_stack_walk_no_il (walk_stack, data);
+}
+
+static void
+emit_bt (MonoProfiler *prof, LogBuffer *logbuffer, FrameData *data)
+{
+       /* FIXME: this is actually tons of data and we should
+        * just output it the first time and use an id the next
+        */
+       if (data->count > num_frames)
+               printf ("bad num frames: %d\n", data->count);
+       emit_value (logbuffer, data->count);
+       //if (*p != data.count) {
+       //      printf ("bad num frames enc at %d: %d -> %d\n", count, data.count, *p); printf ("frames end: %p->%p\n", p, logbuffer->cursor); exit(0);}
+       while (data->count) {
+               emit_method (logbuffer, data->methods [--data->count]);
+       }
+}
+
+static void
+gc_alloc (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
+{
+       init_thread (prof, TRUE);
+
+       int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces) ? TYPE_ALLOC_BT : 0;
+       FrameData data;
+       uintptr_t len = mono_object_get_size (obj);
+       /* account for object alignment in the heap */
+       len += 7;
+       len &= ~7;
+
+       if (do_bt)
+               collect_bt (&data);
+
+       ENTER_LOG (&gc_allocs_ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               LEB128_SIZE /* klass */ +
+               LEB128_SIZE /* obj */ +
+               LEB128_SIZE /* size */ +
+               (do_bt ? (
+                       LEB128_SIZE /* count */ +
+                       data.count * (
+                               LEB128_SIZE /* method */
+                       )
+               ) : 0)
+       );
+
+       emit_event (logbuffer, do_bt | TYPE_ALLOC);
+       emit_ptr (logbuffer, klass);
+       emit_obj (logbuffer, obj);
+       emit_value (logbuffer, len);
+
+       if (do_bt)
+               emit_bt (prof, logbuffer, &data);
+
+       EXIT_LOG;
+}
+
+static void
+gc_moves (MonoProfiler *prof, void **objects, int num)
+{
+       ENTER_LOG (&gc_moves_ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               LEB128_SIZE /* num */ +
+               num * (
+                       LEB128_SIZE /* object */
+               )
+       );
+
+       emit_event (logbuffer, TYPE_GC_MOVE | TYPE_GC);
+       emit_value (logbuffer, num);
+
+       for (int i = 0; i < num; ++i)
+               emit_obj (logbuffer, objects [i]);
+
+       EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+}
+
+static void
+gc_handle (MonoProfiler *prof, int op, int type, uintptr_t handle, MonoObject *obj)
+{
+       int do_bt = nocalls && InterlockedRead (&runtime_inited) && !notraces;
+       FrameData data;
+
+       if (do_bt)
+               collect_bt (&data);
+
+       gint32 *ctr = op == MONO_PROFILER_GC_HANDLE_CREATED ? &gc_handle_creations_ctr : &gc_handle_deletions_ctr;
+
+       ENTER_LOG (ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               LEB128_SIZE /* type */ +
+               LEB128_SIZE /* handle */ +
+               (op == MONO_PROFILER_GC_HANDLE_CREATED ? (
+                       LEB128_SIZE /* obj */
+               ) : 0) +
+               (do_bt ? (
+                       LEB128_SIZE /* count */ +
+                       data.count * (
+                               LEB128_SIZE /* method */
+                       )
+               ) : 0)
+       );
+
+       if (op == MONO_PROFILER_GC_HANDLE_CREATED)
+               emit_event (logbuffer, (do_bt ? TYPE_GC_HANDLE_CREATED_BT : TYPE_GC_HANDLE_CREATED) | TYPE_GC);
+       else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
+               emit_event (logbuffer, (do_bt ? TYPE_GC_HANDLE_DESTROYED_BT : TYPE_GC_HANDLE_DESTROYED) | TYPE_GC);
+       else
+               g_assert_not_reached ();
+
+       emit_value (logbuffer, type);
+       emit_value (logbuffer, handle);
+
+       if (op == MONO_PROFILER_GC_HANDLE_CREATED)
+               emit_obj (logbuffer, obj);
+
+       if (do_bt)
+               emit_bt (prof, logbuffer, &data);
+
+       EXIT_LOG;
+}
+
+static void
+finalize_begin (MonoProfiler *prof)
+{
+       ENTER_LOG (&finalize_begins_ctr, buf,
+               EVENT_SIZE /* event */
+       );
+
+       emit_event (buf, TYPE_GC_FINALIZE_START | TYPE_GC);
+
+       EXIT_LOG;
+}
+
+static void
+finalize_end (MonoProfiler *prof)
+{
+       ENTER_LOG (&finalize_ends_ctr, buf,
+               EVENT_SIZE /* event */
+       );
+
+       emit_event (buf, TYPE_GC_FINALIZE_END | TYPE_GC);
+
+       EXIT_LOG;
+}
+
+static void
+finalize_object_begin (MonoProfiler *prof, MonoObject *obj)
+{
+       ENTER_LOG (&finalize_object_begins_ctr, buf,
+               EVENT_SIZE /* event */ +
+               LEB128_SIZE /* obj */
+       );
+
+       emit_event (buf, TYPE_GC_FINALIZE_OBJECT_START | TYPE_GC);
+       emit_obj (buf, obj);
+
+       EXIT_LOG;
+}
+
+static void
+finalize_object_end (MonoProfiler *prof, MonoObject *obj)
+{
+       ENTER_LOG (&finalize_object_ends_ctr, buf,
+               EVENT_SIZE /* event */ +
+               LEB128_SIZE /* obj */
+       );
+
+       emit_event (buf, TYPE_GC_FINALIZE_OBJECT_END | TYPE_GC);
+       emit_obj (buf, obj);
+
+       EXIT_LOG;
+}
+
+static char*
+push_nesting (char *p, MonoClass *klass)
+{
+       MonoClass *nesting;
+       const char *name;
+       const char *nspace;
+       nesting = mono_class_get_nesting_type (klass);
+       if (nesting) {
+               p = push_nesting (p, nesting);
+               *p++ = '/';
+               *p = 0;
+       }
+       name = mono_class_get_name (klass);
+       nspace = mono_class_get_namespace (klass);
+       if (*nspace) {
+               strcpy (p, nspace);
+               p += strlen (nspace);
+               *p++ = '.';
+               *p = 0;
+       }
+       strcpy (p, name);
+       p += strlen (name);
+       return p;
+}
+
+static char*
+type_name (MonoClass *klass)
+{
+       char buf [1024];
+       char *p;
+       push_nesting (buf, klass);
+       p = (char *) g_malloc (strlen (buf) + 1);
+       strcpy (p, buf);
+       return p;
+}
+
+static void
+image_loaded (MonoProfiler *prof, MonoImage *image, int result)
+{
+       if (result != MONO_PROFILE_OK)
+               return;
+
+       const char *name = mono_image_get_filename (image);
+       int nlen = strlen (name) + 1;
+
+       ENTER_LOG (&image_loads_ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               BYTE_SIZE /* type */ +
+               LEB128_SIZE /* image */ +
+               nlen /* name */
+       );
+
+       emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
+       emit_byte (logbuffer, TYPE_IMAGE);
+       emit_ptr (logbuffer, image);
+       memcpy (logbuffer->cursor, name, nlen);
+       logbuffer->cursor += nlen;
+
+       EXIT_LOG;
+}
+
+static void
+image_unloaded (MonoProfiler *prof, MonoImage *image)
+{
+       const char *name = mono_image_get_filename (image);
+       int nlen = strlen (name) + 1;
+
+       ENTER_LOG (&image_unloads_ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               BYTE_SIZE /* type */ +
+               LEB128_SIZE /* image */ +
+               nlen /* name */
+       );
+
+       emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
+       emit_byte (logbuffer, TYPE_IMAGE);
+       emit_ptr (logbuffer, image);
+       memcpy (logbuffer->cursor, name, nlen);
+       logbuffer->cursor += nlen;
+
+       EXIT_LOG;
+}
+
+static void
+assembly_loaded (MonoProfiler *prof, MonoAssembly *assembly, int result)
+{
+       if (result != MONO_PROFILE_OK)
+               return;
+
+       char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
+       int nlen = strlen (name) + 1;
+
+       ENTER_LOG (&assembly_loads_ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               BYTE_SIZE /* type */ +
+               LEB128_SIZE /* assembly */ +
+               nlen /* name */
+       );
+
+       emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
+       emit_byte (logbuffer, TYPE_ASSEMBLY);
+       emit_ptr (logbuffer, assembly);
+       memcpy (logbuffer->cursor, name, nlen);
+       logbuffer->cursor += nlen;
+
+       EXIT_LOG;
+
+       mono_free (name);
+}
+
+static void
+assembly_unloaded (MonoProfiler *prof, MonoAssembly *assembly)
+{
+       char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
+       int nlen = strlen (name) + 1;
+
+       ENTER_LOG (&assembly_unloads_ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               BYTE_SIZE /* type */ +
+               LEB128_SIZE /* assembly */ +
+               nlen /* name */
+       );
+
+       emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
+       emit_byte (logbuffer, TYPE_ASSEMBLY);
+       emit_ptr (logbuffer, assembly);
+       memcpy (logbuffer->cursor, name, nlen);
+       logbuffer->cursor += nlen;
+
+       EXIT_LOG;
+
+       mono_free (name);
+}
+
+static void
+class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
+{
+       if (result != MONO_PROFILE_OK)
+               return;
+
+       char *name;
+
+       if (InterlockedRead (&runtime_inited))
+               name = mono_type_get_name (mono_class_get_type (klass));
+       else
+               name = type_name (klass);
+
+       int nlen = strlen (name) + 1;
+       MonoImage *image = mono_class_get_image (klass);
+
+       ENTER_LOG (&class_loads_ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               BYTE_SIZE /* type */ +
+               LEB128_SIZE /* klass */ +
+               LEB128_SIZE /* image */ +
+               nlen /* name */
+       );
+
+       emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
+       emit_byte (logbuffer, TYPE_CLASS);
+       emit_ptr (logbuffer, klass);
+       emit_ptr (logbuffer, image);
+       memcpy (logbuffer->cursor, name, nlen);
+       logbuffer->cursor += nlen;
+
+       EXIT_LOG;
+
+       if (runtime_inited)
+               mono_free (name);
+       else
+               g_free (name);
+}
+
+static void
+class_unloaded (MonoProfiler *prof, MonoClass *klass)
+{
+       char *name;
+
+       if (InterlockedRead (&runtime_inited))
+               name = mono_type_get_name (mono_class_get_type (klass));
+       else
+               name = type_name (klass);
+
+       int nlen = strlen (name) + 1;
+       MonoImage *image = mono_class_get_image (klass);
+
+       ENTER_LOG (&class_unloads_ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               BYTE_SIZE /* type */ +
+               LEB128_SIZE /* klass */ +
+               LEB128_SIZE /* image */ +
+               nlen /* name */
+       );
+
+       emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
+       emit_byte (logbuffer, TYPE_CLASS);
+       emit_ptr (logbuffer, klass);
+       emit_ptr (logbuffer, image);
+       memcpy (logbuffer->cursor, name, nlen);
+       logbuffer->cursor += nlen;
+
+       EXIT_LOG;
+
+       if (runtime_inited)
+               mono_free (name);
+       else
+               g_free (name);
+}
+
+static void process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method);
+
+static void
+method_enter (MonoProfiler *prof, MonoMethod *method)
+{
+       process_method_enter_coverage (prof, method);
+
+       if (!only_coverage && PROF_TLS_GET ()->call_depth++ <= max_call_depth) {
+               ENTER_LOG (&method_entries_ctr, logbuffer,
+                       EVENT_SIZE /* event */ +
+                       LEB128_SIZE /* method */
+               );
+
+               emit_event (logbuffer, TYPE_ENTER | TYPE_METHOD);
+               emit_method (logbuffer, method);
+
+               EXIT_LOG;
+       }
+}
+
+static void
+method_leave (MonoProfiler *prof, MonoMethod *method)
+{
+       if (!only_coverage && --PROF_TLS_GET ()->call_depth <= max_call_depth) {
+               ENTER_LOG (&method_exits_ctr, logbuffer,
+                       EVENT_SIZE /* event */ +
+                       LEB128_SIZE /* method */
+               );
+
+               emit_event (logbuffer, TYPE_LEAVE | TYPE_METHOD);
+               emit_method (logbuffer, method);
+
+               EXIT_LOG;
+       }
+}
+
+static void
+method_exc_leave (MonoProfiler *prof, MonoMethod *method)
+{
+       if (!only_coverage && !nocalls && --PROF_TLS_GET ()->call_depth <= max_call_depth) {
+               ENTER_LOG (&method_exception_exits_ctr, logbuffer,
+                       EVENT_SIZE /* event */ +
+                       LEB128_SIZE /* method */
+               );
+
+               emit_event (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
+               emit_method (logbuffer, method);
+
+               EXIT_LOG;
+       }
+}
+
+static void
+method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji, int result)
+{
+       if (result != MONO_PROFILE_OK)
+               return;
+
+       register_method_local (method, ji);
+
+       process_requests ();
+}
+
+static void
+code_buffer_new (MonoProfiler *prof, void *buffer, int size, MonoProfilerCodeBufferType type, void *data)
+{
+       char *name;
+       int nlen;
+
+       if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
+               name = (char *) data;
+               nlen = strlen (name) + 1;
+       } else {
+               name = NULL;
+               nlen = 0;
+       }
+
+       ENTER_LOG (&code_buffers_ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               BYTE_SIZE /* type */ +
+               LEB128_SIZE /* buffer */ +
+               LEB128_SIZE /* size */ +
+               (name ? (
+                       nlen /* name */
+               ) : 0)
+       );
+
+       emit_event (logbuffer, TYPE_JITHELPER | TYPE_RUNTIME);
+       emit_byte (logbuffer, type);
+       emit_ptr (logbuffer, buffer);
+       emit_value (logbuffer, size);
+
+       if (name) {
+               memcpy (logbuffer->cursor, name, nlen);
+               logbuffer->cursor += nlen;
+       }
+
+       EXIT_LOG;
+}
+
+static void
+throw_exc (MonoProfiler *prof, MonoObject *object)
+{
+       int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces) ? TYPE_THROW_BT : 0;
+       FrameData data;
+
+       if (do_bt)
+               collect_bt (&data);
+
+       ENTER_LOG (&exception_throws_ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               LEB128_SIZE /* object */ +
+               (do_bt ? (
+                       LEB128_SIZE /* count */ +
+                       data.count * (
+                               LEB128_SIZE /* method */
+                       )
+               ) : 0)
+       );
+
+       emit_event (logbuffer, do_bt | TYPE_EXCEPTION);
+       emit_obj (logbuffer, object);
+
+       if (do_bt)
+               emit_bt (prof, logbuffer, &data);
+
+       EXIT_LOG;
+}
+
+static void
+clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num)
+{
+       ENTER_LOG (&exception_clauses_ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               BYTE_SIZE /* clause type */ +
+               LEB128_SIZE /* clause num */ +
+               LEB128_SIZE /* method */
+       );
+
+       emit_event (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
+       emit_byte (logbuffer, clause_type);
+       emit_value (logbuffer, clause_num);
+       emit_method (logbuffer, method);
+
+       EXIT_LOG;
+}
+
+static void
+monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent event)
+{
+       int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces && event == MONO_PROFILER_MONITOR_CONTENTION) ? TYPE_MONITOR_BT : 0;
+       FrameData data;
+
+       if (do_bt)
+               collect_bt (&data);
+
+       gint32 *ctr;
+
+       switch (event) {
+       case MONO_PROFILER_MONITOR_CONTENTION:
+               ctr = &monitor_contentions_ctr;
+               break;
+       case MONO_PROFILER_MONITOR_DONE:
+               ctr = &monitor_acquisitions_ctr;
+               break;
+       case MONO_PROFILER_MONITOR_FAIL:
+               ctr = &monitor_failures_ctr;
+               break;
+       default:
+               g_assert_not_reached ();
+               break;
+       }
+
+       ENTER_LOG (ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               LEB128_SIZE /* object */ +
+               (do_bt ? (
+                       LEB128_SIZE /* count */ +
+                       data.count * (
+                               LEB128_SIZE /* method */
+                       )
+               ) : 0)
+       );
+
+       emit_event (logbuffer, (event << 4) | do_bt | TYPE_MONITOR);
+       emit_obj (logbuffer, object);
+
+       if (do_bt)
+               emit_bt (profiler, logbuffer, &data);
+
+       EXIT_LOG;
+}
+
+static void
+thread_start (MonoProfiler *prof, uintptr_t tid)
+{
+       init_thread (prof, TRUE);
+
+       ENTER_LOG (&thread_starts_ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               BYTE_SIZE /* type */ +
+               LEB128_SIZE /* tid */
+       );
+
+       emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
+       emit_byte (logbuffer, TYPE_THREAD);
+       emit_ptr (logbuffer, (void*) tid);
+
+       EXIT_LOG;
+}
+
+static void
+thread_end (MonoProfiler *prof, uintptr_t tid)
+{
+       ENTER_LOG (&thread_ends_ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               BYTE_SIZE /* type */ +
+               LEB128_SIZE /* tid */
+       );
+
+       emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
+       emit_byte (logbuffer, TYPE_THREAD);
+       emit_ptr (logbuffer, (void*) tid);
+
+       EXIT_LOG_EXPLICIT (NO_SEND, NO_REQUESTS);
+
+       MonoProfilerThread *thread = PROF_TLS_GET ();
+
+       thread->ended = TRUE;
+       remove_thread (thread);
+
+       PROF_TLS_SET (NULL);
+}
+
+static void
+thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
+{
+       int len = strlen (name) + 1;
+
+       ENTER_LOG (&thread_names_ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               BYTE_SIZE /* type */ +
+               LEB128_SIZE /* tid */ +
+               len /* name */
+       );
+
+       emit_event (logbuffer, TYPE_METADATA);
+       emit_byte (logbuffer, TYPE_THREAD);
+       emit_ptr (logbuffer, (void*)tid);
+       memcpy (logbuffer->cursor, name, len);
+       logbuffer->cursor += len;
+
+       EXIT_LOG;
+}
+
+static void
+domain_loaded (MonoProfiler *prof, MonoDomain *domain, int result)
+{
+       if (result != MONO_PROFILE_OK)
+               return;
+
+       ENTER_LOG (&domain_loads_ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               BYTE_SIZE /* type */ +
+               LEB128_SIZE /* domain id */
+       );
+
+       emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
+       emit_byte (logbuffer, TYPE_DOMAIN);
+       emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
+
+       EXIT_LOG;
+}
+
+static void
+domain_unloaded (MonoProfiler *prof, MonoDomain *domain)
+{
+       ENTER_LOG (&domain_unloads_ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               BYTE_SIZE /* type */ +
+               LEB128_SIZE /* domain id */
+       );
+
+       emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
+       emit_byte (logbuffer, TYPE_DOMAIN);
+       emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
+
+       EXIT_LOG;
+}
+
+static void
+domain_name (MonoProfiler *prof, MonoDomain *domain, const char *name)
+{
+       int nlen = strlen (name) + 1;
+
+       ENTER_LOG (&domain_names_ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               BYTE_SIZE /* type */ +
+               LEB128_SIZE /* domain id */ +
+               nlen /* name */
+       );
+
+       emit_event (logbuffer, TYPE_METADATA);
+       emit_byte (logbuffer, TYPE_DOMAIN);
+       emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
+       memcpy (logbuffer->cursor, name, nlen);
+       logbuffer->cursor += nlen;
+
+       EXIT_LOG;
+}
+
+static void
+context_loaded (MonoProfiler *prof, MonoAppContext *context)
+{
+       ENTER_LOG (&context_loads_ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               BYTE_SIZE /* type */ +
+               LEB128_SIZE /* context id */ +
+               LEB128_SIZE /* domain id */
+       );
+
+       emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
+       emit_byte (logbuffer, TYPE_CONTEXT);
+       emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
+       emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
+
+       EXIT_LOG;
+}
+
+static void
+context_unloaded (MonoProfiler *prof, MonoAppContext *context)
+{
+       ENTER_LOG (&context_unloads_ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               BYTE_SIZE /* type */ +
+               LEB128_SIZE /* context id */ +
+               LEB128_SIZE /* domain id */
+       );
+
+       emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
+       emit_byte (logbuffer, TYPE_CONTEXT);
+       emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
+       emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
+
+       EXIT_LOG;
+}
+
+typedef struct {
+       MonoMethod *method;
+       MonoDomain *domain;
+       void *base_address;
+       int offset;
+} AsyncFrameInfo;
+
+typedef struct {
+       MonoLockFreeQueueNode node;
+       MonoProfiler *prof;
+       uint64_t time;
+       uintptr_t tid;
+       void *ip;
+       int count;
+       AsyncFrameInfo frames [MONO_ZERO_LEN_ARRAY];
+} SampleHit;
+
+static mono_bool
+async_walk_stack (MonoMethod *method, MonoDomain *domain, void *base_address, int offset, void *data)
+{
+       SampleHit *sample = (SampleHit *) data;
+
+       if (sample->count < num_frames) {
+               int i = sample->count;
+
+               sample->frames [i].method = method;
+               sample->frames [i].domain = domain;
+               sample->frames [i].base_address = base_address;
+               sample->frames [i].offset = offset;
+
+               sample->count++;
+       }
+
+       return sample->count == num_frames;
+}
+
+#define SAMPLE_SLOT_SIZE(FRAMES) (sizeof (SampleHit) + sizeof (AsyncFrameInfo) * (FRAMES - MONO_ZERO_LEN_ARRAY))
+#define SAMPLE_BLOCK_SIZE (mono_pagesize ())
+
+static void
+enqueue_sample_hit (gpointer p)
+{
+       SampleHit *sample = p;
+
+       mono_lock_free_queue_node_unpoison (&sample->node);
+       mono_lock_free_queue_enqueue (&sample->prof->dumper_queue, &sample->node);
+       mono_os_sem_post (&sample->prof->dumper_queue_sem);
+}
+
+static void
+mono_sample_hit (MonoProfiler *profiler, unsigned char *ip, void *context)
+{
+       /*
+        * Please note: We rely on the runtime loading the profiler with
+        * MONO_DL_EAGER (RTLD_NOW) so that references to runtime functions within
+        * this function (and its siblings) are resolved when the profiler is
+        * loaded. Otherwise, we would potentially invoke the dynamic linker when
+        * invoking runtime functions, which is not async-signal-safe.
+        */
+
+       if (InterlockedRead (&in_shutdown))
+               return;
+
+       SampleHit *sample = (SampleHit *) mono_lock_free_queue_dequeue (&profiler->sample_reuse_queue);
+
+       if (!sample) {
+               /*
+                * If we're out of reusable sample events and we're not allowed to
+                * allocate more, we have no choice but to drop the event.
+                */
+               if (InterlockedRead (&sample_allocations_ctr) >= max_allocated_sample_hits)
+                       return;
+
+               sample = mono_lock_free_alloc (&profiler->sample_allocator);
+               sample->prof = profiler;
+               mono_lock_free_queue_node_init (&sample->node, TRUE);
+
+               InterlockedIncrement (&sample_allocations_ctr);
+       }
+
+       sample->count = 0;
+       mono_stack_walk_async_safe (&async_walk_stack, context, sample);
+
+       sample->time = current_time ();
+       sample->tid = thread_id ();
+       sample->ip = ip;
+
+       mono_thread_hazardous_try_free (sample, enqueue_sample_hit);
+}
+
+static uintptr_t *code_pages = 0;
+static int num_code_pages = 0;
+static int size_code_pages = 0;
+#define CPAGE_SHIFT (9)
+#define CPAGE_SIZE (1 << CPAGE_SHIFT)
+#define CPAGE_MASK (~(CPAGE_SIZE - 1))
+#define CPAGE_ADDR(p) ((p) & CPAGE_MASK)
+
+static uintptr_t
+add_code_page (uintptr_t *hash, uintptr_t hsize, uintptr_t page)
+{
+       uintptr_t i;
+       uintptr_t start_pos;
+       start_pos = (page >> CPAGE_SHIFT) % hsize;
+       i = start_pos;
+       do {
+               if (hash [i] && CPAGE_ADDR (hash [i]) == CPAGE_ADDR (page)) {
+                       return 0;
+               } else if (!hash [i]) {
+                       hash [i] = page;
+                       return 1;
+               }
+               /* wrap around */
+               if (++i == hsize)
+                       i = 0;
+       } while (i != start_pos);
+       /* should not happen */
+       printf ("failed code page store\n");
+       return 0;
+}
+
+static void
+add_code_pointer (uintptr_t ip)
+{
+       uintptr_t i;
+       if (num_code_pages * 2 >= size_code_pages) {
+               uintptr_t *n;
+               uintptr_t old_size = size_code_pages;
+               size_code_pages *= 2;
+               if (size_code_pages == 0)
+                       size_code_pages = 16;
+               n = (uintptr_t *) g_calloc (sizeof (uintptr_t) * size_code_pages, 1);
+               for (i = 0; i < old_size; ++i) {
+                       if (code_pages [i])
+                               add_code_page (n, size_code_pages, code_pages [i]);
+               }
+               if (code_pages)
+                       g_free (code_pages);
+               code_pages = n;
+       }
+       num_code_pages += add_code_page (code_pages, size_code_pages, ip & CPAGE_MASK);
+}
+
+/* ELF code crashes on some systems. */
+//#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
+#if 0
+static void
+dump_ubin (MonoProfiler *prof, const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
+{
+       int len = strlen (filename) + 1;
+
+       ENTER_LOG (&sample_ubins_ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               LEB128_SIZE /* load address */ +
+               LEB128_SIZE /* offset */ +
+               LEB128_SIZE /* size */ +
+               nlen /* file name */
+       );
+
+       emit_event (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_UBIN);
+       emit_svalue (logbuffer, load_addr);
+       emit_uvalue (logbuffer, offset);
+       emit_uvalue (logbuffer, size);
+       memcpy (logbuffer->cursor, filename, len);
+       logbuffer->cursor += len;
+
+       EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+}
+#endif
+
+static void
+dump_usym (MonoProfiler *prof, const char *name, uintptr_t value, uintptr_t size)
+{
+       int len = strlen (name) + 1;
+
+       ENTER_LOG (&sample_usyms_ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               LEB128_SIZE /* value */ +
+               LEB128_SIZE /* size */ +
+               len /* name */
+       );
+
+       emit_event (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_USYM);
+       emit_ptr (logbuffer, (void*)value);
+       emit_value (logbuffer, size);
+       memcpy (logbuffer->cursor, name, len);
+       logbuffer->cursor += len;
+
+       EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+}
+
+/* ELF code crashes on some systems. */
+//#if defined(ELFMAG0)
+#if 0
+
+#if SIZEOF_VOID_P == 4
+#define ELF_WSIZE 32
+#else
+#define ELF_WSIZE 64
+#endif
+#ifndef ElfW
+#define ElfW(type)      _ElfW (Elf, ELF_WSIZE, type)
+#define _ElfW(e,w,t)    _ElfW_1 (e, w, _##t)
+#define _ElfW_1(e,w,t)  e##w##t
+#endif
+
+static void
+dump_elf_symbols (MonoProfiler *prof, ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
+{
+       int i;
+       for (i = 0; i < num_symbols; ++i) {
+               const char* sym;
+               sym =  strtab + symbols [i].st_name;
+               if (!symbols [i].st_name || !symbols [i].st_size || (symbols [i].st_info & 0xf) != STT_FUNC)
+                       continue;
+               //printf ("symbol %s at %d\n", sym, symbols [i].st_value);
+               dump_usym (sym, (uintptr_t)load_addr + symbols [i].st_value, symbols [i].st_size);
+       }
+}
+
+static int
+read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
+{
+       int fd, i;
+       void *data;
+       struct stat statb;
+       uint64_t file_size;
+       ElfW(Ehdr) *header;
+       ElfW(Shdr) *sheader;
+       ElfW(Shdr) *shstrtabh;
+       ElfW(Shdr) *symtabh = NULL;
+       ElfW(Shdr) *strtabh = NULL;
+       ElfW(Sym) *symbols = NULL;
+       const char *strtab;
+       int num_symbols;
+
+       fd = open (filename, O_RDONLY);
+       if (fd < 0)
+               return 0;
+       if (fstat (fd, &statb) != 0) {
+               close (fd);
+               return 0;
+       }
+       file_size = statb.st_size;
+       data = mmap (NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
+       close (fd);
+       if (data == MAP_FAILED)
+               return 0;
+       header = data;
+       if (header->e_ident [EI_MAG0] != ELFMAG0 ||
+                       header->e_ident [EI_MAG1] != ELFMAG1 ||
+                       header->e_ident [EI_MAG2] != ELFMAG2 ||
+                       header->e_ident [EI_MAG3] != ELFMAG3 ) {
+               munmap (data, file_size);
+               return 0;
+       }
+       sheader = (void*)((char*)data + header->e_shoff);
+       shstrtabh = (void*)((char*)sheader + (header->e_shentsize * header->e_shstrndx));
+       strtab = (const char*)data + shstrtabh->sh_offset;
+       for (i = 0; i < header->e_shnum; ++i) {
+               //printf ("section header: %d\n", sheader->sh_type);
+               if (sheader->sh_type == SHT_SYMTAB) {
+                       symtabh = sheader;
+                       strtabh = (void*)((char*)data + header->e_shoff + sheader->sh_link * header->e_shentsize);
+                       /*printf ("symtab section header: %d, .strstr: %d\n", i, sheader->sh_link);*/
+                       break;
+               }
+               sheader = (void*)((char*)sheader + header->e_shentsize);
+       }
+       if (!symtabh || !strtabh) {
+               munmap (data, file_size);
+               return 0;
+       }
+       strtab = (const char*)data + strtabh->sh_offset;
+       num_symbols = symtabh->sh_size / symtabh->sh_entsize;
+       symbols = (void*)((char*)data + symtabh->sh_offset);
+       dump_elf_symbols (symbols, num_symbols, strtab, load_addr);
+       munmap (data, file_size);
+       return 1;
+}
+#endif
+
+/* ELF code crashes on some systems. */
+//#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
+#if 0
+static int
+elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
+{
+       MonoProfiler *prof = data;
+       char buf [256];
+       const char *filename;
+       BinaryObject *obj;
+       char *a = (void*)info->dlpi_addr;
+       int i, num_sym;
+       ElfW(Dyn) *dyn = NULL;
+       ElfW(Sym) *symtab = NULL;
+       ElfW(Word) *hash_table = NULL;
+       ElfW(Ehdr) *header = NULL;
+       const char* strtab = NULL;
+       for (obj = prof->binary_objects; obj; obj = obj->next) {
+               if (obj->addr == a)
+                       return 0;
+       }
+       filename = info->dlpi_name;
+       if (!filename)
+               return 0;
+       if (!info->dlpi_addr && !filename [0]) {
+               int l = readlink ("/proc/self/exe", buf, sizeof (buf) - 1);
+               if (l > 0) {
+                       buf [l] = 0;
+                       filename = buf;
+               }
+       }
+       obj = g_calloc (sizeof (BinaryObject), 1);
+       obj->addr = (void*)info->dlpi_addr;
+       obj->name = pstrdup (filename);
+       obj->next = prof->binary_objects;
+       prof->binary_objects = obj;
+       //printf ("loaded file: %s at %p, segments: %d\n", filename, (void*)info->dlpi_addr, info->dlpi_phnum);
+       a = NULL;
+       for (i = 0; i < info->dlpi_phnum; ++i) {
+               //printf ("segment type %d file offset: %d, size: %d\n", info->dlpi_phdr[i].p_type, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
+               if (info->dlpi_phdr[i].p_type == PT_LOAD && !header) {
+                       header = (ElfW(Ehdr)*)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
+                       if (header->e_ident [EI_MAG0] != ELFMAG0 ||
+                                       header->e_ident [EI_MAG1] != ELFMAG1 ||
+                                       header->e_ident [EI_MAG2] != ELFMAG2 ||
+                                       header->e_ident [EI_MAG3] != ELFMAG3 ) {
+                               header = NULL;
+                       }
+                       dump_ubin (prof, filename, info->dlpi_addr + info->dlpi_phdr[i].p_vaddr, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
+               } else if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
+                       dyn = (ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
+               }
+       }
+       if (read_elf_symbols (prof, filename, (void*)info->dlpi_addr))
+               return 0;
+       if (!info->dlpi_name || !info->dlpi_name[0])
+               return 0;
+       if (!dyn)
+               return 0;
+       for (i = 0; dyn [i].d_tag != DT_NULL; ++i) {
+               if (dyn [i].d_tag == DT_SYMTAB) {
+                       if (symtab && do_debug)
+                               printf ("multiple symtabs: %d\n", i);
+                       symtab = (ElfW(Sym) *)(a + dyn [i].d_un.d_ptr);
+               } else if (dyn [i].d_tag == DT_HASH) {
+                       hash_table = (ElfW(Word) *)(a + dyn [i].d_un.d_ptr);
+               } else if (dyn [i].d_tag == DT_STRTAB) {
+                       strtab = (const char*)(a + dyn [i].d_un.d_ptr);
+               }
+       }
+       if (!hash_table)
+               return 0;
+       num_sym = hash_table [1];
+       dump_elf_symbols (prof, symtab, num_sym, strtab, (void*)info->dlpi_addr);
+       return 0;
+}
+
+static int
+load_binaries (MonoProfiler *prof)
+{
+       dl_iterate_phdr (elf_dl_callback, prof);
+       return 1;
+}
+#else
+static int
+load_binaries (MonoProfiler *prof)
+{
+       return 0;
+}
+#endif
+
+static const char*
+symbol_for (uintptr_t code)
+{
+#ifdef HAVE_DLADDR
+       void *ip = (void*)code;
+       Dl_info di;
+       if (dladdr (ip, &di)) {
+               if (di.dli_sname)
+                       return di.dli_sname;
+       } else {
+       /*      char **names;
+               names = backtrace_symbols (&ip, 1);
+               if (names) {
+                       const char* p = names [0];
+                       g_free (names);
+                       return p;
+               }
+               */
+       }
+#endif
+       return NULL;
+}
+
+static void
+dump_unmanaged_coderefs (MonoProfiler *prof)
+{
+       int i;
+       const char* last_symbol;
+       uintptr_t addr, page_end;
+
+       if (load_binaries (prof))
+               return;
+       for (i = 0; i < size_code_pages; ++i) {
+               const char* sym;
+               if (!code_pages [i] || code_pages [i] & 1)
+                       continue;
+               last_symbol = NULL;
+               addr = CPAGE_ADDR (code_pages [i]);
+               page_end = addr + CPAGE_SIZE;
+               code_pages [i] |= 1;
+               /* we dump the symbols for the whole page */
+               for (; addr < page_end; addr += 16) {
+                       sym = symbol_for (addr);
+                       if (sym && sym == last_symbol)
+                               continue;
+                       last_symbol = sym;
+                       if (!sym)
+                               continue;
+                       dump_usym (prof, sym, addr, 0); /* let's not guess the size */
+                       //printf ("found symbol at %p: %s\n", (void*)addr, sym);
+               }
+       }
+}
+
+static int
+mono_cpu_count (void)
+{
+#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.
+        * Instead we use /sys entries to query the actual hardware CPU count.
+        */
+       int count = 0;
+       char buffer[8] = {'\0'};
+       int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
+       /* Format of the /sys entry is a cpulist of indexes which in the case
+        * of present is always of the form "0-(n-1)" when there is more than
+        * 1 core, n being the number of CPU cores in the system. Otherwise
+        * the value is simply 0
+        */
+       if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
+               count = strtol (((char*)buffer) + 2, NULL, 10);
+       if (present != -1)
+               close (present);
+       if (count > 0)
+               return count + 1;
+#endif
+
+#if defined(HOST_ARM) || defined (HOST_ARM64)
+
+       /* ARM platforms 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. */
+
+#ifdef _SC_NPROCESSORS_CONF
+       {
+               int count = sysconf (_SC_NPROCESSORS_CONF);
+               if (count > 0)
+                       return count;
+       }
+#endif
+
+#else
+
+#ifdef HAVE_SCHED_GETAFFINITY
+       {
+               cpu_set_t set;
+               if (sched_getaffinity (getpid (), sizeof (set), &set) == 0)
+                       return CPU_COUNT (&set);
+       }
+#endif
+#ifdef _SC_NPROCESSORS_ONLN
+       {
+               int count = sysconf (_SC_NPROCESSORS_ONLN);
+               if (count > 0)
+                       return count;
+       }
+#endif
+
+#endif /* defined(HOST_ARM) || defined (HOST_ARM64) */
+
+#ifdef USE_SYSCTL
+       {
+               int count;
+               int mib [2];
+               size_t len = sizeof (int);
+               mib [0] = CTL_HW;
+               mib [1] = HW_NCPU;
+               if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
+                       return count;
+       }
+#endif
+#ifdef HOST_WIN32
+       {
+               SYSTEM_INFO info;
+               GetSystemInfo (&info);
+               return info.dwNumberOfProcessors;
+       }
+#endif
+
+       static gboolean warned;
+
+       if (!warned) {
+               g_warning ("Don't know how to determine CPU count on this platform; assuming 1");
+               warned = TRUE;
+       }
+
+       return 1;
+}
+
+typedef struct MonoCounterAgent {
+       MonoCounter *counter;
+       // MonoCounterAgent specific data :
+       void *value;
+       size_t value_size;
+       short index;
+       short emitted;
+       struct MonoCounterAgent *next;
+} MonoCounterAgent;
+
+static MonoCounterAgent* counters;
+static int counters_index = 1;
+static mono_mutex_t counters_mutex;
+
+static void
+counters_add_agent (MonoCounter *counter)
+{
+       if (InterlockedRead (&in_shutdown))
+               return;
+
+       MonoCounterAgent *agent, *item;
+
+       mono_os_mutex_lock (&counters_mutex);
+
+       for (agent = counters; agent; agent = agent->next) {
+               if (agent->counter == counter) {
+                       agent->value_size = 0;
+                       if (agent->value) {
+                               g_free (agent->value);
+                               agent->value = NULL;
+                       }
+                       goto done;
+               }
+       }
+
+       agent = (MonoCounterAgent *) g_malloc (sizeof (MonoCounterAgent));
+       agent->counter = counter;
+       agent->value = NULL;
+       agent->value_size = 0;
+       agent->index = counters_index++;
+       agent->emitted = 0;
+       agent->next = NULL;
+
+       if (!counters) {
+               counters = agent;
+       } else {
+               item = counters;
+               while (item->next)
+                       item = item->next;
+               item->next = agent;
+       }
+
+done:
+       mono_os_mutex_unlock (&counters_mutex);
+}
+
+static mono_bool
+counters_init_foreach_callback (MonoCounter *counter, gpointer data)
+{
+       counters_add_agent (counter);
+       return TRUE;
+}
+
+static void
+counters_init (MonoProfiler *profiler)
+{
+       mono_os_mutex_init (&counters_mutex);
+
+       mono_counters_on_register (&counters_add_agent);
+       mono_counters_foreach (counters_init_foreach_callback, NULL);
+}
+
+static void
+counters_emit (MonoProfiler *profiler)
+{
+       MonoCounterAgent *agent;
+       int len = 0;
+       int size =
+               EVENT_SIZE /* event */ +
+               LEB128_SIZE /* len */
+       ;
+
+       mono_os_mutex_lock (&counters_mutex);
+
+       for (agent = counters; agent; agent = agent->next) {
+               if (agent->emitted)
+                       continue;
+
+               size +=
+                       LEB128_SIZE /* section */ +
+                       strlen (mono_counter_get_name (agent->counter)) + 1 /* name */ +
+                       BYTE_SIZE /* type */ +
+                       BYTE_SIZE /* unit */ +
+                       BYTE_SIZE /* variance */ +
+                       LEB128_SIZE /* index */
+               ;
+
+               len++;
+       }
+
+       if (!len)
+               goto done;
+
+       ENTER_LOG (&counter_descriptors_ctr, logbuffer, size);
+
+       emit_event (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
+       emit_value (logbuffer, len);
+
+       for (agent = counters; agent; agent = agent->next) {
+               const char *name;
+
+               if (agent->emitted)
+                       continue;
+
+               name = mono_counter_get_name (agent->counter);
+               emit_value (logbuffer, mono_counter_get_section (agent->counter));
+               emit_string (logbuffer, name, strlen (name) + 1);
+               emit_byte (logbuffer, mono_counter_get_type (agent->counter));
+               emit_byte (logbuffer, mono_counter_get_unit (agent->counter));
+               emit_byte (logbuffer, mono_counter_get_variance (agent->counter));
+               emit_value (logbuffer, agent->index);
+
+               agent->emitted = 1;
+       }
+
+       EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+
+done:
+       mono_os_mutex_unlock (&counters_mutex);
+}
+
+static void
+counters_sample (MonoProfiler *profiler, uint64_t timestamp)
+{
+       MonoCounterAgent *agent;
+       MonoCounter *counter;
+       int type;
+       int buffer_size;
+       void *buffer;
+       int size;
+
+       counters_emit (profiler);
+
+       buffer_size = 8;
+       buffer = g_calloc (1, buffer_size);
+
+       mono_os_mutex_lock (&counters_mutex);
+
+       size =
+               EVENT_SIZE /* event */
+       ;
+
+       for (agent = counters; agent; agent = agent->next) {
+               size +=
+                       LEB128_SIZE /* index */ +
+                       BYTE_SIZE /* type */ +
+                       mono_counter_get_size (agent->counter) /* value */
+               ;
+       }
+
+       size +=
+               LEB128_SIZE /* stop marker */
+       ;
+
+       ENTER_LOG (&counter_samples_ctr, logbuffer, size);
+
+       emit_event_time (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE, timestamp);
+
+       for (agent = counters; agent; agent = agent->next) {
+               size_t size;
+
+               counter = agent->counter;
+
+               size = mono_counter_get_size (counter);
+
+               if (size > buffer_size) {
+                       buffer_size = size;
+                       buffer = g_realloc (buffer, buffer_size);
+               }
+
+               memset (buffer, 0, buffer_size);
+
+               g_assert (mono_counters_sample (counter, buffer, size));
+
+               type = mono_counter_get_type (counter);
+
+               if (!agent->value) {
+                       agent->value = g_calloc (1, size);
+                       agent->value_size = size;
+               } else {
+                       if (type == MONO_COUNTER_STRING) {
+                               if (strcmp (agent->value, buffer) == 0)
+                                       continue;
+                       } else {
+                               if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
+                                       continue;
+                       }
+               }
+
+               emit_uvalue (logbuffer, agent->index);
+               emit_byte (logbuffer, type);
+               switch (type) {
+               case MONO_COUNTER_INT:
+#if SIZEOF_VOID_P == 4
+               case MONO_COUNTER_WORD:
+#endif
+                       emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
+                       break;
+               case MONO_COUNTER_UINT:
+                       emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
+                       break;
+               case MONO_COUNTER_TIME_INTERVAL:
+               case MONO_COUNTER_LONG:
+#if SIZEOF_VOID_P == 8
+               case MONO_COUNTER_WORD:
+#endif
+                       emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
+                       break;
+               case MONO_COUNTER_ULONG:
+                       emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
+                       break;
+               case MONO_COUNTER_DOUBLE:
+                       emit_double (logbuffer, *(double*)buffer);
+                       break;
+               case MONO_COUNTER_STRING:
+                       if (size == 0) {
+                               emit_byte (logbuffer, 0);
+                       } else {
+                               emit_byte (logbuffer, 1);
+                               emit_string (logbuffer, (char*)buffer, size);
+                       }
+                       break;
+               default:
+                       g_assert_not_reached ();
+               }
+
+               if (type == MONO_COUNTER_STRING && size > agent->value_size) {
+                       agent->value = g_realloc (agent->value, size);
+                       agent->value_size = size;
+               }
+
+               if (size > 0)
+                       memcpy (agent->value, buffer, size);
+       }
+       g_free (buffer);
+
+       emit_value (logbuffer, 0);
+
+       EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+
+       mono_os_mutex_unlock (&counters_mutex);
+}
+
+typedef struct _PerfCounterAgent PerfCounterAgent;
+struct _PerfCounterAgent {
+       PerfCounterAgent *next;
+       int index;
+       char *category_name;
+       char *name;
+       int type;
+       gint64 value;
+       guint8 emitted;
+       guint8 updated;
+       guint8 deleted;
+};
+
+static PerfCounterAgent *perfcounters = NULL;
+
+static void
+perfcounters_emit (MonoProfiler *profiler)
+{
+       PerfCounterAgent *pcagent;
+       int len = 0;
+       int size =
+               EVENT_SIZE /* event */ +
+               LEB128_SIZE /* len */
+       ;
+
+       for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
+               if (pcagent->emitted)
+                       continue;
+
+               size +=
+                       LEB128_SIZE /* section */ +
+                       strlen (pcagent->category_name) + 1 /* category name */ +
+                       strlen (pcagent->name) + 1 /* name */ +
+                       BYTE_SIZE /* type */ +
+                       BYTE_SIZE /* unit */ +
+                       BYTE_SIZE /* variance */ +
+                       LEB128_SIZE /* index */
+               ;
+
+               len++;
+       }
+
+       if (!len)
+               return;
+
+       ENTER_LOG (&perfcounter_descriptors_ctr, logbuffer, size);
+
+       emit_event (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
+       emit_value (logbuffer, len);
+
+       for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
+               if (pcagent->emitted)
+                       continue;
+
+               emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
+               emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
+               emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
+               emit_byte (logbuffer, MONO_COUNTER_LONG);
+               emit_byte (logbuffer, MONO_COUNTER_RAW);
+               emit_byte (logbuffer, MONO_COUNTER_VARIABLE);
+               emit_value (logbuffer, pcagent->index);
+
+               pcagent->emitted = 1;
+       }
+
+       EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+}
+
+static gboolean
+perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
+{
+       PerfCounterAgent *pcagent;
+
+       for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
+               if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
+                       continue;
+               if (pcagent->value == value)
+                       return TRUE;
+
+               pcagent->value = value;
+               pcagent->updated = 1;
+               pcagent->deleted = 0;
+               return TRUE;
+       }
+
+       pcagent = g_new0 (PerfCounterAgent, 1);
+       pcagent->next = perfcounters;
+       pcagent->index = counters_index++;
+       pcagent->category_name = g_strdup (category_name);
+       pcagent->name = g_strdup (name);
+       pcagent->type = (int) type;
+       pcagent->value = value;
+       pcagent->emitted = 0;
+       pcagent->updated = 1;
+       pcagent->deleted = 0;
+
+       perfcounters = pcagent;
+
+       return TRUE;
+}
+
+static void
+perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp)
+{
+       PerfCounterAgent *pcagent;
+       int len = 0;
+       int size;
+
+       mono_os_mutex_lock (&counters_mutex);
+
+       /* mark all perfcounters as deleted, foreach will unmark them as necessary */
+       for (pcagent = perfcounters; pcagent; pcagent = pcagent->next)
+               pcagent->deleted = 1;
+
+       mono_perfcounter_foreach (perfcounters_foreach, perfcounters);
+
+       perfcounters_emit (profiler);
+
+       size =
+               EVENT_SIZE /* event */
+       ;
+
+       for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
+               if (pcagent->deleted || !pcagent->updated)
+                       continue;
+
+               size +=
+                       LEB128_SIZE /* index */ +
+                       BYTE_SIZE /* type */ +
+                       LEB128_SIZE /* value */
+               ;
+
+               len++;
+       }
+
+       if (!len)
+               goto done;
+
+       size +=
+               LEB128_SIZE /* stop marker */
+       ;
+
+       ENTER_LOG (&perfcounter_samples_ctr, logbuffer, size);
+
+       emit_event_time (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE, timestamp);
+
+       for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
+               if (pcagent->deleted || !pcagent->updated)
+                       continue;
+               emit_uvalue (logbuffer, pcagent->index);
+               emit_byte (logbuffer, MONO_COUNTER_LONG);
+               emit_svalue (logbuffer, pcagent->value);
+
+               pcagent->updated = 0;
+       }
+
+       emit_value (logbuffer, 0);
+
+       EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+
+done:
+       mono_os_mutex_unlock (&counters_mutex);
+}
+
+static void
+counters_and_perfcounters_sample (MonoProfiler *prof)
+{
+       uint64_t now = current_time ();
+
+       counters_sample (prof, now);
+       perfcounters_sample (prof, now);
+}
+
+#define COVERAGE_DEBUG(x) if (debug_coverage) {x}
+static mono_mutex_t coverage_mutex;
+static MonoConcurrentHashTable *coverage_methods = NULL;
+static MonoConcurrentHashTable *coverage_assemblies = NULL;
+static MonoConcurrentHashTable *coverage_classes = NULL;
+
+static MonoConcurrentHashTable *filtered_classes = NULL;
+static MonoConcurrentHashTable *entered_methods = NULL;
+static MonoConcurrentHashTable *image_to_methods = NULL;
+static MonoConcurrentHashTable *suppressed_assemblies = NULL;
+static gboolean coverage_initialized = FALSE;
+
+static GPtrArray *coverage_data = NULL;
+static int previous_offset = 0;
+
+typedef struct {
+       MonoLockFreeQueueNode node;
+       MonoMethod *method;
+} MethodNode;
+
+typedef struct {
+       int offset;
+       int counter;
+       char *filename;
+       int line;
+       int column;
+} CoverageEntry;
+
+static void
+free_coverage_entry (gpointer data, gpointer userdata)
+{
+       CoverageEntry *entry = (CoverageEntry *)data;
+       g_free (entry->filename);
+       g_free (entry);
+}
+
+static void
+obtain_coverage_for_method (MonoProfiler *prof, const MonoProfileCoverageEntry *entry)
+{
+       int offset = entry->iloffset - previous_offset;
+       CoverageEntry *e = g_new (CoverageEntry, 1);
+
+       previous_offset = entry->iloffset;
+
+       e->offset = offset;
+       e->counter = entry->counter;
+       e->filename = g_strdup(entry->filename ? entry->filename : "");
+       e->line = entry->line;
+       e->column = entry->col;
+
+       g_ptr_array_add (coverage_data, e);
+}
+
+static char *
+parse_generic_type_names(char *name)
+{
+       char *new_name, *ret;
+       int within_generic_declaration = 0, generic_members = 1;
+
+       if (name == NULL || *name == '\0')
+               return g_strdup ("");
+
+       if (!(ret = new_name = (char *) g_calloc (strlen (name) * 4 + 1, sizeof (char))))
+               return NULL;
+
+       do {
+               switch (*name) {
+                       case '<':
+                               within_generic_declaration = 1;
+                               break;
+
+                       case '>':
+                               within_generic_declaration = 0;
+
+                               if (*(name - 1) != '<') {
+                                       *new_name++ = '`';
+                                       *new_name++ = '0' + generic_members;
+                               } else {
+                                       memcpy (new_name, "&lt;&gt;", 8);
+                                       new_name += 8;
+                               }
+
+                               generic_members = 0;
+                               break;
+
+                       case ',':
+                               generic_members++;
+                               break;
+
+                       default:
+                               if (!within_generic_declaration)
+                                       *new_name++ = *name;
+
+                               break;
+               }
+       } while (*name++);
+
+       return ret;
+}
+
+static int method_id;
+static void
+build_method_buffer (gpointer key, gpointer value, gpointer userdata)
+{
+       MonoMethod *method = (MonoMethod *)value;
+       MonoProfiler *prof = (MonoProfiler *)userdata;
+       MonoClass *klass;
+       MonoImage *image;
+       char *class_name;
+       const char *image_name, *method_name, *sig, *first_filename;
+       guint i;
+
+       previous_offset = 0;
+       coverage_data = g_ptr_array_new ();
+
+       mono_profiler_coverage_get (prof, method, obtain_coverage_for_method);
+
+       klass = mono_method_get_class (method);
+       image = mono_class_get_image (klass);
+       image_name = mono_image_get_name (image);
+
+       sig = mono_signature_get_desc (mono_method_signature (method), TRUE);
+       class_name = parse_generic_type_names (mono_type_get_name (mono_class_get_type (klass)));
+       method_name = mono_method_get_name (method);
+
+       if (coverage_data->len != 0) {
+               CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[0];
+               first_filename = entry->filename ? entry->filename : "";
+       } else
+               first_filename = "";
+
+       image_name = image_name ? image_name : "";
+       sig = sig ? sig : "";
+       method_name = method_name ? method_name : "";
+
+       ENTER_LOG (&coverage_methods_ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               strlen (image_name) + 1 /* image name */ +
+               strlen (class_name) + 1 /* class name */ +
+               strlen (method_name) + 1 /* method name */ +
+               strlen (sig) + 1 /* signature */ +
+               strlen (first_filename) + 1 /* first file name */ +
+               LEB128_SIZE /* token */ +
+               LEB128_SIZE /* method id */ +
+               LEB128_SIZE /* entries */
+       );
+
+       emit_event (logbuffer, TYPE_COVERAGE_METHOD | TYPE_COVERAGE);
+       emit_string (logbuffer, image_name, strlen (image_name) + 1);
+       emit_string (logbuffer, class_name, strlen (class_name) + 1);
+       emit_string (logbuffer, method_name, strlen (method_name) + 1);
+       emit_string (logbuffer, sig, strlen (sig) + 1);
+       emit_string (logbuffer, first_filename, strlen (first_filename) + 1);
+
+       emit_uvalue (logbuffer, mono_method_get_token (method));
+       emit_uvalue (logbuffer, method_id);
+       emit_value (logbuffer, coverage_data->len);
+
+       EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+
+       for (i = 0; i < coverage_data->len; i++) {
+               CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[i];
+
+               ENTER_LOG (&coverage_statements_ctr, logbuffer,
+                       EVENT_SIZE /* event */ +
+                       LEB128_SIZE /* method id */ +
+                       LEB128_SIZE /* offset */ +
+                       LEB128_SIZE /* counter */ +
+                       LEB128_SIZE /* line */ +
+                       LEB128_SIZE /* column */
+               );
+
+               emit_event (logbuffer, TYPE_COVERAGE_STATEMENT | TYPE_COVERAGE);
+               emit_uvalue (logbuffer, method_id);
+               emit_uvalue (logbuffer, entry->offset);
+               emit_uvalue (logbuffer, entry->counter);
+               emit_uvalue (logbuffer, entry->line);
+               emit_uvalue (logbuffer, entry->column);
+
+               EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+       }
+
+       method_id++;
+
+       g_free (class_name);
+
+       g_ptr_array_foreach (coverage_data, free_coverage_entry, NULL);
+       g_ptr_array_free (coverage_data, TRUE);
+       coverage_data = NULL;
+}
+
+/* This empties the queue */
+static guint
+count_queue (MonoLockFreeQueue *queue)
+{
+       MonoLockFreeQueueNode *node;
+       guint count = 0;
+
+       while ((node = mono_lock_free_queue_dequeue (queue))) {
+               count++;
+               mono_thread_hazardous_try_free (node, g_free);
+       }
+
+       return count;
+}
+
+static void
+build_class_buffer (gpointer key, gpointer value, gpointer userdata)
+{
+       MonoClass *klass = (MonoClass *)key;
+       MonoLockFreeQueue *class_methods = (MonoLockFreeQueue *)value;
+       MonoImage *image;
+       char *class_name;
+       const char *assembly_name;
+       int number_of_methods, partially_covered;
+       guint fully_covered;
+
+       image = mono_class_get_image (klass);
+       assembly_name = mono_image_get_name (image);
+       class_name = mono_type_get_name (mono_class_get_type (klass));
+
+       assembly_name = assembly_name ? assembly_name : "";
+       number_of_methods = mono_class_num_methods (klass);
+       fully_covered = count_queue (class_methods);
+       /* We don't handle partial covered yet */
+       partially_covered = 0;
+
+       ENTER_LOG (&coverage_classes_ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               strlen (assembly_name) + 1 /* assembly name */ +
+               strlen (class_name) + 1 /* class name */ +
+               LEB128_SIZE /* no. methods */ +
+               LEB128_SIZE /* fully covered */ +
+               LEB128_SIZE /* partially covered */
+       );
+
+       emit_event (logbuffer, TYPE_COVERAGE_CLASS | TYPE_COVERAGE);
+       emit_string (logbuffer, assembly_name, strlen (assembly_name) + 1);
+       emit_string (logbuffer, class_name, strlen (class_name) + 1);
+       emit_uvalue (logbuffer, number_of_methods);
+       emit_uvalue (logbuffer, fully_covered);
+       emit_uvalue (logbuffer, partially_covered);
+
+       EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+
+       g_free (class_name);
+}
+
+static void
+get_coverage_for_image (MonoImage *image, int *number_of_methods, guint *fully_covered, int *partially_covered)
+{
+       MonoLockFreeQueue *image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
+
+       *number_of_methods = mono_image_get_table_rows (image, MONO_TABLE_METHOD);
+       if (image_methods)
+               *fully_covered = count_queue (image_methods);
+       else
+               *fully_covered = 0;
+
+       // FIXME: We don't handle partially covered yet.
+       *partially_covered = 0;
+}
+
+static void
+build_assembly_buffer (gpointer key, gpointer value, gpointer userdata)
+{
+       MonoAssembly *assembly = (MonoAssembly *)value;
+       MonoImage *image = mono_assembly_get_image (assembly);
+       const char *name, *guid, *filename;
+       int number_of_methods = 0, partially_covered = 0;
+       guint fully_covered = 0;
+
+       name = mono_image_get_name (image);
+       guid = mono_image_get_guid (image);
+       filename = mono_image_get_filename (image);
+
+       name = name ? name : "";
+       guid = guid ? guid : "";
+       filename = filename ? filename : "";
+
+       get_coverage_for_image (image, &number_of_methods, &fully_covered, &partially_covered);
+
+       ENTER_LOG (&coverage_assemblies_ctr, logbuffer,
+               EVENT_SIZE /* event */ +
+               strlen (name) + 1 /* name */ +
+               strlen (guid) + 1 /* guid */ +
+               strlen (filename) + 1 /* file name */ +
+               LEB128_SIZE /* no. methods */ +
+               LEB128_SIZE /* fully covered */ +
+               LEB128_SIZE /* partially covered */
+       );
+
+       emit_event (logbuffer, TYPE_COVERAGE_ASSEMBLY | TYPE_COVERAGE);
+       emit_string (logbuffer, name, strlen (name) + 1);
+       emit_string (logbuffer, guid, strlen (guid) + 1);
+       emit_string (logbuffer, filename, strlen (filename) + 1);
+       emit_uvalue (logbuffer, number_of_methods);
+       emit_uvalue (logbuffer, fully_covered);
+       emit_uvalue (logbuffer, partially_covered);
+
+       EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+}
+
+static void
+dump_coverage (MonoProfiler *prof)
+{
+       if (!coverage_initialized)
+               return;
+
+       COVERAGE_DEBUG(fprintf (stderr, "Coverage: Started dump\n");)
+       method_id = 0;
+
+       mono_os_mutex_lock (&coverage_mutex);
+       mono_conc_hashtable_foreach (coverage_assemblies, build_assembly_buffer, NULL);
+       mono_conc_hashtable_foreach (coverage_classes, build_class_buffer, NULL);
+       mono_conc_hashtable_foreach (coverage_methods, build_method_buffer, prof);
+       mono_os_mutex_unlock (&coverage_mutex);
+
+       COVERAGE_DEBUG(fprintf (stderr, "Coverage: Finished dump\n");)
+}
+
+static void
+process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method)
+{
+       MonoClass *klass;
+       MonoImage *image;
+
+       if (!coverage_initialized)
+               return;
+
+       klass = mono_method_get_class (method);
+       image = mono_class_get_image (klass);
+
+       if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)))
+               return;
+
+       mono_os_mutex_lock (&coverage_mutex);
+       mono_conc_hashtable_insert (entered_methods, method, method);
+       mono_os_mutex_unlock (&coverage_mutex);
+}
+
+static MonoLockFreeQueueNode *
+create_method_node (MonoMethod *method)
+{
+       MethodNode *node = (MethodNode *) g_malloc (sizeof (MethodNode));
+       mono_lock_free_queue_node_init ((MonoLockFreeQueueNode *) node, FALSE);
+       node->method = method;
+
+       return (MonoLockFreeQueueNode *) node;
+}
+
+static gboolean
+coverage_filter (MonoProfiler *prof, MonoMethod *method)
+{
+       MonoError error;
+       MonoClass *klass;
+       MonoImage *image;
+       MonoAssembly *assembly;
+       MonoMethodHeader *header;
+       guint32 iflags, flags, code_size;
+       char *fqn, *classname;
+       gboolean has_positive, found;
+       MonoLockFreeQueue *image_methods, *class_methods;
+       MonoLockFreeQueueNode *node;
+
+       g_assert (coverage_initialized && "Why are we being asked for coverage filter info when we're not doing coverage?");
+
+       COVERAGE_DEBUG(fprintf (stderr, "Coverage filter for %s\n", mono_method_get_name (method));)
+
+       flags = mono_method_get_flags (method, &iflags);
+       if ((iflags & 0x1000 /*METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL*/) ||
+           (flags & 0x2000 /*METHOD_ATTRIBUTE_PINVOKE_IMPL*/)) {
+               COVERAGE_DEBUG(fprintf (stderr, "   Internal call or pinvoke - ignoring\n");)
+               return FALSE;
+       }
+
+       // Don't need to do anything else if we're already tracking this method
+       if (mono_conc_hashtable_lookup (coverage_methods, method)) {
+               COVERAGE_DEBUG(fprintf (stderr, "   Already tracking\n");)
+               return TRUE;
+       }
+
+       klass = mono_method_get_class (method);
+       image = mono_class_get_image (klass);
+
+       // Don't handle coverage for the core assemblies
+       if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)) != NULL)
+               return FALSE;
+
+       if (prof->coverage_filters) {
+               /* Check already filtered classes first */
+               if (mono_conc_hashtable_lookup (filtered_classes, klass)) {
+                       COVERAGE_DEBUG(fprintf (stderr, "   Already filtered\n");)
+                       return FALSE;
+               }
+
+               classname = mono_type_get_name (mono_class_get_type (klass));
+
+               fqn = g_strdup_printf ("[%s]%s", mono_image_get_name (image), classname);
+
+               COVERAGE_DEBUG(fprintf (stderr, "   Looking for %s in filter\n", fqn);)
+               // Check positive filters first
+               has_positive = FALSE;
+               found = FALSE;
+               for (guint i = 0; i < prof->coverage_filters->len; ++i) {
+                       char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
+
+                       if (filter [0] == '+') {
+                               filter = &filter [1];
+
+                               COVERAGE_DEBUG(fprintf (stderr, "   Checking against +%s ...", filter);)
+
+                               if (strstr (fqn, filter) != NULL) {
+                                       COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
+                                       found = TRUE;
+                               } else
+                                       COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
+
+                               has_positive = TRUE;
+                       }
+               }
+
+               if (has_positive && !found) {
+                       COVERAGE_DEBUG(fprintf (stderr, "   Positive match was not found\n");)
+
+                       mono_os_mutex_lock (&coverage_mutex);
+                       mono_conc_hashtable_insert (filtered_classes, klass, klass);
+                       mono_os_mutex_unlock (&coverage_mutex);
+                       g_free (fqn);
+                       g_free (classname);
+
+                       return FALSE;
+               }
+
+               for (guint i = 0; i < prof->coverage_filters->len; ++i) {
+                       // FIXME: Is substring search sufficient?
+                       char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
+                       if (filter [0] == '+')
+                               continue;
+
+                       // Skip '-'
+                       filter = &filter [1];
+                       COVERAGE_DEBUG(fprintf (stderr, "   Checking against -%s ...", filter);)
+
+                       if (strstr (fqn, filter) != NULL) {
+                               COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
+
+                               mono_os_mutex_lock (&coverage_mutex);
+                               mono_conc_hashtable_insert (filtered_classes, klass, klass);
+                               mono_os_mutex_unlock (&coverage_mutex);
+                               g_free (fqn);
+                               g_free (classname);
+
+                               return FALSE;
+                       } else
+                               COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
+
+               }
+
+               g_free (fqn);
+               g_free (classname);
+       }
+
+       COVERAGE_DEBUG(fprintf (stderr, "   Handling coverage for %s\n", mono_method_get_name (method));)
+       header = mono_method_get_header_checked (method, &error);
+       mono_error_cleanup (&error);
+
+       mono_method_header_get_code (header, &code_size, NULL);
+
+       assembly = mono_image_get_assembly (image);
+
+       // Need to keep the assemblies around for as long as they are kept in the hashtable
+       // Nunit, for example, has a habit of unloading them before the coverage statistics are
+       // generated causing a crash. See https://bugzilla.xamarin.com/show_bug.cgi?id=39325
+       mono_assembly_addref (assembly);
+
+       mono_os_mutex_lock (&coverage_mutex);
+       mono_conc_hashtable_insert (coverage_methods, method, method);
+       mono_conc_hashtable_insert (coverage_assemblies, assembly, assembly);
+       mono_os_mutex_unlock (&coverage_mutex);
+
+       image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
+
+       if (image_methods == NULL) {
+               image_methods = (MonoLockFreeQueue *) g_malloc (sizeof (MonoLockFreeQueue));
+               mono_lock_free_queue_init (image_methods);
+               mono_os_mutex_lock (&coverage_mutex);
+               mono_conc_hashtable_insert (image_to_methods, image, image_methods);
+               mono_os_mutex_unlock (&coverage_mutex);
+       }
+
+       node = create_method_node (method);
+       mono_lock_free_queue_enqueue (image_methods, node);
+
+       class_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (coverage_classes, klass);
+
+       if (class_methods == NULL) {
+               class_methods = (MonoLockFreeQueue *) g_malloc (sizeof (MonoLockFreeQueue));
+               mono_lock_free_queue_init (class_methods);
+               mono_os_mutex_lock (&coverage_mutex);
+               mono_conc_hashtable_insert (coverage_classes, klass, class_methods);
+               mono_os_mutex_unlock (&coverage_mutex);
+       }
+
+       node = create_method_node (method);
+       mono_lock_free_queue_enqueue (class_methods, node);
+
+       return TRUE;
+}
+
+#define LINE_BUFFER_SIZE 4096
+/* Max file limit of 128KB */
+#define MAX_FILE_SIZE 128 * 1024
+static char *
+get_file_content (FILE *stream)
+{
+       char *buffer;
+       ssize_t bytes_read;
+       long filesize;
+       int res, offset = 0;
+
+       res = fseek (stream, 0, SEEK_END);
+       if (res < 0)
+         return NULL;
+
+       filesize = ftell (stream);
+       if (filesize < 0)
+         return NULL;
+
+       res = fseek (stream, 0, SEEK_SET);
+       if (res < 0)
+         return NULL;
+
+       if (filesize > MAX_FILE_SIZE)
+         return NULL;
+
+       buffer = (char *) g_malloc ((filesize + 1) * sizeof (char));
+       while ((bytes_read = fread (buffer + offset, 1, LINE_BUFFER_SIZE, stream)) > 0)
+               offset += bytes_read;
+
+       /* NULL terminate our buffer */
+       buffer[filesize] = '\0';
+       return buffer;
+}
+
+static char *
+get_next_line (char *contents, char **next_start)
+{
+       char *p = contents;
+
+       if (p == NULL || *p == '\0') {
+               *next_start = NULL;
+               return NULL;
+       }
+
+       while (*p != '\n' && *p != '\0')
+               p++;
+
+       if (*p == '\n') {
+               *p = '\0';
+               *next_start = p + 1;
+       } else
+               *next_start = NULL;
+
+       return contents;
+}
+
+static void
+init_suppressed_assemblies (void)
+{
+       char *content;
+       char *line;
+       FILE *sa_file;
+
+       suppressed_assemblies = mono_conc_hashtable_new (g_str_hash, g_str_equal);
+       sa_file = fopen (SUPPRESSION_DIR "/mono-profiler-log.suppression", "r");
+       if (sa_file == NULL)
+               return;
+
+       /* Don't need to free @content as it is referred to by the lines stored in @suppressed_assemblies */
+       content = get_file_content (sa_file);
+       if (content == NULL) {
+               g_error ("mono-profiler-log.suppression is greater than 128kb - aborting\n");
+       }
+
+       while ((line = get_next_line (content, &content))) {
+               line = g_strchomp (g_strchug (line));
+               /* No locking needed as we're doing initialization */
+               mono_conc_hashtable_insert (suppressed_assemblies, line, line);
+       }
+
+       fclose (sa_file);
+}
+
+static void
+coverage_init (MonoProfiler *prof)
+{
+       g_assert (!coverage_initialized && "Why are we initializing coverage twice?");
+
+       COVERAGE_DEBUG(fprintf (stderr, "Coverage initialized\n");)
+
+       mono_os_mutex_init (&coverage_mutex);
+       coverage_methods = mono_conc_hashtable_new (NULL, NULL);
+       coverage_assemblies = mono_conc_hashtable_new (NULL, NULL);
+       coverage_classes = mono_conc_hashtable_new (NULL, NULL);
+       filtered_classes = mono_conc_hashtable_new (NULL, NULL);
+       entered_methods = mono_conc_hashtable_new (NULL, NULL);
+       image_to_methods = mono_conc_hashtable_new (NULL, NULL);
+       init_suppressed_assemblies ();
+
+       coverage_initialized = TRUE;
+}
+
+static void
+unref_coverage_assemblies (gpointer key, gpointer value, gpointer userdata)
+{
+       MonoAssembly *assembly = (MonoAssembly *)value;
+       mono_assembly_close (assembly);
+}
+
+static void
+free_sample_hit (gpointer p)
+{
+       mono_lock_free_free (p, SAMPLE_BLOCK_SIZE);
+}
+
+static void
+cleanup_reusable_samples (MonoProfiler *prof)
+{
+       SampleHit *sample;
+
+       while ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&prof->sample_reuse_queue)))
+               mono_thread_hazardous_try_free (sample, free_sample_hit);
+}
+
+static void
+log_shutdown (MonoProfiler *prof)
+{
+       InterlockedWrite (&in_shutdown, 1);
+
+       if (!no_counters)
+               counters_and_perfcounters_sample (prof);
+
+       dump_coverage (prof);
+
+       char c = 1;
+
+       if (write (prof->pipes [1], &c, 1) != 1) {
+               fprintf (stderr, "Could not write to pipe: %s\n", strerror (errno));
+               exit (1);
+       }
+
+       mono_native_thread_join (prof->helper_thread);
+
+       mono_os_mutex_destroy (&counters_mutex);
+
+       MonoCounterAgent *mc_next;
+
+       for (MonoCounterAgent *cur = counters; cur; cur = mc_next) {
+               mc_next = cur->next;
+               g_free (cur);
+       }
+
+       PerfCounterAgent *pc_next;
+
+       for (PerfCounterAgent *cur = perfcounters; cur; cur = pc_next) {
+               pc_next = cur->next;
+               g_free (cur);
+       }
+
+       /*
+        * Ensure that we empty the LLS completely, even if some nodes are
+        * not immediately removed upon calling mono_lls_remove (), by
+        * iterating until the head is NULL.
+        */
+       while (profiler_thread_list.head) {
+               MONO_LLS_FOREACH_SAFE (&profiler_thread_list, MonoProfilerThread, thread) {
+                       g_assert (thread->attached && "Why is a thread in the LLS not attached?");
+
+                       remove_thread (thread);
+               } MONO_LLS_FOREACH_SAFE_END
+       }
+
+       /*
+        * Ensure that all threads have been freed, so that we don't miss any
+        * buffers when we shut down the writer thread below.
+        */
+       mono_thread_hazardous_try_free_all ();
+
+       InterlockedWrite (&prof->run_dumper_thread, 0);
+       mono_os_sem_post (&prof->dumper_queue_sem);
+       mono_native_thread_join (prof->dumper_thread);
+       mono_os_sem_destroy (&prof->dumper_queue_sem);
+
+       InterlockedWrite (&prof->run_writer_thread, 0);
+       mono_os_sem_post (&prof->writer_queue_sem);
+       mono_native_thread_join (prof->writer_thread);
+       mono_os_sem_destroy (&prof->writer_queue_sem);
+
+       /*
+        * Free all writer queue entries, and ensure that all sample hits will be
+        * added to the sample reuse queue.
+        */
+       mono_thread_hazardous_try_free_all ();
+
+       cleanup_reusable_samples (prof);
+
+       /*
+        * Finally, make sure that all sample hits are freed. This should cover all
+        * hazardous data from the profiler. We can now be sure that the runtime
+        * won't later invoke free functions in the profiler library after it has
+        * been unloaded.
+        */
+       mono_thread_hazardous_try_free_all ();
+
+       g_assert (!InterlockedRead (&buffer_rwlock_count) && "Why is the reader count still non-zero?");
+       g_assert (!InterlockedReadPointer (&buffer_rwlock_exclusive) && "Why does someone still hold the exclusive lock?");
+
+#if defined (HAVE_SYS_ZLIB)
+       if (prof->gzfile)
+               gzclose (prof->gzfile);
+#endif
+       if (prof->pipe_output)
+               pclose (prof->file);
+       else
+               fclose (prof->file);
+
+       mono_conc_hashtable_destroy (prof->method_table);
+       mono_os_mutex_destroy (&prof->method_table_mutex);
+
+       if (coverage_initialized) {
+               mono_os_mutex_lock (&coverage_mutex);
+               mono_conc_hashtable_foreach (coverage_assemblies, unref_coverage_assemblies, prof);
+               mono_os_mutex_unlock (&coverage_mutex);
+
+               mono_conc_hashtable_destroy (coverage_methods);
+               mono_conc_hashtable_destroy (coverage_assemblies);
+               mono_conc_hashtable_destroy (coverage_classes);
+               mono_conc_hashtable_destroy (filtered_classes);
+
+               mono_conc_hashtable_destroy (entered_methods);
+               mono_conc_hashtable_destroy (image_to_methods);
+               mono_conc_hashtable_destroy (suppressed_assemblies);
+               mono_os_mutex_destroy (&coverage_mutex);
+       }
+
+       PROF_TLS_FREE ();
+
+       g_free (prof->args);
+       g_free (prof);
+}
+
+static char*
+new_filename (const char* filename)
+{
+       time_t t = time (NULL);
+       int pid = process_id ();
+       char pid_buf [16];
+       char time_buf [16];
+       char *res, *d;
+       const char *p;
+       int count_dates = 0;
+       int count_pids = 0;
+       int s_date, s_pid;
+       struct tm *ts;
+       for (p = filename; *p; p++) {
+               if (*p != '%')
+                       continue;
+               p++;
+               if (*p == 't')
+                       count_dates++;
+               else if (*p == 'p')
+                       count_pids++;
+               else if (*p == 0)
+                       break;
+       }
+       if (!count_dates && !count_pids)
+               return pstrdup (filename);
+       snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
+       ts = gmtime (&t);
+       snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
+               1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
+       s_date = strlen (time_buf);
+       s_pid = strlen (pid_buf);
+       d = res = (char *) g_malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
+       for (p = filename; *p; p++) {
+               if (*p != '%') {
+                       *d++ = *p;
+                       continue;
+               }
+               p++;
+               if (*p == 't') {
+                       strcpy (d, time_buf);
+                       d += s_date;
+                       continue;
+               } else if (*p == 'p') {
+                       strcpy (d, pid_buf);
+                       d += s_pid;
+                       continue;
+               } else if (*p == '%') {
+                       *d++ = '%';
+                       continue;
+               } else if (*p == 0)
+                       break;
+               *d++ = '%';
+               *d++ = *p;
+       }
+       *d = 0;
+       return res;
+}
+
+static void
+add_to_fd_set (fd_set *set, int fd, int *max_fd)
+{
+       /*
+        * This should only trigger for the basic FDs (server socket, pipes) at
+        * startup if for some mysterious reason they're too large. In this case,
+        * the profiler really can't function, and we're better off printing an
+        * error and exiting.
+        */
+       if (fd >= FD_SETSIZE) {
+               fprintf (stderr, "File descriptor is out of bounds for fd_set: %d\n", fd);
+               exit (1);
+       }
+
+       FD_SET (fd, set);
+
+       if (*max_fd < fd)
+               *max_fd = fd;
+}
+
+static void *
+helper_thread (void *arg)
+{
+       MonoProfiler *prof = (MonoProfiler *) arg;
+
+       mono_threads_attach_tools_thread ();
+       mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler helper");
+
+       MonoProfilerThread *thread = init_thread (prof, FALSE);
+
+       GArray *command_sockets = g_array_new (FALSE, FALSE, sizeof (int));
+
+       while (1) {
+               fd_set rfds;
+               int max_fd = -1;
+
+               FD_ZERO (&rfds);
+
+               add_to_fd_set (&rfds, prof->server_socket, &max_fd);
+               add_to_fd_set (&rfds, prof->pipes [0], &max_fd);
+
+               for (gint i = 0; i < command_sockets->len; i++)
+                       add_to_fd_set (&rfds, g_array_index (command_sockets, int, i), &max_fd);
+
+               struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
+
+               // Sleep for 1sec or until a file descriptor has data.
+               if (select (max_fd + 1, &rfds, NULL, NULL, &tv) == -1) {
+                       if (errno == EINTR)
+                               continue;
+
+                       fprintf (stderr, "Error in mono-profiler-log server: %s", strerror (errno));
+                       exit (1);
+               }
+
+               if (!no_counters)
+                       counters_and_perfcounters_sample (prof);
+
+               buffer_lock_excl ();
+
+               sync_point (SYNC_POINT_PERIODIC);
+
+               buffer_unlock_excl ();
+
+               // Are we shutting down?
+               if (FD_ISSET (prof->pipes [0], &rfds)) {
+                       char c;
+                       read (prof->pipes [0], &c, 1);
+                       break;
+               }
+
+               for (gint i = 0; i < command_sockets->len; i++) {
+                       int fd = g_array_index (command_sockets, int, i);
+
+                       if (!FD_ISSET (fd, &rfds))
+                               continue;
+
+                       char buf [64];
+                       int len = read (fd, buf, sizeof (buf) - 1);
+
+                       if (len == -1)
+                               continue;
+
+                       if (!len) {
+                               // The other end disconnected.
+                               g_array_remove_index (command_sockets, i);
+                               close (fd);
+
+                               continue;
+                       }
+
+                       buf [len] = 0;
+
+                       if (!strcmp (buf, "heapshot\n") && hs_mode_ondemand) {
+                               // Rely on the finalization callbacks invoking process_requests ().
+                               heapshot_requested = 1;
+                               mono_gc_finalize_notify ();
+                       }
+               }
+
+               if (FD_ISSET (prof->server_socket, &rfds)) {
+                       int fd = accept (prof->server_socket, NULL, NULL);
+
+                       if (fd != -1) {
+                               if (fd >= FD_SETSIZE)
+                                       close (fd);
+                               else
+                                       g_array_append_val (command_sockets, fd);
+                       }
+               }
+       }
+
+       for (gint i = 0; i < command_sockets->len; i++)
+               close (g_array_index (command_sockets, int, i));
+
+       g_array_free (command_sockets, TRUE);
+
+       send_log_unsafe (FALSE);
+       deinit_thread (thread);
+
+       mono_thread_info_detach ();
+
+       return NULL;
+}
+
+static void
+start_helper_thread (MonoProfiler* prof)
+{
+       if (pipe (prof->pipes) == -1) {
+               fprintf (stderr, "Cannot create pipe: %s\n", strerror (errno));
+               exit (1);
+       }
+
+       prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
+
+       if (prof->server_socket == -1) {
+               fprintf (stderr, "Cannot create server socket: %s\n", strerror (errno));
+               exit (1);
+       }
+
+       struct sockaddr_in server_address;
+
+       memset (&server_address, 0, sizeof (server_address));
+       server_address.sin_family = AF_INET;
+       server_address.sin_addr.s_addr = INADDR_ANY;
+       server_address.sin_port = htons (prof->command_port);
+
+       if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) == -1) {
+               fprintf (stderr, "Cannot bind server socket on port %d: %s\n", prof->command_port, strerror (errno));
+               close (prof->server_socket);
+               exit (1);
+       }
+
+       if (listen (prof->server_socket, 1) == -1) {
+               fprintf (stderr, "Cannot listen on server socket: %s\n", strerror (errno));
+               close (prof->server_socket);
+               exit (1);
+       }
+
+       socklen_t slen = sizeof (server_address);
+
+       if (getsockname (prof->server_socket, (struct sockaddr *) &server_address, &slen)) {
+               fprintf (stderr, "Could not get assigned port: %s\n", strerror (errno));
+               close (prof->server_socket);
+               exit (1);
+       }
+
+       prof->command_port = ntohs (server_address.sin_port);
+
+       if (!mono_native_thread_create (&prof->helper_thread, helper_thread, prof)) {
+               fprintf (stderr, "Could not start helper thread\n");
+               close (prof->server_socket);
+               exit (1);
+       }
+}
+
+static void
+free_writer_entry (gpointer p)
+{
+       mono_lock_free_free (p, WRITER_ENTRY_BLOCK_SIZE);
+}
+
+static gboolean
+handle_writer_queue_entry (MonoProfiler *prof)
+{
+       WriterQueueEntry *entry;
+
+       if ((entry = (WriterQueueEntry *) mono_lock_free_queue_dequeue (&prof->writer_queue))) {
+               if (!entry->methods)
+                       goto no_methods;
+
+               gboolean wrote_methods = FALSE;
+
+               /*
+                * Encode the method events in a temporary log buffer that we
+                * flush to disk before the main buffer, ensuring that all
+                * methods have metadata emitted before they're referenced.
+                *
+                * We use a 'proper' thread-local buffer for this as opposed
+                * to allocating and freeing a buffer by hand because the call
+                * to mono_method_full_name () below may trigger class load
+                * events when it retrieves the signature of the method. So a
+                * thread-local buffer needs to exist when such events occur.
+                */
+               for (guint i = 0; i < entry->methods->len; i++) {
+                       MethodInfo *info = (MethodInfo *) g_ptr_array_index (entry->methods, i);
+
+                       if (mono_conc_hashtable_lookup (prof->method_table, info->method))
+                               goto free_info; // This method already has metadata emitted.
+
+                       /*
+                        * Other threads use this hash table to get a general
+                        * idea of whether a method has already been emitted to
+                        * the stream. Due to the way we add to this table, it
+                        * can easily happen that multiple threads queue up the
+                        * same methods, but that's OK since eventually all
+                        * methods will be in this table and the thread-local
+                        * method lists will just be empty for the rest of the
+                        * app's lifetime.
+                        */
+                       mono_os_mutex_lock (&prof->method_table_mutex);
+                       mono_conc_hashtable_insert (prof->method_table, info->method, info->method);
+                       mono_os_mutex_unlock (&prof->method_table_mutex);
+
+                       char *name = mono_method_full_name (info->method, 1);
+                       int nlen = strlen (name) + 1;
+                       void *cstart = info->ji ? mono_jit_info_get_code_start (info->ji) : NULL;
+                       int csize = info->ji ? mono_jit_info_get_code_size (info->ji) : 0;
+
+                       ENTER_LOG (&method_jits_ctr, logbuffer,
+                               EVENT_SIZE /* event */ +
+                               LEB128_SIZE /* method */ +
+                               LEB128_SIZE /* start */ +
+                               LEB128_SIZE /* size */ +
+                               nlen /* name */
+                       );
+
+                       emit_event_time (logbuffer, TYPE_JIT | TYPE_METHOD, info->time);
+                       emit_method_inner (logbuffer, info->method);
+                       emit_ptr (logbuffer, cstart);
+                       emit_value (logbuffer, csize);
+
+                       memcpy (logbuffer->cursor, name, nlen);
+                       logbuffer->cursor += nlen;
+
+                       EXIT_LOG_EXPLICIT (NO_SEND, NO_REQUESTS);
+
+                       mono_free (name);
+
+                       wrote_methods = TRUE;
+
+               free_info:
+                       g_free (info);
+               }
+
+               g_ptr_array_free (entry->methods, TRUE);
+
+               if (wrote_methods) {
+                       dump_buffer_threadless (prof, PROF_TLS_GET ()->buffer);
+                       init_buffer_state (PROF_TLS_GET ());
+               }
+
+       no_methods:
+               dump_buffer (prof, entry->buffer);
+
+               mono_thread_hazardous_try_free (entry, free_writer_entry);
+
+               return TRUE;
+       }
+
+       return FALSE;
+}
+
+static void *
+writer_thread (void *arg)
+{
+       MonoProfiler *prof = (MonoProfiler *)arg;
+
+       mono_threads_attach_tools_thread ();
+       mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler writer");
+
+       dump_header (prof);
+
+       MonoProfilerThread *thread = init_thread (prof, FALSE);
+
+       while (InterlockedRead (&prof->run_writer_thread)) {
+               mono_os_sem_wait (&prof->writer_queue_sem, MONO_SEM_FLAGS_NONE);
+               handle_writer_queue_entry (prof);
+       }
+
+       /* Drain any remaining entries on shutdown. */
+       while (handle_writer_queue_entry (prof));
+
+       free_buffer (thread->buffer, thread->buffer->size);
+       deinit_thread (thread);
+
+       mono_thread_info_detach ();
+
+       return NULL;
+}
+
+static void
+start_writer_thread (MonoProfiler* prof)
+{
+       InterlockedWrite (&prof->run_writer_thread, 1);
+
+       if (!mono_native_thread_create (&prof->writer_thread, writer_thread, prof)) {
+               fprintf (stderr, "Could not start writer thread\n");
+               exit (1);
+       }
+}
+
+static void
+reuse_sample_hit (gpointer p)
+{
+       SampleHit *sample = p;
+
+       mono_lock_free_queue_node_unpoison (&sample->node);
+       mono_lock_free_queue_enqueue (&sample->prof->sample_reuse_queue, &sample->node);
+}
+
+static gboolean
+handle_dumper_queue_entry (MonoProfiler *prof)
+{
+       SampleHit *sample;
+
+       if ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&prof->dumper_queue))) {
+               for (int i = 0; i < sample->count; ++i) {
+                       MonoMethod *method = sample->frames [i].method;
+                       MonoDomain *domain = sample->frames [i].domain;
+                       void *address = sample->frames [i].base_address;
+
+                       if (!method) {
+                               g_assert (domain && "What happened to the domain pointer?");
+                               g_assert (address && "What happened to the instruction pointer?");
+
+                               MonoJitInfo *ji = mono_jit_info_table_find (domain, (char *) address);
+
+                               if (ji)
+                                       sample->frames [i].method = mono_jit_info_get_method (ji);
+                       }
+               }
+
+               ENTER_LOG (&sample_hits_ctr, logbuffer,
+                       EVENT_SIZE /* event */ +
+                       BYTE_SIZE /* type */ +
+                       LEB128_SIZE /* tid */ +
+                       LEB128_SIZE /* count */ +
+                       1 * (
+                               LEB128_SIZE /* ip */
+                       ) +
+                       LEB128_SIZE /* managed count */ +
+                       sample->count * (
+                               LEB128_SIZE /* method */
+                       )
+               );
+
+               emit_event_time (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT, sample->time);
+               emit_byte (logbuffer, SAMPLE_CYCLES);
+               emit_ptr (logbuffer, (void *) sample->tid);
+               emit_value (logbuffer, 1);
+
+               // TODO: Actual native unwinding.
+               for (int i = 0; i < 1; ++i) {
+                       emit_ptr (logbuffer, sample->ip);
+                       add_code_pointer ((uintptr_t) sample->ip);
+               }
+
+               /* new in data version 6 */
+               emit_uvalue (logbuffer, sample->count);
+
+               for (int i = 0; i < sample->count; ++i)
+                       emit_method (logbuffer, sample->frames [i].method);
+
+               EXIT_LOG_EXPLICIT (DO_SEND, NO_REQUESTS);
+
+               mono_thread_hazardous_try_free (sample, reuse_sample_hit);
+
+               dump_unmanaged_coderefs (prof);
+       }
+
+       return FALSE;
+}
+
+static void *
+dumper_thread (void *arg)
+{
+       MonoProfiler *prof = (MonoProfiler *)arg;
+
+       mono_threads_attach_tools_thread ();
+       mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler dumper");
+
+       MonoProfilerThread *thread = init_thread (prof, FALSE);
+
+       while (InterlockedRead (&prof->run_dumper_thread)) {
+               mono_os_sem_wait (&prof->dumper_queue_sem, MONO_SEM_FLAGS_NONE);
+               handle_dumper_queue_entry (prof);
+       }
+
+       /* Drain any remaining entries on shutdown. */
+       while (handle_dumper_queue_entry (prof));
+
+       send_log_unsafe (FALSE);
+       deinit_thread (thread);
+
+       mono_thread_info_detach ();
+
+       return NULL;
+}
+
+static void
+start_dumper_thread (MonoProfiler* prof)
+{
+       InterlockedWrite (&prof->run_dumper_thread, 1);
+
+       if (!mono_native_thread_create (&prof->dumper_thread, dumper_thread, prof)) {
+               fprintf (stderr, "Could not start dumper thread\n");
+               exit (1);
+       }
+}
+
+static void
+register_counter (const char *name, gint32 *counter)
+{
+       mono_counters_register (name, MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, counter);
+}
+
+static void
+runtime_initialized (MonoProfiler *profiler)
+{
+       InterlockedWrite (&runtime_inited, 1);
+
+       register_counter ("Sample events allocated", &sample_allocations_ctr);
+       register_counter ("Log buffers allocated", &buffer_allocations_ctr);
+
+       register_counter ("Event: Sync points", &sync_points_ctr);
+       register_counter ("Event: Heap objects", &heap_objects_ctr);
+       register_counter ("Event: Heap starts", &heap_starts_ctr);
+       register_counter ("Event: Heap ends", &heap_ends_ctr);
+       register_counter ("Event: Heap roots", &heap_roots_ctr);
+       register_counter ("Event: GC events", &gc_events_ctr);
+       register_counter ("Event: GC resizes", &gc_resizes_ctr);
+       register_counter ("Event: GC allocations", &gc_allocs_ctr);
+       register_counter ("Event: GC moves", &gc_moves_ctr);
+       register_counter ("Event: GC handle creations", &gc_handle_creations_ctr);
+       register_counter ("Event: GC handle deletions", &gc_handle_deletions_ctr);
+       register_counter ("Event: GC finalize starts", &finalize_begins_ctr);
+       register_counter ("Event: GC finalize ends", &finalize_ends_ctr);
+       register_counter ("Event: GC finalize object starts", &finalize_object_begins_ctr);
+       register_counter ("Event: GC finalize object ends", &finalize_object_ends_ctr);
+       register_counter ("Event: Image loads", &image_loads_ctr);
+       register_counter ("Event: Image unloads", &image_unloads_ctr);
+       register_counter ("Event: Assembly loads", &assembly_loads_ctr);
+       register_counter ("Event: Assembly unloads", &assembly_unloads_ctr);
+       register_counter ("Event: Class loads", &class_loads_ctr);
+       register_counter ("Event: Class unloads", &class_unloads_ctr);
+       register_counter ("Event: Method entries", &method_entries_ctr);
+       register_counter ("Event: Method exits", &method_exits_ctr);
+       register_counter ("Event: Method exception leaves", &method_exception_exits_ctr);
+       register_counter ("Event: Method JITs", &method_jits_ctr);
+       register_counter ("Event: Code buffers", &code_buffers_ctr);
+       register_counter ("Event: Exception throws", &exception_throws_ctr);
+       register_counter ("Event: Exception clauses", &exception_clauses_ctr);
+       register_counter ("Event: Monitor contentions", &monitor_contentions_ctr);
+       register_counter ("Event: Monitor acquisitions", &monitor_acquisitions_ctr);
+       register_counter ("Event: Monitor failures", &monitor_failures_ctr);
+       register_counter ("Event: Thread starts", &thread_starts_ctr);
+       register_counter ("Event: Thread ends", &thread_ends_ctr);
+       register_counter ("Event: Thread names", &thread_names_ctr);
+       register_counter ("Event: Domain loads", &domain_loads_ctr);
+       register_counter ("Event: Domain unloads", &domain_unloads_ctr);
+       register_counter ("Event: Domain names", &domain_names_ctr);
+       register_counter ("Event: Context loads", &context_loads_ctr);
+       register_counter ("Event: Context unloads", &context_unloads_ctr);
+       register_counter ("Event: Sample binaries", &sample_ubins_ctr);
+       register_counter ("Event: Sample symbols", &sample_usyms_ctr);
+       register_counter ("Event: Sample hits", &sample_hits_ctr);
+       register_counter ("Event: Counter descriptors", &counter_descriptors_ctr);
+       register_counter ("Event: Counter samples", &counter_samples_ctr);
+       register_counter ("Event: Performance counter descriptors", &perfcounter_descriptors_ctr);
+       register_counter ("Event: Performance counter samples", &perfcounter_samples_ctr);
+       register_counter ("Event: Coverage methods", &coverage_methods_ctr);
+       register_counter ("Event: Coverage statements", &coverage_statements_ctr);
+       register_counter ("Event: Coverage classes", &coverage_classes_ctr);
+       register_counter ("Event: Coverage assemblies", &coverage_assemblies_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*
+create_profiler (const char *args, const char *filename, GPtrArray *filters)
+{
+       MonoProfiler *prof;
+       char *nf;
+       int force_delete = 0;
+       prof = (MonoProfiler *) g_calloc (1, sizeof (MonoProfiler));
+
+       prof->args = pstrdup (args);
+       prof->command_port = command_port;
+       if (filename && *filename == '-') {
+               force_delete = 1;
+               filename++;
+       }
+       if (!filename) {
+               if (do_report)
+                       filename = "|mprof-report -";
+               else
+                       filename = "output.mlpd";
+               nf = (char*)filename;
+       } else {
+               nf = new_filename (filename);
+               if (do_report) {
+                       int s = strlen (nf) + 32;
+                       char *p = (char *) g_malloc (s);
+                       snprintf (p, s, "|mprof-report '--out=%s' -", nf);
+                       g_free (nf);
+                       nf = p;
+               }
+       }
+       if (*nf == '|') {
+               prof->file = popen (nf + 1, "w");
+               prof->pipe_output = 1;
+       } else if (*nf == '#') {
+               int fd = strtol (nf + 1, NULL, 10);
+               prof->file = fdopen (fd, "a");
+       } else {
+               if (force_delete)
+                       unlink (nf);
+               prof->file = fopen (nf, "wb");
+       }
+       if (!prof->file) {
+               fprintf (stderr, "Cannot create profiler output: %s\n", nf);
+               exit (1);
+       }
+
+#if defined (HAVE_SYS_ZLIB)
+       if (use_zip)
+               prof->gzfile = gzdopen (fileno (prof->file), "wb");
+#endif
+
+       /*
+        * If you hit this assert while increasing MAX_FRAMES, you need to increase
+        * SAMPLE_BLOCK_SIZE as well.
+        */
+       g_assert (SAMPLE_SLOT_SIZE (MAX_FRAMES) * 2 < LOCK_FREE_ALLOC_SB_USABLE_SIZE (SAMPLE_BLOCK_SIZE));
+
+       // FIXME: We should free this stuff too.
+       mono_lock_free_allocator_init_size_class (&prof->sample_size_class, SAMPLE_SLOT_SIZE (num_frames), SAMPLE_BLOCK_SIZE);
+       mono_lock_free_allocator_init_allocator (&prof->sample_allocator, &prof->sample_size_class, MONO_MEM_ACCOUNT_PROFILER);
+
+       mono_lock_free_queue_init (&prof->sample_reuse_queue);
+
+       g_assert (sizeof (WriterQueueEntry) * 2 < LOCK_FREE_ALLOC_SB_USABLE_SIZE (WRITER_ENTRY_BLOCK_SIZE));
+
+       // FIXME: We should free this stuff too.
+       mono_lock_free_allocator_init_size_class (&prof->writer_entry_size_class, sizeof (WriterQueueEntry), WRITER_ENTRY_BLOCK_SIZE);
+       mono_lock_free_allocator_init_allocator (&prof->writer_entry_allocator, &prof->writer_entry_size_class, MONO_MEM_ACCOUNT_PROFILER);
+
+       mono_lock_free_queue_init (&prof->writer_queue);
+       mono_os_sem_init (&prof->writer_queue_sem, 0);
+
+       mono_lock_free_queue_init (&prof->dumper_queue);
+       mono_os_sem_init (&prof->dumper_queue_sem, 0);
+
+       mono_os_mutex_init (&prof->method_table_mutex);
+       prof->method_table = mono_conc_hashtable_new (NULL, NULL);
+
+       if (do_coverage)
+               coverage_init (prof);
+       prof->coverage_filters = filters;
+
+       prof->startup_time = current_time ();
+       return prof;
+}
+
+static void
+usage (int do_exit)
+{
+       printf ("Log profiler version %d.%d (format: %d)\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR, LOG_DATA_VERSION);
+       printf ("Usage: mono --profile=log[:OPTION1[,OPTION2...]] program.exe\n");
+       printf ("Options:\n");
+       printf ("\thelp                 show this usage info\n");
+       printf ("\t[no]alloc            enable/disable recording allocation info\n");
+       printf ("\t[no]calls            enable/disable recording enter/leave method events\n");
+       printf ("\theapshot[=MODE]      record heap shot info (by default at each major collection)\n");
+       printf ("\t                     MODE: every XXms milliseconds, every YYgc collections, ondemand\n");
+       printf ("\tcounters             sample counters every 1s\n");
+       printf ("\tsample[=TYPE]        use statistical sampling mode (by default cycles/100)\n");
+       printf ("\t                     TYPE: cycles,instr,cacherefs,cachemiss,branches,branchmiss\n");
+       printf ("\t                     TYPE can be followed by /FREQUENCY\n");
+       printf ("\tmaxframes=NUM        collect up to NUM stack frames\n");
+       printf ("\tcalldepth=NUM        ignore method events for call chain depth bigger than NUM\n");
+       printf ("\toutput=FILENAME      write the data to file FILENAME (-FILENAME to overwrite)\n");
+       printf ("\toutput=|PROGRAM      write the data to the stdin of PROGRAM\n");
+       printf ("\t                     %%t is subtituted with date and time, %%p with the pid\n");
+       printf ("\treport               create a report instead of writing the raw data to a file\n");
+       printf ("\tzip                  compress the output data\n");
+       printf ("\tport=PORTNUM         use PORTNUM for the listening command server\n");
+       printf ("\tcoverage             enable collection of code coverage data\n");
+       printf ("\tcovfilter=ASSEMBLY   add an assembly to the code coverage filters\n");
+       printf ("\t                     add a + to include the assembly or a - to exclude it\n");
+       printf ("\t                     filter=-mscorlib\n");
+       printf ("\tcovfilter-file=FILE  use FILE to generate the list of assemblies to be filtered\n");
+       if (do_exit)
+               exit (1);
+}
+
+static const char*
+match_option (const char* p, const char *opt, char **rval)
+{
+       int len = strlen (opt);
+       if (strncmp (p, opt, len) == 0) {
+               if (rval) {
+                       if (p [len] == '=' && p [len + 1]) {
+                               const char *opt = p + len + 1;
+                               const char *end = strchr (opt, ',');
+                               char *val;
+                               int l;
+                               if (end == NULL) {
+                                       l = strlen (opt);
+                               } else {
+                                       l = end - opt;
+                               }
+                               val = (char *) g_malloc (l + 1);
+                               memcpy (val, opt, l);
+                               val [l] = 0;
+                               *rval = val;
+                               return opt + l;
+                       }
+                       if (p [len] == 0 || p [len] == ',') {
+                               *rval = NULL;
+                               return p + len + (p [len] == ',');
+                       }
+                       usage (1);
+               } else {
+                       if (p [len] == 0)
+                               return p + len;
+                       if (p [len] == ',')
+                               return p + len + 1;
+               }
+       }
+       return p;
+}
+
+static void
+set_sample_freq (char *val)
+{
+       do_mono_sample = 1;
+       sample_freq = 100;
+
+       if (!val)
+               return;
+
+       char *p = val;
+
+       // Is it only the frequency (new option style)?
+       if (isdigit (*p))
+               goto parse;
+
+       // Skip the sample type for backwards compatibility.
+       while (isalpha (*p))
+               p++;
+
+       // Skip the forward slash only if we got a sample type.
+       if (p != val && *p == '/') {
+               p++;
+
+               char *end;
+
+       parse:
+               sample_freq = strtoul (p, &end, 10);
+
+               if (p == end)
+                       usage (1);
+
+               p = end;
+       }
+
+       if (*p)
+               usage (1);
+
+       g_free (val);
+}
+
+static void
+set_hsmode (char* val, int allow_empty)
+{
+       char *end;
+       unsigned int count;
+       if (allow_empty && !val)
+               return;
+       if (strcmp (val, "ondemand") == 0) {
+               hs_mode_ondemand = 1;
+               g_free (val);
+               return;
+       }
+       count = strtoul (val, &end, 10);
+       if (val == end)
+               usage (1);
+       if (strcmp (end, "ms") == 0)
+               hs_mode_ms = count;
+       else if (strcmp (end, "gc") == 0)
+               hs_mode_gc = count;
+       else
+               usage (1);
+       g_free (val);
+}
+
+/*
+ * declaration to silence the compiler: this is the entry point that
+ * mono will load from the shared library and call.
+ */
+extern void
+mono_profiler_startup (const char *desc);
+
+extern void
+mono_profiler_startup_log (const char *desc);
+
+/*
+ * this is the entry point that will be used when the profiler
+ * is embedded inside the main executable.
+ */
+void
+mono_profiler_startup_log (const char *desc)
+{
+       mono_profiler_startup (desc);
+}
+
+void
+mono_profiler_startup (const char *desc)
+{
+       MonoProfiler *prof;
+       GPtrArray *filters = NULL;
+       char *filename = NULL;
+       const char *p;
+       const char *opt;
+       int calls_enabled = 0;
+       int allocs_enabled = 0;
+       int events = MONO_PROFILE_GC|MONO_PROFILE_ALLOCATIONS|
+               MONO_PROFILE_GC_MOVES|MONO_PROFILE_CLASS_EVENTS|MONO_PROFILE_THREADS|
+               MONO_PROFILE_ENTER_LEAVE|MONO_PROFILE_JIT_COMPILATION|MONO_PROFILE_EXCEPTIONS|
+               MONO_PROFILE_MONITOR_EVENTS|MONO_PROFILE_MODULE_EVENTS|MONO_PROFILE_GC_ROOTS|
+               MONO_PROFILE_INS_COVERAGE|MONO_PROFILE_APPDOMAIN_EVENTS|MONO_PROFILE_CONTEXT_EVENTS|
+               MONO_PROFILE_ASSEMBLY_EVENTS|MONO_PROFILE_GC_FINALIZATION;
+
+       max_allocated_sample_hits = mono_cpu_count () * 1000;
+
+       p = desc;
+       if (strncmp (p, "log", 3))
+               usage (1);
+       p += 3;
+       if (*p == ':')
+               p++;
+       for (; *p; p = opt) {
+               char *val;
+               if (*p == ',') {
+                       opt = p + 1;
+                       continue;
+               }
+               if ((opt = match_option (p, "help", NULL)) != p) {
+                       usage (0);
+                       continue;
+               }
+               if ((opt = match_option (p, "calls", NULL)) != p) {
+                       calls_enabled = 1;
+                       continue;
+               }
+               if ((opt = match_option (p, "nocalls", NULL)) != p) {
+                       events &= ~MONO_PROFILE_ENTER_LEAVE;
+                       nocalls = 1;
+                       continue;
+               }
+               if ((opt = match_option (p, "alloc", NULL)) != p) {
+                       allocs_enabled = 1;
+                       continue;
+               }
+               if ((opt = match_option (p, "noalloc", NULL)) != p) {
+                       events &= ~MONO_PROFILE_ALLOCATIONS;
+                       events &= ~MONO_PROFILE_GC_MOVES;
+                       continue;
+               }
+               if ((opt = match_option (p, "nocounters", NULL)) != p) {
+                       no_counters = TRUE;
+                       continue;
+               }
+               if ((opt = match_option (p, "time", &val)) != p) {
+                       // For backwards compatibility.
+                       if (strcmp (val, "fast") && strcmp (val, "null"))
+                               usage (1);
+                       g_free (val);
+                       continue;
+               }
+               if ((opt = match_option (p, "report", NULL)) != p) {
+                       do_report = 1;
+                       continue;
+               }
+               if ((opt = match_option (p, "debug", NULL)) != p) {
+                       do_debug = 1;
+                       continue;
+               }
+               if ((opt = match_option (p, "sampling-real", NULL)) != p) {
+                       sampling_mode = MONO_PROFILER_STAT_MODE_REAL;
+                       continue;
+               }
+               if ((opt = match_option (p, "sampling-process", NULL)) != p) {
+                       sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
+                       continue;
+               }
+               if ((opt = match_option (p, "heapshot", &val)) != p) {
+                       events &= ~MONO_PROFILE_ALLOCATIONS;
+                       events &= ~MONO_PROFILE_GC_MOVES;
+                       events &= ~MONO_PROFILE_ENTER_LEAVE;
+                       nocalls = 1;
+                       do_heap_shot = 1;
+                       set_hsmode (val, 1);
+                       continue;
+               }
+               if ((opt = match_option (p, "sample", &val)) != p) {
+                       events &= ~MONO_PROFILE_ALLOCATIONS;
+                       events &= ~MONO_PROFILE_GC_MOVES;
+                       events &= ~MONO_PROFILE_ENTER_LEAVE;
+                       nocalls = 1;
+                       set_sample_freq (val);
+                       continue;
+               }
+               if ((opt = match_option (p, "zip", NULL)) != p) {
+                       use_zip = 1;
+                       continue;
+               }
+               if ((opt = match_option (p, "output", &val)) != p) {
+                       filename = val;
+                       continue;
+               }
+               if ((opt = match_option (p, "port", &val)) != p) {
+                       char *end;
+                       command_port = strtoul (val, &end, 10);
+                       g_free (val);
+                       continue;
+               }
+               if ((opt = match_option (p, "maxframes", &val)) != p) {
+                       char *end;
+                       num_frames = strtoul (val, &end, 10);
+                       if (num_frames > MAX_FRAMES)
+                               num_frames = MAX_FRAMES;
+                       g_free (val);
+                       notraces = num_frames == 0;
+                       continue;
+               }
+               if ((opt = match_option (p, "maxsamples", &val)) != p) {
+                       char *end;
+                       max_allocated_sample_hits = strtoul (val, &end, 10);
+                       if (!max_allocated_sample_hits)
+                               max_allocated_sample_hits = G_MAXINT32;
+                       g_free (val);
+                       continue;
+               }
+               if ((opt = match_option (p, "calldepth", &val)) != p) {
+                       char *end;
+                       max_call_depth = strtoul (val, &end, 10);
+                       g_free (val);
+                       continue;
+               }
+               if ((opt = match_option (p, "counters", NULL)) != p) {
+                       // For backwards compatibility.
+                       continue;
+               }
+               if ((opt = match_option (p, "coverage", NULL)) != p) {
+                       do_coverage = 1;
+                       events |= MONO_PROFILE_ENTER_LEAVE;
+                       debug_coverage = (g_getenv ("MONO_PROFILER_DEBUG_COVERAGE") != NULL);
+                       continue;
+               }
+               if ((opt = match_option (p, "onlycoverage", NULL)) != p) {
+                       only_coverage = TRUE;
+                       continue;
+               }
+               if ((opt = match_option (p, "covfilter-file", &val)) != p) {
+                       FILE *filter_file;
+                       char *line, *content;
+
+                       if (filters == NULL)
+                               filters = g_ptr_array_new ();
+
+                       filter_file = fopen (val, "r");
+                       if (filter_file == NULL) {
+                               fprintf (stderr, "Unable to open %s\n", val);
+                               exit (0);
+                       }
+
+                       /* Don't need to free content as it is referred to by the lines stored in @filters */
+                       content = get_file_content (filter_file);
+                       if (content == NULL)
+                               fprintf (stderr, "WARNING: %s is greater than 128kb - ignoring\n", val);
+
+                       while ((line = get_next_line (content, &content)))
+                               g_ptr_array_add (filters, g_strchug (g_strchomp (line)));
+
+                       fclose (filter_file);
+                       continue;
+               }
+               if ((opt = match_option (p, "covfilter", &val)) != p) {
+                       if (filters == NULL)
+                               filters = g_ptr_array_new ();
+
+                       g_ptr_array_add (filters, val);
+                       continue;
+               }
+               if (opt == p) {
+                       usage (0);
+                       exit (0);
+               }
+       }
+
+       if (calls_enabled) {
+               events |= MONO_PROFILE_ENTER_LEAVE;
+               nocalls = 0;
+       }
+
+       if (allocs_enabled) {
+               events |= MONO_PROFILE_ALLOCATIONS;
+               events |= MONO_PROFILE_GC_MOVES;
+       }
+
+       // Only activate the bare minimum events the profiler needs to function.
+       if (only_coverage) {
+               if (!do_coverage) {
+                       fprintf (stderr, "The onlycoverage option is only valid when paired with the coverage option\n");
+                       exit (1);
+               }
+
+               no_counters = TRUE;
+               events = MONO_PROFILE_GC | MONO_PROFILE_THREADS | MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_INS_COVERAGE;
+       }
+
+       init_time ();
+
+       PROF_TLS_INIT ();
+
+       prof = create_profiler (desc, filename, filters);
+       if (!prof) {
+               PROF_TLS_FREE ();
+               return;
+       }
+
+       mono_lls_init (&profiler_thread_list, NULL);
+
+       init_thread (prof, TRUE);
+
+       mono_profiler_install (prof, log_shutdown);
+       mono_profiler_install_gc (gc_event, gc_resize);
+       mono_profiler_install_allocation (gc_alloc);
+       mono_profiler_install_gc_moves (gc_moves);
+       mono_profiler_install_gc_roots (gc_handle, gc_roots);
+       mono_profiler_install_gc_finalize (finalize_begin, finalize_object_begin, finalize_object_end, finalize_end);
+       mono_profiler_install_appdomain (NULL, domain_loaded, domain_unloaded, NULL);
+       mono_profiler_install_appdomain_name (domain_name);
+       mono_profiler_install_context (context_loaded, context_unloaded);
+       mono_profiler_install_class (NULL, class_loaded, class_unloaded, NULL);
+       mono_profiler_install_module (NULL, image_loaded, image_unloaded, NULL);
+       mono_profiler_install_assembly (NULL, assembly_loaded, assembly_unloaded, NULL);
+       mono_profiler_install_thread (thread_start, thread_end);
+       mono_profiler_install_thread_name (thread_name);
+       mono_profiler_install_enter_leave (method_enter, method_leave);
+       mono_profiler_install_jit_end (method_jitted);
+       mono_profiler_install_code_buffer_new (code_buffer_new);
+       mono_profiler_install_exception (throw_exc, method_exc_leave, clause_exc);
+       mono_profiler_install_monitor (monitor_event);
+       mono_profiler_install_runtime_initialized (runtime_initialized);
+       if (do_coverage)
+               mono_profiler_install_coverage_filter (coverage_filter);
+
+       if (do_mono_sample && sample_freq) {
+               events |= MONO_PROFILE_STATISTICAL;
+               mono_profiler_set_statistical_mode (sampling_mode, sample_freq);
+               mono_profiler_install_statistical (mono_sample_hit);
+       }
+
+       mono_profiler_set_events ((MonoProfileFlags)events);
+}
diff --git a/mono/profiler/mono-profiler-log.h b/mono/profiler/mono-profiler-log.h
new file mode 100644 (file)
index 0000000..99b5782
--- /dev/null
@@ -0,0 +1,156 @@
+#ifndef __MONO_PROFLOG_H__
+#define __MONO_PROFLOG_H__
+
+#define BUF_ID 0x4D504C01
+#define LOG_HEADER_ID 0x4D505A01
+#define LOG_VERSION_MAJOR 1
+#define LOG_VERSION_MINOR 1
+#define LOG_DATA_VERSION 13
+
+/*
+ * Changes in major/minor versions:
+ * version 1.0: removed sysid field from header
+ *              added args, arch, os fields to header
+ *
+ * Changes in data versions:
+ * version 2: added offsets in heap walk
+ * version 3: added GC roots
+ * version 4: added sample/statistical profiling
+ * version 5: added counters sampling
+ * version 6: added optional backtrace in sampling info
+ * version 8: added TYPE_RUNTIME and JIT helpers/trampolines
+ * version 9: added MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING
+ * version 10: added TYPE_COVERAGE
+ * version 11: added thread ID to TYPE_SAMPLE_HIT
+               added more load/unload events
+                   unload for class
+                   unload for image
+                   load/unload for appdomain
+                   load/unload for contexts
+                   load/unload/name for assemblies
+               removed TYPE_LOAD_ERR flag (profiler never generated it, now removed from the format itself)
+               added TYPE_GC_HANDLE_{CREATED,DESTROYED}_BT
+               TYPE_JIT events are no longer guaranteed to have code start/size info (can be zero)
+ * version 12: added MONO_COUNTER_PROFILER
+ * version 13: added MONO_GC_EVENT_{PRE_STOP_WORLD_LOCKED,POST_START_WORLD_UNLOCKED}
+               added TYPE_META + TYPE_SYNC_POINT
+               removed il and native offset in TYPE_SAMPLE_HIT
+               methods in backtraces are now encoded as proper method pointers
+               removed flags in backtrace format
+               removed flags in metadata events
+               changed the following fields to a single byte rather than leb128
+                   TYPE_GC_EVENT: event_type, generation
+                   TYPE_HEAP_ROOT: root_type
+                   TYPE_JITHELPER: type
+                   TYPE_SAMPLE_HIT: sample_type
+                   TYPE_CLAUSE: clause_type
+                   TYPE_SAMPLE_COUNTERS_DESC: type, unit, variance
+                   TYPE_SAMPLE_COUNTERS: type
+               added time fields to all events that were missing one
+                   TYPE_HEAP_OBJECT
+                   TYPE_HEAP_ROOT
+                   TYPE_SAMPLE_USYM
+                   TYPE_SAMPLE_COUNTERS_DESC
+                   TYPE_COVERAGE_METHOD
+                   TYPE_COVERAGE_STATEMENT
+                   TYPE_COVERAGE_CLASS
+                   TYPE_COVERAGE_ASSEMBLY
+               moved the time field in TYPE_SAMPLE_HIT to right after the event byte, now encoded as a regular time field
+               changed the time field in TYPE_SAMPLE_COUNTERS to be encoded as a regular time field (in nanoseconds)
+               added TYPE_GC_FINALIZE_{START,END,OBJECT_START,OBJECT_END}
+ */
+
+enum {
+       TYPE_ALLOC,
+       TYPE_GC,
+       TYPE_METADATA,
+       TYPE_METHOD,
+       TYPE_EXCEPTION,
+       TYPE_MONITOR,
+       TYPE_HEAP,
+       TYPE_SAMPLE,
+       TYPE_RUNTIME,
+       TYPE_COVERAGE,
+       TYPE_META,
+       /* extended type for TYPE_HEAP */
+       TYPE_HEAP_START  = 0 << 4,
+       TYPE_HEAP_END    = 1 << 4,
+       TYPE_HEAP_OBJECT = 2 << 4,
+       TYPE_HEAP_ROOT   = 3 << 4,
+       /* extended type for TYPE_METADATA */
+       TYPE_END_LOAD     = 2 << 4,
+       TYPE_END_UNLOAD   = 4 << 4,
+       /* extended type for TYPE_GC */
+       TYPE_GC_EVENT  = 1 << 4,
+       TYPE_GC_RESIZE = 2 << 4,
+       TYPE_GC_MOVE   = 3 << 4,
+       TYPE_GC_HANDLE_CREATED      = 4 << 4,
+       TYPE_GC_HANDLE_DESTROYED    = 5 << 4,
+       TYPE_GC_HANDLE_CREATED_BT   = 6 << 4,
+       TYPE_GC_HANDLE_DESTROYED_BT = 7 << 4,
+       TYPE_GC_FINALIZE_START = 8 << 4,
+       TYPE_GC_FINALIZE_END = 9 << 4,
+       TYPE_GC_FINALIZE_OBJECT_START = 10 << 4,
+       TYPE_GC_FINALIZE_OBJECT_END = 11 << 4,
+       /* extended type for TYPE_METHOD */
+       TYPE_LEAVE     = 1 << 4,
+       TYPE_ENTER     = 2 << 4,
+       TYPE_EXC_LEAVE = 3 << 4,
+       TYPE_JIT       = 4 << 4,
+       /* extended type for TYPE_EXCEPTION */
+       TYPE_THROW_NO_BT = 0 << 7,
+       TYPE_THROW_BT    = 1 << 7,
+       TYPE_CLAUSE      = 1 << 4,
+       /* extended type for TYPE_ALLOC */
+       TYPE_ALLOC_NO_BT  = 0 << 4,
+       TYPE_ALLOC_BT     = 1 << 4,
+       /* extended type for TYPE_MONITOR */
+       TYPE_MONITOR_NO_BT  = 0 << 7,
+       TYPE_MONITOR_BT     = 1 << 7,
+       /* extended type for TYPE_SAMPLE */
+       TYPE_SAMPLE_HIT           = 0 << 4,
+       TYPE_SAMPLE_USYM          = 1 << 4,
+       TYPE_SAMPLE_UBIN          = 2 << 4,
+       TYPE_SAMPLE_COUNTERS_DESC = 3 << 4,
+       TYPE_SAMPLE_COUNTERS      = 4 << 4,
+       /* extended type for TYPE_RUNTIME */
+       TYPE_JITHELPER = 1 << 4,
+       /* extended type for TYPE_COVERAGE */
+       TYPE_COVERAGE_ASSEMBLY = 0 << 4,
+       TYPE_COVERAGE_METHOD   = 1 << 4,
+       TYPE_COVERAGE_STATEMENT = 2 << 4,
+       TYPE_COVERAGE_CLASS = 3 << 4,
+       /* extended type for TYPE_META */
+       TYPE_SYNC_POINT = 0 << 4,
+       TYPE_END
+};
+
+enum {
+       /* metadata type byte for TYPE_METADATA */
+       TYPE_CLASS    = 1,
+       TYPE_IMAGE    = 2,
+       TYPE_ASSEMBLY = 3,
+       TYPE_DOMAIN   = 4,
+       TYPE_THREAD   = 5,
+       TYPE_CONTEXT  = 6,
+};
+
+typedef enum {
+       SYNC_POINT_PERIODIC,
+       SYNC_POINT_WORLD_STOP,
+       SYNC_POINT_WORLD_START
+} MonoProfilerSyncPointType;
+
+// Sampling sources
+// Unless you have compiled with --enable-perf-events, only SAMPLE_CYCLES is available
+enum {
+       SAMPLE_CYCLES = 1,
+       SAMPLE_INSTRUCTIONS,
+       SAMPLE_CACHE_MISSES,
+       SAMPLE_CACHE_REFS,
+       SAMPLE_BRANCHES,
+       SAMPLE_BRANCH_MISSES,
+       SAMPLE_LAST
+};
+
+#endif /* __MONO_PROFLOG_H__ */
diff --git a/mono/profiler/mprof-report.c b/mono/profiler/mprof-report.c
new file mode 100644 (file)
index 0000000..1017d1f
--- /dev/null
@@ -0,0 +1,4306 @@
+/*
+ * mprof-report.c: mprof-report program source: decode and analyze the log profiler data
+ *
+ * Authors:
+ *   Paolo Molaro (lupus@ximian.com)
+ *   Alex Rønne Petersen (alexrp@xamarin.com)
+ *
+ * Copyright 2010 Novell, Inc (http://www.novell.com)
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+
+/*
+ * The Coverage XML output schema
+ * <coverage>
+ *   <assembly/>
+ *   <class/>
+ *   <method>
+ *     <statement/>
+ *   </method>
+ * </coverage>
+ *
+ * Elements:
+ *   <coverage> - The root element of the documentation. It can contain any number of
+ *                <assembly>, <class> or <method> elements.
+ *                Attributes:
+ *                   - version: The version number for the file format - (eg: "0.3")
+ *   <assembly> - Contains data about assemblies. Has no child elements
+ *                Attributes:
+ *                   - name: The name of the assembly - (eg: "System.Xml")
+ *                   - guid: The GUID of the assembly
+ *                   - filename: The filename of the assembly
+ *                   - method-count: The number of methods in the assembly
+ *                   - full: The number of fully covered methods
+ *                   - partial: The number of partially covered methods
+ *   <class> - Contains data about classes. Has no child elements
+ *             Attributes:
+ *                - name: The name of the class
+ *                - method-count: The number of methods in the class
+ *                - full: The number of fully covered methods
+ *                - partial: The number of partially covered methods
+ *   <method> - Contains data about methods. Can contain any number of <statement> elements
+ *              Attributes:
+ *                 - assembly: The name of the parent assembly
+ *                 - class: The name of the parent class
+ *                 - name: The name of the method, with all it's parameters
+ *                 - filename: The name of the source file containing this method
+ *                 - token
+ *   <statement> - Contains data about IL statements. Has no child elements
+ *                 Attributes:
+ *                    - offset: The offset of the statement in the IL code after the previous
+ *                              statement's offset
+ *                    - counter: 1 if the line was covered, 0 if it was not
+ *                    - line: The line number in the parent method's file
+ *                    - column: The column on the line
+ */
+#include <config.h>
+#include "mono-profiler-log.h"
+#include <string.h>
+#include <assert.h>
+#include <stdio.h>
+#include <time.h>
+#if !defined(__APPLE__) && !defined(__FreeBSD__)
+#include <malloc.h>
+#endif
+#include <unistd.h>
+#include <stdlib.h>
+#if defined (HAVE_SYS_ZLIB)
+#include <zlib.h>
+#endif
+#include <glib.h>
+#include <mono/metadata/profiler.h>
+#include <mono/metadata/object.h>
+#include <mono/metadata/debug-helpers.h>
+#include <mono/utils/mono-counters.h>
+
+#define HASH_SIZE 9371
+#define SMALL_HASH_SIZE 31
+
+#if defined(__native_client__) || defined(__native_client_codegen__)
+volatile int __nacl_thread_suspension_needed = 0;
+void __nacl_suspend_thread_if_needed() {}
+#endif
+
+static int debug = 0;
+static int collect_traces = 0;
+static int show_traces = 0;
+static int trace_max = 6;
+static int verbose = 0;
+static uintptr_t *tracked_objects = 0;
+static int num_tracked_objects = 0;
+static uintptr_t thread_filter = 0;
+static uint64_t find_size = 0;
+static const char* find_name = NULL;
+static uint64_t time_from = 0;
+static uint64_t time_to = 0xffffffffffffffffULL;
+static int use_time_filter = 0;
+static uint64_t startup_time = 0;
+static FILE* outfile = NULL;
+static FILE* coverage_outfile = NULL;
+
+static int32_t
+read_int16 (unsigned char *p)
+{
+       int32_t value = *p++;
+       value |= (*p++) << 8;
+       return value;
+}
+
+static int32_t
+read_int32 (unsigned char *p)
+{
+       int32_t value = *p++;
+       value |= (*p++) << 8;
+       value |= (*p++) << 16;
+       value |= (uint32_t)(*p++) << 24;
+       return value;
+}
+
+static int64_t
+read_int64 (unsigned char *p)
+{
+       uint64_t value = *p++;
+       value |= (*p++) << 8;
+       value |= (*p++) << 16;
+       value |= (uint64_t)(*p++) << 24;
+       value |= (uint64_t)(*p++) << 32;
+       value |= (uint64_t)(*p++) << 40;
+       value |= (uint64_t)(*p++) << 48;
+       value |= (uint64_t)(*p++) << 54;
+       return value;
+}
+
+static char*
+pstrdup (const char *s)
+{
+       int len = strlen (s) + 1;
+       char *p = (char *) g_malloc (len);
+       memcpy (p, s, len);
+       return p;
+}
+
+typedef struct _CounterValue CounterValue;
+struct _CounterValue {
+       uint64_t timestamp;
+       unsigned char *buffer;
+       CounterValue *next;
+};
+
+typedef struct _Counter Counter;
+struct _Counter {
+       int index;
+       const char *section;
+       const char *name;
+       int type;
+       int unit;
+       int variance;
+       CounterValue *values;
+       CounterValue *values_last;
+};
+
+typedef struct _CounterList CounterList;
+struct _CounterList {
+       Counter *counter;
+       CounterList *next;
+};
+
+typedef struct _CounterSection CounterSection;
+struct _CounterSection {
+       const char *value;
+       CounterList *counters;
+       CounterList *counters_last;
+       CounterSection *next;
+};
+
+typedef struct _CounterTimestamp CounterTimestamp;
+struct _CounterTimestamp {
+       uint64_t value;
+       CounterSection *sections;
+       CounterSection *sections_last;
+       CounterTimestamp *next;
+};
+
+static CounterList *counters = NULL;
+static CounterSection *counters_sections = NULL;
+static CounterTimestamp *counters_timestamps = NULL;
+
+enum {
+       COUNTERS_SORT_TIME,
+       COUNTERS_SORT_CATEGORY
+};
+
+static int counters_sort_mode = COUNTERS_SORT_TIME;
+
+static void
+add_counter_to_section (Counter *counter)
+{
+       CounterSection *csection, *s;
+       CounterList *clist;
+
+       clist = (CounterList *) g_calloc (1, sizeof (CounterList));
+       clist->counter = counter;
+
+       for (csection = counters_sections; csection; csection = csection->next) {
+               if (strcmp (csection->value, counter->section) == 0) {
+                       /* If section exist */
+                       if (!csection->counters)
+                               csection->counters = clist;
+                       else
+                               csection->counters_last->next = clist;
+                       csection->counters_last = clist;
+                       return;
+               }
+       }
+
+       /* If section does not exist */
+       csection = (CounterSection *) g_calloc (1, sizeof (CounterSection));
+       csection->value = counter->section;
+       csection->counters = clist;
+       csection->counters_last = clist;
+
+       if (!counters_sections) {
+               counters_sections = csection;
+       } else {
+               s = counters_sections;
+               while (s->next)
+                       s = s->next;
+               s->next = csection;
+       }
+}
+
+static void
+add_counter (const char *section, const char *name, int type, int unit, int variance, int index)
+{
+       CounterList *list, *l;
+       Counter *counter;
+
+       for (list = counters; list; list = list->next)
+               if (list->counter->index == index)
+                       return;
+
+       counter = (Counter *) g_calloc (1, sizeof (Counter));
+       counter->section = section;
+       counter->name = name;
+       counter->type = type;
+       counter->unit = unit;
+       counter->variance = variance;
+       counter->index = index;
+
+       list = (CounterList *) g_calloc (1, sizeof (CounterList));
+       list->counter = counter;
+
+       if (!counters) {
+               counters = list;
+       } else {
+               l = counters;
+               while (l->next)
+                       l = l->next;
+               l->next = list;
+       }
+
+       if (counters_sort_mode == COUNTERS_SORT_CATEGORY || !verbose)
+               add_counter_to_section (counter);
+}
+
+static void
+add_counter_to_timestamp (uint64_t timestamp, Counter *counter)
+{
+       CounterTimestamp *ctimestamp, *t;
+       CounterSection *csection;
+       CounterList *clist;
+
+       clist = (CounterList *) g_calloc (1, sizeof (CounterList));
+       clist->counter = counter;
+
+       for (ctimestamp = counters_timestamps; ctimestamp; ctimestamp = ctimestamp->next) {
+               if (ctimestamp->value == timestamp) {
+                       for (csection = ctimestamp->sections; csection; csection = csection->next) {
+                               if (strcmp (csection->value, counter->section) == 0) {
+                                       /* if timestamp exist and section exist */
+                                       if (!csection->counters)
+                                               csection->counters = clist;
+                                       else
+                                               csection->counters_last->next = clist;
+                                       csection->counters_last = clist;
+                                       return;
+                               }
+                       }
+
+                       /* if timestamp exist and section does not exist */
+                       csection = (CounterSection *) g_calloc (1, sizeof (CounterSection));
+                       csection->value = counter->section;
+                       csection->counters = clist;
+                       csection->counters_last = clist;
+
+                       if (!ctimestamp->sections)
+                               ctimestamp->sections = csection;
+                       else
+                               ctimestamp->sections_last->next = csection;
+                       ctimestamp->sections_last = csection;
+                       return;
+               }
+       }
+
+       /* If timestamp do not exist and section does not exist */
+       csection = (CounterSection *) g_calloc (1, sizeof (CounterSection));
+       csection->value = counter->section;
+       csection->counters = clist;
+       csection->counters_last = clist;
+
+       ctimestamp = (CounterTimestamp *) g_calloc (1, sizeof (CounterTimestamp));
+       ctimestamp->value = timestamp;
+       ctimestamp->sections = csection;
+       ctimestamp->sections_last = csection;
+
+       if (!counters_timestamps) {
+               counters_timestamps = ctimestamp;
+       } else {
+               t = counters_timestamps;
+               while (t->next)
+                       t = t->next;
+               t->next = ctimestamp;
+       }
+}
+
+static void
+add_counter_value (int index, CounterValue *value)
+{
+       CounterList *list;
+
+       for (list = counters; list; list = list->next) {
+               if (list->counter->index == index) {
+                       if (!list->counter->values)
+                               list->counter->values = value;
+                       else
+                               list->counter->values_last->next = value;
+                       list->counter->values_last = value;
+
+                       if (counters_sort_mode == COUNTERS_SORT_TIME)
+                               add_counter_to_timestamp (value->timestamp, list->counter);
+
+                       return;
+               }
+       }
+}
+
+static const char*
+section_name (int section)
+{
+       switch (section) {
+       case MONO_COUNTER_JIT: return "Mono JIT";
+       case MONO_COUNTER_GC: return "Mono GC";
+       case MONO_COUNTER_METADATA: return "Mono Metadata";
+       case MONO_COUNTER_GENERICS: return "Mono Generics";
+       case MONO_COUNTER_SECURITY: return "Mono Security";
+       case MONO_COUNTER_RUNTIME: return "Mono Runtime";
+       case MONO_COUNTER_SYSTEM: return "Mono System";
+       case MONO_COUNTER_PROFILER: return "Mono Profiler";
+       default: return "<unknown>";
+       }
+}
+
+static const char*
+type_name (int type)
+{
+       switch (type) {
+       case MONO_COUNTER_INT: return "Int";
+       case MONO_COUNTER_UINT: return "UInt";
+       case MONO_COUNTER_WORD: return "Word";
+       case MONO_COUNTER_LONG: return "Long";
+       case MONO_COUNTER_ULONG: return "ULong";
+       case MONO_COUNTER_DOUBLE: return "Double";
+       case MONO_COUNTER_STRING: return "String";
+       case MONO_COUNTER_TIME_INTERVAL: return "Time Interval";
+       default: return "<unknown>";
+       }
+}
+
+static const char*
+unit_name (int unit)
+{
+       switch (unit) {
+       case MONO_COUNTER_RAW: return "Raw";
+       case MONO_COUNTER_BYTES: return "Bytes";
+       case MONO_COUNTER_TIME: return "Time";
+       case MONO_COUNTER_COUNT: return "Count";
+       case MONO_COUNTER_PERCENTAGE: return "Percentage";
+       default: return "<unknown>";
+       }
+}
+
+static const char*
+variance_name (int variance)
+{
+       switch (variance) {
+       case MONO_COUNTER_MONOTONIC: return "Monotonic";
+       case MONO_COUNTER_CONSTANT: return "Constant";
+       case MONO_COUNTER_VARIABLE: return "Variable";
+       default: return "<unknown>";
+       }
+}
+
+static void
+dump_counters_value (Counter *counter, const char *key_format, const char *key, void *value)
+{
+       char format[32];
+
+       if (value == NULL) {
+               snprintf (format, sizeof (format), "%s : %%s\n", key_format);
+               fprintf (outfile, format, key, "<null>");
+       } else {
+               switch (counter->type) {
+               case MONO_COUNTER_INT:
+#if SIZEOF_VOID_P == 4
+               case MONO_COUNTER_WORD:
+#endif
+                       snprintf (format, sizeof (format), "%s : %%d\n", key_format);
+                       fprintf (outfile, format, key, *(int32_t*)value);
+                       break;
+               case MONO_COUNTER_UINT:
+                       snprintf (format, sizeof (format), "%s : %%u\n", key_format);
+                       fprintf (outfile, format, key, *(uint32_t*)value);
+                       break;
+               case MONO_COUNTER_LONG:
+#if SIZEOF_VOID_P == 8
+               case MONO_COUNTER_WORD:
+#endif
+               case MONO_COUNTER_TIME_INTERVAL:
+                       if (counter->type == MONO_COUNTER_LONG && counter->unit == MONO_COUNTER_TIME) {
+                               snprintf (format, sizeof (format), "%s : %%0.3fms\n", key_format);
+                               fprintf (outfile, format, key, (double)*(int64_t*)value / 10000.0);
+                       } else if (counter->type == MONO_COUNTER_TIME_INTERVAL) {
+                               snprintf (format, sizeof (format), "%s : %%0.3fms\n", key_format);
+                               fprintf (outfile, format, key, (double)*(int64_t*)value / 1000.0);
+                       } else {
+                               snprintf (format, sizeof (format), "%s : %%u\n", key_format);
+                               fprintf (outfile, format, key, *(int64_t*)value);
+                       }
+                       break;
+               case MONO_COUNTER_ULONG:
+                       snprintf (format, sizeof (format), "%s : %%llu\n", key_format);
+                       fprintf (outfile, format, key, *(uint64_t*)value);
+                       break;
+               case MONO_COUNTER_DOUBLE:
+                       snprintf (format, sizeof (format), "%s : %%f\n", key_format);
+                       fprintf (outfile, format, key, *(double*)value);
+                       break;
+               case MONO_COUNTER_STRING:
+                       snprintf (format, sizeof (format), "%s : %%s\n", key_format);
+                       fprintf (outfile, format, key, *(char*)value);
+                       break;
+               }
+       }
+}
+
+static void
+dump_counters (void)
+{
+       Counter *counter;
+       CounterValue *cvalue;
+       CounterTimestamp *ctimestamp;
+       CounterSection *csection;
+       CounterList *clist;
+       char strtimestamp[17];
+       int i, section_printed;
+
+       fprintf (outfile, "\nCounters:\n");
+
+       if (!verbose) {
+               char counters_to_print[][64] = {
+                       "Methods from AOT",
+                       "Methods JITted using mono JIT",
+                       "Methods JITted using LLVM",
+                       "Total time spent JITting (sec)",
+                       "User Time",
+                       "System Time",
+                       "Total Time",
+                       "Working Set",
+                       "Private Bytes",
+                       "Virtual Bytes",
+                       "Page Faults",
+                       "CPU Load Average - 1min",
+                       "CPU Load Average - 5min",
+                       "CPU Load Average - 15min",
+                       ""
+               };
+
+               for (csection = counters_sections; csection; csection = csection->next) {
+                       section_printed = 0;
+
+                       for (clist = csection->counters; clist; clist = clist->next) {
+                               counter = clist->counter;
+                               if (!counter->values_last)
+                                       continue;
+
+                               for (i = 0; counters_to_print [i][0] != 0; i++) {
+                                       if (strcmp (counters_to_print [i], counter->name) == 0) {
+                                               if (!section_printed) {
+                                                       fprintf (outfile, "\t%s:\n", csection->value);
+                                                       section_printed = 1;
+                                               }
+
+                                               dump_counters_value (counter, "\t\t%-30s", counter->name, counter->values_last->buffer);
+                                               break;
+                                       }
+                               }
+                       }
+               }
+       } else if (counters_sort_mode == COUNTERS_SORT_TIME) {
+               for (ctimestamp = counters_timestamps; ctimestamp; ctimestamp = ctimestamp->next) {
+                       fprintf (outfile, "\t%llu:%02llu:%02llu:%02llu.%03llu:\n",
+                               (unsigned long long) (ctimestamp->value / 1000 / 60 / 60 / 24 % 1000),
+                               (unsigned long long) (ctimestamp->value / 1000 / 60 / 60 % 24),
+                               (unsigned long long) (ctimestamp->value / 1000 / 60 % 60),
+                               (unsigned long long) (ctimestamp->value / 1000 % 60),
+                               (unsigned long long) (ctimestamp->value % 1000));
+
+                       for (csection = ctimestamp->sections; csection; csection = csection->next) {
+                               fprintf (outfile, "\t\t%s:\n", csection->value);
+
+                               for (clist = csection->counters; clist; clist = clist->next) {
+                                       counter = clist->counter;
+                                       for (cvalue = counter->values; cvalue; cvalue = cvalue->next) {
+                                               if (cvalue->timestamp != ctimestamp->value)
+                                                       continue;
+
+                                               dump_counters_value (counter, "\t\t\t%-30s", counter->name, cvalue->buffer);
+                                       }
+                               }
+                       }
+               }
+       } else if (counters_sort_mode == COUNTERS_SORT_CATEGORY) {
+               for (csection = counters_sections; csection; csection = csection->next) {
+                       fprintf (outfile, "\t%s:\n", csection->value);
+
+                       for (clist = csection->counters; clist; clist = clist->next) {
+                               counter = clist->counter;
+                               fprintf (outfile, "\t\t%s: [type: %s, unit: %s, variance: %s]\n",
+                                       counter->name, type_name (counter->type), unit_name (counter->unit), variance_name (counter->variance));
+
+                               for (cvalue = counter->values; cvalue; cvalue = cvalue->next) {
+                                       snprintf (strtimestamp, sizeof (strtimestamp), "%llu:%02llu:%02llu:%02llu.%03llu",
+                                               (unsigned long long) (cvalue->timestamp / 1000 / 60 / 60 / 24 % 1000),
+                                               (unsigned long long) (cvalue->timestamp / 1000 / 60 / 60 % 24),
+                                               (unsigned long long) (cvalue->timestamp / 1000 / 60 % 60),
+                                               (unsigned long long) (cvalue->timestamp / 1000 % 60),
+                                               (unsigned long long) (cvalue->timestamp % 1000));
+
+                                       dump_counters_value (counter, "\t\t\t%s", strtimestamp, cvalue->buffer);
+                               }
+                       }
+               }
+       }
+}
+
+static int num_images;
+typedef struct _ImageDesc ImageDesc;
+struct _ImageDesc {
+       ImageDesc *next;
+       intptr_t image;
+       char *filename;
+};
+
+static ImageDesc* image_hash [SMALL_HASH_SIZE] = {0};
+
+static void
+add_image (intptr_t image, char *name)
+{
+       int slot = ((image >> 2) & 0xffff) % SMALL_HASH_SIZE;
+       ImageDesc *cd = (ImageDesc *) g_malloc (sizeof (ImageDesc));
+       cd->image = image;
+       cd->filename = pstrdup (name);
+       cd->next = image_hash [slot];
+       image_hash [slot] = cd;
+       num_images++;
+}
+
+static int num_assemblies;
+
+typedef struct _AssemblyDesc AssemblyDesc;
+struct _AssemblyDesc {
+       AssemblyDesc *next;
+       intptr_t assembly;
+       char *asmname;
+};
+
+static AssemblyDesc* assembly_hash [SMALL_HASH_SIZE] = {0};
+
+static void
+add_assembly (intptr_t assembly, char *name)
+{
+       int slot = ((assembly >> 2) & 0xffff) % SMALL_HASH_SIZE;
+       AssemblyDesc *cd = (AssemblyDesc *) g_malloc (sizeof (AssemblyDesc));
+       cd->assembly = assembly;
+       cd->asmname = pstrdup (name);
+       cd->next = assembly_hash [slot];
+       assembly_hash [slot] = cd;
+       num_assemblies++;
+}
+
+typedef struct _BackTrace BackTrace;
+typedef struct {
+       uint64_t count;
+       BackTrace *bt;
+} CallContext;
+
+typedef struct {
+       int count;
+       int size;
+       CallContext *traces;
+} TraceDesc;
+
+typedef struct _ClassDesc ClassDesc;
+struct _ClassDesc {
+       ClassDesc *next;
+       intptr_t klass;
+       char *name;
+       intptr_t allocs;
+       uint64_t alloc_size;
+       TraceDesc traces;
+};
+
+static ClassDesc* class_hash [HASH_SIZE] = {0};
+static int num_classes = 0;
+
+static ClassDesc*
+add_class (intptr_t klass, const char *name)
+{
+       int slot = ((klass >> 2) & 0xffff) % HASH_SIZE;
+       ClassDesc *cd;
+       cd = class_hash [slot];
+       while (cd && cd->klass != klass)
+               cd = cd->next;
+       /* we resolved an unknown class (unless we had the code unloaded) */
+       if (cd) {
+               /*printf ("resolved unknown: %s\n", name);*/
+               g_free (cd->name);
+               cd->name = pstrdup (name);
+               return cd;
+       }
+       cd = (ClassDesc *) g_calloc (sizeof (ClassDesc), 1);
+       cd->klass = klass;
+       cd->name = pstrdup (name);
+       cd->next = class_hash [slot];
+       cd->allocs = 0;
+       cd->alloc_size = 0;
+       cd->traces.count = 0;
+       cd->traces.size = 0;
+       cd->traces.traces = NULL;
+       class_hash [slot] = cd;
+       num_classes++;
+       return cd;
+}
+
+static ClassDesc *
+lookup_class (intptr_t klass)
+{
+       int slot = ((klass >> 2) & 0xffff) % HASH_SIZE;
+       ClassDesc *cd = class_hash [slot];
+       while (cd && cd->klass != klass)
+               cd = cd->next;
+       if (!cd) {
+               char buf [128];
+               snprintf (buf, sizeof (buf), "unresolved class %p", (void*)klass);
+               return add_class (klass, buf);
+       }
+       return cd;
+}
+
+typedef struct _MethodDesc MethodDesc;
+struct _MethodDesc {
+       MethodDesc *next;
+       intptr_t method;
+       char *name;
+       intptr_t code;
+       int len;
+       int recurse_count;
+       int sample_hits;
+       int ignore_jit; /* when this is set, we collect the metadata but don't count this method fot jit time and code size, when filtering events */
+       uint64_t calls;
+       uint64_t total_time;
+       uint64_t callee_time;
+       uint64_t self_time;
+       TraceDesc traces;
+};
+
+static MethodDesc* method_hash [HASH_SIZE] = {0};
+static int num_methods = 0;
+
+static MethodDesc*
+add_method (intptr_t method, const char *name, intptr_t code, int len)
+{
+       int slot = ((method >> 2) & 0xffff) % HASH_SIZE;
+       MethodDesc *cd;
+       cd = method_hash [slot];
+       while (cd && cd->method != method)
+               cd = cd->next;
+       /* we resolved an unknown method (unless we had the code unloaded) */
+       if (cd) {
+               cd->code = code;
+               cd->len = len;
+               /*printf ("resolved unknown: %s\n", name);*/
+               g_free (cd->name);
+               cd->name = pstrdup (name);
+               return cd;
+       }
+       cd = (MethodDesc *) g_calloc (sizeof (MethodDesc), 1);
+       cd->method = method;
+       cd->name = pstrdup (name);
+       cd->code = code;
+       cd->len = len;
+       cd->calls = 0;
+       cd->total_time = 0;
+       cd->traces.count = 0;
+       cd->traces.size = 0;
+       cd->traces.traces = NULL;
+       cd->next = method_hash [slot];
+       method_hash [slot] = cd;
+       num_methods++;
+       return cd;
+}
+
+static MethodDesc *
+lookup_method (intptr_t method)
+{
+       int slot = ((method >> 2) & 0xffff) % HASH_SIZE;
+       MethodDesc *cd = method_hash [slot];
+       while (cd && cd->method != method)
+               cd = cd->next;
+       if (!cd) {
+               char buf [128];
+               snprintf (buf, sizeof (buf), "unknown method %p", (void*)method);
+               return add_method (method, buf, 0, 0);
+       }
+       return cd;
+}
+
+static int num_stat_samples = 0;
+static int size_stat_samples = 0;
+uintptr_t *stat_samples = NULL;
+int *stat_sample_desc = NULL;
+
+static void
+add_stat_sample (int type, uintptr_t ip) {
+       if (num_stat_samples == size_stat_samples) {
+               size_stat_samples *= 2;
+               if (!size_stat_samples)
+               size_stat_samples = 32;
+               stat_samples = (uintptr_t *) g_realloc (stat_samples, size_stat_samples * sizeof (uintptr_t));
+               stat_sample_desc = (int *) g_realloc (stat_sample_desc, size_stat_samples * sizeof (int));
+       }
+       stat_samples [num_stat_samples] = ip;
+       stat_sample_desc [num_stat_samples++] = type;
+}
+
+static MethodDesc*
+lookup_method_by_ip (uintptr_t ip)
+{
+       int i;
+       MethodDesc* m;
+       /* dumb */
+       for (i = 0; i < HASH_SIZE; ++i) {
+               m = method_hash [i];
+               while (m) {
+                       //printf ("checking %p against %p-%p\n", (void*)ip, (void*)(m->code), (void*)(m->code + m->len));
+                       if (ip >= (uintptr_t)m->code && ip < (uintptr_t)m->code + m->len) {
+                               return m;
+                       }
+                       m = m->next;
+               }
+       }
+       return NULL;
+}
+
+static int
+compare_method_samples (const void *a, const void *b)
+{
+       MethodDesc *const *A = (MethodDesc *const *)a;
+       MethodDesc *const *B = (MethodDesc *const *)b;
+       if ((*A)->sample_hits == (*B)->sample_hits)
+               return 0;
+       if ((*B)->sample_hits < (*A)->sample_hits)
+               return -1;
+       return 1;
+}
+
+typedef struct _UnmanagedSymbol UnmanagedSymbol;
+struct _UnmanagedSymbol {
+       UnmanagedSymbol *parent;
+       char *name;
+       int is_binary;
+       uintptr_t addr;
+       uintptr_t size;
+       uintptr_t sample_hits;
+};
+
+static UnmanagedSymbol **usymbols = NULL;
+static int usymbols_size = 0;
+static int usymbols_num = 0;
+
+static int
+compare_usymbol_addr (const void *a, const void *b)
+{
+       UnmanagedSymbol *const *A = (UnmanagedSymbol *const *)a;
+       UnmanagedSymbol *const *B = (UnmanagedSymbol *const *)b;
+       if ((*B)->addr == (*A)->addr)
+               return 0;
+       if ((*B)->addr > (*A)->addr)
+               return -1;
+       return 1;
+}
+
+static int
+compare_usymbol_samples (const void *a, const void *b)
+{
+       UnmanagedSymbol *const *A = (UnmanagedSymbol *const *)a;
+       UnmanagedSymbol *const *B = (UnmanagedSymbol *const *)b;
+       if ((*B)->sample_hits == (*A)->sample_hits)
+               return 0;
+       if ((*B)->sample_hits < (*A)->sample_hits)
+               return -1;
+       return 1;
+}
+
+static void
+add_unmanaged_symbol (uintptr_t addr, char *name, uintptr_t size)
+{
+       UnmanagedSymbol *sym;
+       if (usymbols_num == usymbols_size) {
+               int new_size = usymbols_size * 2;
+               if (!new_size)
+                       new_size = 16;
+               usymbols = (UnmanagedSymbol **) g_realloc (usymbols, sizeof (void*) * new_size);
+               usymbols_size = new_size;
+       }
+       sym = (UnmanagedSymbol *) g_calloc (sizeof (UnmanagedSymbol), 1);
+       sym->addr = addr;
+       sym->name = name;
+       sym->size = size;
+       usymbols [usymbols_num++] = sym;
+}
+
+/* only valid after the symbols are sorted */
+static UnmanagedSymbol*
+lookup_unmanaged_symbol (uintptr_t addr)
+{
+       int r = usymbols_num - 1;
+       int l = 0;
+       UnmanagedSymbol *sym;
+       int last_best = -1;
+       while (r >= l) {
+               int m = (l + r) / 2;
+               sym = usymbols [m];
+               if (addr == sym->addr)
+                       return sym;
+               if (addr < sym->addr) {
+                       r = m - 1;
+               } else if (addr > sym->addr) {
+                       l = m + 1;
+                       last_best = m;
+               }
+       }
+       if (last_best >= 0 && (addr - usymbols [last_best]->addr) < 4096)
+               return usymbols [last_best];
+       return NULL;
+}
+
+/* we use the same structure for binaries */
+static UnmanagedSymbol **ubinaries = NULL;
+static int ubinaries_size = 0;
+static int ubinaries_num = 0;
+
+static void
+add_unmanaged_binary (uintptr_t addr, char *name, uintptr_t size)
+{
+       UnmanagedSymbol *sym;
+       if (ubinaries_num == ubinaries_size) {
+               int new_size = ubinaries_size * 2;
+               if (!new_size)
+                       new_size = 16;
+               ubinaries = (UnmanagedSymbol **) g_realloc (ubinaries, sizeof (void*) * new_size);
+               ubinaries_size = new_size;
+       }
+       sym = (UnmanagedSymbol *) g_calloc (sizeof (UnmanagedSymbol), 1);
+       sym->addr = addr;
+       sym->name = name;
+       sym->size = size;
+       sym->is_binary = 1;
+       ubinaries [ubinaries_num++] = sym;
+}
+
+static UnmanagedSymbol*
+lookup_unmanaged_binary (uintptr_t addr)
+{
+       int i;
+       for (i = 0; i < ubinaries_num; ++i) {
+               UnmanagedSymbol *ubin = ubinaries [i];
+               if (addr >= ubin->addr && addr < ubin->addr + ubin->size) {
+                       return ubin;
+               }
+       }
+       return NULL;
+}
+
+static const char*
+sample_type_name (int type)
+{
+       switch (type) {
+       case SAMPLE_CYCLES: return "cycles";
+       case SAMPLE_INSTRUCTIONS: return "instructions retired";
+       case SAMPLE_CACHE_MISSES: return "cache misses";
+       case SAMPLE_CACHE_REFS: return "cache references";
+       case SAMPLE_BRANCHES: return "executed branches";
+       case SAMPLE_BRANCH_MISSES: return "unpredicted branches";
+       }
+       return "unknown";
+}
+
+static void
+set_usym_parent (UnmanagedSymbol** cachedus, int count)
+{
+       int i;
+       for (i = 0; i < count; ++i) {
+               UnmanagedSymbol *ubin = lookup_unmanaged_binary (cachedus [i]->addr);
+               if (ubin == cachedus [i])
+                       continue;
+               cachedus [i]->parent = ubin;
+       }
+}
+
+static void
+print_usym (UnmanagedSymbol* um)
+{
+       if (um->parent)
+               fprintf (outfile, "\t%6zd %6.2f %-36s in %s\n", um->sample_hits, um->sample_hits*100.0/num_stat_samples, um->name, um->parent->name);
+       else
+               fprintf (outfile, "\t%6zd %6.2f %s\n", um->sample_hits, um->sample_hits*100.0/num_stat_samples, um->name);
+}
+
+static int
+sym_percent (uintptr_t sample_hits)
+{
+       double pc;
+       if (verbose)
+               return 1;
+       pc = sample_hits*100.0/num_stat_samples;
+       return pc >= 0.1;
+}
+
+static void
+dump_samples (void)
+{
+       int i, u;
+       int count = 0, msize = 0;
+       int unmanaged_hits = 0;
+       int unresolved_hits = 0;
+       MethodDesc** cachedm = NULL;
+       int ucount = 0, usize = 0;
+       UnmanagedSymbol** cachedus = NULL;
+       if (!num_stat_samples)
+               return;
+       qsort (usymbols, usymbols_num, sizeof (UnmanagedSymbol*), compare_usymbol_addr);
+       for (i = 0; i < num_stat_samples; ++i) {
+               MethodDesc *m = lookup_method_by_ip (stat_samples [i]);
+               if (m) {
+                       if (!m->sample_hits) {
+                               if (count == msize) {
+                                       msize *= 2;
+                                       if (!msize)
+                                               msize = 4;
+                                       cachedm = (MethodDesc **) g_realloc (cachedm, sizeof (void*) * msize);
+                               }
+                               cachedm [count++] = m;
+                       }
+                       m->sample_hits++;
+               } else {
+                       UnmanagedSymbol *usym = lookup_unmanaged_symbol (stat_samples [i]);
+                       if (!usym) {
+                               unresolved_hits++;
+                               //printf ("unmanaged hit at %p\n", (void*)stat_samples [i]);
+                               usym = lookup_unmanaged_binary (stat_samples [i]);
+                       }
+                       if (usym) {
+                               if (!usym->sample_hits) {
+                                       if (ucount == usize) {
+                                               usize *= 2;
+                                               if (!usize)
+                                                       usize = 4;
+                                               cachedus = (UnmanagedSymbol **) g_realloc (cachedus, sizeof (void*) * usize);
+                                       }
+                                       cachedus [ucount++] = usym;
+                               }
+                               usym->sample_hits++;
+                       }
+                       unmanaged_hits++;
+               }
+       }
+       qsort (cachedm, count, sizeof (MethodDesc*), compare_method_samples);
+       qsort (cachedus, ucount, sizeof (UnmanagedSymbol*), compare_usymbol_samples);
+       set_usym_parent (cachedus, ucount);
+       fprintf (outfile, "\nStatistical samples summary\n");
+       fprintf (outfile, "\tSample type: %s\n", sample_type_name (stat_sample_desc [0]));
+       fprintf (outfile, "\tUnmanaged hits:  %6d (%4.1f%%)\n", unmanaged_hits, (100.0*unmanaged_hits)/num_stat_samples);
+       fprintf (outfile, "\tManaged hits:    %6d (%4.1f%%)\n", num_stat_samples - unmanaged_hits, (100.0*(num_stat_samples-unmanaged_hits))/num_stat_samples);
+       fprintf (outfile, "\tUnresolved hits: %6d (%4.1f%%)\n", unresolved_hits, (100.0*unresolved_hits)/num_stat_samples);
+       fprintf (outfile, "\t%6s %6s %s\n", "Hits", "%", "Method name");
+       i = 0;
+       u = 0;
+       while (i < count || u < ucount) {
+               if (i < count) {
+                       MethodDesc *m = cachedm [i];
+                       if (u < ucount) {
+                               UnmanagedSymbol *um = cachedus [u];
+                               if (um->sample_hits > m->sample_hits) {
+                                       if (!sym_percent (um->sample_hits))
+                                               break;
+                                       print_usym (um);
+                                       u++;
+                                       continue;
+                               }
+                       }
+                       if (!sym_percent (m->sample_hits))
+                               break;
+                       fprintf (outfile, "\t%6d %6.2f %s\n", m->sample_hits, m->sample_hits*100.0/num_stat_samples, m->name);
+                       i++;
+                       continue;
+               }
+               if (u < ucount) {
+                       UnmanagedSymbol *um = cachedus [u];
+                       if (!sym_percent (um->sample_hits))
+                               break;
+                       print_usym (um);
+                       u++;
+                       continue;
+               }
+       }
+}
+
+typedef struct _HeapClassDesc HeapClassDesc;
+typedef struct {
+       HeapClassDesc *klass;
+       uint64_t count;
+} HeapClassRevRef;
+
+struct _HeapClassDesc {
+       ClassDesc *klass;
+       int64_t count;
+       int64_t total_size;
+       HeapClassRevRef *rev_hash;
+       int rev_hash_size;
+       int rev_count;
+       uintptr_t pinned_references;
+       uintptr_t root_references;
+};
+
+static int
+add_rev_class_hashed (HeapClassRevRef *rev_hash, uintptr_t size, HeapClassDesc *hklass, uint64_t value)
+{
+       uintptr_t i;
+       uintptr_t start_pos;
+       start_pos = (hklass->klass->klass >> 2) % size;
+       assert (start_pos < size);
+       i = start_pos;
+       do {
+               if (rev_hash [i].klass == hklass) {
+                       rev_hash [i].count += value;
+                       return 0;
+               } else if (!rev_hash [i].klass) {
+                       rev_hash [i].klass = hklass;
+                       rev_hash [i].count += value;
+                       start_pos = 0;
+                       for (i = 0; i < size; ++i)
+                               if (rev_hash [i].klass && rev_hash [i].klass->klass == hklass->klass)
+                                       start_pos ++;
+                       assert (start_pos == 1);
+                       return 1;
+               }
+               /* wrap around */
+               if (++i == size)
+                       i = 0;
+       } while (i != start_pos);
+       /* should not happen */
+       printf ("failed revref store\n");
+       return 0;
+}
+
+static void
+add_heap_class_rev (HeapClassDesc *from, HeapClassDesc *to)
+{
+       uintptr_t i;
+       if (to->rev_count * 2 >= to->rev_hash_size) {
+               HeapClassRevRef *n;
+               uintptr_t old_size = to->rev_hash_size;
+               to->rev_hash_size *= 2;
+               if (to->rev_hash_size == 0)
+                       to->rev_hash_size = 4;
+               n = (HeapClassRevRef *) g_calloc (sizeof (HeapClassRevRef) * to->rev_hash_size, 1);
+               for (i = 0; i < old_size; ++i) {
+                       if (to->rev_hash [i].klass)
+                               add_rev_class_hashed (n, to->rev_hash_size, to->rev_hash [i].klass, to->rev_hash [i].count);
+               }
+               if (to->rev_hash)
+                       g_free (to->rev_hash);
+               to->rev_hash = n;
+       }
+       to->rev_count += add_rev_class_hashed (to->rev_hash, to->rev_hash_size, from, 1);
+}
+
+typedef struct {
+       uintptr_t objaddr;
+       HeapClassDesc *hklass;
+       uintptr_t num_refs;
+       uintptr_t refs [0];
+} HeapObjectDesc;
+
+typedef struct _HeapShot HeapShot;
+struct _HeapShot {
+       HeapShot *next;
+       uint64_t timestamp;
+       int class_count;
+       int hash_size;
+       HeapClassDesc **class_hash;
+       HeapClassDesc **sorted;
+       HeapObjectDesc **objects_hash;
+       uintptr_t objects_count;
+       uintptr_t objects_hash_size;
+       uintptr_t num_roots;
+       uintptr_t *roots;
+       uintptr_t *roots_extra;
+       int *roots_types;
+};
+
+static HeapShot *heap_shots = NULL;
+static int num_heap_shots = 0;
+
+static HeapShot*
+new_heap_shot (uint64_t timestamp)
+{
+       HeapShot *hs = (HeapShot *) g_calloc (sizeof (HeapShot), 1);
+       hs->hash_size = 4;
+       hs->class_hash = (HeapClassDesc **) g_calloc (sizeof (void*), hs->hash_size);
+       hs->timestamp = timestamp;
+       num_heap_shots++;
+       hs->next = heap_shots;
+       heap_shots = hs;
+       return hs;
+}
+
+static HeapClassDesc*
+heap_class_lookup (HeapShot *hs, ClassDesc *klass)
+{
+       int i;
+       unsigned int start_pos;
+       start_pos = ((uintptr_t)klass->klass >> 2) % hs->hash_size;
+       i = start_pos;
+       do {
+               HeapClassDesc* cd = hs->class_hash [i];
+               if (!cd)
+                       return NULL;
+               if (cd->klass == klass)
+                       return cd;
+               /* wrap around */
+               if (++i == hs->hash_size)
+                       i = 0;
+       } while (i != start_pos);
+       return NULL;
+}
+
+static int
+add_heap_hashed (HeapClassDesc **hash, HeapClassDesc **retv, uintptr_t hsize, ClassDesc *klass, uint64_t size, uint64_t count)
+{
+       uintptr_t i;
+       uintptr_t start_pos;
+       start_pos = ((uintptr_t)klass->klass >> 2) % hsize;
+       i = start_pos;
+       do {
+               if (hash [i] && hash [i]->klass == klass) {
+                       hash [i]->total_size += size;
+                       hash [i]->count += count;
+                       *retv = hash [i];
+                       return 0;
+               } else if (!hash [i]) {
+                       if (*retv) {
+                               hash [i] = *retv;
+                               return 1;
+                       }
+                       hash [i] = (HeapClassDesc *) g_calloc (sizeof (HeapClassDesc), 1);
+                       hash [i]->klass = klass;
+                       hash [i]->total_size += size;
+                       hash [i]->count += count;
+                       *retv = hash [i];
+                       return 1;
+               }
+               /* wrap around */
+               if (++i == hsize)
+                       i = 0;
+       } while (i != start_pos);
+       /* should not happen */
+       printf ("failed heap class store\n");
+       return 0;
+}
+
+static HeapClassDesc*
+add_heap_shot_class (HeapShot *hs, ClassDesc *klass, uint64_t size)
+{
+       HeapClassDesc *res;
+       int i;
+       if (hs->class_count * 2 >= hs->hash_size) {
+               HeapClassDesc **n;
+               int old_size = hs->hash_size;
+               hs->hash_size *= 2;
+               if (hs->hash_size == 0)
+                       hs->hash_size = 4;
+               n = (HeapClassDesc **) g_calloc (sizeof (void*) * hs->hash_size, 1);
+               for (i = 0; i < old_size; ++i) {
+                       res = hs->class_hash [i];
+                       if (hs->class_hash [i])
+                               add_heap_hashed (n, &res, hs->hash_size, hs->class_hash [i]->klass, hs->class_hash [i]->total_size, hs->class_hash [i]->count);
+               }
+               if (hs->class_hash)
+                       g_free (hs->class_hash);
+               hs->class_hash = n;
+       }
+       res = NULL;
+       hs->class_count += add_heap_hashed (hs->class_hash, &res, hs->hash_size, klass, size, 1);
+       //if (res->count == 1)
+       //      printf ("added heap class: %s\n", res->klass->name);
+       return res;
+}
+
+static HeapObjectDesc*
+alloc_heap_obj (uintptr_t objaddr, HeapClassDesc *hklass, uintptr_t num_refs)
+{
+       HeapObjectDesc* ho = (HeapObjectDesc *) g_calloc (sizeof (HeapObjectDesc) + num_refs * sizeof (uintptr_t), 1);
+       ho->objaddr = objaddr;
+       ho->hklass = hklass;
+       ho->num_refs = num_refs;
+       return ho;
+}
+
+static uintptr_t
+heap_shot_find_obj_slot (HeapShot *hs, uintptr_t objaddr)
+{
+       uintptr_t i;
+       uintptr_t start_pos;
+       HeapObjectDesc **hash = hs->objects_hash;
+       start_pos = ((uintptr_t)objaddr >> 3) % hs->objects_hash_size;
+       i = start_pos;
+       do {
+               if (hash [i] && hash [i]->objaddr == objaddr) {
+                       return i;
+               } else if (!hash [i]) {
+                       break; /* fail */
+               }
+               /* wrap around */
+               if (++i == hs->objects_hash_size)
+                       i = 0;
+       } while (i != start_pos);
+       /* should not happen */
+       //printf ("failed heap obj slot\n");
+       return -1;
+}
+
+static HeapObjectDesc*
+heap_shot_obj_add_refs (HeapShot *hs, uintptr_t objaddr, uintptr_t num, uintptr_t *ref_offset)
+{
+       HeapObjectDesc **hash = hs->objects_hash;
+       uintptr_t i = heap_shot_find_obj_slot (hs, objaddr);
+       if (i >= 0) {
+               HeapObjectDesc* ho = alloc_heap_obj (objaddr, hash [i]->hklass, hash [i]->num_refs + num);
+               *ref_offset = hash [i]->num_refs;
+               memcpy (ho->refs, hash [i]->refs, hash [i]->num_refs * sizeof (uintptr_t));
+               g_free (hash [i]);
+               hash [i] = ho;
+               return ho;
+       }
+       /* should not happen */
+       printf ("failed heap obj update\n");
+       return NULL;
+
+}
+
+static uintptr_t
+add_heap_hashed_obj (HeapObjectDesc **hash, uintptr_t hsize, HeapObjectDesc *obj)
+{
+       uintptr_t i;
+       uintptr_t start_pos;
+       start_pos = ((uintptr_t)obj->objaddr >> 3) % hsize;
+       i = start_pos;
+       do {
+               if (hash [i] && hash [i]->objaddr == obj->objaddr) {
+                       printf ("duplicate object!\n");
+                       return 0;
+               } else if (!hash [i]) {
+                       hash [i] = obj;
+                       return 1;
+               }
+               /* wrap around */
+               if (++i == hsize)
+                       i = 0;
+       } while (i != start_pos);
+       /* should not happen */
+       printf ("failed heap obj store\n");
+       return 0;
+}
+
+static void
+add_heap_shot_obj (HeapShot *hs, HeapObjectDesc *obj)
+{
+       uintptr_t i;
+       if (hs->objects_count * 2 >= hs->objects_hash_size) {
+               HeapObjectDesc **n;
+               uintptr_t old_size = hs->objects_hash_size;
+               hs->objects_hash_size *= 2;
+               if (hs->objects_hash_size == 0)
+                       hs->objects_hash_size = 4;
+               n = (HeapObjectDesc **) g_calloc (sizeof (void*) * hs->objects_hash_size, 1);
+               for (i = 0; i < old_size; ++i) {
+                       if (hs->objects_hash [i])
+                               add_heap_hashed_obj (n, hs->objects_hash_size, hs->objects_hash [i]);
+               }
+               if (hs->objects_hash)
+                       g_free (hs->objects_hash);
+               hs->objects_hash = n;
+       }
+       hs->objects_count += add_heap_hashed_obj (hs->objects_hash, hs->objects_hash_size, obj);
+}
+
+static void
+heap_shot_resolve_reverse_refs (HeapShot *hs)
+{
+       uintptr_t i;
+       for (i = 0; i < hs->objects_hash_size; ++i) {
+               uintptr_t r;
+               HeapObjectDesc *ho = hs->objects_hash [i];
+               if (!ho)
+                       continue;
+               for (r = 0; r < ho->num_refs; ++r) {
+                       uintptr_t oi = heap_shot_find_obj_slot (hs, ho->refs [r]);
+                       add_heap_class_rev (ho->hklass, hs->objects_hash [oi]->hklass);
+               }
+       }
+}
+
+#define MARK_GRAY 1
+#define MARK_BLACK 2
+
+static void
+heap_shot_mark_objects (HeapShot *hs)
+{
+       uintptr_t i, oi, r;
+       unsigned char *marks;
+       HeapObjectDesc *obj, *ref;
+       int marked_some;
+       uintptr_t num_marked = 0, num_unmarked;
+       for (i = 0; i < hs->num_roots; ++i) {
+               HeapClassDesc *cd;
+               oi = heap_shot_find_obj_slot (hs, hs->roots [i]);
+               if (oi == -1) {
+                       continue;
+               }
+               obj = hs->objects_hash [oi];
+               cd = obj->hklass;
+               if (hs->roots_types [i] & MONO_PROFILE_GC_ROOT_PINNING)
+                       cd->pinned_references++;
+               cd->root_references++;
+       }
+       if (!debug)
+               return;
+       /* consistency checks: it seems not all the objects are walked in the heap in some cases */
+       marks = (unsigned char *) g_calloc (hs->objects_hash_size, 1);
+       if (!marks)
+               return;
+       for (i = 0; i < hs->num_roots; ++i) {
+               oi = heap_shot_find_obj_slot (hs, hs->roots [i]);
+               if (oi == -1) {
+                       fprintf (outfile, "root type 0x%x for obj %p (%s) not found in heap\n", hs->roots_types [i], (void*)hs->roots [i], lookup_class (hs->roots_extra [i])->name);
+                       continue;
+               }
+               obj = hs->objects_hash [oi];
+               if (!marks [oi]) {
+                       marks [oi] = obj->num_refs? MARK_GRAY: MARK_BLACK;
+                       num_marked++;
+               }
+       }
+       marked_some = 1;
+       while (marked_some) {
+               marked_some = 0;
+               for (i = 0; i < hs->objects_hash_size; ++i) {
+                       if (marks [i] != MARK_GRAY)
+                               continue;
+                       marks [i] = MARK_BLACK;
+                       obj = hs->objects_hash [i];
+                       for (r = 0; r < obj->num_refs; ++r) {
+                               oi = heap_shot_find_obj_slot (hs, obj->refs [r]);
+                               if (oi == -1) {
+                                       fprintf (outfile, "referenced obj %p not found in heap\n", (void*)obj->refs [r]);
+                                       continue;
+                               }
+                               ref = hs->objects_hash [oi];
+                               if (!marks [oi]) {
+                                       marks [oi] = ref->num_refs? MARK_GRAY: MARK_BLACK;
+                               }
+                       }
+                       marked_some++;
+               }
+       }
+
+       num_unmarked = 0;
+       for (i = 0; i < hs->objects_hash_size; ++i) {
+               if (hs->objects_hash [i] && !marks [i]) {
+                       num_unmarked++;
+                       fprintf (outfile, "object %p (%s) unmarked\n", (void*)hs->objects_hash [i], hs->objects_hash [i]->hklass->klass->name);
+               }
+       }
+       fprintf (outfile, "Total unmarked: %zd/%zd\n", num_unmarked, hs->objects_count);
+       g_free (marks);
+}
+
+static void
+heap_shot_free_objects (HeapShot *hs)
+{
+       uintptr_t i;
+       for (i = 0; i < hs->objects_hash_size; ++i) {
+               HeapObjectDesc *ho = hs->objects_hash [i];
+               if (ho)
+                       g_free (ho);
+       }
+       if (hs->objects_hash)
+               g_free (hs->objects_hash);
+       hs->objects_hash = NULL;
+       hs->objects_hash_size = 0;
+       hs->objects_count = 0;
+}
+
+
+struct _BackTrace {
+       BackTrace *next;
+       unsigned int hash;
+       int count;
+       int id;
+       MethodDesc *methods [1];
+};
+
+static BackTrace *backtrace_hash [HASH_SIZE];
+static BackTrace **backtraces = NULL;
+static int num_backtraces = 0;
+static int next_backtrace = 0;
+
+static int
+hash_backtrace (int count, MethodDesc **methods)
+{
+       int hash = count;
+       int i;
+       for (i = 0; i < count; ++i) {
+               hash = (hash << 5) - hash + methods [i]->method;
+       }
+       return hash;
+}
+
+static int
+compare_backtrace (BackTrace *bt, int count, MethodDesc **methods)
+{
+       int i;
+       if (bt->count != count)
+               return 0;
+       for (i = 0; i < count; ++i)
+               if (methods [i] != bt->methods [i])
+                       return 0;
+       return 1;
+}
+
+static BackTrace*
+add_backtrace (int count, MethodDesc **methods)
+{
+       int hash = hash_backtrace (count, methods);
+       int slot = (hash & 0xffff) % HASH_SIZE;
+       BackTrace *bt = backtrace_hash [slot];
+       while (bt) {
+               if (bt->hash == hash && compare_backtrace (bt, count, methods))
+                       return bt;
+               bt = bt->next;
+       }
+       bt = (BackTrace *) g_malloc (sizeof (BackTrace) + ((count - 1) * sizeof (void*)));
+       bt->next = backtrace_hash [slot];
+       backtrace_hash [slot] = bt;
+       if (next_backtrace == num_backtraces) {
+               num_backtraces *= 2;
+               if (!num_backtraces)
+                       num_backtraces = 16;
+               backtraces = (BackTrace **) g_realloc (backtraces, sizeof (void*) * num_backtraces);
+       }
+       bt->id = next_backtrace++;
+       backtraces [bt->id] = bt;
+       bt->count = count;
+       bt->hash = hash;
+       for (slot = 0; slot < count; ++slot)
+               bt->methods [slot] = methods [slot];
+
+       return bt;
+}
+
+typedef struct _MonitorDesc MonitorDesc;
+typedef struct _ThreadContext ThreadContext;
+typedef struct _DomainContext DomainContext;
+typedef struct _RemCtxContext RemCtxContext;
+
+typedef struct {
+       FILE *file;
+#if defined (HAVE_SYS_ZLIB)
+       gzFile gzfile;
+#endif
+       unsigned char *buf;
+       int size;
+       int data_version;
+       int version_major;
+       int version_minor;
+       int timer_overhead;
+       int pid;
+       int port;
+       char *args;
+       char *arch;
+       char *os;
+       uint64_t startup_time;
+       ThreadContext *threads;
+       ThreadContext *current_thread;
+       DomainContext *domains;
+       DomainContext *current_domain;
+       RemCtxContext *remctxs;
+       RemCtxContext *current_remctx;
+} ProfContext;
+
+struct _ThreadContext {
+       ThreadContext *next;
+       intptr_t thread_id;
+       char *name;
+       /* emulated stack */
+       MethodDesc **stack;
+       uint64_t *time_stack;
+       uint64_t *callee_time_stack;
+       uint64_t last_time;
+       uint64_t contention_start;
+       MonitorDesc *monitor;
+       int stack_size;
+       int stack_id;
+       HeapShot *current_heap_shot;
+       uintptr_t num_roots;
+       uintptr_t size_roots;
+       uintptr_t *roots;
+       uintptr_t *roots_extra;
+       int *roots_types;
+       uint64_t gc_start_times [3];
+};
+
+struct _DomainContext {
+       DomainContext *next;
+       intptr_t domain_id;
+       const char *friendly_name;
+};
+
+struct _RemCtxContext {
+       RemCtxContext *next;
+       intptr_t remctx_id;
+       intptr_t domain_id;
+};
+
+static void
+ensure_buffer (ProfContext *ctx, int size)
+{
+       if (ctx->size < size) {
+               ctx->buf = (unsigned char *) g_realloc (ctx->buf, size);
+               ctx->size = size;
+       }
+}
+
+static int
+load_data (ProfContext *ctx, int size)
+{
+       ensure_buffer (ctx, size);
+#if defined (HAVE_SYS_ZLIB)
+       if (ctx->gzfile) {
+               int r = gzread (ctx->gzfile, ctx->buf, size);
+               if (r == 0)
+                       return size == 0? 1: 0;
+               return r == size;
+       } else
+#endif
+       {
+               int r = fread (ctx->buf, size, 1, ctx->file);
+               if (r == 0)
+                       return size == 0? 1: 0;
+               return r;
+       }
+}
+
+static ThreadContext*
+get_thread (ProfContext *ctx, intptr_t thread_id)
+{
+       ThreadContext *thread;
+       if (ctx->current_thread && ctx->current_thread->thread_id == thread_id)
+               return ctx->current_thread;
+       thread = ctx->threads;
+       while (thread) {
+               if (thread->thread_id == thread_id) {
+                       return thread;
+               }
+               thread = thread->next;
+       }
+       thread = (ThreadContext *) g_calloc (sizeof (ThreadContext), 1);
+       thread->next = ctx->threads;
+       ctx->threads = thread;
+       thread->thread_id = thread_id;
+       thread->last_time = 0;
+       thread->stack_id = 0;
+       thread->stack_size = 32;
+       thread->stack = (MethodDesc **) g_malloc (thread->stack_size * sizeof (void*));
+       thread->time_stack = (uint64_t *) g_malloc (thread->stack_size * sizeof (uint64_t));
+       thread->callee_time_stack = (uint64_t *) g_malloc (thread->stack_size * sizeof (uint64_t));
+       return thread;
+}
+
+static DomainContext *
+get_domain (ProfContext *ctx, intptr_t domain_id)
+{
+       if (ctx->current_domain && ctx->current_domain->domain_id == domain_id)
+               return ctx->current_domain;
+
+       DomainContext *domain = ctx->domains;
+
+       while (domain) {
+               if (domain->domain_id == domain_id)
+                       return domain;
+
+               domain = domain->next;
+       }
+
+       domain = (DomainContext *) g_calloc (sizeof (DomainContext), 1);
+       domain->next = ctx->domains;
+       ctx->domains = domain;
+       domain->domain_id = domain_id;
+
+       return domain;
+}
+
+static RemCtxContext *
+get_remctx (ProfContext *ctx, intptr_t remctx_id)
+{
+       if (ctx->current_remctx && ctx->current_remctx->remctx_id == remctx_id)
+               return ctx->current_remctx;
+
+       RemCtxContext *remctx = ctx->remctxs;
+
+       while (remctx) {
+               if (remctx->remctx_id == remctx_id)
+                       return remctx;
+
+               remctx = remctx->next;
+       }
+
+       remctx = (RemCtxContext *) g_calloc (sizeof (RemCtxContext), 1);
+       remctx->next = ctx->remctxs;
+       ctx->remctxs = remctx;
+       remctx->remctx_id = remctx_id;
+
+       return remctx;
+}
+
+static ThreadContext*
+load_thread (ProfContext *ctx, intptr_t thread_id)
+{
+       ThreadContext *thread = get_thread (ctx, thread_id);
+       ctx->current_thread = thread;
+       return thread;
+}
+
+static void
+ensure_thread_stack (ThreadContext *thread)
+{
+       if (thread->stack_id == thread->stack_size) {
+               thread->stack_size *= 2;
+               thread->stack = (MethodDesc **) g_realloc (thread->stack, thread->stack_size * sizeof (void*));
+               thread->time_stack = (uint64_t *) g_realloc (thread->time_stack, thread->stack_size * sizeof (uint64_t));
+               thread->callee_time_stack = (uint64_t *) g_realloc (thread->callee_time_stack, thread->stack_size * sizeof (uint64_t));
+       }
+}
+
+static int
+add_trace_hashed (CallContext *traces, int size, BackTrace *bt, uint64_t value)
+{
+       int i;
+       unsigned int start_pos;
+       start_pos = bt->hash % size;
+       i = start_pos;
+       do {
+               if (traces [i].bt == bt) {
+                       traces [i].count += value;
+                       return 0;
+               } else if (!traces [i].bt) {
+                       traces [i].bt = bt;
+                       traces [i].count += value;
+                       return 1;
+               }
+               /* wrap around */
+               if (++i == size)
+                       i = 0;
+       } while (i != start_pos);
+       /* should not happen */
+       printf ("failed trace store\n");
+       return 0;
+}
+
+static void
+add_trace_bt (BackTrace *bt, TraceDesc *trace, uint64_t value)
+{
+       int i;
+       if (!collect_traces)
+               return;
+       if (trace->count * 2 >= trace->size) {
+               CallContext *n;
+               int old_size = trace->size;
+               trace->size *= 2;
+               if (trace->size == 0)
+                       trace->size = 4;
+               n = (CallContext *) g_calloc (sizeof (CallContext) * trace->size, 1);
+               for (i = 0; i < old_size; ++i) {
+                       if (trace->traces [i].bt)
+                               add_trace_hashed (n, trace->size, trace->traces [i].bt, trace->traces [i].count);
+               }
+               if (trace->traces)
+                       g_free (trace->traces);
+               trace->traces = n;
+       }
+       trace->count += add_trace_hashed (trace->traces, trace->size, bt, value);
+}
+
+static BackTrace*
+add_trace_thread (ThreadContext *thread, TraceDesc *trace, uint64_t value)
+{
+       BackTrace *bt;
+       int count = thread->stack_id;
+       if (!collect_traces)
+               return NULL;
+       if (count > trace_max)
+               count = trace_max;
+       bt = add_backtrace (count, thread->stack + thread->stack_id - count);
+       add_trace_bt (bt, trace, value);
+       return bt;
+}
+
+static BackTrace*
+add_trace_methods (MethodDesc **methods, int count, TraceDesc *trace, uint64_t value)
+{
+       BackTrace *bt;
+       if (!collect_traces)
+               return NULL;
+       if (count > trace_max)
+               count = trace_max;
+       bt = add_backtrace (count, methods);
+       add_trace_bt (bt, trace, value);
+       return bt;
+}
+
+static void
+thread_add_root (ThreadContext *ctx, uintptr_t obj, int root_type, uintptr_t extra_info)
+{
+       if (ctx->num_roots == ctx->size_roots) {
+               int new_size = ctx->size_roots * 2;
+               if (!new_size)
+                       new_size = 4;
+               ctx->roots = (uintptr_t *) g_realloc (ctx->roots, new_size * sizeof (uintptr_t));
+               ctx->roots_extra = (uintptr_t *) g_realloc (ctx->roots_extra, new_size * sizeof (uintptr_t));
+               ctx->roots_types = (int *) g_realloc (ctx->roots_types, new_size * sizeof (int));
+               ctx->size_roots = new_size;
+       }
+       ctx->roots_types [ctx->num_roots] = root_type;
+       ctx->roots_extra [ctx->num_roots] = extra_info;
+       ctx->roots [ctx->num_roots++] = obj;
+}
+
+static int
+compare_callc (const void *a, const void *b)
+{
+       const CallContext *A = (const CallContext *)a;
+       const CallContext *B = (const CallContext *)b;
+       if (B->count == A->count)
+               return 0;
+       if (B->count < A->count)
+               return -1;
+       return 1;
+}
+
+static void
+sort_context_array (TraceDesc* traces)
+{
+       int i, j;
+       for (i = 0, j = 0; i < traces->size; ++i) {
+               if (traces->traces [i].bt) {
+                       traces->traces [j].bt = traces->traces [i].bt;
+                       traces->traces [j].count = traces->traces [i].count;
+                       j++;
+               }
+       }
+       qsort (traces->traces, traces->count, sizeof (CallContext), compare_callc);
+}
+
+static void
+push_method (ThreadContext *thread, MethodDesc *method, uint64_t timestamp)
+{
+       ensure_thread_stack (thread);
+       thread->time_stack [thread->stack_id] = timestamp;
+       thread->callee_time_stack [thread->stack_id] = 0;
+       thread->stack [thread->stack_id++] = method;
+       method->recurse_count++;
+}
+
+static void
+pop_method (ThreadContext *thread, MethodDesc *method, uint64_t timestamp)
+{
+       method->recurse_count--;
+       if (thread->stack_id > 0 && thread->stack [thread->stack_id - 1] == method) {
+               uint64_t tdiff;
+               thread->stack_id--;
+               method->calls++;
+               if (timestamp < thread->time_stack [thread->stack_id])
+                       fprintf (outfile, "time went backwards for %s\n", method->name);
+               tdiff = timestamp - thread->time_stack [thread->stack_id];
+               if (thread->callee_time_stack [thread->stack_id] > tdiff)
+                       fprintf (outfile, "callee time bigger for %s\n", method->name);
+               method->self_time += tdiff - thread->callee_time_stack [thread->stack_id];
+               method->callee_time += thread->callee_time_stack [thread->stack_id];
+               if (thread->stack_id)
+                       thread->callee_time_stack [thread->stack_id - 1] += tdiff;
+               //fprintf (outfile, "method %s took %d\n", method->name, (int)(tdiff/1000));
+       } else {
+               fprintf (outfile, "unmatched leave at stack pos: %d for method %s\n", thread->stack_id, method->name);
+       }
+}
+
+typedef struct {
+       uint64_t total_time;
+       uint64_t max_time;
+       int count;
+} GCDesc;
+static GCDesc gc_info [3];
+static uint64_t max_heap_size;
+static uint64_t gc_object_moves;
+static int gc_resizes;
+typedef struct {
+       uint64_t created;
+       uint64_t destroyed;
+       uint64_t live;
+       uint64_t max_live;
+       TraceDesc traces;
+       TraceDesc destroy_traces;
+} HandleInfo;
+static HandleInfo handle_info [4];
+
+static const char*
+gc_event_name (int ev)
+{
+       switch (ev) {
+       case MONO_GC_EVENT_START: return "start";
+       case MONO_GC_EVENT_MARK_START: return "mark start";
+       case MONO_GC_EVENT_MARK_END: return "mark end";
+       case MONO_GC_EVENT_RECLAIM_START: return "reclaim start";
+       case MONO_GC_EVENT_RECLAIM_END: return "reclaim end";
+       case MONO_GC_EVENT_END: return "end";
+       case MONO_GC_EVENT_PRE_STOP_WORLD: return "pre stop";
+       case MONO_GC_EVENT_PRE_STOP_WORLD_LOCKED: return "pre stop lock";
+       case MONO_GC_EVENT_POST_STOP_WORLD: return "post stop";
+       case MONO_GC_EVENT_PRE_START_WORLD: return "pre start";
+       case MONO_GC_EVENT_POST_START_WORLD: return "post start";
+       case MONO_GC_EVENT_POST_START_WORLD_UNLOCKED: return "post start unlock";
+       default:
+               return "unknown";
+       }
+}
+
+static const char*
+sync_point_name (int type)
+{
+       switch (type) {
+       case SYNC_POINT_PERIODIC: return "periodic";
+       case SYNC_POINT_WORLD_STOP: return "world stop";
+       case SYNC_POINT_WORLD_START: return "world start";
+       default:
+               return "unknown";
+       }
+}
+
+static uint64_t clause_summary [MONO_EXCEPTION_CLAUSE_FAULT + 1];
+static uint64_t throw_count = 0;
+static TraceDesc exc_traces;
+
+static const char*
+clause_name (int type)
+{
+       switch (type) {
+       case MONO_EXCEPTION_CLAUSE_NONE: return "catch";
+       case MONO_EXCEPTION_CLAUSE_FILTER: return "filter";
+       case MONO_EXCEPTION_CLAUSE_FINALLY: return "finally";
+       case MONO_EXCEPTION_CLAUSE_FAULT: return "fault";
+       default: return "invalid";
+       }
+}
+
+static uint64_t monitor_contention;
+static uint64_t monitor_failed;
+static uint64_t monitor_acquired;
+
+struct _MonitorDesc {
+       MonitorDesc *next;
+       uintptr_t objid;
+       uintptr_t contentions;
+       uint64_t wait_time;
+       uint64_t max_wait_time;
+       TraceDesc traces;
+};
+
+static MonitorDesc* monitor_hash [SMALL_HASH_SIZE] = {0};
+static int num_monitors = 0;
+
+static MonitorDesc*
+lookup_monitor (uintptr_t objid)
+{
+       int slot = ((objid >> 3) & 0xffff) % SMALL_HASH_SIZE;
+       MonitorDesc *cd = monitor_hash [slot];
+       while (cd && cd->objid != objid)
+               cd = cd->next;
+       if (!cd) {
+               cd = (MonitorDesc *) g_calloc (sizeof (MonitorDesc), 1);
+               cd->objid = objid;
+               cd->next = monitor_hash [slot];
+               monitor_hash [slot] = cd;
+               num_monitors++;
+       }
+       return cd;
+}
+
+static const char*
+monitor_ev_name (int ev)
+{
+       switch (ev) {
+       case MONO_PROFILER_MONITOR_CONTENTION: return "contended";
+       case MONO_PROFILER_MONITOR_DONE: return "acquired";
+       case MONO_PROFILER_MONITOR_FAIL: return "not taken";
+       default: return "invalid";
+       }
+}
+
+static const char*
+get_handle_name (int htype)
+{
+       switch (htype) {
+       case 0: return "weak";
+       case 1: return "weaktrack";
+       case 2: return "normal";
+       case 3: return "pinned";
+       default: return "unknown";
+       }
+}
+
+static const char*
+get_root_name (int rtype)
+{
+       switch (rtype & MONO_PROFILE_GC_ROOT_TYPEMASK) {
+       case MONO_PROFILE_GC_ROOT_STACK: return "stack";
+       case MONO_PROFILE_GC_ROOT_FINALIZER: return "finalizer";
+       case MONO_PROFILE_GC_ROOT_HANDLE: return "handle";
+       case MONO_PROFILE_GC_ROOT_OTHER: return "other";
+       case MONO_PROFILE_GC_ROOT_MISC: return "misc";
+       default: return "unknown";
+       }
+}
+
+static uint64_t
+decode_uleb128 (uint8_t *buf, uint8_t **endbuf)
+{
+       uint64_t res = 0;
+       int shift = 0;
+
+       while (1) {
+               uint8_t b = *buf++;
+               res |= (((uint64_t) (b & 0x7f)) << shift);
+
+               if (!(b & 0x80))
+                       break;
+
+               shift += 7;
+       }
+
+       *endbuf = buf;
+
+       return res;
+}
+
+static intptr_t
+decode_sleb128 (uint8_t *buf, uint8_t **endbuf)
+{
+       uint8_t *p = buf;
+       intptr_t res = 0;
+       int shift = 0;
+
+       while (1) {
+               uint8_t b = *p;
+               p++;
+
+               res = res | (((intptr_t) (b & 0x7f)) << shift);
+               shift += 7;
+
+               if (!(b & 0x80)) {
+                       if (shift < sizeof (intptr_t) * 8 && (b & 0x40))
+                               res |= - ((intptr_t) 1 << shift);
+
+                       break;
+               }
+       }
+
+       *endbuf = p;
+
+       return res;
+}
+
+static MethodDesc**
+decode_bt (ProfContext *ctx, MethodDesc** sframes, int *size, unsigned char *p, unsigned char **endp, intptr_t ptr_base, intptr_t *method_base)
+{
+       MethodDesc **frames;
+       int i;
+       if (ctx->data_version < 13)
+               decode_uleb128 (p, &p); /* flags */
+       int count = decode_uleb128 (p, &p);
+       if (count > *size)
+               frames = (MethodDesc **) g_malloc (count * sizeof (void*));
+       else
+               frames = sframes;
+       for (i = 0; i < count; ++i) {
+               intptr_t ptrdiff = decode_sleb128 (p, &p);
+               if (ctx->data_version > 12) {
+                       *method_base += ptrdiff;
+                       frames [i] = lookup_method (*method_base);
+               } else {
+                       frames [i] = lookup_method (ptr_base + ptrdiff);
+               }
+       }
+       *size = count;
+       *endp = p;
+       return frames;
+}
+
+static void
+tracked_creation (uintptr_t obj, ClassDesc *cd, uint64_t size, BackTrace *bt, uint64_t timestamp)
+{
+       int i;
+       for (i = 0; i < num_tracked_objects; ++i) {
+               if (tracked_objects [i] != obj)
+                       continue;
+               fprintf (outfile, "Object %p created (%s, %llu bytes) at %.3f secs.\n", (void*)obj, cd->name, (unsigned long long) size, (timestamp - startup_time)/1000000000.0);
+               if (bt && bt->count) {
+                       int k;
+                       for (k = 0; k < bt->count; ++k)
+                               fprintf (outfile, "\t%s\n", bt->methods [k]->name);
+               }
+       }
+}
+
+static void
+track_handle (uintptr_t obj, int htype, uint32_t handle, BackTrace *bt, uint64_t timestamp)
+{
+       int i;
+       for (i = 0; i < num_tracked_objects; ++i) {
+               if (tracked_objects [i] != obj)
+                       continue;
+               fprintf (outfile, "Object %p referenced from handle %u at %.3f secs.\n", (void*)obj, handle, (timestamp - startup_time) / 1000000000.0);
+               if (bt && bt->count) {
+                       int k;
+                       for (k = 0; k < bt->count; ++k)
+                               fprintf (outfile, "\t%s\n", bt->methods [k]->name);
+               }
+       }
+}
+
+static void
+track_move (uintptr_t src, uintptr_t dst)
+{
+       int i;
+       for (i = 0; i < num_tracked_objects; ++i) {
+               if (tracked_objects [i] == src)
+                       fprintf (outfile, "Object %p moved to %p\n", (void*)src, (void*)dst);
+               else if (tracked_objects [i] == dst)
+                       fprintf (outfile, "Object %p moved from %p\n", (void*)dst, (void*)src);
+       }
+}
+
+static void
+track_obj_reference (uintptr_t obj, uintptr_t parent, ClassDesc *cd)
+{
+       int i;
+       for (i = 0; i < num_tracked_objects; ++i) {
+               if (tracked_objects [i] == obj)
+                       fprintf (outfile, "Object %p referenced from %p (%s).\n", (void*)obj, (void*)parent, cd->name);
+       }
+}
+
+static void
+found_object (uintptr_t obj)
+{
+       num_tracked_objects ++;
+       tracked_objects = (uintptr_t *) g_realloc (tracked_objects, num_tracked_objects * sizeof (tracked_objects [0]));
+       tracked_objects [num_tracked_objects - 1] = obj;
+}
+
+static int num_jit_helpers = 0;
+static int jit_helpers_code_size = 0;
+
+static const char*
+code_buffer_desc (int type)
+{
+       switch (type) {
+       case MONO_PROFILER_CODE_BUFFER_METHOD:
+               return "method";
+       case MONO_PROFILER_CODE_BUFFER_METHOD_TRAMPOLINE:
+               return "method trampoline";
+       case MONO_PROFILER_CODE_BUFFER_UNBOX_TRAMPOLINE:
+               return "unbox trampoline";
+       case MONO_PROFILER_CODE_BUFFER_IMT_TRAMPOLINE:
+               return "imt trampoline";
+       case MONO_PROFILER_CODE_BUFFER_GENERICS_TRAMPOLINE:
+               return "generics trampoline";
+       case MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE:
+               return "specific trampoline";
+       case MONO_PROFILER_CODE_BUFFER_HELPER:
+               return "misc helper";
+       case MONO_PROFILER_CODE_BUFFER_MONITOR:
+               return "monitor/lock";
+       case MONO_PROFILER_CODE_BUFFER_DELEGATE_INVOKE:
+               return "delegate invoke";
+       case MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING:
+               return "exception handling";
+       default:
+               return "unspecified";
+       }
+}
+
+typedef struct _CoverageAssembly CoverageAssembly;
+struct _CoverageAssembly {
+       char *name;
+       char *guid;
+       char *filename;
+       int number_of_methods;
+       int fully_covered;
+       int partially_covered;
+};
+
+typedef struct _CoverageClass CoverageClass;
+struct _CoverageClass {
+       char *assembly_name;
+       char *class_name;
+       int number_of_methods;
+       int fully_covered;
+       int partially_covered;
+};
+
+typedef struct _CoverageCoverage CoverageCoverage;
+struct _CoverageCoverage {
+       int method_id;
+       int offset;
+       int count;
+       int line;
+       int column;
+};
+
+typedef struct _CoverageMethod CoverageMethod;
+struct _CoverageMethod {
+       char *assembly_name;
+       char *class_name;
+       char *method_name;
+       char *method_signature;
+       char *filename;
+       int token;
+       int n_statements;
+       int method_id;
+       GPtrArray *coverage;
+};
+static GPtrArray *coverage_assemblies = NULL;
+static GPtrArray *coverage_methods = NULL;
+static GPtrArray *coverage_statements = NULL;
+static GHashTable *coverage_methods_hash = NULL;
+static GPtrArray *coverage_classes = NULL;
+static GHashTable *coverage_assembly_classes = NULL;
+
+static void
+gather_coverage_statements (void)
+{
+       for (guint i = 0; i < coverage_statements->len; i++) {
+               CoverageCoverage *coverage = (CoverageCoverage *)coverage_statements->pdata[i];
+               CoverageMethod *method = (CoverageMethod *)g_hash_table_lookup (coverage_methods_hash, GINT_TO_POINTER (coverage->method_id));
+               if (method == NULL) {
+                       fprintf (outfile, "Cannot find method with ID: %d\n", coverage->method_id);
+                       continue;
+               }
+
+               g_ptr_array_add (method->coverage, coverage);
+       }
+}
+
+static void
+coverage_add_assembly (CoverageAssembly *assembly)
+{
+       if (coverage_assemblies == NULL)
+               coverage_assemblies = g_ptr_array_new ();
+
+       g_ptr_array_add (coverage_assemblies, assembly);
+}
+
+static void
+coverage_add_method (CoverageMethod *method)
+{
+       if (coverage_methods == NULL) {
+               coverage_methods = g_ptr_array_new ();
+               coverage_methods_hash = g_hash_table_new (NULL, NULL);
+       }
+
+       g_ptr_array_add (coverage_methods, method);
+       g_hash_table_insert (coverage_methods_hash, GINT_TO_POINTER (method->method_id), method);
+}
+
+static void
+coverage_add_class (CoverageClass *klass)
+{
+       GPtrArray *classes = NULL;
+
+       if (coverage_classes == NULL) {
+               coverage_classes = g_ptr_array_new ();
+               coverage_assembly_classes = g_hash_table_new (g_str_hash, g_str_equal);
+       }
+
+       g_ptr_array_add (coverage_classes, klass);
+       classes = (GPtrArray *)g_hash_table_lookup (coverage_assembly_classes, klass->assembly_name);
+       if (classes == NULL) {
+               classes = g_ptr_array_new ();
+               g_hash_table_insert (coverage_assembly_classes, klass->assembly_name, classes);
+       }
+       g_ptr_array_add (classes, klass);
+}
+
+static void
+coverage_add_coverage (CoverageCoverage *coverage)
+{
+       if (coverage_statements == NULL)
+               coverage_statements = g_ptr_array_new ();
+
+       g_ptr_array_add (coverage_statements, coverage);
+}
+
+#define OBJ_ADDR(diff) ((obj_base + diff) << 3)
+#define LOG_TIME(base,diff) /*fprintf("outfile, time %llu + %llu near offset %d\n", base, diff, p - ctx->buf)*/
+
+
+/* Stats */
+#define BUFFER_HEADER_SIZE 48
+
+typedef struct {
+       int count, min_size, max_size, bytes;
+} EventStat;
+
+static int buffer_count;
+static EventStat stats [256];
+
+static void
+record_event_stats (int type, int size)
+{
+       ++stats [type].count;
+       if (!stats [type].min_size)
+               stats [type].min_size = size;
+       stats [type].min_size = MIN (stats [type].min_size, size);
+       stats [type].max_size = MAX (stats [type].max_size, size);
+       stats [type].bytes += size;
+}
+
+static int
+decode_buffer (ProfContext *ctx)
+{
+       unsigned char *p;
+       unsigned char *end;
+       intptr_t thread_id;
+       intptr_t ptr_base;
+       intptr_t obj_base;
+       intptr_t method_base;
+       uint64_t time_base;
+       uint64_t file_offset;
+       int len, i;
+       ThreadContext *thread;
+
+#ifdef HAVE_SYS_ZLIB
+       if (ctx->gzfile)
+               file_offset = gztell (ctx->gzfile);
+       else
+#endif
+               file_offset = ftell (ctx->file);
+       if (!load_data (ctx, 48))
+               return 0;
+       p = ctx->buf;
+       if (read_int32 (p) != BUF_ID) {
+               fprintf (outfile, "Incorrect buffer id: 0x%x\n", read_int32 (p));
+               for (i = 0; i < 48; ++i) {
+                       fprintf (outfile, "0x%x%s", p [i], i % 8?" ":"\n");
+               }
+               return 0;
+       }
+       len = read_int32 (p + 4);
+       time_base = read_int64 (p + 8);
+       ptr_base = read_int64 (p + 16);
+       obj_base = read_int64 (p + 24);
+       thread_id = read_int64 (p + 32);
+       method_base = read_int64 (p + 40);
+       if (debug)
+               fprintf (outfile, "buf: thread:%zx, len: %d, time: %llu, file offset: %llu\n", thread_id, len, (unsigned long long) time_base, (unsigned long long) file_offset);
+       thread = load_thread (ctx, thread_id);
+       if (!load_data (ctx, len))
+               return 0;
+
+       ++buffer_count;
+
+       if (!startup_time) {
+               startup_time = time_base;
+               if (use_time_filter) {
+                       time_from += startup_time;
+                       time_to += startup_time;
+               }
+       }
+       for (i = 0; i < thread->stack_id; ++i)
+               thread->stack [i]->recurse_count++;
+       p = ctx->buf;
+       end = p + len;
+       while (p < end) {
+               unsigned char *start = p;
+               unsigned char event = *p;
+               switch (*p & 0xf) {
+               case TYPE_GC: {
+                       int subtype = *p & 0xf0;
+                       uint64_t tdiff = decode_uleb128 (p + 1, &p);
+                       LOG_TIME (time_base, tdiff);
+                       time_base += tdiff;
+                       if (subtype == TYPE_GC_RESIZE) {
+                               uint64_t new_size = decode_uleb128 (p, &p);
+                               if (debug)
+                                       fprintf (outfile, "gc heap resized to %llu\n", (unsigned long long) new_size);
+                               gc_resizes++;
+                               if (new_size > max_heap_size)
+                                       max_heap_size = new_size;
+                       } else if (subtype == TYPE_GC_EVENT) {
+                               uint64_t ev;
+                               if (ctx->data_version > 12)
+                                       ev = *p++;
+                               else
+                                       ev = decode_uleb128 (p, &p);
+                               int gen;
+                               if (ctx->data_version > 12)
+                                       gen = *p++;
+                               else
+                                       gen = decode_uleb128 (p, &p);
+                               if (debug)
+                                       fprintf (outfile, "gc event for gen%d: %s at %llu (thread: 0x%zx)\n", gen, gc_event_name (ev), (unsigned long long) time_base, thread->thread_id);
+                               if (gen > 2) {
+                                       fprintf (outfile, "incorrect gc gen: %d\n", gen);
+                                       break;
+                               }
+                               if (ev == MONO_GC_EVENT_START) {
+                                       thread->gc_start_times [gen] = time_base;
+                                       gc_info [gen].count++;
+                               } else if (ev == MONO_GC_EVENT_END) {
+                                       tdiff = time_base - thread->gc_start_times [gen];
+                                       gc_info [gen].total_time += tdiff;
+                                       if (tdiff > gc_info [gen].max_time)
+                                               gc_info [gen].max_time = tdiff;
+                               }
+                       } else if (subtype == TYPE_GC_MOVE) {
+                               int j, num = decode_uleb128 (p, &p);
+                               gc_object_moves += num / 2;
+                               for (j = 0; j < num; j += 2) {
+                                       intptr_t obj1diff = decode_sleb128 (p, &p);
+                                       intptr_t obj2diff = decode_sleb128 (p, &p);
+                                       if (num_tracked_objects)
+                                               track_move (OBJ_ADDR (obj1diff), OBJ_ADDR (obj2diff));
+                                       if (debug) {
+                                               fprintf (outfile, "moved obj %p to %p\n", (void*)OBJ_ADDR (obj1diff), (void*)OBJ_ADDR (obj2diff));
+                                       }
+                               }
+                       } else if (subtype == TYPE_GC_HANDLE_CREATED || subtype == TYPE_GC_HANDLE_CREATED_BT) {
+                               int has_bt = subtype == TYPE_GC_HANDLE_CREATED_BT;
+                               int num_bt = 0;
+                               MethodDesc *sframes [8];
+                               MethodDesc **frames = sframes;
+                               int htype = decode_uleb128 (p, &p);
+                               uint32_t handle = decode_uleb128 (p, &p);
+                               intptr_t objdiff = decode_sleb128 (p, &p);
+                               if (has_bt) {
+                                       num_bt = 8;
+                                       frames = decode_bt (ctx, sframes, &num_bt, p, &p, ptr_base, &method_base);
+                                       if (!frames) {
+                                               fprintf (outfile, "Cannot load backtrace\n");
+                                               return 0;
+                                       }
+                               }
+                               if (htype > 3)
+                                       return 0;
+                               if ((thread_filter && thread_filter == thread->thread_id) || (time_base >= time_from && time_base < time_to)) {
+                                       handle_info [htype].created++;
+                                       handle_info [htype].live++;
+                                       if (handle_info [htype].live > handle_info [htype].max_live)
+                                               handle_info [htype].max_live = handle_info [htype].live;
+                                       BackTrace *bt;
+                                       if (has_bt)
+                                               bt = add_trace_methods (frames, num_bt, &handle_info [htype].traces, 1);
+                                       else
+                                               bt = add_trace_thread (thread, &handle_info [htype].traces, 1);
+                                       if (num_tracked_objects)
+                                               track_handle (OBJ_ADDR (objdiff), htype, handle, bt, time_base);
+                               }
+                               if (debug)
+                                       fprintf (outfile, "handle (%s) %u created for object %p\n", get_handle_name (htype), handle, (void*)OBJ_ADDR (objdiff));
+                               if (frames != sframes)
+                                       g_free (frames);
+                       } else if (subtype == TYPE_GC_HANDLE_DESTROYED || subtype == TYPE_GC_HANDLE_DESTROYED_BT) {
+                               int has_bt = subtype == TYPE_GC_HANDLE_DESTROYED_BT;
+                               int num_bt = 0;
+                               MethodDesc *sframes [8];
+                               MethodDesc **frames = sframes;
+                               int htype = decode_uleb128 (p, &p);
+                               uint32_t handle = decode_uleb128 (p, &p);
+                               if (has_bt) {
+                                       num_bt = 8;
+                                       frames = decode_bt (ctx, sframes, &num_bt, p, &p, ptr_base, &method_base);
+                                       if (!frames) {
+                                               fprintf (outfile, "Cannot load backtrace\n");
+                                               return 0;
+                                       }
+                               }
+                               if (htype > 3)
+                                       return 0;
+                               if ((thread_filter && thread_filter == thread->thread_id) || (time_base >= time_from && time_base < time_to)) {
+                                       handle_info [htype].destroyed ++;
+                                       handle_info [htype].live--;
+                                       BackTrace *bt;
+                                       if (has_bt)
+                                               bt = add_trace_methods (frames, num_bt, &handle_info [htype].destroy_traces, 1);
+                                       else
+                                               bt = add_trace_thread (thread, &handle_info [htype].destroy_traces, 1);
+                                       /* TODO: track_handle_free () - would need to record and keep track of the associated object address... */
+                               }
+                               if (debug)
+                                       fprintf (outfile, "handle (%s) %u destroyed\n", get_handle_name (htype), handle);
+                               if (frames != sframes)
+                                       g_free (frames);
+                       } else if (subtype == TYPE_GC_FINALIZE_START) {
+                               // TODO: Generate a finalizer report based on these events.
+                               if (debug)
+                                       fprintf (outfile, "gc finalizer queue being processed at %llu\n", (unsigned long long) time_base);
+                       } else if (subtype == TYPE_GC_FINALIZE_END) {
+                               if (debug)
+                                       fprintf (outfile, "gc finalizer queue finished processing at %llu\n", (unsigned long long) time_base);
+                       } else if (subtype == TYPE_GC_FINALIZE_OBJECT_START) {
+                               intptr_t objdiff = decode_sleb128 (p, &p);
+                               if (debug)
+                                       fprintf (outfile, "gc finalizing object %p at %llu\n", (void *) OBJ_ADDR (objdiff), (unsigned long long) time_base);
+                       } else if (subtype == TYPE_GC_FINALIZE_OBJECT_END) {
+                               intptr_t objdiff = decode_sleb128 (p, &p);
+                               if (debug)
+                                       fprintf (outfile, "gc finalized object %p at %llu\n", (void *) OBJ_ADDR (objdiff), (unsigned long long) time_base);
+                       }
+                       break;
+               }
+               case TYPE_METADATA: {
+                       int subtype = *p & 0xf0;
+                       const char *load_str = subtype == TYPE_END_LOAD ? "loaded" : "unloaded";
+                       uint64_t tdiff = decode_uleb128 (p + 1, &p);
+                       int mtype = *p++;
+                       intptr_t ptrdiff = decode_sleb128 (p, &p);
+                       LOG_TIME (time_base, tdiff);
+                       time_base += tdiff;
+                       if (mtype == TYPE_CLASS) {
+                               intptr_t imptrdiff = decode_sleb128 (p, &p);
+                               if (ctx->data_version < 13)
+                                       decode_uleb128 (p, &p); /* flags */
+                               if (debug)
+                                       fprintf (outfile, "%s class %p (%s in %p) at %llu\n", load_str, (void*)(ptr_base + ptrdiff), p, (void*)(ptr_base + imptrdiff), (unsigned long long) time_base);
+                               if (subtype == TYPE_END_LOAD)
+                                       add_class (ptr_base + ptrdiff, (char*)p);
+                               while (*p) p++;
+                               p++;
+                       } else if (mtype == TYPE_IMAGE) {
+                               if (ctx->data_version < 13)
+                                       decode_uleb128 (p, &p); /* flags */
+                               if (debug)
+                                       fprintf (outfile, "%s image %p (%s) at %llu\n", load_str, (void*)(ptr_base + ptrdiff), p, (unsigned long long) time_base);
+                               if (subtype == TYPE_END_LOAD)
+                                       add_image (ptr_base + ptrdiff, (char*)p);
+                               while (*p) p++;
+                               p++;
+                       } else if (mtype == TYPE_ASSEMBLY) {
+                               if (ctx->data_version < 13)
+                                       decode_uleb128 (p, &p); /* flags */
+                               if (debug)
+                                       fprintf (outfile, "%s assembly %p (%s) at %llu\n", load_str, (void*)(ptr_base + ptrdiff), p, (unsigned long long) time_base);
+                               if (subtype == TYPE_END_LOAD)
+                                       add_assembly (ptr_base + ptrdiff, (char*)p);
+                               while (*p) p++;
+                               p++;
+                       } else if (mtype == TYPE_DOMAIN) {
+                               if (ctx->data_version < 13)
+                                       decode_uleb128 (p, &p); /* flags */
+                               DomainContext *nd = get_domain (ctx, ptr_base + ptrdiff);
+                               /* no subtype means it's a name event, rather than start/stop */
+                               if (subtype == 0)
+                                       nd->friendly_name = pstrdup ((char *) p);
+                               if (debug) {
+                                       if (subtype == 0)
+                                               fprintf (outfile, "domain %p named at %llu: %s\n", (void *) (ptr_base + ptrdiff), (unsigned long long) time_base, p);
+                                       else
+                                               fprintf (outfile, "%s thread %p at %llu\n", load_str, (void *) (ptr_base + ptrdiff), (unsigned long long) time_base);
+                               }
+                               if (subtype == 0) {
+                                       while (*p) p++;
+                                       p++;
+                               }
+                       } else if (mtype == TYPE_CONTEXT) {
+                               if (ctx->data_version < 13)
+                                       decode_uleb128 (p, &p); /* flags */
+                               intptr_t domaindiff = decode_sleb128 (p, &p);
+                               if (debug)
+                                       fprintf (outfile, "%s context %p (%p) at %llu\n", load_str, (void*)(ptr_base + ptrdiff), (void *) (ptr_base + domaindiff), (unsigned long long) time_base);
+                               if (subtype == TYPE_END_LOAD)
+                                       get_remctx (ctx, ptr_base + ptrdiff)->domain_id = ptr_base + domaindiff;
+                       } else if (mtype == TYPE_THREAD) {
+                               if (ctx->data_version < 13)
+                                       decode_uleb128 (p, &p); /* flags */
+                               ThreadContext *nt = get_thread (ctx, ptr_base + ptrdiff);
+                               /* no subtype means it's a name event, rather than start/stop */
+                               if (subtype == 0)
+                                       nt->name = pstrdup ((char*)p);
+                               if (debug) {
+                                       if (subtype == 0)
+                                               fprintf (outfile, "thread %p named at %llu: %s\n", (void*)(ptr_base + ptrdiff), (unsigned long long) time_base, p);
+                                       else
+                                               fprintf (outfile, "%s thread %p at %llu\n", load_str, (void *) (ptr_base + ptrdiff), (unsigned long long) time_base);
+                               }
+                               if (subtype == 0) {
+                                       while (*p) p++;
+                                       p++;
+                               }
+                       }
+                       break;
+               }
+               case TYPE_ALLOC: {
+                       int has_bt = *p & TYPE_ALLOC_BT;
+                       uint64_t tdiff = decode_uleb128 (p + 1, &p);
+                       intptr_t ptrdiff = decode_sleb128 (p, &p);
+                       intptr_t objdiff = decode_sleb128 (p, &p);
+                       uint64_t len;
+                       int num_bt = 0;
+                       MethodDesc* sframes [8];
+                       MethodDesc** frames = sframes;
+                       ClassDesc *cd = lookup_class (ptr_base + ptrdiff);
+                       len = decode_uleb128 (p, &p);
+                       LOG_TIME (time_base, tdiff);
+                       time_base += tdiff;
+                       if (debug)
+                               fprintf (outfile, "alloced object %p, size %llu (%s) at %llu\n", (void*)OBJ_ADDR (objdiff), (unsigned long long) len, lookup_class (ptr_base + ptrdiff)->name, (unsigned long long) time_base);
+                       if (has_bt) {
+                               num_bt = 8;
+                               frames = decode_bt (ctx, sframes, &num_bt, p, &p, ptr_base, &method_base);
+                               if (!frames) {
+                                       fprintf (outfile, "Cannot load backtrace\n");
+                                       return 0;
+                               }
+                       }
+                       if ((thread_filter && thread_filter == thread->thread_id) || (time_base >= time_from && time_base < time_to)) {
+                               BackTrace *bt;
+                               cd->allocs++;
+                               cd->alloc_size += len;
+                               if (has_bt)
+                                       bt = add_trace_methods (frames, num_bt, &cd->traces, len);
+                               else
+                                       bt = add_trace_thread (thread, &cd->traces, len);
+                               if (find_size && len >= find_size) {
+                                       if (!find_name || strstr (cd->name, find_name))
+                                               found_object (OBJ_ADDR (objdiff));
+                               } else if (!find_size && find_name && strstr (cd->name, find_name)) {
+                                       found_object (OBJ_ADDR (objdiff));
+                               }
+                               if (num_tracked_objects)
+                                       tracked_creation (OBJ_ADDR (objdiff), cd, len, bt, time_base);
+                       }
+                       if (frames != sframes)
+                               g_free (frames);
+                       break;
+               }
+               case TYPE_METHOD: {
+                       int subtype = *p & 0xf0;
+                       uint64_t tdiff = decode_uleb128 (p + 1, &p);
+                       int64_t ptrdiff = decode_sleb128 (p, &p);
+                       LOG_TIME (time_base, tdiff);
+                       time_base += tdiff;
+                       method_base += ptrdiff;
+                       if (subtype == TYPE_JIT) {
+                               intptr_t codediff = decode_sleb128 (p, &p);
+                               int codelen = decode_uleb128 (p, &p);
+                               MethodDesc *jitted_method;
+                               if (debug)
+                                       fprintf (outfile, "jitted method %p (%s), size: %d, code: %p\n", (void*)(method_base), p, codelen, (void*)(ptr_base + codediff));
+                               jitted_method = add_method (method_base, (char*)p, ptr_base + codediff, codelen);
+                               if (!(time_base >= time_from && time_base < time_to))
+                                       jitted_method->ignore_jit = 1;
+                               while (*p) p++;
+                               p++;
+                       } else {
+                               MethodDesc *method;
+                               if ((thread_filter && thread_filter != thread->thread_id))
+                                       break;
+                               if (!(time_base >= time_from && time_base < time_to))
+                                       break;
+                               method = lookup_method (method_base);
+                               if (subtype == TYPE_ENTER) {
+                                       add_trace_thread (thread, &method->traces, 1);
+                                       push_method (thread, method, time_base);
+                               } else {
+                                       pop_method (thread, method, time_base);
+                               }
+                               if (debug)
+                                       fprintf (outfile, "%s method %s\n", subtype == TYPE_ENTER? "enter": subtype == TYPE_EXC_LEAVE? "exleave": "leave", method->name);
+                       }
+                       break;
+               }
+               case TYPE_HEAP: {
+                       int subtype = *p & 0xf0;
+                       if (subtype == TYPE_HEAP_OBJECT) {
+                               HeapObjectDesc *ho = NULL;
+                               int i;
+                               intptr_t objdiff;
+                               if (ctx->data_version > 12) {
+                                       uint64_t tdiff = decode_uleb128 (p + 1, &p);
+                                       LOG_TIME (time_base, tdiff);
+                                       time_base += tdiff;
+                                       objdiff = decode_sleb128 (p, &p);
+                               } else
+                                       objdiff = decode_sleb128 (p + 1, &p);
+                               intptr_t ptrdiff = decode_sleb128 (p, &p);
+                               uint64_t size = decode_uleb128 (p, &p);
+                               uintptr_t num = decode_uleb128 (p, &p);
+                               uintptr_t ref_offset = 0;
+                               uintptr_t last_obj_offset = 0;
+                               ClassDesc *cd = lookup_class (ptr_base + ptrdiff);
+                               if (size) {
+                                       HeapClassDesc *hcd = add_heap_shot_class (thread->current_heap_shot, cd, size);
+                                       if (collect_traces) {
+                                               ho = alloc_heap_obj (OBJ_ADDR (objdiff), hcd, num);
+                                               add_heap_shot_obj (thread->current_heap_shot, ho);
+                                               ref_offset = 0;
+                                       }
+                               } else {
+                                       if (collect_traces)
+                                               ho = heap_shot_obj_add_refs (thread->current_heap_shot, OBJ_ADDR (objdiff), num, &ref_offset);
+                               }
+                               for (i = 0; i < num; ++i) {
+                                       /* FIXME: use object distance to measure how good
+                                        * the GC is at keeping related objects close
+                                        */
+                                       uintptr_t offset = ctx->data_version > 1? last_obj_offset + decode_uleb128 (p, &p): -1;
+                                       intptr_t obj1diff = decode_sleb128 (p, &p);
+                                       last_obj_offset = offset;
+                                       if (collect_traces)
+                                               ho->refs [ref_offset + i] = OBJ_ADDR (obj1diff);
+                                       if (num_tracked_objects)
+                                               track_obj_reference (OBJ_ADDR (obj1diff), OBJ_ADDR (objdiff), cd);
+                               }
+                               if (debug && size)
+                                       fprintf (outfile, "traced object %p, size %llu (%s), refs: %zd\n", (void*)OBJ_ADDR (objdiff), (unsigned long long) size, cd->name, num);
+                       } else if (subtype == TYPE_HEAP_ROOT) {
+                               uintptr_t num;
+                               if (ctx->data_version > 12) {
+                                       uint64_t tdiff = decode_uleb128 (p + 1, &p);
+                                       LOG_TIME (time_base, tdiff);
+                                       time_base += tdiff;
+                                       num = decode_uleb128 (p, &p);
+                               } else
+                                       num = decode_uleb128 (p + 1, &p);
+                               uintptr_t gc_num G_GNUC_UNUSED = decode_uleb128 (p, &p);
+                               int i;
+                               for (i = 0; i < num; ++i) {
+                                       intptr_t objdiff = decode_sleb128 (p, &p);
+                                       int root_type;
+                                       if (ctx->data_version > 12)
+                                               root_type = *p++;
+                                       else
+                                               root_type = decode_uleb128 (p, &p);
+                                       /* we just discard the extra info for now */
+                                       uintptr_t extra_info = decode_uleb128 (p, &p);
+                                       if (debug)
+                                               fprintf (outfile, "object %p is a %s root\n", (void*)OBJ_ADDR (objdiff), get_root_name (root_type));
+                                       if (collect_traces)
+                                               thread_add_root (thread, OBJ_ADDR (objdiff), root_type, extra_info);
+                               }
+                       } else if (subtype == TYPE_HEAP_END) {
+                               uint64_t tdiff = decode_uleb128 (p + 1, &p);
+                               LOG_TIME (time_base, tdiff);
+                               time_base += tdiff;
+                               if (debug)
+                                       fprintf (outfile, "heap shot end\n");
+                               if (collect_traces) {
+                                       HeapShot *hs = thread->current_heap_shot;
+                                       if (hs && thread->num_roots) {
+                                               /* transfer the root ownershipt to the heapshot */
+                                               hs->num_roots = thread->num_roots;
+                                               hs->roots = thread->roots;
+                                               hs->roots_extra = thread->roots_extra;
+                                               hs->roots_types = thread->roots_types;
+                                       } else {
+                                               g_free (thread->roots);
+                                               g_free (thread->roots_extra);
+                                               g_free (thread->roots_types);
+                                       }
+                                       thread->num_roots = 0;
+                                       thread->size_roots = 0;
+                                       thread->roots = NULL;
+                                       thread->roots_extra = NULL;
+                                       thread->roots_types = NULL;
+                                       heap_shot_resolve_reverse_refs (hs);
+                                       heap_shot_mark_objects (hs);
+                                       heap_shot_free_objects (hs);
+                               }
+                               thread->current_heap_shot = NULL;
+                       } else if (subtype == TYPE_HEAP_START) {
+                               uint64_t tdiff = decode_uleb128 (p + 1, &p);
+                               LOG_TIME (time_base, tdiff);
+                               time_base += tdiff;
+                               if (debug)
+                                       fprintf (outfile, "heap shot start\n");
+                               thread->current_heap_shot = new_heap_shot (time_base);
+                       }
+                       break;
+               }
+               case TYPE_MONITOR: {
+                       int event = (*p >> 4) & 0x3;
+                       int has_bt = *p & TYPE_MONITOR_BT;
+                       uint64_t tdiff = decode_uleb128 (p + 1, &p);
+                       intptr_t objdiff = decode_sleb128 (p, &p);
+                       MethodDesc* sframes [8];
+                       MethodDesc** frames = sframes;
+                       int record;
+                       int num_bt = 0;
+                       LOG_TIME (time_base, tdiff);
+                       time_base += tdiff;
+                       record = (!thread_filter || thread_filter == thread->thread_id);
+                       if (!(time_base >= time_from && time_base < time_to))
+                               record = 0;
+                       if (event == MONO_PROFILER_MONITOR_CONTENTION) {
+                               MonitorDesc *mdesc = lookup_monitor (OBJ_ADDR (objdiff));
+                               if (record) {
+                                       monitor_contention++;
+                                       mdesc->contentions++;
+                                       thread->monitor = mdesc;
+                                       thread->contention_start = time_base;
+                               }
+                               if (has_bt) {
+                                       num_bt = 8;
+                                       frames = decode_bt (ctx, sframes, &num_bt, p, &p, ptr_base, &method_base);
+                                       if (!frames) {
+                                               fprintf (outfile, "Cannot load backtrace\n");
+                                               return 0;
+                                       }
+                                       if (record)
+                                               add_trace_methods (frames, num_bt, &mdesc->traces, 1);
+                               } else {
+                                       if (record)
+                                               add_trace_thread (thread, &mdesc->traces, 1);
+                               }
+                       } else if (event == MONO_PROFILER_MONITOR_FAIL) {
+                               if (record) {
+                                       monitor_failed++;
+                                       if (thread->monitor && thread->contention_start) {
+                                               uint64_t wait_time = time_base - thread->contention_start;
+                                               if (wait_time > thread->monitor->max_wait_time)
+                                                       thread->monitor->max_wait_time = wait_time;
+                                               thread->monitor->wait_time += wait_time;
+                                               thread->monitor = NULL;
+                                               thread->contention_start = 0;
+                                       }
+                               }
+                       } else if (event == MONO_PROFILER_MONITOR_DONE) {
+                               if (record) {
+                                       monitor_acquired++;
+                                       if (thread->monitor && thread->contention_start) {
+                                               uint64_t wait_time = time_base - thread->contention_start;
+                                               if (wait_time > thread->monitor->max_wait_time)
+                                                       thread->monitor->max_wait_time = wait_time;
+                                               thread->monitor->wait_time += wait_time;
+                                               thread->monitor = NULL;
+                                               thread->contention_start = 0;
+                                       }
+                               }
+                       }
+                       if (debug)
+                               fprintf (outfile, "monitor %s for object %p\n", monitor_ev_name (event), (void*)OBJ_ADDR (objdiff));
+                       if (frames != sframes)
+                               g_free (frames);
+                       break;
+               }
+               case TYPE_EXCEPTION: {
+                       int subtype = *p & 0x70;
+                       int has_bt = *p & TYPE_THROW_BT;
+                       uint64_t tdiff = decode_uleb128 (p + 1, &p);
+                       MethodDesc* sframes [8];
+                       MethodDesc** frames = sframes;
+                       int record;
+                       LOG_TIME (time_base, tdiff);
+                       time_base += tdiff;
+                       record = (!thread_filter || thread_filter == thread->thread_id);
+                       if (!(time_base >= time_from && time_base < time_to))
+                               record = 0;
+                       if (subtype == TYPE_CLAUSE) {
+                               int clause_type;
+                               if (ctx->data_version > 12)
+                                       clause_type = *p++;
+                               else
+                                       clause_type = decode_uleb128 (p, &p);
+                               int clause_num = decode_uleb128 (p, &p);
+                               int64_t ptrdiff = decode_sleb128 (p, &p);
+                               method_base += ptrdiff;
+                               if (record)
+                                       clause_summary [clause_type]++;
+                               if (debug)
+                                       fprintf (outfile, "clause %s (%d) in method %s\n", clause_name (clause_type), clause_num, lookup_method (method_base)->name);
+                       } else {
+                               intptr_t objdiff = decode_sleb128 (p, &p);
+                               if (record)
+                                       throw_count++;
+                               if (has_bt) {
+                                       has_bt = 8;
+                                       frames = decode_bt (ctx, sframes, &has_bt, p, &p, ptr_base, &method_base);
+                                       if (!frames) {
+                                               fprintf (outfile, "Cannot load backtrace\n");
+                                               return 0;
+                                       }
+                                       if (record)
+                                               add_trace_methods (frames, has_bt, &exc_traces, 1);
+                               } else {
+                                       if (record)
+                                               add_trace_thread (thread, &exc_traces, 1);
+                               }
+                               if (frames != sframes)
+                                       g_free (frames);
+                               if (debug)
+                                       fprintf (outfile, "throw %p\n", (void*)OBJ_ADDR (objdiff));
+                       }
+                       break;
+               }
+               case TYPE_RUNTIME: {
+                       int subtype = *p & 0xf0;
+                       uint64_t tdiff = decode_uleb128 (p + 1, &p);
+                       LOG_TIME (time_base, tdiff);
+                       time_base += tdiff;
+                       if (subtype == TYPE_JITHELPER) {
+                               int type;
+                               if (ctx->data_version > 12)
+                                       type = *p++;
+                               else
+                                       type = decode_uleb128 (p, &p);
+                               intptr_t codediff = decode_sleb128 (p, &p);
+                               int codelen = decode_uleb128 (p, &p);
+                               const char *name;
+                               if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
+                                       name = (const char *)p;
+                                       while (*p) p++;
+                                               p++;
+                               } else {
+                                       name = code_buffer_desc (type);
+                               }
+                               num_jit_helpers++;
+                               jit_helpers_code_size += codelen;
+                               if (debug)
+                                       fprintf (outfile, "jit helper %s, size: %d, code: %p\n", name, codelen, (void*)(ptr_base + codediff));
+                       }
+                       break;
+               }
+               case TYPE_SAMPLE: {
+                       int subtype = *p & 0xf0;
+                       if (subtype == TYPE_SAMPLE_HIT) {
+                               int i;
+                               int sample_type;
+                               uint64_t tstamp;
+                               if (ctx->data_version > 12) {
+                                       uint64_t tdiff = decode_uleb128 (p + 1, &p);
+                                       LOG_TIME (time_base, tdiff);
+                                       time_base += tdiff;
+                                       sample_type = *p++;
+                                       tstamp = time_base;
+                               } else {
+                                       sample_type = decode_uleb128 (p + 1, &p);
+                                       tstamp = decode_uleb128 (p, &p);
+                               }
+                               void *tid = (void *) thread_id;
+                               if (ctx->data_version > 10)
+                                       tid = (void *) (ptr_base + decode_sleb128 (p, &p));
+                               int count = decode_uleb128 (p, &p);
+                               for (i = 0; i < count; ++i) {
+                                       uintptr_t ip = ptr_base + decode_sleb128 (p, &p);
+                                       if ((tstamp >= time_from && tstamp < time_to))
+                                               add_stat_sample (sample_type, ip);
+                                       if (debug)
+                                               fprintf (outfile, "sample hit, type: %d at %p for thread %p\n", sample_type, (void*)ip, tid);
+                               }
+                               if (ctx->data_version > 5) {
+                                       count = decode_uleb128 (p, &p);
+                                       for (i = 0; i < count; ++i) {
+                                               MethodDesc *method;
+                                               int64_t ptrdiff = decode_sleb128 (p, &p);
+                                               method_base += ptrdiff;
+                                               method = lookup_method (method_base);
+                                               if (debug)
+                                                       fprintf (outfile, "sample hit bt %d: %s\n", i, method->name);
+                                               if (ctx->data_version < 13) {
+                                                       decode_sleb128 (p, &p); /* il offset */
+                                                       decode_sleb128 (p, &p); /* native offset */
+                                               }
+                                       }
+                               }
+                       } else if (subtype == TYPE_SAMPLE_USYM) {
+                               /* un unmanaged symbol description */
+                               uintptr_t addr;
+                               if (ctx->data_version > 12) {
+                                       uint64_t tdiff = decode_uleb128 (p + 1, &p);
+                                       LOG_TIME (time_base, tdiff);
+                                       time_base += tdiff;
+                                       addr = ptr_base + decode_sleb128 (p, &p);
+                               } else
+                                       addr = ptr_base + decode_sleb128 (p + 1, &p);
+                               uintptr_t size = decode_uleb128 (p, &p);
+                               char *name;
+                               name = pstrdup ((char*)p);
+                               add_unmanaged_symbol (addr, name, size);
+                               if (debug)
+                                       fprintf (outfile, "unmanaged symbol %s at %p\n", name, (void*)addr);
+                               while (*p) p++;
+                               p++;
+                       } else if (subtype == TYPE_SAMPLE_UBIN) {
+                               /* un unmanaged binary loaded in memory */
+                               uint64_t tdiff = decode_uleb128 (p + 1, &p);
+                               uintptr_t addr = decode_sleb128 (p, &p);
+                               uint64_t offset G_GNUC_UNUSED = decode_uleb128 (p, &p);
+                               uintptr_t size = decode_uleb128 (p, &p);
+                               char *name;
+                               LOG_TIME (time_base, tdiff);
+                               time_base += tdiff;
+                               name = pstrdup ((char*)p);
+                               add_unmanaged_binary (addr, name, size);
+                               if (debug)
+                                       fprintf (outfile, "unmanaged binary %s at %p\n", name, (void*)addr);
+                               while (*p) p++;
+                               p++;
+                       } else if (subtype == TYPE_SAMPLE_COUNTERS_DESC) {
+                               uint64_t i, len;
+                               if (ctx->data_version > 12) {
+                                       uint64_t tdiff = decode_uleb128 (p + 1, &p);
+                                       LOG_TIME (time_base, tdiff);
+                                       time_base += tdiff;
+                                       len = decode_uleb128 (p, &p);
+                               } else
+                                       len = decode_uleb128 (p + 1, &p);
+                               for (i = 0; i < len; i++) {
+                                       uint64_t type, unit, variance, index;
+                                       uint64_t section = decode_uleb128 (p, &p);
+                                       char *section_str, *name;
+                                       if (section != MONO_COUNTER_PERFCOUNTERS) {
+                                               section_str = (char*) section_name (section);
+                                       } else {
+                                               section_str = pstrdup ((char*)p);
+                                               while (*p++);
+                                       }
+                                       name = pstrdup ((char*)p);
+                                       while (*p++);
+                                       if (ctx->data_version > 12) {
+                                               type = *p++;
+                                               unit = *p++;
+                                               variance = *p++;
+                                       } else {
+                                               type = decode_uleb128 (p, &p);
+                                               unit = decode_uleb128 (p, &p);
+                                               variance = decode_uleb128 (p, &p);
+                                       }
+                                       index = decode_uleb128 (p, &p);
+                                       add_counter (section_str, name, (int)type, (int)unit, (int)variance, (int)index);
+                               }
+                       } else if (subtype == TYPE_SAMPLE_COUNTERS) {
+                               int i;
+                               CounterValue *value, *previous = NULL;
+                               CounterList *list;
+                               uint64_t timestamp; // milliseconds since startup
+                               if (ctx->data_version > 12) {
+                                       uint64_t tdiff = decode_uleb128 (p + 1, &p);
+                                       LOG_TIME (time_base, tdiff);
+                                       time_base += tdiff;
+                                       timestamp = (time_base - startup_time) / 1000 / 1000;
+                               } else
+                                       timestamp = decode_uleb128 (p + 1, &p);
+                               uint64_t time_between = timestamp / 1000 * 1000 * 1000 * 1000 + startup_time;
+                               while (1) {
+                                       uint64_t type, index = decode_uleb128 (p, &p);
+                                       if (index == 0)
+                                               break;
+
+                                       for (list = counters; list; list = list->next) {
+                                               if (list->counter->index == (int)index) {
+                                                       previous = list->counter->values_last;
+                                                       break;
+                                               }
+                                       }
+
+                                       if (ctx->data_version > 12)
+                                               type = *p++;
+                                       else
+                                               type = decode_uleb128 (p, &p);
+
+                                       value = (CounterValue *) g_calloc (1, sizeof (CounterValue));
+                                       value->timestamp = timestamp;
+
+                                       switch (type) {
+                                       case MONO_COUNTER_INT:
+#if SIZEOF_VOID_P == 4
+                                       case MONO_COUNTER_WORD:
+#endif
+                                               value->buffer = (unsigned char *)g_malloc (sizeof (int32_t));
+                                               *(int32_t*)value->buffer = (int32_t)decode_sleb128 (p, &p) + (previous ? (*(int32_t*)previous->buffer) : 0);
+                                               break;
+                                       case MONO_COUNTER_UINT:
+                                               value->buffer = (unsigned char *) g_malloc (sizeof (uint32_t));
+                                               *(uint32_t*)value->buffer = (uint32_t)decode_uleb128 (p, &p) + (previous ? (*(uint32_t*)previous->buffer) : 0);
+                                               break;
+                                       case MONO_COUNTER_LONG:
+#if SIZEOF_VOID_P == 8
+                                       case MONO_COUNTER_WORD:
+#endif
+                                       case MONO_COUNTER_TIME_INTERVAL:
+                                               value->buffer = (unsigned char *) g_malloc (sizeof (int64_t));
+                                               *(int64_t*)value->buffer = (int64_t)decode_sleb128 (p, &p) + (previous ? (*(int64_t*)previous->buffer) : 0);
+                                               break;
+                                       case MONO_COUNTER_ULONG:
+                                               value->buffer = (unsigned char *) g_malloc (sizeof (uint64_t));
+                                               *(uint64_t*)value->buffer = (uint64_t)decode_uleb128 (p, &p) + (previous ? (*(uint64_t*)previous->buffer) : 0);
+                                               break;
+                                       case MONO_COUNTER_DOUBLE:
+                                               value->buffer = (unsigned char *) g_malloc (sizeof (double));
+#if TARGET_BYTE_ORDER == G_LITTLE_ENDIAN
+                                               for (i = 0; i < sizeof (double); i++)
+#else
+                                               for (i = sizeof (double) - 1; i >= 0; i--)
+#endif
+                                                       value->buffer[i] = *p++;
+                                               break;
+                                       case MONO_COUNTER_STRING:
+                                               if (*p++ == 0) {
+                                                       value->buffer = NULL;
+                                               } else {
+                                                       value->buffer = (unsigned char*) pstrdup ((char*)p);
+                                                       while (*p++);
+                                               }
+                                               break;
+                                       }
+                                       if (time_between >= time_from && time_between <= time_to)
+                                               add_counter_value (index, value);
+                               }
+                       } else {
+                               return 0;
+                       }
+                       break;
+               }
+               case TYPE_COVERAGE:{
+                       int subtype = *p & 0xf0;
+                       switch (subtype) {
+                       case TYPE_COVERAGE_METHOD: {
+                               CoverageMethod *method = g_new0 (CoverageMethod, 1);
+                               const char *assembly, *klass, *name, *sig, *filename;
+                               int token, n_offsets, method_id;
+
+                               p++;
+
+                               if (ctx->data_version > 12) {
+                                       uint64_t tdiff = decode_uleb128 (p, &p);
+                                       LOG_TIME (time_base, tdiff);
+                                       time_base += tdiff;
+                               }
+
+                               assembly = (const char *)p; while (*p) p++; p++;
+                               klass = (const char *)p; while (*p) p++; p++;
+                               name = (const char *)p; while (*p) p++; p++;
+                               sig = (const char *)p; while (*p) p++; p++;
+                               filename = (const char *)p; while (*p) p++; p++;
+
+                               token = decode_uleb128 (p, &p);
+                               method_id = decode_uleb128 (p, &p);
+                               n_offsets = decode_uleb128 (p, &p);
+
+                               method->assembly_name = g_strdup (assembly);
+                               method->class_name = g_strdup (klass);
+                               method->method_name = g_strdup (name);
+                               method->method_signature = g_strdup (sig);
+                               method->filename = g_strdup (filename);
+                               method->token = token;
+                               method->n_statements = n_offsets;
+                               method->coverage = g_ptr_array_new ();
+                               method->method_id = method_id;
+
+                               coverage_add_method (method);
+
+                               break;
+                       }
+                       case TYPE_COVERAGE_STATEMENT: {
+                               CoverageCoverage *coverage = g_new0 (CoverageCoverage, 1);
+                               int offset, count, line, column, method_id;
+
+                               p++;
+
+                               if (ctx->data_version > 12) {
+                                       uint64_t tdiff = decode_uleb128 (p, &p);
+                                       LOG_TIME (time_base, tdiff);
+                                       time_base += tdiff;
+                               }
+
+                               method_id = decode_uleb128 (p, &p);
+                               offset = decode_uleb128 (p, &p);
+                               count = decode_uleb128 (p, &p);
+                               line = decode_uleb128 (p, &p);
+                               column = decode_uleb128 (p, &p);
+
+                               coverage->method_id = method_id;
+                               coverage->offset = offset;
+                               coverage->count = count;
+                               coverage->line = line;
+                               coverage->column = column;
+
+                               coverage_add_coverage (coverage);
+                               break;
+                       }
+                       case TYPE_COVERAGE_ASSEMBLY: {
+                               CoverageAssembly *assembly = g_new0 (CoverageAssembly, 1);
+                               char *name, *guid, *filename;
+                               int number_of_methods, fully_covered, partially_covered;
+                               p++;
+
+                               if (ctx->data_version > 12) {
+                                       uint64_t tdiff = decode_uleb128 (p, &p);
+                                       LOG_TIME (time_base, tdiff);
+                                       time_base += tdiff;
+                               }
+
+                               name = (char *)p; while (*p) p++; p++;
+                               guid = (char *)p; while (*p) p++; p++;
+                               filename = (char *)p; while (*p) p++; p++;
+                               number_of_methods = decode_uleb128 (p, &p);
+                               fully_covered = decode_uleb128 (p, &p);
+                               partially_covered = decode_uleb128 (p, &p);
+
+                               assembly->name = g_strdup (name);
+                               assembly->guid = g_strdup (guid);
+                               assembly->filename = g_strdup (filename);
+                               assembly->number_of_methods = number_of_methods;
+                               assembly->fully_covered = fully_covered;
+                               assembly->partially_covered = partially_covered;
+
+                               coverage_add_assembly (assembly);
+                               break;
+                       }
+                       case TYPE_COVERAGE_CLASS: {
+                               CoverageClass *klass = g_new0 (CoverageClass, 1);
+                               char *assembly_name, *class_name;
+                               int number_of_methods, fully_covered, partially_covered;
+                               p++;
+
+                               if (ctx->data_version > 12) {
+                                       uint64_t tdiff = decode_uleb128 (p, &p);
+                                       LOG_TIME (time_base, tdiff);
+                                       time_base += tdiff;
+                               }
+
+                               assembly_name = (char *)p; while (*p) p++; p++;
+                               class_name = (char *)p; while (*p) p++; p++;
+                               number_of_methods = decode_uleb128 (p, &p);
+                               fully_covered = decode_uleb128 (p, &p);
+                               partially_covered = decode_uleb128 (p, &p);
+
+                               klass->assembly_name = g_strdup (assembly_name);
+                               klass->class_name = g_strdup (class_name);
+                               klass->number_of_methods = number_of_methods;
+                               klass->fully_covered = fully_covered;
+                               klass->partially_covered = partially_covered;
+
+                               coverage_add_class (klass);
+                               break;
+                       }
+
+                       default:
+                               break;
+                       }
+                       break;
+               }
+               case TYPE_META: {
+                       int subtype = *p & 0xf0;
+                       uint64_t tdiff = decode_uleb128 (p + 1, &p);
+                       LOG_TIME (time_base, tdiff);
+                       time_base += tdiff;
+                       if (subtype == TYPE_SYNC_POINT) {
+                               int type = *p++;
+                               if (debug)
+                                       fprintf (outfile, "sync point %i (%s)\n", type, sync_point_name (type));
+                       }
+                       break;
+               }
+               default:
+                       fprintf (outfile, "unhandled profiler event: 0x%x at file offset: %llu + %lld (len: %d\n)\n", *p, (unsigned long long) file_offset, (long long) (p - ctx->buf), len);
+                       exit (1);
+               }
+               record_event_stats (event, p - start);
+       }
+       thread->last_time = time_base;
+       for (i = 0; i < thread->stack_id; ++i)
+               thread->stack [i]->recurse_count = 0;
+       return 1;
+}
+
+static int
+read_header_string (ProfContext *ctx, char **field)
+{
+       if (!load_data (ctx, 4))
+               return 0;
+
+       if (!load_data (ctx, read_int32 (ctx->buf)))
+               return 0;
+
+       *field = pstrdup ((const char *) ctx->buf);
+
+       return 1;
+}
+
+static ProfContext*
+load_file (char *name)
+{
+       unsigned char *p;
+       ProfContext *ctx = (ProfContext *) g_calloc (sizeof (ProfContext), 1);
+       if (strcmp (name, "-") == 0)
+               ctx->file = stdin;
+       else
+               ctx->file = fopen (name, "rb");
+       if (!ctx->file) {
+               printf ("Cannot open file: %s\n", name);
+               exit (1);
+       }
+#if defined (HAVE_SYS_ZLIB)
+       if (ctx->file != stdin)
+               ctx->gzfile = gzdopen (fileno (ctx->file), "rb");
+#endif
+       if (!load_data (ctx, 30))
+               return NULL;
+       p = ctx->buf;
+       if (read_int32 (p) != LOG_HEADER_ID || p [6] > LOG_DATA_VERSION)
+               return NULL;
+       ctx->version_major = p [4];
+       ctx->version_minor = p [5];
+       ctx->data_version = p [6];
+       /* reading 64 bit files on 32 bit systems not supported yet */
+       if (p [7] > sizeof (void*))
+               return NULL;
+       if (read_int32 (p + 20)) /* flags must be 0 */
+               return NULL;
+       ctx->startup_time = read_int64 (p + 8);
+       ctx->timer_overhead = read_int32 (p + 16);
+       ctx->pid = read_int32 (p + 24);
+       ctx->port = read_int16 (p + 28);
+       if (ctx->version_major >= 1) {
+               if (!read_header_string (ctx, &ctx->args))
+                       return NULL;
+               if (!read_header_string (ctx, &ctx->arch))
+                       return NULL;
+               if (!read_header_string (ctx, &ctx->os))
+                       return NULL;
+       } else {
+               if (!load_data (ctx, 2)) /* old opsys field, was never used */
+                       return NULL;
+       }
+       return ctx;
+}
+
+enum {
+       ALLOC_SORT_BYTES,
+       ALLOC_SORT_COUNT
+};
+static int alloc_sort_mode = ALLOC_SORT_BYTES;
+
+static int
+compare_class (const void *a, const void *b)
+{
+       ClassDesc *const *A = (ClassDesc *const *)a;
+       ClassDesc *const *B = (ClassDesc *const *)b;
+       uint64_t vala, valb;
+       if (alloc_sort_mode == ALLOC_SORT_BYTES) {
+               vala = (*A)->alloc_size;
+               valb = (*B)->alloc_size;
+       } else {
+               vala = (*A)->allocs;
+               valb = (*B)->allocs;
+       }
+       if (valb == vala)
+               return 0;
+       if (valb < vala)
+               return -1;
+       return 1;
+}
+
+static void
+dump_header (ProfContext *ctx)
+{
+       time_t st = ctx->startup_time / 1000;
+       char *t = ctime (&st);
+       fprintf (outfile, "\nMono log profiler data\n");
+       fprintf (outfile, "\tProfiler version: %d.%d\n", ctx->version_major, ctx->version_minor);
+       fprintf (outfile, "\tData version: %d\n", ctx->data_version);
+       if (ctx->version_major >= 1) {
+               fprintf (outfile, "\tArguments: %s\n", ctx->args);
+               fprintf (outfile, "\tArchitecture: %s\n", ctx->arch);
+               fprintf (outfile, "\tOperating system: %s\n", ctx->os);
+       }
+       fprintf (outfile, "\tMean timer overhead: %d nanoseconds\n", ctx->timer_overhead);
+       fprintf (outfile, "\tProgram startup: %s", t);
+       if (ctx->pid)
+               fprintf (outfile, "\tProgram ID: %d\n", ctx->pid);
+       if (ctx->port)
+               fprintf (outfile, "\tServer listening on: %d\n", ctx->port);
+}
+
+static void
+dump_traces (TraceDesc *traces, const char *desc)
+{
+       int j;
+       if (!show_traces)
+               return;
+       if (!traces->count)
+               return;
+       sort_context_array (traces);
+       for (j = 0; j < traces->count; ++j) {
+               int k;
+               BackTrace *bt;
+               bt = traces->traces [j].bt;
+               if (!bt->count)
+                       continue;
+               fprintf (outfile, "\t%llu %s from:\n", (unsigned long long) traces->traces [j].count, desc);
+               for (k = 0; k < bt->count; ++k)
+                       fprintf (outfile, "\t\t%s\n", bt->methods [k]->name);
+       }
+}
+
+static void
+dump_threads (ProfContext *ctx)
+{
+       ThreadContext *thread;
+       fprintf (outfile, "\nThread summary\n");
+       for (thread = ctx->threads; thread; thread = thread->next) {
+               if (thread->thread_id) {
+                       fprintf (outfile, "\tThread: %p, name: \"%s\"\n", (void*)thread->thread_id, thread->name? thread->name: "");
+               }
+       }
+}
+
+static void
+dump_domains (ProfContext *ctx)
+{
+       fprintf (outfile, "\nDomain summary\n");
+
+       for (DomainContext *domain = ctx->domains; domain; domain = domain->next)
+               fprintf (outfile, "\tDomain: %p, friendly name: \"%s\"\n", (void *) domain->domain_id, domain->friendly_name);
+}
+
+static void
+dump_remctxs (ProfContext *ctx)
+{
+       fprintf (outfile, "\nContext summary\n");
+
+       for (RemCtxContext *remctx = ctx->remctxs; remctx; remctx = remctx->next)
+               fprintf (outfile, "\tContext: %p, domain: %p\n", (void *) remctx->remctx_id, (void *) remctx->domain_id);
+}
+
+static void
+dump_exceptions (void)
+{
+       int i;
+       fprintf (outfile, "\nException summary\n");
+       fprintf (outfile, "\tThrows: %llu\n", (unsigned long long) throw_count);
+       dump_traces (&exc_traces, "throws");
+       for (i = 0; i <= MONO_EXCEPTION_CLAUSE_FAULT; ++i) {
+               if (!clause_summary [i])
+                       continue;
+               fprintf (outfile, "\tExecuted %s clauses: %llu\n", clause_name (i), (unsigned long long) clause_summary [i]);
+       }
+}
+
+static int
+compare_monitor (const void *a, const void *b)
+{
+       MonitorDesc *const *A = (MonitorDesc *const *)a;
+       MonitorDesc *const *B = (MonitorDesc *const *)b;
+       if ((*B)->wait_time == (*A)->wait_time)
+               return 0;
+       if ((*B)->wait_time < (*A)->wait_time)
+               return -1;
+       return 1;
+}
+
+static void
+dump_monitors (void)
+{
+       MonitorDesc **monitors;
+       int i, j;
+       if (!num_monitors)
+               return;
+       monitors = (MonitorDesc **) g_malloc (sizeof (void*) * num_monitors);
+       for (i = 0, j = 0; i < SMALL_HASH_SIZE; ++i) {
+               MonitorDesc *mdesc = monitor_hash [i];
+               while (mdesc) {
+                       monitors [j++] = mdesc;
+                       mdesc = mdesc->next;
+               }
+       }
+       qsort (monitors, num_monitors, sizeof (void*), compare_monitor);
+       fprintf (outfile, "\nMonitor lock summary\n");
+       for (i = 0; i < num_monitors; ++i) {
+               MonitorDesc *mdesc = monitors [i];
+               fprintf (outfile, "\tLock object %p: %d contentions\n", (void*)mdesc->objid, (int)mdesc->contentions);
+               fprintf (outfile, "\t\t%.6f secs total wait time, %.6f max, %.6f average\n",
+                       mdesc->wait_time/1000000000.0, mdesc->max_wait_time/1000000000.0, mdesc->wait_time/1000000000.0/mdesc->contentions);
+               dump_traces (&mdesc->traces, "contentions");
+       }
+       fprintf (outfile, "\tLock contentions: %llu\n", (unsigned long long) monitor_contention);
+       fprintf (outfile, "\tLock acquired: %llu\n", (unsigned long long) monitor_acquired);
+       fprintf (outfile, "\tLock failures: %llu\n", (unsigned long long) monitor_failed);
+}
+
+static void
+dump_gcs (void)
+{
+       int i;
+       fprintf (outfile, "\nGC summary\n");
+       fprintf (outfile, "\tGC resizes: %d\n", gc_resizes);
+       fprintf (outfile, "\tMax heap size: %llu\n", (unsigned long long) max_heap_size);
+       fprintf (outfile, "\tObject moves: %llu\n", (unsigned long long) gc_object_moves);
+       for (i = 0; i < 3; ++i) {
+               if (!gc_info [i].count)
+                       continue;
+               fprintf (outfile, "\tGen%d collections: %d, max time: %lluus, total time: %lluus, average: %lluus\n",
+                       i, gc_info [i].count,
+                       (unsigned long long) (gc_info [i].max_time / 1000),
+                       (unsigned long long) (gc_info [i].total_time / 1000),
+                       (unsigned long long) (gc_info [i].total_time / gc_info [i].count / 1000));
+       }
+       for (i = 0; i < 3; ++i) {
+               if (!handle_info [i].max_live)
+                       continue;
+               fprintf (outfile, "\tGC handles %s: created: %llu, destroyed: %llu, max: %llu\n",
+                       get_handle_name (i),
+                       (unsigned long long) (handle_info [i].created),
+                       (unsigned long long) (handle_info [i].destroyed),
+                       (unsigned long long) (handle_info [i].max_live));
+               dump_traces (&handle_info [i].traces, "created");
+               dump_traces (&handle_info [i].destroy_traces, "destroyed");
+       }
+}
+
+static void
+dump_jit (void)
+{
+       int i;
+       int code_size = 0;
+       int compiled_methods = 0;
+       MethodDesc* m;
+       fprintf (outfile, "\nJIT summary\n");
+       for (i = 0; i < HASH_SIZE; ++i) {
+               m = method_hash [i];
+               for (m = method_hash [i]; m; m = m->next) {
+                       if (!m->code || m->ignore_jit)
+                               continue;
+                       compiled_methods++;
+                       code_size += m->len;
+               }
+       }
+       fprintf (outfile, "\tCompiled methods: %d\n", compiled_methods);
+       fprintf (outfile, "\tGenerated code size: %d\n", code_size);
+       fprintf (outfile, "\tJIT helpers: %d\n", num_jit_helpers);
+       fprintf (outfile, "\tJIT helpers code size: %d\n", jit_helpers_code_size);
+}
+
+static void
+dump_allocations (void)
+{
+       int i, c;
+       intptr_t allocs = 0;
+       uint64_t size = 0;
+       int header_done = 0;
+       ClassDesc **classes = (ClassDesc **) g_malloc (num_classes * sizeof (void*));
+       ClassDesc *cd;
+       c = 0;
+       for (i = 0; i < HASH_SIZE; ++i) {
+               cd = class_hash [i];
+               while (cd) {
+                       classes [c++] = cd;
+                       cd = cd->next;
+               }
+       }
+       qsort (classes, num_classes, sizeof (void*), compare_class);
+       for (i = 0; i < num_classes; ++i) {
+               cd = classes [i];
+               if (!cd->allocs)
+                       continue;
+               allocs += cd->allocs;
+               size += cd->alloc_size;
+               if (!header_done++) {
+                       fprintf (outfile, "\nAllocation summary\n");
+                       fprintf (outfile, "%10s %10s %8s Type name\n", "Bytes", "Count", "Average");
+               }
+               fprintf (outfile, "%10llu %10zd %8llu %s\n",
+                       (unsigned long long) (cd->alloc_size),
+                       cd->allocs,
+                       (unsigned long long) (cd->alloc_size / cd->allocs),
+                       cd->name);
+               dump_traces (&cd->traces, "bytes");
+       }
+       if (allocs)
+               fprintf (outfile, "Total memory allocated: %llu bytes in %zd objects\n", (unsigned long long) size, allocs);
+}
+
+enum {
+       METHOD_SORT_TOTAL,
+       METHOD_SORT_SELF,
+       METHOD_SORT_CALLS
+};
+
+static int method_sort_mode = METHOD_SORT_TOTAL;
+
+static int
+compare_method (const void *a, const void *b)
+{
+       MethodDesc *const *A = (MethodDesc *const *)a;
+       MethodDesc *const *B = (MethodDesc *const *)b;
+       uint64_t vala, valb;
+       if (method_sort_mode == METHOD_SORT_SELF) {
+               vala = (*A)->self_time;
+               valb = (*B)->self_time;
+       } else if (method_sort_mode == METHOD_SORT_CALLS) {
+               vala = (*A)->calls;
+               valb = (*B)->calls;
+       } else {
+               vala = (*A)->total_time;
+               valb = (*B)->total_time;
+       }
+       if (vala == valb)
+               return 0;
+       if (valb < vala)
+               return -1;
+       return 1;
+}
+
+static void
+dump_metadata (void)
+{
+       fprintf (outfile, "\nMetadata summary\n");
+       fprintf (outfile, "\tLoaded images: %d\n", num_images);
+       if (verbose) {
+               ImageDesc *image;
+               int i;
+               for (i = 0; i < SMALL_HASH_SIZE; ++i) {
+                       image = image_hash [i];
+                       while (image) {
+                               fprintf (outfile, "\t\t%s\n", image->filename);
+                               image = image->next;
+                       }
+               }
+       }
+       fprintf (outfile, "\tLoaded assemblies: %d\n", num_assemblies);
+       if (verbose) {
+               AssemblyDesc *assembly;
+               int i;
+               for (i = 0; i < SMALL_HASH_SIZE; ++i) {
+                       assembly = assembly_hash [i];
+                       while (assembly) {
+                               fprintf (outfile, "\t\t%s\n", assembly->asmname);
+                               assembly = assembly->next;
+                       }
+               }
+       }
+}
+
+static void
+dump_methods (void)
+{
+       int i, c;
+       uint64_t calls = 0;
+       int header_done = 0;
+       MethodDesc **methods = (MethodDesc **) g_malloc (num_methods * sizeof (void*));
+       MethodDesc *cd;
+       c = 0;
+       for (i = 0; i < HASH_SIZE; ++i) {
+               cd = method_hash [i];
+               while (cd) {
+                       cd->total_time = cd->self_time + cd->callee_time;
+                       methods [c++] = cd;
+                       cd = cd->next;
+               }
+       }
+       qsort (methods, num_methods, sizeof (void*), compare_method);
+       for (i = 0; i < num_methods; ++i) {
+               uint64_t msecs;
+               uint64_t smsecs;
+               cd = methods [i];
+               if (!cd->calls)
+                       continue;
+               calls += cd->calls;
+               msecs = cd->total_time / 1000000;
+               smsecs = (cd->total_time - cd->callee_time) / 1000000;
+               if (!msecs && !verbose)
+                       continue;
+               if (!header_done++) {
+                       fprintf (outfile, "\nMethod call summary\n");
+                       fprintf (outfile, "%8s %8s %10s Method name\n", "Total(ms)", "Self(ms)", "Calls");
+               }
+               fprintf (outfile, "%8llu %8llu %10llu %s\n",
+                       (unsigned long long) (msecs),
+                       (unsigned long long) (smsecs),
+                       (unsigned long long) (cd->calls),
+                       cd->name);
+               dump_traces (&cd->traces, "calls");
+       }
+       if (calls)
+               fprintf (outfile, "Total calls: %llu\n", (unsigned long long) calls);
+}
+
+static int
+compare_heap_class (const void *a, const void *b)
+{
+       HeapClassDesc *const *A = (HeapClassDesc *const *)a;
+       HeapClassDesc *const *B = (HeapClassDesc *const *)b;
+       uint64_t vala, valb;
+       if (alloc_sort_mode == ALLOC_SORT_BYTES) {
+               vala = (*A)->total_size;
+               valb = (*B)->total_size;
+       } else {
+               vala = (*A)->count;
+               valb = (*B)->count;
+       }
+       if (valb == vala)
+               return 0;
+       if (valb < vala)
+               return -1;
+       return 1;
+}
+
+static int
+compare_rev_class (const void *a, const void *b)
+{
+       const HeapClassRevRef *A = (const HeapClassRevRef *)a;
+       const HeapClassRevRef *B = (const HeapClassRevRef *)b;
+       if (B->count == A->count)
+               return 0;
+       if (B->count < A->count)
+               return -1;
+       return 1;
+}
+
+static void
+dump_rev_claases (HeapClassRevRef *revs, int count)
+{
+       int j;
+       if (!show_traces)
+               return;
+       if (!count)
+               return;
+       for (j = 0; j < count; ++j) {
+               HeapClassDesc *cd = revs [j].klass;
+               fprintf (outfile, "\t\t%llu references from: %s\n",
+                       (unsigned long long) (revs [j].count),
+                       cd->klass->name);
+       }
+}
+
+static void
+heap_shot_summary (HeapShot *hs, int hs_num, HeapShot *last_hs)
+{
+       uint64_t size = 0;
+       uint64_t count = 0;
+       int ccount = 0;
+       int i;
+       HeapClassDesc *cd;
+       HeapClassDesc **sorted;
+       sorted = (HeapClassDesc **) g_malloc (sizeof (void*) * hs->class_count);
+       for (i = 0; i < hs->hash_size; ++i) {
+               cd = hs->class_hash [i];
+               if (!cd)
+                       continue;
+               count += cd->count;
+               size += cd->total_size;
+               sorted [ccount++] = cd;
+       }
+       hs->sorted = sorted;
+       qsort (sorted, ccount, sizeof (void*), compare_heap_class);
+       fprintf (outfile, "\n\tHeap shot %d at %.3f secs: size: %llu, object count: %llu, class count: %d, roots: %zd\n",
+               hs_num,
+               (hs->timestamp - startup_time)/1000000000.0,
+               (unsigned long long) (size),
+               (unsigned long long) (count),
+               ccount, hs->num_roots);
+       if (!verbose && ccount > 30)
+               ccount = 30;
+       fprintf (outfile, "\t%10s %10s %8s Class name\n", "Bytes", "Count", "Average");
+       for (i = 0; i < ccount; ++i) {
+               HeapClassRevRef *rev_sorted;
+               int j, k;
+               HeapClassDesc *ocd = NULL;
+               cd = sorted [i];
+               if (last_hs)
+                       ocd = heap_class_lookup (last_hs, cd->klass);
+               fprintf (outfile, "\t%10llu %10llu %8llu %s",
+                       (unsigned long long) (cd->total_size),
+                       (unsigned long long) (cd->count),
+                       (unsigned long long) (cd->total_size / cd->count),
+                       cd->klass->name);
+               if (ocd) {
+                       int64_t bdiff = cd->total_size - ocd->total_size;
+                       int64_t cdiff = cd->count - ocd->count;
+                       fprintf (outfile, " (bytes: %+lld, count: %+lld)\n", (long long) bdiff, (long long) cdiff);
+               } else {
+                       fprintf (outfile, "\n");
+               }
+               if (!collect_traces)
+                       continue;
+               rev_sorted = (HeapClassRevRef *) g_malloc (cd->rev_count * sizeof (HeapClassRevRef));
+               k = 0;
+               for (j = 0; j < cd->rev_hash_size; ++j) {
+                       if (cd->rev_hash [j].klass)
+                               rev_sorted [k++] = cd->rev_hash [j];
+               }
+               assert (cd->rev_count == k);
+               qsort (rev_sorted, cd->rev_count, sizeof (HeapClassRevRef), compare_rev_class);
+               if (cd->root_references)
+                       fprintf (outfile, "\t\t%zd root references (%zd pinning)\n", cd->root_references, cd->pinned_references);
+               dump_rev_claases (rev_sorted, cd->rev_count);
+               g_free (rev_sorted);
+       }
+       g_free (sorted);
+}
+
+static int
+compare_heap_shots (const void *a, const void *b)
+{
+       HeapShot *const *A = (HeapShot *const *)a;
+       HeapShot *const *B = (HeapShot *const *)b;
+       if ((*B)->timestamp == (*A)->timestamp)
+               return 0;
+       if ((*B)->timestamp > (*A)->timestamp)
+               return -1;
+       return 1;
+}
+
+static void
+dump_heap_shots (void)
+{
+       HeapShot **hs_sorted;
+       HeapShot *hs;
+       HeapShot *last_hs = NULL;
+       int i;
+       if (!heap_shots)
+               return;
+       hs_sorted = (HeapShot **) g_malloc (num_heap_shots * sizeof (void*));
+       fprintf (outfile, "\nHeap shot summary\n");
+       i = 0;
+       for (hs = heap_shots; hs; hs = hs->next)
+               hs_sorted [i++] = hs;
+       qsort (hs_sorted, num_heap_shots, sizeof (void*), compare_heap_shots);
+       for (i = 0; i < num_heap_shots; ++i) {
+               hs = hs_sorted [i];
+               heap_shot_summary (hs, i, last_hs);
+               last_hs = hs;
+       }
+}
+
+/* This is a very basic escape function that escapes < > and &
+   Ideally we'd use g_markup_escape_string but that function isn't
+        available in Mono's eglib. This was written without looking at the
+        source of that function in glib. */
+static char *
+escape_string_for_xml (const char *string)
+{
+       GString *string_builder = g_string_new (NULL);
+       const char *start, *p;
+
+       start = p = string;
+       while (*p) {
+               while (*p && *p != '&' && *p != '<' && *p != '>')
+                       p++;
+
+               g_string_append_len (string_builder, start, p - start);
+
+               if (*p == '\0')
+                       break;
+
+               switch (*p) {
+               case '<':
+                       g_string_append (string_builder, "&lt;");
+                       break;
+
+               case '>':
+                       g_string_append (string_builder, "&gt;");
+                       break;
+
+               case '&':
+                       g_string_append (string_builder, "&amp;");
+                       break;
+
+               default:
+                       break;
+               }
+
+               p++;
+               start = p;
+       }
+
+       return g_string_free (string_builder, FALSE);
+}
+
+static int
+sort_assemblies (gconstpointer a, gconstpointer b)
+{
+       CoverageAssembly *assembly_a = *(CoverageAssembly **)a;
+       CoverageAssembly *assembly_b = *(CoverageAssembly **)b;
+
+       if (assembly_a->name == NULL && assembly_b->name == NULL)
+               return 0;
+       else if (assembly_a->name == NULL)
+               return -1;
+       else if (assembly_b->name == NULL)
+               return 1;
+
+       return strcmp (assembly_a->name, assembly_b->name);
+}
+
+static void
+dump_coverage (void)
+{
+       if (!coverage_methods && !coverage_assemblies)
+               return;
+
+       gather_coverage_statements ();
+       fprintf (outfile, "\nCoverage Summary:\n");
+
+       if (coverage_outfile) {
+               fprintf (coverage_outfile, "<?xml version=\"1.0\"?>\n");
+               fprintf (coverage_outfile, "<coverage version=\"0.3\">\n");
+       }
+
+       g_ptr_array_sort (coverage_assemblies, sort_assemblies);
+
+       for (guint i = 0; i < coverage_assemblies->len; i++) {
+               CoverageAssembly *assembly = (CoverageAssembly *)coverage_assemblies->pdata[i];
+               GPtrArray *classes;
+
+               if (assembly->number_of_methods != 0) {
+                       int percentage = ((assembly->fully_covered + assembly->partially_covered) * 100) / assembly->number_of_methods;
+                       fprintf (outfile, "\t%s (%s) %d%% covered (%d methods - %d covered)\n", assembly->name, assembly->filename, percentage, assembly->number_of_methods, assembly->fully_covered);
+               } else
+                       fprintf (outfile, "\t%s (%s) ?%% covered (%d methods - %d covered)\n", assembly->name, assembly->filename, assembly->number_of_methods, assembly->fully_covered);
+
+               if (coverage_outfile) {
+                       char *escaped_name, *escaped_filename;
+                       escaped_name = escape_string_for_xml (assembly->name);
+                       escaped_filename = escape_string_for_xml (assembly->filename);
+
+                       fprintf (coverage_outfile, "\t<assembly name=\"%s\" guid=\"%s\" filename=\"%s\" method-count=\"%d\" full=\"%d\" partial=\"%d\"/>\n", escaped_name, assembly->guid, escaped_filename, assembly->number_of_methods, assembly->fully_covered, assembly->partially_covered);
+
+                       g_free (escaped_name);
+                       g_free (escaped_filename);
+               }
+
+               classes = (GPtrArray *)g_hash_table_lookup (coverage_assembly_classes, assembly->name);
+               if (classes) {
+                       for (guint j = 0; j < classes->len; j++) {
+                               CoverageClass *klass = (CoverageClass *)classes->pdata [j];
+
+                               if (klass->number_of_methods > 0) {
+                                       int percentage = ((klass->fully_covered + klass->partially_covered) * 100) / klass->number_of_methods;
+                                       fprintf (outfile, "\t\t%s %d%% covered (%d methods - %d covered)\n", klass->class_name, percentage, klass->number_of_methods, klass->fully_covered);
+                               } else
+                                       fprintf (outfile, "\t\t%s ?%% covered (%d methods - %d covered)\n", klass->class_name, klass->number_of_methods, klass->fully_covered);
+
+                               if (coverage_outfile) {
+                                       char *escaped_name;
+                                       escaped_name = escape_string_for_xml (klass->class_name);
+
+                                       fprintf (coverage_outfile, "\t\t<class name=\"%s\" method-count=\"%d\" full=\"%d\" partial=\"%d\"/>\n", escaped_name, klass->number_of_methods, klass->fully_covered, klass->partially_covered);
+                                       g_free (escaped_name);
+                               }
+                       }
+               }
+       }
+
+       for (guint i = 0; i < coverage_methods->len; i++) {
+               CoverageMethod *method = (CoverageMethod *)coverage_methods->pdata [i];
+
+               if (coverage_outfile) {
+                       char *escaped_assembly, *escaped_class, *escaped_method, *escaped_sig, *escaped_filename;
+
+                       escaped_assembly = escape_string_for_xml (method->assembly_name);
+                       escaped_class = escape_string_for_xml (method->class_name);
+                       escaped_method = escape_string_for_xml (method->method_name);
+                       escaped_sig = escape_string_for_xml (method->method_signature);
+                       escaped_filename = escape_string_for_xml (method->filename);
+
+                       fprintf (coverage_outfile, "\t<method assembly=\"%s\" class=\"%s\" name=\"%s (%s)\" filename=\"%s\" token=\"%d\">\n", escaped_assembly, escaped_class, escaped_method, escaped_sig, escaped_filename, method->token);
+
+                       g_free (escaped_assembly);
+                       g_free (escaped_class);
+                       g_free (escaped_method);
+                       g_free (escaped_sig);
+                       g_free (escaped_filename);
+
+                       for (guint j = 0; j < method->coverage->len; j++) {
+                               CoverageCoverage *coverage = (CoverageCoverage *)method->coverage->pdata [j];
+                               fprintf (coverage_outfile, "\t\t<statement offset=\"%d\" counter=\"%d\" line=\"%d\" column=\"%d\"/>\n", coverage->offset, coverage->count, coverage->line, coverage->column);
+                       }
+                       fprintf (coverage_outfile, "\t</method>\n");
+               }
+       }
+
+       if (coverage_outfile) {
+               fprintf (coverage_outfile, "</coverage>\n");
+               fclose (coverage_outfile);
+               coverage_outfile = NULL;
+       }
+}
+
+#define DUMP_EVENT_STAT(EVENT,SUBTYPE) dump_event (#EVENT, #SUBTYPE, EVENT, SUBTYPE);
+
+static void
+dump_event (const char *event_name, const char *subtype_name, int event, int subtype)
+{
+       int idx = event | subtype;
+       EventStat evt = stats [idx];
+       if (!evt.count)
+               return;
+
+       fprintf (outfile, "\t%16s\t%26s\tcount %6d\tmin %3d\tmax %6d\tbytes %d\n", event_name, subtype_name, evt.count, evt.min_size, evt.max_size, evt.bytes);
+}
+
+static void
+dump_stats (void)
+{
+       fprintf (outfile, "\nMlpd statistics\n");
+       fprintf (outfile, "\tBuffer count %d\toverhead %d (%d bytes per header)\n", buffer_count, buffer_count * BUFFER_HEADER_SIZE, BUFFER_HEADER_SIZE);
+       fprintf (outfile, "\nEvent details:\n");
+
+       DUMP_EVENT_STAT (TYPE_ALLOC, TYPE_ALLOC_NO_BT);
+       DUMP_EVENT_STAT (TYPE_ALLOC, TYPE_ALLOC_BT);
+
+       DUMP_EVENT_STAT (TYPE_GC, TYPE_GC_EVENT);
+       DUMP_EVENT_STAT (TYPE_GC, TYPE_GC_RESIZE);
+       DUMP_EVENT_STAT (TYPE_GC, TYPE_GC_MOVE);
+       DUMP_EVENT_STAT (TYPE_GC, TYPE_GC_HANDLE_CREATED);
+       DUMP_EVENT_STAT (TYPE_GC, TYPE_GC_HANDLE_DESTROYED);
+       DUMP_EVENT_STAT (TYPE_GC, TYPE_GC_HANDLE_CREATED_BT);
+       DUMP_EVENT_STAT (TYPE_GC, TYPE_GC_HANDLE_DESTROYED_BT);
+
+       DUMP_EVENT_STAT (TYPE_METADATA, TYPE_END_LOAD);
+       DUMP_EVENT_STAT (TYPE_METADATA, TYPE_END_UNLOAD);
+
+       DUMP_EVENT_STAT (TYPE_METHOD, TYPE_LEAVE);
+       DUMP_EVENT_STAT (TYPE_METHOD, TYPE_ENTER);
+       DUMP_EVENT_STAT (TYPE_METHOD, TYPE_EXC_LEAVE);
+       DUMP_EVENT_STAT (TYPE_METHOD, TYPE_JIT);
+
+       DUMP_EVENT_STAT (TYPE_EXCEPTION, TYPE_THROW_NO_BT);
+       DUMP_EVENT_STAT (TYPE_EXCEPTION, TYPE_THROW_BT);
+       DUMP_EVENT_STAT (TYPE_EXCEPTION, TYPE_CLAUSE);
+
+       DUMP_EVENT_STAT (TYPE_MONITOR, TYPE_MONITOR_NO_BT);
+       DUMP_EVENT_STAT (TYPE_MONITOR, TYPE_MONITOR_BT);
+
+       DUMP_EVENT_STAT (TYPE_HEAP, TYPE_HEAP_START);
+       DUMP_EVENT_STAT (TYPE_HEAP, TYPE_HEAP_END);
+       DUMP_EVENT_STAT (TYPE_HEAP, TYPE_HEAP_OBJECT);
+       DUMP_EVENT_STAT (TYPE_HEAP, TYPE_HEAP_ROOT);
+
+       DUMP_EVENT_STAT (TYPE_SAMPLE, TYPE_SAMPLE_HIT);
+       DUMP_EVENT_STAT (TYPE_SAMPLE, TYPE_SAMPLE_USYM);
+       DUMP_EVENT_STAT (TYPE_SAMPLE, TYPE_SAMPLE_UBIN);
+       DUMP_EVENT_STAT (TYPE_SAMPLE, TYPE_SAMPLE_COUNTERS_DESC);
+       DUMP_EVENT_STAT (TYPE_SAMPLE, TYPE_SAMPLE_COUNTERS);
+
+       DUMP_EVENT_STAT (TYPE_RUNTIME, TYPE_JITHELPER);
+
+       DUMP_EVENT_STAT (TYPE_COVERAGE, TYPE_COVERAGE_ASSEMBLY);
+       DUMP_EVENT_STAT (TYPE_COVERAGE, TYPE_COVERAGE_METHOD);
+       DUMP_EVENT_STAT (TYPE_COVERAGE, TYPE_COVERAGE_STATEMENT);
+       DUMP_EVENT_STAT (TYPE_COVERAGE, TYPE_COVERAGE_CLASS);
+
+       DUMP_EVENT_STAT (TYPE_META, TYPE_SYNC_POINT);
+}
+
+
+
+static void
+flush_context (ProfContext *ctx)
+{
+       ThreadContext *thread;
+       /* FIXME: sometimes there are leftovers: indagate */
+       for (thread = ctx->threads; thread; thread = thread->next) {
+               while (thread->stack_id) {
+                       if (debug)
+                               fprintf (outfile, "thread %p has %d items on stack\n", (void*)thread->thread_id, thread->stack_id);
+                       pop_method (thread, thread->stack [thread->stack_id - 1], thread->last_time);
+               }
+       }
+}
+
+static const char *reports = "header,jit,gc,sample,alloc,call,metadata,exception,monitor,thread,heapshot,counters,coverage";
+
+static const char*
+match_option (const char *p, const char *opt)
+{
+       int len = strlen (opt);
+       if (strncmp (p, opt, len) == 0) {
+               if (p [len] == ',')
+                       len++;
+               return p + len;
+       }
+       return p;
+}
+
+static int
+print_reports (ProfContext *ctx, const char *reps, int parse_only)
+{
+       const char *opt;
+       const char *p;
+       for (p = reps; *p; p = opt) {
+               if ((opt = match_option (p, "header")) != p) {
+                       if (!parse_only)
+                               dump_header (ctx);
+                       continue;
+               }
+               if ((opt = match_option (p, "thread")) != p) {
+                       if (!parse_only)
+                               dump_threads (ctx);
+                       continue;
+               }
+               if ((opt = match_option (p, "domain")) != p) {
+                       if (!parse_only)
+                               dump_domains (ctx);
+                       continue;
+               }
+               if ((opt = match_option (p, "context")) != p) {
+                       if (!parse_only)
+                               dump_remctxs (ctx);
+                       continue;
+               }
+               if ((opt = match_option (p, "gc")) != p) {
+                       if (!parse_only)
+                               dump_gcs ();
+                       continue;
+               }
+               if ((opt = match_option (p, "jit")) != p) {
+                       if (!parse_only)
+                               dump_jit ();
+                       continue;
+               }
+               if ((opt = match_option (p, "alloc")) != p) {
+                       if (!parse_only)
+                               dump_allocations ();
+                       continue;
+               }
+               if ((opt = match_option (p, "call")) != p) {
+                       if (!parse_only)
+                               dump_methods ();
+                       continue;
+               }
+               if ((opt = match_option (p, "metadata")) != p) {
+                       if (!parse_only)
+                               dump_metadata ();
+                       continue;
+               }
+               if ((opt = match_option (p, "exception")) != p) {
+                       if (!parse_only)
+                               dump_exceptions ();
+                       continue;
+               }
+               if ((opt = match_option (p, "monitor")) != p) {
+                       if (!parse_only)
+                               dump_monitors ();
+                       continue;
+               }
+               if ((opt = match_option (p, "heapshot")) != p) {
+                       if (!parse_only)
+                               dump_heap_shots ();
+                       continue;
+               }
+               if ((opt = match_option (p, "sample")) != p) {
+                       if (!parse_only)
+                               dump_samples ();
+                       continue;
+               }
+               if ((opt = match_option (p, "counters")) != p) {
+                       if (!parse_only)
+                               dump_counters ();
+                       continue;
+               }
+               if ((opt = match_option (p, "coverage")) != p) {
+                       if (!parse_only)
+                               dump_coverage ();
+                       continue;
+               }
+               if ((opt = match_option (p, "stats")) != p) {
+                       if (!parse_only)
+                               dump_stats ();
+                       continue;
+               }
+               return 0;
+       }
+       return 1;
+}
+
+static int
+add_find_spec (const char *p)
+{
+       if (p [0] == 'S' && p [1] == ':') {
+               char *vale;
+               find_size = strtoul (p + 2, &vale, 10);
+               return 1;
+       } else if (p [0] == 'T' && p [1] == ':') {
+               find_name = p + 2;
+               return 1;
+       }
+       return 0;
+}
+
+static void
+usage (void)
+{
+       printf ("Mono log profiler report version %d.%d\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR);
+       printf ("Usage: mprof-report [OPTIONS] FILENAME\n");
+       printf ("FILENAME can be '-' to read from standard input.\n");
+       printf ("Options:\n");
+       printf ("\t--help               display this help\n");
+       printf ("\t--out=FILE           write to FILE instead of stdout\n");
+       printf ("\t--traces             collect and show backtraces\n");
+       printf ("\t--maxframes=NUM      limit backtraces to NUM entries\n");
+       printf ("\t--reports=R1[,R2...] print the specified reports. Defaults are:\n");
+       printf ("\t                     %s\n", reports);
+       printf ("\t--method-sort=MODE   sort methods according to MODE: total, self, calls\n");
+       printf ("\t--alloc-sort=MODE    sort allocations according to MODE: bytes, count\n");
+       printf ("\t--counters-sort=MODE sort counters according to MODE: time, category\n");
+       printf ("\t                     only accessible in verbose mode\n");
+       printf ("\t--track=OB1[,OB2...] track what happens to objects OBJ1, O2 etc.\n");
+       printf ("\t--find=FINDSPEC      find and track objects matching FINFSPEC, where FINDSPEC is:\n");
+       printf ("\t                     S:minimum_size or T:partial_name\n");
+       printf ("\t--thread=THREADID    consider just the data for thread THREADID\n");
+       printf ("\t--time=FROM-TO       consider data FROM seconds from startup up to TO seconds\n");
+       printf ("\t--verbose            increase verbosity level\n");
+       printf ("\t--debug              display decoding debug info for mprof-report devs\n");
+       printf ("\t--coverage-out=FILE  write the coverage info to FILE as XML\n");
+}
+
+int
+main (int argc, char *argv[])
+{
+       ProfContext *ctx;
+       int i;
+       outfile = stdout;
+       for (i = 1; i < argc; ++i) {
+               if (strcmp ("--debug", argv [i]) == 0) {
+                       debug++;
+               } else if (strcmp ("--help", argv [i]) == 0) {
+                       usage ();
+                       return 0;
+               } else if (strncmp ("--alloc-sort=", argv [i], 13) == 0) {
+                       const char *val = argv [i] + 13;
+                       if (strcmp (val, "bytes") == 0) {
+                               alloc_sort_mode = ALLOC_SORT_BYTES;
+                       } else if (strcmp (val, "count") == 0) {
+                               alloc_sort_mode = ALLOC_SORT_COUNT;
+                       } else {
+                               usage ();
+                               return 1;
+                       }
+               } else if (strncmp ("--method-sort=", argv [i], 14) == 0) {
+                       const char *val = argv [i] + 14;
+                       if (strcmp (val, "total") == 0) {
+                               method_sort_mode = METHOD_SORT_TOTAL;
+                       } else if (strcmp (val, "self") == 0) {
+                               method_sort_mode = METHOD_SORT_SELF;
+                       } else if (strcmp (val, "calls") == 0) {
+                               method_sort_mode = METHOD_SORT_CALLS;
+                       } else {
+                               usage ();
+                               return 1;
+                       }
+               } else if (strncmp ("--counters-sort=", argv [i], 16) == 0) {
+                       const char *val = argv [i] + 16;
+                       if (strcmp (val, "time") == 0) {
+                               counters_sort_mode = COUNTERS_SORT_TIME;
+                       } else if (strcmp (val, "category") == 0) {
+                               counters_sort_mode = COUNTERS_SORT_CATEGORY;
+                       } else {
+                               usage ();
+                               return 1;
+                       }
+               } else if (strncmp ("--reports=", argv [i], 10) == 0) {
+                       const char *val = argv [i] + 10;
+                       if (!print_reports (NULL, val, 1)) {
+                               usage ();
+                               return 1;
+                       }
+                       reports = val;
+               } else if (strncmp ("--out=", argv [i], 6) == 0) {
+                       const char *val = argv [i] + 6;
+                       outfile = fopen (val, "w");
+                       if (!outfile) {
+                               printf ("Cannot open output file: %s\n", val);
+                               return 1;
+                       }
+               } else if (strncmp ("--maxframes=", argv [i], 12) == 0) {
+                       const char *val = argv [i] + 12;
+                       char *vale;
+                       trace_max = strtoul (val, &vale, 10);
+               } else if (strncmp ("--find=", argv [i], 7) == 0) {
+                       const char *val = argv [i] + 7;
+                       if (!add_find_spec (val)) {
+                               usage ();
+                               return 1;
+                       }
+               } else if (strncmp ("--track=", argv [i], 8) == 0) {
+                       const char *val = argv [i] + 8;
+                       char *vale;
+                       while (*val) {
+                               uintptr_t tracked_obj;
+                               if (*val == ',') {
+                                       val++;
+                                       continue;
+                               }
+                               tracked_obj = strtoul (val, &vale, 0);
+                               found_object (tracked_obj);
+                               val = vale;
+                       }
+               } else if (strncmp ("--thread=", argv [i], 9) == 0) {
+                       const char *val = argv [i] + 9;
+                       char *vale;
+                       thread_filter = strtoul (val, &vale, 0);
+               } else if (strncmp ("--time=", argv [i], 7) == 0) {
+                       char *val = pstrdup (argv [i] + 7);
+                       double from_secs, to_secs;
+                       char *top = strchr (val, '-');
+                       if (!top) {
+                               usage ();
+                               return 1;
+                       }
+                       *top++ = 0;
+                       from_secs = atof (val);
+                       to_secs = atof (top);
+                       g_free (val);
+                       if (from_secs > to_secs) {
+                               usage ();
+                               return 1;
+                       }
+                       time_from = from_secs * 1000000000;
+                       time_to = to_secs * 1000000000;
+                       use_time_filter = 1;
+               } else if (strcmp ("--verbose", argv [i]) == 0) {
+                       verbose++;
+               } else if (strcmp ("--traces", argv [i]) == 0) {
+                       show_traces = 1;
+                       collect_traces = 1;
+               } else if (strncmp ("--coverage-out=", argv [i], 15) == 0) {
+                       const char *val = argv [i] + 15;
+                       coverage_outfile = fopen (val, "w");
+                       if (!coverage_outfile) {
+                               printf ("Cannot open output file: %s\n", val);
+                               return 1;
+                       }
+               } else {
+                       break;
+               }
+       }
+       if (i >= argc) {
+               usage ();
+               return 2;
+       }
+       ctx = load_file (argv [i]);
+       if (!ctx) {
+               printf ("Not a log profiler data file (or unsupported version).\n");
+               return 1;
+       }
+       while (decode_buffer (ctx));
+       flush_context (ctx);
+       if (num_tracked_objects)
+               return 0;
+       print_reports (ctx, reports, 0);
+       return 0;
+}
diff --git a/mono/profiler/proflog.c b/mono/profiler/proflog.c
deleted file mode 100644 (file)
index 17f4383..0000000
+++ /dev/null
@@ -1,5394 +0,0 @@
-/*
- * proflog.c: mono log profiler
- *
- * Authors:
- *   Paolo Molaro (lupus@ximian.com)
- *   Alex Rønne Petersen (alexrp@xamarin.com)
- *
- * Copyright 2010 Novell, Inc (http://www.novell.com)
- * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
- * Licensed under the MIT license. See LICENSE file in the project root for full license information.
- */
-
-#include <config.h>
-#include "../mini/jit.h"
-#include "../metadata/metadata-internals.h"
-#include <mono/metadata/profiler.h>
-#include <mono/metadata/threads.h>
-#include <mono/metadata/debug-helpers.h>
-#include <mono/metadata/mono-config.h>
-#include <mono/metadata/mono-gc.h>
-#include <mono/metadata/mono-perfcounters.h>
-#include <mono/metadata/appdomain.h>
-#include <mono/metadata/assembly.h>
-#include <mono/metadata/tokentype.h>
-#include <mono/metadata/tabledefs.h>
-#include <mono/utils/atomic.h>
-#include <mono/utils/mono-membar.h>
-#include <mono/utils/mono-mmap.h>
-#include <mono/utils/mono-counters.h>
-#include <mono/utils/mono-os-mutex.h>
-#include <mono/utils/mono-os-semaphore.h>
-#include <mono/utils/mono-conc-hashtable.h>
-#include <mono/utils/mono-linked-list-set.h>
-#include <mono/utils/lock-free-alloc.h>
-#include <mono/utils/lock-free-queue.h>
-#include <mono/utils/hazard-pointer.h>
-#include <mono/utils/mono-threads.h>
-#include <mono/utils/mono-threads-api.h>
-#include <stdlib.h>
-#include <string.h>
-#include <assert.h>
-#include <glib.h>
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-#ifdef HAVE_SCHED_GETAFFINITY
-#include <sched.h>
-#endif
-#include <fcntl.h>
-#include <errno.h>
-#if defined(HOST_WIN32) || defined(DISABLE_SOCKETS)
-#define DISABLE_HELPER_THREAD 1
-#endif
-
-#ifndef _GNU_SOURCE
-#define _GNU_SOURCE
-#endif
-#ifdef HAVE_DLFCN_H
-#include <dlfcn.h>
-#endif
-#ifdef HAVE_EXECINFO_H
-#include <execinfo.h>
-#endif
-#ifdef HAVE_LINK_H
-#include <link.h>
-#endif
-
-#ifndef DISABLE_HELPER_THREAD
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <sys/select.h>
-#endif
-
-#ifdef HOST_WIN32
-#include <windows.h>
-#else
-#include <pthread.h>
-#endif
-
-#ifdef HAVE_SYS_STAT_H
-#include <sys/stat.h>
-#endif
-
-#include "utils.c"
-#include "proflog.h"
-
-#if defined (HAVE_SYS_ZLIB)
-#include <zlib.h>
-#endif
-
-#if defined(__linux__)
-
-#include <unistd.h>
-#include <sys/syscall.h>
-
-#ifdef ENABLE_PERF_EVENTS
-#include <linux/perf_event.h>
-
-#define USE_PERF_EVENTS 1
-
-static int read_perf_mmap (MonoProfiler* prof, int cpu);
-#endif
-
-#endif
-
-#define BUFFER_SIZE (4096 * 16)
-
-/* Worst-case size in bytes of a 64-bit value encoded with LEB128. */
-#define LEB128_SIZE 10
-/* Size of a value encoded as a single byte. */
-#define BYTE_SIZE 1
-/* Size in bytes of the event prefix (ID + time). */
-#define EVENT_SIZE (BYTE_SIZE + LEB128_SIZE)
-
-static int nocalls = 0;
-static int notraces = 0;
-static int use_zip = 0;
-static int do_report = 0;
-static int do_heap_shot = 0;
-static int max_call_depth = 100;
-static volatile int runtime_inited = 0;
-static int need_helper_thread = 0;
-static int command_port = 0;
-static int heapshot_requested = 0;
-static int sample_type = 0;
-static int sample_freq = 0;
-static int do_mono_sample = 0;
-static int in_shutdown = 0;
-static int do_debug = 0;
-static int do_counters = 0;
-static int do_coverage = 0;
-static gboolean debug_coverage = FALSE;
-static MonoProfileSamplingMode sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
-static int max_allocated_sample_hits;
-
-static gint32 sample_hits;
-static gint32 sample_flushes;
-static gint32 sample_allocations;
-static gint32 buffer_allocations;
-static gint32 thread_starts;
-static gint32 thread_ends;
-static gint32 domain_loads;
-static gint32 domain_unloads;
-static gint32 context_loads;
-static gint32 context_unloads;
-static gint32 assembly_loads;
-static gint32 assembly_unloads;
-static gint32 image_loads;
-static gint32 image_unloads;
-static gint32 class_loads;
-static gint32 class_unloads;
-
-static MonoLinkedListSet profiler_thread_list;
-
-/*
- * file format:
- * [header] [buffer]*
- *
- * The file is composed by a header followed by 0 or more buffers.
- * Each buffer contains events that happened on a thread: for a given thread
- * buffers that appear later in the file are guaranteed to contain events
- * that happened later in time. Buffers from separate threads could be interleaved,
- * though.
- * Buffers are not required to be aligned.
- *
- * header format:
- * [id: 4 bytes] constant value: LOG_HEADER_ID
- * [major: 1 byte] [minor: 1 byte] major and minor version of the log profiler
- * [format: 1 byte] version of the data format for the rest of the file
- * [ptrsize: 1 byte] size in bytes of a pointer in the profiled program
- * [startup time: 8 bytes] time in milliseconds since the unix epoch when the program started
- * [timer overhead: 4 bytes] approximate overhead in nanoseconds of the timer
- * [flags: 4 bytes] file format flags, should be 0 for now
- * [pid: 4 bytes] pid of the profiled process
- * [port: 2 bytes] tcp port for server if != 0
- * [args size: 4 bytes] size of args
- * [args: string] arguments passed to the profiler
- * [arch size: 4 bytes] size of arch
- * [arch: string] architecture the profiler is running on
- * [os size: 4 bytes] size of os
- * [os: string] operating system the profiler is running on
- *
- * The multiple byte integers are in little-endian format.
- *
- * buffer format:
- * [buffer header] [event]*
- * Buffers have a fixed-size header followed by 0 or more bytes of event data.
- * Timing information and other values in the event data are usually stored
- * as uleb128 or sleb128 integers. To save space, as noted for each item below,
- * some data is represented as a difference between the actual value and
- * either the last value of the same type (like for timing information) or
- * as the difference from a value stored in a buffer header.
- *
- * For timing information the data is stored as uleb128, since timing
- * increases in a monotonic way in each thread: the value is the number of
- * nanoseconds to add to the last seen timing data in a buffer. The first value
- * in a buffer will be calculated from the time_base field in the buffer head.
- *
- * Object or heap sizes are stored as uleb128.
- * Pointer differences are stored as sleb128, instead.
- *
- * If an unexpected value is found, the rest of the buffer should be ignored,
- * as generally the later values need the former to be interpreted correctly.
- *
- * buffer header format:
- * [bufid: 4 bytes] constant value: BUF_ID
- * [len: 4 bytes] size of the data following the buffer header
- * [time_base: 8 bytes] time base in nanoseconds since an unspecified epoch
- * [ptr_base: 8 bytes] base value for pointers
- * [obj_base: 8 bytes] base value for object addresses
- * [thread id: 8 bytes] system-specific thread ID (pthread_t for example)
- * [method_base: 8 bytes] base value for MonoMethod pointers
- *
- * event format:
- * [extended info: upper 4 bits] [type: lower 4 bits]
- * [time diff: uleb128] nanoseconds since last timing
- * [data]*
- * The data that follows depends on type and the extended info.
- * Type is one of the enum values in proflog.h: TYPE_ALLOC, TYPE_GC,
- * TYPE_METADATA, TYPE_METHOD, TYPE_EXCEPTION, TYPE_MONITOR, TYPE_HEAP.
- * The extended info bits are interpreted based on type, see
- * each individual event description below.
- * strings are represented as a 0-terminated utf8 sequence.
- *
- * backtrace format:
- * [num: uleb128] number of frames following
- * [frame: sleb128]* mum MonoMethod* as a pointer difference from the last such
- * pointer or the buffer method_base
- *
- * type alloc format:
- * type: TYPE_ALLOC
- * exinfo: flags: TYPE_ALLOC_BT
- * [ptr: sleb128] class as a byte difference from ptr_base
- * [obj: sleb128] object address as a byte difference from obj_base
- * [size: uleb128] size of the object in the heap
- * If the TYPE_ALLOC_BT flag is set, a backtrace follows.
- *
- * type GC format:
- * type: TYPE_GC
- * exinfo: one of TYPE_GC_EVENT, TYPE_GC_RESIZE, TYPE_GC_MOVE, TYPE_GC_HANDLE_CREATED[_BT],
- * TYPE_GC_HANDLE_DESTROYED[_BT], TYPE_GC_FINALIZE_START, TYPE_GC_FINALIZE_END,
- * TYPE_GC_FINALIZE_OBJECT_START, TYPE_GC_FINALIZE_OBJECT_END
- * if exinfo == TYPE_GC_RESIZE
- *     [heap_size: uleb128] new heap size
- * if exinfo == TYPE_GC_EVENT
- *     [event type: byte] GC event (MONO_GC_EVENT_* from profiler.h)
- *     [generation: byte] GC generation event refers to
- * if exinfo == TYPE_GC_MOVE
- *     [num_objects: uleb128] number of object moves that follow
- *     [objaddr: sleb128]+ num_objects object pointer differences from obj_base
- *     num is always an even number: the even items are the old
- *     addresses, the odd numbers are the respective new object addresses
- * if exinfo == TYPE_GC_HANDLE_CREATED[_BT]
- *     [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
- *     upper bits reserved as flags
- *     [handle: uleb128] GC handle value
- *     [objaddr: sleb128] object pointer differences from obj_base
- *     If exinfo == TYPE_GC_HANDLE_CREATED_BT, a backtrace follows.
- * if exinfo == TYPE_GC_HANDLE_DESTROYED[_BT]
- *     [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
- *     upper bits reserved as flags
- *     [handle: uleb128] GC handle value
- *     If exinfo == TYPE_GC_HANDLE_DESTROYED_BT, a backtrace follows.
- * if exinfo == TYPE_GC_FINALIZE_OBJECT_{START,END}
- *     [object: sleb128] the object as a difference from obj_base
- *
- * type metadata format:
- * type: TYPE_METADATA
- * exinfo: one of: TYPE_END_LOAD, TYPE_END_UNLOAD (optional for TYPE_THREAD and TYPE_DOMAIN)
- * [mtype: byte] metadata type, one of: TYPE_CLASS, TYPE_IMAGE, TYPE_ASSEMBLY, TYPE_DOMAIN,
- * TYPE_THREAD, TYPE_CONTEXT
- * [pointer: sleb128] pointer of the metadata type depending on mtype
- * if mtype == TYPE_CLASS
- *     [image: sleb128] MonoImage* as a pointer difference from ptr_base
- *     [name: string] full class name
- * if mtype == TYPE_IMAGE
- *     [name: string] image file name
- * if mtype == TYPE_ASSEMBLY
- *     [name: string] assembly name
- * if mtype == TYPE_DOMAIN && exinfo == 0
- *     [name: string] domain friendly name
- * if mtype == TYPE_CONTEXT
- *     [domain: sleb128] domain id as pointer
- * if mtype == TYPE_THREAD && exinfo == 0
- *     [name: string] thread name
- *
- * type method format:
- * type: TYPE_METHOD
- * exinfo: one of: TYPE_LEAVE, TYPE_ENTER, TYPE_EXC_LEAVE, TYPE_JIT
- * [method: sleb128] MonoMethod* as a pointer difference from the last such
- * pointer or the buffer method_base
- * if exinfo == TYPE_JIT
- *     [code address: sleb128] pointer to the native code as a diff from ptr_base
- *     [code size: uleb128] size of the generated code
- *     [name: string] full method name
- *
- * type exception format:
- * type: TYPE_EXCEPTION
- * exinfo: TYPE_THROW_BT flag or one of: TYPE_CLAUSE
- * if exinfo == TYPE_CLAUSE
- *     [clause type: byte] MonoExceptionEnum enum value
- *     [clause index: uleb128] index of the current clause
- *     [method: sleb128] MonoMethod* as a pointer difference from the last such
- *     pointer or the buffer method_base
- * else
- *     [object: sleb128] the exception object as a difference from obj_base
- *     if exinfo has TYPE_THROW_BT set, a backtrace follows.
- *
- * type runtime format:
- * type: TYPE_RUNTIME
- * exinfo: one of: TYPE_JITHELPER
- * if exinfo == TYPE_JITHELPER
- *     [type: byte] MonoProfilerCodeBufferType enum value
- *     [buffer address: sleb128] pointer to the native code as a diff from ptr_base
- *     [buffer size: uleb128] size of the generated code
- *     if type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE
- *             [name: string] buffer description name
- *
- * type monitor format:
- * type: TYPE_MONITOR
- * exinfo: TYPE_MONITOR_BT flag and one of: MONO_PROFILER_MONITOR_(CONTENTION|FAIL|DONE)
- * [object: sleb128] the lock object as a difference from obj_base
- * if exinfo.low3bits == MONO_PROFILER_MONITOR_CONTENTION
- *     If the TYPE_MONITOR_BT flag is set, a backtrace follows.
- *
- * type heap format
- * type: TYPE_HEAP
- * exinfo: one of TYPE_HEAP_START, TYPE_HEAP_END, TYPE_HEAP_OBJECT, TYPE_HEAP_ROOT
- * if exinfo == TYPE_HEAP_OBJECT
- *     [object: sleb128] the object as a difference from obj_base
- *     [class: sleb128] the object MonoClass* as a difference from ptr_base
- *     [size: uleb128] size of the object on the heap
- *     [num_refs: uleb128] number of object references
- *     each referenced objref is preceded by a uleb128 encoded offset: the
- *     first offset is from the object address and each next offset is relative
- *     to the previous one
- *     [objrefs: sleb128]+ object referenced as a difference from obj_base
- *     The same object can appear multiple times, but only the first time
- *     with size != 0: in the other cases this data will only be used to
- *     provide additional referenced objects.
- * if exinfo == TYPE_HEAP_ROOT
- *     [num_roots: uleb128] number of root references
- *     [num_gc: uleb128] number of major gcs
- *     [object: sleb128] the object as a difference from obj_base
- *     [root_type: byte] the root_type: MonoProfileGCRootType (profiler.h)
- *     [extra_info: uleb128] the extra_info value
- *     object, root_type and extra_info are repeated num_roots times
- *
- * type sample format
- * type: TYPE_SAMPLE
- * exinfo: one of TYPE_SAMPLE_HIT, TYPE_SAMPLE_USYM, TYPE_SAMPLE_UBIN, TYPE_SAMPLE_COUNTERS_DESC, TYPE_SAMPLE_COUNTERS
- * if exinfo == TYPE_SAMPLE_HIT
- *     [sample_type: byte] type of sample (SAMPLE_*)
- *     [thread: sleb128] thread id as difference from ptr_base
- *     [count: uleb128] number of following instruction addresses
- *     [ip: sleb128]* instruction pointer as difference from ptr_base
- *     [mbt_count: uleb128] number of managed backtrace frames
- *     [method: sleb128]* MonoMethod* as a pointer difference from the last such
- *     pointer or the buffer method_base (the first such method can be also indentified by ip, but this is not neccessarily true)
- * if exinfo == TYPE_SAMPLE_USYM
- *     [address: sleb128] symbol address as a difference from ptr_base
- *     [size: uleb128] symbol size (may be 0 if unknown)
- *     [name: string] symbol name
- * if exinfo == TYPE_SAMPLE_UBIN
- *     [address: sleb128] address where binary has been loaded
- *     [offset: uleb128] file offset of mapping (the same file can be mapped multiple times)
- *     [size: uleb128] memory size
- *     [name: string] binary name
- * if exinfo == TYPE_SAMPLE_COUNTERS_DESC
- *     [len: uleb128] number of counters
- *     for i = 0 to len
- *             [section: uleb128] section of counter
- *             if section == MONO_COUNTER_PERFCOUNTERS:
- *                     [section_name: string] section name of counter
- *             [name: string] name of counter
- *             [type: byte] type of counter
- *             [unit: byte] unit of counter
- *             [variance: byte] variance of counter
- *             [index: uleb128] unique index of counter
- * if exinfo == TYPE_SAMPLE_COUNTERS
- *     while true:
- *             [index: uleb128] unique index of counter
- *             if index == 0:
- *                     break
- *             [type: byte] type of counter value
- *             if type == string:
- *                     if value == null:
- *                             [0: uleb128] 0 -> value is null
- *                     else:
- *                             [1: uleb128] 1 -> value is not null
- *                             [value: string] counter value
- *             else:
- *                     [value: uleb128/sleb128/double] counter value, can be sleb128, uleb128 or double (determined by using type)
- *
- * type coverage format
- * type: TYPE_COVERAGE
- * exinfo: one of TYPE_COVERAGE_METHOD, TYPE_COVERAGE_STATEMENT, TYPE_COVERAGE_ASSEMBLY, TYPE_COVERAGE_CLASS
- * if exinfo == TYPE_COVERAGE_METHOD
- *  [assembly: string] name of assembly
- *  [class: string] name of the class
- *  [name: string] name of the method
- *  [signature: string] the signature of the method
- *  [filename: string] the file path of the file that contains this method
- *  [token: uleb128] the method token
- *  [method_id: uleb128] an ID for this data to associate with the buffers of TYPE_COVERAGE_STATEMENTS
- *  [len: uleb128] the number of TYPE_COVERAGE_BUFFERS associated with this method
- * if exinfo == TYPE_COVERAGE_STATEMENTS
- *  [method_id: uleb128] an the TYPE_COVERAGE_METHOD buffer to associate this with
- *  [offset: uleb128] the il offset relative to the previous offset
- *  [counter: uleb128] the counter for this instruction
- *  [line: uleb128] the line of filename containing this instruction
- *  [column: uleb128] the column containing this instruction
- * if exinfo == TYPE_COVERAGE_ASSEMBLY
- *  [name: string] assembly name
- *  [guid: string] assembly GUID
- *  [filename: string] assembly filename
- *  [number_of_methods: uleb128] the number of methods in this assembly
- *  [fully_covered: uleb128] the number of fully covered methods
- *  [partially_covered: uleb128] the number of partially covered methods
- *    currently partially_covered will always be 0, and fully_covered is the
- *    number of methods that are fully and partially covered.
- * if exinfo == TYPE_COVERAGE_CLASS
- *  [name: string] assembly name
- *  [class: string] class name
- *  [number_of_methods: uleb128] the number of methods in this class
- *  [fully_covered: uleb128] the number of fully covered methods
- *  [partially_covered: uleb128] the number of partially covered methods
- *    currently partially_covered will always be 0, and fully_covered is the
- *    number of methods that are fully and partially covered.
- *
- * type meta format:
- * type: TYPE_META
- * exinfo: one of: TYPE_SYNC_POINT
- * if exinfo == TYPE_SYNC_POINT
- *     [type: byte] MonoProfilerSyncPointType enum value
- */
-
-// Pending data to be written to the log, for a single thread.
-// Threads periodically flush their own LogBuffers by calling safe_send
-typedef struct _LogBuffer LogBuffer;
-struct _LogBuffer {
-       // Next (older) LogBuffer in processing queue
-       LogBuffer *next;
-
-       uint64_t time_base;
-       uint64_t last_time;
-       uintptr_t ptr_base;
-       uintptr_t method_base;
-       uintptr_t last_method;
-       uintptr_t obj_base;
-       uintptr_t thread_id;
-
-       // Bytes allocated for this LogBuffer
-       int size;
-
-       // Start of currently unused space in buffer
-       unsigned char* cursor;
-
-       // Pointer to start-of-structure-plus-size (for convenience)
-       unsigned char* buf_end;
-
-       // Start of data in buffer. Contents follow "buffer format" described above.
-       unsigned char buf [1];
-};
-
-typedef struct {
-       MonoLinkedListSetNode node;
-
-       // The current log buffer for this thread.
-       LogBuffer *buffer;
-
-       // Methods referenced by events in `buffer`, see `MethodInfo`.
-       GPtrArray *methods;
-
-       // Current call depth for enter/leave events.
-       int call_depth;
-
-       // Indicates whether this thread is currently writing to its `buffer`.
-       int busy;
-} MonoProfilerThread;
-
-static inline void
-ign_res (int G_GNUC_UNUSED unused, ...)
-{
-}
-
-/*
- * These macros create a scope to avoid leaking the buffer returned
- * from ensure_logbuf () as it may have been invalidated by a GC
- * thread during STW. If you called init_thread () with add_to_lls =
- * FALSE, then don't use these macros.
- */
-
-#define ENTER_LOG \
-       do { \
-               buffer_lock (); \
-               g_assert (!PROF_TLS_GET ()->busy++ && "Why are we trying to write a new event while already writing one?")
-
-#define EXIT_LOG \
-               PROF_TLS_GET ()->busy--; \
-               buffer_unlock (); \
-       } while (0)
-
-static volatile gint32 buffer_rwlock_count;
-static volatile gpointer buffer_rwlock_exclusive;
-
-// Can be used recursively.
-static void
-buffer_lock (void)
-{
-       /*
-        * If the thread holding the exclusive lock tries to modify the
-        * reader count, just make it a no-op. This way, we also avoid
-        * invoking the GC safe point macros below, which could break if
-        * done from a thread that is currently the initiator of STW.
-        *
-        * In other words, we rely on the fact that the GC thread takes
-        * the exclusive lock in the gc_event () callback when the world
-        * is about to stop.
-        */
-       if (InterlockedReadPointer (&buffer_rwlock_exclusive) != (gpointer) thread_id ()) {
-               MONO_ENTER_GC_SAFE;
-
-               while (InterlockedReadPointer (&buffer_rwlock_exclusive))
-                       mono_thread_info_yield ();
-
-               InterlockedIncrement (&buffer_rwlock_count);
-
-               MONO_EXIT_GC_SAFE;
-       }
-
-       mono_memory_barrier ();
-}
-
-static void
-buffer_unlock (void)
-{
-       mono_memory_barrier ();
-
-       // See the comment in buffer_lock ().
-       if (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id ())
-               return;
-
-       g_assert (InterlockedRead (&buffer_rwlock_count) && "Why are we trying to decrement a zero reader count?");
-
-       InterlockedDecrement (&buffer_rwlock_count);
-}
-
-// Cannot be used recursively.
-static void
-buffer_lock_excl (void)
-{
-       gpointer tid = (gpointer) thread_id ();
-
-       g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) != tid && "Why are we taking the exclusive lock twice?");
-
-       MONO_ENTER_GC_SAFE;
-
-       while (InterlockedCompareExchangePointer (&buffer_rwlock_exclusive, tid, 0))
-               mono_thread_info_yield ();
-
-       while (InterlockedRead (&buffer_rwlock_count))
-               mono_thread_info_yield ();
-
-       MONO_EXIT_GC_SAFE;
-
-       mono_memory_barrier ();
-}
-
-static void
-buffer_unlock_excl (void)
-{
-       mono_memory_barrier ();
-
-       g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) && "Why is the exclusive lock not held?");
-       g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id () && "Why does another thread hold the exclusive lock?");
-       g_assert (!InterlockedRead (&buffer_rwlock_count) && "Why are there readers when the exclusive lock is held?");
-
-       InterlockedWritePointer (&buffer_rwlock_exclusive, NULL);
-}
-
-typedef struct _BinaryObject BinaryObject;
-struct _BinaryObject {
-       BinaryObject *next;
-       void *addr;
-       char *name;
-};
-
-struct _MonoProfiler {
-       FILE* file;
-#if defined (HAVE_SYS_ZLIB)
-       gzFile gzfile;
-#endif
-       char *args;
-       uint64_t startup_time;
-       int pipe_output;
-       int last_gc_gen_started;
-       int command_port;
-       int server_socket;
-       int pipes [2];
-#ifndef HOST_WIN32
-       pthread_t helper_thread;
-       pthread_t writer_thread;
-       pthread_t dumper_thread;
-#endif
-       volatile gint32 run_writer_thread;
-       MonoLockFreeAllocSizeClass writer_entry_size_class;
-       MonoLockFreeAllocator writer_entry_allocator;
-       MonoLockFreeQueue writer_queue;
-       MonoSemType writer_queue_sem;
-       MonoConcurrentHashTable *method_table;
-       mono_mutex_t method_table_mutex;
-       volatile gint32 run_dumper_thread;
-       MonoLockFreeQueue dumper_queue;
-       MonoSemType dumper_queue_sem;
-       MonoLockFreeAllocSizeClass sample_size_class;
-       MonoLockFreeAllocator sample_allocator;
-       MonoLockFreeQueue sample_reuse_queue;
-       BinaryObject *binary_objects;
-       GPtrArray *coverage_filters;
-};
-
-typedef struct {
-       MonoLockFreeQueueNode node;
-       GPtrArray *methods;
-       LogBuffer *buffer;
-} WriterQueueEntry;
-
-#define WRITER_ENTRY_BLOCK_SIZE (mono_pagesize ())
-
-typedef struct {
-       MonoMethod *method;
-       MonoJitInfo *ji;
-       uint64_t time;
-} MethodInfo;
-
-#ifdef HOST_WIN32
-
-#define PROF_TLS_SET(VAL) (TlsSetValue (profiler_tls, (VAL)))
-#define PROF_TLS_GET() ((MonoProfilerThread *) TlsGetValue (profiler_tls))
-#define PROF_TLS_INIT() (profiler_tls = TlsAlloc ())
-#define PROF_TLS_FREE() (TlsFree (profiler_tls))
-
-static DWORD profiler_tls;
-
-#elif HAVE_KW_THREAD
-
-#define PROF_TLS_SET(VAL) (profiler_tls = (VAL))
-#define PROF_TLS_GET() (profiler_tls)
-#define PROF_TLS_INIT()
-#define PROF_TLS_FREE()
-
-static __thread MonoProfilerThread *profiler_tls;
-
-#else
-
-#define PROF_TLS_SET(VAL) (pthread_setspecific (profiler_tls, (VAL)))
-#define PROF_TLS_GET() ((MonoProfilerThread *) pthread_getspecific (profiler_tls))
-#define PROF_TLS_INIT() (pthread_key_create (&profiler_tls, NULL))
-#define PROF_TLS_FREE() (pthread_key_delete (&profiler_tls))
-
-static pthread_key_t profiler_tls;
-
-#endif
-
-static char*
-pstrdup (const char *s)
-{
-       int len = strlen (s) + 1;
-       char *p = (char *)malloc (len);
-       memcpy (p, s, len);
-       return p;
-}
-
-static LogBuffer*
-create_buffer (void)
-{
-       LogBuffer* buf = (LogBuffer *)alloc_buffer (BUFFER_SIZE);
-
-       InterlockedIncrement (&buffer_allocations);
-
-       buf->size = BUFFER_SIZE;
-       buf->time_base = current_time ();
-       buf->last_time = buf->time_base;
-       buf->buf_end = (unsigned char*)buf + buf->size;
-       buf->cursor = buf->buf;
-       return buf;
-}
-
-static void
-init_buffer_state (MonoProfilerThread *thread)
-{
-       thread->buffer = create_buffer ();
-       thread->methods = NULL;
-}
-
-static void
-clear_hazard_pointers (MonoThreadHazardPointers *hp)
-{
-       mono_hazard_pointer_clear (hp, 0);
-       mono_hazard_pointer_clear (hp, 1);
-       mono_hazard_pointer_clear (hp, 2);
-}
-
-static MonoProfilerThread *
-init_thread (gboolean add_to_lls)
-{
-       MonoProfilerThread *thread = PROF_TLS_GET ();
-
-       /*
-        * Sometimes we may try to initialize a thread twice. One example is the
-        * main thread: We initialize it when setting up the profiler, but we will
-        * also get a thread_start () callback for it. Another example is when
-        * attaching new threads to the runtime: We may get a gc_alloc () callback
-        * for that thread's thread object (where we initialize it), soon followed
-        * by a thread_start () callback.
-        *
-        * These cases are harmless anyhow. Just return if we've already done the
-        * initialization work.
-        */
-       if (thread)
-               return thread;
-
-       thread = malloc (sizeof (MonoProfilerThread));
-       thread->node.key = thread_id ();
-       thread->call_depth = 0;
-       thread->busy = 0;
-
-       init_buffer_state (thread);
-
-       /*
-        * Some internal profiler threads don't need to be cleaned up
-        * by the main thread on shutdown.
-        */
-       if (add_to_lls) {
-               MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
-               g_assert (mono_lls_insert (&profiler_thread_list, hp, &thread->node) && "Why can't we insert the thread in the LLS?");
-               clear_hazard_pointers (hp);
-       }
-
-       PROF_TLS_SET (thread);
-
-       return thread;
-}
-
-// Only valid if init_thread () was called with add_to_lls = FALSE.
-static void
-deinit_thread (MonoProfilerThread *thread)
-{
-       free (thread);
-       PROF_TLS_SET (NULL);
-}
-
-static LogBuffer *
-ensure_logbuf_inner (LogBuffer *old, int bytes)
-{
-       if (old && old->cursor + bytes + 100 < old->buf_end)
-               return old;
-
-       LogBuffer *new_ = create_buffer ();
-       new_->next = old;
-
-       return new_;
-}
-
-// Only valid if init_thread () was called with add_to_lls = FALSE.
-static LogBuffer *
-ensure_logbuf_unsafe (int bytes)
-{
-       MonoProfilerThread *thread = PROF_TLS_GET ();
-       LogBuffer *old = thread->buffer;
-       LogBuffer *new_ = ensure_logbuf_inner (old, bytes);
-
-       if (new_ == old)
-               return old; // Still enough space.
-
-       thread->buffer = new_;
-
-       return new_;
-}
-
-/*
- * Any calls to this function should be wrapped in the ENTER_LOG and
- * EXIT_LOG macros to prevent the returned pointer from leaking
- * outside of the critical region created by the calls to buffer_lock ()
- * and buffer_unlock () that those macros insert. If the pointer leaks,
- * it can and will lead to crashes as the GC or helper thread may
- * invalidate the pointer at any time.
- *
- * Note: If you're calling from a thread that called init_thread () with
- * add_to_lls = FALSE, you should use ensure_logbuf_unsafe () and omit
- * the macros.
- */
-static LogBuffer*
-ensure_logbuf (int bytes)
-{
-       g_assert (PROF_TLS_GET ()->busy && "Why are we trying to expand our buffer without the busy flag set?");
-
-       return ensure_logbuf_unsafe (bytes);
-}
-
-static void
-emit_byte (LogBuffer *logbuffer, int value)
-{
-       logbuffer->cursor [0] = value;
-       logbuffer->cursor++;
-       assert (logbuffer->cursor <= logbuffer->buf_end);
-}
-
-static void
-emit_value (LogBuffer *logbuffer, int value)
-{
-       encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
-       assert (logbuffer->cursor <= logbuffer->buf_end);
-}
-
-static void
-emit_time (LogBuffer *logbuffer, uint64_t value)
-{
-       uint64_t tdiff = value - logbuffer->last_time;
-       //if (value < logbuffer->last_time)
-       //      printf ("time went backwards\n");
-       //if (tdiff > 1000000)
-       //      printf ("large time offset: %llu\n", tdiff);
-       encode_uleb128 (tdiff, logbuffer->cursor, &logbuffer->cursor);
-       /*if (tdiff != decode_uleb128 (p, &p))
-               printf ("incorrect encoding: %llu\n", tdiff);*/
-       logbuffer->last_time = value;
-       assert (logbuffer->cursor <= logbuffer->buf_end);
-}
-
-static void
-emit_event_time (LogBuffer *logbuffer, int event, uint64_t time)
-{
-       emit_byte (logbuffer, event);
-       emit_time (logbuffer, time);
-}
-
-static void
-emit_event (LogBuffer *logbuffer, int event)
-{
-       emit_event_time (logbuffer, event, current_time ());
-}
-
-static void
-emit_svalue (LogBuffer *logbuffer, int64_t value)
-{
-       encode_sleb128 (value, logbuffer->cursor, &logbuffer->cursor);
-       assert (logbuffer->cursor <= logbuffer->buf_end);
-}
-
-static void
-emit_uvalue (LogBuffer *logbuffer, uint64_t value)
-{
-       encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
-       assert (logbuffer->cursor <= logbuffer->buf_end);
-}
-
-static void
-emit_ptr (LogBuffer *logbuffer, void *ptr)
-{
-       if (!logbuffer->ptr_base)
-               logbuffer->ptr_base = (uintptr_t)ptr;
-       emit_svalue (logbuffer, (intptr_t)ptr - logbuffer->ptr_base);
-       assert (logbuffer->cursor <= logbuffer->buf_end);
-}
-
-static void
-emit_method_inner (LogBuffer *logbuffer, void *method)
-{
-       if (!logbuffer->method_base) {
-               logbuffer->method_base = (intptr_t)method;
-               logbuffer->last_method = (intptr_t)method;
-       }
-       encode_sleb128 ((intptr_t)((char*)method - (char*)logbuffer->last_method), logbuffer->cursor, &logbuffer->cursor);
-       logbuffer->last_method = (intptr_t)method;
-       assert (logbuffer->cursor <= logbuffer->buf_end);
-}
-
-/*
-typedef struct {
-       MonoMethod *method;
-       MonoJitInfo *found;
-} MethodSearch;
-
-static void
-find_method (MonoDomain *domain, void *user_data)
-{
-       MethodSearch *search = user_data;
-
-       if (search->found)
-               return;
-
-       MonoJitInfo *ji = mono_get_jit_info_from_method (domain, search->method);
-
-       // It could be AOT'd, so we need to get it from the AOT runtime's cache.
-       if (!ji) {
-               void *ip = mono_aot_get_method (domain, search->method);
-
-               // Avoid a slow path in mono_jit_info_table_find ().
-               if (ip)
-                       ji = mono_jit_info_table_find (domain, ip);
-       }
-
-       if (ji)
-               search->found = ji;
-}
-*/
-
-static void
-register_method_local (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji)
-{
-       if (!mono_conc_hashtable_lookup (prof->method_table, method)) {
-               /*
-                * FIXME: In some cases, we crash while looking up JIT info for AOT'd methods.
-                * This usually happens for static constructors. This code is disabled for now
-                * as we don't need this info for anything critical.
-                *
-                * https://bugzilla.xamarin.com/show_bug.cgi?id=35171
-                */
-               /*
-               if (!ji) {
-                       MethodSearch search = { method, NULL };
-
-                       mono_domain_foreach (find_method, &search);
-
-                       ji = search.found;
-               }
-               */
-
-               /*
-                * FIXME: We can't always find JIT info for a generic shared method, especially
-                * if we obtained the MonoMethod during an async stack walk. For now, we deal
-                * with this by giving the generic shared method name and dummy code start/size
-                * information (i.e. zeroes).
-                */
-               //g_assert (ji);
-
-               MethodInfo *info = (MethodInfo *) malloc (sizeof (MethodInfo));
-
-               info->method = method;
-               info->ji = ji;
-               info->time = current_time ();
-
-               MonoProfilerThread *thread = PROF_TLS_GET ();
-               GPtrArray *arr = thread->methods ? thread->methods : (thread->methods = g_ptr_array_new ());
-               g_ptr_array_add (arr, info);
-       }
-}
-
-static void
-emit_method (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
-{
-       register_method_local (prof, method, NULL);
-       emit_method_inner (logbuffer, method);
-}
-
-static void
-emit_obj (LogBuffer *logbuffer, void *ptr)
-{
-       if (!logbuffer->obj_base)
-               logbuffer->obj_base = (uintptr_t)ptr >> 3;
-       emit_svalue (logbuffer, ((uintptr_t)ptr >> 3) - logbuffer->obj_base);
-       assert (logbuffer->cursor <= logbuffer->buf_end);
-}
-
-static void
-emit_string (LogBuffer *logbuffer, const char *str, size_t size)
-{
-       size_t i = 0;
-       if (str) {
-               for (; i < size; i++) {
-                       if (str[i] == '\0')
-                               break;
-                       emit_byte (logbuffer, str [i]);
-               }
-       }
-       emit_byte (logbuffer, '\0');
-}
-
-static void
-emit_double (LogBuffer *logbuffer, double value)
-{
-       int i;
-       unsigned char buffer[8];
-       memcpy (buffer, &value, 8);
-#if G_BYTE_ORDER == G_BIG_ENDIAN
-       for (i = 7; i >= 0; i--)
-#else
-       for (i = 0; i < 8; i++)
-#endif
-               emit_byte (logbuffer, buffer[i]);
-}
-
-static char*
-write_int16 (char *buf, int32_t value)
-{
-       int i;
-       for (i = 0; i < 2; ++i) {
-               buf [i] = value;
-               value >>= 8;
-       }
-       return buf + 2;
-}
-
-static char*
-write_int32 (char *buf, int32_t value)
-{
-       int i;
-       for (i = 0; i < 4; ++i) {
-               buf [i] = value;
-               value >>= 8;
-       }
-       return buf + 4;
-}
-
-static char*
-write_int64 (char *buf, int64_t value)
-{
-       int i;
-       for (i = 0; i < 8; ++i) {
-               buf [i] = value;
-               value >>= 8;
-       }
-       return buf + 8;
-}
-
-static char *
-write_header_string (char *p, const char *str)
-{
-       size_t len = strlen (str) + 1;
-
-       p = write_int32 (p, len);
-       strcpy (p, str);
-
-       return p + len;
-}
-
-static void
-dump_header (MonoProfiler *profiler)
-{
-       const char *args = profiler->args;
-       const char *arch = mono_config_get_cpu ();
-       const char *os = mono_config_get_os ();
-
-       char *hbuf = malloc (
-               sizeof (gint32) /* header id */ +
-               sizeof (gint8) /* major version */ +
-               sizeof (gint8) /* minor version */ +
-               sizeof (gint8) /* data version */ +
-               sizeof (gint8) /* word size */ +
-               sizeof (gint64) /* startup time */ +
-               sizeof (gint32) /* timer overhead */ +
-               sizeof (gint32) /* flags */ +
-               sizeof (gint32) /* process id */ +
-               sizeof (gint16) /* command port */ +
-               sizeof (gint32) + strlen (args) + 1 /* arguments */ +
-               sizeof (gint32) + strlen (arch) + 1 /* architecture */ +
-               sizeof (gint32) + strlen (os) + 1 /* operating system */
-       );
-       char *p = hbuf;
-
-       p = write_int32 (p, LOG_HEADER_ID);
-       *p++ = LOG_VERSION_MAJOR;
-       *p++ = LOG_VERSION_MINOR;
-       *p++ = LOG_DATA_VERSION;
-       *p++ = sizeof (void *);
-       p = write_int64 (p, ((uint64_t) time (NULL)) * 1000);
-       p = write_int32 (p, get_timer_overhead ());
-       p = write_int32 (p, 0); /* flags */
-       p = write_int32 (p, process_id ());
-       p = write_int16 (p, profiler->command_port);
-       p = write_header_string (p, args);
-       p = write_header_string (p, arch);
-       p = write_header_string (p, os);
-
-#if defined (HAVE_SYS_ZLIB)
-       if (profiler->gzfile) {
-               gzwrite (profiler->gzfile, hbuf, p - hbuf);
-       } else
-#endif
-       {
-               fwrite (hbuf, p - hbuf, 1, profiler->file);
-               fflush (profiler->file);
-       }
-
-       free (hbuf);
-}
-
-static void
-send_buffer (MonoProfiler *prof, MonoProfilerThread *thread)
-{
-       WriterQueueEntry *entry = mono_lock_free_alloc (&prof->writer_entry_allocator);
-       entry->methods = thread->methods;
-       entry->buffer = thread->buffer;
-
-       mono_lock_free_queue_node_init (&entry->node, FALSE);
-
-       mono_lock_free_queue_enqueue (&prof->writer_queue, &entry->node);
-       mono_os_sem_post (&prof->writer_queue_sem);
-}
-
-static void
-remove_thread (MonoProfiler *prof, MonoProfilerThread *thread, gboolean from_callback)
-{
-       MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
-
-       if (mono_lls_remove (&profiler_thread_list, hp, &thread->node)) {
-               LogBuffer *buffer = thread->buffer;
-
-               /*
-                * No need to take the buffer lock here as no other threads can
-                * be accessing this buffer anymore.
-                */
-
-               if (!from_callback) {
-                       /*
-                        * The thread is being cleaned up by the main thread during
-                        * shutdown. This typically happens for internal runtime
-                        * threads. We need to synthesize a thread end event.
-                        */
-
-                       buffer = ensure_logbuf_inner (buffer,
-                               EVENT_SIZE /* event */ +
-                               BYTE_SIZE /* type */ +
-                               LEB128_SIZE /* tid */
-                       );
-
-                       emit_event (buffer, TYPE_END_UNLOAD | TYPE_METADATA);
-                       emit_byte (buffer, TYPE_THREAD);
-                       emit_ptr (buffer, (void *) thread->node.key);
-               }
-
-               send_buffer (prof, thread);
-
-               mono_thread_hazardous_try_free (thread, free);
-       }
-
-       clear_hazard_pointers (hp);
-
-       if (from_callback)
-               PROF_TLS_SET (NULL);
-}
-
-static void
-dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
-{
-       char hbuf [128];
-       char *p = hbuf;
-
-       if (buf->next)
-               dump_buffer (profiler, buf->next);
-
-       p = write_int32 (p, BUF_ID);
-       p = write_int32 (p, buf->cursor - buf->buf);
-       p = write_int64 (p, buf->time_base);
-       p = write_int64 (p, buf->ptr_base);
-       p = write_int64 (p, buf->obj_base);
-       p = write_int64 (p, buf->thread_id);
-       p = write_int64 (p, buf->method_base);
-
-#if defined (HAVE_SYS_ZLIB)
-       if (profiler->gzfile) {
-               gzwrite (profiler->gzfile, hbuf, p - hbuf);
-               gzwrite (profiler->gzfile, buf->buf, buf->cursor - buf->buf);
-       } else
-#endif
-       {
-               fwrite (hbuf, p - hbuf, 1, profiler->file);
-               fwrite (buf->buf, buf->cursor - buf->buf, 1, profiler->file);
-               fflush (profiler->file);
-       }
-
-       free_buffer (buf, buf->size);
-}
-
-static void
-dump_buffer_threadless (MonoProfiler *profiler, LogBuffer *buf)
-{
-       for (LogBuffer *iter = buf; iter; iter = iter->next)
-               iter->thread_id = 0;
-
-       dump_buffer (profiler, buf);
-}
-
-static void
-process_requests (MonoProfiler *profiler)
-{
-       if (heapshot_requested)
-               mono_gc_collect (mono_gc_max_generation ());
-}
-
-static void counters_init (MonoProfiler *profiler);
-static void counters_sample (MonoProfiler *profiler, uint64_t timestamp);
-
-static void
-safe_send (MonoProfiler *profiler)
-{
-       /* We need the runtime initialized so that we have threads and hazard
-        * pointers available. Otherwise, the lock free queue will not work and
-        * there won't be a thread to process the data.
-        *
-        * While the runtime isn't initialized, we just accumulate data in the
-        * thread local buffer list.
-        */
-       if (!InterlockedRead (&runtime_inited))
-               return;
-
-       MonoProfilerThread *thread = PROF_TLS_GET ();
-
-       buffer_lock ();
-
-       send_buffer (profiler, thread);
-       init_buffer_state (thread);
-
-       buffer_unlock ();
-}
-
-static void
-send_if_needed (MonoProfiler *prof)
-{
-       if (PROF_TLS_GET ()->buffer->next)
-               safe_send (prof);
-}
-
-static void
-safe_send_threadless (MonoProfiler *prof)
-{
-       LogBuffer *buf = PROF_TLS_GET ()->buffer;
-
-       for (LogBuffer *iter = buf; iter; iter = iter->next)
-               iter->thread_id = 0;
-
-       safe_send (prof);
-}
-
-static void
-send_if_needed_threadless (MonoProfiler *prof)
-{
-       if (PROF_TLS_GET ()->buffer->next)
-               safe_send_threadless (prof);
-}
-
-// Assumes that the exclusive lock is held.
-static void
-sync_point_flush (MonoProfiler *prof)
-{
-       g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id () && "Why don't we hold the exclusive lock?");
-
-       MONO_LLS_FOREACH_SAFE (&profiler_thread_list, MonoProfilerThread, thread) {
-               send_buffer (prof, thread);
-               init_buffer_state (thread);
-       } MONO_LLS_FOREACH_SAFE_END
-}
-
-// Assumes that the exclusive lock is held.
-static void
-sync_point_mark (MonoProfiler *prof, MonoProfilerSyncPointType type)
-{
-       g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id () && "Why don't we hold the exclusive lock?");
-
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               LEB128_SIZE /* type */
-       );
-
-       emit_event (logbuffer, TYPE_META | TYPE_SYNC_POINT);
-       emit_byte (logbuffer, type);
-
-       EXIT_LOG;
-
-       switch (type) {
-       case SYNC_POINT_PERIODIC:
-               safe_send_threadless (prof);
-               break;
-       case SYNC_POINT_WORLD_STOP:
-       case SYNC_POINT_WORLD_START:
-               safe_send (prof);
-               break;
-       default:
-               g_assert_not_reached ();
-               break;
-       }
-}
-
-// Assumes that the exclusive lock is held.
-static void
-sync_point (MonoProfiler *prof, MonoProfilerSyncPointType type)
-{
-       sync_point_flush (prof);
-       sync_point_mark (prof, type);
-}
-
-static int
-gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
-{
-       /* account for object alignment in the heap */
-       size += 7;
-       size &= ~7;
-
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               LEB128_SIZE /* obj */ +
-               LEB128_SIZE /* klass */ +
-               LEB128_SIZE /* size */ +
-               LEB128_SIZE /* num */ +
-               num * (
-                       LEB128_SIZE /* offset */ +
-                       LEB128_SIZE /* ref */
-               )
-       );
-
-       emit_event (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
-       emit_obj (logbuffer, obj);
-       emit_ptr (logbuffer, klass);
-       emit_value (logbuffer, size);
-       emit_value (logbuffer, num);
-
-       uintptr_t last_offset = 0;
-
-       for (int i = 0; i < num; ++i) {
-               emit_value (logbuffer, offsets [i] - last_offset);
-               last_offset = offsets [i];
-               emit_obj (logbuffer, refs [i]);
-       }
-
-       EXIT_LOG;
-
-       return 0;
-}
-
-static unsigned int hs_mode_ms = 0;
-static unsigned int hs_mode_gc = 0;
-static unsigned int hs_mode_ondemand = 0;
-static unsigned int gc_count = 0;
-static uint64_t last_hs_time = 0;
-
-static void
-heap_walk (MonoProfiler *profiler)
-{
-       if (!do_heap_shot)
-               return;
-
-       gboolean do_walk = 0;
-       uint64_t now = current_time ();
-
-       if (hs_mode_ms && (now - last_hs_time) / 1000000 >= hs_mode_ms)
-               do_walk = TRUE;
-       else if (hs_mode_gc && (gc_count % hs_mode_gc) == 0)
-               do_walk = TRUE;
-       else if (hs_mode_ondemand)
-               do_walk = heapshot_requested;
-       else if (!hs_mode_ms && !hs_mode_gc && profiler->last_gc_gen_started == mono_gc_max_generation ())
-               do_walk = TRUE;
-
-       if (!do_walk)
-               return;
-
-       heapshot_requested = 0;
-
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */
-       );
-
-       emit_event (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
-
-       EXIT_LOG;
-
-       mono_gc_walk_heap (0, gc_reference, NULL);
-
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */
-       );
-
-       now = current_time ();
-
-       emit_event (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
-
-       EXIT_LOG;
-
-       last_hs_time = now;
-}
-
-static void
-gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation)
-{
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               BYTE_SIZE /* gc event */ +
-               BYTE_SIZE /* generation */
-       );
-
-       emit_event (logbuffer, TYPE_GC_EVENT | TYPE_GC);
-       emit_byte (logbuffer, ev);
-       emit_byte (logbuffer, generation);
-
-       EXIT_LOG;
-
-       switch (ev) {
-       case MONO_GC_EVENT_START:
-               /* to deal with nested gen1 after gen0 started */
-               profiler->last_gc_gen_started = generation;
-
-               if (generation == mono_gc_max_generation ())
-                       gc_count++;
-               break;
-       case MONO_GC_EVENT_PRE_STOP_WORLD_LOCKED:
-               /*
-                * Ensure that no thread can be in the middle of writing to
-                * a buffer when the world stops...
-                */
-               buffer_lock_excl ();
-               break;
-       case MONO_GC_EVENT_POST_STOP_WORLD:
-               /*
-                * ... So that we now have a consistent view of all buffers.
-                * This allows us to flush them. We need to do this because
-                * they may contain object allocation events that need to be
-                * committed to the log file before any object move events
-                * that will be produced during this GC.
-                */
-               sync_point (profiler, SYNC_POINT_WORLD_STOP);
-               break;
-       case MONO_GC_EVENT_PRE_START_WORLD:
-               heap_walk (profiler);
-               break;
-       case MONO_GC_EVENT_POST_START_WORLD_UNLOCKED:
-               /*
-                * Similarly, we must now make sure that any object moves
-                * written to the GC thread's buffer are flushed. Otherwise,
-                * object allocation events for certain addresses could come
-                * after the move events that made those addresses available.
-                */
-               sync_point_mark (profiler, SYNC_POINT_WORLD_START);
-
-               /*
-                * Finally, it is safe to allow other threads to write to
-                * their buffers again.
-                */
-               buffer_unlock_excl ();
-               break;
-       default:
-               break;
-       }
-}
-
-static void
-gc_resize (MonoProfiler *profiler, int64_t new_size)
-{
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               LEB128_SIZE /* new size */
-       );
-
-       emit_event (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
-       emit_value (logbuffer, new_size);
-
-       EXIT_LOG;
-}
-
-// If you alter MAX_FRAMES, you may need to alter SAMPLE_BLOCK_SIZE too.
-#define MAX_FRAMES 32
-
-typedef struct {
-       int count;
-       MonoMethod* methods [MAX_FRAMES];
-       int32_t il_offsets [MAX_FRAMES];
-       int32_t native_offsets [MAX_FRAMES];
-} FrameData;
-
-static int num_frames = MAX_FRAMES;
-
-static mono_bool
-walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
-{
-       FrameData *frame = (FrameData *)data;
-       if (method && frame->count < num_frames) {
-               frame->il_offsets [frame->count] = il_offset;
-               frame->native_offsets [frame->count] = native_offset;
-               frame->methods [frame->count++] = method;
-               //printf ("In %d %s at %d (native: %d)\n", frame->count, mono_method_get_name (method), il_offset, native_offset);
-       }
-       return frame->count == num_frames;
-}
-
-/*
- * a note about stack walks: they can cause more profiler events to fire,
- * so we need to make sure they don't happen after we started emitting an
- * event, hence the collect_bt/emit_bt split.
- */
-static void
-collect_bt (FrameData *data)
-{
-       data->count = 0;
-       mono_stack_walk_no_il (walk_stack, data);
-}
-
-static void
-emit_bt (MonoProfiler *prof, LogBuffer *logbuffer, FrameData *data)
-{
-       /* FIXME: this is actually tons of data and we should
-        * just output it the first time and use an id the next
-        */
-       if (data->count > num_frames)
-               printf ("bad num frames: %d\n", data->count);
-       emit_value (logbuffer, data->count);
-       //if (*p != data.count) {
-       //      printf ("bad num frames enc at %d: %d -> %d\n", count, data.count, *p); printf ("frames end: %p->%p\n", p, logbuffer->cursor); exit(0);}
-       while (data->count) {
-               emit_method (prof, logbuffer, data->methods [--data->count]);
-       }
-}
-
-static void
-gc_alloc (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
-{
-       init_thread (TRUE);
-
-       int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces) ? TYPE_ALLOC_BT : 0;
-       FrameData data;
-       uintptr_t len = mono_object_get_size (obj);
-       /* account for object alignment in the heap */
-       len += 7;
-       len &= ~7;
-
-       if (do_bt)
-               collect_bt (&data);
-
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               LEB128_SIZE /* klass */ +
-               LEB128_SIZE /* obj */ +
-               LEB128_SIZE /* size */ +
-               (do_bt ? (
-                       LEB128_SIZE /* count */ +
-                       data.count * (
-                               LEB128_SIZE /* method */
-                       )
-               ) : 0)
-       );
-
-       emit_event (logbuffer, do_bt | TYPE_ALLOC);
-       emit_ptr (logbuffer, klass);
-       emit_obj (logbuffer, obj);
-       emit_value (logbuffer, len);
-
-       if (do_bt)
-               emit_bt (prof, logbuffer, &data);
-
-       EXIT_LOG;
-
-       send_if_needed (prof);
-
-       process_requests (prof);
-}
-
-static void
-gc_moves (MonoProfiler *prof, void **objects, int num)
-{
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               LEB128_SIZE /* num */ +
-               num * (
-                       LEB128_SIZE /* object */
-               )
-       );
-
-       emit_event (logbuffer, TYPE_GC_MOVE | TYPE_GC);
-       emit_value (logbuffer, num);
-
-       for (int i = 0; i < num; ++i)
-               emit_obj (logbuffer, objects [i]);
-
-       EXIT_LOG;
-}
-
-static void
-gc_roots (MonoProfiler *prof, int num, void **objects, int *root_types, uintptr_t *extra_info)
-{
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               LEB128_SIZE /* num */ +
-               LEB128_SIZE /* collections */ +
-               num * (
-                       LEB128_SIZE /* object */ +
-                       LEB128_SIZE /* root type */ +
-                       LEB128_SIZE /* extra info */
-               )
-       );
-
-       emit_event (logbuffer, TYPE_HEAP_ROOT | TYPE_HEAP);
-       emit_value (logbuffer, num);
-       emit_value (logbuffer, mono_gc_collection_count (mono_gc_max_generation ()));
-
-       for (int i = 0; i < num; ++i) {
-               emit_obj (logbuffer, objects [i]);
-               emit_byte (logbuffer, root_types [i]);
-               emit_value (logbuffer, extra_info [i]);
-       }
-
-       EXIT_LOG;
-}
-
-static void
-gc_handle (MonoProfiler *prof, int op, int type, uintptr_t handle, MonoObject *obj)
-{
-       int do_bt = nocalls && InterlockedRead (&runtime_inited) && !notraces;
-       FrameData data;
-
-       if (do_bt)
-               collect_bt (&data);
-
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               LEB128_SIZE /* type */ +
-               LEB128_SIZE /* handle */ +
-               (op == MONO_PROFILER_GC_HANDLE_CREATED ? (
-                       LEB128_SIZE /* obj */
-               ) : 0) +
-               (do_bt ? (
-                       LEB128_SIZE /* count */ +
-                       data.count * (
-                               LEB128_SIZE /* method */
-                       )
-               ) : 0)
-       );
-
-       if (op == MONO_PROFILER_GC_HANDLE_CREATED)
-               emit_event (logbuffer, (do_bt ? TYPE_GC_HANDLE_CREATED_BT : TYPE_GC_HANDLE_CREATED) | TYPE_GC);
-       else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
-               emit_event (logbuffer, (do_bt ? TYPE_GC_HANDLE_DESTROYED_BT : TYPE_GC_HANDLE_DESTROYED) | TYPE_GC);
-       else
-               g_assert_not_reached ();
-
-       emit_value (logbuffer, type);
-       emit_value (logbuffer, handle);
-
-       if (op == MONO_PROFILER_GC_HANDLE_CREATED)
-               emit_obj (logbuffer, obj);
-
-       if (do_bt)
-               emit_bt (prof, logbuffer, &data);
-
-       EXIT_LOG;
-
-       process_requests (prof);
-}
-
-static void
-finalize_begin (MonoProfiler *prof)
-{
-       ENTER_LOG;
-
-       LogBuffer *buf = ensure_logbuf (
-               EVENT_SIZE /* event */
-       );
-
-       emit_event (buf, TYPE_GC_FINALIZE_START | TYPE_GC);
-
-       EXIT_LOG;
-
-       process_requests (prof);
-}
-
-static void
-finalize_end (MonoProfiler *prof)
-{
-       ENTER_LOG;
-
-       LogBuffer *buf = ensure_logbuf (
-               EVENT_SIZE /* event */
-       );
-
-       emit_event (buf, TYPE_GC_FINALIZE_END | TYPE_GC);
-
-       EXIT_LOG;
-
-       process_requests (prof);
-}
-
-static void
-finalize_object_begin (MonoProfiler *prof, MonoObject *obj)
-{
-       ENTER_LOG;
-
-       LogBuffer *buf = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               LEB128_SIZE /* obj */
-       );
-
-       emit_event (buf, TYPE_GC_FINALIZE_OBJECT_START | TYPE_GC);
-       emit_obj (buf, obj);
-
-       EXIT_LOG;
-
-       process_requests (prof);
-}
-
-static void
-finalize_object_end (MonoProfiler *prof, MonoObject *obj)
-{
-       ENTER_LOG;
-
-       LogBuffer *buf = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               LEB128_SIZE /* obj */
-       );
-
-       emit_event (buf, TYPE_GC_FINALIZE_OBJECT_END | TYPE_GC);
-       emit_obj (buf, obj);
-
-       EXIT_LOG;
-
-       process_requests (prof);
-}
-
-static char*
-push_nesting (char *p, MonoClass *klass)
-{
-       MonoClass *nesting;
-       const char *name;
-       const char *nspace;
-       nesting = mono_class_get_nesting_type (klass);
-       if (nesting) {
-               p = push_nesting (p, nesting);
-               *p++ = '/';
-               *p = 0;
-       }
-       name = mono_class_get_name (klass);
-       nspace = mono_class_get_namespace (klass);
-       if (*nspace) {
-               strcpy (p, nspace);
-               p += strlen (nspace);
-               *p++ = '.';
-               *p = 0;
-       }
-       strcpy (p, name);
-       p += strlen (name);
-       return p;
-}
-
-static char*
-type_name (MonoClass *klass)
-{
-       char buf [1024];
-       char *p;
-       push_nesting (buf, klass);
-       p = (char *)malloc (strlen (buf) + 1);
-       strcpy (p, buf);
-       return p;
-}
-
-static void
-image_loaded (MonoProfiler *prof, MonoImage *image, int result)
-{
-       if (result != MONO_PROFILE_OK)
-               return;
-
-       const char *name = mono_image_get_filename (image);
-       int nlen = strlen (name) + 1;
-
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               BYTE_SIZE /* type */ +
-               LEB128_SIZE /* image */ +
-               nlen /* name */
-       );
-
-       emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
-       emit_byte (logbuffer, TYPE_IMAGE);
-       emit_ptr (logbuffer, image);
-       memcpy (logbuffer->cursor, name, nlen);
-       logbuffer->cursor += nlen;
-
-       EXIT_LOG;
-
-       send_if_needed (prof);
-
-       process_requests (prof);
-
-       InterlockedIncrement (&image_loads);
-}
-
-static void
-image_unloaded (MonoProfiler *prof, MonoImage *image)
-{
-       const char *name = mono_image_get_filename (image);
-       int nlen = strlen (name) + 1;
-
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               BYTE_SIZE /* type */ +
-               LEB128_SIZE /* image */ +
-               nlen /* name */
-       );
-
-       emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
-       emit_byte (logbuffer, TYPE_IMAGE);
-       emit_ptr (logbuffer, image);
-       memcpy (logbuffer->cursor, name, nlen);
-       logbuffer->cursor += nlen;
-
-       EXIT_LOG;
-
-       send_if_needed (prof);
-
-       process_requests (prof);
-
-       InterlockedIncrement (&image_unloads);
-}
-
-static void
-assembly_loaded (MonoProfiler *prof, MonoAssembly *assembly, int result)
-{
-       if (result != MONO_PROFILE_OK)
-               return;
-
-       char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
-       int nlen = strlen (name) + 1;
-
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               BYTE_SIZE /* type */ +
-               LEB128_SIZE /* assembly */ +
-               nlen /* name */
-       );
-
-       emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
-       emit_byte (logbuffer, TYPE_ASSEMBLY);
-       emit_ptr (logbuffer, assembly);
-       memcpy (logbuffer->cursor, name, nlen);
-       logbuffer->cursor += nlen;
-
-       EXIT_LOG;
-
-       mono_free (name);
-
-       send_if_needed (prof);
-
-       process_requests (prof);
-
-       InterlockedIncrement (&assembly_loads);
-}
-
-static void
-assembly_unloaded (MonoProfiler *prof, MonoAssembly *assembly)
-{
-       char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
-       int nlen = strlen (name) + 1;
-
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               BYTE_SIZE /* type */ +
-               LEB128_SIZE /* assembly */ +
-               nlen /* name */
-       );
-
-       emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
-       emit_byte (logbuffer, TYPE_ASSEMBLY);
-       emit_ptr (logbuffer, assembly);
-       memcpy (logbuffer->cursor, name, nlen);
-       logbuffer->cursor += nlen;
-
-       EXIT_LOG;
-
-       mono_free (name);
-
-       send_if_needed (prof);
-
-       process_requests (prof);
-
-       InterlockedIncrement (&assembly_unloads);
-}
-
-static void
-class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
-{
-       if (result != MONO_PROFILE_OK)
-               return;
-
-       char *name;
-
-       if (InterlockedRead (&runtime_inited))
-               name = mono_type_get_name (mono_class_get_type (klass));
-       else
-               name = type_name (klass);
-
-       int nlen = strlen (name) + 1;
-       MonoImage *image = mono_class_get_image (klass);
-
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               BYTE_SIZE /* type */ +
-               LEB128_SIZE /* klass */ +
-               LEB128_SIZE /* image */ +
-               nlen /* name */
-       );
-
-       emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
-       emit_byte (logbuffer, TYPE_CLASS);
-       emit_ptr (logbuffer, klass);
-       emit_ptr (logbuffer, image);
-       memcpy (logbuffer->cursor, name, nlen);
-       logbuffer->cursor += nlen;
-
-       EXIT_LOG;
-
-       if (runtime_inited)
-               mono_free (name);
-       else
-               g_free (name);
-
-       send_if_needed (prof);
-
-       process_requests (prof);
-
-       InterlockedIncrement (&class_loads);
-}
-
-static void
-class_unloaded (MonoProfiler *prof, MonoClass *klass)
-{
-       char *name;
-
-       if (InterlockedRead (&runtime_inited))
-               name = mono_type_get_name (mono_class_get_type (klass));
-       else
-               name = type_name (klass);
-
-       int nlen = strlen (name) + 1;
-       MonoImage *image = mono_class_get_image (klass);
-
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               BYTE_SIZE /* type */ +
-               LEB128_SIZE /* klass */ +
-               LEB128_SIZE /* image */ +
-               nlen /* name */
-       );
-
-       emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
-       emit_byte (logbuffer, TYPE_CLASS);
-       emit_ptr (logbuffer, klass);
-       emit_ptr (logbuffer, image);
-       memcpy (logbuffer->cursor, name, nlen);
-       logbuffer->cursor += nlen;
-
-       EXIT_LOG;
-
-       if (runtime_inited)
-               mono_free (name);
-       else
-               g_free (name);
-
-       send_if_needed (prof);
-
-       process_requests (prof);
-
-       InterlockedIncrement (&class_unloads);
-}
-
-#ifndef DISABLE_HELPER_THREAD
-static void process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method);
-#endif /* DISABLE_HELPER_THREAD */
-
-static void
-method_enter (MonoProfiler *prof, MonoMethod *method)
-{
-#ifndef DISABLE_HELPER_THREAD
-       process_method_enter_coverage (prof, method);
-#endif /* DISABLE_HELPER_THREAD */
-
-       if (PROF_TLS_GET ()->call_depth++ <= max_call_depth) {
-               ENTER_LOG;
-
-               LogBuffer *logbuffer = ensure_logbuf (
-                       EVENT_SIZE /* event */ +
-                       LEB128_SIZE /* method */
-               );
-
-               emit_event (logbuffer, TYPE_ENTER | TYPE_METHOD);
-               emit_method (prof, logbuffer, method);
-
-               EXIT_LOG;
-       }
-
-       send_if_needed (prof);
-
-       process_requests (prof);
-}
-
-static void
-method_leave (MonoProfiler *prof, MonoMethod *method)
-{
-       if (--PROF_TLS_GET ()->call_depth <= max_call_depth) {
-               ENTER_LOG;
-
-               LogBuffer *logbuffer = ensure_logbuf (
-                       EVENT_SIZE /* event */ +
-                       LEB128_SIZE /* method */
-               );
-
-               emit_event (logbuffer, TYPE_LEAVE | TYPE_METHOD);
-               emit_method (prof, logbuffer, method);
-
-               EXIT_LOG;
-       }
-
-       send_if_needed (prof);
-
-       process_requests (prof);
-}
-
-static void
-method_exc_leave (MonoProfiler *prof, MonoMethod *method)
-{
-       if (!nocalls && --PROF_TLS_GET ()->call_depth <= max_call_depth) {
-               ENTER_LOG;
-
-               LogBuffer *logbuffer = ensure_logbuf (
-                       EVENT_SIZE /* event */ +
-                       LEB128_SIZE /* method */
-               );
-
-               emit_event (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
-               emit_method (prof, logbuffer, method);
-
-               EXIT_LOG;
-       }
-
-       send_if_needed (prof);
-
-       process_requests (prof);
-}
-
-static void
-method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji, int result)
-{
-       if (result != MONO_PROFILE_OK)
-               return;
-
-       register_method_local (prof, method, ji);
-
-       process_requests (prof);
-}
-
-static void
-code_buffer_new (MonoProfiler *prof, void *buffer, int size, MonoProfilerCodeBufferType type, void *data)
-{
-       char *name;
-       int nlen;
-
-       if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
-               name = (char *) data;
-               nlen = strlen (name) + 1;
-       } else {
-               name = NULL;
-               nlen = 0;
-       }
-
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               BYTE_SIZE /* type */ +
-               LEB128_SIZE /* buffer */ +
-               LEB128_SIZE /* size */ +
-               (name ? (
-                       nlen /* name */
-               ) : 0)
-       );
-
-       emit_event (logbuffer, TYPE_JITHELPER | TYPE_RUNTIME);
-       emit_byte (logbuffer, type);
-       emit_ptr (logbuffer, buffer);
-       emit_value (logbuffer, size);
-
-       if (name) {
-               memcpy (logbuffer->cursor, name, nlen);
-               logbuffer->cursor += nlen;
-       }
-
-       EXIT_LOG;
-
-       process_requests (prof);
-}
-
-static void
-throw_exc (MonoProfiler *prof, MonoObject *object)
-{
-       int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces) ? TYPE_THROW_BT : 0;
-       FrameData data;
-
-       if (do_bt)
-               collect_bt (&data);
-
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               LEB128_SIZE /* object */ +
-               (do_bt ? (
-                       LEB128_SIZE /* count */ +
-                       data.count * (
-                               LEB128_SIZE /* method */
-                       )
-               ) : 0)
-       );
-
-       emit_event (logbuffer, do_bt | TYPE_EXCEPTION);
-       emit_obj (logbuffer, object);
-
-       if (do_bt)
-               emit_bt (prof, logbuffer, &data);
-
-       EXIT_LOG;
-
-       process_requests (prof);
-}
-
-static void
-clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num)
-{
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               BYTE_SIZE /* clause type */ +
-               LEB128_SIZE /* clause num */ +
-               LEB128_SIZE /* method */
-       );
-
-       emit_event (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
-       emit_byte (logbuffer, clause_type);
-       emit_value (logbuffer, clause_num);
-       emit_method (prof, logbuffer, method);
-
-       EXIT_LOG;
-
-       process_requests (prof);
-}
-
-static void
-monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent event)
-{
-       int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces && event == MONO_PROFILER_MONITOR_CONTENTION) ? TYPE_MONITOR_BT : 0;
-       FrameData data;
-
-       if (do_bt)
-               collect_bt (&data);
-
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               LEB128_SIZE /* object */ +
-               (do_bt ? (
-                       LEB128_SIZE /* count */ +
-                       data.count * (
-                               LEB128_SIZE /* method */
-                       )
-               ) : 0)
-       );
-
-       emit_event (logbuffer, (event << 4) | do_bt | TYPE_MONITOR);
-       emit_obj (logbuffer, object);
-
-       if (do_bt)
-               emit_bt (profiler, logbuffer, &data);
-
-       EXIT_LOG;
-
-       process_requests (profiler);
-}
-
-static void
-thread_start (MonoProfiler *prof, uintptr_t tid)
-{
-       init_thread (TRUE);
-
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               BYTE_SIZE /* type */ +
-               LEB128_SIZE /* tid */
-       );
-
-       emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
-       emit_byte (logbuffer, TYPE_THREAD);
-       emit_ptr (logbuffer, (void*) tid);
-
-       EXIT_LOG;
-
-       send_if_needed (prof);
-
-       process_requests (prof);
-
-       InterlockedIncrement (&thread_starts);
-}
-
-static void
-thread_end (MonoProfiler *prof, uintptr_t tid)
-{
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               BYTE_SIZE /* type */ +
-               LEB128_SIZE /* tid */
-       );
-
-       emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
-       emit_byte (logbuffer, TYPE_THREAD);
-       emit_ptr (logbuffer, (void*) tid);
-
-       EXIT_LOG;
-
-       // Don't process requests as the thread is detached from the runtime.
-
-       remove_thread (prof, PROF_TLS_GET (), TRUE);
-
-       InterlockedIncrement (&thread_ends);
-}
-
-static void
-domain_loaded (MonoProfiler *prof, MonoDomain *domain, int result)
-{
-       if (result != MONO_PROFILE_OK)
-               return;
-
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               BYTE_SIZE /* type */ +
-               LEB128_SIZE /* domain id */
-       );
-
-       emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
-       emit_byte (logbuffer, TYPE_DOMAIN);
-       emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
-
-       EXIT_LOG;
-
-       send_if_needed (prof);
-
-       process_requests (prof);
-
-       InterlockedIncrement (&domain_loads);
-}
-
-static void
-domain_unloaded (MonoProfiler *prof, MonoDomain *domain)
-{
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               BYTE_SIZE /* type */ +
-               LEB128_SIZE /* domain id */
-       );
-
-       emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
-       emit_byte (logbuffer, TYPE_DOMAIN);
-       emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
-
-       EXIT_LOG;
-
-       send_if_needed (prof);
-
-       process_requests (prof);
-
-       InterlockedIncrement (&domain_unloads);
-}
-
-static void
-domain_name (MonoProfiler *prof, MonoDomain *domain, const char *name)
-{
-       int nlen = strlen (name) + 1;
-
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               BYTE_SIZE /* type */ +
-               LEB128_SIZE /* domain id */ +
-               nlen /* name */
-       );
-
-       emit_event (logbuffer, TYPE_METADATA);
-       emit_byte (logbuffer, TYPE_DOMAIN);
-       emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
-       memcpy (logbuffer->cursor, name, nlen);
-       logbuffer->cursor += nlen;
-
-       EXIT_LOG;
-
-       send_if_needed (prof);
-
-       process_requests (prof);
-}
-
-static void
-context_loaded (MonoProfiler *prof, MonoAppContext *context)
-{
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               BYTE_SIZE /* type */ +
-               LEB128_SIZE /* context id */ +
-               LEB128_SIZE /* domain id */
-       );
-
-       emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
-       emit_byte (logbuffer, TYPE_CONTEXT);
-       emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
-       emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
-
-       EXIT_LOG;
-
-       send_if_needed (prof);
-
-       process_requests (prof);
-
-       InterlockedIncrement (&context_loads);
-}
-
-static void
-context_unloaded (MonoProfiler *prof, MonoAppContext *context)
-{
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               BYTE_SIZE /* type */ +
-               LEB128_SIZE /* context id */ +
-               LEB128_SIZE /* domain id */
-       );
-
-       emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
-       emit_byte (logbuffer, TYPE_CONTEXT);
-       emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
-       emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
-
-       EXIT_LOG;
-
-       send_if_needed (prof);
-
-       process_requests (prof);
-
-       InterlockedIncrement (&context_unloads);
-}
-
-static void
-thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
-{
-       int len = strlen (name) + 1;
-
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               BYTE_SIZE /* type */ +
-               LEB128_SIZE /* tid */ +
-               len /* name */
-       );
-
-       emit_event (logbuffer, TYPE_METADATA);
-       emit_byte (logbuffer, TYPE_THREAD);
-       emit_ptr (logbuffer, (void*)tid);
-       memcpy (logbuffer->cursor, name, len);
-       logbuffer->cursor += len;
-
-       EXIT_LOG;
-
-       send_if_needed (prof);
-
-       process_requests (prof);
-}
-
-typedef struct {
-       MonoMethod *method;
-       MonoDomain *domain;
-       void *base_address;
-       int offset;
-} AsyncFrameInfo;
-
-typedef struct {
-       MonoLockFreeQueueNode node;
-       MonoProfiler *prof;
-       uint64_t time;
-       uintptr_t tid;
-       void *ip;
-       int count;
-       AsyncFrameInfo frames [MONO_ZERO_LEN_ARRAY];
-} SampleHit;
-
-static mono_bool
-async_walk_stack (MonoMethod *method, MonoDomain *domain, void *base_address, int offset, void *data)
-{
-       SampleHit *sample = (SampleHit *) data;
-
-       if (sample->count < num_frames) {
-               int i = sample->count;
-
-               sample->frames [i].method = method;
-               sample->frames [i].domain = domain;
-               sample->frames [i].base_address = base_address;
-               sample->frames [i].offset = offset;
-
-               sample->count++;
-       }
-
-       return sample->count == num_frames;
-}
-
-#define SAMPLE_SLOT_SIZE(FRAMES) (sizeof (SampleHit) + sizeof (AsyncFrameInfo) * (FRAMES - MONO_ZERO_LEN_ARRAY))
-#define SAMPLE_BLOCK_SIZE (mono_pagesize ())
-
-static void
-enqueue_sample_hit (gpointer p)
-{
-       SampleHit *sample = p;
-
-       mono_lock_free_queue_node_unpoison (&sample->node);
-       mono_lock_free_queue_enqueue (&sample->prof->dumper_queue, &sample->node);
-       mono_os_sem_post (&sample->prof->dumper_queue_sem);
-
-       InterlockedIncrement (&sample_flushes);
-}
-
-static void
-mono_sample_hit (MonoProfiler *profiler, unsigned char *ip, void *context)
-{
-       /*
-        * Please note: We rely on the runtime loading the profiler with
-        * MONO_DL_EAGER (RTLD_NOW) so that references to runtime functions within
-        * this function (and its siblings) are resolved when the profiler is
-        * loaded. Otherwise, we would potentially invoke the dynamic linker when
-        * invoking runtime functions, which is not async-signal-safe.
-        */
-
-       if (in_shutdown)
-               return;
-
-       InterlockedIncrement (&sample_hits);
-
-       SampleHit *sample = (SampleHit *) mono_lock_free_queue_dequeue (&profiler->sample_reuse_queue);
-
-       if (!sample) {
-               /*
-                * If we're out of reusable sample events and we're not allowed to
-                * allocate more, we have no choice but to drop the event.
-                */
-               if (InterlockedRead (&sample_allocations) >= max_allocated_sample_hits)
-                       return;
-
-               sample = mono_lock_free_alloc (&profiler->sample_allocator);
-               sample->prof = profiler;
-               mono_lock_free_queue_node_init (&sample->node, TRUE);
-
-               InterlockedIncrement (&sample_allocations);
-       }
-
-       sample->count = 0;
-       mono_stack_walk_async_safe (&async_walk_stack, context, sample);
-
-       sample->time = current_time ();
-       sample->tid = thread_id ();
-       sample->ip = ip;
-
-       if (do_debug) {
-               int len;
-               char buf [256];
-               snprintf (buf, sizeof (buf), "hit at %p in thread %p after %llu ms\n", ip, (void *) sample->tid, (unsigned long long int) ((sample->time - profiler->startup_time) / 10000 / 100));
-               len = strlen (buf);
-               ign_res (write (2, buf, len));
-       }
-
-       mono_thread_hazardous_try_free (sample, enqueue_sample_hit);
-}
-
-static uintptr_t *code_pages = 0;
-static int num_code_pages = 0;
-static int size_code_pages = 0;
-#define CPAGE_SHIFT (9)
-#define CPAGE_SIZE (1 << CPAGE_SHIFT)
-#define CPAGE_MASK (~(CPAGE_SIZE - 1))
-#define CPAGE_ADDR(p) ((p) & CPAGE_MASK)
-
-static uintptr_t
-add_code_page (uintptr_t *hash, uintptr_t hsize, uintptr_t page)
-{
-       uintptr_t i;
-       uintptr_t start_pos;
-       start_pos = (page >> CPAGE_SHIFT) % hsize;
-       i = start_pos;
-       do {
-               if (hash [i] && CPAGE_ADDR (hash [i]) == CPAGE_ADDR (page)) {
-                       return 0;
-               } else if (!hash [i]) {
-                       hash [i] = page;
-                       return 1;
-               }
-               /* wrap around */
-               if (++i == hsize)
-                       i = 0;
-       } while (i != start_pos);
-       /* should not happen */
-       printf ("failed code page store\n");
-       return 0;
-}
-
-static void
-add_code_pointer (uintptr_t ip)
-{
-       uintptr_t i;
-       if (num_code_pages * 2 >= size_code_pages) {
-               uintptr_t *n;
-               uintptr_t old_size = size_code_pages;
-               size_code_pages *= 2;
-               if (size_code_pages == 0)
-                       size_code_pages = 16;
-               n = (uintptr_t *)calloc (sizeof (uintptr_t) * size_code_pages, 1);
-               for (i = 0; i < old_size; ++i) {
-                       if (code_pages [i])
-                               add_code_page (n, size_code_pages, code_pages [i]);
-               }
-               if (code_pages)
-                       g_free (code_pages);
-               code_pages = n;
-       }
-       num_code_pages += add_code_page (code_pages, size_code_pages, ip & CPAGE_MASK);
-}
-
-/* ELF code crashes on some systems. */
-//#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
-#if 0
-static void
-dump_ubin (const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
-{
-       int len = strlen (filename) + 1;
-
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               LEB128_SIZE /* load address */ +
-               LEB128_SIZE /* offset */ +
-               LEB128_SIZE /* size */ +
-               nlen /* file name */
-       );
-
-       emit_event (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_UBIN);
-       emit_svalue (logbuffer, load_addr);
-       emit_uvalue (logbuffer, offset);
-       emit_uvalue (logbuffer, size);
-       memcpy (logbuffer->cursor, filename, len);
-       logbuffer->cursor += len;
-
-       EXIT_LOG;
-}
-#endif
-
-static void
-dump_usym (const char *name, uintptr_t value, uintptr_t size)
-{
-       int len = strlen (name) + 1;
-
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               LEB128_SIZE /* value */ +
-               LEB128_SIZE /* size */ +
-               len /* name */
-       );
-
-       emit_event (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_USYM);
-       emit_ptr (logbuffer, (void*)value);
-       emit_value (logbuffer, size);
-       memcpy (logbuffer->cursor, name, len);
-       logbuffer->cursor += len;
-
-       EXIT_LOG;
-}
-
-/* ELF code crashes on some systems. */
-//#if defined(ELFMAG0)
-#if 0
-
-#if SIZEOF_VOID_P == 4
-#define ELF_WSIZE 32
-#else
-#define ELF_WSIZE 64
-#endif
-#ifndef ElfW
-#define ElfW(type)      _ElfW (Elf, ELF_WSIZE, type)
-#define _ElfW(e,w,t)    _ElfW_1 (e, w, _##t)
-#define _ElfW_1(e,w,t)  e##w##t
-#endif
-
-static void
-dump_elf_symbols (ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
-{
-       int i;
-       for (i = 0; i < num_symbols; ++i) {
-               const char* sym;
-               sym =  strtab + symbols [i].st_name;
-               if (!symbols [i].st_name || !symbols [i].st_size || (symbols [i].st_info & 0xf) != STT_FUNC)
-                       continue;
-               //printf ("symbol %s at %d\n", sym, symbols [i].st_value);
-               dump_usym (sym, (uintptr_t)load_addr + symbols [i].st_value, symbols [i].st_size);
-       }
-}
-
-static int
-read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
-{
-       int fd, i;
-       void *data;
-       struct stat statb;
-       uint64_t file_size;
-       ElfW(Ehdr) *header;
-       ElfW(Shdr) *sheader;
-       ElfW(Shdr) *shstrtabh;
-       ElfW(Shdr) *symtabh = NULL;
-       ElfW(Shdr) *strtabh = NULL;
-       ElfW(Sym) *symbols = NULL;
-       const char *strtab;
-       int num_symbols;
-
-       fd = open (filename, O_RDONLY);
-       if (fd < 0)
-               return 0;
-       if (fstat (fd, &statb) != 0) {
-               close (fd);
-               return 0;
-       }
-       file_size = statb.st_size;
-       data = mmap (NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
-       close (fd);
-       if (data == MAP_FAILED)
-               return 0;
-       header = data;
-       if (header->e_ident [EI_MAG0] != ELFMAG0 ||
-                       header->e_ident [EI_MAG1] != ELFMAG1 ||
-                       header->e_ident [EI_MAG2] != ELFMAG2 ||
-                       header->e_ident [EI_MAG3] != ELFMAG3 ) {
-               munmap (data, file_size);
-               return 0;
-       }
-       sheader = (void*)((char*)data + header->e_shoff);
-       shstrtabh = (void*)((char*)sheader + (header->e_shentsize * header->e_shstrndx));
-       strtab = (const char*)data + shstrtabh->sh_offset;
-       for (i = 0; i < header->e_shnum; ++i) {
-               //printf ("section header: %d\n", sheader->sh_type);
-               if (sheader->sh_type == SHT_SYMTAB) {
-                       symtabh = sheader;
-                       strtabh = (void*)((char*)data + header->e_shoff + sheader->sh_link * header->e_shentsize);
-                       /*printf ("symtab section header: %d, .strstr: %d\n", i, sheader->sh_link);*/
-                       break;
-               }
-               sheader = (void*)((char*)sheader + header->e_shentsize);
-       }
-       if (!symtabh || !strtabh) {
-               munmap (data, file_size);
-               return 0;
-       }
-       strtab = (const char*)data + strtabh->sh_offset;
-       num_symbols = symtabh->sh_size / symtabh->sh_entsize;
-       symbols = (void*)((char*)data + symtabh->sh_offset);
-       dump_elf_symbols (symbols, num_symbols, strtab, load_addr);
-       munmap (data, file_size);
-       return 1;
-}
-#endif
-
-/* ELF code crashes on some systems. */
-//#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
-#if 0
-static int
-elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
-{
-       MonoProfiler *prof = data;
-       char buf [256];
-       const char *filename;
-       BinaryObject *obj;
-       char *a = (void*)info->dlpi_addr;
-       int i, num_sym;
-       ElfW(Dyn) *dyn = NULL;
-       ElfW(Sym) *symtab = NULL;
-       ElfW(Word) *hash_table = NULL;
-       ElfW(Ehdr) *header = NULL;
-       const char* strtab = NULL;
-       for (obj = prof->binary_objects; obj; obj = obj->next) {
-               if (obj->addr == a)
-                       return 0;
-       }
-       filename = info->dlpi_name;
-       if (!filename)
-               return 0;
-       if (!info->dlpi_addr && !filename [0]) {
-               int l = readlink ("/proc/self/exe", buf, sizeof (buf) - 1);
-               if (l > 0) {
-                       buf [l] = 0;
-                       filename = buf;
-               }
-       }
-       obj = g_calloc (sizeof (BinaryObject), 1);
-       obj->addr = (void*)info->dlpi_addr;
-       obj->name = pstrdup (filename);
-       obj->next = prof->binary_objects;
-       prof->binary_objects = obj;
-       //printf ("loaded file: %s at %p, segments: %d\n", filename, (void*)info->dlpi_addr, info->dlpi_phnum);
-       a = NULL;
-       for (i = 0; i < info->dlpi_phnum; ++i) {
-               //printf ("segment type %d file offset: %d, size: %d\n", info->dlpi_phdr[i].p_type, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
-               if (info->dlpi_phdr[i].p_type == PT_LOAD && !header) {
-                       header = (ElfW(Ehdr)*)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
-                       if (header->e_ident [EI_MAG0] != ELFMAG0 ||
-                                       header->e_ident [EI_MAG1] != ELFMAG1 ||
-                                       header->e_ident [EI_MAG2] != ELFMAG2 ||
-                                       header->e_ident [EI_MAG3] != ELFMAG3 ) {
-                               header = NULL;
-                       }
-                       dump_ubin (filename, info->dlpi_addr + info->dlpi_phdr[i].p_vaddr, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
-               } else if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
-                       dyn = (ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
-               }
-       }
-       if (read_elf_symbols (prof, filename, (void*)info->dlpi_addr))
-               return 0;
-       if (!info->dlpi_name || !info->dlpi_name[0])
-               return 0;
-       if (!dyn)
-               return 0;
-       for (i = 0; dyn [i].d_tag != DT_NULL; ++i) {
-               if (dyn [i].d_tag == DT_SYMTAB) {
-                       if (symtab && do_debug)
-                               printf ("multiple symtabs: %d\n", i);
-                       symtab = (ElfW(Sym) *)(a + dyn [i].d_un.d_ptr);
-               } else if (dyn [i].d_tag == DT_HASH) {
-                       hash_table = (ElfW(Word) *)(a + dyn [i].d_un.d_ptr);
-               } else if (dyn [i].d_tag == DT_STRTAB) {
-                       strtab = (const char*)(a + dyn [i].d_un.d_ptr);
-               }
-       }
-       if (!hash_table)
-               return 0;
-       num_sym = hash_table [1];
-       dump_elf_symbols (symtab, num_sym, strtab, (void*)info->dlpi_addr);
-       return 0;
-}
-
-static int
-load_binaries (MonoProfiler *prof)
-{
-       dl_iterate_phdr (elf_dl_callback, prof);
-       return 1;
-}
-#else
-static int
-load_binaries (MonoProfiler *prof)
-{
-       return 0;
-}
-#endif
-
-static const char*
-symbol_for (uintptr_t code)
-{
-#ifdef HAVE_DLADDR
-       void *ip = (void*)code;
-       Dl_info di;
-       if (dladdr (ip, &di)) {
-               if (di.dli_sname)
-                       return di.dli_sname;
-       } else {
-       /*      char **names;
-               names = backtrace_symbols (&ip, 1);
-               if (names) {
-                       const char* p = names [0];
-                       g_free (names);
-                       return p;
-               }
-               */
-       }
-#endif
-       return NULL;
-}
-
-static void
-dump_unmanaged_coderefs (MonoProfiler *prof)
-{
-       int i;
-       const char* last_symbol;
-       uintptr_t addr, page_end;
-
-       if (load_binaries (prof))
-               return;
-       for (i = 0; i < size_code_pages; ++i) {
-               const char* sym;
-               if (!code_pages [i] || code_pages [i] & 1)
-                       continue;
-               last_symbol = NULL;
-               addr = CPAGE_ADDR (code_pages [i]);
-               page_end = addr + CPAGE_SIZE;
-               code_pages [i] |= 1;
-               /* we dump the symbols for the whole page */
-               for (; addr < page_end; addr += 16) {
-                       sym = symbol_for (addr);
-                       if (sym && sym == last_symbol)
-                               continue;
-                       last_symbol = sym;
-                       if (!sym)
-                               continue;
-                       dump_usym (sym, addr, 0); /* let's not guess the size */
-                       //printf ("found symbol at %p: %s\n", (void*)addr, sym);
-               }
-       }
-}
-
-static int
-mono_cpu_count (void)
-{
-#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.
-        * Instead we use /sys entries to query the actual hardware CPU count.
-        */
-       int count = 0;
-       char buffer[8] = {'\0'};
-       int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
-       /* Format of the /sys entry is a cpulist of indexes which in the case
-        * of present is always of the form "0-(n-1)" when there is more than
-        * 1 core, n being the number of CPU cores in the system. Otherwise
-        * the value is simply 0
-        */
-       if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
-               count = strtol (((char*)buffer) + 2, NULL, 10);
-       if (present != -1)
-               close (present);
-       if (count > 0)
-               return count + 1;
-#endif
-
-#if defined(HOST_ARM) || defined (HOST_ARM64)
-
-       /* ARM platforms 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. */
-
-#ifdef _SC_NPROCESSORS_CONF
-       {
-               int count = sysconf (_SC_NPROCESSORS_CONF);
-               if (count > 0)
-                       return count;
-       }
-#endif
-
-#else
-
-#ifdef HAVE_SCHED_GETAFFINITY
-       {
-               cpu_set_t set;
-               if (sched_getaffinity (getpid (), sizeof (set), &set) == 0)
-                       return CPU_COUNT (&set);
-       }
-#endif
-#ifdef _SC_NPROCESSORS_ONLN
-       {
-               int count = sysconf (_SC_NPROCESSORS_ONLN);
-               if (count > 0)
-                       return count;
-       }
-#endif
-
-#endif /* defined(HOST_ARM) || defined (HOST_ARM64) */
-
-#ifdef USE_SYSCTL
-       {
-               int count;
-               int mib [2];
-               size_t len = sizeof (int);
-               mib [0] = CTL_HW;
-               mib [1] = HW_NCPU;
-               if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
-                       return count;
-       }
-#endif
-#ifdef HOST_WIN32
-       {
-               SYSTEM_INFO info;
-               GetSystemInfo (&info);
-               return info.dwNumberOfProcessors;
-       }
-#endif
-       /* FIXME: warn */
-       return 1;
-}
-
-#if USE_PERF_EVENTS
-
-typedef struct {
-       int perf_fd;
-       unsigned int prev_pos;
-       void *mmap_base;
-       struct perf_event_mmap_page *page_desc;
-} PerfData ;
-
-static PerfData *perf_data = NULL;
-static int num_perf;
-#define PERF_PAGES_SHIFT 4
-static int num_pages = 1 << PERF_PAGES_SHIFT;
-static unsigned int mmap_mask;
-
-typedef struct {
-       struct perf_event_header h;
-       uint64_t ip;
-       uint32_t pid;
-       uint32_t tid;
-       uint64_t timestamp;
-       uint64_t period;
-       uint64_t nframes;
-} PSample;
-
-static int
-perf_event_syscall (struct perf_event_attr *attr, pid_t pid, int cpu, int group_fd, unsigned long flags)
-{
-       attr->size = PERF_ATTR_SIZE_VER0;
-       //printf ("perf attr size: %d\n", attr->size);
-#if defined(__x86_64__)
-       return syscall(/*__NR_perf_event_open*/ 298, attr, pid, cpu, group_fd, flags);
-#elif defined(__i386__)
-       return syscall(/*__NR_perf_event_open*/ 336, attr, pid, cpu, group_fd, flags);
-#elif defined(__arm__) || defined (__aarch64__)
-       return syscall(/*__NR_perf_event_open*/ 364, attr, pid, cpu, group_fd, flags);
-#else
-       return -1;
-#endif
-}
-
-static int
-setup_perf_map (PerfData *perf)
-{
-       perf->mmap_base = mmap (NULL, (num_pages + 1) * getpagesize (), PROT_READ|PROT_WRITE, MAP_SHARED, perf->perf_fd, 0);
-       if (perf->mmap_base == MAP_FAILED) {
-               if (do_debug)
-                       printf ("failed mmap\n");
-               return 0;
-       }
-       perf->page_desc = perf->mmap_base;
-       if (do_debug)
-               printf ("mmap version: %d\n", perf->page_desc->version);
-       return 1;
-}
-
-static void
-dump_perf_hits (MonoProfiler *prof, void *buf, int size)
-{
-       int count = 1;
-       int mbt_count = 0;
-       void *end = (char*)buf + size;
-       int samples = 0;
-       int pid = getpid ();
-
-       while (buf < end) {
-               PSample *s = buf;
-               if (s->h.size == 0)
-                       break;
-               if (pid != s->pid) {
-                       if (do_debug)
-                               printf ("event for different pid: %d\n", s->pid);
-                       buf = (char*)buf + s->h.size;
-                       continue;
-               }
-               /*ip = (void*)s->ip;
-               printf ("sample: %d, size: %d, ip: %p (%s), timestamp: %llu, nframes: %llu\n",
-                       s->h.type, s->h.size, ip, symbol_for (ip), s->timestamp, s->nframes);*/
-
-               ENTER_LOG;
-
-               LogBuffer *logbuffer = ensure_logbuf (
-                       EVENT_SIZE /* event */ +
-                       BYTE_SIZE /* type */ +
-                       LEB128_SIZE /* tid */ +
-                       LEB128_SIZE /* count */ +
-                       count * (
-                               LEB128_SIZE /* ip */
-                       ) +
-                       LEB128_SIZE /* managed count */ +
-                       mbt_count * (
-                               LEB128_SIZE /* method */
-                       )
-               );
-
-               emit_event (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
-               emit_byte (logbuffer, sample_type);
-               /*
-                * No useful thread ID to write here, since throughout the
-                * profiler we use pthread_self () but the ID we get from
-                * perf is the kernel's thread ID.
-                */
-               emit_ptr (logbuffer, 0);
-               emit_value (logbuffer, count);
-               emit_ptr (logbuffer, (void*)(uintptr_t)s->ip);
-               /* no support here yet for the managed backtrace */
-               emit_uvalue (logbuffer, mbt_count);
-
-               EXIT_LOG;
-
-               add_code_pointer (s->ip);
-               buf = (char*)buf + s->h.size;
-               samples++;
-       }
-       if (do_debug)
-               printf ("dumped %d samples\n", samples);
-       dump_unmanaged_coderefs (prof);
-}
-
-/* read events from the ring buffer */
-static int
-read_perf_mmap (MonoProfiler* prof, int cpu)
-{
-       PerfData *perf = perf_data + cpu;
-       unsigned char *buf;
-       unsigned char *data = (unsigned char*)perf->mmap_base + getpagesize ();
-       unsigned int head = perf->page_desc->data_head;
-       int diff, size;
-       unsigned int old;
-
-       mono_memory_read_barrier ();
-
-       old = perf->prev_pos;
-       diff = head - old;
-       if (diff < 0) {
-               if (do_debug)
-                       printf ("lost mmap events: old: %d, head: %d\n", old, head);
-               old = head;
-       }
-       size = head - old;
-       if ((old & mmap_mask) + size != (head & mmap_mask)) {
-               buf = data + (old & mmap_mask);
-               size = mmap_mask + 1 - (old & mmap_mask);
-               old += size;
-               /* size bytes at buf */
-               if (do_debug)
-                       printf ("found1 bytes of events: %d\n", size);
-               dump_perf_hits (prof, buf, size);
-       }
-       buf = data + (old & mmap_mask);
-       size = head - old;
-       /* size bytes at buf */
-       if (do_debug)
-               printf ("found bytes of events: %d\n", size);
-       dump_perf_hits (prof, buf, size);
-       old += size;
-       perf->prev_pos = old;
-       perf->page_desc->data_tail = old;
-       return 0;
-}
-
-static int
-setup_perf_event_for_cpu (PerfData *perf, int cpu)
-{
-       struct perf_event_attr attr;
-       memset (&attr, 0, sizeof (attr));
-       attr.type = PERF_TYPE_HARDWARE;
-       switch (sample_type) {
-       case SAMPLE_CYCLES: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
-       case SAMPLE_INSTRUCTIONS: attr.config = PERF_COUNT_HW_INSTRUCTIONS; break;
-       case SAMPLE_CACHE_MISSES: attr.config = PERF_COUNT_HW_CACHE_MISSES; break;
-       case SAMPLE_CACHE_REFS: attr.config = PERF_COUNT_HW_CACHE_REFERENCES; break;
-       case SAMPLE_BRANCHES: attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS; break;
-       case SAMPLE_BRANCH_MISSES: attr.config = PERF_COUNT_HW_BRANCH_MISSES; break;
-       default: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
-       }
-       attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_PERIOD | PERF_SAMPLE_TIME;
-//     attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
-       attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING | PERF_FORMAT_ID;
-       attr.inherit = 1;
-       attr.freq = 1;
-       attr.sample_freq = sample_freq;
-
-       perf->perf_fd = perf_event_syscall (&attr, getpid (), cpu, -1, 0);
-       if (do_debug)
-               printf ("perf fd: %d, freq: %d, event: %llu\n", perf->perf_fd, sample_freq, attr.config);
-       if (perf->perf_fd < 0) {
-               if (perf->perf_fd == -EPERM) {
-                       fprintf (stderr, "Perf syscall denied, do \"echo 1 > /proc/sys/kernel/perf_event_paranoid\" as root to enable.\n");
-               } else {
-                       if (do_debug)
-                               perror ("open perf event");
-               }
-               return 0;
-       }
-       if (!setup_perf_map (perf)) {
-               close (perf->perf_fd);
-               perf->perf_fd = -1;
-               return 0;
-       }
-       return 1;
-}
-
-static int
-setup_perf_event (void)
-{
-       int i, count = 0;
-       mmap_mask = num_pages * getpagesize () - 1;
-       num_perf = mono_cpu_count ();
-       perf_data = g_calloc (num_perf, sizeof (PerfData));
-       for (i = 0; i < num_perf; ++i) {
-               count += setup_perf_event_for_cpu (perf_data + i, i);
-       }
-       if (count)
-               return 1;
-       g_free (perf_data);
-       perf_data = NULL;
-       return 0;
-}
-
-#endif /* USE_PERF_EVENTS */
-
-#ifndef DISABLE_HELPER_THREAD
-
-typedef struct MonoCounterAgent {
-       MonoCounter *counter;
-       // MonoCounterAgent specific data :
-       void *value;
-       size_t value_size;
-       short index;
-       short emitted;
-       struct MonoCounterAgent *next;
-} MonoCounterAgent;
-
-static MonoCounterAgent* counters;
-static gboolean counters_initialized = FALSE;
-static int counters_index = 1;
-static mono_mutex_t counters_mutex;
-
-static void
-counters_add_agent (MonoCounter *counter)
-{
-       MonoCounterAgent *agent, *item;
-
-       if (!counters_initialized)
-               return;
-
-       mono_os_mutex_lock (&counters_mutex);
-
-       for (agent = counters; agent; agent = agent->next) {
-               if (agent->counter == counter) {
-                       agent->value_size = 0;
-                       if (agent->value) {
-                               g_free (agent->value);
-                               agent->value = NULL;
-                       }
-                       mono_os_mutex_unlock (&counters_mutex);
-                       return;
-               }
-       }
-
-       agent = (MonoCounterAgent *)malloc (sizeof (MonoCounterAgent));
-       agent->counter = counter;
-       agent->value = NULL;
-       agent->value_size = 0;
-       agent->index = counters_index++;
-       agent->emitted = 0;
-       agent->next = NULL;
-
-       if (!counters) {
-               counters = agent;
-       } else {
-               item = counters;
-               while (item->next)
-                       item = item->next;
-               item->next = agent;
-       }
-
-       mono_os_mutex_unlock (&counters_mutex);
-}
-
-static mono_bool
-counters_init_foreach_callback (MonoCounter *counter, gpointer data)
-{
-       counters_add_agent (counter);
-       return TRUE;
-}
-
-static void
-counters_init (MonoProfiler *profiler)
-{
-       assert (!counters_initialized);
-
-       mono_os_mutex_init (&counters_mutex);
-
-       counters_initialized = TRUE;
-
-       mono_counters_on_register (&counters_add_agent);
-       mono_counters_foreach (counters_init_foreach_callback, NULL);
-}
-
-static void
-counters_emit (MonoProfiler *profiler)
-{
-       MonoCounterAgent *agent;
-       int len = 0;
-       int size =
-               EVENT_SIZE /* event */ +
-               LEB128_SIZE /* len */
-       ;
-
-       if (!counters_initialized)
-               return;
-
-       mono_os_mutex_lock (&counters_mutex);
-
-       for (agent = counters; agent; agent = agent->next) {
-               if (agent->emitted)
-                       continue;
-
-               size +=
-                       LEB128_SIZE /* section */ +
-                       strlen (mono_counter_get_name (agent->counter)) + 1 /* name */ +
-                       BYTE_SIZE /* type */ +
-                       BYTE_SIZE /* unit */ +
-                       BYTE_SIZE /* variance */ +
-                       LEB128_SIZE /* index */
-               ;
-
-               len += 1;
-       }
-
-       if (!len) {
-               mono_os_mutex_unlock (&counters_mutex);
-               return;
-       }
-
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (size);
-
-       emit_event (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
-       emit_value (logbuffer, len);
-
-       for (agent = counters; agent; agent = agent->next) {
-               const char *name;
-
-               if (agent->emitted)
-                       continue;
-
-               name = mono_counter_get_name (agent->counter);
-               emit_value (logbuffer, mono_counter_get_section (agent->counter));
-               emit_string (logbuffer, name, strlen (name) + 1);
-               emit_byte (logbuffer, mono_counter_get_type (agent->counter));
-               emit_byte (logbuffer, mono_counter_get_unit (agent->counter));
-               emit_byte (logbuffer, mono_counter_get_variance (agent->counter));
-               emit_value (logbuffer, agent->index);
-
-               agent->emitted = 1;
-       }
-
-       EXIT_LOG;
-
-       mono_os_mutex_unlock (&counters_mutex);
-}
-
-static void
-counters_sample (MonoProfiler *profiler, uint64_t timestamp)
-{
-       MonoCounterAgent *agent;
-       MonoCounter *counter;
-       int type;
-       int buffer_size;
-       void *buffer;
-       int size;
-
-       if (!counters_initialized)
-               return;
-
-       counters_emit (profiler);
-
-       buffer_size = 8;
-       buffer = g_calloc (1, buffer_size);
-
-       mono_os_mutex_lock (&counters_mutex);
-
-       size =
-               EVENT_SIZE /* event */
-       ;
-
-       for (agent = counters; agent; agent = agent->next) {
-               size +=
-                       LEB128_SIZE /* index */ +
-                       BYTE_SIZE /* type */ +
-                       mono_counter_get_size (agent->counter) /* value */
-               ;
-       }
-
-       size +=
-               LEB128_SIZE /* stop marker */
-       ;
-
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (size);
-
-       emit_event_time (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE, timestamp);
-
-       for (agent = counters; agent; agent = agent->next) {
-               size_t size;
-
-               counter = agent->counter;
-
-               size = mono_counter_get_size (counter);
-               if (size < 0) {
-                       continue; // FIXME error
-               } else if (size > buffer_size) {
-                       buffer_size = size;
-                       buffer = g_realloc (buffer, buffer_size);
-               }
-
-               memset (buffer, 0, buffer_size);
-
-               if (mono_counters_sample (counter, buffer, size) < 0)
-                       continue; // FIXME error
-
-               type = mono_counter_get_type (counter);
-
-               if (!agent->value) {
-                       agent->value = g_calloc (1, size);
-                       agent->value_size = size;
-               } else {
-                       if (type == MONO_COUNTER_STRING) {
-                               if (strcmp (agent->value, buffer) == 0)
-                                       continue;
-                       } else {
-                               if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
-                                       continue;
-                       }
-               }
-
-               emit_uvalue (logbuffer, agent->index);
-               emit_byte (logbuffer, type);
-               switch (type) {
-               case MONO_COUNTER_INT:
-#if SIZEOF_VOID_P == 4
-               case MONO_COUNTER_WORD:
-#endif
-                       emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
-                       break;
-               case MONO_COUNTER_UINT:
-                       emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
-                       break;
-               case MONO_COUNTER_TIME_INTERVAL:
-               case MONO_COUNTER_LONG:
-#if SIZEOF_VOID_P == 8
-               case MONO_COUNTER_WORD:
-#endif
-                       emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
-                       break;
-               case MONO_COUNTER_ULONG:
-                       emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
-                       break;
-               case MONO_COUNTER_DOUBLE:
-                       emit_double (logbuffer, *(double*)buffer);
-                       break;
-               case MONO_COUNTER_STRING:
-                       if (size == 0) {
-                               emit_byte (logbuffer, 0);
-                       } else {
-                               emit_byte (logbuffer, 1);
-                               emit_string (logbuffer, (char*)buffer, size);
-                       }
-                       break;
-               default:
-                       assert (0);
-               }
-
-               if (type == MONO_COUNTER_STRING && size > agent->value_size) {
-                       agent->value = g_realloc (agent->value, size);
-                       agent->value_size = size;
-               }
-
-               if (size > 0)
-                       memcpy (agent->value, buffer, size);
-       }
-       g_free (buffer);
-
-       emit_value (logbuffer, 0);
-
-       EXIT_LOG;
-
-       mono_os_mutex_unlock (&counters_mutex);
-}
-
-typedef struct _PerfCounterAgent PerfCounterAgent;
-struct _PerfCounterAgent {
-       PerfCounterAgent *next;
-       int index;
-       char *category_name;
-       char *name;
-       int type;
-       gint64 value;
-       guint8 emitted;
-       guint8 updated;
-       guint8 deleted;
-};
-
-static PerfCounterAgent *perfcounters = NULL;
-
-static void
-perfcounters_emit (MonoProfiler *profiler)
-{
-       PerfCounterAgent *pcagent;
-       int len = 0;
-       int size =
-               EVENT_SIZE /* event */ +
-               LEB128_SIZE /* len */
-       ;
-
-       for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
-               if (pcagent->emitted)
-                       continue;
-
-               size +=
-                       LEB128_SIZE /* section */ +
-                       strlen (pcagent->category_name) + 1 /* category name */ +
-                       strlen (pcagent->name) + 1 /* name */ +
-                       BYTE_SIZE /* type */ +
-                       BYTE_SIZE /* unit */ +
-                       BYTE_SIZE /* variance */ +
-                       LEB128_SIZE /* index */
-               ;
-
-               len += 1;
-       }
-
-       if (!len)
-               return;
-
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (size);
-
-       emit_event (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
-       emit_value (logbuffer, len);
-
-       for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
-               if (pcagent->emitted)
-                       continue;
-
-               emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
-               emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
-               emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
-               emit_byte (logbuffer, MONO_COUNTER_LONG);
-               emit_byte (logbuffer, MONO_COUNTER_RAW);
-               emit_byte (logbuffer, MONO_COUNTER_VARIABLE);
-               emit_value (logbuffer, pcagent->index);
-
-               pcagent->emitted = 1;
-       }
-
-       EXIT_LOG;
-}
-
-static gboolean
-perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
-{
-       PerfCounterAgent *pcagent;
-
-       for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
-               if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
-                       continue;
-               if (pcagent->value == value)
-                       return TRUE;
-
-               pcagent->value = value;
-               pcagent->updated = 1;
-               pcagent->deleted = 0;
-               return TRUE;
-       }
-
-       pcagent = g_new0 (PerfCounterAgent, 1);
-       pcagent->next = perfcounters;
-       pcagent->index = counters_index++;
-       pcagent->category_name = g_strdup (category_name);
-       pcagent->name = g_strdup (name);
-       pcagent->type = (int) type;
-       pcagent->value = value;
-       pcagent->emitted = 0;
-       pcagent->updated = 1;
-       pcagent->deleted = 0;
-
-       perfcounters = pcagent;
-
-       return TRUE;
-}
-
-static void
-perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp)
-{
-       PerfCounterAgent *pcagent;
-       int size;
-
-       if (!counters_initialized)
-               return;
-
-       mono_os_mutex_lock (&counters_mutex);
-
-       /* mark all perfcounters as deleted, foreach will unmark them as necessary */
-       for (pcagent = perfcounters; pcagent; pcagent = pcagent->next)
-               pcagent->deleted = 1;
-
-       mono_perfcounter_foreach (perfcounters_foreach, perfcounters);
-
-       perfcounters_emit (profiler);
-
-       size =
-               EVENT_SIZE /* event */
-       ;
-
-       for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
-               if (pcagent->deleted || !pcagent->updated)
-                       continue;
-
-               size +=
-                       LEB128_SIZE /* index */ +
-                       BYTE_SIZE /* type */ +
-                       LEB128_SIZE /* value */
-               ;
-       }
-
-       size +=
-               LEB128_SIZE /* stop marker */
-       ;
-
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (size);
-
-       emit_event_time (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE, timestamp);
-
-       for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
-               if (pcagent->deleted || !pcagent->updated)
-                       continue;
-               emit_uvalue (logbuffer, pcagent->index);
-               emit_byte (logbuffer, MONO_COUNTER_LONG);
-               emit_svalue (logbuffer, pcagent->value);
-
-               pcagent->updated = 0;
-       }
-
-       emit_value (logbuffer, 0);
-
-       EXIT_LOG;
-
-       mono_os_mutex_unlock (&counters_mutex);
-}
-
-static void
-counters_and_perfcounters_sample (MonoProfiler *prof)
-{
-       uint64_t now = current_time ();
-
-       counters_sample (prof, now);
-       perfcounters_sample (prof, now);
-}
-
-#define COVERAGE_DEBUG(x) if (debug_coverage) {x}
-static mono_mutex_t coverage_mutex;
-static MonoConcurrentHashTable *coverage_methods = NULL;
-static MonoConcurrentHashTable *coverage_assemblies = NULL;
-static MonoConcurrentHashTable *coverage_classes = NULL;
-
-static MonoConcurrentHashTable *filtered_classes = NULL;
-static MonoConcurrentHashTable *entered_methods = NULL;
-static MonoConcurrentHashTable *image_to_methods = NULL;
-static MonoConcurrentHashTable *suppressed_assemblies = NULL;
-static gboolean coverage_initialized = FALSE;
-
-static GPtrArray *coverage_data = NULL;
-static int previous_offset = 0;
-
-typedef struct {
-       MonoLockFreeQueueNode node;
-       MonoMethod *method;
-} MethodNode;
-
-typedef struct {
-       int offset;
-       int counter;
-       char *filename;
-       int line;
-       int column;
-} CoverageEntry;
-
-static void
-free_coverage_entry (gpointer data, gpointer userdata)
-{
-       CoverageEntry *entry = (CoverageEntry *)data;
-       g_free (entry->filename);
-       g_free (entry);
-}
-
-static void
-obtain_coverage_for_method (MonoProfiler *prof, const MonoProfileCoverageEntry *entry)
-{
-       int offset = entry->iloffset - previous_offset;
-       CoverageEntry *e = g_new (CoverageEntry, 1);
-
-       previous_offset = entry->iloffset;
-
-       e->offset = offset;
-       e->counter = entry->counter;
-       e->filename = g_strdup(entry->filename ? entry->filename : "");
-       e->line = entry->line;
-       e->column = entry->col;
-
-       g_ptr_array_add (coverage_data, e);
-}
-
-static char *
-parse_generic_type_names(char *name)
-{
-       char *new_name, *ret;
-       int within_generic_declaration = 0, generic_members = 1;
-
-       if (name == NULL || *name == '\0')
-               return g_strdup ("");
-
-       if (!(ret = new_name = (char *)calloc (strlen (name) * 4 + 1, sizeof (char))))
-               return NULL;
-
-       do {
-               switch (*name) {
-                       case '<':
-                               within_generic_declaration = 1;
-                               break;
-
-                       case '>':
-                               within_generic_declaration = 0;
-
-                               if (*(name - 1) != '<') {
-                                       *new_name++ = '`';
-                                       *new_name++ = '0' + generic_members;
-                               } else {
-                                       memcpy (new_name, "&lt;&gt;", 8);
-                                       new_name += 8;
-                               }
-
-                               generic_members = 0;
-                               break;
-
-                       case ',':
-                               generic_members++;
-                               break;
-
-                       default:
-                               if (!within_generic_declaration)
-                                       *new_name++ = *name;
-
-                               break;
-               }
-       } while (*name++);
-
-       return ret;
-}
-
-static int method_id;
-static void
-build_method_buffer (gpointer key, gpointer value, gpointer userdata)
-{
-       MonoMethod *method = (MonoMethod *)value;
-       MonoProfiler *prof = (MonoProfiler *)userdata;
-       MonoClass *klass;
-       MonoImage *image;
-       char *class_name;
-       const char *image_name, *method_name, *sig, *first_filename;
-       guint i;
-
-       previous_offset = 0;
-       coverage_data = g_ptr_array_new ();
-
-       mono_profiler_coverage_get (prof, method, obtain_coverage_for_method);
-
-       klass = mono_method_get_class (method);
-       image = mono_class_get_image (klass);
-       image_name = mono_image_get_name (image);
-
-       sig = mono_signature_get_desc (mono_method_signature (method), TRUE);
-       class_name = parse_generic_type_names (mono_type_get_name (mono_class_get_type (klass)));
-       method_name = mono_method_get_name (method);
-
-       if (coverage_data->len != 0) {
-               CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[0];
-               first_filename = entry->filename ? entry->filename : "";
-       } else
-               first_filename = "";
-
-       image_name = image_name ? image_name : "";
-       sig = sig ? sig : "";
-       method_name = method_name ? method_name : "";
-
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               strlen (image_name) + 1 /* image name */ +
-               strlen (class_name) + 1 /* class name */ +
-               strlen (method_name) + 1 /* method name */ +
-               strlen (sig) + 1 /* signature */ +
-               strlen (first_filename) + 1 /* first file name */ +
-               LEB128_SIZE /* token */ +
-               LEB128_SIZE /* method id */ +
-               LEB128_SIZE /* entries */
-       );
-
-       emit_event (logbuffer, TYPE_COVERAGE_METHOD | TYPE_COVERAGE);
-       emit_string (logbuffer, image_name, strlen (image_name) + 1);
-       emit_string (logbuffer, class_name, strlen (class_name) + 1);
-       emit_string (logbuffer, method_name, strlen (method_name) + 1);
-       emit_string (logbuffer, sig, strlen (sig) + 1);
-       emit_string (logbuffer, first_filename, strlen (first_filename) + 1);
-
-       emit_uvalue (logbuffer, mono_method_get_token (method));
-       emit_uvalue (logbuffer, method_id);
-       emit_value (logbuffer, coverage_data->len);
-
-       EXIT_LOG;
-
-       send_if_needed (prof);
-
-       for (i = 0; i < coverage_data->len; i++) {
-               CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[i];
-
-               ENTER_LOG;
-
-               LogBuffer *logbuffer = ensure_logbuf (
-                       EVENT_SIZE /* event */ +
-                       LEB128_SIZE /* method id */ +
-                       LEB128_SIZE /* offset */ +
-                       LEB128_SIZE /* counter */ +
-                       LEB128_SIZE /* line */ +
-                       LEB128_SIZE /* column */
-               );
-
-               emit_event (logbuffer, TYPE_COVERAGE_STATEMENT | TYPE_COVERAGE);
-               emit_uvalue (logbuffer, method_id);
-               emit_uvalue (logbuffer, entry->offset);
-               emit_uvalue (logbuffer, entry->counter);
-               emit_uvalue (logbuffer, entry->line);
-               emit_uvalue (logbuffer, entry->column);
-
-               EXIT_LOG;
-
-               send_if_needed (prof);
-       }
-
-       method_id++;
-
-       g_free (class_name);
-
-       g_ptr_array_foreach (coverage_data, free_coverage_entry, NULL);
-       g_ptr_array_free (coverage_data, TRUE);
-       coverage_data = NULL;
-}
-
-/* This empties the queue */
-static guint
-count_queue (MonoLockFreeQueue *queue)
-{
-       MonoLockFreeQueueNode *node;
-       guint count = 0;
-
-       while ((node = mono_lock_free_queue_dequeue (queue))) {
-               count++;
-               mono_thread_hazardous_try_free (node, free);
-       }
-
-       return count;
-}
-
-static void
-build_class_buffer (gpointer key, gpointer value, gpointer userdata)
-{
-       MonoClass *klass = (MonoClass *)key;
-       MonoLockFreeQueue *class_methods = (MonoLockFreeQueue *)value;
-       MonoProfiler *prof = (MonoProfiler *)userdata;
-       MonoImage *image;
-       char *class_name;
-       const char *assembly_name;
-       int number_of_methods, partially_covered;
-       guint fully_covered;
-
-       image = mono_class_get_image (klass);
-       assembly_name = mono_image_get_name (image);
-       class_name = mono_type_get_name (mono_class_get_type (klass));
-
-       assembly_name = assembly_name ? assembly_name : "";
-       number_of_methods = mono_class_num_methods (klass);
-       fully_covered = count_queue (class_methods);
-       /* We don't handle partial covered yet */
-       partially_covered = 0;
-
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               strlen (assembly_name) + 1 /* assembly name */ +
-               strlen (class_name) + 1 /* class name */ +
-               LEB128_SIZE /* no. methods */ +
-               LEB128_SIZE /* fully covered */ +
-               LEB128_SIZE /* partially covered */
-       );
-
-       emit_event (logbuffer, TYPE_COVERAGE_CLASS | TYPE_COVERAGE);
-       emit_string (logbuffer, assembly_name, strlen (assembly_name) + 1);
-       emit_string (logbuffer, class_name, strlen (class_name) + 1);
-       emit_uvalue (logbuffer, number_of_methods);
-       emit_uvalue (logbuffer, fully_covered);
-       emit_uvalue (logbuffer, partially_covered);
-
-       EXIT_LOG;
-
-       send_if_needed (prof);
-
-       g_free (class_name);
-}
-
-static void
-get_coverage_for_image (MonoImage *image, int *number_of_methods, guint *fully_covered, int *partially_covered)
-{
-       MonoLockFreeQueue *image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
-
-       *number_of_methods = mono_image_get_table_rows (image, MONO_TABLE_METHOD);
-       if (image_methods)
-               *fully_covered = count_queue (image_methods);
-       else
-               *fully_covered = 0;
-
-       // FIXME: We don't handle partially covered yet.
-       *partially_covered = 0;
-}
-
-static void
-build_assembly_buffer (gpointer key, gpointer value, gpointer userdata)
-{
-       MonoAssembly *assembly = (MonoAssembly *)value;
-       MonoProfiler *prof = (MonoProfiler *)userdata;
-       MonoImage *image = mono_assembly_get_image (assembly);
-       const char *name, *guid, *filename;
-       int number_of_methods = 0, partially_covered = 0;
-       guint fully_covered = 0;
-
-       name = mono_image_get_name (image);
-       guid = mono_image_get_guid (image);
-       filename = mono_image_get_filename (image);
-
-       name = name ? name : "";
-       guid = guid ? guid : "";
-       filename = filename ? filename : "";
-
-       get_coverage_for_image (image, &number_of_methods, &fully_covered, &partially_covered);
-
-       ENTER_LOG;
-
-       LogBuffer *logbuffer = ensure_logbuf (
-               EVENT_SIZE /* event */ +
-               strlen (name) + 1 /* name */ +
-               strlen (guid) + 1 /* guid */ +
-               strlen (filename) + 1 /* file name */ +
-               LEB128_SIZE /* no. methods */ +
-               LEB128_SIZE /* fully covered */ +
-               LEB128_SIZE /* partially covered */
-       );
-
-       emit_event (logbuffer, TYPE_COVERAGE_ASSEMBLY | TYPE_COVERAGE);
-       emit_string (logbuffer, name, strlen (name) + 1);
-       emit_string (logbuffer, guid, strlen (guid) + 1);
-       emit_string (logbuffer, filename, strlen (filename) + 1);
-       emit_uvalue (logbuffer, number_of_methods);
-       emit_uvalue (logbuffer, fully_covered);
-       emit_uvalue (logbuffer, partially_covered);
-
-       EXIT_LOG;
-
-       send_if_needed (prof);
-}
-
-static void
-dump_coverage (MonoProfiler *prof)
-{
-       if (!coverage_initialized)
-               return;
-
-       COVERAGE_DEBUG(fprintf (stderr, "Coverage: Started dump\n");)
-       method_id = 0;
-
-       mono_os_mutex_lock (&coverage_mutex);
-       mono_conc_hashtable_foreach (coverage_assemblies, build_assembly_buffer, prof);
-       mono_conc_hashtable_foreach (coverage_classes, build_class_buffer, prof);
-       mono_conc_hashtable_foreach (coverage_methods, build_method_buffer, prof);
-       mono_os_mutex_unlock (&coverage_mutex);
-
-       COVERAGE_DEBUG(fprintf (stderr, "Coverage: Finished dump\n");)
-}
-
-static void
-process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method)
-{
-       MonoClass *klass;
-       MonoImage *image;
-
-       if (!coverage_initialized)
-               return;
-
-       klass = mono_method_get_class (method);
-       image = mono_class_get_image (klass);
-
-       if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)))
-               return;
-
-       mono_os_mutex_lock (&coverage_mutex);
-       mono_conc_hashtable_insert (entered_methods, method, method);
-       mono_os_mutex_unlock (&coverage_mutex);
-}
-
-static MonoLockFreeQueueNode *
-create_method_node (MonoMethod *method)
-{
-       MethodNode *node = (MethodNode *)g_malloc (sizeof (MethodNode));
-       mono_lock_free_queue_node_init ((MonoLockFreeQueueNode *) node, FALSE);
-       node->method = method;
-
-       return (MonoLockFreeQueueNode *) node;
-}
-
-static gboolean
-coverage_filter (MonoProfiler *prof, MonoMethod *method)
-{
-       MonoError error;
-       MonoClass *klass;
-       MonoImage *image;
-       MonoAssembly *assembly;
-       MonoMethodHeader *header;
-       guint32 iflags, flags, code_size;
-       char *fqn, *classname;
-       gboolean has_positive, found;
-       MonoLockFreeQueue *image_methods, *class_methods;
-       MonoLockFreeQueueNode *node;
-
-       if (!coverage_initialized)
-               return FALSE;
-
-       COVERAGE_DEBUG(fprintf (stderr, "Coverage filter for %s\n", mono_method_get_name (method));)
-
-       flags = mono_method_get_flags (method, &iflags);
-       if ((iflags & 0x1000 /*METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL*/) ||
-           (flags & 0x2000 /*METHOD_ATTRIBUTE_PINVOKE_IMPL*/)) {
-               COVERAGE_DEBUG(fprintf (stderr, "   Internal call or pinvoke - ignoring\n");)
-               return FALSE;
-       }
-
-       // Don't need to do anything else if we're already tracking this method
-       if (mono_conc_hashtable_lookup (coverage_methods, method)) {
-               COVERAGE_DEBUG(fprintf (stderr, "   Already tracking\n");)
-               return TRUE;
-       }
-
-       klass = mono_method_get_class (method);
-       image = mono_class_get_image (klass);
-
-       // Don't handle coverage for the core assemblies
-       if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)) != NULL)
-               return FALSE;
-
-       if (prof->coverage_filters) {
-               /* Check already filtered classes first */
-               if (mono_conc_hashtable_lookup (filtered_classes, klass)) {
-                       COVERAGE_DEBUG(fprintf (stderr, "   Already filtered\n");)
-                       return FALSE;
-               }
-
-               classname = mono_type_get_name (mono_class_get_type (klass));
-
-               fqn = g_strdup_printf ("[%s]%s", mono_image_get_name (image), classname);
-
-               COVERAGE_DEBUG(fprintf (stderr, "   Looking for %s in filter\n", fqn);)
-               // Check positive filters first
-               has_positive = FALSE;
-               found = FALSE;
-               for (guint i = 0; i < prof->coverage_filters->len; ++i) {
-                       char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
-
-                       if (filter [0] == '+') {
-                               filter = &filter [1];
-
-                               COVERAGE_DEBUG(fprintf (stderr, "   Checking against +%s ...", filter);)
-
-                               if (strstr (fqn, filter) != NULL) {
-                                       COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
-                                       found = TRUE;
-                               } else
-                                       COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
-
-                               has_positive = TRUE;
-                       }
-               }
-
-               if (has_positive && !found) {
-                       COVERAGE_DEBUG(fprintf (stderr, "   Positive match was not found\n");)
-
-                       mono_os_mutex_lock (&coverage_mutex);
-                       mono_conc_hashtable_insert (filtered_classes, klass, klass);
-                       mono_os_mutex_unlock (&coverage_mutex);
-                       g_free (fqn);
-                       g_free (classname);
-
-                       return FALSE;
-               }
-
-               for (guint i = 0; i < prof->coverage_filters->len; ++i) {
-                       // FIXME: Is substring search sufficient?
-                       char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
-                       if (filter [0] == '+')
-                               continue;
-
-                       // Skip '-'
-                       filter = &filter [1];
-                       COVERAGE_DEBUG(fprintf (stderr, "   Checking against -%s ...", filter);)
-
-                       if (strstr (fqn, filter) != NULL) {
-                               COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
-
-                               mono_os_mutex_lock (&coverage_mutex);
-                               mono_conc_hashtable_insert (filtered_classes, klass, klass);
-                               mono_os_mutex_unlock (&coverage_mutex);
-                               g_free (fqn);
-                               g_free (classname);
-
-                               return FALSE;
-                       } else
-                               COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
-
-               }
-
-               g_free (fqn);
-               g_free (classname);
-       }
-
-       COVERAGE_DEBUG(fprintf (stderr, "   Handling coverage for %s\n", mono_method_get_name (method));)
-       header = mono_method_get_header_checked (method, &error);
-       mono_error_cleanup (&error);
-
-       mono_method_header_get_code (header, &code_size, NULL);
-
-       assembly = mono_image_get_assembly (image);
-
-       // Need to keep the assemblies around for as long as they are kept in the hashtable
-       // Nunit, for example, has a habit of unloading them before the coverage statistics are
-       // generated causing a crash. See https://bugzilla.xamarin.com/show_bug.cgi?id=39325
-       mono_assembly_addref (assembly);
-
-       mono_os_mutex_lock (&coverage_mutex);
-       mono_conc_hashtable_insert (coverage_methods, method, method);
-       mono_conc_hashtable_insert (coverage_assemblies, assembly, assembly);
-       mono_os_mutex_unlock (&coverage_mutex);
-
-       image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
-
-       if (image_methods == NULL) {
-               image_methods = (MonoLockFreeQueue *)g_malloc (sizeof (MonoLockFreeQueue));
-               mono_lock_free_queue_init (image_methods);
-               mono_os_mutex_lock (&coverage_mutex);
-               mono_conc_hashtable_insert (image_to_methods, image, image_methods);
-               mono_os_mutex_unlock (&coverage_mutex);
-       }
-
-       node = create_method_node (method);
-       mono_lock_free_queue_enqueue (image_methods, node);
-
-       class_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (coverage_classes, klass);
-
-       if (class_methods == NULL) {
-               class_methods = (MonoLockFreeQueue *)g_malloc (sizeof (MonoLockFreeQueue));
-               mono_lock_free_queue_init (class_methods);
-               mono_os_mutex_lock (&coverage_mutex);
-               mono_conc_hashtable_insert (coverage_classes, klass, class_methods);
-               mono_os_mutex_unlock (&coverage_mutex);
-       }
-
-       node = create_method_node (method);
-       mono_lock_free_queue_enqueue (class_methods, node);
-
-       return TRUE;
-}
-
-#define LINE_BUFFER_SIZE 4096
-/* Max file limit of 128KB */
-#define MAX_FILE_SIZE 128 * 1024
-static char *
-get_file_content (FILE *stream)
-{
-       char *buffer;
-       ssize_t bytes_read;
-       long filesize;
-       int res, offset = 0;
-
-       res = fseek (stream, 0, SEEK_END);
-       if (res < 0)
-         return NULL;
-
-       filesize = ftell (stream);
-       if (filesize < 0)
-         return NULL;
-
-       res = fseek (stream, 0, SEEK_SET);
-       if (res < 0)
-         return NULL;
-
-       if (filesize > MAX_FILE_SIZE)
-         return NULL;
-
-       buffer = (char *)g_malloc ((filesize + 1) * sizeof (char));
-       while ((bytes_read = fread (buffer + offset, 1, LINE_BUFFER_SIZE, stream)) > 0)
-               offset += bytes_read;
-
-       /* NULL terminate our buffer */
-       buffer[filesize] = '\0';
-       return buffer;
-}
-
-static char *
-get_next_line (char *contents, char **next_start)
-{
-       char *p = contents;
-
-       if (p == NULL || *p == '\0') {
-               *next_start = NULL;
-               return NULL;
-       }
-
-       while (*p != '\n' && *p != '\0')
-               p++;
-
-       if (*p == '\n') {
-               *p = '\0';
-               *next_start = p + 1;
-       } else
-               *next_start = NULL;
-
-       return contents;
-}
-
-static void
-init_suppressed_assemblies (void)
-{
-       char *content;
-       char *line;
-       FILE *sa_file;
-
-       suppressed_assemblies = mono_conc_hashtable_new (g_str_hash, g_str_equal);
-       sa_file = fopen (SUPPRESSION_DIR "/mono-profiler-log.suppression", "r");
-       if (sa_file == NULL)
-               return;
-
-       /* Don't need to free @content as it is referred to by the lines stored in @suppressed_assemblies */
-       content = get_file_content (sa_file);
-       if (content == NULL) {
-               g_error ("mono-profiler-log.suppression is greater than 128kb - aborting\n");
-       }
-
-       while ((line = get_next_line (content, &content))) {
-               line = g_strchomp (g_strchug (line));
-               /* No locking needed as we're doing initialization */
-               mono_conc_hashtable_insert (suppressed_assemblies, line, line);
-       }
-
-       fclose (sa_file);
-}
-
-#endif /* DISABLE_HELPER_THREAD */
-
-static void
-coverage_init (MonoProfiler *prof)
-{
-#ifndef DISABLE_HELPER_THREAD
-       assert (!coverage_initialized);
-
-       COVERAGE_DEBUG(fprintf (stderr, "Coverage initialized\n");)
-
-       mono_os_mutex_init (&coverage_mutex);
-       coverage_methods = mono_conc_hashtable_new (NULL, NULL);
-       coverage_assemblies = mono_conc_hashtable_new (NULL, NULL);
-       coverage_classes = mono_conc_hashtable_new (NULL, NULL);
-       filtered_classes = mono_conc_hashtable_new (NULL, NULL);
-       entered_methods = mono_conc_hashtable_new (NULL, NULL);
-       image_to_methods = mono_conc_hashtable_new (NULL, NULL);
-       init_suppressed_assemblies ();
-
-       coverage_initialized = TRUE;
-#endif /* DISABLE_HELPER_THREAD */
-}
-
-static void
-unref_coverage_assemblies (gpointer key, gpointer value, gpointer userdata)
-{
-       MonoAssembly *assembly = (MonoAssembly *)value;
-       mono_assembly_close (assembly);
-}
-
-static void
-free_sample_hit (gpointer p)
-{
-       mono_lock_free_free (p, SAMPLE_BLOCK_SIZE);
-}
-
-static void
-cleanup_reusable_samples (MonoProfiler *prof)
-{
-       SampleHit *sample;
-
-       while ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&prof->sample_reuse_queue)))
-               mono_thread_hazardous_try_free (sample, free_sample_hit);
-}
-
-static void
-log_shutdown (MonoProfiler *prof)
-{
-       void *res;
-
-       in_shutdown = 1;
-#ifndef DISABLE_HELPER_THREAD
-       counters_and_perfcounters_sample (prof);
-
-       dump_coverage (prof);
-
-       if (prof->command_port) {
-               char c = 1;
-               ign_res (write (prof->pipes [1], &c, 1));
-               pthread_join (prof->helper_thread, &res);
-       }
-#endif
-#if USE_PERF_EVENTS
-       if (perf_data) {
-               int i;
-               for (i = 0; i < num_perf; ++i)
-                       read_perf_mmap (prof, i);
-       }
-#endif
-
-       /*
-        * Ensure that we empty the LLS completely, even if some nodes are
-        * not immediately removed upon calling mono_lls_remove (), by
-        * iterating until the head is NULL.
-        */
-       while (profiler_thread_list.head) {
-               MONO_LLS_FOREACH_SAFE (&profiler_thread_list, MonoProfilerThread, thread) {
-                       remove_thread (prof, thread, FALSE);
-               } MONO_LLS_FOREACH_SAFE_END
-       }
-
-       InterlockedWrite (&prof->run_dumper_thread, 0);
-       mono_os_sem_post (&prof->dumper_queue_sem);
-       pthread_join (prof->dumper_thread, &res);
-       mono_os_sem_destroy (&prof->dumper_queue_sem);
-
-       InterlockedWrite (&prof->run_writer_thread, 0);
-       mono_os_sem_post (&prof->writer_queue_sem);
-       pthread_join (prof->writer_thread, &res);
-       mono_os_sem_destroy (&prof->writer_queue_sem);
-
-       cleanup_reusable_samples (prof);
-
-       /*
-        * Pump the entire hazard free queue to make sure that anything we allocated
-        * in the profiler will be freed. If we don't do this, the runtime could get
-        * around to freeing some items after the profiler has been unloaded, which
-        * would mean calling into functions in the profiler library, leading to a
-        * crash.
-        */
-       mono_thread_hazardous_try_free_all ();
-
-       g_assert (!InterlockedRead (&buffer_rwlock_count) && "Why is the reader count still non-zero?");
-       g_assert (!InterlockedReadPointer (&buffer_rwlock_exclusive) && "Why does someone still hold the exclusive lock?");
-
-#if defined (HAVE_SYS_ZLIB)
-       if (prof->gzfile)
-               gzclose (prof->gzfile);
-#endif
-       if (prof->pipe_output)
-               pclose (prof->file);
-       else
-               fclose (prof->file);
-
-       mono_conc_hashtable_destroy (prof->method_table);
-       mono_os_mutex_destroy (&prof->method_table_mutex);
-
-       if (coverage_initialized) {
-               mono_os_mutex_lock (&coverage_mutex);
-               mono_conc_hashtable_foreach (coverage_assemblies, unref_coverage_assemblies, prof);
-               mono_os_mutex_unlock (&coverage_mutex);
-
-               mono_conc_hashtable_destroy (coverage_methods);
-               mono_conc_hashtable_destroy (coverage_assemblies);
-               mono_conc_hashtable_destroy (coverage_classes);
-               mono_conc_hashtable_destroy (filtered_classes);
-
-               mono_conc_hashtable_destroy (entered_methods);
-               mono_conc_hashtable_destroy (image_to_methods);
-               mono_conc_hashtable_destroy (suppressed_assemblies);
-               mono_os_mutex_destroy (&coverage_mutex);
-       }
-
-       PROF_TLS_FREE ();
-
-       g_free (prof->args);
-       g_free (prof);
-}
-
-static char*
-new_filename (const char* filename)
-{
-       time_t t = time (NULL);
-       int pid = process_id ();
-       char pid_buf [16];
-       char time_buf [16];
-       char *res, *d;
-       const char *p;
-       int count_dates = 0;
-       int count_pids = 0;
-       int s_date, s_pid;
-       struct tm *ts;
-       for (p = filename; *p; p++) {
-               if (*p != '%')
-                       continue;
-               p++;
-               if (*p == 't')
-                       count_dates++;
-               else if (*p == 'p')
-                       count_pids++;
-               else if (*p == 0)
-                       break;
-       }
-       if (!count_dates && !count_pids)
-               return pstrdup (filename);
-       snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
-       ts = gmtime (&t);
-       snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
-               1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
-       s_date = strlen (time_buf);
-       s_pid = strlen (pid_buf);
-       d = res = (char *)malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
-       for (p = filename; *p; p++) {
-               if (*p != '%') {
-                       *d++ = *p;
-                       continue;
-               }
-               p++;
-               if (*p == 't') {
-                       strcpy (d, time_buf);
-                       d += s_date;
-                       continue;
-               } else if (*p == 'p') {
-                       strcpy (d, pid_buf);
-                       d += s_pid;
-                       continue;
-               } else if (*p == '%') {
-                       *d++ = '%';
-                       continue;
-               } else if (*p == 0)
-                       break;
-               *d++ = '%';
-               *d++ = *p;
-       }
-       *d = 0;
-       return res;
-}
-
-//this is exposed by the JIT, but it's not meant to be a supported API for now.
-extern void mono_threads_attach_tools_thread (void);
-
-#ifndef DISABLE_HELPER_THREAD
-
-static void*
-helper_thread (void* arg)
-{
-       MonoProfiler* prof = (MonoProfiler *)arg;
-       int command_socket;
-       int len;
-       char buf [64];
-
-       mono_threads_attach_tools_thread ();
-       mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler helper");
-
-       init_thread (FALSE);
-
-       //fprintf (stderr, "Server listening\n");
-       command_socket = -1;
-       while (1) {
-               fd_set rfds;
-               struct timeval tv;
-               int max_fd = -1;
-               FD_ZERO (&rfds);
-               FD_SET (prof->server_socket, &rfds);
-               max_fd = prof->server_socket;
-               FD_SET (prof->pipes [0], &rfds);
-               if (max_fd < prof->pipes [0])
-                       max_fd = prof->pipes [0];
-               if (command_socket >= 0) {
-                       FD_SET (command_socket, &rfds);
-                       if (max_fd < command_socket)
-                               max_fd = command_socket;
-               }
-#if USE_PERF_EVENTS
-               if (perf_data) {
-                       int i;
-                       for ( i = 0; i < num_perf; ++i) {
-                               if (perf_data [i].perf_fd < 0)
-                                       continue;
-                               FD_SET (perf_data [i].perf_fd, &rfds);
-                               if (max_fd < perf_data [i].perf_fd)
-                                       max_fd = perf_data [i].perf_fd;
-                       }
-               }
-#endif
-
-               counters_and_perfcounters_sample (prof);
-
-               buffer_lock_excl ();
-
-               sync_point (prof, SYNC_POINT_PERIODIC);
-
-               buffer_unlock_excl ();
-
-               tv.tv_sec = 1;
-               tv.tv_usec = 0;
-               len = select (max_fd + 1, &rfds, NULL, NULL, &tv);
-
-               if (len < 0) {
-                       if (errno == EINTR)
-                               continue;
-
-                       g_warning ("Error in proflog server: %s", strerror (errno));
-                       return NULL;
-               }
-
-               if (FD_ISSET (prof->pipes [0], &rfds)) {
-                       char c;
-                       read (prof->pipes [0], &c, 1);
-                       if (do_debug)
-                               fprintf (stderr, "helper shutdown\n");
-#if USE_PERF_EVENTS
-                       if (perf_data) {
-                               int i;
-                               for ( i = 0; i < num_perf; ++i) {
-                                       if (perf_data [i].perf_fd < 0)
-                                               continue;
-                                       if (FD_ISSET (perf_data [i].perf_fd, &rfds))
-                                               read_perf_mmap (prof, i);
-                               }
-                       }
-#endif
-                       safe_send_threadless (prof);
-                       return NULL;
-               }
-#if USE_PERF_EVENTS
-               if (perf_data) {
-                       int i;
-                       for ( i = 0; i < num_perf; ++i) {
-                               if (perf_data [i].perf_fd < 0)
-                                       continue;
-                               if (FD_ISSET (perf_data [i].perf_fd, &rfds)) {
-                                       read_perf_mmap (prof, i);
-                                       send_if_needed_threadless (prof);
-                               }
-                       }
-               }
-#endif
-               if (command_socket >= 0 && FD_ISSET (command_socket, &rfds)) {
-                       len = read (command_socket, buf, sizeof (buf) - 1);
-                       if (len < 0)
-                               continue;
-                       if (len == 0) {
-                               close (command_socket);
-                               command_socket = -1;
-                               continue;
-                       }
-                       buf [len] = 0;
-                       if (strcmp (buf, "heapshot\n") == 0 && hs_mode_ondemand) {
-                               // Rely on the finalization callbacks invoking process_requests ().
-                               heapshot_requested = 1;
-                               mono_gc_finalize_notify ();
-                       }
-                       continue;
-               }
-               if (!FD_ISSET (prof->server_socket, &rfds)) {
-                       continue;
-               }
-               command_socket = accept (prof->server_socket, NULL, NULL);
-               if (command_socket < 0)
-                       continue;
-               //fprintf (stderr, "Accepted connection\n");
-       }
-
-       mono_thread_info_detach ();
-
-       return NULL;
-}
-
-static int
-start_helper_thread (MonoProfiler* prof)
-{
-       struct sockaddr_in server_address;
-       int r;
-       socklen_t slen;
-       if (pipe (prof->pipes) < 0) {
-               fprintf (stderr, "Cannot create pipe\n");
-               return 0;
-       }
-       prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
-       if (prof->server_socket < 0) {
-               fprintf (stderr, "Cannot create server socket\n");
-               return 0;
-       }
-       memset (&server_address, 0, sizeof (server_address));
-       server_address.sin_family = AF_INET;
-       server_address.sin_addr.s_addr = INADDR_ANY;
-       server_address.sin_port = htons (prof->command_port);
-       if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) < 0) {
-               fprintf (stderr, "Cannot bind server socket, port: %d: %s\n", prof->command_port, strerror (errno));
-               close (prof->server_socket);
-               return 0;
-       }
-       if (listen (prof->server_socket, 1) < 0) {
-               fprintf (stderr, "Cannot listen server socket\n");
-               close (prof->server_socket);
-               return 0;
-       }
-       slen = sizeof (server_address);
-       if (getsockname (prof->server_socket, (struct sockaddr *)&server_address, &slen) == 0) {
-               prof->command_port = ntohs (server_address.sin_port);
-               /*fprintf (stderr, "Assigned server port: %d\n", prof->command_port);*/
-       }
-
-       r = pthread_create (&prof->helper_thread, NULL, helper_thread, prof);
-       if (r) {
-               close (prof->server_socket);
-               return 0;
-       }
-       return 1;
-}
-#endif
-
-static void
-free_writer_entry (gpointer p)
-{
-       mono_lock_free_free (p, WRITER_ENTRY_BLOCK_SIZE);
-}
-
-static gboolean
-handle_writer_queue_entry (MonoProfiler *prof)
-{
-       WriterQueueEntry *entry;
-
-       if ((entry = (WriterQueueEntry *) mono_lock_free_queue_dequeue (&prof->writer_queue))) {
-               if (!entry->methods)
-                       goto no_methods;
-
-               LogBuffer *buf = NULL;
-
-               /*
-                * Encode the method events in a temporary log buffer that we
-                * flush to disk before the main buffer, ensuring that all
-                * methods have metadata emitted before they're referenced.
-                *
-                * We use a 'proper' thread-local buffer for this as opposed
-                * to allocating and freeing a buffer by hand because the call
-                * to mono_method_full_name () below may trigger class load
-                * events when it retrieves the signature of the method. So a
-                * thread-local buffer needs to exist when such events occur.
-                */
-               for (guint i = 0; i < entry->methods->len; i++) {
-                       MethodInfo *info = (MethodInfo *) g_ptr_array_index (entry->methods, i);
-
-                       if (mono_conc_hashtable_lookup (prof->method_table, info->method))
-                               goto free_info; // This method already has metadata emitted.
-
-                       /*
-                        * Other threads use this hash table to get a general
-                        * idea of whether a method has already been emitted to
-                        * the stream. Due to the way we add to this table, it
-                        * can easily happen that multiple threads queue up the
-                        * same methods, but that's OK since eventually all
-                        * methods will be in this table and the thread-local
-                        * method lists will just be empty for the rest of the
-                        * app's lifetime.
-                        */
-                       mono_os_mutex_lock (&prof->method_table_mutex);
-                       mono_conc_hashtable_insert (prof->method_table, info->method, info->method);
-                       mono_os_mutex_unlock (&prof->method_table_mutex);
-
-                       char *name = mono_method_full_name (info->method, 1);
-                       int nlen = strlen (name) + 1;
-                       void *cstart = info->ji ? mono_jit_info_get_code_start (info->ji) : NULL;
-                       int csize = info->ji ? mono_jit_info_get_code_size (info->ji) : 0;
-
-                       buf = ensure_logbuf_unsafe (
-                               EVENT_SIZE /* event */ +
-                               LEB128_SIZE /* method */ +
-                               LEB128_SIZE /* start */ +
-                               LEB128_SIZE /* size */ +
-                               nlen /* name */
-                       );
-
-                       emit_event_time (buf, TYPE_JIT | TYPE_METHOD, info->time);
-                       emit_method_inner (buf, info->method);
-                       emit_ptr (buf, cstart);
-                       emit_value (buf, csize);
-
-                       memcpy (buf->cursor, name, nlen);
-                       buf->cursor += nlen;
-
-                       mono_free (name);
-
-               free_info:
-                       g_free (info);
-               }
-
-               g_ptr_array_free (entry->methods, TRUE);
-
-               if (buf) {
-                       dump_buffer_threadless (prof, buf);
-                       init_buffer_state (PROF_TLS_GET ());
-               }
-
-       no_methods:
-               dump_buffer (prof, entry->buffer);
-
-               mono_thread_hazardous_try_free (entry, free_writer_entry);
-
-               return TRUE;
-       }
-
-       return FALSE;
-}
-
-static void *
-writer_thread (void *arg)
-{
-       MonoProfiler *prof = (MonoProfiler *)arg;
-
-       mono_threads_attach_tools_thread ();
-       mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler writer");
-
-       dump_header (prof);
-
-       MonoProfilerThread *thread = init_thread (FALSE);
-
-       while (InterlockedRead (&prof->run_writer_thread)) {
-               mono_os_sem_wait (&prof->writer_queue_sem, MONO_SEM_FLAGS_NONE);
-               handle_writer_queue_entry (prof);
-       }
-
-       /* Drain any remaining entries on shutdown. */
-       while (handle_writer_queue_entry (prof));
-
-       free_buffer (thread->buffer, thread->buffer->size);
-       deinit_thread (thread);
-
-       mono_thread_info_detach ();
-
-       return NULL;
-}
-
-static int
-start_writer_thread (MonoProfiler* prof)
-{
-       InterlockedWrite (&prof->run_writer_thread, 1);
-
-       return !pthread_create (&prof->writer_thread, NULL, writer_thread, prof);
-}
-
-static void
-reuse_sample_hit (gpointer p)
-{
-       SampleHit *sample = p;
-
-       mono_lock_free_queue_node_unpoison (&sample->node);
-       mono_lock_free_queue_enqueue (&sample->prof->sample_reuse_queue, &sample->node);
-}
-
-static gboolean
-handle_dumper_queue_entry (MonoProfiler *prof)
-{
-       SampleHit *sample;
-
-       if ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&prof->dumper_queue))) {
-               for (int i = 0; i < sample->count; ++i) {
-                       MonoMethod *method = sample->frames [i].method;
-                       MonoDomain *domain = sample->frames [i].domain;
-                       void *address = sample->frames [i].base_address;
-
-                       if (!method) {
-                               g_assert (domain && "What happened to the domain pointer?");
-                               g_assert (address && "What happened to the instruction pointer?");
-
-                               MonoJitInfo *ji = mono_jit_info_table_find (domain, (char *) address);
-
-                               if (ji)
-                                       sample->frames [i].method = mono_jit_info_get_method (ji);
-                       }
-               }
-
-               LogBuffer *logbuffer = ensure_logbuf_unsafe (
-                       EVENT_SIZE /* event */ +
-                       BYTE_SIZE /* type */ +
-                       LEB128_SIZE /* tid */ +
-                       LEB128_SIZE /* count */ +
-                       1 * (
-                               LEB128_SIZE /* ip */
-                       ) +
-                       LEB128_SIZE /* managed count */ +
-                       sample->count * (
-                               LEB128_SIZE /* method */
-                       )
-               );
-
-               emit_event_time (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT, sample->time);
-               emit_byte (logbuffer, sample_type);
-               emit_ptr (logbuffer, (void *) sample->tid);
-               emit_value (logbuffer, 1);
-
-               // TODO: Actual native unwinding.
-               for (int i = 0; i < 1; ++i) {
-                       emit_ptr (logbuffer, sample->ip);
-                       add_code_pointer ((uintptr_t) sample->ip);
-               }
-
-               /* new in data version 6 */
-               emit_uvalue (logbuffer, sample->count);
-
-               for (int i = 0; i < sample->count; ++i)
-                       emit_method (prof, logbuffer, sample->frames [i].method);
-
-               mono_thread_hazardous_try_free (sample, reuse_sample_hit);
-
-               dump_unmanaged_coderefs (prof);
-
-               send_if_needed_threadless (prof);
-       }
-
-       return FALSE;
-}
-
-static void *
-dumper_thread (void *arg)
-{
-       MonoProfiler *prof = (MonoProfiler *)arg;
-
-       mono_threads_attach_tools_thread ();
-       mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler dumper");
-
-       MonoProfilerThread *thread = init_thread (FALSE);
-
-       while (InterlockedRead (&prof->run_dumper_thread)) {
-               mono_os_sem_wait (&prof->dumper_queue_sem, MONO_SEM_FLAGS_NONE);
-               handle_dumper_queue_entry (prof);
-       }
-
-       /* Drain any remaining entries on shutdown. */
-       while (handle_dumper_queue_entry (prof));
-
-       safe_send_threadless (prof);
-       deinit_thread (thread);
-
-       mono_thread_info_detach ();
-
-       return NULL;
-}
-
-static int
-start_dumper_thread (MonoProfiler* prof)
-{
-       InterlockedWrite (&prof->run_dumper_thread, 1);
-
-       return !pthread_create (&prof->dumper_thread, NULL, dumper_thread, prof);
-}
-
-static void
-runtime_initialized (MonoProfiler *profiler)
-{
-       InterlockedWrite (&runtime_inited, 1);
-
-#ifndef DISABLE_HELPER_THREAD
-       if (hs_mode_ondemand || need_helper_thread) {
-               if (!start_helper_thread (profiler))
-                       profiler->command_port = 0;
-       }
-#endif
-
-       start_writer_thread (profiler);
-       start_dumper_thread (profiler);
-
-       mono_counters_register ("Sample hits", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &sample_hits);
-       mono_counters_register ("Sample flushes", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &sample_flushes);
-       mono_counters_register ("Sample events allocated", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &sample_allocations);
-       mono_counters_register ("Log buffers allocated", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &buffer_allocations);
-       mono_counters_register ("Thread start events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &thread_starts);
-       mono_counters_register ("Thread stop events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &thread_ends);
-       mono_counters_register ("Domain load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &domain_loads);
-       mono_counters_register ("Domain unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &domain_unloads);
-       mono_counters_register ("Context load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &context_loads);
-       mono_counters_register ("Context unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &context_unloads);
-       mono_counters_register ("Assembly load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &assembly_loads);
-       mono_counters_register ("Assembly unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &assembly_unloads);
-       mono_counters_register ("Image load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &image_loads);
-       mono_counters_register ("Image unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &image_unloads);
-       mono_counters_register ("Class load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &class_loads);
-       mono_counters_register ("Class unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &class_unloads);
-
-#ifndef DISABLE_HELPER_THREAD
-       counters_init (profiler);
-       counters_sample (profiler, 0);
-#endif
-       /* ensure the main thread data and startup are available soon */
-       safe_send (profiler);
-}
-
-static MonoProfiler*
-create_profiler (const char *args, const char *filename, GPtrArray *filters)
-{
-       MonoProfiler *prof;
-       char *nf;
-       int force_delete = 0;
-       prof = (MonoProfiler *)calloc (1, sizeof (MonoProfiler));
-
-       prof->args = pstrdup (args);
-       prof->command_port = command_port;
-       if (filename && *filename == '-') {
-               force_delete = 1;
-               filename++;
-       }
-       if (!filename) {
-               if (do_report)
-                       filename = "|mprof-report -";
-               else
-                       filename = "output.mlpd";
-               nf = (char*)filename;
-       } else {
-               nf = new_filename (filename);
-               if (do_report) {
-                       int s = strlen (nf) + 32;
-                       char *p = (char *)malloc (s);
-                       snprintf (p, s, "|mprof-report '--out=%s' -", nf);
-                       g_free (nf);
-                       nf = p;
-               }
-       }
-       if (*nf == '|') {
-               prof->file = popen (nf + 1, "w");
-               prof->pipe_output = 1;
-       } else if (*nf == '#') {
-               int fd = strtol (nf + 1, NULL, 10);
-               prof->file = fdopen (fd, "a");
-       } else {
-               if (force_delete)
-                       unlink (nf);
-               prof->file = fopen (nf, "wb");
-       }
-       if (!prof->file) {
-               fprintf (stderr, "Cannot create profiler output: %s\n", nf);
-               exit (1);
-       }
-#if defined (HAVE_SYS_ZLIB)
-       if (use_zip)
-               prof->gzfile = gzdopen (fileno (prof->file), "wb");
-#endif
-#if USE_PERF_EVENTS
-       if (sample_type && sample_freq && !do_mono_sample)
-               need_helper_thread = setup_perf_event ();
-       if (!perf_data) {
-               /* FIXME: warn if different freq or sample type */
-               do_mono_sample = 1;
-       }
-#endif
-       if (do_mono_sample) {
-               need_helper_thread = 1;
-       }
-       if (do_counters && !need_helper_thread) {
-               need_helper_thread = 1;
-       }
-
-       /*
-        * If you hit this assert while increasing MAX_FRAMES, you need to increase
-        * SAMPLE_BLOCK_SIZE as well.
-        */
-       g_assert (SAMPLE_SLOT_SIZE (MAX_FRAMES) * 2 < LOCK_FREE_ALLOC_SB_USABLE_SIZE (SAMPLE_BLOCK_SIZE));
-
-       // FIXME: We should free this stuff too.
-       mono_lock_free_allocator_init_size_class (&prof->sample_size_class, SAMPLE_SLOT_SIZE (num_frames), SAMPLE_BLOCK_SIZE);
-       mono_lock_free_allocator_init_allocator (&prof->sample_allocator, &prof->sample_size_class, MONO_MEM_ACCOUNT_PROFILER);
-
-       mono_lock_free_queue_init (&prof->sample_reuse_queue);
-
-#ifdef DISABLE_HELPER_THREAD
-       if (hs_mode_ondemand)
-               fprintf (stderr, "Ondemand heapshot unavailable on this arch.\n");
-
-       if (do_coverage)
-               fprintf (stderr, "Coverage unavailable on this arch.\n");
-
-#endif
-
-       g_assert (sizeof (WriterQueueEntry) * 2 < LOCK_FREE_ALLOC_SB_USABLE_SIZE (WRITER_ENTRY_BLOCK_SIZE));
-
-       // FIXME: We should free this stuff too.
-       mono_lock_free_allocator_init_size_class (&prof->writer_entry_size_class, sizeof (WriterQueueEntry), WRITER_ENTRY_BLOCK_SIZE);
-       mono_lock_free_allocator_init_allocator (&prof->writer_entry_allocator, &prof->writer_entry_size_class, MONO_MEM_ACCOUNT_PROFILER);
-
-       mono_lock_free_queue_init (&prof->writer_queue);
-       mono_os_sem_init (&prof->writer_queue_sem, 0);
-
-       mono_lock_free_queue_init (&prof->dumper_queue);
-       mono_os_sem_init (&prof->dumper_queue_sem, 0);
-
-       mono_os_mutex_init (&prof->method_table_mutex);
-       prof->method_table = mono_conc_hashtable_new (NULL, NULL);
-
-       if (do_coverage)
-               coverage_init (prof);
-       prof->coverage_filters = filters;
-
-       prof->startup_time = current_time ();
-       return prof;
-}
-
-static void
-usage (int do_exit)
-{
-       printf ("Log profiler version %d.%d (format: %d)\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR, LOG_DATA_VERSION);
-       printf ("Usage: mono --profile=log[:OPTION1[,OPTION2...]] program.exe\n");
-       printf ("Options:\n");
-       printf ("\thelp                 show this usage info\n");
-       printf ("\t[no]alloc            enable/disable recording allocation info\n");
-       printf ("\t[no]calls            enable/disable recording enter/leave method events\n");
-       printf ("\theapshot[=MODE]      record heap shot info (by default at each major collection)\n");
-       printf ("\t                     MODE: every XXms milliseconds, every YYgc collections, ondemand\n");
-       printf ("\tcounters             sample counters every 1s\n");
-       printf ("\tsample[=TYPE]        use statistical sampling mode (by default cycles/100)\n");
-       printf ("\t                     TYPE: cycles,instr,cacherefs,cachemiss,branches,branchmiss\n");
-       printf ("\t                     TYPE can be followed by /FREQUENCY\n");
-       printf ("\ttime=fast            use a faster (but more inaccurate) timer\n");
-       printf ("\tmaxframes=NUM        collect up to NUM stack frames\n");
-       printf ("\tcalldepth=NUM        ignore method events for call chain depth bigger than NUM\n");
-       printf ("\toutput=FILENAME      write the data to file FILENAME (-FILENAME to overwrite)\n");
-       printf ("\toutput=|PROGRAM      write the data to the stdin of PROGRAM\n");
-       printf ("\t                     %%t is subtituted with date and time, %%p with the pid\n");
-       printf ("\treport               create a report instead of writing the raw data to a file\n");
-       printf ("\tzip                  compress the output data\n");
-       printf ("\tport=PORTNUM         use PORTNUM for the listening command server\n");
-       printf ("\tcoverage             enable collection of code coverage data\n");
-       printf ("\tcovfilter=ASSEMBLY   add an assembly to the code coverage filters\n");
-       printf ("\t                     add a + to include the assembly or a - to exclude it\n");
-       printf ("\t                     filter=-mscorlib\n");
-       printf ("\tcovfilter-file=FILE  use FILE to generate the list of assemblies to be filtered\n");
-       if (do_exit)
-               exit (1);
-}
-
-static const char*
-match_option (const char* p, const char *opt, char **rval)
-{
-       int len = strlen (opt);
-       if (strncmp (p, opt, len) == 0) {
-               if (rval) {
-                       if (p [len] == '=' && p [len + 1]) {
-                               const char *opt = p + len + 1;
-                               const char *end = strchr (opt, ',');
-                               char *val;
-                               int l;
-                               if (end == NULL) {
-                                       l = strlen (opt);
-                               } else {
-                                       l = end - opt;
-                               }
-                               val = (char *)malloc (l + 1);
-                               memcpy (val, opt, l);
-                               val [l] = 0;
-                               *rval = val;
-                               return opt + l;
-                       }
-                       if (p [len] == 0 || p [len] == ',') {
-                               *rval = NULL;
-                               return p + len + (p [len] == ',');
-                       }
-                       usage (1);
-               } else {
-                       if (p [len] == 0)
-                               return p + len;
-                       if (p [len] == ',')
-                               return p + len + 1;
-               }
-       }
-       return p;
-}
-
-typedef struct {
-       const char *name;
-       int sample_mode;
-} SampleMode;
-
-static const SampleMode sample_modes [] = {
-       {"cycles", SAMPLE_CYCLES},
-       {"instr", SAMPLE_INSTRUCTIONS},
-       {"cachemiss", SAMPLE_CACHE_MISSES},
-       {"cacherefs", SAMPLE_CACHE_REFS},
-       {"branches", SAMPLE_BRANCHES},
-       {"branchmiss", SAMPLE_BRANCH_MISSES},
-       {NULL, 0}
-};
-
-static void
-set_sample_mode (char* val, int allow_empty)
-{
-       char *end;
-       char *maybe_freq = NULL;
-       unsigned int count;
-       const SampleMode *smode = sample_modes;
-#ifndef USE_PERF_EVENTS
-       do_mono_sample = 1;
-#endif
-       if (allow_empty && !val) {
-               sample_type = SAMPLE_CYCLES;
-               sample_freq = 100;
-               return;
-       }
-       if (strcmp (val, "mono") == 0) {
-               do_mono_sample = 1;
-               sample_type = SAMPLE_CYCLES;
-               g_free (val);
-               return;
-       }
-       for (smode = sample_modes; smode->name; smode++) {
-               int l = strlen (smode->name);
-               if (strncmp (val, smode->name, l) == 0) {
-                       sample_type = smode->sample_mode;
-                       maybe_freq = val + l;
-                       break;
-               }
-       }
-       if (!smode->name)
-               usage (1);
-       if (*maybe_freq == '/') {
-               count = strtoul (maybe_freq + 1, &end, 10);
-               if (maybe_freq + 1 == end)
-                       usage (1);
-               sample_freq = count;
-       } else if (*maybe_freq != 0) {
-               usage (1);
-       } else {
-               sample_freq = 100;
-       }
-       g_free (val);
-}
-
-static void
-set_hsmode (char* val, int allow_empty)
-{
-       char *end;
-       unsigned int count;
-       if (allow_empty && !val)
-               return;
-       if (strcmp (val, "ondemand") == 0) {
-               hs_mode_ondemand = 1;
-               g_free (val);
-               return;
-       }
-       count = strtoul (val, &end, 10);
-       if (val == end)
-               usage (1);
-       if (strcmp (end, "ms") == 0)
-               hs_mode_ms = count;
-       else if (strcmp (end, "gc") == 0)
-               hs_mode_gc = count;
-       else
-               usage (1);
-       g_free (val);
-}
-
-/*
- * declaration to silence the compiler: this is the entry point that
- * mono will load from the shared library and call.
- */
-extern void
-mono_profiler_startup (const char *desc);
-
-extern void
-mono_profiler_startup_log (const char *desc);
-
-/*
- * this is the entry point that will be used when the profiler
- * is embedded inside the main executable.
- */
-void
-mono_profiler_startup_log (const char *desc)
-{
-       mono_profiler_startup (desc);
-}
-
-void
-mono_profiler_startup (const char *desc)
-{
-       MonoProfiler *prof;
-       GPtrArray *filters = NULL;
-       char *filename = NULL;
-       const char *p;
-       const char *opt;
-       int fast_time = 0;
-       int calls_enabled = 0;
-       int allocs_enabled = 0;
-       int only_counters = 0;
-       int only_coverage = 0;
-       int events = MONO_PROFILE_GC|MONO_PROFILE_ALLOCATIONS|
-               MONO_PROFILE_GC_MOVES|MONO_PROFILE_CLASS_EVENTS|MONO_PROFILE_THREADS|
-               MONO_PROFILE_ENTER_LEAVE|MONO_PROFILE_JIT_COMPILATION|MONO_PROFILE_EXCEPTIONS|
-               MONO_PROFILE_MONITOR_EVENTS|MONO_PROFILE_MODULE_EVENTS|MONO_PROFILE_GC_ROOTS|
-               MONO_PROFILE_INS_COVERAGE|MONO_PROFILE_APPDOMAIN_EVENTS|MONO_PROFILE_CONTEXT_EVENTS|
-               MONO_PROFILE_ASSEMBLY_EVENTS|MONO_PROFILE_GC_FINALIZATION;
-
-       max_allocated_sample_hits = mono_cpu_count () * 1000;
-
-       p = desc;
-       if (strncmp (p, "log", 3))
-               usage (1);
-       p += 3;
-       if (*p == ':')
-               p++;
-       for (; *p; p = opt) {
-               char *val;
-               if (*p == ',') {
-                       opt = p + 1;
-                       continue;
-               }
-               if ((opt = match_option (p, "help", NULL)) != p) {
-                       usage (0);
-                       continue;
-               }
-               if ((opt = match_option (p, "calls", NULL)) != p) {
-                       calls_enabled = 1;
-                       continue;
-               }
-               if ((opt = match_option (p, "nocalls", NULL)) != p) {
-                       events &= ~MONO_PROFILE_ENTER_LEAVE;
-                       nocalls = 1;
-                       continue;
-               }
-               if ((opt = match_option (p, "alloc", NULL)) != p) {
-                       allocs_enabled = 1;
-                       continue;
-               }
-               if ((opt = match_option (p, "noalloc", NULL)) != p) {
-                       events &= ~MONO_PROFILE_ALLOCATIONS;
-                       continue;
-               }
-               if ((opt = match_option (p, "time", &val)) != p) {
-                       if (strcmp (val, "fast") == 0)
-                               fast_time = 1;
-                       else if (strcmp (val, "null") == 0)
-                               fast_time = 2;
-                       else
-                               usage (1);
-                       g_free (val);
-                       continue;
-               }
-               if ((opt = match_option (p, "report", NULL)) != p) {
-                       do_report = 1;
-                       continue;
-               }
-               if ((opt = match_option (p, "debug", NULL)) != p) {
-                       do_debug = 1;
-                       continue;
-               }
-               if ((opt = match_option (p, "sampling-real", NULL)) != p) {
-                       sampling_mode = MONO_PROFILER_STAT_MODE_REAL;
-                       continue;
-               }
-               if ((opt = match_option (p, "sampling-process", NULL)) != p) {
-                       sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
-                       continue;
-               }
-               if ((opt = match_option (p, "heapshot", &val)) != p) {
-                       events &= ~MONO_PROFILE_ALLOCATIONS;
-                       events &= ~MONO_PROFILE_ENTER_LEAVE;
-                       nocalls = 1;
-                       do_heap_shot = 1;
-                       set_hsmode (val, 1);
-                       continue;
-               }
-               if ((opt = match_option (p, "sample", &val)) != p) {
-                       events &= ~MONO_PROFILE_ALLOCATIONS;
-                       events &= ~MONO_PROFILE_ENTER_LEAVE;
-                       nocalls = 1;
-                       set_sample_mode (val, 1);
-                       continue;
-               }
-               if ((opt = match_option (p, "hsmode", &val)) != p) {
-                       fprintf (stderr, "The hsmode profiler option is obsolete, use heapshot=MODE.\n");
-                       set_hsmode (val, 0);
-                       continue;
-               }
-               if ((opt = match_option (p, "zip", NULL)) != p) {
-                       use_zip = 1;
-                       continue;
-               }
-               if ((opt = match_option (p, "output", &val)) != p) {
-                       filename = val;
-                       continue;
-               }
-               if ((opt = match_option (p, "port", &val)) != p) {
-                       char *end;
-                       command_port = strtoul (val, &end, 10);
-                       g_free (val);
-                       continue;
-               }
-               if ((opt = match_option (p, "maxframes", &val)) != p) {
-                       char *end;
-                       num_frames = strtoul (val, &end, 10);
-                       if (num_frames > MAX_FRAMES)
-                               num_frames = MAX_FRAMES;
-                       g_free (val);
-                       notraces = num_frames == 0;
-                       continue;
-               }
-               if ((opt = match_option (p, "maxsamples", &val)) != p) {
-                       char *end;
-                       max_allocated_sample_hits = strtoul (val, &end, 10);
-                       if (!max_allocated_sample_hits)
-                               max_allocated_sample_hits = G_MAXINT32;
-                       g_free (val);
-                       continue;
-               }
-               if ((opt = match_option (p, "calldepth", &val)) != p) {
-                       char *end;
-                       max_call_depth = strtoul (val, &end, 10);
-                       g_free (val);
-                       continue;
-               }
-               if ((opt = match_option (p, "counters", NULL)) != p) {
-                       do_counters = 1;
-                       continue;
-               }
-               if ((opt = match_option (p, "countersonly", NULL)) != p) {
-                       only_counters = 1;
-                       continue;
-               }
-               if ((opt = match_option (p, "coverage", NULL)) != p) {
-                       do_coverage = 1;
-                       events |= MONO_PROFILE_ENTER_LEAVE;
-                       debug_coverage = (g_getenv ("MONO_PROFILER_DEBUG_COVERAGE") != NULL);
-                       continue;
-               }
-               if ((opt = match_option (p, "onlycoverage", NULL)) != p) {
-                       only_coverage = 1;
-                       continue;
-               }
-               if ((opt = match_option (p, "covfilter-file", &val)) != p) {
-                       FILE *filter_file;
-                       char *line, *content;
-
-                       if (filters == NULL)
-                               filters = g_ptr_array_new ();
-
-                       filter_file = fopen (val, "r");
-                       if (filter_file == NULL) {
-                               fprintf (stderr, "Unable to open %s\n", val);
-                               exit (0);
-                       }
-
-                       /* Don't need to free content as it is referred to by the lines stored in @filters */
-                       content = get_file_content (filter_file);
-                       if (content == NULL)
-                               fprintf (stderr, "WARNING: %s is greater than 128kb - ignoring\n", val);
-
-                       while ((line = get_next_line (content, &content)))
-                               g_ptr_array_add (filters, g_strchug (g_strchomp (line)));
-
-                       fclose (filter_file);
-                       continue;
-               }
-               if ((opt = match_option (p, "covfilter", &val)) != p) {
-                       if (filters == NULL)
-                               filters = g_ptr_array_new ();
-
-                       g_ptr_array_add (filters, val);
-                       continue;
-               }
-               if (opt == p) {
-                       usage (0);
-                       exit (0);
-               }
-       }
-       if (calls_enabled) {
-               events |= MONO_PROFILE_ENTER_LEAVE;
-               nocalls = 0;
-       }
-       if (allocs_enabled)
-               events |= MONO_PROFILE_ALLOCATIONS;
-       if (only_counters)
-               events = 0;
-       if (only_coverage)
-               events = MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_INS_COVERAGE;
-
-       utils_init (fast_time);
-
-       PROF_TLS_INIT ();
-
-       prof = create_profiler (desc, filename, filters);
-       if (!prof) {
-               PROF_TLS_FREE ();
-               return;
-       }
-
-       mono_lls_init (&profiler_thread_list, NULL);
-
-       init_thread (TRUE);
-
-       mono_profiler_install (prof, log_shutdown);
-       mono_profiler_install_gc (gc_event, gc_resize);
-       mono_profiler_install_allocation (gc_alloc);
-       mono_profiler_install_gc_moves (gc_moves);
-       mono_profiler_install_gc_roots (gc_handle, gc_roots);
-       mono_profiler_install_gc_finalize (finalize_begin, finalize_object_begin, finalize_object_end, finalize_end);
-       mono_profiler_install_appdomain (NULL, domain_loaded, domain_unloaded, NULL);
-       mono_profiler_install_appdomain_name (domain_name);
-       mono_profiler_install_context (context_loaded, context_unloaded);
-       mono_profiler_install_class (NULL, class_loaded, class_unloaded, NULL);
-       mono_profiler_install_module (NULL, image_loaded, image_unloaded, NULL);
-       mono_profiler_install_assembly (NULL, assembly_loaded, assembly_unloaded, NULL);
-       mono_profiler_install_thread (thread_start, thread_end);
-       mono_profiler_install_thread_name (thread_name);
-       mono_profiler_install_enter_leave (method_enter, method_leave);
-       mono_profiler_install_jit_end (method_jitted);
-       mono_profiler_install_code_buffer_new (code_buffer_new);
-       mono_profiler_install_exception (throw_exc, method_exc_leave, clause_exc);
-       mono_profiler_install_monitor (monitor_event);
-       mono_profiler_install_runtime_initialized (runtime_initialized);
-       if (do_coverage)
-               mono_profiler_install_coverage_filter (coverage_filter);
-
-       if (do_mono_sample && sample_type == SAMPLE_CYCLES && sample_freq && !only_counters) {
-               events |= MONO_PROFILE_STATISTICAL;
-               mono_profiler_set_statistical_mode (sampling_mode, sample_freq);
-               mono_profiler_install_statistical (mono_sample_hit);
-       }
-
-       mono_profiler_set_events ((MonoProfileFlags)events);
-}
diff --git a/mono/profiler/proflog.h b/mono/profiler/proflog.h
deleted file mode 100644 (file)
index 5649d8b..0000000
+++ /dev/null
@@ -1,155 +0,0 @@
-#ifndef __MONO_PROFLOG_H__
-#define __MONO_PROFLOG_H__
-
-#define BUF_ID 0x4D504C01
-#define LOG_HEADER_ID 0x4D505A01
-#define LOG_VERSION_MAJOR 1
-#define LOG_VERSION_MINOR 0
-#define LOG_DATA_VERSION 13
-/*
- * Changes in major/minor versions:
- * version 1.0: removed sysid field from header
- *              added args, arch, os fields to header
- *
- * Changes in data versions:
- * version 2: added offsets in heap walk
- * version 3: added GC roots
- * version 4: added sample/statistical profiling
- * version 5: added counters sampling
- * version 6: added optional backtrace in sampling info
- * version 8: added TYPE_RUNTIME and JIT helpers/trampolines
- * version 9: added MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING
- * version 10: added TYPE_COVERAGE
- * version 11: added thread ID to TYPE_SAMPLE_HIT
-               added more load/unload events
-                   unload for class
-                   unload for image
-                   load/unload for appdomain
-                   load/unload for contexts
-                   load/unload/name for assemblies
-               removed TYPE_LOAD_ERR flag (profiler never generated it, now removed from the format itself)
-               added TYPE_GC_HANDLE_{CREATED,DESTROYED}_BT
-               TYPE_JIT events are no longer guaranteed to have code start/size info (can be zero)
- * version 12: added MONO_COUNTER_PROFILER
- * version 13: added MONO_GC_EVENT_{PRE_STOP_WORLD_LOCKED,POST_START_WORLD_UNLOCKED}
-               added TYPE_META + TYPE_SYNC_POINT
-               removed il and native offset in TYPE_SAMPLE_HIT
-               methods in backtraces are now encoded as proper method pointers
-               removed flags in backtrace format
-               removed flags in metadata events
-               changed the following fields to a single byte rather than leb128
-                   TYPE_GC_EVENT: event_type, generation
-                   TYPE_HEAP_ROOT: root_type
-                   TYPE_JITHELPER: type
-                   TYPE_SAMPLE_HIT: sample_type
-                   TYPE_CLAUSE: clause_type
-                   TYPE_SAMPLE_COUNTERS_DESC: type, unit, variance
-                   TYPE_SAMPLE_COUNTERS: type
-               added time fields to all events that were missing one
-                   TYPE_HEAP_OBJECT
-                   TYPE_HEAP_ROOT
-                   TYPE_SAMPLE_USYM
-                   TYPE_SAMPLE_COUNTERS_DESC
-                   TYPE_COVERAGE_METHOD
-                   TYPE_COVERAGE_STATEMENT
-                   TYPE_COVERAGE_CLASS
-                   TYPE_COVERAGE_ASSEMBLY
-               moved the time field in TYPE_SAMPLE_HIT to right after the event byte, now encoded as a regular time field
-               changed the time field in TYPE_SAMPLE_COUNTERS to be encoded as a regular time field (in nanoseconds)
-               added TYPE_GC_FINALIZE_{START,END,OBJECT_START,OBJECT_END}
- */
-
-enum {
-       TYPE_ALLOC,
-       TYPE_GC,
-       TYPE_METADATA,
-       TYPE_METHOD,
-       TYPE_EXCEPTION,
-       TYPE_MONITOR,
-       TYPE_HEAP,
-       TYPE_SAMPLE,
-       TYPE_RUNTIME,
-       TYPE_COVERAGE,
-       TYPE_META,
-       /* extended type for TYPE_HEAP */
-       TYPE_HEAP_START  = 0 << 4,
-       TYPE_HEAP_END    = 1 << 4,
-       TYPE_HEAP_OBJECT = 2 << 4,
-       TYPE_HEAP_ROOT   = 3 << 4,
-       /* extended type for TYPE_METADATA */
-       TYPE_END_LOAD     = 2 << 4,
-       TYPE_END_UNLOAD   = 4 << 4,
-       /* extended type for TYPE_GC */
-       TYPE_GC_EVENT  = 1 << 4,
-       TYPE_GC_RESIZE = 2 << 4,
-       TYPE_GC_MOVE   = 3 << 4,
-       TYPE_GC_HANDLE_CREATED      = 4 << 4,
-       TYPE_GC_HANDLE_DESTROYED    = 5 << 4,
-       TYPE_GC_HANDLE_CREATED_BT   = 6 << 4,
-       TYPE_GC_HANDLE_DESTROYED_BT = 7 << 4,
-       TYPE_GC_FINALIZE_START = 8 << 4,
-       TYPE_GC_FINALIZE_END = 9 << 4,
-       TYPE_GC_FINALIZE_OBJECT_START = 10 << 4,
-       TYPE_GC_FINALIZE_OBJECT_END = 11 << 4,
-       /* extended type for TYPE_METHOD */
-       TYPE_LEAVE     = 1 << 4,
-       TYPE_ENTER     = 2 << 4,
-       TYPE_EXC_LEAVE = 3 << 4,
-       TYPE_JIT       = 4 << 4,
-       /* extended type for TYPE_EXCEPTION */
-       TYPE_THROW_NO_BT = 0 << 7,
-       TYPE_THROW_BT    = 1 << 7,
-       TYPE_CLAUSE      = 1 << 4,
-       /* extended type for TYPE_ALLOC */
-       TYPE_ALLOC_NO_BT  = 0 << 4,
-       TYPE_ALLOC_BT     = 1 << 4,
-       /* extended type for TYPE_MONITOR */
-       TYPE_MONITOR_NO_BT  = 0 << 7,
-       TYPE_MONITOR_BT     = 1 << 7,
-       /* extended type for TYPE_SAMPLE */
-       TYPE_SAMPLE_HIT           = 0 << 4,
-       TYPE_SAMPLE_USYM          = 1 << 4,
-       TYPE_SAMPLE_UBIN          = 2 << 4,
-       TYPE_SAMPLE_COUNTERS_DESC = 3 << 4,
-       TYPE_SAMPLE_COUNTERS      = 4 << 4,
-       /* extended type for TYPE_RUNTIME */
-       TYPE_JITHELPER = 1 << 4,
-       /* extended type for TYPE_COVERAGE */
-       TYPE_COVERAGE_ASSEMBLY = 0 << 4,
-       TYPE_COVERAGE_METHOD   = 1 << 4,
-       TYPE_COVERAGE_STATEMENT = 2 << 4,
-       TYPE_COVERAGE_CLASS = 3 << 4,
-       /* extended type for TYPE_META */
-       TYPE_SYNC_POINT = 0 << 4,
-       TYPE_END
-};
-
-enum {
-       /* metadata type byte for TYPE_METADATA */
-       TYPE_CLASS    = 1,
-       TYPE_IMAGE    = 2,
-       TYPE_ASSEMBLY = 3,
-       TYPE_DOMAIN   = 4,
-       TYPE_THREAD   = 5,
-       TYPE_CONTEXT  = 6,
-};
-
-typedef enum {
-       SYNC_POINT_PERIODIC,
-       SYNC_POINT_WORLD_STOP,
-       SYNC_POINT_WORLD_START
-} MonoProfilerSyncPointType;
-
-// Sampling sources
-// Unless you have compiled with --enable-perf-events, only SAMPLE_CYCLES is available
-enum {
-       SAMPLE_CYCLES = 1,
-       SAMPLE_INSTRUCTIONS,
-       SAMPLE_CACHE_MISSES,
-       SAMPLE_CACHE_REFS,
-       SAMPLE_BRANCHES,
-       SAMPLE_BRANCH_MISSES,
-       SAMPLE_LAST
-};
-
-#endif /* __MONO_PROFLOG_H__ */
diff --git a/mono/profiler/utils.c b/mono/profiler/utils.c
deleted file mode 100644 (file)
index cfa7589..0000000
+++ /dev/null
@@ -1,426 +0,0 @@
-/*
- * utils.c: log profiler and reporter utils
- *
- * We have here the minimal needed portability functions: we can't depend
- * on the ones provided by the runtime, since they are internal and,
- * especially mprof-report is an external program.
- * Note also that we don't take a glib/eglib dependency here for mostly
- * the same reason (but also because we need tight control in the profiler
- * over memory allocation, which needs to work with the world stopped).
- *
- * Author:
- *   Paolo Molaro (lupus@ximian.com)
- *
- * Copyright 2010 Novell, Inc (http://www.novell.com)
- * Licensed under the MIT license. See LICENSE file in the project root for full license information.
- */
-#include "utils.h"
-#include <stdlib.h>
-#include <time.h>
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
-#ifdef HOST_WIN32
-#include <windows.h>
-#else
-#include <pthread.h>
-#include <sched.h>
-#endif
-#include <glib.h>
-
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#endif
-#if HAVE_SYS_MMAN_H
-#include <sys/mman.h>
-#endif
-
-#if defined(__APPLE__)
-#include <mach/mach_time.h>  
-#include <stdio.h> 
-
-static mach_timebase_info_data_t timebase_info;
-#endif
-
-#ifndef MAP_ANONYMOUS
-#define MAP_ANONYMOUS MAP_ANON
-#endif
-
-#define TICKS_PER_SEC 1000000000LL
-
-#if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__linux__) && defined(HAVE_SCHED_GETCPU)
-#define HAVE_RDTSC 1
-#endif
-
-typedef struct {
-       unsigned int timer_count;
-       int last_cpu;
-       uint64_t last_rdtsc;
-       uint64_t last_time;
-} TlsData;
-
-#ifdef HOST_WIN32
-static int tls_data;
-#define DECL_TLS_DATA TlsData *tls; tls = (TlsData *) TlsGetValue (tls_data); if (tls == NULL) { tls = (TlsData *) g_calloc (sizeof (TlsData), 1); TlsSetValue (tls_data, tls); }
-#define TLS_INIT(x) x = TlsAlloc()
-#elif HAVE_KW_THREAD
-static __thread TlsData tls_data;
-#define DECL_TLS_DATA TlsData *tls = &tls_data
-#define TLS_INIT(x)
-#else
-static pthread_key_t tls_data;
-#define DECL_TLS_DATA TlsData *tls; tls = (TlsData *) pthread_getspecific (tls_data); if (tls == NULL) { tls = (TlsData *) g_calloc (sizeof (TlsData), 1); pthread_setspecific (tls_data, tls); }
-#define TLS_INIT(x) pthread_key_create(&x, NULL)
-#endif
-
-#ifdef HOST_WIN32
-static CRITICAL_SECTION log_lock;
-static LARGE_INTEGER pcounter_freq;
-#else
-static pthread_mutex_t log_lock = PTHREAD_MUTEX_INITIALIZER;
-#endif
-
-static int timer_overhead = 0;
-static uint64_t time_inc = 0;
-typedef uint64_t (*TimeFunc)(void);
-
-static TimeFunc time_func;
-
-static uint64_t
-clock_time (void)
-{
-#if defined(__APPLE__)
-       uint64_t time = mach_absolute_time ();
-       
-       time *= timebase_info.numer;
-       time /= timebase_info.denom;
-
-       return time;
-#elif defined(HOST_WIN32)
-       LARGE_INTEGER value;
-       QueryPerformanceCounter (&value);
-       return value.QuadPart * TICKS_PER_SEC / pcounter_freq.QuadPart;
-#elif defined(CLOCK_MONOTONIC)
-       struct timespec tspec;
-       clock_gettime (CLOCK_MONOTONIC, &tspec);
-       return ((uint64_t)tspec.tv_sec * TICKS_PER_SEC + tspec.tv_nsec);
-#else
-       struct timeval tv;
-       gettimeofday (&tv, NULL);
-       return ((uint64_t)tv.tv_sec * TICKS_PER_SEC + tv.tv_usec * 1000);
-#endif
-}
-
-/* must be power of two */
-#define TIME_ADJ 8
-
-static uint64_t
-fast_current_time (void)
-{
-       DECL_TLS_DATA;
-       if (tls->timer_count++ & (TIME_ADJ - 1)) {
-               tls->last_time += time_inc;
-               return tls->last_time;
-       }
-       tls->last_time = clock_time ();
-       return tls->last_time;
-}
-
-#if HAVE_RDTSC
-
-#define rdtsc(low,high) \
-       __asm__ __volatile__("rdtsc" : "=a" (low), "=d" (high))
-
-static uint64_t
-safe_rdtsc (int *cpu)
-{
-       unsigned int low, high;
-       int c1 = sched_getcpu ();
-       int c2;
-       rdtsc (low, high);
-       c2 = sched_getcpu ();
-       if (c1 != c2) {
-               *cpu = -1;
-               return 0;
-       }
-       *cpu = c1;
-       return (((uint64_t) high) << 32) + (uint64_t)low;
-}
-
-static double cpu_freq;
-
-static int 
-have_rdtsc (void) {
-       char buf[256];
-       int have_freq = 0;
-       int have_flag = 0;
-       float val;
-       FILE *cpuinfo;
-       int cpu = sched_getcpu ();
-
-       if (cpu < 0)
-               return 0;
-
-       if (!(cpuinfo = fopen ("/proc/cpuinfo", "r")))
-               return 0;
-       while (fgets (buf, sizeof(buf), cpuinfo)) {
-               if (sscanf (buf, "cpu MHz : %f", &val) == 1) {
-                       /*printf ("got mh: %f\n", val);*/
-                       have_freq = 1;
-                       cpu_freq = val * 1000000;
-               }
-               if (strncmp (buf, "flags :", 5) == 0) {
-                       if (strstr (buf, "constant_tsc")) {
-                               have_flag = 1;
-                               /*printf ("have tsc\n");*/
-                       }
-               }
-       }
-       fclose (cpuinfo);
-       return have_flag? have_freq: 0;
-}
-
-static uint64_t
-rdtsc_current_time (void)
-{
-       DECL_TLS_DATA;
-       if (tls->timer_count++ & (TIME_ADJ*8 - 1)) {
-               int cpu;
-               uint64_t tsc = safe_rdtsc (&cpu);
-               if (cpu != -1 && cpu == tls->last_cpu) {
-                       int64_t diff = tsc - tls->last_rdtsc;
-                       uint64_t nsecs;
-                       if (diff > 0) {
-                               nsecs = (double)diff/cpu_freq;
-                               //printf ("%llu cycles: %llu nsecs\n", diff, nsecs);
-                               return tls->last_time + nsecs;
-                       } else {
-                               printf ("tsc went backwards\n");
-                       }
-               } else {
-                       //printf ("wrong cpu: %d\n", cpu);
-               }
-       }
-       tls->last_time = clock_time ();
-       tls->last_rdtsc = safe_rdtsc (&tls->last_cpu);
-       return tls->last_time;
-}
-#else
-#define have_rdtsc() 0
-#define rdtsc_current_time fast_current_time
-#endif
-
-static uint64_t
-null_time (void)
-{
-       static uint64_t timer = 0;
-       return timer++;
-}
-
-void
-utils_init (int fast_time)
-{
-       int i;
-       uint64_t time_start, time_end;
-       TLS_INIT (tls_data);
-#ifdef HOST_WIN32
-       InitializeCriticalSection (&log_lock);
-       QueryPerformanceFrequency (&pcounter_freq);
-#endif
-#if defined (__APPLE__)
-       mach_timebase_info (&timebase_info);
-#endif
-
-       if (fast_time > 1) {
-               time_func = null_time;
-       } else if (fast_time) {
-               uint64_t timea;
-               uint64_t timeb;
-               clock_time ();
-               timea = clock_time ();
-               timeb = clock_time ();
-               time_inc = (timeb - timea) / TIME_ADJ;
-               /*printf ("time inc: %llu, timea: %llu, timeb: %llu, diff: %llu\n", time_inc, timea, timeb, timec-timeb);*/
-               if (have_rdtsc ())
-                       time_func = rdtsc_current_time;
-               else
-                       time_func = fast_current_time;
-       } else {
-               time_func = clock_time;
-       }
-       time_start = time_func ();
-       for (i = 0; i < 256; ++i)
-               time_func ();
-       time_end = time_func ();
-       timer_overhead = (time_end - time_start) / 256;
-}
-
-int
-get_timer_overhead (void)
-{
-       return timer_overhead;
-}
-
-uint64_t
-current_time (void)
-{
-       return time_func ();
-}
-
-void*
-alloc_buffer (int size)
-{
-       void *ptr;
-#ifdef HOST_WIN32
-       ptr = VirtualAlloc (NULL, size, MEM_COMMIT, PAGE_READWRITE);
-       return ptr;
-#else
-       ptr = mmap (NULL, size, PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
-       if (ptr == MAP_FAILED)
-               return NULL;
-       return ptr;
-#endif
-}
-
-void
-free_buffer (void *buf, int size)
-{
-#ifdef HOST_WIN32
-       VirtualFree (buf, 0, MEM_RELEASE);
-#else
-       munmap (buf, size);
-#endif
-}
-
-void
-take_lock (void)
-{
-#ifdef HOST_WIN32
-       EnterCriticalSection (&log_lock);
-#else
-       pthread_mutex_lock (&log_lock);
-#endif
-}
-
-void
-release_lock (void)
-{
-#ifdef HOST_WIN32
-       LeaveCriticalSection (&log_lock);
-#else
-       pthread_mutex_unlock (&log_lock);
-#endif
-}
-
-void
-encode_uleb128 (uint64_t value, uint8_t *buf, uint8_t **endbuf)
-{
-       uint8_t *p = buf;
-
-       do {
-               uint8_t b = value & 0x7f;
-               value >>= 7;
-               if (value != 0) /* more bytes to come */
-                       b |= 0x80;
-               *p ++ = b;
-       } while (value);
-
-       *endbuf = p;
-}
-
-void
-encode_sleb128 (intptr_t value, uint8_t *buf, uint8_t **endbuf)
-{
-       int more = 1;
-       int negative = (value < 0);
-       unsigned int size = sizeof (intptr_t) * 8;
-       uint8_t byte;
-       uint8_t *p = buf;
-
-       while (more) {
-               byte = value & 0x7f;
-               value >>= 7;
-               /* the following is unnecessary if the
-                * implementation of >>= uses an arithmetic rather
-                * than logical shift for a signed left operand
-                */
-               if (negative)
-                       /* sign extend */
-                       value |= - ((intptr_t)1 <<(size - 7));
-               /* sign bit of byte is second high order bit (0x40) */
-               if ((value == 0 && !(byte & 0x40)) ||
-                       (value == -1 && (byte & 0x40)))
-                       more = 0;
-               else
-                       byte |= 0x80;
-               *p ++= byte;
-       }
-
-       *endbuf = p;
-}
-
-uint64_t
-decode_uleb128 (uint8_t *buf, uint8_t **endbuf)
-{
-       uint64_t res = 0;
-       int shift = 0;
-
-       while (1) {
-               uint8_t b = *buf++;
-
-               res |= (((uint64_t)(b & 0x7f)) << shift);
-               if (!(b & 0x80))
-                       break;
-               shift += 7;
-       }
-
-       *endbuf = buf;
-
-       return res;
-}
-
-intptr_t
-decode_sleb128 (uint8_t *buf, uint8_t **endbuf)
-{
-       uint8_t *p = buf;
-       intptr_t res = 0;
-       int shift = 0;
-
-       while (1) {
-               uint8_t b = *p;
-               p ++;
-
-               res = res | (((intptr_t)(b & 0x7f)) << shift);
-               shift += 7;
-               if (!(b & 0x80)) {
-                       if (shift < sizeof (intptr_t) * 8 && (b & 0x40))
-                               res |= - ((intptr_t)1 << shift);
-                       break;
-               }
-       }
-
-       *endbuf = p;
-
-       return res;
-}
-
-uintptr_t
-thread_id (void)
-{
-#ifdef HOST_WIN32
-       return (uintptr_t)GetCurrentThreadId ();
-#else
-       return (uintptr_t)pthread_self ();
-#endif
-}
-
-uintptr_t
-process_id (void)
-{
-#ifdef HOST_WIN32
-       return GetCurrentProcessId ();
-#else
-       return (uintptr_t)getpid ();
-#endif
-}
-
diff --git a/mono/profiler/utils.h b/mono/profiler/utils.h
deleted file mode 100644 (file)
index 3af56d2..0000000
+++ /dev/null
@@ -1,24 +0,0 @@
-#ifndef __MONO_MPLOG_UTILS_H__
-#define __MONO_MPLOG_UTILS_H__
-
-#include "config.h"
-#include "mono/utils/mono-publib.h"
-
-void utils_init (int fast_time);
-int get_timer_overhead (void);
-uint64_t current_time (void);
-void* alloc_buffer (int size);
-void free_buffer (void *buf, int size);
-void take_lock (void);
-void release_lock (void);
-uintptr_t thread_id (void);
-uintptr_t process_id (void);
-
-void encode_uleb128 (uint64_t value, uint8_t *buf, uint8_t **endbuf);
-void encode_sleb128 (intptr_t value, uint8_t *buf, uint8_t **endbuf);
-uint64_t decode_uleb128 (uint8_t *buf, uint8_t **endbuf);
-intptr_t decode_sleb128 (uint8_t *buf, uint8_t **endbuf);
-
-
-#endif /* __MONO_MPLOG_UTILS_H__ */
-
index 9fe2f3ceeb4a62b9fc16be861e6d28179fcaac1c..62039f7267901a805e94c8e1fb79c4c7c72a9dca 100644 (file)
@@ -110,4 +110,9 @@ void mono_gc_memmove_aligned (void *dest, const void *src, size_t size);
 
 FILE *mono_gc_get_logfile (void);
 
+/* equivalent to options set via MONO_GC_PARAMS */
+void mono_gc_params_set (const char* options);
+/* equivalent to options set via MONO_GC_DEBUG */
+void mono_gc_debug_set (const char* options);
+
 #endif
index ff078a716739439b233abc2afa39189035ed8c24..2fdd86c2bf0613f7e75129c417d5a3341f82c1a4 100644 (file)
@@ -290,6 +290,8 @@ static SGEN_TV_DECLARE (time_major_conc_collection_end);
 
 int gc_debug_level = 0;
 FILE* gc_debug_file;
+static char* gc_params_options;
+static char* gc_debug_options;
 
 /*
 void
@@ -990,6 +992,24 @@ mono_gc_get_logfile (void)
        return gc_debug_file;
 }
 
+void
+mono_gc_params_set (const char* options)
+{
+       if (gc_params_options)
+               g_free (gc_params_options);
+
+       gc_params_options = g_strdup (options);
+}
+
+void
+mono_gc_debug_set (const char* options)
+{
+       if (gc_debug_options)
+               g_free (gc_debug_options);
+
+       gc_debug_options = g_strdup (options);
+}
+
 static void
 scan_finalizer_entries (SgenPointerQueue *fin_queue, ScanCopyContext ctx)
 {
@@ -1169,7 +1189,6 @@ finish_gray_stack (int generation, ScanCopyContext ctx)
 
        g_assert (sgen_gray_object_queue_is_empty (queue));
 
-       sgen_gray_object_queue_trim_free_list (queue);
        binary_protocol_finish_gray_stack_end (sgen_timestamp (), generation);
 }
 
@@ -2736,6 +2755,8 @@ sgen_gc_init (void)
        char **opts, **ptr;
        char *major_collector_opt = NULL;
        char *minor_collector_opt = NULL;
+       char *params_opts = NULL;
+       char *debug_opts = NULL;
        size_t max_heap = 0;
        size_t soft_limit = 0;
        int result;
@@ -2773,8 +2794,12 @@ sgen_gc_init (void)
 
        mono_coop_mutex_init (&sgen_interruption_mutex);
 
-       if ((env = g_getenv (MONO_GC_PARAMS_NAME))) {
-               opts = g_strsplit (env, ",", -1);
+       if ((env = g_getenv (MONO_GC_PARAMS_NAME)) || gc_params_options) {
+               params_opts = g_strdup_printf ("%s,%s", gc_params_options ? gc_params_options : "", env ? env : "");
+       }
+
+       if (params_opts) {
+               opts = g_strsplit (params_opts, ",", -1);
                for (ptr = opts; *ptr; ++ptr) {
                        char *opt = *ptr;
                        if (g_str_has_prefix (opt, "major=")) {
@@ -2976,15 +3001,22 @@ sgen_gc_init (void)
        if (minor_collector_opt)
                g_free (minor_collector_opt);
 
+       if (params_opts)
+               g_free (params_opts);
+
        alloc_nursery ();
 
        sgen_pinning_init ();
        sgen_cement_init (cement_enabled);
 
-       if ((env = g_getenv (MONO_GC_DEBUG_NAME))) {
+       if ((env = g_getenv (MONO_GC_DEBUG_NAME)) || gc_debug_options) {
+               debug_opts = g_strdup_printf ("%s,%s", gc_debug_options ? gc_debug_options  : "", env ? env : "");
+       }
+
+       if (debug_opts) {
                gboolean usage_printed = FALSE;
 
-               opts = g_strsplit (env, ",", -1);
+               opts = g_strsplit (debug_opts, ",", -1);
                for (ptr = opts; ptr && *ptr; ptr ++) {
                        char *opt = *ptr;
                        if (!strcmp (opt, ""))
@@ -3115,6 +3147,9 @@ sgen_gc_init (void)
                g_strfreev (opts);
        }
 
+       if (debug_opts)
+               g_free (debug_opts);
+
        if (check_mark_bits_after_major_collection)
                nursery_clear_policy = CLEAR_AT_GC;
 
index 9b5f92a19547916049f9129c7ed8a1fd360497c8..f8f04c145807db19fb27a7676f73d36f77555a05 100644 (file)
@@ -49,8 +49,6 @@ sgen_gray_object_alloc_queue_section (SgenGrayQueue *queue)
 {
        GrayQueueSection *section;
 
-       HEAVY_STAT (stat_gray_queue_section_alloc ++);
-
        if (queue->alloc_prepare_func)
                queue->alloc_prepare_func (queue);
 
@@ -60,6 +58,8 @@ sgen_gray_object_alloc_queue_section (SgenGrayQueue *queue)
                queue->free_list = section->next;
                STATE_TRANSITION (section, GRAY_QUEUE_SECTION_STATE_FREE_LIST, GRAY_QUEUE_SECTION_STATE_FLOATING);
        } else {
+               HEAVY_STAT (stat_gray_queue_section_alloc ++);
+
                /* Allocate a new section */
                section = (GrayQueueSection *)sgen_alloc_internal (INTERNAL_MEM_GRAY_QUEUE);
                STATE_SET (section, GRAY_QUEUE_SECTION_STATE_FLOATING);
index ca30670b71ab4e712d39639fc1c7e6bd2e2ba307..e8c0d7ab595a74fa63e86d3a8e03e087df4fd542 100644 (file)
 #include "mono/sgen/sgen-memory-governor.h"
 #include "mono/sgen/sgen-client.h"
 
-/* keep each size a multiple of ALLOC_ALIGN */
+/*
+ * When allocating sgen memory we choose the allocator with the smallest slot size
+ * that can fit our requested size. These slots are allocated within a block that
+ * can contain at least 2 slots of the specific size.
+ *
+ * Currently, slots from 8 to 2044/2040 are allocated inside 4096 sized blocks,
+ * 2728 to 4092/4088 inside 8192 sized blocks, and higher inside 16384 sized
+ * blocks. We also need to make sure the slots are pointer size aligned so we
+ * don't allocate unaligned memory.
+ *
+ * The computation of these sizes spawns from two basic rules :
+ *     - if we use slots of size s1 that fit n times in a block, it is illogical
+ * to use another slot of size s2 which also fits the same n times in a block.
+ *     - if we use slots of size s1 that fit n times in a block, there is no
+ * s2 > s1 that can fit n times in the block. That would mean we are wasting memory
+ * when allocating size S where s1 < S <= s2.
+ */
 #if SIZEOF_VOID_P == 4
 static const int allocator_sizes [] = {
           8,   16,   24,   32,   40,   48,   64,   80,
-         96,  128,  160,  192,  224,  248,  296,  320,
-        384,  448,  504,  528,  584,  680,  816, 1088,
-       1360, 2046, 2336, 2728, 3272, 4094, 5456, 8190 };
+         96,  124,  160,  192,  224,  252,  292,  340,
+        408,  452,  508,  584,  680,  816, 1020,
+       1364, 2044, 2728, 4092, 5460, 8188 };
 #else
 static const int allocator_sizes [] = {
           8,   16,   24,   32,   40,   48,   64,   80,
-         96,  128,  160,  192,  224,  248,  296,  320,
-        384,  448,  504,  528,  584,  680,  816, 1088,
-       1360, 2044, 2336, 2728, 3272, 4092, 5456, 8188 };
+         96,  128,  160,  192,  224,  248,  288,  336,
+        368,  448,  504,  584,  680,  816, 1016,
+       1360, 2040, 2728, 4088, 5456, 8184 };
 #endif
 
 #define NUM_ALLOCATORS (sizeof (allocator_sizes) / sizeof (int))
@@ -49,12 +65,13 @@ block_size (size_t slot_size)
        static int pagesize = -1;
 
        int size;
+       size_t aligned_slot_size = SGEN_ALIGN_UP_TO (slot_size, SIZEOF_VOID_P);
 
        if (pagesize == -1)
                pagesize = mono_pagesize ();
 
        for (size = pagesize; size < LOCK_FREE_ALLOC_SB_MAX_SIZE; size <<= 1) {
-               if (slot_size * 2 <= LOCK_FREE_ALLOC_SB_USABLE_SIZE (size))
+               if (aligned_slot_size * 2 <= LOCK_FREE_ALLOC_SB_USABLE_SIZE (size))
                        return size;
        }
        return LOCK_FREE_ALLOC_SB_MAX_SIZE;
@@ -173,6 +190,8 @@ sgen_alloc_internal_dynamic (size_t size, int type, gboolean assert_on_failure)
                        sgen_assert_memory_alloc (NULL, size, description_for_type (type));
                memset (p, 0, size);
        }
+
+       SGEN_ASSERT (0, !(((mword)p) & (sizeof(gpointer) - 1)), "Why do we allocate unaligned addresses ?");
        return p;
 }
 
@@ -206,6 +225,8 @@ sgen_alloc_internal (int type)
        p = mono_lock_free_alloc (&allocators [index]);
        memset (p, 0, size);
 
+       SGEN_ASSERT (0, !(((mword)p) & (sizeof(gpointer) - 1)), "Why do we allocate unaligned addresses ?");
+
        return p;
 }
 
@@ -264,13 +285,17 @@ sgen_init_internal_allocator (void)
        }
 
        for (size = mono_pagesize (); size <= LOCK_FREE_ALLOC_SB_MAX_SIZE; size <<= 1) {
-               int max_size = LOCK_FREE_ALLOC_SB_USABLE_SIZE (size) / 2;
+               int max_size = (LOCK_FREE_ALLOC_SB_USABLE_SIZE (size) / 2) & ~(SIZEOF_VOID_P - 1);
                /*
                 * we assert that allocator_sizes contains the biggest possible object size
-                * per block (4K => 4080 / 2 = 2040, 8k => 8176 / 2 = 4088, 16k => 16368 / 2 = 8184 on 64bits),
+                * per block which has to be an aligned address.
+                * (4K => 2040, 8k => 4088, 16k => 8184 on 64bits),
                 * so that we do not get different block sizes for sizes that should go to the same one
                 */
                g_assert (allocator_sizes [index_for_size (max_size)] == max_size);
+               g_assert (block_size (max_size) == size);
+               if (size < LOCK_FREE_ALLOC_SB_MAX_SIZE)
+                       g_assert (block_size (max_size + 1) == size << 1);
        }
 }
 
index 74c5c02a0278355074ab21273d63831791da11af..44ddf94b24dad9e505796d536d2d0c6f99417e14 100644 (file)
@@ -58,6 +58,11 @@ sgen_object_layout_dump (FILE *out)
        fprintf (out, "ref-array %lu\n", count_ref_array);
        fprintf (out, "vtype-array %lu\n", count_vtype_array);
 }
+#else
 
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_sgen_layout_stats_quiet_lnk4221(void) {}
 #endif
+#endif /* SGEN_OBJECT_LAYOUT_STATISTICS */
 #endif
index 3c96a2f0106bfc78cf20bca223315e7bd3f8c63a..d6460111a0f4094c25b90ca38e8f2445e0d6edd8 100644 (file)
@@ -142,7 +142,8 @@ COPY_OR_MARK_FUNCTION_NAME (GCObject **ptr, GCObject *obj, SgenGrayQueue *queue)
 
                SGEN_ASSERT (9, !SGEN_VTABLE_IS_PINNED (vtable_word), "Pinned object in non-pinned block?");
 
-               desc = sgen_vtable_get_descriptor ((GCVTable)vtable_word);
+               /* We untag the vtable for concurrent M&S, in case bridge is running and it tagged it */
+               desc = sgen_vtable_get_descriptor ((GCVTable)SGEN_POINTER_UNTAG_VTABLE (vtable_word));
                type = desc & DESC_TYPE_MASK;
 
                if (sgen_safe_object_is_small (obj, type)) {
@@ -183,7 +184,7 @@ COPY_OR_MARK_FUNCTION_NAME (GCObject **ptr, GCObject *obj, SgenGrayQueue *queue)
 
                        sgen_los_pin_object (obj);
                        if (SGEN_OBJECT_HAS_REFERENCES (obj))
-                               GRAY_OBJECT_ENQUEUE (queue, obj, sgen_obj_get_descriptor (obj));
+                               GRAY_OBJECT_ENQUEUE (queue, obj, desc);
                }
                return FALSE;
        }
index dc69381547f60bfb192de3cbec934092f20022c3..d6c7f130f3cae7571d5524cd7cdf67c65119ce28 100644 (file)
@@ -295,7 +295,7 @@ sgen_output_log_entry (SgenLogEntry *entry, gint64 stw_time, int generation)
 
        switch (entry->type) {
                case SGEN_LOG_NURSERY:
-                       mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC, "GC_MINOR%s: (%s) time %.2fms, %s promoted %dK major size: %dK in use: %dK los size: %dK in use: %dK",
+                       mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC, "GC_MINOR%s: (%s) time %.2fms, %s promoted %zdK major size: %zdK in use: %zdK los size: %zdK in use: %zdK",
                                entry->is_overflow ? "_OVERFLOW" : "",
                                entry->reason ? entry->reason : "",
                                entry->time / 10000.0f,
@@ -307,7 +307,7 @@ sgen_output_log_entry (SgenLogEntry *entry, gint64 stw_time, int generation)
                                entry->los_size_in_use / 1024);
                        break;
                case SGEN_LOG_MAJOR_SERIAL:
-                       mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC, "GC_MAJOR%s: (%s) time %.2fms, %s los size: %dK in use: %dK",
+                       mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC, "GC_MAJOR%s: (%s) time %.2fms, %s los size: %zdK in use: %zdK",
                                entry->is_overflow ? "_OVERFLOW" : "",
                                entry->reason ? entry->reason : "",
                                (int)entry->time / 10000.0f,
@@ -319,7 +319,7 @@ sgen_output_log_entry (SgenLogEntry *entry, gint64 stw_time, int generation)
                        mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC, "GC_MAJOR_CONCURRENT_START: (%s)", entry->reason ? entry->reason : "");
                        break;
                case SGEN_LOG_MAJOR_CONC_FINISH:
-                       mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC, "GC_MAJOR_CONCURRENT_FINISH: (%s) time %.2fms, %s los size: %dK in use: %dK",
+                       mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC, "GC_MAJOR_CONCURRENT_FINISH: (%s) time %.2fms, %s los size: %zdK in use: %zdK",
                                entry->reason ? entry->reason : "",
                                entry->time / 10000.0f,
                                full_timing_buff,
@@ -327,7 +327,7 @@ sgen_output_log_entry (SgenLogEntry *entry, gint64 stw_time, int generation)
                                entry->los_size_in_use / 1024);
                        break;
                case SGEN_LOG_MAJOR_SWEEP_FINISH:
-                       mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC, "GC_MAJOR_SWEEP: major size: %dK in use: %dK",
+                       mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC, "GC_MAJOR_SWEEP: major size: %zdK in use: %zdK",
                                entry->major_size / 1024,
                                entry->major_size_in_use / 1024);
                        break;
index dfdff8c9062f2a7e25f8b5d5591ebc1b1b598187..76eebdd86edfe066f5bfbdf1c6c51d6ad562372e 100644 (file)
@@ -97,7 +97,7 @@ sgen_workers_ensure_awake (void)
 }
 
 static void
-worker_try_finish (void)
+worker_try_finish (WorkerData *data)
 {
        State old_state;
 
@@ -115,6 +115,8 @@ worker_try_finish (void)
        } while (!set_state (old_state, STATE_NOT_WORKING));
 
        binary_protocol_worker_finish (sgen_timestamp (), forced_stop);
+
+       sgen_gray_object_queue_trim_free_list (&data->private_gray_queue);
 }
 
 void
@@ -226,7 +228,7 @@ marker_idle_func (void *data_untyped)
                        sgen_thread_pool_job_enqueue (job);
                        preclean_job = NULL;
                } else {
-                       worker_try_finish ();
+                       worker_try_finish (data);
                }
        }
 }
index 1a83dfa5898c2ef363148e7340cbeb8c665b3609..9f3996923b4931e3420e9811db9233fdf3d60852 100644 (file)
@@ -6,7 +6,7 @@ else
 FEATUREFUL_RUNTIME_TEST = test-appdomain-unload
 endif
 
-check-local: assemblyresolve/test/asm.dll testjit test-generic-sharing test-type-load test-cattr-type-load test-reflection-load-with-context test_platform     \
+check-local: assemblyresolve/test/asm.dll testjit test-generic-sharing test-type-load test-multi-netmodule test-cattr-type-load test-reflection-load-with-context test_platform        \
                 test-console-output test-messages test-env-options test-unhandled-exception-2 $(FEATUREFUL_RUNTIME_TEST) test-process-stress rm-empty-logs
 check-full: test-sgen check-local
 check-parallel: compile-tests check-full
@@ -140,6 +140,7 @@ BASE_TEST_MOBILE_STATIC_NOT_SUPPORTED= \
        threadpool-exceptions7.cs # Needs AppDomains \
        cross-domain.cs # Needs AppDomains \
        generic-unloading.2.cs # Needs AppDomains \
+       namedmutex-destroy-race.cs # needs named Mutex \
        thread6.cs # On MOBILE, ThreadAbortException doesn't have necessary field for this test
 
 # Disabled until ?mcs is fixed
@@ -468,7 +469,7 @@ BASE_TEST_CS_SRC_UNIVERSAL=         \
        bug-29585.cs    \
        priority.cs     \
        abort-cctor.cs  \
-       namedmutex-destroy-race.cs
+       thread-native-exit.cs
 
 if INSTALL_MOBILE_STATIC
 BASE_TEST_CS_SRC= \
@@ -1066,6 +1067,14 @@ test-type-load: $(TEST_DRIVER_DEPEND)
        @echo "Testing load-exception.exe..."
        @$(RUNTIME) load-exceptions.exe > load-exceptions.exe.stdout 2> load-exceptions.exe.stderr
 
+EXTRA_DIST += test-multi-netmodule-1-netmodule.cs test-multi-netmodule-2-dll1.cs test-multi-netmodule-3-dll2.cs test-multi-netmodule-4-exe.cs
+test-multi-netmodule:
+       @$(MCS) -t:module test-multi-netmodule-1-netmodule.cs
+       @$(MCS) -addmodule:test-multi-netmodule-1-netmodule.netmodule -t:library test-multi-netmodule-2-dll1.cs
+       @$(MCS) -addmodule:test-multi-netmodule-1-netmodule.netmodule -t:library test-multi-netmodule-3-dll2.cs
+       @$(MCS) -r:test-multi-netmodule-2-dll1.dll test-multi-netmodule-4-exe.cs
+       $(RUNTIME) test-multi-netmodule-4-exe.exe > test-multi-netmodule-4-exe.exe.stdout 2> test-multi-netmodule-4-exe.exe.stderr
+
 EXTRA_DIST += custom-attr-errors.cs custom-attr-errors-lib.cs
 test-cattr-type-load: $(TEST_DRIVER_DEPEND) custom-attr-errors.cs custom-attr-errors-lib.cs
        $(MCS) -D:WITH_MEMBERS /t:library $(srcdir)/custom-attr-errors-lib.cs
index 62529ecc557579f80dd442a8da3fcac7ca42ca1e..d2a09a6d068a6290ca4045289e175b872061f7f8 100644 (file)
@@ -7229,3 +7229,15 @@ mono_test_marshal_fixed_array (FixedArrayStruct s)
 {
        return s.array [0] + s.array [1] + s.array [2];
 }
+
+LIBTEST_API int STDCALL
+mono_test_marshal_pointer_array (int *arr[])
+{
+       int i;
+
+       for (i = 0; i < 10; ++i) {
+               if (*arr [i] != -1)
+                       return 1;
+       }
+       return 0;
+}
index e170ba441ab44b5f9b32da5c914faac2a80d437d..f9ecf68a4027a95b9da5b0681024afd47b435f97 100644 (file)
@@ -1922,5 +1922,22 @@ public unsafe class Tests {
 
                return mono_test_marshal_fixed_array (s);
        }
+
+       [DllImport ("libtest", EntryPoint="mono_test_marshal_pointer_array")]
+       public static extern int mono_test_marshal_pointer_array (int*[] arr);
+
+       public static unsafe int test_0_pointer_array () {
+               var arr = new int [10];
+               for (int i = 0; i < arr.Length; i++)
+                       arr [i] = -1;
+               var arr2 = new int*[10];
+               for (int i = 0; i < arr2.Length; i++) {
+                       GCHandle handle = GCHandle.Alloc(arr[i], GCHandleType.Pinned);
+                       fixed (int *ptr = &arr[i]) {
+                               arr2[i] = ptr;
+                       }
+               }
+               return mono_test_marshal_pointer_array (arr2);
+       }
 }
 
diff --git a/mono/tests/test-multi-netmodule-1-netmodule.cs b/mono/tests/test-multi-netmodule-1-netmodule.cs
new file mode 100644 (file)
index 0000000..2abdc39
--- /dev/null
@@ -0,0 +1,4 @@
+// Compiler options: -t:module
+
+public class M1 {
+}
diff --git a/mono/tests/test-multi-netmodule-2-dll1.cs b/mono/tests/test-multi-netmodule-2-dll1.cs
new file mode 100644 (file)
index 0000000..018db84
--- /dev/null
@@ -0,0 +1,5 @@
+// Compiler options: -addmodule:test-multi-netmodule-1-netmodule.netmodule -t:library
+
+public class M2 {
+       public M1 m1 = new M1();
+}
diff --git a/mono/tests/test-multi-netmodule-3-dll2.cs b/mono/tests/test-multi-netmodule-3-dll2.cs
new file mode 100644 (file)
index 0000000..4229b80
--- /dev/null
@@ -0,0 +1,5 @@
+// Compiler options: -addmodule:test-multi-netmodule-1-netmodule.netmodule -t:library
+
+public class M3 {
+       public M1 m1 = new M1();
+}
diff --git a/mono/tests/test-multi-netmodule-4-exe.cs b/mono/tests/test-multi-netmodule-4-exe.cs
new file mode 100644 (file)
index 0000000..03cd242
--- /dev/null
@@ -0,0 +1,28 @@
+// Compiler options: -r:test-multi-netmodule-2-dll1.dll
+
+using System;
+using System.Reflection;
+
+public class M4 {
+       public static int Main () {
+               M2 m2 = new M2();
+
+               // Expecting failure
+               try {
+                       var DLL = Assembly.LoadFile(@"test-multi-netmodule-3-dll2.dll");
+               var m3Type = DLL.GetType("M3");
+               var m3 = Activator.CreateInstance(m3Type);
+               var m3m1Field = m3Type.GetField("m1");
+
+               Console.WriteLine("M3    assembly:" + m3Type.Assembly);
+                       Console.WriteLine("M3.M1 assembly:" + m3m1Field.DeclaringType.Assembly);
+        } catch (System.TypeLoadException) {
+               return 0;
+        }
+
+               Console.WriteLine("M2    assembly:" + typeof (M2).Assembly);
+               Console.WriteLine("M2.M1 assembly:" + m2.m1.GetType().Assembly);
+
+               return 1;
+       }
+}
diff --git a/mono/tests/thread-native-exit.cs b/mono/tests/thread-native-exit.cs
new file mode 100644 (file)
index 0000000..e112be0
--- /dev/null
@@ -0,0 +1,71 @@
+
+using System;
+using System.Runtime.InteropServices;
+using System.Threading;
+
+class Driver
+{
+       [DllImport ("libc")]
+       extern static void pthread_exit (IntPtr value);
+
+       [DllImport ("kernel32")]
+       extern static void ExitThread (IntPtr value);
+
+       static Thread GetThread1 ()
+       {
+               return new Thread (() => {
+                       /* Exit bypassing completely the runtime */
+                       if (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX)
+                           pthread_exit (IntPtr.Zero);
+                       else
+                           ExitThread (IntPtr.Zero);
+               });
+       }
+
+       static Thread GetThread2 ()
+       {
+               return new Thread (() => {
+                       /* Exit without returning from the ThreadStart delegate */
+                       Thread.CurrentThread.Abort ();
+               });
+       }
+
+       static Thread GetThread3 ()
+       {
+               return new Thread (() => {
+                       /* Exit by returning from the ThreadStart delegate */
+                       return;
+               });
+       }
+
+       static Thread[] CreateThreads ()
+       {
+               return new Thread [] {
+                       GetThread1 (),
+                       GetThread2 (),
+                       GetThread3 (),
+               };
+       }
+
+       public static void Main ()
+       {
+               Thread[] threads;
+
+               {
+                       threads = CreateThreads ();
+
+                       for (int i = 0; i < threads.Length; ++i)
+                               threads [i].Start ();
+
+                       for (int i = 0; i < threads.Length; ++i)
+                               threads [i].Join ();
+               }
+
+               {
+                       threads = CreateThreads ();
+
+                       for (int i = 0; i < threads.Length; ++i)
+                               threads [i].Start ();
+               }
+       }
+}
\ No newline at end of file
index d67b9ff1fed2bb89a6a5697356203fd73b123b95..5bc5bbd600326c90c774a43f7280e805ff0e1c04 100644 (file)
@@ -27,9 +27,12 @@ monoutils_sources = \
        mono-dl-darwin.c        \
        mono-dl-posix.c         \
        mono-dl.h               \
+       mono-dl-windows.h       \
        mono-log-windows.c      \
        mono-log-common.c       \
        mono-log-posix.c        \
+       mono-log-android.c \
+       mono-log-darwin.c \
        mono-internal-hash.c    \
        mono-internal-hash.h    \
        mono-io-portability.c   \
@@ -38,8 +41,10 @@ monoutils_sources = \
        mono-filemap.c          \
        mono-math.c             \
        mono-mmap.c             \
+       mono-mmap-windows.c             \
        mono-mmap.h             \
        mono-mmap-internals.h   \
+       mono-mmap-windows.h     \
        mono-os-mutex.h         \
        mono-coop-mutex.h               \
        mono-once.h             \
@@ -47,7 +52,9 @@ monoutils_sources = \
        mono-networkinterfaces.c                \
        mono-networkinterfaces.h                \
        mono-proclib.c          \
+       mono-proclib-windows.c          \
        mono-proclib.h          \
+       mono-proclib-windows.h          \
        mono-publib.c           \
        mono-string.h           \
        mono-time.c             \
@@ -147,7 +154,9 @@ monoutils_sources = \
        networking-windows.c    \
        networking.h    \
        mono-rand.c     \
+       mono-rand-windows.c     \
        mono-rand.h \
+       mono-rand-windows.h \
        memfuncs.c \
        memfuncs.h \
        parse.c \
index 86afad502ffe27947c4bf7718bc49abbd4ded33c..2f5e8a8a673a8688e78c577b57b7c194effaad76 100644 (file)
@@ -581,6 +581,10 @@ InterlockedCompareExchange64(volatile gint64 *dest, gint64 exch, gint64 comp)
        return(old);
 }
 
+#endif
 #endif
 
+#if defined(HOST_WIN32) && defined(_MSC_VER)
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_atomic_lnk4221(void) {}
 #endif
index 43a690c75920671419df88b5d2dc80ba1f8c1ca0..09926ffcd5f2266ce632b71bf837ec8dc73c9c5e 100644 (file)
@@ -473,6 +473,12 @@ check_image_may_reference_image(MonoImage *from, MonoImage *to)
                        // For each queued image visit all directly referenced images
                        int inner_idx;
 
+                       // 'files' and 'modules' semantically contain the same items but because of lazy loading we must check both
+                       for (inner_idx = 0; !success && inner_idx < checking->file_count; inner_idx++)
+                       {
+                               CHECK_IMAGE_VISIT (checking->files[inner_idx]);
+                       }
+
                        for (inner_idx = 0; !success && inner_idx < checking->module_count; inner_idx++)
                        {
                                CHECK_IMAGE_VISIT (checking->modules[inner_idx]);
@@ -480,8 +486,8 @@ check_image_may_reference_image(MonoImage *from, MonoImage *to)
 
                        for (inner_idx = 0; !success && inner_idx < checking->nreferences; inner_idx++)
                        {
-                               // References are lazy-loaded and thus allowed to be NULL.
-                               // If they are NULL, we don't care about them for this search, because they haven't impacted ref_count yet.
+                               // Assembly references are lazy-loaded and thus allowed to be NULL.
+                               // If they are NULL, we don't care about them for this search, because their images haven't impacted ref_count yet.
                                if (checking->references[inner_idx])
                                {
                                        CHECK_IMAGE_VISIT (checking->references[inner_idx]->image);
@@ -540,10 +546,10 @@ check_image_set_may_reference_image_set (MonoImageSet *from, MonoImageSet *to)
                if (to->images[to_idx] == mono_defaults.corlib)
                        seen = TRUE;
 
-               // For each item in to->images, scan over from->images looking for it.
+               // For each item in to->images, scan over from->images seeking a path to it.
                for (from_idx = 0; !seen && from_idx < from->nimages; from_idx++)
                {
-                       if (to->images[to_idx] == from->images[from_idx])
+                       if (check_image_may_reference_image (from->images[from_idx], to->images[to_idx]))
                                seen = TRUE;
                }
 
index 1f4ca74112a498f7b4b35316c4ebffebd369eb73..3dcbe286cca7ee4da0924ddf14f8e010e40607b7 100644 (file)
@@ -12,6 +12,7 @@
 
 #include <config.h>
 #include <mono/utils/atomic.h>
+#include <mono/utils/mono-compiler.h>
 #include <mono/utils/mono-publib.h>
 
 typedef enum {
@@ -185,12 +186,18 @@ void assert_in_gc_critical_region (void);
 void check_metadata_store(void *from, void *to);
 void check_metadata_store_local(void *from, void *to);
 
+#define CHECKED_METADATA_STORE(ptr, val) check_metadata_store ((ptr), (val))
+#define CHECKED_METADATA_STORE_LOCAL(ptr, val) check_metadata_store_local ((ptr), (val))
+
 #else
 
 #define CHECKED_METADATA_WRITE_PTR(ptr, val) do { (ptr) = (val); } while (0)
 #define CHECKED_METADATA_WRITE_PTR_LOCAL(ptr, val) do { (ptr) = (val); } while (0)
 #define CHECKED_METADATA_WRITE_PTR_ATOMIC(ptr, val) do { mono_atomic_store_release (&(ptr), (val)); } while (0)
 
+#define CHECKED_METADATA_STORE(ptr, val) do { (ptr); (val); } while (0)
+#define CHECKED_METADATA_STORE_LOCAL(ptr, val) do { (ptr); (val); } while (0)
+
 #endif /* defined(ENABLE_CHECKED_BUILD_METADATA) */
 
 #ifdef ENABLE_CHECKED_BUILD_THREAD
@@ -201,7 +208,7 @@ void check_metadata_store_local(void *from, void *to);
 
 void checked_build_thread_transition(const char *transition, void *info, int from_state, int suspend_count, int next_state, int suspend_count_delta);
 
-G_GNUC_NORETURN void mono_fatal_with_history(const char *msg, ...);
+G_GNUC_NORETURN MONO_ATTR_FORMAT_PRINTF(1,2) void mono_fatal_with_history(const char *msg, ...);
 
 #else
 
index 70d550d95c239b6b6d5ce5d868f31633a590c7d1..9501307fc1dd29f5c8c3c26baa9073c3b5856bf5 100644 (file)
@@ -27,8 +27,8 @@
 #define __MONO_LOCKFREEALLOC_H__
 
 #include <glib.h>
-
-#include "lock-free-queue.h"
+#include <mono/utils/lock-free-queue.h>
+#include <mono/utils/mono-mmap.h>
 
 typedef struct {
        MonoLockFreeQueue partial;
index d03ba8051aa565a53319b35aad89cecae2b9f450..7becf4816ffd571052129646b5c7c39ae7db4275 100644 (file)
 #define MONO_ATTR_USED
 #endif
 
+#ifdef __GNUC__
+#define MONO_ATTR_FORMAT_PRINTF(fmt_pos,arg_pos) __attribute__((format(printf,fmt_pos,arg_pos)))
+#else
+#define MONO_ATTR_FORMAT_PRINTF(fmt_pos,arg_pos)
+#endif
+
 #ifdef HAVE_KW_THREAD
 
 #define MONO_HAVE_FAST_TLS
 #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>
@@ -275,12 +278,6 @@ typedef SSIZE_T ssize_t;
 #define MONO_LLVM_INTERNAL 
 #endif
 
-#if HAVE_DEPRECATED
-#define MONO_DEPRECATED __attribute__ ((deprecated))
-#else
-#define MONO_DEPRECATED 
-#endif
-
 #ifdef __GNUC__
 #define MONO_ALWAYS_INLINE __attribute__((always_inline))
 #elif defined(_MSC_VER)
index 2704c8662a8d1e2919a99fb3afb91361a551bb1d..0a1bd524cfd42261ac798b6f0b2eb1b8c7fe726f 100644 (file)
@@ -699,6 +699,8 @@ mono_ia64_context_get_fp (MonoContext *ctx)
 
 #elif ((defined(__mips__) && !defined(MONO_CROSS_COMPILE)) || (defined(TARGET_MIPS))) && SIZEOF_REGISTER == 4 /* defined(__ia64__) */
 
+#define MONO_ARCH_HAS_MONO_CONTEXT 1
+
 #include <mono/arch/mips/mips-codegen.h>
 
 typedef struct {
index ae33b4a9f39336cb31f1c31f31d43ee7e4d497ed..f867960803ba46f7c81f828b8a4e56fc614fd382 100644 (file)
@@ -347,6 +347,13 @@ page_faults (void)
        return mono_process_get_data (GINT_TO_POINTER (mono_process_current_pid ()), MONO_PROCESS_FAULTS);
 }
 
+
+// If cpu_load gets inlined on Windows then cpu_load_1min, cpu_load_5min and cpu_load_15min can be folded into a single function and that will
+// cause a failure when registering counters since the same function address will be used by all three functions. Preventing this method from being inlined
+// will make sure the registered callback functions remains unique.
+#ifdef _MSC_VER
+__declspec(noinline)
+#endif
 static double
 cpu_load (int kind)
 {
diff --git a/mono/utils/mono-dl-windows-uwp.c b/mono/utils/mono-dl-windows-uwp.c
new file mode 100644 (file)
index 0000000..8bb8e6c
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * mono-dl-windows-uwp.c: UWP dl support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+
+#if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
+#include <Windows.h>
+#include "mono/utils/mono-dl-windows.h"
+
+void*
+mono_dl_lookup_symbol_in_process (const char *symbol_name)
+{
+       g_unsupported_api ("EnumProcessModules");
+       SetLastError (ERROR_NOT_SUPPORTED);
+
+       return NULL;
+}
+
+char*
+mono_dl_current_error_string (void)
+{
+       char *ret = NULL;
+       TCHAR buf [1024];
+       DWORD code = GetLastError ();
+
+       if (!FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
+               code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, G_N_ELEMENTS(buf) - 1, NULL))
+               buf[0] = TEXT('\0');
+
+       ret = u16to8 (buf);
+       return ret;
+}
+
+#else /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_mono_dl_windows_uwp_quiet_lnk4221(void) {}
+#endif
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
index 9e3efa796f7aa93503ab2fa1712d2be476519c73..04f695d22de38e15d4a199142b400023df9e5f1c 100644 (file)
@@ -13,6 +13,7 @@
 #if defined(HOST_WIN32)
 
 #include "mono/utils/mono-dl.h"
+#include "mono/utils/mono-dl-windows.h"
 #include "mono/utils/mono-embed.h"
 #include "mono/utils/mono-path.h"
 
@@ -25,7 +26,6 @@
 #include <windows.h>
 #include <psapi.h>
 
-
 const char*
 mono_dl_get_so_prefix (void)
 {
@@ -48,14 +48,20 @@ mono_dl_open_file (const char *file, int flags)
        gpointer hModule = NULL;
        if (file) {
                gunichar2* file_utf16 = g_utf8_to_utf16 (file, strlen (file), NULL, NULL, NULL);
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
                guint last_sem = SetErrorMode (SEM_FAILCRITICALERRORS);
+#endif
                guint32 last_error = 0;
 
                hModule = LoadLibrary (file_utf16);
                if (!hModule)
                        last_error = GetLastError ();
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
                SetErrorMode (last_sem);
+#endif
+
                g_free (file_utf16);
 
                if (!hModule)
@@ -73,23 +79,15 @@ mono_dl_close_handle (MonoDl *module)
                FreeLibrary (module->handle);
 }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 void*
-mono_dl_lookup_symbol (MonoDl *module, const char *symbol_name)
+mono_dl_lookup_symbol_in_process (const char *symbol_name)
 {
        HMODULE *modules;
        DWORD buffer_size = sizeof (HMODULE) * 1024;
        DWORD needed, i;
        gpointer proc = NULL;
 
-       /* get the symbol directly from the specified module */
-       if (!module->main_module)
-               return GetProcAddress (module->handle, symbol_name);
-
-       /* get the symbol from the main module */
-       proc = GetProcAddress (module->handle, symbol_name);
-       if (proc != NULL)
-               return proc;
-
        /* get the symbol from the loaded DLLs */
        modules = (HMODULE *) g_malloc (buffer_size);
        if (modules == NULL)
@@ -129,6 +127,25 @@ mono_dl_lookup_symbol (MonoDl *module, const char *symbol_name)
        g_free (modules);
        return NULL;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+void*
+mono_dl_lookup_symbol (MonoDl *module, const char *symbol_name)
+{
+       gpointer proc = NULL;
+
+       /* get the symbol directly from the specified module */
+       if (!module->main_module)
+               return GetProcAddress (module->handle, symbol_name);
+
+       /* get the symbol from the main module */
+       proc = GetProcAddress (module->handle, symbol_name);
+       if (proc != NULL)
+               return proc;
+
+       /* get the symbol from the loaded DLLs */
+       return mono_dl_lookup_symbol_in_process (symbol_name);
+}
 
 int
 mono_dl_convert_flags (int flags)
@@ -136,6 +153,7 @@ mono_dl_convert_flags (int flags)
        return 0;
 }
 
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
 char*
 mono_dl_current_error_string (void)
 {
@@ -153,6 +171,7 @@ mono_dl_current_error_string (void)
        }
        return ret;
 }
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
 
 int
 mono_dl_get_executable_path (char *buf, int buflen)
@@ -165,5 +184,4 @@ mono_dl_get_system_dir (void)
 {
        return NULL;
 }
-
 #endif
diff --git a/mono/utils/mono-dl-windows.h b/mono/utils/mono-dl-windows.h
new file mode 100644 (file)
index 0000000..5215418
--- /dev/null
@@ -0,0 +1,14 @@
+#ifndef __MONO_UTILS_DL_WINDOWS_H__
+#define __MONO_UTILS_DL_WINDOWS_H__
+
+#include <config.h>
+#include <glib.h>
+
+#ifdef HOST_WIN32
+#include "mono/utils/mono-dl.h"
+
+void*
+mono_dl_lookup_symbol_in_process (const char *symbol_name);
+#endif /* HOST_WIN32 */
+#endif /* __MONO_UTILS_DL_WINDOWS_H__ */
+
index e143901748d710d2e2f8bce87d31b0bf32dbe102..c74923c00944b34d83aa5c2da0cc4a2fa19931d4 100644 (file)
@@ -32,6 +32,12 @@ typedef struct {
        void *padding [3];
 } MonoErrorInternal;
 
+/* Invariant: the error strings are allocated in the mempool of the given image */
+struct _MonoErrorBoxed {
+       MonoError error;
+       MonoImage *image;
+};
+
 #define error_init(error) do { \
        ((MonoErrorInternal*)(error))->error_code = MONO_ERROR_NONE;    \
        ((MonoErrorInternal*)(error))->flags = 0;       \
@@ -57,64 +63,67 @@ mono_error_dup_strings (MonoError *error, gboolean dup_strings);
 
 /* This function is not very useful as you can't provide any details beyond the message.*/
 void
-mono_error_set_error (MonoError *error, int error_code, const char *msg_format, ...);
+mono_error_set_error (MonoError *error, int error_code, const char *msg_format, ...) MONO_ATTR_FORMAT_PRINTF(3,4);
 
 void
-mono_error_set_assembly_load (MonoError *error, const char *assembly_name, const char *msg_format, ...);
+mono_error_set_assembly_load (MonoError *error, const char *assembly_name, const char *msg_format, ...) MONO_ATTR_FORMAT_PRINTF(3,4);
 
 void
 mono_error_set_assembly_load_simple (MonoError *error, const char *assembly_name, gboolean refection_only);
 
 void
-mono_error_set_type_load_class (MonoError *error, MonoClass *klass, const char *msg_format, ...);
+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_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_set_method_load (MonoError *error, MonoClass *klass, const char *method_name, const char *msg_format, ...);
+mono_error_set_method_load (MonoError *error, MonoClass *klass, const char *method_name, const char *msg_format, ...) MONO_ATTR_FORMAT_PRINTF(4,5);
 
 void
-mono_error_set_field_load (MonoError *error, MonoClass *klass, const char *field_name, const char *msg_format, ...);
+mono_error_set_field_load (MonoError *error, MonoClass *klass, const char *field_name, const char *msg_format, ...)  MONO_ATTR_FORMAT_PRINTF(4,5);
 
 void
-mono_error_set_bad_image (MonoError *error, MonoImage *image, const char *msg_format, ...);
+mono_error_set_bad_image (MonoError *error, MonoImage *image, const char *msg_format, ...) MONO_ATTR_FORMAT_PRINTF(3,4);
 
 void
-mono_error_set_bad_image_name (MonoError *error, const char *file_name, const char *msg_format, ...);
+mono_error_set_bad_image_name (MonoError *error, const char *file_name, const char *msg_format, ...) MONO_ATTR_FORMAT_PRINTF(3,4);
 
 void
-mono_error_set_out_of_memory (MonoError *error, const char *msg_format, ...);
+mono_error_set_out_of_memory (MonoError *error, const char *msg_format, ...) MONO_ATTR_FORMAT_PRINTF(2,3);
 
 void
-mono_error_set_argument (MonoError *error, const char *argument, const char *msg_format, ...);
+mono_error_set_argument (MonoError *error, const char *argument, const char *msg_format, ...) MONO_ATTR_FORMAT_PRINTF(3,4);
 
 void
-mono_error_set_argument_null (MonoError *oerror, const char *argument, const char *msg_format, ...);
+mono_error_set_argument_null (MonoError *oerror, const char *argument, const char *msg_format, ...) MONO_ATTR_FORMAT_PRINTF(3,4);
 
 void
-mono_error_set_not_verifiable (MonoError *oerror, MonoMethod *method, const char *msg_format, ...);
+mono_error_set_not_verifiable (MonoError *oerror, MonoMethod *method, const char *msg_format, ...) MONO_ATTR_FORMAT_PRINTF(3,4);
 
 void
-mono_error_set_generic_error (MonoError *error, const char * name_space, const char *name, const char *msg_format, ...);
+mono_error_set_generic_error (MonoError *error, const char * name_space, const char *name, const char *msg_format, ...) MONO_ATTR_FORMAT_PRINTF(4,5);
 
 void
-mono_error_set_execution_engine (MonoError *error, const char *msg_format, ...);
+mono_error_set_execution_engine (MonoError *error, const char *msg_format, ...) MONO_ATTR_FORMAT_PRINTF(2,3);
 
 void
-mono_error_set_not_implemented (MonoError *error, const char *msg_format, ...);
+mono_error_set_not_implemented (MonoError *error, const char *msg_format, ...) MONO_ATTR_FORMAT_PRINTF(2,3);
 
 void
-mono_error_set_not_supported (MonoError *error, const char *msg_format, ...);
+mono_error_set_not_supported (MonoError *error, const char *msg_format, ...) MONO_ATTR_FORMAT_PRINTF(2,3);
 
 void
-mono_error_set_invalid_operation (MonoError *error, const char *msg_format, ...);
+mono_error_set_invalid_operation (MonoError *error, const char *msg_format, ...) MONO_ATTR_FORMAT_PRINTF(2,3);
 
 void
 mono_error_set_exception_instance (MonoError *error, MonoException *exc);
 
 void
-mono_error_set_invalid_program (MonoError *oerror, const char *msg_format, ...);
+mono_error_set_invalid_program (MonoError *oerror, const char *msg_format, ...) MONO_ATTR_FORMAT_PRINTF(2,3);
 
 MonoException*
 mono_error_prepare_exception (MonoError *error, MonoError *error_out);
@@ -128,4 +137,11 @@ mono_error_raise_exception (MonoError *error);
 void
 mono_error_move (MonoError *dest, MonoError *src);
 
+MonoErrorBoxed*
+mono_error_box (const MonoError *error, MonoImage *image);
+
+gboolean
+mono_error_set_from_boxed (MonoError *error, const MonoErrorBoxed *from);
+
+
 #endif
index 7e186b6b717ce06b2f4103bb2ab3abe22e5ce2df..a59f2a123fb112f62d245290be57a7c909920f8b 100644 (file)
@@ -38,6 +38,12 @@ is_managed_exception (MonoErrorInternal *error)
        return (error->error_code == MONO_ERROR_EXCEPTION_INSTANCE);
 }
 
+static gboolean
+is_boxed (MonoErrorInternal *error)
+{
+       return ((error->flags & MONO_ERROR_MEMPOOL_BOXED) != 0);
+}
+
 static void
 mono_error_prepare (MonoErrorInternal *error)
 {
@@ -116,6 +122,8 @@ mono_error_cleanup (MonoError *oerror)
 
        /* Two cleanups in a row without an intervening init. */
        g_assert (orig_error_code != MONO_ERROR_CLEANUP_CALLED_SENTINEL);
+       /* Mempool stored error shouldn't be cleaned up */
+       g_assert (!is_boxed (error));
 
        /* Mark it as cleaned up. */
        error->error_code = MONO_ERROR_CLEANUP_CALLED_SENTINEL;
@@ -294,13 +302,22 @@ mono_error_set_assembly_load_simple (MonoError *oerror, const char *assembly_nam
 
 void
 mono_error_set_type_load_class (MonoError *oerror, MonoClass *klass, const char *msg_format, ...)
+{
+       va_list args;
+       va_start (args, msg_format);
+       mono_error_vset_type_load_class (oerror, klass, msg_format, args);
+       va_end (args);
+}
+
+void
+mono_error_vset_type_load_class (MonoError *oerror, MonoClass *klass, const char *msg_format, va_list args)
 {
        MonoErrorInternal *error = (MonoErrorInternal*)oerror;
        mono_error_prepare (error);
 
        error->error_code = MONO_ERROR_TYPE_LOAD;
        mono_error_set_class (oerror, klass);
-       set_error_message ();
+       set_error_messagev ();
 }
 
 /*
@@ -618,7 +635,7 @@ mono_error_prepare_exception (MonoError *oerror, MonoError *error_out)
                        }
 
                        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);
@@ -730,6 +747,9 @@ mono_error_convert_to_exception (MonoError *target_error)
        MonoError error;
        MonoException *ex;
 
+       /* Mempool stored error shouldn't be cleaned up */
+       g_assert (!is_boxed ((MonoErrorInternal*)target_error));
+
        if (mono_error_ok (target_error))
                return NULL;
 
@@ -752,3 +772,97 @@ mono_error_move (MonoError *dest, MonoError *src)
        memcpy (dest, src, sizeof (MonoErrorInternal));
        mono_error_init (src);
 }
+
+/**
+ * mono_error_box:
+ * @ierror: The input error that will be boxed.
+ * @image: The mempool of this image will hold the boxed error.
+ *
+ * Creates a new boxed error in the given mempool from MonoError.
+ * It does not alter ierror, so you still have to clean it up with
+ * mono_error_cleanup or mono_error_convert_to_exception or another such function.
+ *
+ * Returns the boxed error, or NULL if the mempool could not allocate.
+ */
+MonoErrorBoxed*
+mono_error_box (const MonoError *ierror, MonoImage *image)
+{
+       MonoErrorInternal *from = (MonoErrorInternal*)ierror;
+       /* Don't know how to box a gchandle */
+       g_assert (!is_managed_exception (from));
+       MonoErrorBoxed* box = mono_image_alloc (image, sizeof (MonoErrorBoxed));
+       box->image = image;
+       mono_error_init_flags (&box->error, MONO_ERROR_MEMPOOL_BOXED);
+       MonoErrorInternal *to = (MonoErrorInternal*)&box->error;
+
+#define DUP_STR(field) do {                                            \
+               if (from->field) {                                      \
+                       if (!(to->field = mono_image_strdup (image, from->field))) \
+                               to->flags |= MONO_ERROR_INCOMPLETE;     \
+               } else {                                                \
+                       to->field = NULL;                               \
+               }                                                       \
+       } while (0)
+
+       to->error_code = from->error_code;
+       DUP_STR (type_name);
+       DUP_STR (assembly_name);
+       DUP_STR (member_name);
+       DUP_STR (exception_name_space);
+       DUP_STR (exception_name);
+       DUP_STR (full_message);
+       DUP_STR (full_message_with_fields);
+       DUP_STR (first_argument);
+       to->exn.klass = from->exn.klass;
+
+#undef DUP_STR
+       
+       return box;
+}
+
+
+/**
+ * mono_error_set_from_boxed:
+ * @oerror: The error that will be set to the contents of the box.
+ * @box: A mempool-allocated error.
+ *
+ * Sets the error condition in the oerror from the contents of the
+ * given boxed error.  Does not alter the boxed error, so it can be
+ * used in a future call to mono_error_set_from_boxed as needed.  The
+ * oerror should've been previously initialized with mono_error_init,
+ * as usual.
+ *
+ * Returns TRUE on success or FALSE on failure.
+ */
+gboolean
+mono_error_set_from_boxed (MonoError *oerror, const MonoErrorBoxed *box)
+{
+       MonoErrorInternal* to = (MonoErrorInternal*)oerror;
+       MonoErrorInternal* from = (MonoErrorInternal*)&box->error;
+       g_assert (!is_managed_exception (from));
+
+       mono_error_prepare (to);
+       to->flags |= MONO_ERROR_FREE_STRINGS;
+#define DUP_STR(field) do {                                            \
+               if (from->field) {                                      \
+                       if (!(to->field = g_strdup (from->field)))      \
+                               to->flags |= MONO_ERROR_INCOMPLETE;     \
+               } else {                                                \
+                       to->field = NULL;                               \
+               }                                                       \
+       } while (0)
+
+       to->error_code = from->error_code;
+       DUP_STR (type_name);
+       DUP_STR (assembly_name);
+       DUP_STR (member_name);
+       DUP_STR (exception_name_space);
+       DUP_STR (exception_name);
+       DUP_STR (full_message);
+       DUP_STR (full_message_with_fields);
+       DUP_STR (first_argument);
+       to->exn.klass = from->exn.klass;
+                 
+#undef DUP_STR
+       return (to->flags & MONO_ERROR_INCOMPLETE) == 0 ;
+}
index 0aba0e1d61abb4219d6cfc15a9a8ead976c1ceaa..fa9caa6759e36bb2cecb619b19822f56e08520e2 100644 (file)
@@ -12,7 +12,11 @@ enum {
        /*
        Something happened while processing the error and the resulting message is incomplete.
        */
-       MONO_ERROR_INCOMPLETE = 0x0002
+       MONO_ERROR_INCOMPLETE = 0x0002,
+       /*
+       This MonoError is heap allocated in a mempool
+        */
+       MONO_ERROR_MEMPOOL_BOXED = 0x0004
 };
 
 enum {
@@ -48,6 +52,9 @@ typedef struct _MonoError {
        void *hidden_1 [12]; /*DON'T TOUCH */
 } MonoError;
 
+/* Mempool-allocated MonoError.*/
+typedef struct _MonoErrorBoxed MonoErrorBoxed;
+
 MONO_BEGIN_DECLS
 
 MONO_API void
index 54c6320d2b6f6a08bc8fc2fe249f315bbde8cac8..f423096a7800194c73af530b756e897f9b8050c9 100644 (file)
@@ -387,4 +387,11 @@ static inline gchar *mono_portability_find_file_internal (GString **report, cons
        g_free (new_pathname);
        return(NULL);
 }
+
+#else /* DISABLE_PORTABILITY */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_mono_io_portability_quiet_lnk4221(void) {}
 #endif
+#endif /* DISABLE_PORTABILITY */
diff --git a/mono/utils/mono-log-android.c b/mono/utils/mono-log-android.c
new file mode 100644 (file)
index 0000000..fde2fd0
--- /dev/null
@@ -0,0 +1,92 @@
+/*
+ * mono-log-android.c: Android-specific interface to the logger
+ *
+ * This module contains the Android logcat logger interface
+ *
+ * Author:
+ *    Marek Habersack <grendel@twistedcode.net>
+ *
+ */
+#include <config.h>
+
+#if defined (PLATFORM_ANDROID)
+
+#include <android/log.h>
+#include "mono-logger-internals.h"
+
+/**
+ * mono_log_open_logcat
+ *
+ *     Open access to Android logcat (no-op)
+ *
+ *     @path - Not used
+ *     @userData - Not used
+ */   
+void
+mono_log_open_logcat (const char *path, void *userData)
+{
+       /* No-op on Android */
+}
+
+/**
+ * mono_log_write_logcat
+ *
+ *     Write data to Android logcat.
+ *
+ *     @domain - Identifier string
+ *     @level - Logging level flags
+ *     @format - Printf format string
+ *     @vargs - Variable argument list
+ */
+void
+mono_log_write_logcat (const char *log_domain, GLogLevelFlags level, mono_bool hdr, const char *message)
+{
+       android_LogPriority apriority;
+
+       switch (level & G_LOG_LEVEL_MASK)
+       {
+               case G_LOG_LEVEL_ERROR:
+                       apriority = ANDROID_LOG_FATAL;
+                       break;
+
+               case G_LOG_LEVEL_CRITICAL:
+                       apriority = ANDROID_LOG_ERROR;
+                       break;
+
+               case G_LOG_LEVEL_WARNING:
+                       apriority = ANDROID_LOG_WARN;
+                       break;
+
+               case G_LOG_LEVEL_MESSAGE:
+                       apriority = ANDROID_LOG_INFO;
+                       break;
+
+               case G_LOG_LEVEL_INFO:
+                       apriority = ANDROID_LOG_DEBUG;
+                       break;
+
+               case G_LOG_LEVEL_DEBUG:
+                       apriority = ANDROID_LOG_VERBOSE;
+                       break;
+
+               default:
+                       apriority = ANDROID_LOG_UNKNOWN;
+                       break;
+       }
+
+       __android_log_write (apriority, log_domain, message);
+       if (apriority == ANDROID_LOG_FATAL)
+               abort ();
+}
+
+/**
+ * mono_log_close_logcat
+ *
+ *     Close access to Android logcat (no-op)
+ */
+void
+mono_log_close_logcat ()
+{
+       /* No-op on Android */
+}
+#endif
index 4948b91b80fbd84435428d56098e47d751d3b2a0..bdb6dffb50e27f1838959452b585907afa062bbf 100644 (file)
@@ -26,6 +26,7 @@
 #include <process.h>
 #endif
 #include "mono-logger-internals.h"
+#include "mono-proclib.h"
 
 static FILE *logFile = NULL;
 static void *logUserData = NULL;
@@ -119,7 +120,7 @@ mono_log_write_logfile (const char *log_domain, GLogLevelFlags level, mono_bool
                struct tm *tod;
                time(&t);
                tod = localtime(&t);
-               pid = _getpid();
+               pid = mono_process_current_pid ();
                strftime(logTime, sizeof(logTime), "%F %T", tod);
 #endif
                fprintf (logFile, "%s level[%c] mono[%d]: %s\n", logTime, mapLogFileLevel (level), pid, message);
diff --git a/mono/utils/mono-log-darwin.c b/mono/utils/mono-log-darwin.c
new file mode 100644 (file)
index 0000000..1214291
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ * mono-log-darwin.c: Darwin-specific interface to the logger
+ *
+ */
+#include <config.h>
+
+#if defined(HOST_IOS)
+
+#include <asl.h>
+#include "mono-logger-internals.h"
+static int
+to_asl_priority (GLogLevelFlags log_level)
+{
+       switch (log_level & G_LOG_LEVEL_MASK)
+       {
+               case G_LOG_LEVEL_ERROR:     return ASL_LEVEL_CRIT;
+               case G_LOG_LEVEL_CRITICAL:  return ASL_LEVEL_ERR;
+               case G_LOG_LEVEL_WARNING:   return ASL_LEVEL_WARNING;
+               case G_LOG_LEVEL_MESSAGE:   return ASL_LEVEL_NOTICE;
+               case G_LOG_LEVEL_INFO:      return ASL_LEVEL_INFO;
+               case G_LOG_LEVEL_DEBUG:     return ASL_LEVEL_DEBUG;
+       }
+       return ASL_LEVEL_ERR;
+}
+
+void
+mono_log_open_asl (const char *path, void *userData)
+{
+}
+
+void
+mono_log_write_asl (const char *log_domain, GLogLevelFlags level, mono_bool hdr, const char *message)
+{
+       asl_log (NULL, NULL, to_asl_priority (level), "%s%s%s\n",
+               log_domain != NULL ? log_domain : "",
+               log_domain != NULL ? ": " : "",
+               message);
+
+       if (level & G_LOG_LEVEL_ERROR)
+               abort();
+}
+
+void
+mono_log_close_asl ()
+{
+}
+#endif
index f6cd987fbba85c31ebda11b966b220ef3067f7ac..ab5db470e1941f75bd2e712d119f979ffa6ff602 100644 (file)
@@ -24,6 +24,7 @@
 #include <time.h>
 #include <process.h>
 #include "mono-logger-internals.h"
+#include "mono-proclib.h"
 
 static FILE *logFile = NULL;
 static void *logUserData = NULL;
@@ -88,7 +89,7 @@ void
 mono_log_write_syslog(const char *domain, GLogLevelFlags level, mono_bool hdr, const char *message)
 {
        time_t t;
-       pid_t pid;
+       int pid;
        char logTime [80];
 
        if (logFile == NULL)
@@ -97,7 +98,7 @@ mono_log_write_syslog(const char *domain, GLogLevelFlags level, mono_bool hdr, c
        struct tm *tod;
        time(&t);
        tod = localtime(&t);
-       pid = _getpid();
+       pid = mono_process_current_pid ();
        strftime(logTime, sizeof(logTime), "%F %T", tod);
 
        fprintf (logFile, "%s level[%c] mono[%d]: %s\n", logTime, mapLogFileLevel (level), pid, message);
index 57ef259677fd4b3ec81df0cadc1f70e6da914eb0..d1e2599c30dd1e489a3cf8ff2884e09241d2b62f 100644 (file)
@@ -2,6 +2,7 @@
 #define __MONO_LOGGER_INTERNAL_H__
 
 #include <glib.h>
+#include <mono/utils/mono-compiler.h>
 #include "mono-logger.h"
 
 G_BEGIN_DECLS
@@ -74,8 +75,8 @@ mono_tracev (GLogLevelFlags level, MonoTraceMask mask, const char *format, va_li
  * Traces a new message, depending on the current logging level
  * and trace mask.
  */
-G_GNUC_UNUSED static void
-mono_trace (GLogLevelFlags level, MonoTraceMask mask, const char *format, ...) 
+G_GNUC_UNUSED MONO_ATTR_FORMAT_PRINTF(3,4) static void
+mono_trace (GLogLevelFlags level, MonoTraceMask mask, const char *format, ...)
 {
        if(G_UNLIKELY (level <= mono_internal_current_level && mask & mono_internal_current_mask)) {
                va_list args;
@@ -175,6 +176,19 @@ void mono_log_open_logfile (const char *, void *);
 void mono_log_write_logfile (const char *, GLogLevelFlags, mono_bool, const char *);
 void mono_log_close_logfile (void);
 
+#if PLATFORM_ANDROID
+void mono_log_open_logcat (const char *path, void *userData);
+void mono_log_write_logcat (const char *log_domain, GLogLevelFlags level, mono_bool hdr, const char *message);
+void mono_log_close_logcat (void);
+#endif
+
+#if defined(HOST_IOS)
+void mono_log_open_asl (const char *path, void *userData);
+void mono_log_write_asl (const char *log_domain, GLogLevelFlags level, mono_bool hdr, const char *message);
+void mono_log_close_asl (void);
+
+#endif
+
 G_END_DECLS
 
 #endif /* __MONO_LOGGER_INTERNAL_H__ */
index 20457c95b677c91eedb261eace27b409229db62d..5cc59c77fbe6dd87bf56d097df56dc7380e9baf9 100644 (file)
@@ -148,19 +148,30 @@ mono_trace_set_logdest_string (const char *dest)
        if(level_stack == NULL)
                mono_trace_init();
 
+#if PLATFORM_ANDROID
+       logger.opener = mono_log_open_logcat;
+       logger.writer = mono_log_write_logcat;
+       logger.closer = mono_log_close_logcat;
+       logger.dest   = (char*) dest;
+#elif defined (HOST_IOS)
+       logger.opener = mono_log_open_asl;
+       logger.writer = mono_log_write_asl;
+       logger.closer = mono_log_close_asl;
+       logger.dest   = (char*) dest;
+#else
        if ((dest == NULL) || (strcmp("syslog", dest) != 0)) {
                logger.opener = mono_log_open_logfile;
                logger.writer = mono_log_write_logfile;
                logger.closer = mono_log_close_logfile;
                logger.dest   = (char *) dest;
-               mono_trace_set_log_handler_internal(&logger, NULL);
        } else {
                logger.opener = mono_log_open_syslog;
                logger.writer = mono_log_write_syslog;
                logger.closer = mono_log_close_syslog;
                logger.dest   = (char *) dest;
-               mono_trace_set_log_handler_internal(&logger, NULL);
        }
+#endif
+       mono_trace_set_log_handler_internal(&logger, NULL);
 }
 
 /**
@@ -280,7 +291,7 @@ mono_trace_set_mask_string (const char *value)
                        continue;
                }
                for (i = 0; valid_flags[i]; i++) {
-                       int len = strlen (valid_flags[i]);
+                       size_t len = strlen (valid_flags[i]);
                        if (strncmp (tok, valid_flags[i], len) == 0 && (tok[len] == 0 || tok[len] == ',')) {
                                flags |= valid_masks[i];
                                tok += len;
index faca70b8ca95e655d759182f8538356a5291a8e5..90695609f0875b608f7c6ad3069b970459e4e86c 100644 (file)
 
 #include "mono-compiler.h"
 
-int mono_pages_not_faulted (void *addr, size_t length);
+void *
+malloc_shared_area (int pid);
+
+char*
+aligned_address (char *mem, size_t size, size_t alignment);
+
+void
+account_mem (MonoMemAccountType type, ssize_t size);
+
+int
+mono_pages_not_faulted (void *addr, size_t length);
 
 #endif /* __MONO_UTILS_MMAP_INTERNAL_H__ */
 
diff --git a/mono/utils/mono-mmap-windows-uwp.c b/mono/utils/mono-mmap-windows-uwp.c
new file mode 100644 (file)
index 0000000..5565200
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * mono-dl-windows-uwp.c: UWP dl support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+
+#if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
+#include <Windows.h>
+#include <mono/utils/mono-mmap-windows.h>
+
+void*
+mono_file_map (size_t length, int flags, int fd, guint64 offset, void **ret_handle)
+{
+       void *ptr;
+       int mflags = 0;
+       HANDLE file, mapping;
+       int prot = mono_mmap_win_prot_from_flags (flags);
+
+       mflags = FILE_MAP_READ;
+       if (flags & MONO_MMAP_WRITE)
+               mflags = FILE_MAP_COPY;
+
+       file = (HANDLE) _get_osfhandle (fd);
+       mapping = CreateFileMappingFromApp (file, NULL, prot, length, NULL);
+
+       if (mapping == NULL)
+               return NULL;
+
+       ptr = MapViewOfFileFromApp (mapping, mflags, offset, length);
+
+       if (ptr == NULL) {
+               CloseHandle (mapping);
+               return NULL;
+       }
+
+       *ret_handle = (void*)mapping;
+       return ptr;
+}
+
+int
+mono_file_unmap (void *addr, void *handle)
+{
+       UnmapViewOfFile (addr);
+       CloseHandle ((HANDLE)handle);
+       return 0;
+}
+
+#else /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_mono_mmap_windows_uwp_quiet_lnk4221(void) {}
+#endif
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
diff --git a/mono/utils/mono-mmap-windows.c b/mono/utils/mono-mmap-windows.c
new file mode 100644 (file)
index 0000000..6fe7766
--- /dev/null
@@ -0,0 +1,204 @@
+/*
+ * mono-mmap-windows.c: Windows support for mapping code into the process address space
+ *
+ * Author:
+ *   Mono Team (mono-list@lists.ximian.com)
+ *
+ * Copyright 2001-2008 Novell, Inc.
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+ */
+
+#include <config.h>
+#include <glib.h>
+
+#if defined(HOST_WIN32)
+#include <Windows.h>
+#include "mono/utils/mono-mmap-windows.h"
+#include <mono/utils/mono-counters.h>
+#include <io.h>
+
+static void *malloced_shared_area = NULL;
+
+int
+mono_pagesize (void)
+{
+       SYSTEM_INFO info;
+       static int saved_pagesize = 0;
+       if (saved_pagesize)
+               return saved_pagesize;
+       GetSystemInfo (&info);
+       saved_pagesize = info.dwAllocationGranularity;
+       return saved_pagesize;
+}
+
+int
+mono_mmap_win_prot_from_flags (int flags)
+{
+       int prot = flags & (MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
+       switch (prot) {
+       case 0: prot = PAGE_NOACCESS; break;
+       case MONO_MMAP_READ: prot = PAGE_READONLY; break;
+       case MONO_MMAP_READ|MONO_MMAP_EXEC: prot = PAGE_EXECUTE_READ; break;
+       case MONO_MMAP_READ|MONO_MMAP_WRITE: prot = PAGE_READWRITE; break;
+       case MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC: prot = PAGE_EXECUTE_READWRITE; break;
+       case MONO_MMAP_WRITE: prot = PAGE_READWRITE; break;
+       case MONO_MMAP_WRITE|MONO_MMAP_EXEC: prot = PAGE_EXECUTE_READWRITE; break;
+       case MONO_MMAP_EXEC: prot = PAGE_EXECUTE; break;
+       default:
+               g_assert_not_reached ();
+       }
+       return prot;
+}
+
+void*
+mono_valloc (void *addr, size_t length, int flags, MonoMemAccountType type)
+{
+       void *ptr;
+       int mflags = MEM_RESERVE|MEM_COMMIT;
+       int prot = mono_mmap_win_prot_from_flags (flags);
+       /* translate the flags */
+
+       ptr = VirtualAlloc (addr, length, mflags, prot);
+
+       account_mem (type, (ssize_t)length);
+
+       return ptr;
+}
+
+void*
+mono_valloc_aligned (size_t length, size_t alignment, int flags, MonoMemAccountType type)
+{
+       int prot = mono_mmap_win_prot_from_flags (flags);
+       char *mem = VirtualAlloc (NULL, length + alignment, MEM_RESERVE, prot);
+       char *aligned;
+
+       if (!mem)
+               return NULL;
+
+       aligned = aligned_address (mem, length, alignment);
+
+       aligned = VirtualAlloc (aligned, length, MEM_COMMIT, prot);
+       g_assert (aligned);
+
+       account_mem (type, (ssize_t)length);
+
+       return aligned;
+}
+
+int
+mono_vfree (void *addr, size_t length, MonoMemAccountType type)
+{
+       MEMORY_BASIC_INFORMATION mbi;
+       SIZE_T query_result = VirtualQuery (addr, &mbi, sizeof (mbi));
+       BOOL res;
+
+       g_assert (query_result);
+
+       res = VirtualFree (mbi.AllocationBase, 0, MEM_RELEASE);
+
+       g_assert (res);
+
+       account_mem (type, -(ssize_t)length);
+
+       return 0;
+}
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+void*
+mono_file_map (size_t length, int flags, int fd, guint64 offset, void **ret_handle)
+{
+       void *ptr;
+       int mflags = 0;
+       HANDLE file, mapping;
+       int prot = mono_mmap_win_prot_from_flags (flags);
+       /* translate the flags */
+       /*if (flags & MONO_MMAP_PRIVATE)
+               mflags |= MAP_PRIVATE;
+       if (flags & MONO_MMAP_SHARED)
+               mflags |= MAP_SHARED;
+       if (flags & MONO_MMAP_ANON)
+               mflags |= MAP_ANONYMOUS;
+       if (flags & MONO_MMAP_FIXED)
+               mflags |= MAP_FIXED;
+       if (flags & MONO_MMAP_32BIT)
+               mflags |= MAP_32BIT;*/
+
+       mflags = FILE_MAP_READ;
+       if (flags & MONO_MMAP_WRITE)
+               mflags = FILE_MAP_COPY;
+
+       file = (HANDLE) _get_osfhandle (fd);
+
+       mapping = CreateFileMapping (file, NULL, prot, 0, 0, NULL);
+
+       if (mapping == NULL)
+               return NULL;
+
+       ptr = MapViewOfFile (mapping, mflags, 0, offset, length);
+
+       if (ptr == NULL) {
+               CloseHandle (mapping);
+               return NULL;
+       }
+       *ret_handle = (void*)mapping;
+       return ptr;
+}
+
+int
+mono_file_unmap (void *addr, void *handle)
+{
+       UnmapViewOfFile (addr);
+       CloseHandle ((HANDLE)handle);
+       return 0;
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+int
+mono_mprotect (void *addr, size_t length, int flags)
+{
+       DWORD oldprot;
+       int prot = mono_mmap_win_prot_from_flags (flags);
+
+       if (flags & MONO_MMAP_DISCARD) {
+               VirtualFree (addr, length, MEM_DECOMMIT);
+               VirtualAlloc (addr, length, MEM_COMMIT, prot);
+               return 0;
+       }
+       return VirtualProtect (addr, length, prot, &oldprot) == 0;
+}
+
+void*
+mono_shared_area (void)
+{
+       if (!malloced_shared_area)
+               malloced_shared_area = malloc_shared_area (0);
+       /* get the pid here */
+       return malloced_shared_area;
+}
+
+void
+mono_shared_area_remove (void)
+{
+       if (malloced_shared_area)
+               g_free (malloced_shared_area);
+       malloced_shared_area = NULL;
+}
+
+void*
+mono_shared_area_for_pid (void *pid)
+{
+       return NULL;
+}
+
+void
+mono_shared_area_unload (void *area)
+{
+}
+
+int
+mono_shared_area_instances (void **array, int count)
+{
+       return 0;
+}
+
+#endif
diff --git a/mono/utils/mono-mmap-windows.h b/mono/utils/mono-mmap-windows.h
new file mode 100644 (file)
index 0000000..44da254
--- /dev/null
@@ -0,0 +1,15 @@
+#ifndef __MONO_UTILS_MMAP_WINDOWS_H__
+#define __MONO_UTILS_MMAP_WINDOWS_H__
+
+#include <config.h>
+#include <glib.h>
+
+#ifdef HOST_WIN32
+#include "mono/utils/mono-mmap.h"
+#include "mono/utils/mono-mmap-internals.h"
+
+int
+mono_mmap_win_prot_from_flags (int flags);
+#endif /* HOST_WIN32 */
+#endif /* __MONO_UTILS_MMAP_WINDOWS_H__ */
+
index 491318465faf804a0767d46b45b838d8020814b5..91fe5a12def4517d7c1d364df7117cef53aa988f 100644 (file)
@@ -8,12 +8,9 @@
  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
  */
 
-#include "config.h"
+#include <config.h>
 
-#ifdef HOST_WIN32
-#include <windows.h>
-#include <io.h>
-#else
+#ifndef HOST_WIN32
 #include <sys/types.h>
 #if HAVE_SYS_STAT_H
 #include <sys/stat.h>
@@ -29,7 +26,7 @@
 #include <unistd.h>
 #include <stdlib.h>
 #include <errno.h>
-#endif
+#endif /* !HOST_WIN32 */
 
 #include "mono-mmap.h"
 #include "mono-mmap-internals.h"
@@ -38,7 +35,6 @@
 #include <mono/utils/atomic.h>
 #include <mono/utils/mono-counters.h>
 
-
 #define BEGIN_CRITICAL_SECTION do { \
        MonoThreadInfo *__info = mono_thread_info_current_unchecked (); \
        if (__info) __info->inside_critical_region = TRUE;      \
@@ -63,9 +59,7 @@ typedef struct {
        short stats_end;
 } SAreaHeader;
 
-static void* malloced_shared_area = NULL;
-
-static void*
+void*
 malloc_shared_area (int pid)
 {
        int size = mono_pagesize ();
@@ -78,7 +72,7 @@ malloc_shared_area (int pid)
        return sarea;
 }
 
-static char*
+char*
 aligned_address (char *mem, size_t size, size_t alignment)
 {
        char *aligned = (char*)((size_t)(mem + (alignment - 1)) & ~(alignment - 1));
@@ -88,7 +82,7 @@ aligned_address (char *mem, size_t size, size_t alignment)
 
 static volatile size_t allocation_count [MONO_MEM_ACCOUNT_MAX];
 
-static void
+void
 account_mem (MonoMemAccountType type, ssize_t size)
 {
 #if SIZEOF_VOID_P == 4
@@ -135,186 +129,12 @@ mono_mem_account_register_counters (void)
 }
 
 #ifdef HOST_WIN32
-
-int
-mono_pagesize (void)
-{
-       SYSTEM_INFO info;
-       static int saved_pagesize = 0;
-       if (saved_pagesize)
-               return saved_pagesize;
-       GetSystemInfo (&info);
-       saved_pagesize = info.dwAllocationGranularity;
-       return saved_pagesize;
-}
-
-static int
-prot_from_flags (int flags)
-{
-       int prot = flags & (MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
-       switch (prot) {
-       case 0: prot = PAGE_NOACCESS; break;
-       case MONO_MMAP_READ: prot = PAGE_READONLY; break;
-       case MONO_MMAP_READ|MONO_MMAP_EXEC: prot = PAGE_EXECUTE_READ; break;
-       case MONO_MMAP_READ|MONO_MMAP_WRITE: prot = PAGE_READWRITE; break;
-       case MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC: prot = PAGE_EXECUTE_READWRITE; break;
-       case MONO_MMAP_WRITE: prot = PAGE_READWRITE; break;
-       case MONO_MMAP_WRITE|MONO_MMAP_EXEC: prot = PAGE_EXECUTE_READWRITE; break;
-       case MONO_MMAP_EXEC: prot = PAGE_EXECUTE; break;
-       default:
-               g_assert_not_reached ();
-       }
-       return prot;
-}
-
-void*
-mono_valloc (void *addr, size_t length, int flags, MonoMemAccountType type)
-{
-       void *ptr;
-       int mflags = MEM_RESERVE|MEM_COMMIT;
-       int prot = prot_from_flags (flags);
-       /* translate the flags */
-
-       ptr = VirtualAlloc (addr, length, mflags, prot);
-
-       account_mem (type, (ssize_t)length);
-
-       return ptr;
-}
-
-void*
-mono_valloc_aligned (size_t length, size_t alignment, int flags, MonoMemAccountType type)
-{
-       int prot = prot_from_flags (flags);
-       char *mem = VirtualAlloc (NULL, length + alignment, MEM_RESERVE, prot);
-       char *aligned;
-
-       if (!mem)
-               return NULL;
-
-       aligned = aligned_address (mem, length, alignment);
-
-       aligned = VirtualAlloc (aligned, length, MEM_COMMIT, prot);
-       g_assert (aligned);
-
-       account_mem (type, (ssize_t)length);
-
-       return aligned;
-}
-
+// Windows specific implementation in mono-mmap-windows.c
 #define HAVE_VALLOC_ALIGNED
 
-int
-mono_vfree (void *addr, size_t length, MonoMemAccountType type)
-{
-       MEMORY_BASIC_INFORMATION mbi;
-       SIZE_T query_result = VirtualQuery (addr, &mbi, sizeof (mbi));
-       BOOL res;
-
-       g_assert (query_result);
-
-       res = VirtualFree (mbi.AllocationBase, 0, MEM_RELEASE);
-
-       g_assert (res);
-
-       account_mem (type, -(ssize_t)length);
-
-       return 0;
-}
-
-void*
-mono_file_map (size_t length, int flags, int fd, guint64 offset, void **ret_handle)
-{
-       void *ptr;
-       int mflags = 0;
-       HANDLE file, mapping;
-       int prot = prot_from_flags (flags);
-       /* translate the flags */
-       /*if (flags & MONO_MMAP_PRIVATE)
-               mflags |= MAP_PRIVATE;
-       if (flags & MONO_MMAP_SHARED)
-               mflags |= MAP_SHARED;
-       if (flags & MONO_MMAP_ANON)
-               mflags |= MAP_ANONYMOUS;
-       if (flags & MONO_MMAP_FIXED)
-               mflags |= MAP_FIXED;
-       if (flags & MONO_MMAP_32BIT)
-               mflags |= MAP_32BIT;*/
-
-       mflags = FILE_MAP_READ;
-       if (flags & MONO_MMAP_WRITE)
-               mflags = FILE_MAP_COPY;
-
-       file = (HANDLE) _get_osfhandle (fd);
-       mapping = CreateFileMapping (file, NULL, prot, 0, 0, NULL);
-       if (mapping == NULL)
-               return NULL;
-       ptr = MapViewOfFile (mapping, mflags, 0, offset, length);
-       if (ptr == NULL) {
-               CloseHandle (mapping);
-               return NULL;
-       }
-       *ret_handle = (void*)mapping;
-       return ptr;
-}
-
-int
-mono_file_unmap (void *addr, void *handle)
-{
-       UnmapViewOfFile (addr);
-       CloseHandle ((HANDLE)handle);
-       return 0;
-}
-
-int
-mono_mprotect (void *addr, size_t length, int flags)
-{
-       DWORD oldprot;
-       int prot = prot_from_flags (flags);
-
-       if (flags & MONO_MMAP_DISCARD) {
-               VirtualFree (addr, length, MEM_DECOMMIT);
-               VirtualAlloc (addr, length, MEM_COMMIT, prot);
-               return 0;
-       }
-       return VirtualProtect (addr, length, prot, &oldprot) == 0;
-}
-
-void*
-mono_shared_area (void)
-{
-       if (!malloced_shared_area)
-               malloced_shared_area = malloc_shared_area (0);
-       /* get the pid here */
-       return malloced_shared_area;
-}
-
-void
-mono_shared_area_remove (void)
-{
-       if (malloced_shared_area)
-               g_free (malloced_shared_area);
-       malloced_shared_area = NULL;
-}
-
-void*
-mono_shared_area_for_pid (void *pid)
-{
-       return NULL;
-}
-
-void
-mono_shared_area_unload (void *area)
-{
-}
-
-int
-mono_shared_area_instances (void **array, int count)
-{
-       return 0;
-}
-
 #else
+
+static void* malloced_shared_area = NULL;
 #if defined(HAVE_MMAP)
 
 /**
index 9f59ce1ea821df2fa3dd849edd89d8e3a8b8aee7..c4bfe620f98edd116b07884e10c0f9b5ecae0922 100644 (file)
@@ -291,7 +291,12 @@ typedef HANDLE MonoSemType;
 static inline void
 mono_os_sem_init (MonoSemType *sem, int value)
 {
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
        *sem = CreateSemaphore (NULL, value, 0x7FFFFFFF, NULL);
+#else
+       *sem = CreateSemaphoreEx (NULL, value, 0x7FFFFFFF, NULL, 0, SEMAPHORE_ALL_ACCESS);
+#endif
+
        if (G_UNLIKELY (*sem == NULL))
                g_error ("%s: CreateSemaphore failed with error %d", __func__, GetLastError ());
 }
diff --git a/mono/utils/mono-proclib-windows-uwp.c b/mono/utils/mono-proclib-windows-uwp.c
new file mode 100644 (file)
index 0000000..e278ecc
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * mono-proclib-windows-uwp.c: UWP proclib support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+
+#if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
+#include <Windows.h>
+#include <mono/utils/mono-proclib.h>
+
+gint32
+mono_cpu_usage (MonoCpuUsageState *prev)
+{
+       gint32 cpu_usage = 0;
+       gint64 cpu_total_time;
+       gint64 cpu_busy_time;
+       guint64 idle_time;
+       guint64 kernel_time;
+       guint64 user_time;
+       guint64 current_time;
+       guint64 creation_time;
+       guint64 exit_time;
+
+       GetSystemTimeAsFileTime ((FILETIME*)&current_time);
+       if (!GetProcessTimes (GetCurrentProcess (), (FILETIME*)&creation_time, (FILETIME*)&exit_time, (FILETIME*)&kernel_time, (FILETIME*)&user_time)) {
+               g_error ("GetProcessTimes() failed, error code is %d\n", GetLastError ());
+               return -1;
+       }
+
+       // GetProcessTimes user_time is a sum of user time spend by all threads in the process.
+       // This means that the total user time can be more than real time. In order to adjust for this
+       // the total available time that we can be scheduled depends on the number of available cores.
+       // For example, having 2 threads running 100% on a 2 core system for 100 ms will return a user_time of 200ms
+       // but the current_time - creation_time will only be 100ms but by adjusting the available time based on number of
+       // of availalbe cores will gives use the total load of the process.
+       guint64 total_available_time = (current_time - creation_time) * mono_cpu_count ();
+
+       idle_time = total_available_time - (kernel_time + user_time);
+
+       cpu_total_time = (gint64)((idle_time - (prev ? prev->idle_time : 0)) + (user_time - (prev ? prev->user_time : 0)) + (kernel_time - (prev ? prev->kernel_time : 0)));
+       cpu_busy_time = (gint64)(cpu_total_time - (idle_time - (prev ? prev->idle_time : 0)));
+
+       if (prev) {
+               prev->idle_time = idle_time;
+               prev->kernel_time = kernel_time;
+               prev->user_time = user_time;
+       }
+
+       if (cpu_total_time > 0 && cpu_busy_time > 0)
+               cpu_usage = (gint32)(cpu_busy_time * 100 / cpu_total_time);
+
+       return cpu_usage;
+}
+
+#else /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_mono_proclib_windows_uwp_quiet_lnk4221(void) {}
+#endif
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
diff --git a/mono/utils/mono-proclib-windows.c b/mono/utils/mono-proclib-windows.c
new file mode 100644 (file)
index 0000000..6386a51
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * mono-proclib-windows.c: Windows proclib support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+
+#include <config.h>
+#include <glib.h>
+
+#ifdef HOST_WIN32
+#include <windows.h>
+#include "mono/utils/mono-proclib.h"
+
+int
+mono_process_current_pid ()
+{
+       return (int) GetCurrentProcessId ();
+}
+
+/**
+ * mono_cpu_count:
+ *
+ * Return the number of processors on the system.
+ */
+int
+mono_cpu_count (void)
+{
+       SYSTEM_INFO info;
+       GetSystemInfo (&info);
+       return info.dwNumberOfProcessors;
+}
+
+/*
+ * This function returns the cpu usage in percentage,
+ * normalized on the number of cores.
+ *
+ * Warning : the percentage returned can be > 100%. This
+ * might happens on systems like Android which, for
+ * battery and performance reasons, shut down cores and
+ * lie about the number of active cores.
+ */
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+gint32
+mono_cpu_usage (MonoCpuUsageState *prev)
+{
+       gint32 cpu_usage = 0;
+       gint64 cpu_total_time;
+       gint64 cpu_busy_time;
+       guint64 idle_time;
+       guint64 kernel_time;
+       guint64 user_time;
+
+       if (!GetSystemTimes ((FILETIME*) &idle_time, (FILETIME*) &kernel_time, (FILETIME*) &user_time)) {
+               g_error ("GetSystemTimes() failed, error code is %d\n", GetLastError ());
+               return -1;
+       }
+
+       cpu_total_time = (gint64)((user_time - (prev ? prev->user_time : 0)) + (kernel_time - (prev ? prev->kernel_time : 0)));
+       cpu_busy_time = (gint64)(cpu_total_time - (idle_time - (prev ? prev->idle_time : 0)));
+
+       if (prev) {
+               prev->idle_time = idle_time;
+               prev->kernel_time = kernel_time;
+               prev->user_time = user_time;
+       }
+
+       if (cpu_total_time > 0 && cpu_busy_time > 0)
+               cpu_usage = (gint32)(cpu_busy_time * 100 / cpu_total_time);
+
+       return cpu_usage;
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+#endif /* HOST_WIN32*/
diff --git a/mono/utils/mono-proclib-windows.h b/mono/utils/mono-proclib-windows.h
new file mode 100644 (file)
index 0000000..f14c7a4
--- /dev/null
@@ -0,0 +1,13 @@
+#ifndef __MONO_UTILS_PROCLIB_WINDOWS_H__
+#define __MONO_UTILS_PROCLIB_WINDOWS_H__
+
+#include <config.h>
+#include <glib.h>
+
+#ifdef HOST_WIN32
+#include <process.h>
+#include "mono/utils/mono-proclib.h"
+
+#endif /* HOST_WIN32 */
+#endif /* __MONO_UTILS_PROCLIB_WINDOWS_H__ */
+
index 79da32b45118f4e6f992207c723ce14f880477c0..9c37ccf2ec11874e121c4a394e980461c8a3c9f3 100644 (file)
 #include <sched.h>
 #endif
 
-#ifdef HOST_WIN32
-#include <windows.h>
-#include <process.h>
-#endif
-
 #if defined(_POSIX_VERSION)
 #include <sys/errno.h>
 #include <sys/param.h>
@@ -187,7 +182,7 @@ get_pid_status_item_buf (int pid, const char *item, char *rbuf, int blen, MonoPr
        char buf [256];
        char *s;
        FILE *f;
-       int len = strlen (item);
+       size_t len = strlen (item);
 
        g_snprintf (buf, sizeof (buf), "/proc/%d/status", pid);
        f = fopen (buf, "r");
@@ -286,7 +281,7 @@ mono_process_get_name (gpointer pid, char *buf, int len)
        char fname [128];
        FILE *file;
        char *p;
-       int r;
+       size_t r;
        sprintf (fname, "/proc/%d/cmdline", GPOINTER_TO_INT (pid));
        buf [0] = 0;
        file = fopen (fname, "r");
@@ -443,7 +438,8 @@ get_process_stat_item (int pid, int pos, int sum, MonoProcessError *error)
        char buf [512];
        char *s, *end;
        FILE *f;
-       int len, i;
+       size_t len;
+       int i;
        gint64 value;
 
        g_snprintf (buf, sizeof (buf), "/proc/%d/stat", pid);
@@ -637,31 +633,27 @@ mono_process_get_data (gpointer pid, MonoProcessData data)
        return mono_process_get_data_with_error (pid, data, &error);
 }
 
+#ifndef HOST_WIN32
 int
 mono_process_current_pid ()
 {
 #if defined(HAVE_UNISTD_H)
        return (int) getpid ();
-#elif defined(HOST_WIN32)
-       return (int) GetCurrentProcessId ();
 #else
 #error getpid
 #endif
 }
+#endif /* !HOST_WIN32 */
 
 /**
  * mono_cpu_count:
  *
  * Return the number of processors on the system.
  */
+#ifndef HOST_WIN32
 int
 mono_cpu_count (void)
 {
-#ifdef HOST_WIN32
-       SYSTEM_INFO info;
-       GetSystemInfo (&info);
-       return info.dwNumberOfProcessors;
-#else
 #ifdef PLATFORM_ANDROID
        /* Android tries really hard to save power by powering off CPUs on SMP phones which
         * means the normal way to query cpu count returns a wrong value with userspace API.
@@ -779,10 +771,10 @@ mono_cpu_count (void)
                        return count;
        }
 #endif
-#endif /* HOST_WIN32 */
        /* FIXME: warn */
        return 1;
 }
+#endif /* !HOST_WIN32 */
 
 static void
 get_cpu_times (int cpu_id, gint64 *user, gint64 *systemt, gint64 *irq, gint64 *sirq, gint64 *idle)
@@ -889,14 +881,13 @@ mono_atexit (void (*func)(void))
  * battery and performance reasons, shut down cores and
  * lie about the number of active cores.
  */
+#ifndef HOST_WIN32
 gint32
 mono_cpu_usage (MonoCpuUsageState *prev)
 {
        gint32 cpu_usage = 0;
        gint64 cpu_total_time;
        gint64 cpu_busy_time;
-
-#ifndef HOST_WIN32
        struct rusage resource_usage;
        gint64 current_time;
        gint64 kernel_time;
@@ -919,28 +910,10 @@ mono_cpu_usage (MonoCpuUsageState *prev)
                prev->user_time = user_time;
                prev->current_time = current_time;
        }
-#else
-       guint64 idle_time;
-       guint64 kernel_time;
-       guint64 user_time;
-
-       if (!GetSystemTimes ((FILETIME*) &idle_time, (FILETIME*) &kernel_time, (FILETIME*) &user_time)) {
-               g_error ("GetSystemTimes() failed, error code is %d\n", GetLastError ());
-               return -1;
-       }
-
-       cpu_total_time = (gint64)((user_time - (prev ? prev->user_time : 0)) + (kernel_time - (prev ? prev->kernel_time : 0)));
-       cpu_busy_time = (gint64)(cpu_total_time - (idle_time - (prev ? prev->idle_time : 0)));
-
-       if (prev) {
-               prev->idle_time = idle_time;
-               prev->kernel_time = kernel_time;
-               prev->user_time = user_time;
-       }
-#endif
 
        if (cpu_total_time > 0 && cpu_busy_time > 0)
                cpu_usage = (gint32)(cpu_busy_time * 100 / cpu_total_time);
 
        return cpu_usage;
 }
+#endif /* !HOST_WIN32 */
index 89d4fb68b7590a565057dd42d4ca1844ac571340..e2614388ce96038ff74ab94e56bea381c128ee23 100644 (file)
@@ -116,6 +116,15 @@ mono_set_allocator_vtable (MonoAllocatorVTable* vtable);
 #define MONO_RT_EXTERNAL_ONLY
 #endif /* MONO_INSIDE_RUNTIME */
 
+#ifdef __GNUC__
+#define _MONO_DEPRECATED __attribute__ ((deprecated))
+#elif defined (_MSC_VER)
+#define _MONO_DEPRECATED __declspec (deprecated)
+#else
+#define _MONO_DEPRECATED
+#endif
+
+#define MONO_DEPRECATED MONO_API MONO_RT_EXTERNAL_ONLY _MONO_DEPRECATED
 
 MONO_END_DECLS
 
diff --git a/mono/utils/mono-rand-windows-uwp.c b/mono/utils/mono-rand-windows-uwp.c
new file mode 100644 (file)
index 0000000..e9030fe
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+ * mono-rand-windows-uwp.c: UWP rand support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+
+#if G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT)
+#include <Windows.h>
+#include "mono/utils/mono-rand-windows.h"
+
+MONO_WIN32_CRYPT_PROVIDER_HANDLE
+mono_rand_win_open_provider (void)
+{
+       MONO_WIN32_CRYPT_PROVIDER_HANDLE provider = 0;
+
+       if (!BCRYPT_SUCCESS (BCryptOpenAlgorithmProvider (&provider, BCRYPT_RNG_ALGORITHM, NULL, 0)))
+               provider = 0;
+
+       return provider;
+}
+
+gboolean
+mono_rand_win_gen (MONO_WIN32_CRYPT_PROVIDER_HANDLE provider, guchar *buffer, size_t buffer_size)
+{
+       g_assert (provider != 0 && buffer != 0);
+       return (BCRYPT_SUCCESS (BCryptGenRandom (provider, buffer, (ULONG) buffer_size, 0))) ? TRUE : FALSE;
+}
+
+gboolean
+mono_rand_win_seed (MONO_WIN32_CRYPT_PROVIDER_HANDLE provider, guchar *seed, size_t seed_size)
+{
+       g_assert (provider != 0 && seed != 0);
+       return (BCRYPT_SUCCESS (BCryptGenRandom (provider, seed, (ULONG) seed_size, BCRYPT_RNG_USE_ENTROPY_IN_BUFFER))) ? TRUE : FALSE;
+}
+
+void
+mono_rand_win_close_provider (MONO_WIN32_CRYPT_PROVIDER_HANDLE provider)
+{
+       g_assert (provider != 0);
+       BCryptCloseAlgorithmProvider (provider, 0);
+}
+
+#else /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_mono_rand_windows_uwp_quiet_lnk4221(void) {}
+#endif
+#endif /* G_HAVE_API_SUPPORT(HAVE_UWP_WINAPI_SUPPORT) */
diff --git a/mono/utils/mono-rand-windows.c b/mono/utils/mono-rand-windows.c
new file mode 100644 (file)
index 0000000..2ff32a9
--- /dev/null
@@ -0,0 +1,172 @@
+/*
+ * mono-rand-windows.c: Windows rand support for Mono.
+ *
+ * Copyright 2016 Microsoft
+ * Licensed under the MIT license. See LICENSE file in the project root for full license information.
+*/
+#include <config.h>
+#include <glib.h>
+#include "mono-error.h"
+#include "mono-error-internals.h"
+#include "mono-rand.h"
+
+#if defined(HOST_WIN32)
+#include <windows.h>
+#include "mono/utils/mono-rand-windows.h"
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+#ifndef PROV_INTEL_SEC
+#define PROV_INTEL_SEC         22
+#endif
+#ifndef CRYPT_VERIFY_CONTEXT
+#define CRYPT_VERIFY_CONTEXT   0xF0000000
+#endif
+
+MONO_WIN32_CRYPT_PROVIDER_HANDLE
+mono_rand_win_open_provider (void)
+{
+       MONO_WIN32_CRYPT_PROVIDER_HANDLE provider = 0;
+
+       /* There is no need to create a container for just random data,
+        * so we can use CRYPT_VERIFY_CONTEXT (one call) see:
+        * http://blogs.msdn.com/dangriff/archive/2003/11/19/51709.aspx */
+
+       /* We first try to use the Intel PIII RNG if drivers are present */
+       if (!CryptAcquireContext (&provider, NULL, NULL, PROV_INTEL_SEC, CRYPT_VERIFY_CONTEXT)) {
+               /* not a PIII or no drivers available, use default RSA CSP */
+               if (!CryptAcquireContext (&provider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFY_CONTEXT)) {
+                       /* exception will be thrown in managed code */
+                       provider = 0;
+               }
+       }
+
+       return provider;
+}
+
+void
+mono_rand_win_close_provider (MONO_WIN32_CRYPT_PROVIDER_HANDLE provider)
+{
+       CryptReleaseContext (provider, 0);
+}
+
+gboolean
+mono_rand_win_gen (MONO_WIN32_CRYPT_PROVIDER_HANDLE provider, guchar *buffer, size_t buffer_size)
+{
+       return CryptGenRandom (provider, (DWORD) buffer_size, buffer);
+}
+
+gboolean
+mono_rand_win_seed (MONO_WIN32_CRYPT_PROVIDER_HANDLE provider, guchar *seed, size_t seed_size)
+{
+       /* add seeding material to the RNG */
+       return CryptGenRandom (provider, (DWORD) seed_size, seed);
+}
+#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
+
+/**
+ * mono_rand_open:
+ *
+ * Returns: True if random source is global, false if mono_rand_init can be called repeatedly to get randomness instances.
+ *
+ * Initializes entire RNG system. Must be called once per process before calling mono_rand_init.
+ */
+gboolean
+mono_rand_open (void)
+{
+       return FALSE;
+}
+
+/**
+ * mono_rand_init:
+ * @seed: A string containing seed data
+ * @seed_size: Length of seed string
+ *
+ * Returns: On success, a non-NULL handle which can be used to fetch random data from mono_rand_try_get_bytes. On failure, NULL.
+ *
+ * Initializes an RNG client.
+ */
+gpointer
+mono_rand_init (guchar *seed, gint seed_size)
+{
+       MONO_WIN32_CRYPT_PROVIDER_HANDLE provider = 0;
+
+       /* try to open crypto provider. */
+       provider = mono_rand_win_open_provider ();
+
+       /* seed the CSP with the supplied buffer (if present) */
+       if (provider != 0 && seed != NULL) {
+               /* the call we replace the seed with random - this isn't what is
+                * expected from the class library user */
+               guchar *data = g_malloc (seed_size);
+               if (data != NULL) {
+                       memcpy (data, seed, seed_size);
+                       /* add seeding material to the RNG */
+                       mono_rand_win_seed (provider, data, seed_size);
+                       /* zeroize and free */
+                       memset (data, 0, seed_size);
+                       g_free (data);
+               }
+       }
+
+       return (gpointer) provider;
+}
+
+/**
+ * mono_rand_try_get_bytes:
+ * @handle: A pointer to an RNG handle. Handle is set to NULL on failure.
+ * @buffer: A buffer into which to write random data.
+ * @buffer_size: Number of bytes to write into buffer.
+ * @error: Set on error.
+ *
+ * Returns: FALSE on failure and sets @error, TRUE on success.
+ *
+ * Extracts bytes from an RNG handle.
+ */
+gboolean
+mono_rand_try_get_bytes (gpointer *handle, guchar *buffer, gint buffer_size, MonoError *error)
+{
+       MONO_WIN32_CRYPT_PROVIDER_HANDLE provider;
+
+       mono_error_init (error);
+
+       g_assert (handle);
+       provider = (MONO_WIN32_CRYPT_PROVIDER_HANDLE) *handle;
+
+       /* generate random bytes */
+       if (!mono_rand_win_gen (provider, buffer, buffer_size)) {
+               mono_rand_win_close_provider (provider);
+               /* we may have lost our context with CryptoAPI, but all hope isn't lost yet! */
+               provider = mono_rand_win_open_provider ();
+               if (provider != 0) {
+
+                       /* retry generate of random bytes */
+                       if (!mono_rand_win_gen (provider, buffer, buffer_size)) {
+                               /* failure, close provider */
+                               mono_rand_win_close_provider (provider);
+                               provider = 0;
+                       }
+               }
+
+               /* make sure client gets new opened provider handle or NULL on failure */
+               *handle = (gpointer) provider;
+               if (*handle == 0) {
+                       /* exception will be thrown in managed code */
+                       mono_error_set_execution_engine (error, "Failed to gen random bytes (%d)", GetLastError ());
+                       return FALSE;
+               }
+       }
+       return TRUE;
+}
+
+/**
+ * mono_rand_close:
+ * @handle: An RNG handle.
+ *
+ * Releases an RNG handle.
+ */
+void
+mono_rand_close (gpointer handle)
+{
+       mono_rand_win_close_provider ((MONO_WIN32_CRYPT_PROVIDER_HANDLE) handle);
+}
+#endif /* HOST_WIN32 */
diff --git a/mono/utils/mono-rand-windows.h b/mono/utils/mono-rand-windows.h
new file mode 100644 (file)
index 0000000..f60c121
--- /dev/null
@@ -0,0 +1,33 @@
+#ifndef _MONO_UTILS_RAND_WINDOWS_H_
+#define _MONO_UTILS_RAND_WINDOWS_H_
+
+#include <config.h>
+#include <glib.h>
+
+#ifdef HOST_WIN32
+
+#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
+#include <wincrypt.h>
+#define MONO_WIN32_CRYPT_PROVIDER_HANDLE HCRYPTPROV
+
+#else
+
+#include <bcrypt.h>
+#define MONO_WIN32_CRYPT_PROVIDER_HANDLE BCRYPT_ALG_HANDLE
+#endif
+
+MONO_WIN32_CRYPT_PROVIDER_HANDLE
+mono_rand_win_open_provider (void);
+
+gboolean
+mono_rand_win_gen (MONO_WIN32_CRYPT_PROVIDER_HANDLE provider, guchar *buffer, size_t buffer_size);
+
+gboolean
+mono_rand_win_seed (MONO_WIN32_CRYPT_PROVIDER_HANDLE provider, guchar *seed, size_t seed_size);
+
+void
+mono_rand_win_close_provider (MONO_WIN32_CRYPT_PROVIDER_HANDLE provider);
+
+#endif /* HOST_WIN32 */
+#endif /* _MONO_UTILS_RAND_WINDOWS_H_ */
+
index 0e5a85384705341e3c5233e0db110fae07201803..1ac91179382d2ffb4ee7f5e826bca141e7cc4bb5 100644 (file)
@@ -13,7 +13,6 @@
  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
  */
 
-
 #include <glib.h>
 #include <config.h>
 
 #include "metadata/object.h"
 
 #ifdef HOST_WIN32
-
-#include <windows.h>
-#include <wincrypt.h>
-
-#ifndef PROV_INTEL_SEC
-#define PROV_INTEL_SEC         22
-#endif
-#ifndef CRYPT_VERIFY_CONTEXT
-#define CRYPT_VERIFY_CONTEXT   0xF0000000
-#endif
-
-/**
- * mono_rand_open:
- *
- * Returns: True if random source is global, false if mono_rand_init can be called repeatedly to get randomness instances.
- *
- * Initializes entire RNG system. Must be called once per process before calling mono_rand_init.
- */
-gboolean
-mono_rand_open (void)
-{
-       return FALSE;
-}
-
-/**
- * mono_rand_init:
- * @seed: A string containing seed data
- * @seed_size: Length of seed string
- *
- * Returns: On success, a non-NULL handle which can be used to fetch random data from mono_rand_try_get_bytes. On failure, NULL.
- *
- * Initializes an RNG client.
- */
-gpointer
-mono_rand_init (guchar *seed, gint seed_size)
-{
-       HCRYPTPROV provider = 0;
-
-       /* There is no need to create a container for just random data,
-        * so we can use CRYPT_VERIFY_CONTEXT (one call) see: 
-        * http://blogs.msdn.com/dangriff/archive/2003/11/19/51709.aspx */
-
-       /* We first try to use the Intel PIII RNG if drivers are present */
-       if (!CryptAcquireContext (&provider, NULL, NULL, PROV_INTEL_SEC, CRYPT_VERIFY_CONTEXT)) {
-               /* not a PIII or no drivers available, use default RSA CSP */
-               if (!CryptAcquireContext (&provider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFY_CONTEXT)) {
-                       /* exception will be thrown in managed code */
-                       provider = 0;
-               }
-       }
-
-       /* seed the CSP with the supplied buffer (if present) */
-       if (provider != 0 && seed) {
-               /* the call we replace the seed with random - this isn't what is
-                * expected from the class library user */
-               guchar *data = g_malloc (seed_size);
-               if (data) {
-                       memcpy (data, seed, seed_size);
-                       /* add seeding material to the RNG */
-                       CryptGenRandom (provider, seed_size, data);
-                       /* zeroize and free */
-                       memset (data, 0, seed_size);
-                       g_free (data);
-               }
-       }
-
-       return (gpointer) provider;
-}
-
-/**
- * mono_rand_try_get_bytes:
- * @handle: A pointer to an RNG handle. Handle is set to NULL on failure.
- * @buffer: A buffer into which to write random data.
- * @buffer_size: Number of bytes to write into buffer.
- * @error: Set on error.
- *
- * Returns: FALSE on failure and sets @error, TRUE on success.
- *
- * Extracts bytes from an RNG handle.
- */
-gboolean
-mono_rand_try_get_bytes (gpointer *handle, guchar *buffer, gint buffer_size, MonoError *error)
-{
-       HCRYPTPROV provider;
-
-       mono_error_init (error);
-
-       g_assert (handle);
-       provider = (HCRYPTPROV) *handle;
-
-       if (!CryptGenRandom (provider, buffer_size, buffer)) {
-               CryptReleaseContext (provider, 0);
-               /* we may have lost our context with CryptoAPI, but all hope isn't lost yet! */
-               provider = (HCRYPTPROV) mono_rand_init (NULL, 0);
-               if (!CryptGenRandom (provider, buffer_size, buffer)) {
-                       /* exception will be thrown in managed code */
-                       CryptReleaseContext (provider, 0);
-                       *handle = 0;
-                       mono_error_set_execution_engine (error, "Failed to gen random bytes (%d)", GetLastError ());
-                       return FALSE;
-               }
-       }
-       return TRUE;
-}
-
-/**
- * mono_rand_close:
- * @handle: An RNG handle.
- * @buffer: A buffer into which to write random data.
- * @buffer_size: Number of bytes to write into buffer.
- *
- * Releases an RNG handle.
- */
-void
-mono_rand_close (gpointer handle)
-{
-       CryptReleaseContext ((HCRYPTPROV) handle, 0);
-}
-
+// Windows specific implementation in mono-rand-windows.c
 #elif defined (HAVE_SYS_UN_H) && !defined(__native_client__)
 
 #include <errno.h>
index 9bfbdc51682b2db4fa1b2f94e30a6028ae7e2764..3416fe682071f24cc15d7f0898345600b0bf0dd9 100644 (file)
@@ -70,7 +70,7 @@ coop_tls_pop (gpointer received_cookie)
 
        stack = mono_native_tls_get_value (coop_reset_count_stack_key);
        if (!stack || 0 == stack->len)
-               mono_fatal_with_history ("Received cookie %p but found no stack at all, %x\n", received_cookie);
+               mono_fatal_with_history ("Received cookie %p but found no stack at all\n", received_cookie);
 
        expected_cookie = g_array_index (stack, gpointer, stack->len - 1);
        stack->len --;
index 4b9f5d393f5e79fb7ee9dc489f7fe8b00a0e7f69..29486bac076f757f7882a401b576b661da675d82 100644 (file)
@@ -18,7 +18,6 @@
 #include <mono/utils/mono-threads-posix-signals.h>
 #include <mono/utils/mono-coop-semaphore.h>
 #include <mono/metadata/gc-internals.h>
-#include <mono/metadata/w32mutex-utils.h>
 #include <mono/utils/w32handle.h>
 
 #include <errno.h>
@@ -46,8 +45,6 @@ mono_threads_platform_register (MonoThreadInfo *info)
 {
        gpointer thread_handle;
 
-       info->owned_mutexes = g_ptr_array_new ();
-
        thread_handle = mono_w32handle_new (MONO_W32HANDLE_THREAD, NULL);
        if (thread_handle == INVALID_HANDLE_VALUE)
                g_error ("%s: failed to create handle", __func__);
@@ -57,35 +54,42 @@ mono_threads_platform_register (MonoThreadInfo *info)
 }
 
 int
-mono_threads_platform_create_thread (MonoThreadStart thread_fn, gpointer thread_data, gsize stack_size, MonoNativeThreadId *out_tid)
+mono_threads_platform_create_thread (MonoThreadStart thread_fn, gpointer thread_data, gsize* const stack_size, MonoNativeThreadId *out_tid)
 {
        pthread_attr_t attr;
        pthread_t thread;
        int policy;
        struct sched_param param;
        gint res;
+       gsize set_stack_size;
+       size_t min_size;
 
        res = pthread_attr_init (&attr);
        g_assert (!res);
 
+       if (stack_size)
+               set_stack_size = *stack_size;
+       else
+               set_stack_size = 0;
+
 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
-       if (stack_size == 0) {
+       if (set_stack_size == 0) {
 #if HAVE_VALGRIND_MEMCHECK_H
                if (RUNNING_ON_VALGRIND)
-                       stack_size = 1 << 20;
+                       set_stack_size = 1 << 20;
                else
-                       stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
+                       set_stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
 #else
-               stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
+               set_stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
 #endif
        }
 
 #ifdef PTHREAD_STACK_MIN
-       if (stack_size < PTHREAD_STACK_MIN)
-               stack_size = PTHREAD_STACK_MIN;
+       if (set_stack_size < PTHREAD_STACK_MIN)
+               set_stack_size = PTHREAD_STACK_MIN;
 #endif
 
-       res = pthread_attr_setstacksize (&attr, stack_size);
+       res = pthread_attr_setstacksize (&attr, set_stack_size);
        g_assert (!res);
 #endif /* HAVE_PTHREAD_ATTR_SETSTACKSIZE */
 
@@ -128,6 +132,14 @@ mono_threads_platform_create_thread (MonoThreadStart thread_fn, gpointer thread_
        if (res != 0)
                g_error ("%s: pthread_attr_setschedparam failed, error: \"%s\" (%d)", g_strerror (res), res);
 
+       if (stack_size) {
+               res = pthread_attr_getstacksize (&attr, &min_size);
+               if (res != 0)
+                       g_error ("%s: pthread_attr_getstacksize failed, error: \"%s\" (%d)", g_strerror (res), res);
+               else
+                       *stack_size = min_size;
+       }
+
        /* Actually start the thread */
        res = mono_gc_pthread_create (&thread, &attr, (gpointer (*)(gpointer)) thread_fn, thread_data);
        if (res)
@@ -160,7 +172,11 @@ mono_threads_platform_exit (int exit_code)
 void
 mono_threads_platform_unregister (MonoThreadInfo *info)
 {
-       mono_threads_platform_set_exited (info);
+       g_assert (info->handle);
+
+       /* The thread is no longer active, so unref it */
+       mono_w32handle_unref (info->handle);
+       info->handle = NULL;
 }
 
 int
@@ -287,73 +303,32 @@ mono_native_thread_set_name (MonoNativeThreadId tid, const char *name)
 #endif
 }
 
-void
-mono_threads_platform_set_exited (MonoThreadInfo *info)
+gboolean
+mono_native_thread_join (MonoNativeThreadId tid)
 {
-       gpointer mutex_handle;
-       int i, thr_ret;
-       pthread_t tid;
-
-       g_assert (info->handle);
-
-       if (mono_w32handle_issignalled (info->handle))
-               g_error ("%s: handle %p thread %p has already exited, it's handle is signalled", __func__, info->handle, mono_thread_info_get_tid (info));
-       if (mono_w32handle_get_type (info->handle) == MONO_W32HANDLE_UNUSED)
-               g_error ("%s: handle %p thread %p has already exited, it's handle type is 'unused'", __func__, info->handle, mono_thread_info_get_tid (info));
-
-       tid = pthread_self ();
-
-       for (i = 0; i < info->owned_mutexes->len; i++) {
-               mutex_handle = g_ptr_array_index (info->owned_mutexes, i);
-               mono_w32mutex_abandon (mutex_handle, tid);
-               mono_thread_info_disown_mutex (info, mutex_handle);
-       }
-
-       g_ptr_array_free (info->owned_mutexes, TRUE);
+       void *res;
 
-       thr_ret = mono_w32handle_lock_handle (info->handle);
-       g_assert (thr_ret == 0);
-
-       mono_w32handle_set_signal_state (info->handle, TRUE, TRUE);
-
-       thr_ret = mono_w32handle_unlock_handle (info->handle);
-       g_assert (thr_ret == 0);
-
-       /* The thread is no longer active, so unref it */
-       mono_w32handle_unref (info->handle);
-
-       info->handle = NULL;
+       return !pthread_join (tid, &res);
 }
 
 void
-mono_threads_platform_describe (MonoThreadInfo *info, GString *text)
+mono_threads_platform_set_exited (gpointer handle)
 {
-       int i;
-
-       g_string_append_printf (text, "thread handle %p state : ", info->handle);
+       int thr_ret;
 
-       mono_thread_info_describe_interrupt_token (info, text);
+       g_assert (handle);
+       if (mono_w32handle_issignalled (handle))
+               g_error ("%s: handle %p thread %p has already exited, it's handle is signalled", __func__, handle, mono_native_thread_id_get ());
+       if (mono_w32handle_get_type (handle) == MONO_W32HANDLE_UNUSED)
+               g_error ("%s: handle %p thread %p has already exited, it's handle type is 'unused'", __func__, handle, mono_native_thread_id_get ());
 
-       g_string_append_printf (text, ", owns (");
-       for (i = 0; i < info->owned_mutexes->len; i++)
-               g_string_append_printf (text, i > 0 ? ", %p" : "%p", g_ptr_array_index (info->owned_mutexes, i));
-       g_string_append_printf (text, ")");
-}
-
-void
-mono_threads_platform_own_mutex (MonoThreadInfo *info, gpointer mutex_handle)
-{
-       mono_w32handle_ref (mutex_handle);
-
-       g_ptr_array_add (info->owned_mutexes, mutex_handle);
-}
+       thr_ret = mono_w32handle_lock_handle (handle);
+       g_assert (thr_ret == 0);
 
-void
-mono_threads_platform_disown_mutex (MonoThreadInfo *info, gpointer mutex_handle)
-{
-       mono_w32handle_unref (mutex_handle);
+       mono_w32handle_set_signal_state (handle, TRUE, TRUE);
 
-       g_ptr_array_remove (info->owned_mutexes, mutex_handle);
+       thr_ret = mono_w32handle_unlock_handle (handle);
+       g_assert (thr_ret == 0);
 }
 
 static const gchar* thread_typename (void)
index 19afe3e6b8e0d4276d3abb4aa01d328a0f291407..02d25b76e1cd31061a36a1e32bb8614edc8ea433 100644 (file)
@@ -24,6 +24,7 @@ mono_threads_abort_syscall_init (void)
 static void CALLBACK
 abort_apc (ULONG_PTR param)
 {
+       THREADS_INTERRUPT_DEBUG ("%06d - abort_apc () called", GetCurrentThreadId ());
 }
 
 void
@@ -35,6 +36,7 @@ mono_threads_suspend_abort_syscall (MonoThreadInfo *info)
        handle = OpenThread (THREAD_ALL_ACCESS, FALSE, id);
        g_assert (handle);
 
+       THREADS_INTERRUPT_DEBUG ("%06d - Aborting syscall in thread %06d", GetCurrentThreadId (), id);
        QueueUserAPC ((PAPCFUNC)abort_apc, handle, (ULONG_PTR)NULL);
 
        CloseHandle (handle);
index 4761af48d0c90507c6fc9433a6b882b05afb804f..791b898005ad36573273f75ac53d5b2fcdf032eb 100644 (file)
@@ -149,12 +149,12 @@ mono_threads_platform_register (MonoThreadInfo *info)
 }
 
 int
-mono_threads_platform_create_thread (MonoThreadStart thread_fn, gpointer thread_data, gsize stack_size, MonoNativeThreadId *out_tid)
+mono_threads_platform_create_thread (MonoThreadStart thread_fn, gpointer thread_data, gsize* const stack_size, MonoNativeThreadId *out_tid)
 {
        HANDLE result;
        DWORD thread_id;
 
-       result = CreateThread (NULL, stack_size, (LPTHREAD_START_ROUTINE) thread_fn, thread_data, 0, &thread_id);
+       result = CreateThread (NULL, stack_size ? *stack_size : 0, (LPTHREAD_START_ROUTINE) thread_fn, thread_data, 0, &thread_id);
        if (!result)
                return -1;
 
@@ -165,6 +165,12 @@ mono_threads_platform_create_thread (MonoThreadStart thread_fn, gpointer thread_
        if (out_tid)
                *out_tid = thread_id;
 
+       if (stack_size) {
+               // TOOD: Use VirtualQuery to get correct value 
+               // http://stackoverflow.com/questions/2480095/thread-stack-size-on-windows-visual-c
+               *stack_size = 2 * 1024 * 1024;
+       }
+
        return 0;
 }
 
@@ -187,6 +193,21 @@ mono_native_thread_create (MonoNativeThreadId *tid, gpointer func, gpointer arg)
        return CreateThread (NULL, 0, (func), (arg), 0, (tid)) != NULL;
 }
 
+gboolean
+mono_native_thread_join (MonoNativeThreadId tid)
+{
+       HANDLE handle;
+
+       if (!(handle = OpenThread (THREAD_ALL_ACCESS, TRUE, tid)))
+               return FALSE;
+
+       DWORD res = WaitForSingleObject (handle, INFINITE);
+
+       CloseHandle (handle);
+
+       return res != WAIT_FAILED;
+}
+
 #if HAVE_DECL___READFSDWORD==0
 static MONO_ALWAYS_INLINE unsigned long long
 __readfsdword (unsigned long offset)
@@ -243,7 +264,10 @@ mono_threads_platform_exit (int exit_code)
 void
 mono_threads_platform_unregister (MonoThreadInfo *info)
 {
-       mono_threads_platform_set_exited (info);
+       g_assert (info->handle);
+
+       CloseHandle (info->handle);
+       info->handle = NULL;
 }
 
 int
@@ -309,30 +333,8 @@ mono_native_thread_set_name (MonoNativeThreadId tid, const char *name)
 }
 
 void
-mono_threads_platform_set_exited (MonoThreadInfo *info)
-{
-       g_assert (info->handle);
-       // No need to call CloseHandle() here since the InternalThread
-       // destructor will close the handle when the finalizer thread calls it
-       info->handle = NULL;
-}
-
-void
-mono_threads_platform_describe (MonoThreadInfo *info, GString *text)
-{
-       /* TODO */
-}
-
-void
-mono_threads_platform_own_mutex (MonoThreadInfo *info, gpointer mutex_handle)
-{
-       g_assert_not_reached ();
-}
-
-void
-mono_threads_platform_disown_mutex (MonoThreadInfo *info, gpointer mutex_handle)
+mono_threads_platform_set_exited (gpointer handle)
 {
-       g_assert_not_reached ();
 }
 
 void
index 2f07dbae1f1393f39fd62d5ac0a32d3eaae39864..6ead6cfc23d1ba088f9654673d7ee14b45018d64 100644 (file)
@@ -260,8 +260,6 @@ mono_threads_wait_pending_operations (void)
 
 //Thread initialization code
 
-static void mono_threads_unregister_current_thread (MonoThreadInfo *info);
-
 static inline void
 mono_hazard_pointer_clear_all (MonoThreadHazardPointers *hp, int retain)
 {
@@ -400,6 +398,8 @@ unregister_thread (void *arg)
        gpointer gc_unsafe_stackdata;
        MonoThreadInfo *info;
        int small_id;
+       gboolean result;
+       gpointer handle;
 
        info = (MonoThreadInfo *) arg;
        g_assert (info);
@@ -416,8 +416,6 @@ unregister_thread (void *arg)
 
        mono_native_tls_set_value (thread_exited_key, GUINT_TO_POINTER (1));
 
-       mono_threads_platform_unregister (info);
-
        /*
         * TLS destruction order is not reliable so small_id might be cleaned up
         * before us.
@@ -426,6 +424,10 @@ unregister_thread (void *arg)
        mono_native_tls_set_value (small_id_key, GUINT_TO_POINTER (info->small_id + 1));
 #endif
 
+       /* we need to duplicate it, as the info->handle is going
+        * to be closed when unregistering from the platform */
+       handle = mono_threads_platform_duplicate_handle (info);
+
        /*
        First perform the callback that requires no locks.
        This callback has the potential of taking other locks, so we do it before.
@@ -444,7 +446,10 @@ unregister_thread (void *arg)
        */
        if (threads_callbacks.thread_unregister)
                threads_callbacks.thread_unregister (info);
-       mono_threads_unregister_current_thread (info);
+
+       mono_threads_platform_unregister (info);
+       result = mono_thread_info_remove (info);
+       g_assert (result);
        mono_threads_transition_detach (info);
 
        mono_thread_info_suspend_unlock ();
@@ -457,6 +462,13 @@ unregister_thread (void *arg)
        mono_thread_hazardous_try_free_some ();
 
        mono_thread_small_id_free (small_id);
+
+       /* Signal the w32handle. It can be done as late as here
+        * because w32handle does not access the current MonoThreadInfo,
+        * neither does it switch state to BLOCKING. */
+       mono_threads_platform_set_exited (handle);
+
+       mono_threads_platform_close_thread_handle (handle);
 }
 
 static void
@@ -480,20 +492,6 @@ thread_exited_dtor (void *arg)
 #endif
 }
 
-/**
- * Removes the current thread from the thread list.
- * This must be called from the thread unregister callback and nowhere else.
- * The current thread must be passed as TLS might have already been cleaned up.
-*/
-static void
-mono_threads_unregister_current_thread (MonoThreadInfo *info)
-{
-       gboolean result;
-       g_assert (mono_thread_info_get_tid (info) == mono_native_thread_id_get ());
-       result = mono_thread_info_remove (info);
-       g_assert (result);
-}
-
 MonoThreadInfo*
 mono_thread_info_current_unchecked (void)
 {
@@ -1187,7 +1185,7 @@ inner_start_thread (gpointer data)
  * Returns: a windows or io-layer handle for the thread.
  */
 HANDLE
-mono_threads_create_thread (MonoThreadStart start, gpointer arg, gsize stack_size, MonoNativeThreadId *out_tid)
+mono_threads_create_thread (MonoThreadStart start, gpointer arg, gsize * const stack_size, MonoNativeThreadId *out_tid)
 {
        CreateThreadData *thread_data;
        gint res;
@@ -1652,7 +1650,9 @@ void
 mono_thread_info_set_exited (THREAD_INFO_TYPE *info)
 {
        g_assert (mono_thread_info_is_current (info));
-       mono_threads_platform_set_exited (info);
+
+       g_assert (info->handle);
+       mono_threads_platform_set_exited (info->handle);
 }
 
 gpointer
@@ -1661,21 +1661,3 @@ mono_thread_info_duplicate_handle (MonoThreadInfo *info)
        g_assert (mono_thread_info_is_current (info));
        return mono_threads_platform_duplicate_handle (info);
 }
-
-void
-mono_thread_info_describe (MonoThreadInfo *info, GString *text)
-{
-       mono_threads_platform_describe (info, text);
-}
-
-void
-mono_thread_info_own_mutex (MonoThreadInfo *info, gpointer mutex_handle)
-{
-       mono_threads_platform_own_mutex (info, mutex_handle);
-}
-
-void
-mono_thread_info_disown_mutex (MonoThreadInfo *info, gpointer mutex_handle)
-{
-       mono_threads_platform_disown_mutex (info, mutex_handle);
-}
index 493d44884ca49f564d9f9f057479bf082645848a..aebfaca9952904d246f54e863254c8054d92f97f 100644 (file)
@@ -241,11 +241,6 @@ typedef struct {
 
        /* Stack mark for targets that explicitly require one */
        gpointer stack_mark;
-
-#if defined(_POSIX_VERSION) || defined(__native_client__)
-       /* This is the data that was stored in the w32 handle */
-       GPtrArray *owned_mutexes;
-#endif
 } MonoThreadInfo;
 
 typedef struct {
@@ -448,7 +443,7 @@ gboolean
 mono_thread_info_is_live (THREAD_INFO_TYPE *info);
 
 HANDLE
-mono_threads_create_thread (MonoThreadStart start, gpointer arg, gsize stack_size, MonoNativeThreadId *out_tid);
+mono_threads_create_thread (MonoThreadStart start, gpointer arg, gsize * const stack_size, MonoNativeThreadId *out_tid);
 
 int
 mono_threads_get_max_stack_size (void);
@@ -521,16 +516,13 @@ gboolean mono_threads_suspend_needs_abort_syscall (void);
 
 void mono_threads_platform_register (THREAD_INFO_TYPE *info);
 void mono_threads_platform_unregister (THREAD_INFO_TYPE *info);
-int mono_threads_platform_create_thread (MonoThreadStart thread_fn, gpointer thread_data, gsize stack_size, MonoNativeThreadId *out_tid);
+int mono_threads_platform_create_thread (MonoThreadStart thread_fn, gpointer thread_data, gsize* const stack_size, MonoNativeThreadId *out_tid);
 void mono_threads_platform_get_stack_bounds (guint8 **staddr, size_t *stsize);
 gboolean mono_threads_platform_yield (void);
 void mono_threads_platform_exit (int exit_code);
 HANDLE mono_threads_platform_open_thread_handle (HANDLE handle, MonoNativeThreadId tid);
 void mono_threads_platform_close_thread_handle (HANDLE handle);
-void mono_threads_platform_set_exited (THREAD_INFO_TYPE *info);
-void mono_threads_platform_describe (THREAD_INFO_TYPE *info, GString *text);
-void mono_threads_platform_own_mutex (THREAD_INFO_TYPE *info, gpointer mutex_handle);
-void mono_threads_platform_disown_mutex (THREAD_INFO_TYPE *info, gpointer mutex_handle);
+void mono_threads_platform_set_exited (gpointer handle);
 gpointer mono_threads_platform_duplicate_handle (THREAD_INFO_TYPE *info);
 
 void mono_threads_coop_begin_global_suspend (void);
@@ -539,15 +531,18 @@ void mono_threads_coop_end_global_suspend (void);
 MONO_API MonoNativeThreadId
 mono_native_thread_id_get (void);
 
-gboolean
+MONO_API gboolean
 mono_native_thread_id_equals (MonoNativeThreadId id1, MonoNativeThreadId id2);
 
-gboolean
+MONO_API gboolean
 mono_native_thread_create (MonoNativeThreadId *tid, gpointer func, gpointer arg);
 
 MONO_API void
 mono_native_thread_set_name (MonoNativeThreadId tid, const char *name);
 
+MONO_API gboolean
+mono_native_thread_join (MonoNativeThreadId tid);
+
 /*Mach specific internals */
 void mono_threads_init_dead_letter (void);
 void mono_threads_install_dead_letter (void);
@@ -649,13 +644,4 @@ mono_thread_info_is_current (THREAD_INFO_TYPE *info);
 gpointer
 mono_thread_info_duplicate_handle (THREAD_INFO_TYPE *info);
 
-void
-mono_thread_info_describe (THREAD_INFO_TYPE *info, GString *text);
-
-void
-mono_thread_info_own_mutex (THREAD_INFO_TYPE *info, gpointer mutex_handle);
-
-void
-mono_thread_info_disown_mutex (THREAD_INFO_TYPE *info, gpointer mutex_handle);
-
 #endif /* __MONO_THREADS_H__ */
index c3501f25268fdc6b74b4bea84595698f1139a935..763c85b0d3757f6244eef499a30492de291cc39d 100644 (file)
@@ -53,4 +53,10 @@ inet_pton (int family, const char *address, void *inaddrp)
        return -1;
 }
 
+#else /* !HAVE_INET_PTON */
+
+#ifdef _MSC_VER
+// Quiet Visual Studio linker warning, LNK4221, in cases when this source file intentional ends up empty.
+void __mono_win32_networking_missing_lnk4221(void) {}
+#endif
 #endif /* !HAVE_INET_PTON */
index fc3d1a33f368212a5f1ed9c4272c4713a70acdeb..bd82fb5578ddf4add10e219f7bbcc8ae7e73ad35 100644 (file)
@@ -659,8 +659,11 @@ mono_w32handle_ref_core (gpointer handle, MonoW32HandleBase *handle_data)
 static gboolean
 mono_w32handle_unref_core (gpointer handle, MonoW32HandleBase *handle_data, guint minimum)
 {
+       MonoW32HandleType type;
        guint old, new;
 
+       type = handle_data->type;
+
        do {
                old = handle_data->ref;
                if (!(old >= minimum))
@@ -669,8 +672,11 @@ mono_w32handle_unref_core (gpointer handle, MonoW32HandleBase *handle_data, guin
                new = old - 1;
        } while (InterlockedCompareExchange ((gint32*) &handle_data->ref, new, old) != old);
 
+       /* handle_data might contain invalid data from now on, if
+        * another thread is unref'ing this handle at the same time */
+
        mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_W32HANDLE, "%s: unref %s handle %p, ref: %d -> %d destroy: %s",
-               __func__, mono_w32handle_ops_typename (handle_data->type), handle, old, new, new == 0 ? "true" : "false");
+               __func__, mono_w32handle_ops_typename (type), handle, old, new, new == 0 ? "true" : "false");
 
        return new == 0;
 }
@@ -1289,7 +1295,7 @@ mono_w32handle_wait_multiple (gpointer *handles, gsize nhandles, gboolean waital
        alerted = FALSE;
 
        if (nhandles > MONO_W32HANDLE_MAXIMUM_WAIT_OBJECTS) {
-               mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_W32HANDLE, "%s: too many handles: %d",
+               mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_W32HANDLE, "%s: too many handles: %zd",
                        __func__, nhandles);
 
                return MONO_W32HANDLE_WAIT_RET_FAILED;
index 5d638f1b8fb83ca27fd2e0ea78b5c61c346f91f7..775c7b8e5e3c98948f5eefbe4603b6f662985c80 100644 (file)
@@ -60,6 +60,7 @@
       <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>\r
       <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>\r
     </ClInclude>\r
+    <ClInclude Include="..\mono\mini\mini-windows.h" />\r
     <ClInclude Include="..\mono\mini\mini-x86.h">\r
       <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>\r
       <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>\r
index 35641c0e6af5d06deb99314d48f855f80a571cc8..e0a3ad1227f88d363f3e10bf3fe48b46bde5e444 100644 (file)
     <ClInclude Include="..\mono\mini\mini-amd64-gsharedvt.h">\r
       <Filter>Header Files</Filter>\r
     </ClInclude>\r
+    <ClInclude Include="..\mono\mini\mini-windows.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
   </ItemGroup>\r
   <ItemGroup>\r
     <Filter Include="Header Files">\r
index 78517bc7c3aece3e8f2b96fc3d519c791872fe43..06836b9b0f83279c80f69bfadb86467affbc24e2 100644 (file)
     <ClCompile Include="..\mono\metadata\class.c" />\r
     <ClCompile Include="..\mono\metadata\cominterop.c" />\r
     <ClCompile Include="..\mono\metadata\console-win32.c" />\r
+    <ClCompile Include="..\mono\metadata\socket-io-windows.c" />\r
+    <ClCompile Include="..\mono\metadata\file-io-windows.c" />\r
+    <ClCompile Include="..\mono\metadata\icall-windows.c" />\r
+    <ClCompile Include="..\mono\metadata\marshal-windows.c" />\r
+    <ClCompile Include="..\mono\metadata\mono-security-windows.c" />\r
+    <ClCompile Include="..\mono\metadata\process-windows.c" />\r
     <ClCompile Include="..\mono\metadata\w32mutex-win32.c" />\r
     <ClCompile Include="..\mono\metadata\w32semaphore-win32.c" />\r
     <ClCompile Include="..\mono\metadata\w32event-win32.c" />\r
     <ClInclude Include="..\mono\metadata\class.h" />\r
     <ClInclude Include="..\mono\metadata\cominterop.h" />\r
     <ClInclude Include="..\mono\metadata\console-io.h" />\r
+    <ClInclude Include="..\mono\metadata\console-win32-internals.h" />\r
+    <ClInclude Include="..\mono\metadata\coree-internals.h" />\r
     <ClInclude Include="..\mono\metadata\coree.h" />\r
     <ClInclude Include="..\mono\metadata\culture-info-tables.h" />\r
     <ClInclude Include="..\mono\metadata\culture-info.h" />\r
     <ClInclude Include="..\mono\metadata\dynamic-stream-internals.h" />\r
     <ClInclude Include="..\mono\metadata\environment.h" />\r
     <ClInclude Include="..\mono\metadata\exception.h" />\r
+    <ClInclude Include="..\mono\metadata\file-io-internals.h" />\r
+    <ClInclude Include="..\mono\metadata\file-io-windows-internals.h" />\r
     <ClInclude Include="..\mono\metadata\file-io.h" />\r
     <ClInclude Include="..\mono\metadata\filewatcher.h" />\r
     <ClInclude Include="..\mono\metadata\gc-internals.h" />\r
     <ClInclude Include="..\mono\metadata\handle.h" />\r
+    <ClInclude Include="..\mono\metadata\icall-windows-internals.h" />\r
+    <ClInclude Include="..\mono\metadata\icall-internals.h" />\r
+    <ClInclude Include="..\mono\metadata\marshal-internals.h" />\r
+    <ClInclude Include="..\mono\metadata\marshal-windows-internals.h" />\r
+    <ClInclude Include="..\mono\metadata\mono-security-windows-internals.h" />\r
     <ClInclude Include="..\mono\metadata\number-ms.h" />\r
+    <ClInclude Include="..\mono\metadata\process-internals.h" />\r
+    <ClInclude Include="..\mono\metadata\process-windows-internals.h" />\r
     <ClInclude Include="..\mono\metadata\remoting.h" />\r
     <ClInclude Include="..\mono\metadata\seq-points-data.h" />\r
     <ClInclude Include="..\mono\metadata\sgen-bridge-internals.h" />\r
     <ClInclude Include="..\mono\metadata\sgen-client-mono.h" />\r
+    <ClInclude Include="..\mono\metadata\socket-io-windows-internals.h" />\r
     <ClInclude Include="..\mono\metadata\threadpool-ms-io.h" />\r
     <ClInclude Include="..\mono\metadata\threadpool-ms.h" />\r
     <ClInclude Include="..\mono\sgen\gc-internal-agnostic.h" />\r
index ba4d25f1ba94d8e9c6028b819c66bbfb4f414532..10ea5f5b356ae49a74d1e9fa5acba34a46039444 100644 (file)
     <ClCompile Include="..\mono\metadata\sgen-os-coop.c">\r
       <Filter>Source Files\sgen</Filter>\r
     </ClCompile>\r
+    <ClCompile Include="..\mono\metadata\socket-io-windows.c">\r
+         <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\mono\metadata\file-io-windows.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\mono\metadata\icall-windows.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\mono\metadata\marshal-windows.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\mono\metadata\mono-security-windows.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\mono\metadata\process-windows.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
   </ItemGroup>\r
   <ItemGroup>\r
     <ClInclude Include="..\mono\metadata\appdomain.h">\r
     <ClInclude Include="..\mono\metadata\sre-internals.h">\r
       <Filter>Header Files</Filter>\r
     </ClInclude>\r
+    <ClInclude Include="..\mono\metadata\socket-io-windows-internals.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\mono\metadata\coree-internals.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\mono\metadata\console-win32-internals.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\mono\metadata\file-io-windows-internals.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\mono\metadata\file-io-internals.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\mono\metadata\icall-internals.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\mono\metadata\icall-windows-internals.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\mono\metadata\marshal-windows-internals.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\mono\metadata\marshal-internals.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\mono\metadata\mono-security-windows-internals.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\mono\metadata\process-windows-internals.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\mono\metadata\process-internals.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
   </ItemGroup>\r
   <ItemGroup>\r
     <Filter Include="Header Files">\r
index ca9ce67c4658365ada96d183ab9f909a5e9a2ec0..5f2d80f47a6dee4d3cf0566fa981ec9ba4216a07 100644 (file)
     <ClCompile Include="..\mono\utils\mono-log-common.c" />\r
     <ClCompile Include="..\mono\utils\mono-math.c" />\r
     <ClCompile Include="..\mono\utils\mono-md5.c" />\r
+    <ClCompile Include="..\mono\utils\mono-mmap-windows.c" />\r
     <ClCompile Include="..\mono\utils\mono-mmap.c" />\r
     <ClCompile Include="..\mono\utils\mono-networkinterfaces.c" />\r
+    <ClCompile Include="..\mono\utils\mono-proclib-windows.c" />\r
+    <ClCompile Include="..\mono\utils\mono-rand-windows.c" />\r
     <ClCompile Include="..\mono\utils\mono-rand.c" />\r
     <ClCompile Include="..\mono\utils\mono-threads-state-machine.c" />\r
     <ClCompile Include="..\mono\utils\networking.c" />\r
     <ClInclude Include="..\mono\utils\mono-counters.h" />\r
     <ClInclude Include="..\mono\utils\mono-digest.h" />\r
     <ClInclude Include="..\mono\utils\mono-dl-fallback.h" />\r
+    <ClInclude Include="..\mono\utils\mono-dl-windows.h" />\r
     <ClInclude Include="..\mono\utils\mono-dl.h" />\r
     <ClInclude Include="..\mono\utils\mono-error-internals.h" />\r
     <ClInclude Include="..\mono\utils\mono-error.h" />\r
     <ClInclude Include="..\mono\utils\mono-math.h" />\r
     <ClInclude Include="..\mono\utils\mono-membar.h" />\r
     <ClInclude Include="..\mono\utils\mono-memory-model.h" />\r
+    <ClInclude Include="..\mono\utils\mono-mmap-windows.h" />\r
     <ClInclude Include="..\mono\utils\mono-mmap.h" />\r
     <ClInclude Include="..\mono\utils\mono-networkinterfaces.h" />\r
     <ClInclude Include="..\mono\utils\mono-once.h" />\r
     <ClInclude Include="..\mono\utils\mono-os-semaphore.h" />\r
     <ClInclude Include="..\mono\utils\mono-path.h" />\r
     <ClInclude Include="..\mono\utils\mono-poll.h" />\r
+    <ClInclude Include="..\mono\utils\mono-proclib-windows.h" />\r
     <ClInclude Include="..\mono\utils\mono-proclib.h" />\r
     <ClInclude Include="..\mono\utils\mono-property-hash.h" />\r
     <ClInclude Include="..\mono\utils\mono-publib.h" />\r
+    <ClInclude Include="..\mono\utils\mono-rand-windows.h" />\r
     <ClInclude Include="..\mono\utils\mono-rand.h" />\r
     <ClInclude Include="..\mono\utils\mono-sigcontext.h" />\r
     <ClInclude Include="..\mono\utils\mono-stack-unwinding.h" />\r
   <ImportGroup Label="ExtensionTargets">\r
     <Import Project="$(VCTargetsPath)\BuildCustomizations\masm.targets" />\r
   </ImportGroup>\r
-</Project>
+</Project>
\ No newline at end of file
index dae5e304a8738c178927c709bde9b29795b02e85..f74ea0cb33c66b7a97f36ed73dd04fc2f5716d84 100644 (file)
     <ClCompile Include="..\mono\utils\mono-log-windows.c">\r
       <Filter>Source Files</Filter>\r
     </ClCompile>\r
+    <ClCompile Include="..\mono\utils\mono-rand-windows.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\mono\utils\mono-proclib-windows.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\mono\utils\mono-mmap-windows.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
   </ItemGroup>\r
   <ItemGroup>\r
     <ClInclude Include="..\mono\utils\atomic.h">\r
     <ClInclude Include="..\mono\utils\valgrind.h">\r
       <Filter>Header Files</Filter>\r
     </ClInclude>\r
+    <ClInclude Include="..\mono\utils\mono-rand-windows.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\mono\utils\mono-dl-windows.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\mono\utils\mono-mmap-windows.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\mono\utils\mono-proclib-windows.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
   </ItemGroup>\r
   <ItemGroup>\r
     <Filter Include="Header Files">\r
index 2251543e666491a794934617bde33931d99d5dfd..f5a0e9ab98ae02180157b09927d2fccd54f239a3 100644 (file)
@@ -241,6 +241,7 @@ mono_disasm_code
 mono_disasm_code_one
 mono_dl_fallback_register
 mono_dl_fallback_unregister
+mono_dl_open
 mono_dllmap_insert
 mono_domain_add_class_static_data
 mono_domain_assembly_open
@@ -495,6 +496,7 @@ mono_ldstr
 mono_ldtoken
 mono_load_remote_field
 mono_load_remote_field_new
+mono_loader_register_module
 mono_lock_free_alloc
 mono_lock_free_allocator_check_consistency
 mono_lock_free_allocator_init_allocator
index fca1c3d1d9c09cfb2b76a2fac8804126d102934a..611e4c7035cc49ff71830dfce29f6a8eabeb4c0f 100644 (file)
@@ -97,4 +97,18 @@ CloseZStream
 ReadZStream\r
 WriteZStream\r
 Flush\r
-\r
+zipWriteInFileInZip\r
+zipCloseFileInZip\r
+zipOpen2\r
+zipClose\r
+zipOpenNewFileInZip\r
+unzOpen2\r
+unzCloseCurrentFile\r
+unztell\r
+unzGoToFirstFile\r
+unzGoToNextFile\r
+unzLocateFile\r
+unzOpenCurrentFile2\r
+unzGetCurrentFileInfo\r
+unzReadCurrentFile\r
+unzClose\r
index 83304969ab20ec2f93929d747146fd03db64a965..de0276892fa51410ace9318b026d559401d2cdc4 100644 (file)
@@ -87,7 +87,6 @@
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">\r
     <ClCompile>\r
       <Optimization>Disabled</Optimization>\r
-      <AdditionalIncludeDirectories>$(MONO_DIR);$(MONO_EGLIB_SOURCE_DIR);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
       <PreprocessorDefinitions>_DEBUG;__i386__;TARGET_X86;_WIN32_WINNT=0x0600;WIN32;_WIN32;__WIN32__;_WINDOWS;WINDOWS;HOST_WIN32;TARGET_WIN32;_CRT_SECURE_NO_DEPRECATE;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
       <MinimalRebuild>true</MinimalRebuild>\r
       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>\r
@@ -96,6 +95,7 @@
       <WarningLevel>Level3</WarningLevel>\r
       <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r
       <CompileAs>CompileAsC</CompileAs>\r
+      <AdditionalIncludeDirectories>$(MONO_DIR);$(MONO_EGLIB_SOURCE_DIR);$(MONO_DIR)/support;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
     </ClCompile>\r
     <Link>\r
       <AdditionalDependencies>eglib.lib;%(AdditionalDependencies)</AdditionalDependencies>\r
     </Midl>\r
     <ClCompile>\r
       <Optimization>Disabled</Optimization>\r
-      <AdditionalIncludeDirectories>$(MONO_DIR);$(MONO_EGLIB_SOURCE_DIR);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
       <PreprocessorDefinitions>_DEBUG;__x86_64__;_WIN32_WINNT=0x0600;WIN64;_WIN64;WIN32;_WIN32;__WIN32__;_WINDOWS;WINDOWS;HOST_WIN32;TARGET_WIN32;_CRT_SECURE_NO_DEPRECATE;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
       <MinimalRebuild>true</MinimalRebuild>\r
       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>\r
       <WarningLevel>Level3</WarningLevel>\r
       <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r
       <CompileAs>CompileAsC</CompileAs>\r
+      <AdditionalIncludeDirectories>$(MONO_DIR);$(MONO_EGLIB_SOURCE_DIR);$(MONO_DIR)/support;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
     </ClCompile>\r
     <Link>\r
       <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>\r
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">\r
     <ClCompile>\r
       <Optimization>MinSpace</Optimization>\r
-      <AdditionalIncludeDirectories>$(MONO_DIR);$(MONO_EGLIB_SOURCE_DIR);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
       <PreprocessorDefinitions>NDEBUG;__i386__;TARGET_X86;i386;_WIN32_WINNT=0x0600;WIN32;_WIN32;__WIN32__;_WINDOWS;WINDOWS;HOST_WIN32;TARGET_WIN32;_CRT_SECURE_NO_DEPRECATE;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
       <PrecompiledHeader>\r
       </PrecompiledHeader>\r
       <WarningLevel>Level3</WarningLevel>\r
       <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r
       <CompileAs>CompileAsC</CompileAs>\r
+      <AdditionalIncludeDirectories>$(MONO_DIR);$(MONO_EGLIB_SOURCE_DIR);$(MONO_DIR)/support;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
     </ClCompile>\r
     <Link>\r
       <AdditionalDependencies>eglib.lib;%(AdditionalDependencies)</AdditionalDependencies>\r
     </Midl>\r
     <ClCompile>\r
       <Optimization>MinSpace</Optimization>\r
-      <AdditionalIncludeDirectories>$(MONO_DIR);$(MONO_EGLIB_SOURCE_DIR);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
       <PreprocessorDefinitions>NDEBUG;__x86_64__;_WIN32_WINNT=0x0600;WIN64;_WIN64;WIN32;_WIN32;__WIN32__;_WINDOWS;WINDOWS;HOST_WIN32;TARGET_WIN32;_CRT_SECURE_NO_DEPRECATE;HAVE_CONFIG_H;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
       <PrecompiledHeader>\r
       </PrecompiledHeader>\r
       <WarningLevel>Level3</WarningLevel>\r
       <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r
       <CompileAs>CompileAsC</CompileAs>\r
+      <AdditionalIncludeDirectories>$(MONO_DIR);$(MONO_EGLIB_SOURCE_DIR);$(MONO_DIR)/support;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
     </ClCompile>\r
     <Link>\r
       <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>\r
     <ClCompile Include="..\support\inflate.c" />\r
     <ClCompile Include="..\support\inftrees.c" />\r
     <ClCompile Include="..\support\map.c" />\r
+    <ClCompile Include="..\support\minizip\ioapi.c" />\r
+    <ClCompile Include="..\support\minizip\iowin32.c" />\r
+    <ClCompile Include="..\support\minizip\minizip.c" />\r
+    <ClCompile Include="..\support\minizip\unzip.c" />\r
+    <ClCompile Include="..\support\minizip\zip.c" />\r
     <ClCompile Include="..\support\signal.c" />\r
     <ClCompile Include="..\support\stdio.c" />\r
     <ClCompile Include="..\support\stdlib.c" />\r
     <ClInclude Include="..\support\inflate.h" />\r
     <ClInclude Include="..\support\inftrees.h" />\r
     <ClInclude Include="..\support\map.h" />\r
+    <ClInclude Include="..\support\minizip\crypt.h" />\r
+    <ClInclude Include="..\support\minizip\ioapi.h" />\r
+    <ClInclude Include="..\support\minizip\iowin32.h" />\r
+    <ClInclude Include="..\support\minizip\unzip.h" />\r
+    <ClInclude Include="..\support\minizip\zip.h" />\r
     <ClInclude Include="..\support\mph.h" />\r
     <ClInclude Include="..\support\trees.h" />\r
     <ClInclude Include="..\support\zconf.h" />\r
+    <ClInclude Include="..\support\zlib.h" />\r
     <ClInclude Include="..\support\zutil.h" />\r
   </ItemGroup>\r
   <ItemGroup>\r
index 9df33f5e0d4580e92a5ec3325a5827f1df5a95d1..1cd4d6b86659f977351c9e9a6ab4f309af855c4f 100644 (file)
     <ClCompile Include="..\support\zutil.c">\r
       <Filter>Source Files</Filter>\r
     </ClCompile>\r
+    <ClCompile Include="..\support\minizip\iowin32.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\support\minizip\minizip.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\support\minizip\unzip.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\support\minizip\zip.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\support\minizip\ioapi.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
   </ItemGroup>\r
   <ItemGroup>\r
     <ClInclude Include="..\support\crc32.h">\r
     <ClInclude Include="..\support\zutil.h">\r
       <Filter>Header Files</Filter>\r
     </ClInclude>\r
+    <ClInclude Include="..\support\minizip\crypt.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\support\minizip\unzip.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\support\minizip\iowin32.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\support\minizip\zip.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\support\zlib.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
+    <ClInclude Include="..\support\minizip\ioapi.h">\r
+      <Filter>Header Files</Filter>\r
+    </ClInclude>\r
   </ItemGroup>\r
   <ItemGroup>\r
     <Filter Include="Header Files">\r
index 1f82284e7c29e944108087ebb05d2fa117fdac27..1722591c2f397fcd574413a75dd699b8602dcec5 100644 (file)
@@ -241,6 +241,7 @@ mono_disasm_code
 mono_disasm_code_one
 mono_dl_fallback_register
 mono_dl_fallback_unregister
+mono_dl_open
 mono_dllmap_insert
 mono_domain_add_class_static_data
 mono_domain_assembly_open
@@ -497,6 +498,7 @@ mono_ldstr
 mono_ldtoken
 mono_load_remote_field
 mono_load_remote_field_new
+mono_loader_register_module
 mono_lock_free_alloc
 mono_lock_free_allocator_check_consistency
 mono_lock_free_allocator_init_allocator
index 5a6e9116bd9759204af84f6bbdaa11fd2f611fb0..36dc0ecaab784bf2821ed819726385cece236c45 100644 (file)
@@ -96,7 +96,7 @@
     <ClCompile>\r
       <Optimization>Disabled</Optimization>\r
       <AdditionalIncludeDirectories>$(MONO_DIR);$(MONO_INCLUDE_DIR);$(MONO_JIT_INCLUDE_DIR);$(MONO_EGLIB_SOURCE_DIR);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
-      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_WINDOWS;__WIN32__;HOST_WIN32;TARGET_WIN32;__i386__;TARGET_X86;GC_NOT_DLL;GC_GCJ_SUPPORT;GC_WIN32_THREADS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <PreprocessorDefinitions>WIN32;WIN32_LEAN_AND_MEAN;_DEBUG;_CONSOLE;_WINDOWS;__WIN32__;HOST_WIN32;TARGET_WIN32;__i386__;TARGET_X86;GC_NOT_DLL;GC_GCJ_SUPPORT;GC_WIN32_THREADS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
       <MinimalRebuild>true</MinimalRebuild>\r
       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>\r
       <PrecompiledHeader>\r
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">\r
     <ClCompile>\r
       <Optimization>MinSpace</Optimization>\r
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <PreprocessorDefinitions>WIN32;WIN32_LEAN_AND_MEAN;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
       <PrecompiledHeader>\r
       </PrecompiledHeader>\r
       <WarningLevel>Level3</WarningLevel>\r
     <ClCompile>\r
       <Optimization>Disabled</Optimization>\r
       <AdditionalIncludeDirectories>$(MONO_DIR);$(MONO_INCLUDE_DIR);$(MONO_JIT_INCLUDE_DIR);$(MONO_EGLIB_SOURCE_DIR);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r
-      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_WINDOWS;__WIN32__;HOST_WIN32;TARGET_WIN32;__i386__;TARGET_X86;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <PreprocessorDefinitions>WIN32;WIN32_LEAN_AND_MEAN;_DEBUG;_CONSOLE;_WINDOWS;__WIN32__;HOST_WIN32;TARGET_WIN32;__i386__;TARGET_X86;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
       <MinimalRebuild>true</MinimalRebuild>\r
       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>\r
       <PrecompiledHeader>\r
     </Midl>\r
     <ClCompile>\r
       <Optimization>MinSpace</Optimization>\r
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
+      <PreprocessorDefinitions>WIN32;WIN32_LEAN_AND_MEAN;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r
       <PrecompiledHeader>\r
       </PrecompiledHeader>\r
       <WarningLevel>Level3</WarningLevel>\r
     <ClCompile Include="..\mono\metadata\console-win32.c" />\r
     <ClCompile Include="..\mono\metadata\domain.c" />\r
     <ClCompile Include="..\mono\metadata\environment.c" />\r
+    <ClCompile Include="..\mono\metadata\file-io-windows.c" />\r
     <ClCompile Include="..\mono\metadata\file-io.c" />\r
     <ClCompile Include="..\mono\metadata\filewatcher.c" />\r
     <ClCompile Include="..\mono\metadata\gc.c" />\r
+    <ClCompile Include="..\mono\metadata\icall-windows.c" />\r
     <ClCompile Include="..\mono\metadata\icall.c" />\r
     <ClCompile Include="..\mono\metadata\image.c" />\r
     <ClCompile Include="..\mono\metadata\loader.c" />\r
     <ClCompile Include="..\mono\metadata\locales.c" />\r
+    <ClCompile Include="..\mono\metadata\marshal-windows.c" />\r
     <ClCompile Include="..\mono\metadata\marshal.c" />\r
     <ClCompile Include="..\mono\metadata\metadata.c" />\r
     <ClCompile Include="..\mono\metadata\monitor.c" />\r
     <ClCompile Include="..\mono\metadata\mono-config.c" />\r
+    <ClCompile Include="..\mono\metadata\process-windows.c" />\r
     <ClCompile Include="..\mono\utils\mono-dl.c" />\r
     <ClCompile Include="..\mono\metadata\object.c" />\r
     <ClCompile Include="..\mono\metadata\process.c" />\r
index 7658bc13f5ccac3041bad6c063a548c009266315..d05fff4fa9698c44a9e6d05351d256f696703009 100644 (file)
     <ClCompile Include="..\tools\pedump\pedump.c">\r
       <Filter>Source Files</Filter>\r
     </ClCompile>\r
+    <ClCompile Include="..\mono\metadata\process-windows.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\mono\metadata\marshal-windows.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\mono\metadata\icall-windows.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
+    <ClCompile Include="..\mono\metadata\file-io-windows.c">\r
+      <Filter>Source Files</Filter>\r
+    </ClCompile>\r
   </ItemGroup>\r
   <ItemGroup>\r
     <Filter Include="Header Files">\r
index d2424feca659f855fe33bd575d5348dc83ffd53b..e958929f8e2f12ed3059b7ed98adbd07be2ab915 100644 (file)
       <resources>System.Web.Http.WebHost.Properties.CommonWebApiResources,../../../external/aspnetwebstack/src/Common/CommonWebApiResources.resx System.Web.Http.WebHost.Properties.SRResources,../../../external/aspnetwebstack/src/System.Web.Http.WebHost/Properties/SRResources.resx</resources>
       <response>System.Web.Http.WebHost.dll.sources</response>
     </project>
-    <project dir="class/Mono.Security.Providers.NewSystemSource" library="Mono.Security.Providers.NewSystemSource-net_4_x">
-      <boot>false</boot>
-      <flags>/codepage:65001 -d:NET_4_0 -d:NET_4_5 -d:NET_4_6 -d:MONO -nowarn:1699 -nostdlib -r:./../../class/lib/net_4_x/mscorlib.dll -debug -optimize /noconfig -d:SECURITY_DEP -unsafe -nowarn:1030 -keyfile:../mono.pub -delaysign -d:MONO -d:FEATURE_PAL -d:MONO_FEATURE_NEW_TLS -d:MONO_FEATURE_NEW_SYSTEM_SOURCE -d:DISABLE_CAS_USE -d:MONO_SECURITY_ALIAS -r:./../../class/lib/net_4_x/System.dll -r:MonoSecurity=./../../class/lib/net_4_x/Mono.Security.dll</flags>
-      <output>Mono.Security.Providers.NewSystemSource.dll</output>
-      <built_sources></built_sources>
-      <library_output>./../../class/lib/net_4_x/Mono.Security.Providers.NewSystemSource.dll</library_output>
-      <fx_version>4.5</fx_version>
-      <profile>net_4_x</profile>
-      <resources></resources>
-      <response>Mono.Security.Providers.NewSystemSource.dll.sources</response>
-    </project>
-    <project dir="class/Mono.Security.Providers.NewTls" library="Mono.Security.Providers.NewTls-net_4_x">
-      <boot>false</boot>
-      <flags>/codepage:65001 -d:NET_4_0 -d:NET_4_5 -d:NET_4_6 -d:MONO -nowarn:1699 -nostdlib -r:./../../class/lib/net_4_x/mscorlib.dll -debug -optimize /noconfig -unsafe -nowarn:1030 -keyfile:../mono.pub -delaysign -r:./../../class/lib/net_4_x/System.dll -r:./../../class/lib/net_4_x/Mono.Security.dll -r:NewSystemSource=./../../class/lib/net_4_x/Mono.Security.Providers.NewSystemSource.dll</flags>
-      <output>Mono.Security.Providers.NewTls.dll</output>
-      <built_sources></built_sources>
-      <library_output>./../../class/lib/net_4_x/Mono.Security.Providers.NewTls.dll</library_output>
-      <fx_version>4.5</fx_version>
-      <profile>net_4_x</profile>
-      <resources></resources>
-      <response>Mono.Security.Providers.NewTls.dll.sources</response>
-    </project>
     <project dir="class/System.Runtime.InteropServices.RuntimeInformation" library="System.Runtime.InteropServices.RuntimeInformation-net_4_x">
       <boot>false</boot>
       <flags>/codepage:65001 -d:NET_4_0 -d:NET_4_5 -d:NET_4_6 -d:MONO -nowarn:1699 -nostdlib -r:./../../class/lib/net_4_x/mscorlib.dll -debug -optimize /noconfig -r:./../../class/lib/net_4_x/System.dll</flags>
       <resources></resources>
       <response>System.Xml.Serialization.dll.sources</response>
     </project>
-    <project dir="class/Mono.Security.Providers.DotNet" library="Mono.Security.Providers.DotNet-net_4_x">
-      <boot>false</boot>
-      <flags>/codepage:65001 -d:NET_4_0 -d:NET_4_5 -d:NET_4_6 -d:MONO -nowarn:1699 -nostdlib -r:./../../class/lib/net_4_x/mscorlib.dll -debug -optimize /noconfig -unsafe -nowarn:1030 -keyfile:../mono.pub -delaysign -r:./../../class/lib/net_4_x/System.dll -r:./../../class/lib/net_4_x/Mono.Security.dll</flags>
-      <output>Mono.Security.Providers.DotNet.dll</output>
-      <built_sources></built_sources>
-      <library_output>./../../class/lib/net_4_x/Mono.Security.Providers.DotNet.dll</library_output>
-      <fx_version>4.5</fx_version>
-      <profile>net_4_x</profile>
-      <resources></resources>
-      <response>Mono.Security.Providers.DotNet.dll.sources</response>
-    </project>
-    <project dir="class/Mono.Security.Providers.OldTls" library="Mono.Security.Providers.OldTls-net_4_x">
-      <boot>false</boot>
-      <flags>/codepage:65001 -d:NET_4_0 -d:NET_4_5 -d:NET_4_6 -d:MONO -nowarn:1699 -nostdlib -r:./../../class/lib/net_4_x/mscorlib.dll -debug -optimize /noconfig -unsafe -nowarn:1030 -keyfile:../mono.pub -delaysign -d:SECURITY_DEP -r:./../../class/lib/net_4_x/System.dll -r:./../../class/lib/net_4_x/Mono.Security.dll</flags>
-      <output>Mono.Security.Providers.OldTls.dll</output>
-      <built_sources></built_sources>
-      <library_output>./../../class/lib/net_4_x/Mono.Security.Providers.OldTls.dll</library_output>
-      <fx_version>4.5</fx_version>
-      <profile>net_4_x</profile>
-      <resources></resources>
-      <response>Mono.Security.Providers.OldTls.dll.sources</response>
-    </project>
     <project dir="class/System.DirectoryServices.Protocols" library="System.DirectoryServices.Protocols-net_4_x">
       <boot>false</boot>
       <flags>/codepage:65001 -d:NET_4_0 -d:NET_4_5 -d:NET_4_6 -d:MONO -nowarn:1699 -nostdlib -r:./../../class/lib/net_4_x/mscorlib.dll -debug -optimize /noconfig -r:./../../class/lib/net_4_x/System.dll -r:./../../class/lib/net_4_x/System.DirectoryServices.dll -r:./../../class/lib/net_4_x/System.Xml.dll</flags>
index ba17c5e4e215857005ff74c9b74f17746742998a..97642ca158a70e2e16d7b747fe3516f163d25cb0 100644 (file)
@@ -181,10 +181,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Web.Http.SelfHost-ne
 EndProject
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Web.Http.WebHost-net_4_x", "mcs/class/System.Web.Http.WebHost/System.Web.Http.WebHost-net_4_x.csproj", "{2AF7E697-07BA-439E-89BF-076AEE4AE04C}"
 EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mono.Security.Providers.NewSystemSource-net_4_x", "mcs/class/Mono.Security.Providers.NewSystemSource/Mono.Security.Providers.NewSystemSource-net_4_x.csproj", "{0BB4541F-9B1A-4CBC-BEB1-00B31B37F74E}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mono.Security.Providers.NewTls-net_4_x", "mcs/class/Mono.Security.Providers.NewTls/Mono.Security.Providers.NewTls-net_4_x.csproj", "{C8B8E524-BB3A-44E2-8C22-E3313E9F477C}"
-EndProject
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Build.Framework-net_4_x", "mcs/class/Microsoft.Build.Framework/Microsoft.Build.Framework-net_4_x.csproj", "{5E39A911-F4E6-4B4B-B8AC-111BB1DD80C6}"
 EndProject
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Build.Utilities-net_4_x", "mcs/class/Microsoft.Build.Utilities/Microsoft.Build.Utilities-net_4_x.csproj", "{8E5728E0-CEAF-431F-963E-EB1DEE15C506}"
@@ -287,10 +283,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Windows-net_4_x", "m
 EndProject
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Xml.Serialization-net_4_x", "mcs/class/System.Xml.Serialization/System.Xml.Serialization-net_4_x.csproj", "{2210873E-99FC-48A2-A261-D650BAE33A1C}"
 EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mono.Security.Providers.DotNet-net_4_x", "mcs/class/Mono.Security.Providers.DotNet/Mono.Security.Providers.DotNet-net_4_x.csproj", "{391EDD2B-85AC-4FCA-B607-AAD6C51E6799}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mono.Security.Providers.OldTls-net_4_x", "mcs/class/Mono.Security.Providers.OldTls/Mono.Security.Providers.OldTls-net_4_x.csproj", "{E485E885-59B1-4081-BC66-56AAAFD8771A}"
-EndProject
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.DirectoryServices.Protocols-net_4_x", "mcs/class/System.DirectoryServices.Protocols/System.DirectoryServices.Protocols-net_4_x.csproj", "{EF08F249-31A1-4E62-8391-ECBA5227B686}"
 EndProject
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.VisualC-net_4_x", "mcs/class/Microsoft.VisualC/Microsoft.VisualC-net_4_x.csproj", "{ACA2694D-9F07-4AE2-9171-9AB5DD1A8C18}"
@@ -1041,14 +1033,6 @@ Global
                {2AF7E697-07BA-439E-89BF-076AEE4AE04C}.Debug|Any CPU.Build.0 = Debug|Any CPU
                {2AF7E697-07BA-439E-89BF-076AEE4AE04C}.Release|Any CPU.ActiveCfg = Release|Any CPU
                {2AF7E697-07BA-439E-89BF-076AEE4AE04C}.Release|Any CPU.Build.0 = Release|Any CPU
-               {0BB4541F-9B1A-4CBC-BEB1-00B31B37F74E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
-               {0BB4541F-9B1A-4CBC-BEB1-00B31B37F74E}.Debug|Any CPU.Build.0 = Debug|Any CPU
-               {0BB4541F-9B1A-4CBC-BEB1-00B31B37F74E}.Release|Any CPU.ActiveCfg = Release|Any CPU
-               {0BB4541F-9B1A-4CBC-BEB1-00B31B37F74E}.Release|Any CPU.Build.0 = Release|Any CPU
-               {C8B8E524-BB3A-44E2-8C22-E3313E9F477C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
-               {C8B8E524-BB3A-44E2-8C22-E3313E9F477C}.Debug|Any CPU.Build.0 = Debug|Any CPU
-               {C8B8E524-BB3A-44E2-8C22-E3313E9F477C}.Release|Any CPU.ActiveCfg = Release|Any CPU
-               {C8B8E524-BB3A-44E2-8C22-E3313E9F477C}.Release|Any CPU.Build.0 = Release|Any CPU
                {5E39A911-F4E6-4B4B-B8AC-111BB1DD80C6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
                {5E39A911-F4E6-4B4B-B8AC-111BB1DD80C6}.Debug|Any CPU.Build.0 = Debug|Any CPU
                {5E39A911-F4E6-4B4B-B8AC-111BB1DD80C6}.Release|Any CPU.ActiveCfg = Release|Any CPU
@@ -1253,14 +1237,6 @@ Global
                {2210873E-99FC-48A2-A261-D650BAE33A1C}.Debug|Any CPU.Build.0 = Debug|Any CPU
                {2210873E-99FC-48A2-A261-D650BAE33A1C}.Release|Any CPU.ActiveCfg = Release|Any CPU
                {2210873E-99FC-48A2-A261-D650BAE33A1C}.Release|Any CPU.Build.0 = Release|Any CPU
-               {391EDD2B-85AC-4FCA-B607-AAD6C51E6799}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
-               {391EDD2B-85AC-4FCA-B607-AAD6C51E6799}.Debug|Any CPU.Build.0 = Debug|Any CPU
-               {391EDD2B-85AC-4FCA-B607-AAD6C51E6799}.Release|Any CPU.ActiveCfg = Release|Any CPU
-               {391EDD2B-85AC-4FCA-B607-AAD6C51E6799}.Release|Any CPU.Build.0 = Release|Any CPU
-               {E485E885-59B1-4081-BC66-56AAAFD8771A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
-               {E485E885-59B1-4081-BC66-56AAAFD8771A}.Debug|Any CPU.Build.0 = Debug|Any CPU
-               {E485E885-59B1-4081-BC66-56AAAFD8771A}.Release|Any CPU.ActiveCfg = Release|Any CPU
-               {E485E885-59B1-4081-BC66-56AAAFD8771A}.Release|Any CPU.Build.0 = Release|Any CPU
                {EF08F249-31A1-4E62-8391-ECBA5227B686}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
                {EF08F249-31A1-4E62-8391-ECBA5227B686}.Debug|Any CPU.Build.0 = Debug|Any CPU
                {EF08F249-31A1-4E62-8391-ECBA5227B686}.Release|Any CPU.ActiveCfg = Release|Any CPU
index a036cf1f8dbc283329b0c3c07ec21baf97d9f750..a22d2a91ff418265354bc59c8043ba1a16403891 100644 (file)
@@ -2,6 +2,7 @@
 /al
 /al1
 /al2
+/btls-cert-sync
 /caspol
 /cert-sync
 /cert2spc
index fa2d8378bbf8dc85dcc279bf8c1a0cadf5e9790b..39595455dadf28dc64a1a5e957b13143d0b365b0 100644 (file)
@@ -34,8 +34,9 @@ bin_SCRIPTS = \
        $(MDOC_SUBCOMMANDS)     \
        $(MDOC_COMPAT)          \
        mono-test-install       \
-       peverify                        \
-       mcs                                     \
+       peverify                \
+       mcs                     \
+       mono-package-runtime    \
        mono-heapviz            \
        $(scripts_mono_configuration_crypto)
 
@@ -72,6 +73,7 @@ scripts_4_0 = \
        prj2make$(SCRIPT_SUFFIX)                \
        soapsuds$(SCRIPT_SUFFIX)                \
        caspol$(SCRIPT_SUFFIX)                  \
+       btls-cert-sync$(SCRIPT_SUFFIX)          \
        cert-sync$(SCRIPT_SUFFIX)               \
        cert2spc$(SCRIPT_SUFFIX)                \
        certmgr$(SCRIPT_SUFFIX)                 \
@@ -156,6 +158,7 @@ EXTRA_DIST =                        \
        update_submodules               \
        mcs.in                          \
        dmcs.in                         \
+       mono-package-runtime    \
        mono-test-install       \
        mono-heapviz            \
        $(MDOC_COMPAT)          \
index 74f0d1bbf386169c651b16b7ff4828e506e0bf64..ab17183b1b0bf0a8d5cfc1565fbd926becb336bb 100755 (executable)
@@ -10,7 +10,10 @@ else
     export CFLAGS="-ggdb3 -O2"
 fi
 
-if [[ ${CI_TAGS} == *'coop-gc'* ]]; then EXTRA_CONF_FLAGS="${EXTRA_CONF_FLAGS} --with-cooperative-gc=yes"; export MONO_CHECK_MODE=gc,thread; fi
+if [[ ${CI_TAGS} == *'coop-gc'* ]]; then EXTRA_CONF_FLAGS="${EXTRA_CONF_FLAGS} --with-cooperative-gc=yes"; fi
+
+if [[ ${CI_TAGS} == *'checked-coop'* ]]; then EXTRA_CONF_FLAGS="${EXTRA_CONF_FLAGS} --enable-checked-build=gc,thread"; export MONO_CHECK_MODE=gc,thread; fi
+if [[ ${CI_TAGS} == *'checked-all'* ]]; then EXTRA_CONF_FLAGS="${EXTRA_CONF_FLAGS} --enable-checked-build=all"; export MONO_CHECK_MODE=all; fi
 
 if [[ ${label} == 'osx-i386' ]]; then EXTRA_CONF_FLAGS="${EXTRA_CONF_FLAGS} --with-libgdiplus=/Library/Frameworks/Mono.framework/Versions/Current/lib/libgdiplus.dylib --build=i386-apple-darwin11.2.0"; fi
 if [[ ${label} == 'osx-amd64' ]]; then EXTRA_CONF_FLAGS="${EXTRA_CONF_FLAGS} --with-libgdiplus=/Library/Frameworks/Mono.framework/Versions/Current/lib/libgdiplus.dylib "; fi
@@ -52,11 +55,6 @@ fi
 if [[ ${CI_TAGS} == *'monolite'* ]]; then make get-monolite-latest; fi
 
 ${TESTCMD} --label=make --timeout=300m --fatal make -j4 -w V=1
-if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]];
-    then
-    exit 0
-    # we don't run the test suite on Windows PRs, we just ensure the build succeeds, so end here
-fi
 
 if [[ ${CI_TAGS} == *'acceptance-tests'* ]];
     then
index bffda6b73f7191f1673b4e3123ca9c18b95589ea..4784623bd063e18cc08c7080500ffb8b9b3c76fd 100755 (executable)
@@ -9,26 +9,30 @@ ${TESTCMD} --label=verify --timeout=15m make -w -C runtime mcs-compileall
 ${TESTCMD} --label=profiler --timeout=30m make -w -C mono/profiler -k check
 ${TESTCMD} --label=compiler --timeout=30m make -w -C mcs/tests run-test
 ${TESTCMD} --label=compiler-errors --timeout=30m make -w -C mcs/errors run-test
-${TESTCMD} --label=System --timeout=10m make -w -C mcs/class/System run-test
+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
-${TESTCMD} --label=System.Security --timeout=5m make -w -C mcs/class/System.Security run-test;
-${TESTCMD} --label=System.Drawing --timeout=5m make -w -C mcs/class/System.Drawing run-test
-if [[ ${label} == osx-* ]]
+${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
+fi
+if [[ ${label} == osx-* ]] || [[ ${label} == w* ]]
 then ${TESTCMD} --label=Windows.Forms --skip;
 else ${TESTCMD} --label=Windows.Forms --timeout=5m make -w -C mcs/class/System.Windows.Forms run-test
 fi
 ${TESTCMD} --label=System.Data --timeout=5m make -w -C mcs/class/System.Data 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;
-${TESTCMD} --label=Mono.Posix --timeout=5m make -w -C mcs/class/Mono.Posix 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
 ${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;
-${TESTCMD} --label=System.Runtime.Remoting --timeout=5m make -w -C mcs/class/System.Runtime.Remoting 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=Cscompmgd --timeout=5m make -w -C mcs/class/Cscompmgd run-test;
 ${TESTCMD} --label=Commons.Xml.Relaxng --timeout=5m make -w -C mcs/class/Commons.Xml.Relaxng run-test;
-${TESTCMD} --label=System.ServiceProcess --timeout=5m make -w -C mcs/class/System.ServiceProcess run-test;
+if [[ -n "${ghprbPullId}" ]] && [[ ${label} == w* ]]; then ${TESTCMD} --label=System.ServiceProcess --skip; else ${TESTCMD} --label=System.ServiceProcess --timeout=5m make -w -C mcs/class/System.ServiceProcess run-test; fi
 ${TESTCMD} --label=I18N.CJK --timeout=5m make -w -C mcs/class/I18N/CJK run-test
 ${TESTCMD} --label=I18N.West --timeout=5m make -w -C mcs/class/I18N/West run-test
 ${TESTCMD} --label=I18N.MidEast --timeout=5m make -w -C mcs/class/I18N/MidEast run-test
@@ -42,8 +46,8 @@ ${TESTCMD} --label=Mono.Tasklets --timeout=5m make -w -C mcs/class/Mono.Tasklets
 ${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
 ${TESTCMD} --label=System.Web.Extensions --timeout=5m make -w -C mcs/class/System.Web.Extensions run-test
-${TESTCMD} --label=System.Core --timeout=15m make -w -C mcs/class/System.Core run-test
-${TESTCMD} --label=symbolicate --timeout=60m make -w -C mcs/tools/mono-symbolicate check
+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=System.Data.DSE --timeout=5m make -w -C mcs/class/System.Data.DataSetExtensions run-test
 ${TESTCMD} --label=System.Web.Abstractions --timeout=5m make -w -C mcs/class/System.Web.Abstractions run-test
index 52d6f1668003d6eb79373b94101697d66f0f8bfa..05f5015611ec91e07ef669e6eb671ff84a830339 100755 (executable)
@@ -2,4 +2,4 @@
 
 export TESTCMD=`dirname "${BASH_SOURCE[0]}"`/run-step.sh
 
-${TESTCMD} --label=check-profiler-stress --timeout=20h make -C acceptance-tests check-profiler-stress
+${TESTCMD} --label=check-profiler-stress --timeout=24h make -C acceptance-tests check-profiler-stress
diff --git a/scripts/mono-package-runtime b/scripts/mono-package-runtime
new file mode 100644 (file)
index 0000000..d71942b
--- /dev/null
@@ -0,0 +1,36 @@
+#!/bin/sh
+
+if test x$2 = x; then
+   echo usage is: mono-package-runtime MONO_INSTALL_PREFIX LABEL
+   echo The file will be created in the current directory
+   exit 1
+fi
+
+prefix=$1
+output=$2
+if test ! -d $prefix; then
+   echo the specified path is not a directory: $prefix
+   exit 1
+fi
+
+if test -e $output.zip; then
+   echo The output file already exists, refusing to overwrite: $output.zip
+   exit 1
+fi
+
+if test ! -e $prefix/bin/mono; then
+   echo The $prefix does not contains a bin/mono
+   exit 1
+fi
+
+if test ! -d $prefix/lib/mono/4.5; then
+   echo The $prefix does not contains a lib/mono/4.5
+   exit 1
+fi
+
+o=`pwd`/$output
+
+cd $prefix
+(zip -u $o.zip bin/mono lib/mono/4.5/mscorlib.dll lib/mono/4.5/System*dll lib/mono/4.5/Mono.CSharp.dll lib/mono/4.5/Microsoft*dll lib/mono/4.5/FSharp*.dll lib/mono/4.5/I18N*dll lib/mono/4.5/Accessibility.dll lib/mono/4.5/RabbitMQ.Client.dll lib/mono/4.5/ICSharpCode.SharpZipLib.dll lib/mono/4.5/CustomMarshalers.dll etc/mono/config etc/mono/4.5/machine.config etc/mono/4.5/web.config lib/mono/4.5/Mono.Cairo.dll lib/mono/4.5/Mono.Data.Sqlite.dll lib/mono/4.5/Mono.Posix.dll lib/mono/4.5/Mono.Security.*dll lib/mono/4.5/Mono.Simd.dll)
+echo Created file $o.zip
+
index a6daf8b05286c8b10b8dabe416649fee9906b609..d15685302eb4ca05c6a649ecba90f9911b7e6131 100644 (file)
 
 /* Version number of package */
 #define VERSION "#MONO_VERSION#"
+
+#ifndef HAVE_WINAPI_FAMILY_SUPPORT
+
+#define HAVE_WINAPI_FAMILY_SUPPORT
+
+/* WIN API Family support */
+#include <winapifamily.h>
+
+#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
+       #define HAVE_CLASSIC_WINAPI_SUPPORT 1
+       #define HAVE_UWP_WINAPI_SUPPORT 0
+#elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)
+       #define HAVE_CLASSIC_WINAPI_SUPPORT 0
+       #define HAVE_UWP_WINAPI_SUPPORT 1
+#else
+       #define HAVE_CLASSIC_WINAPI_SUPPORT 0
+       #define HAVE_UWP_WINAPI_SUPPORT 0
+#endif
+
+#endif
 #endif